-------------------------------------------------------------------------------- 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 pest 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=f75ec3cf676c808a -C extra-filename=-f75ec3cf676c808a --out-dir /usr/home/liquid/tmp/.tmpL387jg/target/debug/deps -L dependency=/usr/home/liquid/tmp/.tmpL387jg/target/debug/deps --extern ucd_trie=/usr/home/liquid/tmp/.tmpL387jg/target/debug/deps/libucd_trie-d46691434d354cd9.rmeta -Adeprecated -Aunknown-lints -Zincremental-verify-ich Data file: results/cgout-w-profiling-pest-2.1.3-Check-Full Events recorded: Ir Events shown: Ir Event sort order: Ir Thresholds: 0.1 Include dirs: User annotated: Auto-annotation: on -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 4,874,310,953 (100.0%) PROGRAM TOTALS -------------------------------------------------------------------------------- Ir file:function -------------------------------------------------------------------------------- 110,388,633 ( 2.26%) ./malloc/malloc.c:_int_malloc 102,177,533 ( 2.10%) ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S:__memcpy_avx_unaligned_erms 92,853,109 ( 1.90%) ./malloc/malloc.c:_int_free 60,775,452 ( 1.25%) ./malloc/malloc.c:malloc 47,052,132 ( 0.97%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs:rustc_const_eval::transform::check_consts::qualifs::in_operand::::qualif_local::{closure#0}> 41,019,017 ( 0.84%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::from_key_hashed_nocheck:: 37,275,487 ( 0.76%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::get:: 30,678,921 ( 0.63%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/mod.rs:::next_token 29,041,638 ( 0.60%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/util.rs:::is_trivially_unpin 27,734,665 ( 0.57%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::short_write_process_buffer:: 27,646,440 ( 0.57%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/util.rs:::is_freeze 25,611,566 ( 0.53%) ./malloc/malloc.c:free 24,068,938 ( 0.49%) ./malloc/malloc.c:malloc_consolidate 23,613,382 ( 0.48%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lexer/src/lib.rs:::advance_token 22,153,259 ( 0.45%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:::temporary_scope 22,127,385 ( 0.45%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::parse_token_tree 21,981,302 ( 0.45%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs:::span_data_to_lines_and_cols 21,722,944 ( 0.45%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::attrs 19,181,380 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/hir/map/mod.rs:::find_parent_node 18,933,426 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp/ring.rs:>::pop_first 18,851,467 ( 0.39%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs:::advance_left 18,604,620 ( 0.38%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::short_write_process_buffer:: 18,481,409 ( 0.38%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::check 18,262,775 ( 0.37%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/mod.rs:::check_static_ptr 17,628,665 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:>::hash_stable 17,533,194 ( 0.36%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/vec_deque/mod.rs:>::push_back 17,203,972 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/middle/region.rs:>>::get:: 16,928,378 ( 0.35%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::maybe_lint_level_root_bounded 16,793,787 ( 0.34%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump 16,084,279 ( 0.33%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs:::mirror_expr_inner 15,495,961 ( 0.32%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::next 15,111,451 ( 0.31%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::from_key_hashed_nocheck:: 14,660,632 ( 0.30%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::node_type_opt 14,369,940 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::enter::, rustc_trait_selection::traits::structural_match::search_for_structural_match_violation::{closure#0}> 14,025,119 ( 0.29%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 13,644,528 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::new 13,534,311 ( 0.28%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::advance_left 13,390,783 ( 0.27%) ./malloc/malloc.c:unlink_chunk.constprop.0 12,435,525 ( 0.26%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/structural_match.rs:::enter::, rustc_trait_selection::traits::structural_match::search_for_structural_match_violation::{closure#0}> 12,276,972 ( 0.25%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>>::insert 12,237,366 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:>::hash_stable 12,219,156 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::attrs 12,179,817 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs:::next_with_spacing 12,166,228 ( 0.25%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 12,142,478 ( 0.25%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_assoc_expr_with 12,030,731 ( 0.25%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, (), core::hash::BuildHasherDefault>>::from_hash::>::{closure#0}> 11,879,395 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/thir/cx/expr.rs:::make_mirror_unadjusted 11,786,910 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/mod.rs:::ty 11,783,659 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/regionck.rs:::visit_expr 11,455,291 ( 0.24%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/expr/as_operand.rs:::as_operand 11,085,841 ( 0.23%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/levels.rs:::push 10,958,498 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/lexer/tokentrees.rs:::push 10,804,999 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/../../stdarch/crates/core_arch/src/x86/sse2.rs:>>::from_key_hashed_nocheck:: 10,745,114 ( 0.22%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/writeback.rs:::visit_node_id 10,305,124 ( 0.21%) ./elf/dl-lookup.c:_dl_lookup_symbol_x 10,032,603 ( 0.21%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/collections/hash/map.rs:>>::get:: 9,751,424 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:rustc_const_eval::transform::check_consts::qualifs::in_rvalue::::qualif_local::{closure#0}> 9,742,791 ( 0.20%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/expr.rs:::check_expr_with_expectation_and_args 9,646,341 ( 0.20%) /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} 9,465,465 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::eq 9,178,415 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/types.rs:::check_expr 9,127,169 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::const_val_to_op 9,044,215 ( 0.19%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::eval_operand 8,942,538 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/type_check/mod.rs:::visit_constant 8,866,447 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs:rustc_const_eval::transform::check_consts::qualifs::in_operand:: as rustc_middle::mir::visit::Visitor>::visit_assign::{closure#0}> 8,704,141 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs:::scan_string 8,687,466 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs:::slice_write_process_buffer 8,636,118 ( 0.18%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs:>>::from_key_hashed_nocheck:: 8,604,973 ( 0.18%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs:>>::get:: 8,533,449 ( 0.18%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_hir_pretty/src/lib.rs:::print_expr 8,402,303 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_passes/src/region.rs:::visit_expr 8,368,229 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pp.rs:::check_stack 8,332,754 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:>::truncate 8,315,510 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs:rustc_const_eval::transform::check_consts::qualifs::in_operand::::qualif_local::{closure#0}> 8,304,214 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/mem_categorization.rs:::cat_expr_unadjusted 8,292,558 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/coercion.rs:>::coerce 8,291,964 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/mod.rs:::const_for_ty 8,233,522 ( 0.17%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/uint_macros.rs:::slice_write_process_buffer 7,975,500 ( 0.16%) /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 7,957,366 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/flags.rs:::add_const 7,922,004 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/vec_deque/mod.rs:::advance_left 7,829,460 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_hir/src/intravisit.rs:rustc_hir::intravisit::walk_expr:: 7,771,149 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::place_field 7,768,675 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::bump_with 7,753,401 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/structural_match.rs:::visit_ty 7,744,561 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::force_allocation_maybe_sized 7,707,480 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::ident 7,679,687 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_privacy/src/lib.rs:::check_expr_pat_type 7,675,047 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place::> 7,625,121 ( 0.16%) /usr/home/liquid/rust/worktree-benchmarking/library/std/src/sys/unix/alloc.rs:__rdl_alloc 7,511,075 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::copy_op_no_validate 7,492,433 ( 0.15%) /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::> 7,441,232 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:)>>::remove_entry::>::{closure#0}> 7,423,526 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_metadata/src/rmeta/encoder.rs:>::encode 7,396,982 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/vec_deque/mod.rs:::check_stack 7,394,969 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::insert::>::{closure#0}> 7,335,847 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs:rustc_const_eval::transform::check_consts::qualifs::in_rvalue::::qualif_local::{closure#0}> 7,311,608 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/expand.rs:::filter_map_expr 7,178,934 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_passes/src/check_attr.rs:::check_attributes 7,166,145 ( 0.15%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::get:: 7,105,490 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/early.rs: as rustc_ast::visit::Visitor>::visit_expr 7,090,347 ( 0.15%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/place.rs:>::write_immediate_to_mplace_no_validate 7,014,052 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs:::clone 7,011,888 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::node_type 6,990,672 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/symbol.rs:::as_str 6,935,698 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/walk.rs:::next 6,907,148 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/cell.rs:::find_parent_node 6,892,073 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::insert::>::{closure#0}> 6,844,320 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/early.rs: as rustc_ast::visit::Visitor>::visit_expr 6,825,663 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/util/literal.rs:rustc_ast::util::literal::integer_lit 6,804,013 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/option.rs:::attrs 6,786,991 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::try_read_immediate 6,731,341 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/scope.rs:::as_operand 6,669,216 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/rustc_entry.rs:, rustc_middle::mir::interpret::allocation::Allocation), core::hash::BuildHasherDefault>>::rustc_entry 6,631,783 ( 0.14%) ./malloc/malloc.c:realloc 6,618,660 ( 0.14%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:::push 6,615,697 ( 0.14%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/ptr/mod.rs:core::ptr::drop_in_place:: 6,562,251 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_dot_or_call_expr_with_ 6,542,008 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/mod.rs:::next_token 6,454,230 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/hygiene.rs:>::hash_stable 6,422,671 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/expr/as_constant.rs:::as_constant 6,359,805 ( 0.13%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 6,354,909 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:::to 6,311,142 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/vec_deque/mod.rs:>::pop_first 6,291,731 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/mod.rs:::shallow_resolve_ty 6,275,666 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/writeback.rs:::visit_expr 6,246,810 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pprust/state.rs:::maybe_print_comment 6,233,235 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/util.rs:rustc_middle::ty::util::needs_drop_components 6,221,021 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/expr.rs:::check_expr_kind 6,138,323 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/mod.rs:::attrs 6,120,797 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/late.rs:::resolve_expr 6,106,966 ( 0.13%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_prefix_expr 6,079,590 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/structural_match.rs:rustc_trait_selection::traits::structural_match::search_for_structural_match_violation 6,076,792 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:::check 6,028,700 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/type_check/canonical.rs:::fully_perform_op::<&rustc_middle::ty::TyS, rustc_middle::ty::ParamEnvAnd>> 6,024,378 ( 0.12%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:>::reserve_rehash::>::{closure#0}> 5,993,641 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/late.rs:rustc_hir::intravisit::walk_expr::> 5,969,308 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_privacy/src/lib.rs: as rustc_middle::ty::fold::TypeVisitor>::visit_ty 5,952,344 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_opt_lit 5,922,798 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/ptr.rs:>::map::<::parse_dot_or_call_expr_with::{closure#0}::{closure#0}> 5,901,954 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::next_token 5,831,742 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/memory.rs:>::get_mut 5,822,707 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_lowering/src/expr.rs:rustc_data_structures::stack::ensure_sufficient_stack::::lower_expr_mut::{closure#0}> 5,807,340 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/expr.rs:::parse_lit_expr 5,774,038 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_index/src/vec.rs:::mirror_expr_inner 5,762,533 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/slice/iter/macros.rs:::advance_token 5,748,606 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/builtin.rs:::check_heap_type 5,726,245 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_serialize/src/leb128.rs:>::encode 5,681,386 ( 0.12%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/util/literal.rs:::from_lit_token 5,588,778 ( 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}> 5,587,410 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::eq 5,557,471 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map.rs: as core::ops::drop::Drop>::drop 5,535,500 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/types.rs:::inherent_atomic_method_call 5,469,254 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/promote_consts.rs:::validate_local 5,451,034 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/mod.rs:core::num::from_str_radix 5,429,354 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_query_system/src/query/caches.rs:::attrs 5,400,959 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/region_constraints/mod.rs:::new 5,381,260 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs:>>::insert 5,351,855 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/context.rs:::intern_ty 5,300,620 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::get_bytes_mut:: 5,281,021 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/attr.rs:::parse_outer_attributes 5,279,796 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, rustc_middle::mir::interpret::allocation::Allocation), core::hash::BuildHasherDefault>>::rustc_entry 5,249,447 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_privacy/src/lib.rs:::visit_expr 5,248,788 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs:::in_any_value_of_ty 5,235,372 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs:::warn_if_unreachable 5,194,205 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/mod.rs:::expect 5,164,696 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:, rustc_query_system::cache::WithDepNode, rustc_middle::traits::SelectionError>>)> as core::ops::drop::Drop>::drop 5,163,872 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/mir/interpret/allocation.rs:::write_scalar:: 5,126,865 ( 0.11%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs: as core::ops::drop::Drop>::drop 5,123,382 ( 0.11%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/raw_vec.rs:core::ptr::drop_in_place::> 5,116,698 ( 0.10%) /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs:)> as core::ops::drop::Drop>::drop 5,104,499 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/types.rs:::check_expr 5,095,230 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/passes.rs:::check_expr 5,087,189 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/core/src/fmt/mod.rs:core::fmt::write 5,074,234 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/scope.rs:::pop_scope 5,034,820 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/type_check/mod.rs:::check_rvalue 4,980,012 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/consts/kind.rs:::check_static_ptr 4,978,908 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/interpret/operand.rs:>::const_to_op 4,971,952 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs:>::truncate 4,905,269 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/span_encoding.rs:>::hash_stable 4,893,242 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs:::to 4,890,848 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs:::hash:: 4,889,863 ( 0.10%) /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/vec/mod.rs: as core::ops::drop::Drop>::drop -------------------------------------------------------------------------------- -- 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);)*) => { 24,838 ( 0.00%) $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> { . self.opaque.$name(value) 29,842 ( 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 { 3,281 ( 0.00%) e.emit_lazy_distance(*self) . } . } . . impl<'a, 'tcx, T: Encodable>> Encodable> . for Lazy<[T]> . { 95 ( 0.00%) fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . e.emit_usize(self.meta)?; 682 ( 0.00%) if self.meta == 0 { . return Ok(()); . } 1,959 ( 0.00%) e.emit_lazy_distance(*self) 30 ( 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 { 8,631 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 12,963 ( 0.00%) if *self != LOCAL_CRATE && s.is_proc_macro { . panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self); . } . s.emit_u32(self.as_u32()) 7,398 ( 0.00%) } . } . . impl<'a, 'tcx> Encodable> for DefIndex { 6,105 ( 0.00%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { . s.emit_u32(self.as_u32()) 7,326 ( 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 { 774,000 ( 0.02%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 464,400 ( 0.01%) rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s) 928,800 ( 0.02%) } . } . . impl<'a, 'tcx> Encodable> for ExpnId { . fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 1,050 ( 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. 3,540 ( 0.00%) s.hygiene_ctxt.schedule_expn_data_for_encoding(*self); . } 2,408 ( 0.00%) self.krate.encode(s)?; . self.local_id.encode(s) . } . } . . impl<'a, 'tcx> Encodable> for Span { 1,236,936 ( 0.03%) fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { 927,702 ( 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. 309,234 ( 0.01%) if s.is_proc_macro { . SyntaxContext::root().encode(s)?; . } else { 154,617 ( 0.00%) span.ctxt.encode(s)?; . } . 154,617 ( 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); . 772,176 ( 0.02%) if !s.source_file_cache.0.contains(span.lo) { 514 ( 0.00%) let source_map = s.tcx.sess.source_map(); 1,028 ( 0.00%) let source_file_index = source_map.lookup_source_file_idx(span.lo); 514 ( 0.00%) s.source_file_cache = 1,028 ( 0.00%) (source_map.files()[source_file_index].clone(), source_file_index); . } . 464,474 ( 0.01%) if !s.source_file_cache.0.contains(span.hi) { . // Unfortunately, macro expansion still sometimes generates Spans . // that malformed in this way. . return TAG_PARTIAL_SPAN.encode(s); . } . . let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!"); . // Record the fact that we need to encode the data for this `SourceFile` 154,482 ( 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. 926,892 ( 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 246 ( 0.00%) match &*s.source_file_cache.0.external_src.lock() { 82 ( 0.00%) ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos, . src => panic!("Unexpected external source {:?}", src), . } . }; 246 ( 0.00%) let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos; 82 ( 0.00%) let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos; . . (TAG_VALID_SPAN_FOREIGN, lo, hi) . } else { 463,200 ( 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)?; . 308,964 ( 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)` 328 ( 0.00%) let cnum = s.source_file_cache.0.cnum; 246 ( 0.00%) cnum.encode(s)?; . } . . Ok(()) 1,236,936 ( 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 { 7,459 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 3,867 ( 0.00%) self.encode(ecx).unwrap() . } . } . . impl<'a, 'tcx, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, T> for T { 17,329 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { 10,068 ( 0.00%) self.encode(ecx).unwrap() 9,966 ( 0.00%) } . } . . impl<'a, 'tcx, I, T: Encodable>> EncodeContentsForLazy<'a, 'tcx, [T]> for I . where . I: IntoIterator, . I::Item: EncodeContentsForLazy<'a, 'tcx, T>, . { 1,099 ( 0.00%) fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize { 7,367 ( 0.00%) self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count() 1,413 ( 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> { 4,615 ( 0.00%) fn emit_lazy_distance( . &mut self, . lazy: Lazy, . ) -> Result<(), ::Error> { . let pos = lazy.position.get(); 2,877 ( 0.00%) let distance = match self.lazy_state { . LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"), 869 ( 0.00%) LazyState::NodeStart(start) => { . let start = start.get(); 1,738 ( 0.00%) assert!(pos <= start); . start - pos . } 54 ( 0.00%) LazyState::Previous(last_pos) => { 54 ( 0.00%) assert!( . last_pos <= lazy.position, . "make sure that the calls to `lazy*` \ . are in the same order as the metadata fields", . ); 162 ( 0.00%) lazy.position.get() - last_pos.get() . } . }; 1,846 ( 0.00%) self.lazy_state = LazyState::Previous(NonZeroUsize::new(pos).unwrap()); . self.emit_usize(distance) 4,615 ( 0.00%) } . 9,897 ( 0.00%) fn lazy( . &mut self, . value: impl EncodeContentsForLazy<'a, 'tcx, T>, . ) -> Lazy { . let pos = NonZeroUsize::new(self.position()).unwrap(); . 11,904 ( 0.00%) assert_eq!(self.lazy_state, LazyState::NoNode); 35,284 ( 0.00%) self.lazy_state = LazyState::NodeStart(pos); 24,573 ( 0.00%) let meta = value.encode_contents_for_lazy(self); 14,415 ( 0.00%) self.lazy_state = LazyState::NoNode; . 24,983 ( 0.00%) assert!(pos.get() <= self.position()); . . Lazy::from_position_and_meta(pos, meta) 14,458 ( 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); 4,760 ( 0.00%) self.tables.def_keys.set(def_index, def_key); 4,760 ( 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` 1,115 ( 0.00%) required_source_files.contains(*idx) && . // Don't serialize imported `SourceFile`s, unless . // we're in a proc-macro crate. 119 ( 0.00%) (!source_file.is_imported() || self.is_proc_macro) . }) . .map(|(_, source_file)| { 57 ( 0.00%) let mut adapted = match source_file.name { . FileName::Real(ref realname) => { 38 ( 0.00%) let mut adapted = (**source_file).clone(); 304 ( 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. 38 ( 0.00%) let working_dir = &self.tcx.sess.opts.working_dir; 38 ( 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); 133 ( 0.00%) let (joined, remapped) = 209 ( 0.00%) source_map.path_mapping().map_prefix(joined); 38 ( 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(), . } . } . }); 38 ( 0.00%) adapted.name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 19 ( 0.00%) adapted.name.hash(&mut hasher); . hasher.finish::() . }; 19 ( 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. 38 ( 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. 3,663 ( 0.00%) fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) { 2,035 ( 0.00%) match tcx.def_kind(def_id) { . // Constructors . DefKind::Ctor(_, _) => { 36 ( 0.00%) let mir_opt_base = tcx.sess.opts.output_types.should_codegen() . || tcx.sess.opts.debugging_opts.always_encode_mir; . (true, mir_opt_base) . } . // Constants . DefKind::AnonConst . | DefKind::InlineConst . | DefKind::AssocConst . | DefKind::Static . | DefKind::Const => (true, false), . // Full-fledged functions . DefKind::AssocFn | DefKind::Fn => { . let generics = tcx.generics_of(def_id); 1,474 ( 0.00%) let needs_inline = (generics.requires_monomorphization(tcx) 310 ( 0.00%) || tcx.codegen_fn_attrs(def_id).requests_inline()) 534 ( 0.00%) && tcx.sess.opts.output_types.should_codegen(); . // The function has a `const` modifier or is annotated with `default_method_body_is_const`. 291 ( 0.00%) let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id()) 1,455 ( 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; 582 ( 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); 68 ( 0.00%) let needs_inline = (generics.requires_monomorphization(tcx) . || tcx.codegen_fn_attrs(def_id).requests_inline()) 34 ( 0.00%) && tcx.sess.opts.output_types.should_codegen(); 34 ( 0.00%) let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; 34 ( 0.00%) (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), . } 3,663 ( 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); 7,140 ( 0.00%) let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue }; 15,808 ( 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, . }); 2,964 ( 0.00%) record!(self.tables.span[def_id] <- tcx.def_span(def_id)); 11,856 ( 0.00%) record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id)); 7,904 ( 0.00%) record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id)); . if should_encode_visibility(def_kind) { 4,734 ( 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); 4,656 ( 0.00%) self.encode_deprecation(def_id); . } . if should_encode_variances(def_kind) { 704 ( 0.00%) let v = self.tcx.variances_of(def_id); 2,464 ( 0.00%) record!(self.tables.variances[def_id] <- v); . } . if should_encode_generics(def_kind) { . let g = tcx.generics_of(def_id); 3,080 ( 0.00%) record!(self.tables.generics[def_id] <- g); 9,240 ( 0.00%) record!(self.tables.explicit_predicates[def_id] <- self.tcx.explicit_predicates_of(def_id)); 770 ( 0.00%) let inferred_outlives = self.tcx.inferred_outlives_of(def_id); 908 ( 0.00%) if !inferred_outlives.is_empty() { 9 ( 0.00%) record!(self.tables.inferred_outlives[def_id] <- inferred_outlives); . } . } 6,916 ( 0.00%) if let DefKind::Trait | DefKind::TraitAlias = def_kind { 28 ( 0.00%) 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() { 11 ( 0.00%) if implementations.is_empty() { . continue; . } 99 ( 0.00%) record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| { 12 ( 0.00%) assert!(def_id.is_local()); . def_id.index . })); . } . } . 4,564 ( 0.00%) fn encode_item_type(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_item_type({:?})", def_id); 3,912 ( 0.00%) record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id)); 5,216 ( 0.00%) } . . fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) { . let tcx = self.tcx; . let variant = &def.variants[index]; 88 ( 0.00%) let def_id = variant.def_id; . debug!("EncodeContext::encode_enum_variant_info({:?})", def_id); . 132 ( 0.00%) let data = VariantData { 22 ( 0.00%) ctor_kind: variant.ctor_kind, . discr: variant.discr, 22 ( 0.00%) ctor: variant.ctor_def_id.map(|did| did.index), 22 ( 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| { 19 ( 0.00%) assert!(f.did.is_local()); . f.did.index . })); 22 ( 0.00%) self.encode_ident_span(def_id, variant.ident(tcx)); 22 ( 0.00%) self.encode_item_type(def_id); 22 ( 0.00%) if variant.ctor_kind == CtorKind::Fn { . // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`. 24 ( 0.00%) 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]; 80 ( 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 { 16 ( 0.00%) ctor_kind: variant.ctor_kind, . discr: variant.discr, . ctor: Some(def_id.index), 16 ( 0.00%) is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }; . 64 ( 0.00%) record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); 48 ( 0.00%) self.encode_item_type(def_id); 16 ( 0.00%) if variant.ctor_kind == CtorKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . 190 ( 0.00%) fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) { 38 ( 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. 57 ( 0.00%) let reexports = if !self.is_proc_macro { 38 ( 0.00%) match tcx.module_reexports(local_def_id) { . Some(exports) => self.lazy(exports), . _ => Lazy::empty(), . } . } else { . Lazy::empty() . }; . 76 ( 0.00%) record!(self.tables.kind[def_id] <- EntryKind::Mod(reexports)); 38 ( 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. 38 ( 0.00%) let tcx = self.tcx; . let foreign_item_children = md . .item_ids . .iter() 2,455 ( 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(); . 133 ( 0.00%) record!(self.tables.children[def_id] <- direct_children.chain(foreign_item_children)); . } 152 ( 0.00%) } . . fn encode_field( . &mut self, . adt_def: &ty::AdtDef, . variant_index: VariantIdx, . field_index: usize, . ) { . let variant = &adt_def.variants[variant_index]; . let field = &variant.fields[field_index]; . . let def_id = field.did; . debug!("EncodeContext::encode_field({:?})", def_id); . . record!(self.tables.kind[def_id] <- EntryKind::Field); 124 ( 0.00%) self.encode_ident_span(def_id, field.ident(self.tcx)); 186 ( 0.00%) self.encode_item_type(def_id); . } . . fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) { . debug!("EncodeContext::encode_struct_ctor({:?})", def_id); . let tcx = self.tcx; . let variant = adt_def.non_enum_variant(); . . let data = VariantData { -- line 1150 ---------------------------------------- -- line 1166 ---------------------------------------- . let bounds = self.tcx.explicit_item_bounds(def_id); . if !bounds.is_empty() { . record!(self.tables.explicit_item_bounds[def_id] <- bounds); . } . } . . fn encode_info_for_trait_item(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id); 1 ( 0.00%) let tcx = self.tcx; . 7 ( 0.00%) let ast_item = tcx.hir().expect_trait_item(def_id.expect_local()); . let trait_item = tcx.associated_item(def_id); . 5 ( 0.00%) let container = match trait_item.defaultness { . hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault, . hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired, . hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"), . }; . 6 ( 0.00%) match trait_item.kind { . ty::AssocKind::Const => { . let rendered = rustc_hir_pretty::to_string( . &(&self.tcx.hir() as &dyn intravisit::Map<'_>), . |s| s.print_trait_item(ast_item), . ); . let rendered_const = self.lazy(RenderedConst(rendered)); . . record!(self.tables.kind[def_id] <- EntryKind::AssocConst( . container, . Default::default(), . rendered_const, . )); . } . ty::AssocKind::Fn => { 2 ( 0.00%) let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind { 2 ( 0.00%) let param_names = match *m { . hir::TraitFn::Required(ref names) => self.encode_fn_param_names(names), . hir::TraitFn::Provided(body) => self.encode_fn_param_names_for_body(body), . }; . FnData { . asyncness: m_sig.header.asyncness, . constness: hir::Constness::NotConst, . param_names, . } -- line 1209 ---------------------------------------- -- line 1217 ---------------------------------------- . }))); . } . ty::AssocKind::Type => { . self.encode_explicit_item_bounds(def_id); . record!(self.tables.kind[def_id] <- EntryKind::AssocType(container)); . } . } . self.encode_ident_span(def_id, ast_item.ident); 3 ( 0.00%) match trait_item.kind { . ty::AssocKind::Const | ty::AssocKind::Fn => { . self.encode_item_type(def_id); . } . ty::AssocKind::Type => { . if trait_item.defaultness.has_value() { . self.encode_item_type(def_id); . } . } . } 1 ( 0.00%) 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); 394 ( 0.00%) let tcx = self.tcx; . 1,182 ( 0.00%) let ast_item = self.tcx.hir().expect_impl_item(def_id.expect_local()); 197 ( 0.00%) let impl_item = self.tcx.associated_item(def_id); . 788 ( 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)") . } . }; . 1,182 ( 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 => { 382 ( 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 191 ( 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)); . } . } 591 ( 0.00%) self.encode_ident_span(def_id, impl_item.ident(self.tcx)); 985 ( 0.00%) self.encode_item_type(def_id); 788 ( 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); . } 197 ( 0.00%) if impl_item.kind == ty::AssocKind::Fn { . record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } . } . 800 ( 0.00%) fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> { 1,837 ( 0.00%) self.lazy(self.tcx.hir().body_param_names(body_id)) 800 ( 0.00%) } . . 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| { 2,035 ( 0.00%) let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id); 1,518 ( 0.00%) if encode_const || encode_opt { 198 ( 0.00%) Some((def_id, encode_const, encode_opt)) . } else { . None . } 814 ( 0.00%) }) . .collect::>(); 500 ( 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); 99 ( 0.00%) if encode_opt { . record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id)); . } 99 ( 0.00%) if encode_const { 396 ( 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` 99 ( 0.00%) let abstract_const = self.tcx.thir_abstract_const(def_id); 396 ( 0.00%) if let Ok(Some(abstract_const)) = abstract_const { . record!(self.tables.thir_abstract_consts[def_id.to_def_id()] <- abstract_const); . } . } 396 ( 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())); 99 ( 0.00%) let unused = self.tcx.unused_generic_params(instance); 99 ( 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. 6,208 ( 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. 5,432 ( 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) . } . } . } . 4,656 ( 0.00%) fn encode_deprecation(&mut self, def_id: DefId) { . debug!("EncodeContext::encode_deprecation({:?})", def_id); 3,880 ( 0.00%) if let Some(depr) = self.tcx.lookup_deprecation(def_id) { 9 ( 0.00%) record!(self.tables.deprecation[def_id] <- depr); . } 3,875 ( 0.00%) } . 558 ( 0.00%) fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy { 279 ( 0.00%) let hir = self.tcx.hir(); 186 ( 0.00%) let body = hir.body(body_id); 744 ( 0.00%) let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| { 279 ( 0.00%) s.print_expr(&body.value) . }); 186 ( 0.00%) let rendered_const = &RenderedConst(rendered); . self.lazy(rendered_const) 651 ( 0.00%) } . 3,249 ( 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); . 2,166 ( 0.00%) let entry_kind = match item.kind { . hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic, . hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic, 279 ( 0.00%) hir::ItemKind::Const(_, body_id) => { 279 ( 0.00%) let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id); 651 ( 0.00%) EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id)) . } 200 ( 0.00%) hir::ItemKind::Fn(ref sig, .., body) => { . let data = FnData { 100 ( 0.00%) asyncness: sig.header.asyncness, 100 ( 0.00%) constness: sig.header.constness, 200 ( 0.00%) param_names: self.encode_fn_param_names_for_body(body), . }; . . EntryKind::Fn(self.lazy(data)) . } 4 ( 0.00%) hir::ItemKind::Macro(ref macro_def) => { . EntryKind::MacroDef(self.lazy(macro_def.clone())) . } . hir::ItemKind::Mod(ref m) => { 216 ( 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 . } 60 ( 0.00%) hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr), . hir::ItemKind::Struct(ref struct_def, _) => { 24 ( 0.00%) let adt_def = self.tcx.adt_def(def_id); 36 ( 0.00%) let variant = adt_def.non_enum_variant(); . . // Encode def_ids for each field and method . // for methods, write all the stuff get_trait_method . // needs to know 48 ( 0.00%) let ctor = struct_def . .ctor_hir_id() . .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index); . . EntryKind::Struct( . self.lazy(VariantData { 12 ( 0.00%) ctor_kind: variant.ctor_kind, 48 ( 0.00%) discr: variant.discr, . ctor, . is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }), 36 ( 0.00%) adt_def.repr, . ) . } . hir::ItemKind::Union(..) => { . let adt_def = self.tcx.adt_def(def_id); . let variant = adt_def.non_enum_variant(); . . EntryKind::Union( . self.lazy(VariantData { -- line 1461 ---------------------------------------- -- line 1462 ---------------------------------------- . ctor_kind: variant.ctor_kind, . discr: variant.discr, . ctor: None, . is_non_exhaustive: variant.is_field_list_non_exhaustive(), . }), . adt_def.repr, . ) . } 484 ( 0.00%) hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => { 460 ( 0.00%) let trait_ref = self.tcx.impl_trait_ref(def_id); 242 ( 0.00%) let polarity = self.tcx.impl_polarity(def_id); 242 ( 0.00%) let parent = if let Some(trait_ref) = trait_ref { 109 ( 0.00%) let trait_def = self.tcx.trait_def(trait_ref.def_id); 654 ( 0.00%) trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| { 654 ( 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| { 654 ( 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 1498 ---------------------------------------- . constness, . parent_impl: parent, . coerce_unsized_info, . }; . . EntryKind::Impl(self.lazy(data)) . } . hir::ItemKind::Trait(..) => { 4 ( 0.00%) let trait_def = self.tcx.trait_def(def_id); . let data = TraitData { 2 ( 0.00%) unsafety: trait_def.unsafety, 4 ( 0.00%) paren_sugar: trait_def.paren_sugar, 10 ( 0.00%) has_auto_impl: self.tcx.trait_is_auto(def_id), 2 ( 0.00%) is_marker: trait_def.is_marker, 2 ( 0.00%) skip_array_during_method_dispatch: trait_def.skip_array_during_method_dispatch, 2 ( 0.00%) specialization_kind: trait_def.specialization_kind, . must_implement_one_of: trait_def.must_implement_one_of.clone(), . }; . . EntryKind::Trait(self.lazy(data)) . } . 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. 1,715 ( 0.00%) match item.kind { . hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <- 20 ( 0.00%) self.tcx.adt_def(def_id).variants.iter().map(|v| { 22 ( 0.00%) assert!(v.def_id.is_local()); . v.def_id.index . }) . ), . hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { . record!(self.tables.children[def_id] <- 36 ( 0.00%) self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| { 43 ( 0.00%) assert!(f.did.is_local()); . f.did.index . }) . ) . } . hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => { 246 ( 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| { 198 ( 0.00%) assert!(def_id.is_local()); . def_id.index . }) . ); . } . _ => {} . } 831 ( 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(..) 1,348 ( 0.00%) | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id), . _ => {} . } 1,023 ( 0.00%) if let hir::ItemKind::Fn(..) = item.kind { 400 ( 0.00%) record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); . } 786 ( 0.00%) if let hir::ItemKind::Impl { .. } = item.kind { 605 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) { 545 ( 0.00%) record!(self.tables.impl_trait_ref[def_id] <- trait_ref); . } . } 2,744 ( 0.00%) } . . fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) { 348 ( 0.00%) record!(self.tables.kind[def_id] <- kind); 116 ( 0.00%) if encode_type { . self.encode_item_type(def_id); . } . } . . fn encode_info_for_closure(&mut self, hir_id: hir::HirId) { 102 ( 0.00%) let def_id = self.tcx.hir().local_def_id(hir_id); . debug!("EncodeContext::encode_info_for_closure({:?})", def_id); . . // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic, . // including on the signature, which is inferred in `typeck. 51 ( 0.00%) let ty = self.tcx.typeck(def_id).node_type(hir_id); . 51 ( 0.00%) match ty.kind() { . ty::Generator(..) => { . let data = self.tcx.generator_kind(def_id).unwrap(); . record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator(data)); . } . . ty::Closure(..) => { . record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure); . } . . _ => bug!("closure that is neither generator nor closure"), . } 68 ( 0.00%) self.encode_item_type(def_id.to_def_id()); 68 ( 0.00%) if let ty::Closure(def_id, substs) = *ty.kind() { 153 ( 0.00%) record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig()); . } . } . . fn encode_info_for_anon_const(&mut self, id: hir::HirId) { . let def_id = self.tcx.hir().local_def_id(id); . debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id); . let body_id = self.tcx.hir().body_owned_by(id); . 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() { 166 ( 0.00%) expn_data_table.set(index.as_raw(), this.lazy(expn_data)); 166 ( 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 { 20 ( 0.00%) name: self.tcx.crate_name(cnum), 20 ( 0.00%) hash: self.tcx.crate_hash(cnum), 20 ( 0.00%) host_hash: self.tcx.crate_host_hash(cnum), 20 ( 0.00%) kind: self.tcx.dep_kind(cnum), 20 ( 0.00%) extra_filename: self.tcx.extra_filename(cnum), . }; 100 ( 0.00%) (cnum, dep) . }) . .collect::>(); . . { . // Sanity-check the crate numbers . let mut expected_cnum = 1; 40 ( 0.00%) for &(n, _) in &deps { 50 ( 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 17 ( 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() 255 ( 0.00%) .map(|(trait_def_id, mut impls)| { . // Bring everything into deterministic order for hashing 11 ( 0.00%) impls.sort_by_cached_key(|&(index, _)| { 103 ( 0.00%) tcx.hir().def_path_hash(LocalDefId { local_def_index: index }) . }); . 68 ( 0.00%) TraitImpls { . trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index), 51 ( 0.00%) impls: self.lazy(&impls), . } 136 ( 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 { 401 ( 0.00%) self.tcx.hir() . } 1,310,202 ( 0.03%) fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) { 145,578 ( 0.00%) intravisit::walk_expr(self, ex); . self.encode_info_for_expr(ex); 1,164,624 ( 0.02%) } . 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>) { 1,476 ( 0.00%) intravisit::walk_item(self, item); 984 ( 0.00%) match item.kind { . hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these 1,444 ( 0.00%) _ => self.encode_info_for_item(item.def_id.to_def_id(), item), . } 1,968 ( 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); . } 3,996 ( 0.00%) fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { . intravisit::walk_generics(self, generics); . self.encode_info_for_generics(generics); 3,552 ( 0.00%) } . } . . impl<'a, 'tcx> EncodeContext<'a, 'tcx> { 154 ( 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); . } . } 176 ( 0.00%) } . . fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) { . for param in generics.params { 1,080 ( 0.00%) let def_id = self.tcx.hir().local_def_id(param.hir_id); 1,280 ( 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<'_>) { 291,156 ( 0.01%) 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. 4,428 ( 0.00%) fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) { 2,460 ( 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(..) => { 10 ( 0.00%) let def = self.tcx.adt_def(item.def_id.to_def_id()); 20 ( 0.00%) self.encode_fields(def); . . for (i, variant) in def.variants.iter_enumerated() { . self.encode_enum_variant_info(def, i); . 66 ( 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, _) => { 12 ( 0.00%) let def = self.tcx.adt_def(item.def_id.to_def_id()); 24 ( 0.00%) self.encode_fields(def); . . // If the struct has a constructor, encode it. 48 ( 0.00%) if let Some(ctor_hir_id) = struct_def.ctor_hir_id() { . let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id); . self.encode_struct_ctor(def, ctor_def_id.to_def_id()); . } . } . hir::ItemKind::Union(..) => { . let def = self.tcx.adt_def(item.def_id.to_def_id()); . self.encode_fields(def); . } . hir::ItemKind::Impl { .. } => { 788 ( 0.00%) for &trait_item_def_id in 121 ( 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(..) => { 5 ( 0.00%) 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); . } . } . } 3,936 ( 0.00%) } . } . . struct ImplsVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . impls: FxHashMap)>>, . } . . impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplsVisitor<'tcx> { 3,444 ( 0.00%) fn visit_item(&mut self, item: &hir::Item<'_>) { 984 ( 0.00%) match item.kind { . hir::ItemKind::Impl(..) => { 460 ( 0.00%) if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) { 654 ( 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)); . } . } . _ => {} . } 3,936 ( 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,968 ( 0.00%) if let hir::ItemKind::Trait(..) | hir::ItemKind::TraitAlias(..) = item.kind { 2 ( 0.00%) 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. 2 ( 0.00%) visitor.traits.sort_by_cached_key(|&def_id| tcx.def_path_hash(def_id)); . tcx.arena.alloc_slice(&visitor.traits) . }, . . ..*providers . }; . } 359,544 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/map.rs -------------------------------------------------------------------------------- Ir -- line 186 ---------------------------------------- . /// // use the values stored in map . /// ``` . pub struct HashMap { . pub(crate) hash_builder: S, . pub(crate) table: RawTable<(K, V), A>, . } . . impl Clone for HashMap { 424 ( 0.00%) fn clone(&self) -> Self { 760 ( 0.00%) HashMap { . hash_builder: self.hash_builder.clone(), 129 ( 0.00%) table: self.table.clone(), . } 477 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . self.table.clone_from(&source.table); . . // Update hash_builder only if we successfully cloned all elements. . self.hash_builder.clone_from(&source.hash_builder); . } . } -- line 207 ---------------------------------------- -- line 210 ---------------------------------------- . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hasher(hash_builder: &S) -> impl Fn(&(Q, V)) -> u64 + '_ . where . K: Borrow, . Q: Hash, . S: BuildHasher, . { 470,907 ( 0.01%) move |val| make_hash::(hash_builder, &val.0) . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent_key(k: &Q) -> impl Fn(&(K, V)) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 1,965,636 ( 0.04%) move |x| k.eq(x.0.borrow()) . } . . /// Ensures that a single closure type across uses of this which, in turn prevents multiple . /// instances of any functions like RawTable::reserve from being generated . #[cfg_attr(feature = "inline-more", inline)] . fn equivalent(k: &Q) -> impl Fn(&K) -> bool + '_ . where . K: Borrow, . Q: ?Sized + Eq, . { 909,814 ( 0.02%) move |x| k.eq(x.borrow()) . } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, -- line 248 ---------------------------------------- -- line 251 ---------------------------------------- . use core::hash::Hasher; . let mut state = hash_builder.build_hasher(); . val.hash(&mut state); . state.finish() . } . . #[cfg(feature = "nightly")] . #[cfg_attr(feature = "inline-more", inline)] 4 ( 0.00%) pub(crate) fn make_hash(hash_builder: &S, val: &Q) -> u64 . where . K: Borrow, . Q: Hash + ?Sized, . S: BuildHasher, . { . hash_builder.hash_one(val) 8 ( 0.00%) } . . #[cfg(not(feature = "nightly"))] . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn make_insert_hash(hash_builder: &S, val: &K) -> u64 . where . K: Hash, . S: BuildHasher, . { -- line 274 ---------------------------------------- -- line 367 ---------------------------------------- . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . /// . /// [`BuildHasher`]: ../../std/hash/trait.BuildHasher.html . #[cfg_attr(feature = "inline-more", inline)] . pub const fn with_hasher(hash_builder: S) -> Self { 1,824,600 ( 0.04%) Self { . hash_builder, . table: RawTable::new(), . } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. . /// -- line 383 ---------------------------------------- -- line 437 ---------------------------------------- . /// use hashbrown::hash_map::DefaultHashBuilder; . /// . /// let s = DefaultHashBuilder::default(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn with_hasher_in(hash_builder: S, alloc: A) -> Self { 115 ( 0.00%) Self { . hash_builder, . table: RawTable::new_in(alloc), . } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. It will be allocated with the given allocator. . /// -- line 453 ---------------------------------------- -- line 663 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert_eq!(a.len(), 0); . /// a.insert(1, "a"); . /// assert_eq!(a.len(), 1); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn len(&self) -> usize { 10,181 ( 0.00%) self.table.len() . } . . /// Returns `true` if the map contains no elements. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 679 ---------------------------------------- -- line 680 ---------------------------------------- . /// . /// let mut a = HashMap::new(); . /// assert!(a.is_empty()); . /// a.insert(1, "a"); . /// assert!(!a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn is_empty(&self) -> bool { 473,183 ( 0.01%) self.len() == 0 . } . . /// Clears the map, returning all key-value pairs as an iterator. Keeps the . /// allocated memory for reuse. . /// . /// # Examples . /// . /// ``` -- line 696 ---------------------------------------- -- line 790 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut a = HashMap::new(); . /// a.insert(1, "a"); . /// a.clear(); . /// assert!(a.is_empty()); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 6 ( 0.00%) pub fn clear(&mut self) { . self.table.clear(); 6 ( 0.00%) } . . /// Creates a consuming iterator visiting all the keys in arbitrary order. . /// The map cannot be used after calling this. . /// The iterator element type is `K`. . /// . /// # Examples . /// . /// ``` -- line 808 ---------------------------------------- -- line 963 ---------------------------------------- . /// } . /// . /// assert_eq!(letters[&'s'], 2); . /// assert_eq!(letters[&'t'], 3); . /// assert_eq!(letters[&'u'], 1); . /// assert_eq!(letters.get(&'y'), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 488 ( 0.00%) pub fn entry(&mut self, key: K) -> Entry<'_, K, V, S, A> { . let hash = make_insert_hash::(&self.hash_builder, &key); . if let Some(elem) = self.table.find(hash, equivalent_key(&key)) { 125 ( 0.00%) Entry::Occupied(OccupiedEntry { . hash, . key: Some(key), . elem, . table: self, . }) . } else { 485 ( 0.00%) Entry::Vacant(VacantEntry { . hash, . key, . table: self, . }) . } 610 ( 0.00%) } . . /// Gets the given key's corresponding entry by reference in the map for in-place manipulation. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; . /// -- line 995 ---------------------------------------- -- line 1047 ---------------------------------------- . /// ``` . #[inline] . pub fn get(&self, k: &Q) -> Option<&V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 5,508,292 ( 0.11%) match self.get_inner(k) { . Some(&(_, ref v)) => Some(v), . None => None, . } . } . . /// Returns the key-value pair corresponding to the supplied key. . /// . /// The supplied key may be any borrowed form of the map's key type, but -- line 1063 ---------------------------------------- -- line 1091 ---------------------------------------- . } . . #[inline] . fn get_inner(&self, k: &Q) -> Option<&(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 4,944,491 ( 0.10%) if self.table.is_empty() { . None . } else { 2 ( 0.00%) let hash = make_hash::(&self.hash_builder, k); . self.table.get(hash, equivalent_key(k)) . } . } . . /// Returns the key-value pair corresponding to the supplied key, with a mutable reference to value. . /// . /// The supplied key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for -- line 1110 ---------------------------------------- -- line 1155 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.contains_key(&1), true); . /// assert_eq!(map.contains_key(&2), false); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 494,243 ( 0.01%) pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { . self.get_inner(k).is_some() 836,344 ( 0.02%) } . . /// Returns a mutable reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// [`Eq`]: https://doc.rust-lang.org/std/cmp/trait.Eq.html -- line 1177 ---------------------------------------- -- line 1185 ---------------------------------------- . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// if let Some(x) = map.get_mut(&1) { . /// *x = "b"; . /// } . /// assert_eq!(map[&1], "b"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 276 ( 0.00%) pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 828 ( 0.00%) match self.get_inner_mut(k) { . Some(&mut (_, ref mut v)) => Some(v), . None => None, . } 552 ( 0.00%) } . . #[inline] . fn get_inner_mut(&mut self, k: &Q) -> Option<&mut (K, V)> . where . K: Borrow, . Q: Hash + Eq, . { 276 ( 0.00%) if self.table.is_empty() { . None . } else { . let hash = make_hash::(&self.hash_builder, k); . self.table.get_mut(hash, equivalent_key(k)) . } . } . . /// Attempts to get mutable references to `N` values in the map at once. -- line 1219 ---------------------------------------- -- line 1495 ---------------------------------------- . /// assert_eq!(map.insert(37, "a"), None); . /// assert_eq!(map.is_empty(), false); . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 7,174,638 ( 0.15%) pub fn insert(&mut self, k: K, v: V) -> Option { . let hash = make_insert_hash::(&self.hash_builder, &k); 318 ( 0.00%) if let Some((_, item)) = self.table.get_mut(hash, equivalent_key(&k)) { 2 ( 0.00%) Some(mem::replace(item, v)) . } else { 1,950,794 ( 0.04%) self.table 1,600,021 ( 0.03%) .insert(hash, (k, v), make_hasher::(&self.hash_builder)); 99,286 ( 0.00%) None . } 7,049,411 ( 0.14%) } . . /// Insert a key-value pair into the map without checking . /// if the key already exists in the map. . /// . /// Returns a reference to the key and value just inserted. . /// . /// This operation is safe if a key does not exist in the map. . /// -- line 1520 ---------------------------------------- -- line 1592 ---------------------------------------- . /// use hashbrown::HashMap; . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.remove(&1), Some("a")); . /// assert_eq!(map.remove(&1), None); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 610,702 ( 0.01%) pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { . // Avoid `Option::map` because it bloats LLVM IR. 1,322,850 ( 0.03%) match self.remove_entry(k) { 30,879 ( 0.00%) Some((_, v)) => Some(v), 455,280 ( 0.01%) None => None, . } 1,505,769 ( 0.03%) } . . /// Removes a key from the map, returning the stored key and value if the . /// key was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// -- line 1618 ---------------------------------------- -- line 1631 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn remove_entry(&mut self, k: &Q) -> Option<(K, V)> . where . K: Borrow, . Q: Hash + Eq, . { . let hash = make_hash::(&self.hash_builder, k); 583,433 ( 0.01%) self.table.remove_entry(hash, equivalent_key(k)) . } . } . . impl HashMap { . /// Creates a raw entry builder for the HashMap. . /// . /// Raw entries provide the lowest level of control for searching and . /// manipulating a map. They must be manually initialized with a hash and -- line 1647 ---------------------------------------- -- line 2209 ---------------------------------------- . /// Creates a `RawEntryMut` from the given key and its hash. . #[inline] . #[allow(clippy::wrong_self_convention)] . pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S, A> . where . K: Borrow, . Q: Eq, . { 1,681,524 ( 0.03%) self.from_hash(hash, equivalent(k)) . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilderMut<'a, K, V, S, A> { . /// Creates a `RawEntryMut` from the given hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 4,472,905 ( 0.09%) pub fn from_hash(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { . self.search(hash, is_match) 4,765,015 ( 0.10%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> RawEntryMut<'a, K, V, S, A> . where . for<'b> F: FnMut(&'b K) -> bool, . { 527,540 ( 0.01%) match self.map.table.find(hash, |(k, _)| is_match(k)) { 2,763,058 ( 0.06%) Some(elem) => RawEntryMut::Occupied(RawOccupiedEntryMut { . elem, . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), 260,546 ( 0.01%) None => RawEntryMut::Vacant(RawVacantEntryMut { . table: &mut self.map.table, . hash_builder: &self.map.hash_builder, . }), . } . } . } . . impl<'a, K, V, S, A: Allocator + Clone> RawEntryBuilder<'a, K, V, S, A> { -- line 2251 ---------------------------------------- -- line 2260 ---------------------------------------- . { . let hash = make_hash::(&self.map.hash_builder, k); . self.from_key_hashed_nocheck(hash, k) . } . . /// Access an entry by a key and its hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] 4,634,654 ( 0.10%) pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Eq, . { 3,126,399 ( 0.06%) self.from_hash(hash, equivalent(k)) 7,220,526 ( 0.15%) } . . #[cfg_attr(feature = "inline-more", inline)] . fn search(self, hash: u64, mut is_match: F) -> Option<(&'a K, &'a V)> . where . F: FnMut(&K) -> bool, . { 7,953,663 ( 0.16%) match self.map.table.get(hash, |(k, _)| is_match(k)) { . Some(&(ref key, ref value)) => Some((key, value)), . None => None, . } . } . . /// Access an entry by hash. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::wrong_self_convention)] -- line 2289 ---------------------------------------- -- line 2624 ---------------------------------------- . /// and returns a mutable reference to it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::shadow_unrelated)] . pub fn insert_hashed_nocheck(self, hash: u64, key: K, value: V) -> (&'a mut K, &'a mut V) . where . K: Hash, . S: BuildHasher, . { 426,014 ( 0.01%) let &mut (ref mut k, ref mut v) = self.table.insert_entry( . hash, . (key, value), . make_hasher::(self.hash_builder), . ); . (k, v) . } . . /// Set the value of an entry with a custom hasher function. -- line 2640 ---------------------------------------- -- line 2974 ---------------------------------------- . /// map.insert("a", 1); . /// map.insert("b", 2); . /// map.insert("c", 3); . /// . /// // Not possible with .iter() . /// let vec: Vec<(&str, i32)> = map.into_iter().collect(); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] 1,228 ( 0.00%) fn into_iter(self) -> IntoIter { 28,465 ( 0.00%) IntoIter { 16,236 ( 0.00%) inner: self.table.into_iter(), . } 3,684 ( 0.00%) } . } . . impl<'a, K, V> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(&'a K, &'a V)> { . // Avoid `Option::map` because it bloats LLVM IR. 508,957 ( 0.01%) match self.inner.next() { . Some(x) => unsafe { . let r = x.as_ref(); 920 ( 0.00%) Some((&r.0, &r.1)) . }, . None => None, . } . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { 186 ( 0.00%) self.inner.size_hint() . } . } . impl ExactSizeIterator for Iter<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { . self.inner.len() . } . } -- line 3013 ---------------------------------------- -- line 3018 ---------------------------------------- . type Item = (&'a K, &'a mut V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(&'a K, &'a mut V)> { . // Avoid `Option::map` because it bloats LLVM IR. . match self.inner.next() { . Some(x) => unsafe { . let r = x.as_mut(); 4 ( 0.00%) Some((&r.0, &mut r.1)) . }, . None => None, . } . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } -- line 3034 ---------------------------------------- -- line 3051 ---------------------------------------- . } . } . . impl Iterator for IntoIter { . type Item = (K, V); . . #[cfg_attr(feature = "inline-more", inline)] . fn next(&mut self) -> Option<(K, V)> { 1,044 ( 0.00%) self.inner.next() . } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for IntoIter { . #[cfg_attr(feature = "inline-more", inline)] -- line 3067 ---------------------------------------- -- line 3076 ---------------------------------------- . f.debug_list().entries(self.iter()).finish() . } . } . . impl<'a, K, V> Iterator for Keys<'a, K, V> { . type Item = &'a K; . . #[cfg_attr(feature = "inline-more", inline)] 74 ( 0.00%) fn next(&mut self) -> Option<&'a K> { . // Avoid `Option::map` because it bloats LLVM IR. . match self.inner.next() { . Some((k, _)) => Some(k), . None => None, . } 148 ( 0.00%) } . #[cfg_attr(feature = "inline-more", inline)] . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . } . impl ExactSizeIterator for Keys<'_, K, V> { . #[cfg_attr(feature = "inline-more", inline)] . fn len(&self) -> usize { -- line 3098 ---------------------------------------- -- line 3819 ---------------------------------------- . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn insert(self, value: V) -> &'a mut V . where . K: Hash, . S: BuildHasher, . { . let table = &mut self.table.table; 26 ( 0.00%) let entry = table.insert_entry( . self.hash, . (self.key, value), . make_hasher::(&self.table.hash_builder), . ); . &mut entry.1 . } . . #[cfg_attr(feature = "inline-more", inline)] -- line 3835 ---------------------------------------- -- line 4557 ---------------------------------------- . /// keys with new values returned from the iterator. . impl Extend<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher, . A: Allocator + Clone, . { . #[cfg_attr(feature = "inline-more", inline)] 25,176 ( 0.00%) fn extend>(&mut self, iter: T) { . // Keys may be already present or show multiple times in the iterator. . // Reserve the entire hint lower bound if the map is empty. . // Otherwise reserve half the hint (rounded up), so the map . // will only resize twice in the worst case. 19,657 ( 0.00%) let iter = iter.into_iter(); 16,411 ( 0.00%) let reserve = if self.is_empty() { . iter.size_hint().0 . } else { 19 ( 0.00%) (iter.size_hint().0 + 1) / 2 . }; . self.reserve(reserve); . iter.for_each(move |(k, v)| { 69,591 ( 0.00%) self.insert(k, v); . }); 15,878 ( 0.00%) } . . #[inline] . #[cfg(feature = "nightly")] . fn extend_one(&mut self, (k, v): (K, V)) { . self.insert(k, v); . } . . #[inline] -- line 4588 ---------------------------------------- 4,052,409 ( 0.08%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/check_consts/qualifs.rs -------------------------------------------------------------------------------- Ir -- line 82 ---------------------------------------- . /// promotion of temporaries must not change program behavior; if the promoted could be . /// written to, that would be a problem. . pub struct HasMutInterior; . . impl Qualif for HasMutInterior { . const ANALYSIS_NAME: &'static str = "flow_has_mut_interior"; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { 363 ( 0.00%) qualifs.has_mut_interior . } . . fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { 8,286,264 ( 0.17%) !ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env) . } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . _: SubstsRef<'tcx>, . ) -> bool { . // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently. . // It arises structurally for all other types. 4,495 ( 0.00%) Some(adt.did) == cx.tcx.lang_items().unsafe_cell_type() . } . } . . /// Constant containing an ADT that implements `Drop`. . /// This must be ruled out because implicit promotion would remove side-effects . /// that occur as part of dropping that value. N.B., the implicit promotion has . /// to reject const Drop implementations because even if side-effects are ruled . /// out through other means, the execution of the drop could diverge. . pub struct NeedsDrop; . . impl Qualif for NeedsDrop { . const ANALYSIS_NAME: &'static str = "flow_needs_drop"; . const IS_CLEARED_ON_MOVE: bool = true; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { 91 ( 0.00%) qualifs.needs_drop . } . 2,210,016 ( 0.05%) fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { 552,504 ( 0.01%) ty.needs_drop(cx.tcx, cx.param_env) 2,486,268 ( 0.05%) } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . _: SubstsRef<'tcx>, . ) -> bool { 921 ( 0.00%) adt.has_dtor(cx.tcx) . } . } . . /// Constant containing an ADT that implements non-const `Drop`. . /// This must be ruled out because we cannot run `Drop` during compile-time. . pub struct NeedsNonConstDrop; . . impl Qualif for NeedsNonConstDrop { -- line 140 ---------------------------------------- -- line 141 ---------------------------------------- . const ANALYSIS_NAME: &'static str = "flow_needs_nonconst_drop"; . const IS_CLEARED_ON_MOVE: bool = true; . const ALLOW_PROMOTED: bool = true; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { . qualifs.needs_non_const_drop . } . 837 ( 0.00%) fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { . // Avoid selecting for simple cases, such as builtin types. 372 ( 0.00%) if ty::util::is_trivially_const_drop(ty) { . return false; . } . . let Some(drop_trait) = cx.tcx.lang_items().drop_trait() else { . // there is no way to define a type that needs non-const drop . // without having the lang item present. . return false; . }; -- line 159 ---------------------------------------- -- line 196 ---------------------------------------- . let mut fcx = FulfillmentContext::new(); . for nested in impl_src.nested_obligations() { . fcx.register_predicate_obligation(&infcx, nested); . } . . // If we had any errors, then it's bad . !fcx.select_all_or_error(&infcx).is_empty() . }) 837 ( 0.00%) } . . fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . _: SubstsRef<'tcx>, . ) -> bool { . adt.has_non_const_dtor(cx.tcx) . } -- line 212 ---------------------------------------- -- line 214 ---------------------------------------- . . /// A constant that cannot be used as part of a pattern in a `match` expression. . pub struct CustomEq; . . impl Qualif for CustomEq { . const ANALYSIS_NAME: &'static str = "flow_custom_eq"; . . fn in_qualifs(qualifs: &ConstQualifs) -> bool { 182 ( 0.00%) qualifs.custom_eq . } . . fn in_any_value_of_ty<'tcx>(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool { . // If *any* component of a composite data type does not implement `Structural{Partial,}Eq`, . // we know that at least some values of that type are not structural-match. I say "some" . // because that component may be part of an enum variant (e.g., . // `Option::::Some`), in which case some values of this type may be . // structural-match (`Option::None`). 1,105,231 ( 0.02%) traits::search_for_structural_match_violation(cx.body.span, cx.tcx, ty).is_some() . } . 1,274 ( 0.00%) fn in_adt_inherently<'tcx>( . cx: &ConstCx<'_, 'tcx>, . adt: &'tcx AdtDef, . substs: SubstsRef<'tcx>, . ) -> bool { 182 ( 0.00%) let ty = cx.tcx.mk_ty(ty::Adt(adt, substs)); . !ty.is_structural_eq_shallow(cx.tcx) 1,456 ( 0.00%) } . } . . // FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return. . . /// Returns `true` if this `Rvalue` contains qualif `Q`. 218,020 ( 0.00%) pub fn in_rvalue<'tcx, Q, F>( . cx: &ConstCx<'_, 'tcx>, . in_local: &mut F, . rvalue: &Rvalue<'tcx>, . ) -> bool . where . Q: Qualif, . F: FnMut(Local) -> bool, . { 109,010 ( 0.00%) match rvalue { . Rvalue::ThreadLocalRef(_) | Rvalue::NullaryOp(..) => { . Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) . } . . Rvalue::Discriminant(place) | Rvalue::Len(place) => { . in_place::(cx, in_local, place.as_ref()) . } . . Rvalue::Use(operand) . | Rvalue::Repeat(operand, _) . | Rvalue::UnaryOp(_, operand) . | Rvalue::Cast(_, operand, _) 13,459 ( 0.00%) | Rvalue::ShallowInitBox(operand, _) => in_operand::(cx, in_local, operand), . . Rvalue::BinaryOp(_, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(_, box (lhs, rhs)) => { . in_operand::(cx, in_local, lhs) || in_operand::(cx, in_local, rhs) . } . 17,350 ( 0.00%) Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => { . // Special-case reborrows to be more like a copy of the reference. 6,924 ( 0.00%) if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() { 3,462 ( 0.00%) let base_ty = place_base.ty(cx.body, cx.tcx).ty; 6,924 ( 0.00%) if let ty::Ref(..) = base_ty.kind() { 18,948 ( 0.00%) return in_place::(cx, in_local, place_base); . } . } . 27,084 ( 0.00%) in_place::(cx, in_local, place.as_ref()) . } . . Rvalue::Aggregate(kind, operands) => { . // Return early if we know that the struct or enum being constructed is always . // qualified. 32,150 ( 0.00%) if let AggregateKind::Adt(adt_did, _, substs, ..) = **kind { 1,388 ( 0.00%) let def = cx.tcx.adt_def(adt_did); 2,787 ( 0.00%) if Q::in_adt_inherently(cx, def, substs) { . return true; . } 1,206 ( 0.00%) if def.is_union() && Q::in_any_value_of_ty(cx, rvalue.ty(cx.body, cx.tcx)) { . return true; . } . } . . // Otherwise, proceed structurally... 8,851,364 ( 0.18%) operands.iter().any(|o| in_operand::(cx, in_local, o)) . } . } 120,548 ( 0.00%) } . . /// Returns `true` if this `Place` contains qualif `Q`. 180,484 ( 0.00%) pub fn in_place<'tcx, Q, F>(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool . where . Q: Qualif, . F: FnMut(Local) -> bool, . { 5,751 ( 0.00%) let mut place = place; . while let Some((place_base, elem)) = place.last_projection() { . match elem { . ProjectionElem::Index(index) if in_local(index) => return true, . . ProjectionElem::Deref . | ProjectionElem::Field(_, _) . | ProjectionElem::ConstantIndex { .. } . | ProjectionElem::Subslice { .. } -- line 320 ---------------------------------------- -- line 327 ---------------------------------------- . if !Q::in_any_value_of_ty(cx, proj_ty) { . return false; . } . . place = place_base; . } . . assert!(place.projection.is_empty()); 3,195 ( 0.00%) in_local(place.local) 29,248 ( 0.00%) } . . /// Returns `true` if this `Operand` contains qualif `Q`. 17,180,697 ( 0.35%) pub fn in_operand<'tcx, Q, F>( . cx: &ConstCx<'_, 'tcx>, . in_local: &mut F, . operand: &Operand<'tcx>, . ) -> bool . where . Q: Qualif, . F: FnMut(Local) -> bool, . { 3,879,630 ( 0.08%) let constant = match operand { . Operand::Copy(place) | Operand::Move(place) => { 52,640 ( 0.00%) return in_place::(cx, in_local, place.as_ref()); . } . . Operand::Constant(c) => c, . }; . . // Check the qualifs of the value of `const` items. 9,665,815 ( 0.20%) if let Some(ct) = constant.literal.const_for_ty() { 3,866,326 ( 0.08%) if let ty::ConstKind::Unevaluated(ty::Unevaluated { def, substs: _, promoted }) = ct.val { . // Use qualifs of the type for the promoted. Promoteds in MIR body should be possible . // only for `NeedsNonConstDrop` with precise drop checking. This is the only const . // check performed after the promotion. Verify that with an assertion. 636 ( 0.00%) assert!(promoted.is_none() || Q::ALLOW_PROMOTED); . // Don't peek inside trait associated constants. 727 ( 0.00%) if promoted.is_none() && cx.tcx.trait_of_item(def.did).is_none() { 6,269 ( 0.00%) let qualifs = if let Some((did, param_did)) = def.as_const_arg() { . cx.tcx.at(constant.span).mir_const_qualif_const_arg((did, param_did)) . } else { . cx.tcx.at(constant.span).mir_const_qualif(def.did) . }; . 636 ( 0.00%) if !Q::in_qualifs(&qualifs) { . return false; . } . . // Just in case the type is more specific than . // the definition, e.g., impl associated const . // with type parameters, take it into account. . } . } . } . // Otherwise use the qualifs of the type. 4,693,895 ( 0.10%) Q::in_any_value_of_ty(cx, constant.literal.ty()) 15,494,452 ( 0.32%) } 92,516 ( 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 { 276,250 ( 0.01%) 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 { 372 ( 0.00%) pub fn new() -> Self { . let linewidth = 78; 5,593 ( 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, . } 465 ( 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) { 246 ( 0.00%) if !self.scan_stack.is_empty() { 190 ( 0.00%) self.check_stack(0); 190 ( 0.00%) self.advance_left(); . } . } . . fn scan_begin(&mut self, token: BeginToken) { 141,327 ( 0.00%) if self.scan_stack.is_empty() { 190 ( 0.00%) self.left_total = 1; . self.right_total = 1; . self.buf.clear(); . } 565,308 ( 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) { 141,327 ( 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) { 138,671 ( 0.00%) if self.scan_stack.is_empty() { . self.left_total = 1; . self.right_total = 1; . self.buf.clear(); . } else { 277,342 ( 0.01%) self.check_stack(0); . } 554,684 ( 0.01%) let right = self.buf.push(BufEntry { token: Token::Break(token), size: -self.right_total }); . self.scan_stack.push_back(right); 416,013 ( 0.01%) self.right_total += token.blank_space; . } . 2,520,576 ( 0.05%) fn scan_string(&mut self, string: Cow<'static, str>) { 280,064 ( 0.01%) if self.scan_stack.is_empty() { . self.print_string(&string); . } else { . let len = string.len() as isize; 279,913 ( 0.01%) self.buf.push(BufEntry { token: Token::String(string), size: len }); 839,739 ( 0.02%) self.right_total += len; . self.check_stream(); . } 2,239,304 ( 0.05%) } . . fn check_stream(&mut self) { 1,235,422 ( 0.03%) while self.right_total - self.left_total > self.space { 69,462 ( 0.00%) if *self.scan_stack.front().unwrap() == self.buf.index_of_first() { . self.scan_stack.pop_front().unwrap(); 13,168 ( 0.00%) self.buf.first_mut().unwrap().size = SIZE_INFINITY; . } 46,308 ( 0.00%) self.advance_left(); 23,154 ( 0.00%) if self.buf.is_empty() { . break; . } . } . } . 1,096,471 ( 0.02%) fn advance_left(&mut self) { 1,448,784 ( 0.03%) while self.buf.first().unwrap().size >= 0 { 2,103,714 ( 0.04%) let left = self.buf.pop_first().unwrap(); . . match &left.token { . Token::String(string) => { 839,739 ( 0.02%) self.left_total += string.len() as isize; . self.print_string(string); . } . Token::Break(token) => { 416,013 ( 0.01%) self.left_total += token.blank_space; . self.print_break(*token, left.size); . } 7,086 ( 0.00%) Token::Begin(token) => self.print_begin(*token, left.size), . Token::End => self.print_end(), . } . 5,609,904 ( 0.12%) self.last_printed = Some(left.token); . 701,238 ( 0.01%) if self.buf.is_empty() { . break; . } . } 185,992 ( 0.00%) } . 1,248,894 ( 0.03%) fn check_stack(&mut self, mut depth: usize) { 828,865 ( 0.02%) while let Some(&index) = self.scan_stack.back() { . let mut entry = &mut self.buf[index]; 1,766,113 ( 0.04%) match entry.token { . Token::Begin(_) => { 280,102 ( 0.01%) if depth == 0 { . break; . } . self.scan_stack.pop_back().unwrap(); 416,895 ( 0.01%) entry.size += self.right_total; 138,965 ( 0.00%) depth -= 1; . } . Token::End => { . // paper says + not =, but that makes no sense. . self.scan_stack.pop_back().unwrap(); 141,327 ( 0.00%) entry.size = 1; 282,654 ( 0.01%) depth += 1; . } . _ => { . self.scan_stack.pop_back().unwrap(); 383,595 ( 0.01%) entry.size += self.right_total; 383,031 ( 0.01%) if depth == 0 { . break; . } . } . } . } 1,110,128 ( 0.02%) } . . fn get_top(&self) -> PrintFrame { 416,013 ( 0.01%) *self . .print_stack . .last() . .unwrap_or(&PrintFrame::Broken { offset: 0, breaks: Breaks::Inconsistent }) . } . . fn print_begin(&mut self, token: BeginToken, size: isize) { 423,981 ( 0.01%) if size > self.space { 11,810 ( 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 = 830,024 ( 0.02%) 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'); 32,673 ( 0.00%) self.pending_indentation = offset + token.offset; 43,564 ( 0.00%) self.space = self.margin - (offset + token.offset); . } else { 383,340 ( 0.01%) self.pending_indentation += token.blank_space; 511,120 ( 0.01%) 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. 280,064 ( 0.01%) self.out.reserve(self.pending_indentation as usize); 418 ( 0.00%) self.out.extend(iter::repeat(' ').take(self.pending_indentation as usize)); 280,064 ( 0.01%) self.pending_indentation = 0; . . self.out.push_str(string); 1,400,169 ( 0.03%) self.space -= string.len() as isize; . } . . // Convenience functions to talk to the printer. . . /// "raw box" 5,872 ( 0.00%) pub fn rbox(&mut self, indent: usize, breaks: Breaks) { . self.scan_begin(BeginToken { offset: indent as isize, breaks }) 4,404 ( 0.00%) } . . /// Inconsistent breaking box 843,558 ( 0.02%) pub fn ibox(&mut self, indent: usize) { . self.rbox(indent, Breaks::Inconsistent) 702,965 ( 0.01%) } . . /// Consistent breaking box . pub fn cbox(&mut self, indent: usize) { . self.rbox(indent, Breaks::Consistent) . } . 1,109,368 ( 0.02%) pub fn break_offset(&mut self, n: usize, off: isize) { . self.scan_break(BreakToken { offset: off, blank_space: n as isize }) 832,026 ( 0.02%) } . 565,308 ( 0.01%) pub fn end(&mut self) { . self.scan_end() 565,308 ( 0.01%) } . 1,230 ( 0.00%) pub fn eof(mut self) -> String { . self.scan_eof(); 984 ( 0.00%) self.out 1,230 ( 0.00%) } . . pub fn word>>(&mut self, wrd: S) { . let string = wrd.into(); 1,962,139 ( 0.04%) self.scan_string(string) . } . . fn spaces(&mut self, n: usize) { 554,138 ( 0.01%) 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 { 276,250 ( 0.01%) 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 ---------------------------------------- 5,629,422 ( 0.12%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/raw_vec.rs -------------------------------------------------------------------------------- Ir -- line 124 ---------------------------------------- . Self { ptr: Unique::dangling(), cap: 0, alloc } . } . . /// Like `with_capacity`, but parameterized over the choice of . /// allocator for the returned `RawVec`. . #[cfg(not(no_global_oom_handling))] . #[inline] . pub fn with_capacity_in(capacity: usize, alloc: A) -> Self { 40 ( 0.00%) Self::allocate_in(capacity, AllocInit::Uninitialized, alloc) . } . . /// Like `with_capacity_zeroed`, but parameterized over the choice . /// of allocator for the returned `RawVec`. . #[cfg(not(no_global_oom_handling))] . #[inline] . pub fn with_capacity_zeroed_in(capacity: usize, alloc: A) -> Self { . Self::allocate_in(capacity, AllocInit::Zeroed, alloc) -- line 140 ---------------------------------------- -- line 147 ---------------------------------------- . /// . /// # Safety . /// . /// * `len` must be greater than or equal to the most recently requested capacity, and . /// * `len` must be less than or equal to `self.capacity()`. . /// . /// Note, that the requested capacity and `self.capacity()` could differ, as . /// an allocator could overallocate and return a greater memory block than requested. 33 ( 0.00%) pub unsafe fn into_box(self, len: usize) -> Box<[MaybeUninit], A> { . // Sanity-check one half of the safety requirement (we cannot check the other half). . debug_assert!( . len <= self.capacity(), . "`len` must be smaller than or equal to `self.capacity()`" . ); . . let me = ManuallyDrop::new(self); . unsafe { . let slice = slice::from_raw_parts_mut(me.ptr() as *mut MaybeUninit, len); . Box::from_raw_in(slice, ptr::read(&me.alloc)) . } 33 ( 0.00%) } . . #[cfg(not(no_global_oom_handling))] 80 ( 0.00%) fn allocate_in(capacity: usize, init: AllocInit, alloc: A) -> Self { . if mem::size_of::() == 0 { . Self::new_in(alloc) . } else { . // We avoid `unwrap_or_else` here because it bloats the amount of . // LLVM IR generated. . let layout = match Layout::array::(capacity) { . Ok(layout) => layout, . Err(_) => capacity_overflow(), . }; . match alloc_guard(layout.size()) { . Ok(_) => {} . Err(_) => capacity_overflow(), . } 40 ( 0.00%) let result = match init { . AllocInit::Uninitialized => alloc.allocate(layout), . AllocInit::Zeroed => alloc.allocate_zeroed(layout), . }; . let ptr = match result { . Ok(ptr) => ptr, . Err(_) => handle_alloc_error(layout), . }; . -- line 192 ---------------------------------------- -- line 194 ---------------------------------------- . // matches the size requested. If that ever changes, the capacity . // here should change to `ptr.len() / mem::size_of::()`. . Self { . ptr: unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) }, . cap: capacity, . alloc, . } . } 100 ( 0.00%) } . . /// Reconstitutes a `RawVec` from a pointer, capacity, and allocator. . /// . /// # Safety . /// . /// The `ptr` must be allocated (via the given allocator `alloc`), and with the given . /// `capacity`. . /// The `capacity` cannot exceed `isize::MAX` for sized types. (only a concern on 32-bit -- line 210 ---------------------------------------- -- line 233 ---------------------------------------- . } . . /// Returns a shared reference to the allocator backing this `RawVec`. . pub fn allocator(&self) -> &A { . &self.alloc . } . . fn current_memory(&self) -> Option<(NonNull, Layout)> { 14,886,903 ( 0.31%) if mem::size_of::() == 0 || self.cap == 0 { 143,124 ( 0.00%) None . } else { . // We have an allocated chunk of memory, so we can bypass runtime . // checks to get our current layout. . unsafe { . let align = mem::align_of::(); 889,669 ( 0.02%) let size = mem::size_of::() * self.cap; . let layout = Layout::from_size_align_unchecked(size, align); 275,672 ( 0.01%) Some((self.ptr.cast().into(), layout)) . } . } . } . . /// Ensures that the buffer contains at least enough space to hold `len + . /// additional` elements. If it doesn't already have enough capacity, will . /// reallocate enough space plus comfortable slack space to get amortized . /// *O*(1) behavior. Will limit this behavior if it would needlessly cause -- line 258 ---------------------------------------- -- line 274 ---------------------------------------- . #[cfg(not(no_global_oom_handling))] . #[inline] . pub fn reserve(&mut self, len: usize, additional: usize) { . // Callers expect this function to be very cheap when there is already sufficient capacity. . // Therefore, we move all the resizing and error-handling logic from grow_amortized and . // handle_reserve behind a call, while making sure that this function is likely to be . // inlined as just a comparison and a call if the comparison fails. . #[cold] 609,119 ( 0.01%) fn do_reserve_and_handle( . slf: &mut RawVec, . len: usize, . additional: usize, . ) { 1,652 ( 0.00%) handle_reserve(slf.grow_amortized(len, additional)); 794,739 ( 0.02%) } . 1,344,584 ( 0.03%) if self.needs_to_grow(len, additional) { 758,645 ( 0.02%) do_reserve_and_handle(self, len, additional); . } . } . . /// A specialized version of `reserve()` used only by the hot and . /// oft-instantiated `Vec::push()`, which does its own capacity check. . #[cfg(not(no_global_oom_handling))] . #[inline(never)] 623,036 ( 0.01%) pub fn reserve_for_push(&mut self, len: usize) { . handle_reserve(self.grow_amortized(len, 1)); 771,802 ( 0.02%) } . . /// The same as `reserve`, but returns on errors instead of panicking or aborting. . pub fn try_reserve(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { . if self.needs_to_grow(len, additional) { . self.grow_amortized(len, additional) . } else { . Ok(()) . } -- line 309 ---------------------------------------- -- line 322 ---------------------------------------- . /// # Panics . /// . /// Panics if the new capacity exceeds `isize::MAX` bytes. . /// . /// # Aborts . /// . /// Aborts on OOM. . #[cfg(not(no_global_oom_handling))] 19,905 ( 0.00%) pub fn reserve_exact(&mut self, len: usize, additional: usize) { . handle_reserve(self.try_reserve_exact(len, additional)); 19,905 ( 0.00%) } . . /// The same as `reserve_exact`, but returns on errors instead of panicking or aborting. . pub fn try_reserve_exact( . &mut self, . len: usize, . additional: usize, . ) -> Result<(), TryReserveError> { 8,192 ( 0.00%) if self.needs_to_grow(len, additional) { self.grow_exact(len, additional) } else { Ok(()) } . } . . /// Shrinks the buffer down to the specified capacity. If the given amount . /// is 0, actually completely deallocates. . /// . /// # Panics . /// . /// Panics if the given amount is *larger* than the current capacity. . /// . /// # Aborts . /// . /// Aborts on OOM. . #[cfg(not(no_global_oom_handling))] 5,920 ( 0.00%) pub fn shrink_to_fit(&mut self, cap: usize) { . handle_reserve(self.shrink(cap)); 7,104 ( 0.00%) } . } . . impl RawVec { . /// Returns if the buffer needs to grow to fulfill the needed extra capacity. . /// Mainly used to make inlining reserve-calls possible without inlining `grow`. . fn needs_to_grow(&self, len: usize, additional: usize) -> bool { 2,545,009 ( 0.05%) additional > self.capacity().wrapping_sub(len) . } . . fn set_ptr_and_cap(&mut self, ptr: NonNull<[u8]>, cap: usize) { . // Allocators currently return a `NonNull<[u8]>` whose length matches . // the size requested. If that ever changes, the capacity here should . // change to `ptr.len() / mem::size_of::()`. 352,411 ( 0.01%) self.ptr = unsafe { Unique::new_unchecked(ptr.cast().as_ptr()) }; 352,759 ( 0.01%) self.cap = cap; . } . . // This method is usually instantiated many times. So we want it to be as . // small as possible, to improve compile times. But we also want as much of . // its contents to be statically computable as possible, to make the . // generated code run faster. Therefore, this method is carefully written . // so that all of the code that depends on `T` is within it, while as much . // of the code that doesn't depend on `T` as possible is in functions that . // are non-generic over `T`. 2,088 ( 0.00%) fn grow_amortized(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { . // This is ensured by the calling contexts. . debug_assert!(additional > 0); . . if mem::size_of::() == 0 { . // Since we return a capacity of `usize::MAX` when `elem_size` is . // 0, getting to here necessarily means the `RawVec` is overfull. . return Err(CapacityOverflow.into()); . } . . // Nothing we can really do about these checks, sadly. . let required_cap = len.checked_add(additional).ok_or(CapacityOverflow)?; . . // This guarantees exponential growth. The doubling cannot overflow . // because `cap <= isize::MAX` and the type of `cap` is `usize`. 1,390,796 ( 0.03%) let cap = cmp::max(self.cap * 2, required_cap); . let cap = cmp::max(Self::MIN_NON_ZERO_CAP, cap); . . let new_layout = Layout::array::(cap); . . // `finish_grow` is non-generic over `T`. 1,184,761 ( 0.02%) let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; . self.set_ptr_and_cap(ptr, cap); . Ok(()) 2,088 ( 0.00%) } . . // The constraints on this method are much the same as those on . // `grow_amortized`, but this method is usually instantiated less often so . // it's less critical. . fn grow_exact(&mut self, len: usize, additional: usize) -> Result<(), TryReserveError> { . if mem::size_of::() == 0 { . // Since we return a capacity of `usize::MAX` when the type size is . // 0, getting to here necessarily means the `RawVec` is overfull. . return Err(CapacityOverflow.into()); . } . . let cap = len.checked_add(additional).ok_or(CapacityOverflow)?; . let new_layout = Layout::array::(cap); . . // `finish_grow` is non-generic over `T`. 10,573 ( 0.00%) let ptr = finish_grow(new_layout, self.current_memory(), &mut self.alloc)?; . self.set_ptr_and_cap(ptr, cap); . Ok(()) . } . . fn shrink(&mut self, cap: usize) -> Result<(), TryReserveError> { 3,552 ( 0.00%) assert!(cap <= self.capacity(), "Tried to shrink to a larger capacity"); . . let (ptr, layout) = if let Some(mem) = self.current_memory() { mem } else { return Ok(()) }; 3,552 ( 0.00%) let new_size = cap * mem::size_of::(); . . let ptr = unsafe { . let new_layout = Layout::from_size_align_unchecked(new_size, layout.align()); . self.alloc . .shrink(ptr, layout, new_layout) . .map_err(|_| AllocError { layout: new_layout, non_exhaustive: () })? . }; . self.set_ptr_and_cap(ptr, cap); -- line 438 ---------------------------------------- -- line 440 ---------------------------------------- . } . } . . // This function is outside `RawVec` to minimize compile times. See the comment . // above `RawVec::grow_amortized` for details. (The `A` parameter isn't . // significant, because the number of different `A` types seen in practice is . // much smaller than the number of `T` types.) . #[inline(never)] 1,756,115 ( 0.04%) fn finish_grow( . new_layout: Result, . current_memory: Option<(NonNull, Layout)>, . alloc: &mut A, . ) -> Result, TryReserveError> . where . A: Allocator, . { . // Check for the error here to minimize the size of `RawVec::grow_*`. . let new_layout = new_layout.map_err(|_| CapacityOverflow)?; . . alloc_guard(new_layout.size())?; . 983,406 ( 0.02%) let memory = if let Some((ptr, old_layout)) = current_memory { . debug_assert_eq!(old_layout.align(), new_layout.align()); . unsafe { . // The allocator checks for alignment equality . intrinsics::assume(old_layout.align() == new_layout.align()); . alloc.grow(ptr, old_layout, new_layout) . } . } else { . alloc.allocate(new_layout) . }; . . memory.map_err(|_| AllocError { layout: new_layout, non_exhaustive: () }.into()) 1,404,892 ( 0.03%) } . . unsafe impl<#[may_dangle] T, A: Allocator> Drop for RawVec { . /// Frees the memory owned by the `RawVec` *without* trying to drop its contents. 10,110 ( 0.00%) fn drop(&mut self) { 5,866,346 ( 0.12%) if let Some((ptr, layout)) = self.current_memory() { . unsafe { self.alloc.deallocate(ptr, layout) } . } 8,014 ( 0.00%) } . } . . // Central function for reserve error handling. . #[cfg(not(no_global_oom_handling))] . #[inline] . fn handle_reserve(result: Result<(), TryReserveError>) { . match result.map_err(|e| e.kind()) { . Err(CapacityOverflow) => capacity_overflow(), -- line 489 ---------------------------------------- 5,378,148 ( 0.11%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_expand/src/expand.rs -------------------------------------------------------------------------------- Ir -- line 48 ---------------------------------------- . /// A fragment of AST that can be produced by a single macro expansion. . /// Can also serve as an input and intermediate result for macro expansion operations. . pub enum AstFragment { . OptExpr(Option>), . $($Kind($AstTy),)* . } . . /// "Discriminant" of an AST fragment. 63 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq)] . pub enum AstFragmentKind { . OptExpr, . $($Kind,)* . } . . impl AstFragmentKind { . pub fn name(self) -> &'static str { . match self { . AstFragmentKind::OptExpr => "expression", . $(AstFragmentKind::$Kind => $kind_name,)* . } . } . 210 ( 0.00%) fn make_from<'a>(self, result: Box) -> Option { 350 ( 0.00%) match self { . AstFragmentKind::OptExpr => 66 ( 0.00%) result.make_expr().map(Some).map(AstFragment::OptExpr), 81 ( 0.00%) $(AstFragmentKind::$Kind => result.$make_ast().map(AstFragment::$Kind),)* . } 210 ( 0.00%) } . } . . impl AstFragment { 164 ( 0.00%) pub fn add_placeholders(&mut self, placeholders: &[NodeId]) { 164 ( 0.00%) if placeholders.is_empty() { . return; . } 80 ( 0.00%) match self { 40 ( 0.00%) $($(AstFragment::$Kind(ast) => ast.extend(placeholders.iter().flat_map(|id| { . // We are repeating through arguments with `many`, to do that we have to . // mention some macro variable from those arguments even if it's not used. . macro _repeating($flat_map_ast_elt) {} 392 ( 0.00%) placeholder(AstFragmentKind::$Kind, *id, None).$make_ast() . })),)?)* . _ => panic!("unexpected AST fragment kind") . } 328 ( 0.00%) } . . pub fn make_opt_expr(self) -> Option> { 132 ( 0.00%) match self { 66 ( 0.00%) AstFragment::OptExpr(expr) => expr, . _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), . } . } . . $(pub fn $make_ast(self) -> $AstTy { 574 ( 0.00%) match self { 834 ( 0.00%) AstFragment::$Kind(ast) => ast, . _ => panic!("AstFragment::make_* called on the wrong kind of fragment"), . } . })* . . fn make_ast(self) -> T::OutputTy { . T::fragment_to_output(self) . } . 328 ( 0.00%) pub fn mut_visit_with(&mut self, vis: &mut F) { 1,804 ( 0.00%) match self { . AstFragment::OptExpr(opt_expr) => { . visit_clobber(opt_expr, |opt_expr| { 132 ( 0.00%) if let Some(expr) = opt_expr { 165 ( 0.00%) vis.filter_map_expr(expr) . } else { . None . } . }); . } 432 ( 0.00%) $($(AstFragment::$Kind(ast) => vis.$mut_visit_ast(ast),)?)* 249 ( 0.00%) $($(AstFragment::$Kind(ast) => 1,795 ( 0.00%) ast.flat_map_in_place(|ast| vis.$flat_map_ast_elt(ast)),)?)* . } 66 ( 0.00%) } . 2,646 ( 0.00%) pub fn visit_with<'a, V: Visitor<'a>>(&'a self, visitor: &mut V) { 1,668 ( 0.00%) match *self { . AstFragment::OptExpr(Some(ref expr)) => visitor.visit_expr(expr), . AstFragment::OptExpr(None) => {} 11 ( 0.00%) $($(AstFragment::$Kind(ref ast) => visitor.$visit_ast(ast),)?)* . $($(AstFragment::$Kind(ref ast) => for ast_elt in &ast[..] { 968 ( 0.00%) visitor.$visit_ast_elt(ast_elt, $($args)*); . })?)* . } 1,392 ( 0.00%) } . } . . impl<'a> MacResult for crate::mbe::macro_rules::ParserAnyMacro<'a> { 172 ( 0.00%) $(fn $make_ast(self: Box>) . -> Option<$AstTy> { 89 ( 0.00%) Some(self.make(AstFragmentKind::$Kind).$make_ast()) 132 ( 0.00%) })* . } . } . } . . ast_fragments! { . Expr(P) { "expression"; one fn visit_expr; fn visit_expr; fn make_expr; } . Pat(P) { "pattern"; one fn visit_pat; fn visit_pat; fn make_pat; } . Ty(P) { "type"; one fn visit_ty; fn visit_ty; fn make_ty; } -- line 154 ---------------------------------------- -- line 215 ---------------------------------------- . } . . impl AstFragmentKind { . crate fn dummy(self, span: Span) -> AstFragment { . self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment") . } . . pub fn supports_macro_expansion(self) -> SupportsMacroExpansion { 438 ( 0.00%) match self { . AstFragmentKind::OptExpr . | AstFragmentKind::Expr . | AstFragmentKind::Stmts . | AstFragmentKind::Ty . | AstFragmentKind::Pat => SupportsMacroExpansion::Yes { supports_inner_attrs: false }, . AstFragmentKind::Items . | AstFragmentKind::TraitItems . | AstFragmentKind::ImplItems -- line 231 ---------------------------------------- -- line 234 ---------------------------------------- . AstFragmentKind::Arms . | AstFragmentKind::ExprFields . | AstFragmentKind::PatFields . | AstFragmentKind::GenericParams . | AstFragmentKind::Params . | AstFragmentKind::FieldDefs . | AstFragmentKind::Variants => SupportsMacroExpansion::No, . } 146 ( 0.00%) } . 228 ( 0.00%) fn expect_from_annotatables>( . self, . items: I, . ) -> AstFragment { . let mut items = items.into_iter(); 380 ( 0.00%) match self { . AstFragmentKind::Arms => { . AstFragment::Arms(items.map(Annotatable::expect_arm).collect()) . } . AstFragmentKind::ExprFields => { . AstFragment::ExprFields(items.map(Annotatable::expect_expr_field).collect()) . } . AstFragmentKind::PatFields => { . AstFragment::PatFields(items.map(Annotatable::expect_pat_field).collect()) -- line 257 ---------------------------------------- -- line 264 ---------------------------------------- . } . AstFragmentKind::FieldDefs => { . AstFragment::FieldDefs(items.map(Annotatable::expect_field_def).collect()) . } . AstFragmentKind::Variants => { . AstFragment::Variants(items.map(Annotatable::expect_variant).collect()) . } . AstFragmentKind::Items => { 380 ( 0.00%) AstFragment::Items(items.map(Annotatable::expect_item).collect()) . } . AstFragmentKind::ImplItems => { . AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect()) . } . AstFragmentKind::TraitItems => { . AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect()) . } . AstFragmentKind::ForeignItems => { -- line 280 ---------------------------------------- -- line 291 ---------------------------------------- . } . AstFragmentKind::Crate => { . AstFragment::Crate(items.next().expect("expected exactly one crate").expect_crate()) . } . AstFragmentKind::Pat | AstFragmentKind::Ty => { . panic!("patterns and types aren't annotatable") . } . } 228 ( 0.00%) } . } . . pub struct Invocation { . pub kind: InvocationKind, . pub fragment_kind: AstFragmentKind, . pub expansion_data: ExpansionData, . } . -- line 307 ---------------------------------------- -- line 326 ---------------------------------------- . . impl InvocationKind { . fn placeholder_visibility(&self) -> Option { . // HACK: For unnamed fields placeholders should have the same visibility as the actual . // fields because for tuple structs/variants resolve determines visibilities of their . // constructor using these field visibilities before attributes on them are are expanded. . // The assumption is that the attribute expansion cannot change field visibilities, . // and it holds because only inert attributes are supported in this position. 450 ( 0.00%) match self { . InvocationKind::Attr { item: Annotatable::FieldDef(field), .. } . | InvocationKind::Derive { item: Annotatable::FieldDef(field), .. } . if field.ident.is_none() => . { . Some(field.vis.clone()) . } 90 ( 0.00%) _ => None, . } . } . } . . impl Invocation { . pub fn span(&self) -> Span { 1,326 ( 0.00%) match &self.kind { 70 ( 0.00%) InvocationKind::Bang { span, .. } => *span, 20 ( 0.00%) InvocationKind::Attr { attr, .. } => attr.span, 56 ( 0.00%) InvocationKind::Derive { path, .. } => path.span, . } 146 ( 0.00%) } . } . . pub struct MacroExpander<'a, 'b> { . pub cx: &'a mut ExtCtxt<'b>, . monotonic: bool, // cf. `cx.monotonic_expander()` . } . . impl<'a, 'b> MacroExpander<'a, 'b> { . pub fn new(cx: &'a mut ExtCtxt<'b>, monotonic: bool) -> Self { . MacroExpander { cx, monotonic } . } . 10 ( 0.00%) pub fn expand_crate(&mut self, krate: ast::Crate) -> ast::Crate { 6 ( 0.00%) let file_path = match self.cx.source_map().span_to_filename(krate.span) { 11 ( 0.00%) FileName::Real(name) => name . .into_local_path() . .expect("attempting to resolve a file path in an external file"), . other => PathBuf::from(other.prefer_local().to_string()), . }; 4 ( 0.00%) let dir_path = file_path.parent().unwrap_or(&file_path).to_owned(); 3 ( 0.00%) self.cx.root_path = dir_path.clone(); 1 ( 0.00%) self.cx.current_expansion.module = Rc::new(ModuleData { 3 ( 0.00%) mod_path: vec![Ident::from_str(&self.cx.ecfg.crate_name)], 4 ( 0.00%) file_path_stack: vec![file_path], . dir_path, . }); 13 ( 0.00%) let krate = self.fully_expand_fragment(AstFragment::Crate(krate)).make_crate(); 1 ( 0.00%) assert_eq!(krate.id, ast::CRATE_NODE_ID); 2 ( 0.00%) self.cx.trace_macros_diag(); . krate 9 ( 0.00%) } . . // Recursively expand all macro invocations in this AST fragment. 162 ( 0.00%) pub fn fully_expand_fragment(&mut self, input_fragment: AstFragment) -> AstFragment { 18 ( 0.00%) let orig_expansion_data = self.cx.current_expansion.clone(); 54 ( 0.00%) let orig_force_mode = self.cx.force_mode; . . // Collect all macro invocations and replace them with placeholders. 144 ( 0.00%) let (mut fragment_with_placeholders, mut invocations) = 180 ( 0.00%) self.collect_invocations(input_fragment, &[]); . . // Optimization: if we resolve all imports now, . // we'll be able to immediately resolve most of imported macros. . self.resolve_imports(); . . // Resolve paths in all invocations and produce output expanded fragments for them, but . // do not insert them into our input AST fragment yet, only store in `expanded_fragments`. . // The output fragments also go through expansion recursively until no invocations are left. . // Unresolved macros produce dummy outputs as a recovery measure. . invocations.reverse(); . let mut expanded_fragments = Vec::new(); . let mut undetermined_invocations = Vec::new(); 108 ( 0.00%) let (mut progress, mut force) = (false, !self.monotonic); . loop { 1,022 ( 0.00%) let Some((invoc, ext)) = invocations.pop() else { . self.resolve_imports(); 18 ( 0.00%) if undetermined_invocations.is_empty() { . break; . } . invocations = mem::take(&mut undetermined_invocations); . force = !mem::replace(&mut progress, false); . if force && self.monotonic { . self.cx.sess.delay_span_bug( . invocations.last().unwrap().0.span(), . "expansion entered force mode without producing any errors", . ); . } . continue; . }; . 292 ( 0.00%) let ext = match ext { . Some(ext) => ext, . None => { 438 ( 0.00%) let eager_expansion_root = if self.monotonic { . invoc.expansion_data.id . } else { . orig_expansion_data.id . }; 1,314 ( 0.00%) match self.cx.resolver.resolve_macro_invocation( . &invoc, . eager_expansion_root, . force, . ) { . Ok(ext) => ext, . Err(Indeterminate) => { . // Cannot resolve, will retry this invocation later. . undetermined_invocations.push((invoc, None)); . continue; . } . } . } . }; . 146 ( 0.00%) let ExpansionData { depth, id: expn_id, .. } = invoc.expansion_data; 438 ( 0.00%) let depth = depth - orig_expansion_data.depth; 2,482 ( 0.00%) self.cx.current_expansion = invoc.expansion_data.clone(); 146 ( 0.00%) self.cx.force_mode = force; . 292 ( 0.00%) let fragment_kind = invoc.fragment_kind; 2,336 ( 0.00%) let (expanded_fragment, new_invocations) = match self.expand_invoc(invoc, &ext.kind) { 2,774 ( 0.00%) ExpandResult::Ready(fragment) => { . let mut derive_invocations = Vec::new(); 730 ( 0.00%) let derive_placeholders = self . .cx . .resolver . .take_derive_resolutions(expn_id) . .map(|derives| { . derive_invocations.reserve(derives.len()); . derives . .into_iter() 1,792 ( 0.00%) .map(|(path, item, _exts)| { . // FIXME: Consider using the derive resolutions (`_exts`) . // instead of enqueuing the derives to be resolved again later. 56 ( 0.00%) let expn_id = LocalExpnId::fresh_empty(); 672 ( 0.00%) derive_invocations.push(( 1,288 ( 0.00%) Invocation { 1,232 ( 0.00%) kind: InvocationKind::Derive { path, item }, . fragment_kind, . expansion_data: ExpansionData { . id: expn_id, 56 ( 0.00%) ..self.cx.current_expansion.clone() . }, . }, . None, . )); 112 ( 0.00%) NodeId::placeholder_from_expn_id(expn_id) 448 ( 0.00%) }) . .collect::>() . }) . .unwrap_or_default(); . 1,022 ( 0.00%) let (fragment, collected_invocations) = 1,898 ( 0.00%) self.collect_invocations(fragment, &derive_placeholders); . // We choose to expand any derive invocations associated with this macro invocation . // *before* any macro invocations collected from the output fragment . derive_invocations.extend(collected_invocations); 1,314 ( 0.00%) (fragment, derive_invocations) . } . ExpandResult::Retry(invoc) => { . if force { . self.cx.span_bug( . invoc.span(), . "expansion entered force mode but is still stuck", . ); . } else { -- line 498 ---------------------------------------- -- line 499 ---------------------------------------- . // Cannot expand, will retry this invocation later. . undetermined_invocations.push((invoc, Some(ext))); . continue; . } . } . }; . . progress = true; 438 ( 0.00%) if expanded_fragments.len() < depth { . expanded_fragments.push(Vec::new()); . } 1,022 ( 0.00%) expanded_fragments[depth - 1].push((expn_id, expanded_fragment)); . invocations.extend(new_invocations.into_iter().rev()); . } . 414 ( 0.00%) self.cx.current_expansion = orig_expansion_data; 18 ( 0.00%) self.cx.force_mode = orig_force_mode; . . // Finally incorporate all the expanded macros into the input AST fragment. . let mut placeholder_expander = PlaceholderExpander::default(); 8 ( 0.00%) while let Some(expanded_fragments) = expanded_fragments.pop() { 2,798 ( 0.00%) for (expn_id, expanded_fragment) in expanded_fragments.into_iter().rev() { . placeholder_expander 730 ( 0.00%) .add(NodeId::placeholder_from_expn_id(expn_id), expanded_fragment); . } . } 18 ( 0.00%) fragment_with_placeholders.mut_visit_with(&mut placeholder_expander); . fragment_with_placeholders 144 ( 0.00%) } . . fn resolve_imports(&mut self) { 126 ( 0.00%) if self.monotonic { 8 ( 0.00%) self.cx.resolver.resolve_imports(); . } . } . . /// Collects all macro invocations reachable at this time in this AST fragment, and replace . /// them with "placeholders" - dummy macro invocations with specially crafted `NodeId`s. . /// Then call into resolver that builds a skeleton ("reduced graph") of the fragment and . /// prepares data for resolving paths of macro invocations. 1,968 ( 0.00%) fn collect_invocations( . &mut self, . mut fragment: AstFragment, . extra_placeholders: &[NodeId], . ) -> (AstFragment, Vec<(Invocation, Option>)>) { . // Resolve `$crate`s in the fragment for pretty-printing. 656 ( 0.00%) self.cx.resolver.resolve_dollar_crates(); . . let mut invocations = { 984 ( 0.00%) let mut collector = InvocationCollector { . // Non-derive macro invocations cannot see the results of cfg expansion - they . // will either be removed along with the item, or invoked before the cfg/cfg_attr . // attribute is expanded. Therefore, we don't need to configure the tokens . // Derive macros *can* see the results of cfg-expansion - they are handled . // specially in `fully_expand_fragment` . cfg: StripUnconfigured { 164 ( 0.00%) sess: &self.cx.sess, 164 ( 0.00%) features: self.cx.ecfg.features, . config_tokens: false, . }, . cx: self.cx, . invocations: Vec::new(), 164 ( 0.00%) monotonic: self.monotonic, . }; . fragment.mut_visit_with(&mut collector); 656 ( 0.00%) fragment.add_placeholders(extra_placeholders); 656 ( 0.00%) collector.invocations . }; . 328 ( 0.00%) if self.monotonic { 441 ( 0.00%) self.cx . .resolver 294 ( 0.00%) .visit_ast_fragment_with_placeholders(self.cx.current_expansion.id, &fragment); . 441 ( 0.00%) if self.cx.sess.opts.debugging_opts.incremental_relative_spans { . for (invoc, _) in invocations.iter_mut() { . let expn_id = invoc.expansion_data.id; . let parent_def = self.cx.resolver.invocation_parent(expn_id); . let span = match &mut invoc.kind { . InvocationKind::Bang { ref mut span, .. } => span, . InvocationKind::Attr { attr, .. } => &mut attr.span, . InvocationKind::Derive { path, .. } => &mut path.span, . }; . *span = span.with_parent(Some(parent_def)); . } . } . } . 1,476 ( 0.00%) (fragment, invocations) 1,312 ( 0.00%) } . . fn error_recursion_limit_reached(&mut self) { . let expn_data = self.cx.current_expansion.id.expn_data(); . let suggested_limit = match self.cx.ecfg.recursion_limit { . Limit(0) => Limit(2), . limit => limit * 2, . }; . self.cx -- line 596 ---------------------------------------- -- line 620 ---------------------------------------- . } . . fn expand_invoc( . &mut self, . invoc: Invocation, . ext: &SyntaxExtensionKind, . ) -> ExpandResult { . let recursion_limit = 146 ( 0.00%) self.cx.reduced_recursion_limit.unwrap_or(self.cx.ecfg.recursion_limit); 146 ( 0.00%) if !recursion_limit.value_within_limit(self.cx.current_expansion.depth) { . if self.cx.reduced_recursion_limit.is_none() { . self.error_recursion_limit_reached(); . } . . // Reduce the recursion limit by half each time it triggers. . self.cx.reduced_recursion_limit = Some(recursion_limit / 2); . . return ExpandResult::Ready(invoc.fragment_kind.dummy(invoc.span())); . } . 292 ( 0.00%) let (fragment_kind, span) = (invoc.fragment_kind, invoc.span()); 3,066 ( 0.00%) ExpandResult::Ready(match invoc.kind { 910 ( 0.00%) InvocationKind::Bang { mac, .. } => match ext { . SyntaxExtensionKind::Bang(expander) => { . let tok_result = match expander.expand(self.cx, span, mac.args.inner_tokens()) { . Err(_) => return ExpandResult::Ready(fragment_kind.dummy(span)), . Ok(ts) => ts, . }; . self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span) . } . SyntaxExtensionKind::LegacyBang(expander) => { 350 ( 0.00%) let prev = self.cx.current_expansion.prior_type_ascription; 280 ( 0.00%) self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription; 560 ( 0.00%) let tok_result = expander.expand(self.cx, span, mac.args.inner_tokens()); 1,120 ( 0.00%) let result = if let Some(result) = fragment_kind.make_from(tok_result) { . result . } else { . self.error_wrong_fragment_kind(fragment_kind, &mac, span); . fragment_kind.dummy(span) . }; 280 ( 0.00%) self.cx.current_expansion.prior_type_ascription = prev; 280 ( 0.00%) result . } . _ => unreachable!(), 210 ( 0.00%) }, 920 ( 0.00%) InvocationKind::Attr { attr, pos, mut item, derives } => match ext { . SyntaxExtensionKind::Attr(expander) => { . self.gate_proc_macro_input(&item); . self.gate_proc_macro_attr_item(span, &item); . let tokens = match &item { . // FIXME: Collect tokens and use them instead of generating . // fake ones. These are unstable, so it needs to be . // fixed prior to stabilization . // Fake tokens when we are invoking an inner attribute, and -- line 673 ---------------------------------------- -- line 700 ---------------------------------------- . let inner_tokens = attr_item.args.inner_tokens(); . let tok_result = match expander.expand(self.cx, span, inner_tokens, tokens) { . Err(_) => return ExpandResult::Ready(fragment_kind.dummy(span)), . Ok(ts) => ts, . }; . self.parse_ast_fragment(tok_result, fragment_kind, &attr_item.path, span) . } . SyntaxExtensionKind::LegacyAttr(expander) => { 180 ( 0.00%) match validate_attr::parse_meta(&self.cx.sess.parse_sess, &attr) { 280 ( 0.00%) Ok(meta) => { 560 ( 0.00%) let items = match expander.expand(self.cx, span, &meta, item) { 100 ( 0.00%) ExpandResult::Ready(items) => items, . ExpandResult::Retry(item) => { . // Reassemble the original invocation for retrying. . return ExpandResult::Retry(Invocation { . kind: InvocationKind::Attr { attr, pos, item, derives }, . ..invoc . }); . } . }; 20 ( 0.00%) if fragment_kind == AstFragmentKind::Expr && items.is_empty() { . let msg = . "removing an expression is not supported in this position"; . self.cx.span_err(span, msg); . fragment_kind.dummy(span) . } else { 160 ( 0.00%) fragment_kind.expect_from_annotatables(items) . } 40 ( 0.00%) } . Err(mut err) => { . err.emit(); . fragment_kind.dummy(span) . } . } . } . SyntaxExtensionKind::NonMacroAttr => { . self.cx.expanded_inert_attrs.mark(&attr); . item.visit_attrs(|attrs| attrs.insert(pos, attr)); . fragment_kind.expect_from_annotatables(iter::once(item)) . } . _ => unreachable!(), 80 ( 0.00%) }, 1,512 ( 0.00%) InvocationKind::Derive { path, item } => match ext { . SyntaxExtensionKind::Derive(expander) . | SyntaxExtensionKind::LegacyDerive(expander) => { 112 ( 0.00%) if let SyntaxExtensionKind::Derive(..) = ext { . self.gate_proc_macro_input(&item); . } 448 ( 0.00%) let meta = ast::MetaItem { kind: MetaItemKind::Word, span, path }; 1,568 ( 0.00%) let items = match expander.expand(self.cx, span, &meta, item) { 224 ( 0.00%) ExpandResult::Ready(items) => items, . ExpandResult::Retry(item) => { . // Reassemble the original invocation for retrying. . return ExpandResult::Retry(Invocation { . kind: InvocationKind::Derive { path: meta.path, item }, . ..invoc . }); . } . }; 336 ( 0.00%) fragment_kind.expect_from_annotatables(items) 168 ( 0.00%) } . _ => unreachable!(), . }, . }) . } . . fn gate_proc_macro_attr_item(&self, span: Span, item: &Annotatable) { . let kind = match item { . Annotatable::Item(_) -- line 768 ---------------------------------------- -- line 852 ---------------------------------------- . err.emit(); . self.cx.trace_macros_diag(); . kind.dummy(span) . } . } . } . } . 387 ( 0.00%) pub fn parse_ast_fragment<'a>( . this: &mut Parser<'a>, . kind: AstFragmentKind, . ) -> PResult<'a, AstFragment> { 1,118 ( 0.00%) Ok(match kind { . AstFragmentKind::Items => { . let mut items = SmallVec::new(); 465 ( 0.00%) while let Some(item) = this.parse_item(ForceCollect::No)? { . items.push(item); . } 5 ( 0.00%) AstFragment::Items(items) . } . AstFragmentKind::TraitItems => { . let mut items = SmallVec::new(); . while let Some(item) = this.parse_trait_item(ForceCollect::No)? { . items.extend(item); . } . AstFragment::TraitItems(items) . } -- line 878 ---------------------------------------- -- line 888 ---------------------------------------- . while let Some(item) = this.parse_foreign_item(ForceCollect::No)? { . items.extend(item); . } . AstFragment::ForeignItems(items) . } . AstFragmentKind::Stmts => { . let mut stmts = SmallVec::new(); . // Won't make progress on a `}`. 12 ( 0.00%) while this.token != token::Eof && this.token != token::CloseDelim(token::Brace) { 12 ( 0.00%) if let Some(stmt) = this.parse_full_stmt(AttemptLocalParseRecovery::Yes)? { 10 ( 0.00%) stmts.push(stmt); . } . } 16 ( 0.00%) AstFragment::Stmts(stmts) . } 40 ( 0.00%) AstFragmentKind::Expr => AstFragment::Expr(this.parse_expr()?), . AstFragmentKind::OptExpr => { . if this.token != token::Eof { . AstFragment::OptExpr(Some(this.parse_expr()?)) . } else { . AstFragment::OptExpr(None) . } . } . AstFragmentKind::Ty => AstFragment::Ty(this.parse_ty()?), -- line 911 ---------------------------------------- -- line 918 ---------------------------------------- . AstFragmentKind::Arms . | AstFragmentKind::ExprFields . | AstFragmentKind::PatFields . | AstFragmentKind::GenericParams . | AstFragmentKind::Params . | AstFragmentKind::FieldDefs . | AstFragmentKind::Variants => panic!("unexpected AST fragment kind"), . }) 387 ( 0.00%) } . 516 ( 0.00%) pub fn ensure_complete_parse<'a>( . this: &mut Parser<'a>, . macro_path: &ast::Path, . kind_name: &str, . span: Span, . ) { 129 ( 0.00%) if this.token != token::Eof { . let token = pprust::token_to_string(&this.token); . let msg = format!("macro expansion ignores token `{}` and any following", token); . // Avoid emitting backtrace info twice. . let def_site_span = this.token.span.with_ctxt(SyntaxContext::root()); . let mut err = this.struct_span_err(def_site_span, &msg); . err.span_label(span, "caused by the macro expansion here"); . let msg = format!( . "the usage of `{}!` is likely invalid in {} context", -- line 942 ---------------------------------------- -- line 955 ---------------------------------------- . ";".to_owned(), . Applicability::MaybeIncorrect, . ); . } . _ => {} . } . err.emit(); . } 344 ( 0.00%) } . . /// Wraps a call to `noop_visit_*` / `noop_flat_map_*` . /// for an AST node that supports attributes . /// (see the `Annotatable` enum) . /// This method assigns a `NodeId`, and sets that `NodeId` . /// as our current 'lint node id'. If a macro call is found . /// inside this AST node, we will use this AST node's `NodeId` . /// to emit lints associated with that macro (allowing -- line 971 ---------------------------------------- -- line 1031 ---------------------------------------- . fn pre_flat_map_node_collect_attr(_cfg: &StripUnconfigured<'_>, _attr: &ast::Attribute) {} . fn post_flat_map_node_collect_bang(_output: &mut Self::OutputTy, _add_semicolon: AddSemicolon) { . } . fn wrap_flat_map_node_noop_flat_map( . node: Self, . collector: &mut InvocationCollector<'_, '_>, . noop_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy, . ) -> Result { 19,805 ( 0.00%) Ok(noop_flat_map(node, collector)) . } . } . . impl InvocationCollectorNode for P { . const KIND: AstFragmentKind = AstFragmentKind::Items; . fn to_annotatable(self) -> Annotatable { . Annotatable::Item(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { 62 ( 0.00%) fragment.make_items() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 1,338 ( 0.00%) noop_flat_map_item(self, visitor) . } . fn is_mac_call(&self) -> bool { 451 ( 0.00%) matches!(self.kind, ItemKind::MacCall(..)) . } 6 ( 0.00%) fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.into_inner(); 2 ( 0.00%) match node.kind { 13 ( 0.00%) ItemKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No), . _ => unreachable!(), . } 5 ( 0.00%) } 4,950 ( 0.00%) fn wrap_flat_map_node_noop_flat_map( . mut node: Self, . collector: &mut InvocationCollector<'_, '_>, . noop_flat_map: impl FnOnce(Self, &mut InvocationCollector<'_, '_>) -> Self::OutputTy, . ) -> Result { 900 ( 0.00%) if !matches!(node.kind, ItemKind::Mod(..)) { 2,568 ( 0.00%) return Ok(noop_flat_map(node, collector)); . } . . // Work around borrow checker not seeing through `P`'s deref. 242 ( 0.00%) let (ident, span, mut attrs) = (node.ident, node.span, mem::take(&mut node.attrs)); . let ItemKind::Mod(_, mod_kind) = &mut node.kind else { . unreachable!() . }; . . let ecx = &mut collector.cx; 44 ( 0.00%) let (file_path, dir_path, dir_ownership) = match mod_kind { . ModKind::Loaded(_, inline, _) => { . // Inline `mod foo { ... }`, but we still need to push directories. 56 ( 0.00%) let (dir_path, dir_ownership) = mod_dir_path( 8 ( 0.00%) &ecx.sess, 8 ( 0.00%) ident, . &attrs, 4 ( 0.00%) &ecx.current_expansion.module, 4 ( 0.00%) ecx.current_expansion.dir_ownership, 8 ( 0.00%) *inline, . ); 44 ( 0.00%) node.attrs = attrs; . (None, dir_path, dir_ownership) . } . ModKind::Unloaded => { . // We have an outline `mod foo;` so we need to parse the file. 36 ( 0.00%) let old_attrs_len = attrs.len(); 342 ( 0.00%) let ParsedExternalMod { items, inner_span, file_path, dir_path, dir_ownership } = 144 ( 0.00%) parse_external_mod( 36 ( 0.00%) &ecx.sess, 36 ( 0.00%) ident, . span, 18 ( 0.00%) &ecx.current_expansion.module, 18 ( 0.00%) ecx.current_expansion.dir_ownership, . &mut attrs, . ); . 90 ( 0.00%) if let Some(lint_store) = ecx.lint_store { 234 ( 0.00%) lint_store.pre_expansion_lint( 36 ( 0.00%) ecx.sess, 72 ( 0.00%) ecx.resolver.registered_tools(), 36 ( 0.00%) ecx.current_expansion.lint_node_id, . &attrs, . &items, 18 ( 0.00%) ident.name.as_str(), . ); . } . 216 ( 0.00%) *mod_kind = ModKind::Loaded(items, Inline::No, inner_span); 162 ( 0.00%) node.attrs = attrs; 36 ( 0.00%) if node.attrs.len() > old_attrs_len { . // If we loaded an out-of-line module and added some inner attributes, . // then we need to re-configure it and re-collect attributes for . // resolution and expansion. 12 ( 0.00%) return Err(node); . } . (Some(file_path), dir_path, dir_ownership) . } . }; . . // Set the module info before we flat map. 126 ( 0.00%) let mut module = ecx.current_expansion.module.with_dir_path(dir_path); 36 ( 0.00%) module.mod_path.push(ident); 36 ( 0.00%) if let Some(file_path) = file_path { . module.file_path_stack.push(file_path); . } . 36 ( 0.00%) let orig_module = mem::replace(&mut ecx.current_expansion.module, Rc::new(module)); . let orig_dir_ownership = 18 ( 0.00%) mem::replace(&mut ecx.current_expansion.dir_ownership, dir_ownership); . 90 ( 0.00%) let res = Ok(noop_flat_map(node, collector)); . 54 ( 0.00%) collector.cx.current_expansion.dir_ownership = orig_dir_ownership; 72 ( 0.00%) collector.cx.current_expansion.module = orig_module; 72 ( 0.00%) res 4,050 ( 0.00%) } . } . . struct TraitItemTag; . impl InvocationCollectorNode for AstLikeWrapper, TraitItemTag> { . type OutputTy = SmallVec<[P; 1]>; . const KIND: AstFragmentKind = AstFragmentKind::TraitItems; . fn to_annotatable(self) -> Annotatable { . Annotatable::TraitItem(self.wrapped) -- line 1157 ---------------------------------------- -- line 1158 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_trait_items() . } . fn id(&mut self) -> &mut NodeId { . &mut self.wrapped.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 2 ( 0.00%) noop_flat_map_assoc_item(self.wrapped, visitor) . } . fn is_mac_call(&self) -> bool { 1 ( 0.00%) matches!(self.wrapped.kind, AssocItemKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let item = self.wrapped.into_inner(); . match item.kind { . AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No), . _ => unreachable!(), . } . } -- line 1177 ---------------------------------------- -- line 1186 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_impl_items() . } . fn id(&mut self) -> &mut NodeId { . &mut self.wrapped.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 394 ( 0.00%) noop_flat_map_assoc_item(self.wrapped, visitor) . } . fn is_mac_call(&self) -> bool { 197 ( 0.00%) matches!(self.wrapped.kind, AssocItemKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let item = self.wrapped.into_inner(); . match item.kind { . AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No), . _ => unreachable!(), . } . } -- line 1205 ---------------------------------------- -- line 1238 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_variants() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 550 ( 0.00%) noop_flat_map_variant(self, visitor) . } . } . . impl InvocationCollectorNode for ast::FieldDef { . const KIND: AstFragmentKind = AstFragmentKind::FieldDefs; . fn to_annotatable(self) -> Annotatable { . Annotatable::FieldDef(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_field_defs() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 1,178 ( 0.00%) noop_flat_map_field_def(self, visitor) . } . } . . impl InvocationCollectorNode for ast::PatField { . const KIND: AstFragmentKind = AstFragmentKind::PatFields; . fn to_annotatable(self) -> Annotatable { . Annotatable::PatField(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_pat_fields() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 2,280 ( 0.00%) noop_flat_map_pat_field(self, visitor) . } . } . . impl InvocationCollectorNode for ast::ExprField { . const KIND: AstFragmentKind = AstFragmentKind::ExprFields; . fn to_annotatable(self) -> Annotatable { . Annotatable::ExprField(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_expr_fields() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 14,010 ( 0.00%) noop_flat_map_expr_field(self, visitor) . } . } . . impl InvocationCollectorNode for ast::Param { . const KIND: AstFragmentKind = AstFragmentKind::Params; . fn to_annotatable(self) -> Annotatable { . Annotatable::Param(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_params() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 6,660 ( 0.00%) noop_flat_map_param(self, visitor) . } . } . . impl InvocationCollectorNode for ast::GenericParam { . const KIND: AstFragmentKind = AstFragmentKind::GenericParams; . fn to_annotatable(self) -> Annotatable { . Annotatable::GenericParam(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_generic_params() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 3,780 ( 0.00%) noop_flat_map_generic_param(self, visitor) . } . } . . impl InvocationCollectorNode for ast::Arm { . const KIND: AstFragmentKind = AstFragmentKind::Arms; . fn to_annotatable(self) -> Annotatable { . Annotatable::Arm(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_arms() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 2,490 ( 0.00%) noop_flat_map_arm(self, visitor) . } . } . . impl InvocationCollectorNode for ast::Stmt { . type AttrsTy = ast::AttrVec; . const KIND: AstFragmentKind = AstFragmentKind::Stmts; . fn to_annotatable(self) -> Annotatable { . Annotatable::Stmt(P(self)) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { 12 ( 0.00%) fragment.make_stmts() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_flat_map(self, visitor: &mut V) -> Self::OutputTy { 4,284 ( 0.00%) noop_flat_map_stmt(self, visitor) . } . fn is_mac_call(&self) -> bool { 2,178 ( 0.00%) match &self.kind { . StmtKind::MacCall(..) => true, 1 ( 0.00%) StmtKind::Item(item) => matches!(item.kind, ItemKind::MacCall(..)), 134 ( 0.00%) StmtKind::Semi(expr) => matches!(expr.kind, ExprKind::MacCall(..)), . StmtKind::Expr(..) => unreachable!(), . StmtKind::Local(..) | StmtKind::Empty => false, . } . } 54 ( 0.00%) fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . // We pull macro invocations (both attributes and fn-like macro calls) out of their . // `StmtKind`s and treat them as statement macro invocations, not as items or expressions. 90 ( 0.00%) let (add_semicolon, mac, attrs) = match self.kind { 6 ( 0.00%) StmtKind::MacCall(mac) => { 66 ( 0.00%) let ast::MacCallStmt { mac, style, attrs, .. } = mac.into_inner(); 54 ( 0.00%) (style == MacStmtStyle::Semicolon, mac, attrs) . } . StmtKind::Item(item) => match item.into_inner() { . ast::Item { kind: ItemKind::MacCall(mac), attrs, .. } => { . (mac.args.need_semicolon(), mac, attrs.into()) . } . _ => unreachable!(), . }, . StmtKind::Semi(expr) => match expr.into_inner() { . ast::Expr { kind: ExprKind::MacCall(mac), attrs, .. } => { . (mac.args.need_semicolon(), mac, attrs) . } . _ => unreachable!(), . }, . _ => unreachable!(), . }; 18 ( 0.00%) (mac, attrs, if add_semicolon { AddSemicolon::Yes } else { AddSemicolon::No }) 54 ( 0.00%) } 30 ( 0.00%) fn post_flat_map_node_collect_bang(stmts: &mut Self::OutputTy, add_semicolon: AddSemicolon) { . // If this is a macro invocation with a semicolon, then apply that . // semicolon to the final statement produced by expansion. 12 ( 0.00%) if matches!(add_semicolon, AddSemicolon::Yes) { 6 ( 0.00%) if let Some(stmt) = stmts.pop() { 42 ( 0.00%) stmts.push(stmt.add_trailing_semicolon()); . } . } 36 ( 0.00%) } . } . . impl InvocationCollectorNode for ast::Crate { . type OutputTy = ast::Crate; . const KIND: AstFragmentKind = AstFragmentKind::Crate; . fn to_annotatable(self) -> Annotatable { . Annotatable::Crate(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_crate() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_visit(&mut self, visitor: &mut V) { 3 ( 0.00%) noop_visit_crate(self, visitor) . } . } . . impl InvocationCollectorNode for P { . type OutputTy = P; . const KIND: AstFragmentKind = AstFragmentKind::Ty; . fn to_annotatable(self) -> Annotatable { . unreachable!() -- line 1426 ---------------------------------------- -- line 1427 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_ty() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_visit(&mut self, visitor: &mut V) { 3,630 ( 0.00%) noop_visit_ty(self, visitor) . } . fn is_mac_call(&self) -> bool { 1,815 ( 0.00%) matches!(self.kind, ast::TyKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.into_inner(); . match node.kind { . TyKind::MacCall(mac) => (mac, Vec::new(), AddSemicolon::No), . _ => unreachable!(), . } . } -- line 1446 ---------------------------------------- -- line 1454 ---------------------------------------- . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { . fragment.make_pat() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn noop_visit(&mut self, visitor: &mut V) { 2,600 ( 0.00%) noop_visit_pat(self, visitor) . } . fn is_mac_call(&self) -> bool { 1,300 ( 0.00%) matches!(self.kind, PatKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.into_inner(); . match node.kind { . PatKind::MacCall(mac) => (mac, Vec::new(), AddSemicolon::No), . _ => unreachable!(), . } . } -- line 1473 ---------------------------------------- -- line 1476 ---------------------------------------- . impl InvocationCollectorNode for P { . type OutputTy = P; . type AttrsTy = ast::AttrVec; . const KIND: AstFragmentKind = AstFragmentKind::Expr; . fn to_annotatable(self) -> Annotatable { . Annotatable::Expr(self) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { 60 ( 0.00%) fragment.make_expr() . } . fn id(&mut self) -> &mut NodeId { . &mut self.id . } . fn descr() -> &'static str { . "an expression" . } . fn noop_visit(&mut self, visitor: &mut V) { 13,704 ( 0.00%) noop_visit_expr(self, visitor) . } . fn is_mac_call(&self) -> bool { 4,598 ( 0.00%) matches!(self.kind, ExprKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.into_inner(); 60 ( 0.00%) match node.kind { 270 ( 0.00%) ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No), . _ => unreachable!(), . } . } . } . . struct OptExprTag; . impl InvocationCollectorNode for AstLikeWrapper, OptExprTag> { . type OutputTy = Option>; . type AttrsTy = ast::AttrVec; . const KIND: AstFragmentKind = AstFragmentKind::OptExpr; . fn to_annotatable(self) -> Annotatable { . Annotatable::Expr(self.wrapped) . } . fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy { 66 ( 0.00%) fragment.make_opt_expr() . } . fn id(&mut self) -> &mut NodeId { . &mut self.wrapped.id . } . fn noop_flat_map(mut self, visitor: &mut V) -> Self::OutputTy { 281,104 ( 0.01%) noop_visit_expr(&mut self.wrapped, visitor); . Some(self.wrapped) . } . fn is_mac_call(&self) -> bool { 281,170 ( 0.01%) matches!(self.wrapped.kind, ast::ExprKind::MacCall(..)) . } . fn take_mac_call(self) -> (ast::MacCall, Self::AttrsTy, AddSemicolon) { . let node = self.wrapped.into_inner(); 66 ( 0.00%) match node.kind { 297 ( 0.00%) ExprKind::MacCall(mac) => (mac, node.attrs, AddSemicolon::No), . _ => unreachable!(), . } . } . fn pre_flat_map_node_collect_attr(cfg: &StripUnconfigured<'_>, attr: &ast::Attribute) { . cfg.maybe_emit_expr_attr_err(&attr); . } . } . -- line 1539 ---------------------------------------- -- line 1540 ---------------------------------------- . struct InvocationCollector<'a, 'b> { . cx: &'a mut ExtCtxt<'b>, . cfg: StripUnconfigured<'a>, . invocations: Vec<(Invocation, Option>)>, . monotonic: bool, . } . . impl<'a, 'b> InvocationCollector<'a, 'b> { 990 ( 0.00%) fn collect(&mut self, fragment_kind: AstFragmentKind, kind: InvocationKind) -> AstFragment { 180 ( 0.00%) let expn_id = LocalExpnId::fresh_empty(); . let vis = kind.placeholder_visibility(); 1,530 ( 0.00%) self.invocations.push(( 180 ( 0.00%) Invocation { 270 ( 0.00%) kind, . fragment_kind, . expansion_data: ExpansionData { . id: expn_id, 360 ( 0.00%) depth: self.cx.current_expansion.depth + 1, . ..self.cx.current_expansion.clone() . }, . }, . None, . )); 990 ( 0.00%) placeholder(fragment_kind, NodeId::placeholder_from_expn_id(expn_id), vis) 720 ( 0.00%) } . . fn collect_bang(&mut self, mac: ast::MacCall, kind: AstFragmentKind) -> AstFragment { . // cache the macro call span so that it can be . // easily adjusted for incremental compilation 70 ( 0.00%) let span = mac.span(); 1,050 ( 0.00%) self.collect(kind, InvocationKind::Bang { mac, span }) . } . . fn collect_attr( . &mut self, . (attr, pos, derives): (ast::Attribute, usize, Vec), . item: Annotatable, . kind: AstFragmentKind, . ) -> AstFragment { 620 ( 0.00%) self.collect(kind, InvocationKind::Attr { attr, pos, item, derives }) . } . . /// If `item` is an attribute invocation, remove the attribute and return it together with . /// its position and derives following it. We have to collect the derives in order to resolve . /// legacy derive helpers (helpers written before derives that introduce them). . fn take_first_attr( . &self, . item: &mut impl AstLike, . ) -> Option<(ast::Attribute, usize, Vec)> { 148,194 ( 0.00%) let mut attr = None; . 148,194 ( 0.00%) let mut cfg_pos = None; 294,064 ( 0.01%) let mut attr_pos = None; 4,648 ( 0.00%) for (pos, attr) in item.attrs().iter().enumerate() { 8,671 ( 0.00%) if !attr.is_doc_comment() && !self.cx.expanded_inert_attrs.is_marked(attr) { 566 ( 0.00%) let name = attr.ident().map(|ident| ident.name); 1,132 ( 0.00%) if name == Some(sym::cfg) || name == Some(sym::cfg_attr) { 36 ( 0.00%) cfg_pos = Some(pos); // a cfg attr found, no need to search anymore . break; 795 ( 0.00%) } else if attr_pos.is_none() . && !name.map_or(false, rustc_feature::is_builtin_attr_name) . { 60 ( 0.00%) attr_pos = Some(pos); // a non-cfg attr found, still may find a cfg attr . } . } . } . . item.visit_attrs(|attrs| { 594,298 ( 0.01%) attr = Some(match (cfg_pos, attr_pos) { 306 ( 0.00%) (Some(pos), _) => (attrs.remove(pos), pos, Vec::new()), . (_, Some(pos)) => { . let attr = attrs.remove(pos); . let following_derives = attrs[pos..] . .iter() . .filter(|a| a.has_name(sym::derive)) . .flat_map(|a| a.meta_item_list().unwrap_or_default()) . .filter_map(|nested_meta| match nested_meta { . NestedMetaItem::MetaItem(ast::MetaItem { -- line 1617 ---------------------------------------- -- line 1618 ---------------------------------------- . kind: MetaItemKind::Word, . path, . .. . }) => Some(path), . _ => None, . }) . .collect(); . 360 ( 0.00%) (attr, pos, following_derives) . } . _ => return, . }); . }); . . attr . } . . // Detect use of feature-gated or invalid attributes on macro invocations . // since they will not be detected after macro expansion. 490 ( 0.00%) fn check_attributes(&self, attrs: &[ast::Attribute], call: &ast::MacCall) { 210 ( 0.00%) let features = self.cx.ecfg.features.unwrap(); . let mut attrs = attrs.iter().peekable(); . let mut span: Option = None; . while let Some(attr) = attrs.next() { . rustc_ast_passes::feature_gate::check_attribute(attr, self.cx.sess, features); . validate_attr::check_meta(&self.cx.sess.parse_sess, attr); . . let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span }; . span = Some(current_span); -- line 1646 ---------------------------------------- -- line 1671 ---------------------------------------- . attr_name, . macro_name: pprust::path_to_string(&call.path), . invoc_span: call.path.span, . }, . ); . } . } . } 560 ( 0.00%) } . . fn expand_cfg_true( . &mut self, . node: &mut impl AstLike, . attr: ast::Attribute, . pos: usize, . ) -> bool { 36 ( 0.00%) let res = self.cfg.cfg_true(&attr); 36 ( 0.00%) if res { . // FIXME: `cfg(TRUE)` attributes do not currently remove themselves during expansion, . // and some tools like rustdoc and clippy rely on that. Find a way to remove them . // while keeping the tools working. . self.cx.expanded_inert_attrs.mark(&attr); . node.visit_attrs(|attrs| attrs.insert(pos, attr)); . } . res . } -- line 1696 ---------------------------------------- -- line 1701 ---------------------------------------- . }); . } . . fn flat_map_node>( . &mut self, . mut node: Node, . ) -> Node::OutputTy { . loop { 432,745 ( 0.01%) return match self.take_first_attr(&mut node) { 1,064 ( 0.00%) Some((attr, pos, derives)) => match attr.name_or_empty() { . sym::cfg => { 306 ( 0.00%) if self.expand_cfg_true(&mut node, attr, pos) { . continue; . } . Default::default() . } . sym::cfg_attr => { . self.expand_cfg_attr(&mut node, attr, pos); . continue; . } . _ => { . Node::pre_flat_map_node_collect_attr(&self.cfg, &attr); . self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND) . .make_ast::() . } . }, 141,369 ( 0.00%) None if node.is_mac_call() => { 380 ( 0.00%) let (mac, attrs, add_semicolon) = node.take_mac_call(); 75 ( 0.00%) self.check_attributes(&attrs, &mac); 360 ( 0.00%) let mut res = self.collect_bang(mac, Node::KIND).make_ast::(); 18 ( 0.00%) Node::post_flat_map_node_collect_bang(&mut res, add_semicolon); 48 ( 0.00%) res . } . None => { 2,700 ( 0.00%) match Node::wrap_flat_map_node_noop_flat_map(node, self, |mut node, this| { 1,861,555 ( 0.04%) assign_id!(this, node.id(), || node.noop_flat_map(this)) . }) { 17,389 ( 0.00%) Ok(output) => output, 8 ( 0.00%) Err(returned_node) => { 930 ( 0.00%) node = returned_node; . continue; . } . } . } . }; . } 16 ( 0.00%) } . . fn visit_node + DummyAstNode>( . &mut self, . node: &mut Node, . ) { . loop { 18,395 ( 0.00%) return match self.take_first_attr(node) { . Some((attr, pos, derives)) => match attr.name_or_empty() { . sym::cfg => { . let span = attr.span; . if self.expand_cfg_true(node, attr, pos) { . continue; . } . let msg = . format!("removing {} is not supported in this position", Node::descr()); -- line 1762 ---------------------------------------- -- line 1767 ---------------------------------------- . self.expand_cfg_attr(node, attr, pos); . continue; . } . _ => visit_clobber(node, |node| { . self.collect_attr((attr, pos, derives), node.to_annotatable(), Node::KIND) . .make_ast::() . }), . }, 7,713 ( 0.00%) None if node.is_mac_call() => { . visit_clobber(node, |node| { . // Do not clobber unless it's actually a macro (uncommon case). 240 ( 0.00%) let (mac, attrs, _) = node.take_mac_call(); 60 ( 0.00%) self.check_attributes(&attrs, &mac); 270 ( 0.00%) self.collect_bang(mac, Node::KIND).make_ast::() . }) . } . None => { 96,675 ( 0.00%) assign_id!(self, node.id(), || node.noop_visit(self)) . } . }; . } . } . } . . impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> { 6,766 ( 0.00%) fn flat_map_item(&mut self, node: P) -> SmallVec<[P; 1]> { . self.flat_map_node(node) 4,347 ( 0.00%) } . 16 ( 0.00%) fn flat_map_trait_item(&mut self, node: P) -> SmallVec<[P; 1]> { . self.flat_map_node(AstLikeWrapper::new(node, TraitItemTag)) 9 ( 0.00%) } . 3,184 ( 0.00%) fn flat_map_impl_item(&mut self, node: P) -> SmallVec<[P; 1]> { . self.flat_map_node(AstLikeWrapper::new(node, ImplItemTag)) 1,791 ( 0.00%) } . . fn flat_map_foreign_item( . &mut self, . node: P, . ) -> SmallVec<[P; 1]> { . self.flat_map_node(node) . } . 176 ( 0.00%) fn flat_map_variant(&mut self, node: ast::Variant) -> SmallVec<[ast::Variant; 1]> { 462 ( 0.00%) self.flat_map_node(node) 198 ( 0.00%) } . 496 ( 0.00%) fn flat_map_field_def(&mut self, node: ast::FieldDef) -> SmallVec<[ast::FieldDef; 1]> { 930 ( 0.00%) self.flat_map_node(node) 558 ( 0.00%) } . 1,216 ( 0.00%) fn flat_map_pat_field(&mut self, node: ast::PatField) -> SmallVec<[ast::PatField; 1]> { 1,824 ( 0.00%) self.flat_map_node(node) 1,216 ( 0.00%) } . 7,472 ( 0.00%) fn flat_map_expr_field(&mut self, node: ast::ExprField) -> SmallVec<[ast::ExprField; 1]> { 11,208 ( 0.00%) self.flat_map_node(node) 8,406 ( 0.00%) } . 3,552 ( 0.00%) fn flat_map_param(&mut self, node: ast::Param) -> SmallVec<[ast::Param; 1]> { 5,328 ( 0.00%) self.flat_map_node(node) 3,996 ( 0.00%) } . 1,440 ( 0.00%) fn flat_map_generic_param( . &mut self, . node: ast::GenericParam, . ) -> SmallVec<[ast::GenericParam; 1]> { 3,240 ( 0.00%) self.flat_map_node(node) 1,620 ( 0.00%) } . 1,328 ( 0.00%) fn flat_map_arm(&mut self, node: ast::Arm) -> SmallVec<[ast::Arm; 1]> { 1,992 ( 0.00%) self.flat_map_node(node) 1,494 ( 0.00%) } . 9,440 ( 0.00%) fn flat_map_stmt(&mut self, mut node: ast::Stmt) -> SmallVec<[ast::Stmt; 1]> { . // FIXME: invocations in semicolon-less expressions positions are expanded as expressions, . // changing that requires some compatibility measures. 3,776 ( 0.00%) if node.is_expr() { . // The only way that we can end up with a `MacCall` expression statement, . // (as opposed to a `StmtKind::MacCall`) is if we have a macro as the . // traiing expression in a block (e.g. `fn foo() { my_macro!() }`). . // Record this information, so that we can report a more specific . // `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` lint if needed. . // See #78991 for an investigation of treating macros in this position . // as statements, rather than expressions, during parsing. 1,162 ( 0.00%) return match &node.kind { . StmtKind::Expr(expr) 1,162 ( 0.00%) if matches!(**expr, ast::Expr { kind: ExprKind::MacCall(..), .. }) => . { 26 ( 0.00%) self.cx.current_expansion.is_trailing_mac = true; . // Don't use `assign_id` for this statement - it may get removed . // entirely due to a `#[cfg]` on the contained expression 104 ( 0.00%) let res = noop_flat_map_stmt(node, self); 39 ( 0.00%) self.cx.current_expansion.is_trailing_mac = false; . res . } 13,632 ( 0.00%) _ => assign_id!(self, &mut node.id, || noop_flat_map_stmt(node, self)), . }; . } . 2,904 ( 0.00%) self.flat_map_node(node) 7,552 ( 0.00%) } . 13 ( 0.00%) fn visit_crate(&mut self, node: &mut ast::Crate) { . self.visit_node(node) 8 ( 0.00%) } . 14,520 ( 0.00%) fn visit_ty(&mut self, node: &mut P) { . self.visit_node(node) 14,520 ( 0.00%) } . 10,400 ( 0.00%) fn visit_pat(&mut self, node: &mut P) { . self.visit_node(node) 10,400 ( 0.00%) } . 41,382 ( 0.00%) fn visit_expr(&mut self, node: &mut P) { . // FIXME: Feature gating is performed inconsistently between `Expr` and `OptExpr`. . if let Some(attr) = node.attrs.first() { . self.cfg.maybe_emit_expr_attr_err(attr); . } . self.visit_node(node) 36,784 ( 0.00%) } . 2,389,945 ( 0.05%) fn filter_map_expr(&mut self, node: P) -> Option> { . self.flat_map_node(AstLikeWrapper::new(node, OptExprTag)) 1,124,680 ( 0.02%) } . . fn visit_block(&mut self, node: &mut P) { . let orig_dir_ownership = mem::replace( 404 ( 0.00%) &mut self.cx.current_expansion.dir_ownership, . DirOwnership::UnownedViaBlock, . ); . noop_visit_block(node, self); 1,449 ( 0.00%) self.cx.current_expansion.dir_ownership = orig_dir_ownership; . } . . fn visit_id(&mut self, id: &mut NodeId) { . // We may have already assigned a `NodeId` . // by calling `assign_id` 662,687 ( 0.01%) if self.monotonic && *id == ast::DUMMY_NODE_ID { 46,343 ( 0.00%) *id = self.cx.resolver.next_node_id(); . } . } . } . . pub struct ExpansionConfig<'feat> { . pub crate_name: String, . pub features: Option<&'feat Features>, . pub recursion_limit: Limit, . pub trace_mac: bool, . pub should_test: bool, // If false, strip `#[test]` nodes . pub span_debug: bool, // If true, use verbose debugging for `proc_macro::Span` . pub proc_macro_backtrace: bool, // If true, show backtraces for proc-macro panics . } . . impl<'feat> ExpansionConfig<'feat> { 12 ( 0.00%) pub fn default(crate_name: String) -> ExpansionConfig<'static> { 18 ( 0.00%) ExpansionConfig { 9 ( 0.00%) crate_name, . features: None, 6 ( 0.00%) recursion_limit: Limit::new(1024), . trace_mac: false, . should_test: false, . span_debug: false, . proc_macro_backtrace: false, . } 15 ( 0.00%) } . . fn proc_macro_hygiene(&self) -> bool { . self.features.map_or(false, |features| features.proc_macro_hygiene) . } . } 352,322 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/std/src/collections/hash/map.rs -------------------------------------------------------------------------------- Ir -- line 270 ---------------------------------------- . /// . /// let s = RandomState::new(); . /// let mut map = HashMap::with_hasher(s); . /// map.insert(1, 2); . /// ``` . #[inline] . #[stable(feature = "hashmap_build_hasher", since = "1.7.0")] . pub fn with_hasher(hash_builder: S) -> HashMap { 1,385,353 ( 0.03%) HashMap { base: base::HashMap::with_hasher(hash_builder) } . } . . /// Creates an empty `HashMap` with the specified capacity, using `hash_builder` . /// to hash the keys. . /// . /// The hash map will be able to hold at least `capacity` elements without . /// reallocating. If `capacity` is 0, the hash map will not allocate. . /// -- line 286 ---------------------------------------- -- line 300 ---------------------------------------- . /// . /// let s = RandomState::new(); . /// let mut map = HashMap::with_capacity_and_hasher(10, s); . /// map.insert(1, 2); . /// ``` . #[inline] . #[stable(feature = "hashmap_build_hasher", since = "1.7.0")] . pub fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap { 2,056 ( 0.00%) HashMap { base: base::HashMap::with_capacity_and_hasher(capacity, hash_builder) } . } . . /// Returns the number of elements the map can hold without reallocating. . /// . /// This number is a lower bound; the `HashMap` might be able to hold . /// more, but is guaranteed to be able to hold at least this many. . /// . /// # Examples -- line 316 ---------------------------------------- -- line 468 ---------------------------------------- . /// ]); . /// . /// for (key, val) in map.iter() { . /// println!("key: {} val: {}", key, val); . /// } . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn iter(&self) -> Iter<'_, K, V> { 6,910 ( 0.00%) Iter { base: self.base.iter() } . } . . /// An iterator visiting all key-value pairs in arbitrary order, . /// with mutable references to the values. . /// The iterator element type is `(&'a K, &'a mut V)`. . /// . /// # Examples . /// -- line 484 ---------------------------------------- -- line 643 ---------------------------------------- . /// let mut a = HashMap::new(); . /// a.insert(1, "a"); . /// a.clear(); . /// assert!(a.is_empty()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn clear(&mut self) { 1 ( 0.00%) self.base.clear(); . } . . /// Returns a reference to the map's [`BuildHasher`]. . /// . /// # Examples . /// . /// ``` . /// use std::collections::HashMap; -- line 659 ---------------------------------------- -- line 688 ---------------------------------------- . /// ``` . /// use std::collections::HashMap; . /// let mut map: HashMap<&str, i32> = HashMap::new(); . /// map.reserve(10); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn reserve(&mut self, additional: usize) { 1 ( 0.00%) self.base.reserve(additional) . } . . /// Tries to reserve capacity for at least `additional` more elements to be inserted . /// in the given `HashMap`. The collection may reserve more space to avoid . /// frequent reallocations. . /// . /// # Errors . /// -- line 704 ---------------------------------------- -- line 784 ---------------------------------------- . /// assert_eq!(letters[&'s'], 2); . /// assert_eq!(letters[&'t'], 3); . /// assert_eq!(letters[&'u'], 1); . /// assert_eq!(letters.get(&'y'), None); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn entry(&mut self, key: K) -> Entry<'_, K, V> { 1,139,898 ( 0.02%) map_entry(self.base.rustc_entry(key)) . } . . /// Returns a reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// -- line 800 ---------------------------------------- -- line 805 ---------------------------------------- . /// . /// let mut map = HashMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.get(&1), Some(&"a")); . /// assert_eq!(map.get(&2), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 4,375,582 ( 0.09%) pub fn get(&self, k: &Q) -> Option<&V> . where . K: Borrow, . Q: Hash + Eq, . { . self.base.get(k) 5,858,408 ( 0.12%) } . . /// Returns the key-value pair corresponding to the supplied key. . /// . /// The supplied key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// . /// # Examples -- line 827 ---------------------------------------- -- line 862 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn contains_key(&self, k: &Q) -> bool . where . K: Borrow, . Q: Hash + Eq, . { 23,728 ( 0.00%) self.base.contains_key(k) . } . . /// Returns a mutable reference to the value corresponding to the key. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. . /// -- line 878 ---------------------------------------- -- line 890 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get_mut(&mut self, k: &Q) -> Option<&mut V> . where . K: Borrow, . Q: Hash + Eq, . { 583 ( 0.00%) self.base.get_mut(k) . } . . /// Inserts a key-value pair into the map. . /// . /// If the map did not have this key present, [`None`] is returned. . /// . /// If the map did have this key present, the value is updated, and the old . /// value is returned. The key is not updated, though; this matters for -- line 906 ---------------------------------------- -- line 920 ---------------------------------------- . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn insert(&mut self, k: K, v: V) -> Option { 2,742,204 ( 0.06%) self.base.insert(k, v) . } . . /// Tries to insert a key-value pair into the map, and returns . /// a mutable reference to the value in the entry. . /// . /// If the map already had this key present, nothing is updated, and . /// an error containing the occupied entry and the value is returned. . /// -- line 936 ---------------------------------------- -- line 978 ---------------------------------------- . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn remove(&mut self, k: &Q) -> Option . where . K: Borrow, . Q: Hash + Eq, . { 768,372 ( 0.02%) self.base.remove(k) . } . . /// Removes a key from the map, returning the stored key and value if the . /// key was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but . /// [`Hash`] and [`Eq`] on the borrowed form *must* match those for . /// the key type. -- line 994 ---------------------------------------- -- line 1083 ---------------------------------------- . impl Clone for HashMap . where . K: Clone, . V: Clone, . S: Clone, . { . #[inline] . fn clone(&self) -> Self { 575 ( 0.00%) Self { base: self.base.clone() } . } . . #[inline] . fn clone_from(&mut self, other: &Self) { . self.base.clone_from(&other.base); . } . } . -- line 1099 ---------------------------------------- -- line 1155 ---------------------------------------- . type Output = V; . . /// Returns a reference to the value corresponding to the supplied key. . /// . /// # Panics . /// . /// Panics if the key is not present in the `HashMap`. . #[inline] 1,554 ( 0.00%) fn index(&self, key: &Q) -> &V { . self.get(key).expect("no entry found for key") 2,180 ( 0.00%) } . } . . #[stable(feature = "std_collections_from_array", since = "1.56.0")] . // Note: as what is currently the most convenient built-in way to construct . // a HashMap, a simple usage of this function must not *require* the user . // to provide a type annotation in order to infer the third type parameter . // (the hasher parameter, conventionally "S"). . // To that end, this impl is defined using RandomState as the concrete -- line 1173 ---------------------------------------- -- line 1557 ---------------------------------------- . /// Creates a `RawEntryMut` from the given key and its hash. . #[inline] . #[unstable(feature = "hash_raw_entry", issue = "56167")] . pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> RawEntryMut<'a, K, V, S> . where . K: Borrow, . Q: Eq, . { 1,632,913 ( 0.03%) map_raw_entry(self.map.base.raw_entry_mut().from_key_hashed_nocheck(hash, k)) . } . . /// Creates a `RawEntryMut` from the given hash. . #[inline] . #[unstable(feature = "hash_raw_entry", issue = "56167")] . pub fn from_hash(self, hash: u64, is_match: F) -> RawEntryMut<'a, K, V, S> . where . for<'b> F: FnMut(&'b K) -> bool, -- line 1573 ---------------------------------------- -- line 1594 ---------------------------------------- . /// Access an entry by a key and its hash. . #[inline] . #[unstable(feature = "hash_raw_entry", issue = "56167")] . pub fn from_key_hashed_nocheck(self, hash: u64, k: &Q) -> Option<(&'a K, &'a V)> . where . K: Borrow, . Q: Hash + Eq, . { 6,730,919 ( 0.14%) self.map.base.raw_entry().from_key_hashed_nocheck(hash, k) . } . . /// Access an entry by hash. . #[inline] . #[unstable(feature = "hash_raw_entry", issue = "56167")] . pub fn from_hash(self, hash: u64, is_match: F) -> Option<(&'a K, &'a V)> . where . F: FnMut(&K) -> bool, -- line 1610 ---------------------------------------- -- line 2338 ---------------------------------------- . /// assert_eq!(map["poneyland"], 3); . /// . /// *map.entry("poneyland").or_insert(10) *= 2; . /// assert_eq!(map["poneyland"], 6); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn or_insert(self, default: V) -> &'a mut V { 20,872 ( 0.00%) match self { . Occupied(entry) => entry.into_mut(), . Vacant(entry) => entry.insert(default), . } . } . . /// Ensures a value is in the entry by inserting the result of the default function if empty, . /// and returns a mutable reference to the value in the entry. . /// -- line 2354 ---------------------------------------- -- line 2362 ---------------------------------------- . /// . /// map.entry("poneyland").or_insert_with(|| s); . /// . /// assert_eq!(map["poneyland"], "hoho".to_string()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn or_insert_with V>(self, default: F) -> &'a mut V { 46,367 ( 0.00%) match self { . Occupied(entry) => entry.into_mut(), . Vacant(entry) => entry.insert(default()), . } . } . . /// Ensures a value is in the entry by inserting, if empty, the result of the default function. . /// This method allows for generating key-derived values for insertion by providing the default . /// function a reference to the key that was moved during the `.entry(key)` method call. -- line 2378 ---------------------------------------- -- line 2443 ---------------------------------------- . /// assert_eq!(map["poneyland"], 43); . /// ``` . #[inline] . #[stable(feature = "entry_and_modify", since = "1.26.0")] . pub fn and_modify(self, f: F) -> Self . where . F: FnOnce(&mut V), . { 48 ( 0.00%) match self { . Occupied(mut entry) => { . f(entry.get_mut()); . Occupied(entry) . } . Vacant(entry) => Vacant(entry), . } . } . -- line 2459 ---------------------------------------- -- line 2496 ---------------------------------------- . /// map.entry("poneyland").or_default(); . /// . /// assert_eq!(map["poneyland"], None); . /// # } . /// ``` . #[inline] . #[stable(feature = "entry_or_default", since = "1.28.0")] . pub fn or_default(self) -> &'a mut V { 21,946 ( 0.00%) match self { . Occupied(entry) => entry.into_mut(), . Vacant(entry) => entry.insert(Default::default()), . } . } . } . . impl<'a, K, V> OccupiedEntry<'a, K, V> { . /// Gets a reference to the key in the entry. -- line 2512 ---------------------------------------- -- line 2790 ---------------------------------------- . /// if let Entry::Vacant(o) = map.entry("poneyland") { . /// o.insert(37); . /// } . /// assert_eq!(map["poneyland"], 37); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn insert(self, value: V) -> &'a mut V { 107,575 ( 0.00%) self.base.insert(value) . } . . /// Sets the value of the entry with the `VacantEntry`'s key, . /// and returns an `OccupiedEntry`. . /// . /// # Examples . /// . /// ``` -- line 2806 ---------------------------------------- -- line 2823 ---------------------------------------- . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl FromIterator<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher + Default, . { 13 ( 0.00%) fn from_iter>(iter: T) -> HashMap { . let mut map = HashMap::with_hasher(Default::default()); . map.extend(iter); . map 14 ( 0.00%) } . } . . /// Inserts all new key-values from the iterator and replaces values with existing . /// keys with new values returned from the iterator. . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend<(K, V)> for HashMap . where . K: Eq + Hash, . S: BuildHasher, . { . #[inline] . fn extend>(&mut self, iter: T) { 19,597 ( 0.00%) self.base.extend(iter) . } . . #[inline] . fn extend_one(&mut self, (k, v): (K, V)) { . self.base.insert(k, v); . } . . #[inline] -- line 2856 ---------------------------------------- -- line 2928 ---------------------------------------- . // many hash maps are created on a thread. To solve this performance . // trap we cache the first set of randomly generated keys per-thread. . // . // Later in #36481 it was discovered that exposing a deterministic . // iteration order allows a form of DOS attack. To counter that we . // increment one of the seeds on every RandomState creation, giving . // every corresponding HashMap a different iteration order. . thread_local!(static KEYS: Cell<(u64, u64)> = { 1 ( 0.00%) Cell::new(sys::hashmap_random_keys()) . }); . . KEYS.with(|keys| { 3 ( 0.00%) let (k0, k1) = keys.get(); . keys.set((k0.wrapping_add(1), k1)); . RandomState { k0, k1 } . }) . } . } . . #[stable(feature = "hashmap_build_hasher", since = "1.7.0")] . impl BuildHasher for RandomState { -- line 2948 ---------------------------------------- -- line 2967 ---------------------------------------- . /// Creates a new `DefaultHasher`. . /// . /// This hasher is not guaranteed to be the same as all other . /// `DefaultHasher` instances, but is the same as all other `DefaultHasher` . /// instances created through `new` or `default`. . #[stable(feature = "hashmap_default_hasher", since = "1.13.0")] . #[allow(deprecated)] . #[must_use] 3 ( 0.00%) pub fn new() -> DefaultHasher { 12 ( 0.00%) DefaultHasher(SipHasher13::new_with_keys(0, 0)) 3 ( 0.00%) } . } . . #[stable(feature = "hashmap_default_hasher", since = "1.13.0")] . impl Default for DefaultHasher { . /// Creates a new `DefaultHasher` using [`new`]. . /// See its documentation for more. . /// . /// [`new`]: DefaultHasher::new -- line 2985 ---------------------------------------- -- line 2986 ---------------------------------------- . fn default() -> DefaultHasher { . DefaultHasher::new() . } . } . . #[stable(feature = "hashmap_default_hasher", since = "1.13.0")] . impl Hasher for DefaultHasher { . #[inline] 1,074 ( 0.00%) fn write(&mut self, msg: &[u8]) { . self.0.write(msg) 1,074 ( 0.00%) } . . #[inline] . fn finish(&self) -> u64 { . self.0.finish() . } . } . . #[stable(feature = "hashmap_build_hasher", since = "1.7.0")] -- line 3004 ---------------------------------------- -- line 3014 ---------------------------------------- . impl fmt::Debug for RandomState { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . f.debug_struct("RandomState").finish_non_exhaustive() . } . } . . #[inline] . fn map_entry<'a, K: 'a, V: 'a>(raw: base::RustcEntry<'a, K, V>) -> Entry<'a, K, V> { 17,789 ( 0.00%) match raw { 4 ( 0.00%) base::RustcEntry::Occupied(base) => Entry::Occupied(OccupiedEntry { base }), 956 ( 0.00%) base::RustcEntry::Vacant(base) => Entry::Vacant(VacantEntry { base }), . } . } . . #[inline] . pub(super) fn map_try_reserve_error(err: hashbrown::TryReserveError) -> TryReserveError { . match err { . hashbrown::TryReserveError::CapacityOverflow => { . TryReserveErrorKind::CapacityOverflow.into() -- line 3032 ---------------------------------------- -- line 3036 ---------------------------------------- . } . } . } . . #[inline] . fn map_raw_entry<'a, K: 'a, V: 'a, S: 'a>( . raw: base::RawEntryMut<'a, K, V, S>, . ) -> RawEntryMut<'a, K, V, S> { 1,236,188 ( 0.03%) match raw { . base::RawEntryMut::Occupied(base) => RawEntryMut::Occupied(RawOccupiedEntryMut { base }), . base::RawEntryMut::Vacant(base) => RawEntryMut::Vacant(RawVacantEntryMut { base }), . } . } . . #[allow(dead_code)] . fn assert_covariance() { . fn map_key<'new>(v: HashMap<&'static str, u8>) -> HashMap<&'new str, u8> { -- line 3052 ---------------------------------------- 1,475,555 ( 0.03%) -------------------------------------------------------------------------------- -- 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 . // . 4,357,212 ( 0.09%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 3,267,909 ( 0.07%) libc::malloc(layout.size()) as *mut u8 . } else { . #[cfg(target_os = "macos")] . { . if layout.align() > (1 << 31) { . return ptr::null_mut(); . } . } . aligned_malloc(&layout) . } . } . . #[inline] . unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { . // See the comment above in `alloc` for why this check looks the way it does. 88,216 ( 0.00%) if layout.align() <= MIN_ALIGN && layout.align() <= layout.size() { 132,324 ( 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) { 1,111,346 ( 0.02%) libc::free(ptr as *mut libc::c_void) . } . . #[inline] . unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { 282,216 ( 0.01%) if layout.align() <= MIN_ALIGN && layout.align() <= new_size { 564,432 ( 0.01%) libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8 . } else { . realloc_fallback(self, ptr, layout, new_size) . } . } . } . . cfg_if::cfg_if! { . if #[cfg(any( -- line 56 ---------------------------------------- -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/tokenstream.rs -------------------------------------------------------------------------------- Ir -- line 32 ---------------------------------------- . /// . /// If the syntax extension is an MBE macro, it will attempt to match its . /// LHS token tree against the provided token tree, and if it finds a . /// match, will transcribe the RHS token tree, splicing in any captured . /// `macro_parser::matched_nonterminals` into the `SubstNt`s it finds. . /// . /// The RHS of an MBE macro is the only place `SubstNt`s are substituted. . /// Nothing special happens to misnamed or misplaced `SubstNt`s. 3,258,059 ( 0.07%) #[derive(Debug, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum TokenTree { . /// A single token. 1,256,943 ( 0.03%) Token(Token), . /// A delimited sequence of token trees. 11,962 ( 0.00%) Delimited(DelimSpan, DelimToken, TokenStream), . } . . #[derive(Copy, Clone)] . pub enum CanSynthesizeMissingTokens { . Yes, . No, . } . -- line 53 ---------------------------------------- -- line 71 ---------------------------------------- . delim == delim2 && tts.eq_unspanned(&tts2) . } . _ => false, . } . } . . /// Retrieves the `TokenTree`'s span. . pub fn span(&self) -> Span { 180 ( 0.00%) match self { 195 ( 0.00%) TokenTree::Token(token) => token.span, 152 ( 0.00%) TokenTree::Delimited(sp, ..) => sp.entire(), . } 52 ( 0.00%) } . . /// Modify the `TokenTree`'s span in-place. . pub fn set_span(&mut self, span: Span) { 180 ( 0.00%) match self { 52 ( 0.00%) TokenTree::Token(token) => token.span = span, 76 ( 0.00%) TokenTree::Delimited(dspan, ..) => *dspan = DelimSpan::from_single(span), . } 90 ( 0.00%) } . 286 ( 0.00%) pub fn token(kind: TokenKind, span: Span) -> TokenTree { 35,048 ( 0.00%) TokenTree::Token(Token::new(kind, span)) 286 ( 0.00%) } . . /// Returns the opening delimiter as a token tree. 4,297 ( 0.00%) pub fn open_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 12,891 ( 0.00%) TokenTree::token(token::OpenDelim(delim), span.open) 4,297 ( 0.00%) } . . /// Returns the closing delimiter as a token tree. 4,179 ( 0.00%) pub fn close_tt(span: DelimSpan, delim: DelimToken) -> TokenTree { 12,537 ( 0.00%) TokenTree::token(token::CloseDelim(delim), span.close) 4,179 ( 0.00%) } . 1,497 ( 0.00%) pub fn uninterpolate(self) -> TokenTree { 998 ( 0.00%) match self { 4,491 ( 0.00%) TokenTree::Token(token) => TokenTree::Token(token.uninterpolate().into_owned()), . tt => tt, . } 1,996 ( 0.00%) } . } . . impl HashStable for TokenStream . where . CTX: crate::HashStableContext, . { 4,779 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 35,964 ( 0.00%) for sub_tt in self.trees() { . sub_tt.hash_stable(hcx, hasher); . } 4,248 ( 0.00%) } . } . . pub trait CreateTokenStream: sync::Send + sync::Sync { . fn create_token_stream(&self) -> AttrAnnotatedTokenStream; . } . . impl CreateTokenStream for AttrAnnotatedTokenStream { . fn create_token_stream(&self) -> AttrAnnotatedTokenStream { -- line 131 ---------------------------------------- -- line 188 ---------------------------------------- . Delimited(DelimSpan, DelimToken, AttrAnnotatedTokenStream), . /// Stores the attributes for an attribute target, . /// along with the tokens for that attribute target. . /// See `AttributesData` for more information . Attributes(AttributesData), . } . . impl AttrAnnotatedTokenStream { 7,578 ( 0.00%) pub fn new(tokens: Vec<(AttrAnnotatedTokenTree, Spacing)>) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream(Lrc::new(tokens)) 7,578 ( 0.00%) } . . /// Converts this `AttrAnnotatedTokenStream` to a plain `TokenStream . /// During conversion, `AttrAnnotatedTokenTree::Attributes` get 'flattened' . /// back to a `TokenStream` of the form `outer_attr attr_target`. . /// If there are inner attributes, they are inserted into the proper . /// place in the attribute target tokens. . pub fn to_tokenstream(&self) -> TokenStream { . let trees: Vec<_> = self -- line 206 ---------------------------------------- -- line 316 ---------------------------------------- . pub struct TokenStream(pub(crate) Lrc>); . . pub type TreeAndSpacing = (TokenTree, Spacing); . . // `TokenStream` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenStream, 8); . 319,789 ( 0.01%) #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable)] . pub enum Spacing { . Alone, . Joint, . } . . impl TokenStream { . /// Given a `TokenStream` with a `Stream` of only two arguments, return a new `TokenStream` . /// separating the two arguments with a comma for diagnostic suggestions. -- line 332 ---------------------------------------- -- line 371 ---------------------------------------- . impl From<(AttrAnnotatedTokenTree, Spacing)> for AttrAnnotatedTokenStream { . fn from((tree, spacing): (AttrAnnotatedTokenTree, Spacing)) -> AttrAnnotatedTokenStream { . AttrAnnotatedTokenStream::new(vec![(tree, spacing)]) . } . } . . impl From for TokenStream { . fn from(tree: TokenTree) -> TokenStream { 350 ( 0.00%) TokenStream::new(vec![(tree, Spacing::Alone)]) . } . } . . impl From for TreeAndSpacing { . fn from(tree: TokenTree) -> TreeAndSpacing { 14,635 ( 0.00%) (tree, Spacing::Alone) . } . } . . impl iter::FromIterator for TokenStream { . fn from_iter>(iter: I) -> Self { . TokenStream::new(iter.into_iter().map(Into::into).collect::>()) . } . } -- line 393 ---------------------------------------- -- line 401 ---------------------------------------- . } . . impl TokenStream { . pub fn new(streams: Vec) -> TokenStream { . TokenStream(Lrc::new(streams)) . } . . pub fn is_empty(&self) -> bool { 3,366 ( 0.00%) self.0.is_empty() 3,366 ( 0.00%) } . . pub fn len(&self) -> usize { 331,372 ( 0.01%) self.0.len() 43 ( 0.00%) } . . pub fn from_streams(mut streams: SmallVec<[TokenStream; 2]>) -> TokenStream { . match streams.len() { . 0 => TokenStream::default(), . 1 => streams.pop().unwrap(), . _ => { . // We are going to extend the first stream in `streams` with . // the elements from the subsequent streams. This requires -- line 422 ---------------------------------------- -- line 448 ---------------------------------------- . . // Create the final `TokenStream`. . TokenStream(first_stream_lrc) . } . } . } . . pub fn trees(&self) -> Cursor { 1,239 ( 0.00%) self.clone().into_trees() 2,478 ( 0.00%) } . 5,277 ( 0.00%) pub fn into_trees(self) -> Cursor { . Cursor::new(self) 10,554 ( 0.00%) } . . /// Compares two `TokenStream`s, checking equality without regarding span information. . pub fn eq_unspanned(&self, other: &TokenStream) -> bool { . let mut t1 = self.trees(); . let mut t2 = other.trees(); . for (t1, t2) in iter::zip(&mut t1, &mut t2) { . if !t1.eq_unspanned(&t2) { . return false; . } . } . t1.next().is_none() && t2.next().is_none() . } . . pub fn map_enumerated TokenTree>(self, mut f: F) -> TokenStream { 42 ( 0.00%) TokenStream(Lrc::new( . self.0 . .iter() . .enumerate() 540 ( 0.00%) .map(|(i, (tree, is_joint))| (f(i, tree), *is_joint)) . .collect(), . )) . } . } . . // 99.5%+ of the time we have 1 or 2 elements in this vector. . #[derive(Clone)] . pub struct TokenStreamBuilder(SmallVec<[TokenStream; 2]>); -- line 488 ---------------------------------------- -- line 572 ---------------------------------------- . pub struct Cursor { . pub stream: TokenStream, . index: usize, . } . . impl Iterator for Cursor { . type Item = TokenTree; . 38,604 ( 0.00%) fn next(&mut self) -> Option { 72,646 ( 0.00%) self.next_with_spacing().map(|(tree, _)| tree) 51,472 ( 0.00%) } . } . . impl Cursor { . fn new(stream: TokenStream) -> Self { . Cursor { stream, index: 0 } . } . 1,592,090 ( 0.03%) pub fn next_with_spacing(&mut self) -> Option { 993,858 ( 0.02%) if self.index < self.stream.len() { 639,650 ( 0.01%) self.index += 1; 2,162,615 ( 0.04%) Some(self.stream.0[self.index - 1].clone()) . } else { 18,946 ( 0.00%) None . } 1,910,508 ( 0.04%) } . . pub fn index(&self) -> usize { . self.index . } . . pub fn append(&mut self, new_stream: TokenStream) { . if new_stream.is_empty() { . return; . } . let index = self.index; . let stream = mem::take(&mut self.stream); . *self = TokenStream::from_streams(smallvec![stream, new_stream]).into_trees(); . self.index = index; . } . 296,256 ( 0.01%) pub fn look_ahead(&self, n: usize) -> Option<&TokenTree> { 592,512 ( 0.01%) self.stream.0[self.index..].get(n).map(|(tree, _)| tree) 592,512 ( 0.01%) } . } . 26,091 ( 0.00%) #[derive(Debug, Copy, Clone, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub struct DelimSpan { . pub open: Span, . pub close: Span, . } . . impl DelimSpan { 5 ( 0.00%) pub fn from_single(sp: Span) -> Self { . DelimSpan { open: sp, close: sp } 10 ( 0.00%) } . 6,730 ( 0.00%) pub fn from_pair(open: Span, close: Span) -> Self { . DelimSpan { open, close } 3,365 ( 0.00%) } . . pub fn dummy() -> Self { . Self::from_single(DUMMY_SP) 954 ( 0.00%) } . 2,112 ( 0.00%) pub fn entire(self) -> Span { . self.open.with_hi(self.close.hi()) 1,584 ( 0.00%) } . } 12,995 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_const_eval/src/transform/promote_consts.rs -------------------------------------------------------------------------------- Ir -- line 30 ---------------------------------------- . . /// A `MirPass` for promotion. . /// . /// Promotion is the extraction of promotable temps into separate MIR bodies so they can have . /// `'static` lifetime. . /// . /// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each . /// newly created `Constant`. 2,005 ( 0.00%) #[derive(Default)] . pub struct PromoteTemps<'tcx> { . pub promoted_fragments: Cell>>, . } . . impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> { . fn phase_change(&self) -> Option { . Some(MirPhase::ConstPromotion) 802 ( 0.00%) } . 2,406 ( 0.00%) fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { . // There's not really any point in promoting errorful MIR. . // . // This does not include MIR that failed const-checking, which we still try to promote. 401 ( 0.00%) if body.return_ty().references_error() { . tcx.sess.delay_span_bug(body.span, "PromoteTemps: MIR had errors"); . return; . } . 401 ( 0.00%) if body.source.promoted.is_some() { . return; . } . 1,203 ( 0.00%) let mut rpo = traversal::reverse_postorder(body); 1,203 ( 0.00%) let ccx = ConstCx::new(tcx, body); 4,010 ( 0.00%) let (temps, all_candidates) = collect_temps_and_candidates(&ccx, &mut rpo); . . let promotable_candidates = validate_candidates(&ccx, &temps, &all_candidates); . 5,614 ( 0.00%) let promoted = promote_candidates(body, tcx, temps, promotable_candidates); . self.promoted_fragments.set(promoted); 2,807 ( 0.00%) } . } . . /// State of a temporary during collection and promotion. 69,970 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] . pub enum TempState { . /// No references to this temp. . Undefined, . /// One direct assignment and any number of direct uses. . /// A borrow of this temp is promotable if the assigned . /// value is qualified as constant. . Defined { location: Location, uses: usize }, . /// Any other combination of assignments/uses. -- line 81 ---------------------------------------- -- line 102 ---------------------------------------- . . struct Collector<'a, 'tcx> { . ccx: &'a ConstCx<'a, 'tcx>, . temps: IndexVec, . candidates: Vec, . } . . impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> { 89,284 ( 0.00%) fn visit_local(&mut self, &index: &Local, context: PlaceContext, location: Location) { . debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location); . // We're only interested in temporaries and the return place 3,560 ( 0.00%) match self.ccx.body.local_kind(index) { . LocalKind::Temp | LocalKind::ReturnPointer => {} . LocalKind::Arg | LocalKind::Var => return, . } . . // Ignore drops, if the temp gets promoted, . // then it's constant and thus drop is noop. . // Non-uses are also irrelevant. 40,968 ( 0.00%) if context.is_drop() || !context.is_use() { . debug!( . "visit_local: context.is_drop={:?} context.is_use={:?}", . context.is_drop(), . context.is_use(), . ); . return; . } . . let temp = &mut self.temps[index]; . debug!("visit_local: temp={:?}", temp); . if *temp == TempState::Undefined { 19,470 ( 0.00%) match context { . PlaceContext::MutatingUse(MutatingUseContext::Store) . | PlaceContext::MutatingUse(MutatingUseContext::Call) => { 19,470 ( 0.00%) *temp = TempState::Defined { location, uses: 0 }; . return; . } . _ => { /* mark as unpromotable below */ } . } 27,360 ( 0.00%) } else if let TempState::Defined { ref mut uses, .. } = *temp { . // We always allow borrows, even mutable ones, as we need . // to promote mutable borrows of some ZSTs e.g., `&mut []`. 26,684 ( 0.00%) let allowed_use = match context { . PlaceContext::MutatingUse(MutatingUseContext::Borrow) . | PlaceContext::NonMutatingUse(_) => true, . PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false, . }; . debug!("visit_local: allowed_use={:?}", allowed_use); . if allowed_use { 25,932 ( 0.00%) *uses += 1; . return; . } . /* mark as unpromotable below */ . } 357 ( 0.00%) *temp = TempState::Unpromotable; 32,394 ( 0.00%) } . 68,860 ( 0.00%) fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { . self.super_rvalue(rvalue, location); . 12,520 ( 0.00%) match *rvalue { . Rvalue::Ref(..) => { . self.candidates.push(Candidate { location }); . } . _ => {} . } 50,080 ( 0.00%) } . } . 4,010 ( 0.00%) pub fn collect_temps_and_candidates<'tcx>( . ccx: &ConstCx<'_, 'tcx>, . rpo: &mut ReversePostorder<'_, 'tcx>, . ) -> (IndexVec, Vec) { 2,807 ( 0.00%) let mut collector = Collector { 802 ( 0.00%) temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls), . candidates: vec![], . ccx, . }; 7,094 ( 0.00%) for (bb, data) in rpo { . collector.visit_basic_block_data(bb, data); . } 3,609 ( 0.00%) (collector.temps, collector.candidates) 3,208 ( 0.00%) } . . /// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable. . /// . /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion. . struct Validator<'a, 'tcx> { . ccx: &'a ConstCx<'a, 'tcx>, . temps: &'a IndexVec, . } . . impl<'a, 'tcx> std::ops::Deref for Validator<'a, 'tcx> { . type Target = ConstCx<'a, 'tcx>; . . fn deref(&self) -> &Self::Target { 579,985 ( 0.01%) &self.ccx . } . } . . struct Unpromotable; . . impl<'tcx> Validator<'_, 'tcx> { . fn validate_candidate(&self, candidate: Candidate) -> Result<(), Unpromotable> { . let loc = candidate.location; 8,769 ( 0.00%) let statement = &self.body[loc.block].statements[loc.statement_index]; 17,538 ( 0.00%) match &statement.kind { . StatementKind::Assign(box (_, Rvalue::Ref(_, kind, place))) => { . // We can only promote interior borrows of promotable temps (non-temps . // don't get promoted anyway). 14,615 ( 0.00%) self.validate_local(place.local)?; . . // The reference operation itself must be promotable. . // (Needs to come after `validate_local` to avoid ICEs.) 9,036 ( 0.00%) self.validate_ref(*kind, place)?; . . // We do not check all the projections (they do not get promoted anyway), . // but we do stay away from promoting anything involving a dereference. 4,518 ( 0.00%) if place.projection.contains(&ProjectionElem::Deref) { . return Err(Unpromotable); . } . . // We cannot promote things that need dropping, since the promoted value . // would not get dropped. 2,010 ( 0.00%) if self.qualif_local::(place.local) { . return Err(Unpromotable); . } . . Ok(()) . } . _ => bug!(), . } . } . . // FIXME(eddyb) maybe cache this? 50,070 ( 0.00%) fn qualif_local(&self, local: Local) -> bool { 133,520 ( 0.00%) if let TempState::Defined { location: loc, .. } = self.temps[local] { 50,070 ( 0.00%) let num_stmts = self.body[loc.block].statements.len(); . 33,380 ( 0.00%) if loc.statement_index < num_stmts { 16,690 ( 0.00%) let statement = &self.body[loc.block].statements[loc.statement_index]; 33,380 ( 0.00%) match &statement.kind { 66,760 ( 0.00%) StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::( . &self.ccx, 126,748 ( 0.00%) &mut |l| self.qualif_local::(l), . rhs, . ), . _ => { . span_bug!( . statement.source_info.span, . "{:?} is not an assignment", . statement . ); -- line 254 ---------------------------------------- -- line 265 ---------------------------------------- . span_bug!(terminator.source_info.span, "{:?} not promotable", kind); . } . } . } . } else { . let span = self.body.local_decls[local].source_info.span; . span_bug!(span, "{:?} not promotable, qualif_local shouldn't have been called", local); . } 33,380 ( 0.00%) } . . // FIXME(eddyb) maybe cache this? 72,256 ( 0.00%) fn validate_local(&self, local: Local) -> Result<(), Unpromotable> { 72,256 ( 0.00%) if let TempState::Defined { location: loc, .. } = self.temps[local] { 7,847 ( 0.00%) let block = &self.body[loc.block]; 15,694 ( 0.00%) let num_stmts = block.statements.len(); . 15,694 ( 0.00%) if loc.statement_index < num_stmts { 7,638 ( 0.00%) let statement = &block.statements[loc.statement_index]; 15,276 ( 0.00%) match &statement.kind { 7,638 ( 0.00%) StatementKind::Assign(box (_, rhs)) => self.validate_rvalue(rhs), . _ => { . span_bug!( . statement.source_info.span, . "{:?} is not an assignment", . statement . ); . } . } . } else { . let terminator = block.terminator(); 627 ( 0.00%) match &terminator.kind { . TerminatorKind::Call { func, args, .. } => self.validate_call(func, args), . TerminatorKind::Yield { .. } => Err(Unpromotable), . kind => { . span_bug!(terminator.source_info.span, "{:?} not promotable", kind); . } . } . } . } else { . Err(Unpromotable) . } 81,288 ( 0.00%) } . 55,377 ( 0.00%) fn validate_place(&self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> { 88 ( 0.00%) match place.last_projection() { 61,090 ( 0.00%) None => self.validate_local(place.local), 308 ( 0.00%) Some((place_base, elem)) => { . // Validate topmost projection, then recurse. . match elem { . ProjectionElem::Deref => { . let mut promotable = false; . // We need to make sure this is a `Deref` of a local with no further projections. . // Discussion can be found at . // https://github.com/rust-lang/rust/pull/74945#discussion_r463063247 19 ( 0.00%) if let Some(local) = place_base.as_local() { . // This is a special treatment for cases like *&STATIC where STATIC is a . // global static variable. . // This pattern is generated only when global static variables are directly . // accessed and is qualified for promotion safely. 152 ( 0.00%) if let TempState::Defined { location, .. } = self.temps[local] { . let def_stmt = self.body[location.block] . .statements . .get(location.statement_index); . if let Some(Statement { . kind: . StatementKind::Assign(box ( . _, . Rvalue::Use(Operand::Constant(c)), -- line 332 ---------------------------------------- -- line 357 ---------------------------------------- . } . . ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {} . . ProjectionElem::Index(local) => { . let mut promotable = false; . // Only accept if we can predict the index and are indexing an array. . let val = 32 ( 0.00%) if let TempState::Defined { location: loc, .. } = self.temps[local] { 4 ( 0.00%) let block = &self.body[loc.block]; 16 ( 0.00%) if loc.statement_index < block.statements.len() { . let statement = &block.statements[loc.statement_index]; 32 ( 0.00%) match &statement.kind { . StatementKind::Assign(box ( . _, . Rvalue::Use(Operand::Constant(c)), 18 ( 0.00%) )) => c.literal.try_eval_usize(self.tcx, self.param_env), . _ => None, . } . } else { . None . } . } else { . None . }; 3 ( 0.00%) if let Some(idx) = val { . // Determine the type of the thing we are indexing. 12 ( 0.00%) let ty = place_base.ty(self.body, self.tcx).ty; 6 ( 0.00%) match ty.kind() { . ty::Array(_, len) => { . // It's an array; determine its length. . if let Some(len) = len.try_eval_usize(self.tcx, self.param_env) . { . // If the index is in-bounds, go ahead. . if idx < len { . promotable = true; . } -- line 393 ---------------------------------------- -- line 399 ---------------------------------------- . if !promotable { . return Err(Unpromotable); . } . . self.validate_local(local)?; . } . . ProjectionElem::Field(..) => { 21 ( 0.00%) let base_ty = place_base.ty(self.body, self.tcx).ty; 19 ( 0.00%) if base_ty.is_union() { . // No promotion of union field accesses. . return Err(Unpromotable); . } . } . } . 126 ( 0.00%) self.validate_place(place_base) . } . } 352 ( 0.00%) } . 1,092 ( 0.00%) fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> { 1,121,142 ( 0.02%) match operand { 5,806 ( 0.00%) Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()), . . // The qualifs for a constant (e.g. `HasMutInterior`) are checked in . // `validate_rvalue` upon access. . Operand::Constant(c) => { 3,315,885 ( 0.07%) if let Some(def_id) = c.check_static_ptr(self.tcx) { . // Only allow statics (not consts) to refer to other statics. . // FIXME(eddyb) does this matter at all for promotion? . // FIXME(RalfJung) it makes little sense to not promote this in `fn`/`const fn`, . // and in `const` this cannot occur anyway. The only concern is that we might . // promote even `let x = &STATIC` which would be useless, but this applies to . // promotion inside statics as well. . let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_))); . if !is_static { -- line 435 ---------------------------------------- -- line 442 ---------------------------------------- . } . } . . Ok(()) . } . } . } . 30,443 ( 0.00%) fn validate_ref(&self, kind: BorrowKind, place: &Place<'tcx>) -> Result<(), Unpromotable> { 52,188 ( 0.00%) match kind { . // Reject these borrow types just to be safe. . // FIXME(RalfJung): could we allow them? Should we? No point in it until we have a usecase. . BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable), . . BorrowKind::Shared => { 8,698 ( 0.00%) let has_mut_interior = self.qualif_local::(place.local); 8,698 ( 0.00%) if has_mut_interior { . return Err(Unpromotable); . } . } . . BorrowKind::Mut { .. } => { . let ty = place.ty(self.body, self.tcx).ty; . . // In theory, any zero-sized value could be borrowed -- line 466 ---------------------------------------- -- line 473 ---------------------------------------- . } . } else { . return Err(Unpromotable); . } . } . } . . Ok(()) 39,141 ( 0.00%) } . . fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> { 45,828 ( 0.00%) match rvalue { . Rvalue::Use(operand) | Rvalue::Repeat(operand, _) => { . self.validate_operand(operand)?; . } . . Rvalue::Discriminant(place) | Rvalue::Len(place) => { . self.validate_place(place.as_ref())? . } . . Rvalue::ThreadLocalRef(_) => return Err(Unpromotable), . 1,092 ( 0.00%) Rvalue::Cast(kind, operand, cast_ty) => { 2,184 ( 0.00%) if matches!(kind, CastKind::Misc) { . let operand_ty = operand.ty(self.body, self.tcx); . let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast"); . let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast"); . if let (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) = (cast_in, cast_out) { . // ptr-to-int casts are not possible in consts and thus not promotable . return Err(Unpromotable); . } . // int-to-ptr casts are fine, they just use the integer value at pointer type. . } . 2,184 ( 0.00%) self.validate_operand(operand)?; . } . . Rvalue::NullaryOp(op, _) => match op { . NullOp::SizeOf => {} . NullOp::AlignOf => {} . }, . . Rvalue::ShallowInitBox(_, _) => return Err(Unpromotable), -- line 515 ---------------------------------------- -- line 578 ---------------------------------------- . . self.validate_operand(lhs)?; . self.validate_operand(rhs)?; . } . . Rvalue::AddressOf(_, place) => { . // We accept `&raw *`, i.e., raw reborrows -- creating a raw pointer is . // no problem, only using it is. 30 ( 0.00%) if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() . { 24 ( 0.00%) let base_ty = place_base.ty(self.body, self.tcx).ty; 12 ( 0.00%) if let ty::Ref(..) = base_ty.kind() { 42 ( 0.00%) return self.validate_place(place_base); . } . } . return Err(Unpromotable); . } . . Rvalue::Ref(_, kind, place) => { . // Special-case reborrows to be more like a copy of the reference. . let mut place_simplified = place.as_ref(); 6,787 ( 0.00%) if let Some((place_base, ProjectionElem::Deref)) = . place_simplified.last_projection() . { 8,094 ( 0.00%) let base_ty = place_base.ty(self.body, self.tcx).ty; 2,698 ( 0.00%) if let ty::Ref(..) = base_ty.kind() { . place_simplified = place_base; . } . } . 19,332 ( 0.00%) self.validate_place(place_simplified)?; . . // Check that the reference is fine (using the original place!). . // (Needs to come after `validate_place` to avoid ICEs.) 14,215 ( 0.00%) self.validate_ref(*kind, place)?; . } . . Rvalue::Aggregate(_, operands) => { . for o in operands { 3,622 ( 0.00%) self.validate_operand(o)?; . } . } . } . . Ok(()) . } . . fn validate_call( -- line 625 ---------------------------------------- -- line 626 ---------------------------------------- . &self, . callee: &Operand<'tcx>, . args: &[Operand<'tcx>], . ) -> Result<(), Unpromotable> { . let fn_ty = callee.ty(self.body, self.tcx); . . // Inside const/static items, we promote all (eligible) function calls. . // Everywhere else, we require `#[rustc_promotable]` on the callee. 209 ( 0.00%) let promote_all_const_fn = matches!( 418 ( 0.00%) self.const_kind, . Some(hir::ConstContext::Static(_) | hir::ConstContext::Const) . ); . if !promote_all_const_fn { 836 ( 0.00%) if let ty::FnDef(def_id, _) = *fn_ty.kind() { . // Never promote runtime `const fn` calls of . // functions without `#[rustc_promotable]`. 627 ( 0.00%) if !self.tcx.is_promotable_const_fn(def_id) { . return Err(Unpromotable); . } . } . } . . let is_const_fn = match *fn_ty.kind() { . ty::FnDef(def_id, _) => self.tcx.is_const_fn_raw(def_id), . _ => false, -- line 650 ---------------------------------------- -- line 663 ---------------------------------------- . } . . // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`. . pub fn validate_candidates( . ccx: &ConstCx<'_, '_>, . temps: &IndexVec, . candidates: &[Candidate], . ) -> Vec { 1,203 ( 0.00%) let validator = Validator { ccx, temps }; . . candidates . .iter() . .copied() 2,923 ( 0.00%) .filter(|&candidate| validator.validate_candidate(candidate).is_ok()) . .collect() . } . . struct Promoter<'a, 'tcx> { . tcx: TyCtxt<'tcx>, . source: &'a mut Body<'tcx>, . promoted: Body<'tcx>, . temps: &'a mut IndexVec, -- line 684 ---------------------------------------- -- line 685 ---------------------------------------- . extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>, . . /// If true, all nested temps are also kept in the . /// source MIR, not moved to the promoted MIR. . keep_original: bool, . } . . impl<'a, 'tcx> Promoter<'a, 'tcx> { 992 ( 0.00%) fn new_block(&mut self) -> BasicBlock { 124 ( 0.00%) let span = self.promoted.span; 620 ( 0.00%) self.promoted.basic_blocks_mut().push(BasicBlockData { . statements: vec![], . terminator: Some(Terminator { . source_info: SourceInfo::outermost(span), . kind: TerminatorKind::Return, . }), . is_cleanup: false, . }) 1,116 ( 0.00%) } . 21,824 ( 0.00%) fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) { 2,728 ( 0.00%) let last = self.promoted.basic_blocks().last().unwrap(); . let data = &mut self.promoted[last]; 10,912 ( 0.00%) data.statements.push(Statement { . source_info: SourceInfo::outermost(span), 21,824 ( 0.00%) kind: StatementKind::Assign(Box::new((Place::from(dest), rvalue))), . }); 21,824 ( 0.00%) } . . fn is_temp_kind(&self, local: Local) -> bool { . self.source.local_kind(local) == LocalKind::Temp . } . . /// Copies the initialization of this temp to the . /// promoted MIR, recursing through temps. . fn promote_temp(&mut self, temp: Local) -> Local { . let old_keep_original = self.keep_original; 18,228 ( 0.00%) let loc = match self.temps[temp] { 10,416 ( 0.00%) TempState::Defined { location, uses } if uses > 0 => { 5,208 ( 0.00%) if uses > 1 { . self.keep_original = true; . } . location . } . state => { . span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state); . } . }; 5,208 ( 0.00%) if !self.keep_original { 5,208 ( 0.00%) self.temps[temp] = TempState::PromotedOut; . } . 5,208 ( 0.00%) let num_stmts = self.source[loc.block].statements.len(); . let new_temp = self.promoted.local_decls.push(LocalDecl::new( 2,604 ( 0.00%) self.source.local_decls[temp].ty, . self.source.local_decls[temp].source_info.span, . )); . . debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original); . . // First, take the Rvalue or Call out of the source MIR, . // or duplicate it, depending on keep_original. 7,812 ( 0.00%) if loc.statement_index < num_stmts { 31,248 ( 0.00%) let (mut rvalue, source_info) = { 5,208 ( 0.00%) let statement = &mut self.source[loc.block].statements[loc.statement_index]; 7,812 ( 0.00%) let rhs = match statement.kind { 2,604 ( 0.00%) StatementKind::Assign(box (_, ref mut rhs)) => rhs, . _ => { . span_bug!( . statement.source_info.span, . "{:?} is not an assignment", . statement . ); . } . }; . 20,832 ( 0.00%) ( 5,208 ( 0.00%) if self.keep_original { . rhs.clone() . } else { . let unit = Rvalue::Use(Operand::Constant(Box::new(Constant { 2,604 ( 0.00%) span: statement.source_info.span, . user_ty: None, 5,208 ( 0.00%) literal: ty::Const::zero_sized(self.tcx, self.tcx.types.unit).into(), . }))); . mem::replace(rhs, unit) . }, 2,604 ( 0.00%) statement.source_info, . ) . }; . 5,208 ( 0.00%) self.visit_rvalue(&mut rvalue, loc); 39,060 ( 0.00%) self.assign(new_temp, rvalue, source_info.span); . } else { . let terminator = if self.keep_original { . self.source[loc.block].terminator().clone() . } else { . let terminator = self.source[loc.block].terminator_mut(); . let target = match terminator.kind { . TerminatorKind::Call { destination: Some((_, target)), .. } => target, . ref kind => { -- line 785 ---------------------------------------- -- line 816 ---------------------------------------- . }; . } . ref kind => { . span_bug!(terminator.source_info.span, "{:?} not promotable", kind); . } . }; . }; . 2,604 ( 0.00%) self.keep_original = old_keep_original; . new_temp . } . . fn promote_candidate(mut self, candidate: Candidate, next_promoted_id: usize) -> Body<'tcx> { 992 ( 0.00%) let def = self.source.source.with_opt_param(); . let mut rvalue = { . let promoted = &mut self.promoted; . let promoted_id = Promoted::new(next_promoted_id); 248 ( 0.00%) let tcx = self.tcx; . let mut promoted_operand = |ty, span| { 124 ( 0.00%) promoted.span = span; 1,240 ( 0.00%) promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span); . . Operand::Constant(Box::new(Constant { . span, . user_ty: None, 496 ( 0.00%) literal: tcx 1,240 ( 0.00%) .mk_const(ty::Const { . ty, . val: ty::ConstKind::Unevaluated(ty::Unevaluated { . def, 496 ( 0.00%) substs: InternalSubsts::for_item(tcx, def.did, |param, _| { 348 ( 0.00%) if let ty::GenericParamDefKind::Lifetime = param.kind { 32 ( 0.00%) tcx.lifetimes.re_erased.into() . } else { 240 ( 0.00%) tcx.mk_param_from_def(param) . } . }), . promoted: Some(promoted_id), . }), . }) . .into(), . })) . }; . let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut(); . let loc = candidate.location; . let statement = &mut blocks[loc.block].statements[loc.statement_index]; 620 ( 0.00%) match statement.kind { . StatementKind::Assign(box ( . _, . Rvalue::Ref(ref mut region, borrow_kind, ref mut place), . )) => { . // Use the underlying local for this (necessarily interior) borrow. 496 ( 0.00%) let ty = local_decls.local_decls()[place.local].ty; 248 ( 0.00%) let span = statement.source_info.span; . 124 ( 0.00%) let ref_ty = tcx.mk_ref( 248 ( 0.00%) tcx.lifetimes.re_erased, 248 ( 0.00%) ty::TypeAndMut { ty, mutbl: borrow_kind.to_mutbl_lossy() }, . ); . 372 ( 0.00%) *region = tcx.lifetimes.re_erased; . 124 ( 0.00%) let mut projection = vec![PlaceElem::Deref]; 124 ( 0.00%) projection.extend(place.projection); 496 ( 0.00%) place.projection = tcx.intern_place_elems(&projection); . . // Create a temp to hold the promoted reference. . // This is because `*r` requires `r` to be a local, . // otherwise we would use the `promoted` directly. . let mut promoted_ref = LocalDecl::new(ref_ty, span); 248 ( 0.00%) promoted_ref.source_info = statement.source_info; 1,240 ( 0.00%) let promoted_ref = local_decls.push(promoted_ref); 372 ( 0.00%) assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref); . 496 ( 0.00%) let promoted_ref_statement = Statement { 496 ( 0.00%) source_info: statement.source_info, . kind: StatementKind::Assign(Box::new(( 372 ( 0.00%) Place::from(promoted_ref), . Rvalue::Use(promoted_operand(ref_ty, span)), . ))), . }; 1,240 ( 0.00%) self.extra_statements.push((loc, promoted_ref_statement)); . 868 ( 0.00%) Rvalue::Ref( 372 ( 0.00%) tcx.lifetimes.re_erased, . borrow_kind, . Place { . local: mem::replace(&mut place.local, promoted_ref), . projection: List::empty(), . }, . ) . } . _ => bug!(), . } . }; . 496 ( 0.00%) assert_eq!(self.new_block(), START_BLOCK); 372 ( 0.00%) self.visit_rvalue( . &mut rvalue, . Location { block: BasicBlock::new(0), statement_index: usize::MAX }, . ); . 124 ( 0.00%) let span = self.promoted.span; 1,240 ( 0.00%) self.assign(RETURN_PLACE, rvalue, span); 620 ( 0.00%) self.promoted . } . } . . /// Replaces all temporaries with their promoted counterparts. . impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { . self.tcx . } . 20,832 ( 0.00%) fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) { 5,918 ( 0.00%) if self.is_temp_kind(*local) { 2,604 ( 0.00%) *local = self.promote_temp(*local); . } 20,832 ( 0.00%) } . } . 3,609 ( 0.00%) pub fn promote_candidates<'tcx>( . body: &mut Body<'tcx>, . tcx: TyCtxt<'tcx>, . mut temps: IndexVec, . candidates: Vec, . ) -> IndexVec> { . // Visit candidates in reverse, in case they're nested. . debug!("promote_candidates({:?})", candidates); . . let mut promotions = IndexVec::new(); . . let mut extra_statements = vec![]; 670 ( 0.00%) for candidate in candidates.into_iter().rev() { . let Location { block, statement_index } = candidate.location; 5,360 ( 0.00%) if let StatementKind::Assign(box (place, _)) = &body[block].statements[statement_index].kind . { 670 ( 0.00%) if let Some(local) = place.as_local() { . if temps[local] == TempState::PromotedOut { . // Already promoted. . continue; . } . } . } . . // Declare return place local so that `mir::Body::new` doesn't complain. 372 ( 0.00%) let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect(); . 620 ( 0.00%) let mut scope = body.source_scopes[body.source_info(candidate.location).scope].clone(); . scope.parent_scope = None; . 1,736 ( 0.00%) let promoted = Body::new( 496 ( 0.00%) body.source, // `promoted` gets filled in below . IndexVec::new(), . IndexVec::from_elem_n(scope, 1), 496 ( 0.00%) initial_locals, . IndexVec::new(), . 0, . vec![], . body.span, . body.generator_kind(), . ); . . let promoter = Promoter { -- line 979 ---------------------------------------- -- line 980 ---------------------------------------- . promoted, . tcx, . source: body, . temps: &mut temps, . extra_statements: &mut extra_statements, . keep_original: false, . }; . 1,488 ( 0.00%) let mut promoted = promoter.promote_candidate(candidate, promotions.len()); 248 ( 0.00%) promoted.source.promoted = Some(promotions.next_index()); . promotions.push(promoted); . } . . // Insert each of `extra_statements` before its indicated location, which . // has to be done in reverse location order, to not invalidate the rest. . extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc)); 2,348 ( 0.00%) for (loc, statement) in extra_statements { 1,240 ( 0.00%) body[loc.block].statements.insert(loc.statement_index, statement); . } . . // Eliminate assignments to, and drops of promoted temps. 1,395 ( 0.00%) let promoted = |index: Local| temps[index] == TempState::PromotedOut; . for block in body.basic_blocks_mut() { 100,096 ( 0.00%) block.statements.retain(|statement| match &statement.kind { 6,384 ( 0.00%) StatementKind::Assign(box (place, _)) => { 6,384 ( 0.00%) if let Some(index) = place.as_local() { . !promoted(index) . } else { . true . } . } . StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => { 12,248 ( 0.00%) !promoted(*index) . } . _ => true, . }); . let terminator = block.terminator_mut(); 6,292 ( 0.00%) if let TerminatorKind::Drop { place, target, .. } = &terminator.kind { 593 ( 0.00%) if let Some(index) = place.as_local() { 593 ( 0.00%) if promoted(index) { . terminator.kind = TerminatorKind::Goto { target: *target }; . } . } . } . } . . promotions 3,208 ( 0.00%) } . . /// This function returns `true` if the function being called in the array . /// repeat expression is a `const` function. . pub fn is_const_fn_in_array_repeat_expression<'tcx>( . ccx: &ConstCx<'_, 'tcx>, . place: &Place<'tcx>, . body: &Body<'tcx>, . ) -> bool { -- line 1035 ---------------------------------------- 317,376 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_resolve/src/late.rs -------------------------------------------------------------------------------- Ir -- line 141 ---------------------------------------- . /// parameters. . ConstParamTyRibKind, . } . . impl RibKind<'_> { . /// Whether this rib kind contains generic parameters, as opposed to local . /// variables. . crate fn contains_params(&self) -> bool { 202,279 ( 0.00%) match self { . NormalRibKind . | ClosureOrAsyncRibKind . | FnItemRibKind . | ConstantItemRibKind(..) . | ModuleRibKind(_) . | MacroDefinition(_) . | ConstParamTyRibKind => false, . AssocItemRibKind | ItemRibKind(_) | ForwardGenericParamBanRibKind => true, -- line 157 ---------------------------------------- -- line 174 ---------------------------------------- . #[derive(Debug)] . crate struct Rib<'a, R = Res> { . pub bindings: IdentMap, . pub kind: RibKind<'a>, . } . . impl<'a, R> Rib<'a, R> { . fn new(kind: RibKind<'a>) -> Rib<'a, R> { 4,226 ( 0.00%) Rib { bindings: Default::default(), kind } . } . } . . #[derive(Copy, Clone, PartialEq, Eq, Debug)] . crate enum AliasPossibility { . No, . Maybe, . } -- line 190 ---------------------------------------- -- line 212 ---------------------------------------- . match self { . PathSource::Type | PathSource::Trait(_) | PathSource::Struct => TypeNS, . PathSource::Expr(..) | PathSource::Pat | PathSource::TupleStruct(..) => ValueNS, . PathSource::TraitItem(ns) => ns, . } . } . . fn defer_to_typeck(self) -> bool { 12,091 ( 0.00%) match self { . PathSource::Type . | PathSource::Expr(..) . | PathSource::Pat . | PathSource::Struct . | PathSource::TupleStruct(..) => true, . PathSource::Trait(_) | PathSource::TraitItem(..) => false, . } . } -- line 228 ---------------------------------------- -- line 268 ---------------------------------------- . } . } . . fn is_call(self) -> bool { . matches!(self, PathSource::Expr(Some(&Expr { kind: ExprKind::Call(..), .. }))) . } . . crate fn is_expected(self, res: Res) -> bool { 43,427 ( 0.00%) match self { 43,762 ( 0.00%) PathSource::Type => matches!( 11,128 ( 0.00%) res, . Res::Def( . DefKind::Struct . | DefKind::Union . | DefKind::Enum . | DefKind::Trait . | DefKind::TraitAlias . | DefKind::TyAlias . | DefKind::AssocTy . | DefKind::TyParam . | DefKind::OpaqueTy . | DefKind::ForeignTy, . _, . ) | Res::PrimTy(..) . | Res::SelfTy(..) . ), 327 ( 0.00%) PathSource::Trait(AliasPossibility::No) => matches!(res, Res::Def(DefKind::Trait, _)), . PathSource::Trait(AliasPossibility::Maybe) => { 784 ( 0.00%) matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _)) . } 8,501 ( 0.00%) PathSource::Expr(..) => matches!( 3,909 ( 0.00%) res, . Res::Def( . DefKind::Ctor(_, CtorKind::Const | CtorKind::Fn) . | DefKind::Const . | DefKind::Static . | DefKind::Fn . | DefKind::AssocFn . | DefKind::AssocConst . | DefKind::ConstParam, . _, . ) | Res::Local(..) . | Res::SelfCtor(..) . ), 108 ( 0.00%) PathSource::Pat => matches!( 72 ( 0.00%) res, . Res::Def( . DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::AssocConst, . _, . ) | Res::SelfCtor(..) . ), . PathSource::TupleStruct(..) => res.expected_in_tuple_struct_pat(), 1,096 ( 0.00%) PathSource::Struct => matches!( 822 ( 0.00%) res, . Res::Def( . DefKind::Struct . | DefKind::Union . | DefKind::Variant . | DefKind::TyAlias . | DefKind::AssocTy, . _, . ) | Res::SelfTy(..) . ), . PathSource::TraitItem(ns) => match res { . Res::Def(DefKind::AssocConst | DefKind::AssocFn, _) if ns == ValueNS => true, . Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true, . _ => false, . }, . } 8,597 ( 0.00%) } . . fn error_code(self, has_unexpected_resolution: bool) -> DiagnosticId { . use rustc_errors::error_code; . match (self, has_unexpected_resolution) { . (PathSource::Trait(_), true) => error_code!(E0404), . (PathSource::Trait(_), false) => error_code!(E0405), . (PathSource::Type, true) => error_code!(E0573), . (PathSource::Type, false) => error_code!(E0412), -- line 345 ---------------------------------------- -- line 350 ---------------------------------------- . (PathSource::Pat | PathSource::TupleStruct(..), true) => error_code!(E0532), . (PathSource::Pat | PathSource::TupleStruct(..), false) => error_code!(E0531), . (PathSource::TraitItem(..), true) => error_code!(E0575), . (PathSource::TraitItem(..), false) => error_code!(E0576), . } . } . } . 2 ( 0.00%) #[derive(Default)] . struct DiagnosticMetadata<'ast> { . /// The current trait's associated items' ident, used for diagnostic suggestions. . current_trait_assoc_items: Option<&'ast [P]>, . . /// The current self type if inside an impl (used for better errors). . current_self_type: Option, . . /// The current self item if inside an ADT (used for better errors). -- line 366 ---------------------------------------- -- line 434 ---------------------------------------- . fn visit_attribute(&mut self, _: &'ast Attribute) { . // We do not want to resolve expressions that appear in attributes, . // as they do not correspond to actual code. . } . fn visit_item(&mut self, item: &'ast Item) { . let prev = replace(&mut self.diagnostic_metadata.current_item, Some(item)); . // Always report errors in items we just entered. . let old_ignore = replace(&mut self.in_func_body, false); 892 ( 0.00%) self.resolve_item(item); 446 ( 0.00%) self.in_func_body = old_ignore; 447 ( 0.00%) self.diagnostic_metadata.current_item = prev; . } 1,162 ( 0.00%) fn visit_arm(&mut self, arm: &'ast Arm) { . self.resolve_arm(arm); 996 ( 0.00%) } 5,391 ( 0.00%) fn visit_block(&mut self, block: &'ast Block) { . self.resolve_block(block); 4,792 ( 0.00%) } . fn visit_anon_const(&mut self, constant: &'ast AnonConst) { . // We deal with repeat expressions explicitly in `resolve_expr`. . self.resolve_anon_const(constant, IsRepeatExpr::No); . } . fn visit_expr(&mut self, expr: &'ast Expr) { 426,304 ( 0.01%) self.resolve_expr(expr, None); . } 1,998 ( 0.00%) fn visit_local(&mut self, local: &'ast Local) { 444 ( 0.00%) let local_spans = match local.pat.kind { . // We check for this to avoid tuple struct fields. . PatKind::Wild => None, . _ => Some(( . local.pat.span, . local.ty.as_ref().map(|ty| ty.span), 820 ( 0.00%) local.kind.init().map(|init| init.span), . )), . }; . let original = replace(&mut self.diagnostic_metadata.current_let_binding, local_spans); . self.resolve_local(local); 888 ( 0.00%) self.diagnostic_metadata.current_let_binding = original; 1,776 ( 0.00%) } 14,520 ( 0.00%) fn visit_ty(&mut self, ty: &'ast Ty) { 3,630 ( 0.00%) let prev = self.diagnostic_metadata.current_trait_object; 7,699 ( 0.00%) match ty.kind { 2,502 ( 0.00%) TyKind::Path(ref qself, ref path) => { 7,506 ( 0.00%) self.smart_resolve_path(ty.id, qself.as_ref(), path, PathSource::Type); . } . TyKind::ImplicitSelf => { . let self_ty = Ident::with_dummy_span(kw::SelfUpper); . let res = self 152 ( 0.00%) .resolve_ident_in_lexical_scope(self_ty, TypeNS, Some(ty.id), ty.span) 912 ( 0.00%) .map_or(Res::Err, |d| d.res()); 1,672 ( 0.00%) self.r.record_partial_res(ty.id, PartialRes::new(res)); . } . TyKind::TraitObject(ref bounds, ..) => { 3 ( 0.00%) self.diagnostic_metadata.current_trait_object = Some(&bounds[..]); . } . _ => (), . } 5,445 ( 0.00%) visit::walk_ty(self, ty); 3,630 ( 0.00%) self.diagnostic_metadata.current_trait_object = prev; 12,705 ( 0.00%) } . fn visit_poly_trait_ref(&mut self, tref: &'ast PolyTraitRef, m: &'ast TraitBoundModifier) { 99 ( 0.00%) self.smart_resolve_path( 132 ( 0.00%) tref.trait_ref.ref_id, . None, 6 ( 0.00%) &tref.trait_ref.path, 51 ( 0.00%) PathSource::Trait(AliasPossibility::Maybe), . ); 80 ( 0.00%) visit::walk_poly_trait_ref(self, tref, m); . } . fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) { . match foreign_item.kind { . ForeignItemKind::Fn(box Fn { ref generics, .. }) . | ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => { . self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { . visit::walk_foreign_item(this, foreign_item); . }); -- line 509 ---------------------------------------- -- line 513 ---------------------------------------- . visit::walk_foreign_item(this, foreign_item); . }); . } . ForeignItemKind::MacCall(..) => { . visit::walk_foreign_item(self, foreign_item); . } . } . } 2,781 ( 0.00%) fn visit_fn(&mut self, fn_kind: FnKind<'ast>, sp: Span, _: NodeId) { 5,320 ( 0.00%) let rib_kind = match fn_kind { . // Bail if the function is foreign, and thus cannot validly have . // a body, or if there's no body for some other reason. . FnKind::Fn(FnCtxt::Foreign, _, sig, ..) | FnKind::Fn(_, _, sig, .., None) => { . // We don't need to deal with patterns in parameters, because . // they are not possible for foreign or bodiless functions. . self.visit_fn_header(&sig.header); . visit::walk_fn_decl(self, &sig.decl); . return; . } . FnKind::Fn(FnCtxt::Free, ..) => FnItemRibKind, . FnKind::Fn(FnCtxt::Assoc(_), ..) => NormalRibKind, . FnKind::Closure(..) => ClosureOrAsyncRibKind, . }; 2,156 ( 0.00%) let previous_value = self.diagnostic_metadata.current_function; 616 ( 0.00%) if matches!(fn_kind, FnKind::Fn(..)) { 2,037 ( 0.00%) self.diagnostic_metadata.current_function = Some((fn_kind, sp)); . } . debug!("(resolving function) entering function"); 924 ( 0.00%) let declaration = fn_kind.decl(); . . // Create a value rib for the function. . self.with_rib(ValueNS, rib_kind, |this| { . // Create a label rib for the function. . this.with_label_rib(rib_kind, |this| { . // Add each argument to the rib. 616 ( 0.00%) this.resolve_params(&declaration.inputs); . . visit::walk_fn_ret_ty(this, &declaration.output); . . // Ignore errors in function bodies if this is rustdoc . // Be sure not to set this until the function signature has been resolved. . let previous_state = replace(&mut this.in_func_body, true); . // Resolve the function body, potentially inside the body of an async closure 616 ( 0.00%) match fn_kind { 1,455 ( 0.00%) FnKind::Fn(.., body) => walk_list!(this, visit_block, body), 17 ( 0.00%) FnKind::Closure(_, body) => this.visit_expr(body), . }; . . debug!("(resolving function) leaving function"); 308 ( 0.00%) this.in_func_body = previous_state; . }) . }); 1,848 ( 0.00%) self.diagnostic_metadata.current_function = previous_value; 2,464 ( 0.00%) } . 3,552 ( 0.00%) fn visit_generics(&mut self, generics: &'ast Generics) { . // For type parameter defaults, we have to ban access . // to following type parameters, as the InternalSubsts can only . // provide previous type parameters as they're built. We . // put all the parameters on the ban list and then remove . // them one by one as they are processed and become available. . let mut forward_ty_ban_rib = Rib::new(ForwardGenericParamBanRibKind); . let mut forward_const_ban_rib = Rib::new(ForwardGenericParamBanRibKind); . for param in generics.params.iter() { 1,661 ( 0.00%) match param.kind { . GenericParamKind::Type { .. } => { . forward_ty_ban_rib . .bindings 116 ( 0.00%) .insert(Ident::with_dummy_span(param.ident.name), Res::Err); . } . GenericParamKind::Const { .. } => { . forward_const_ban_rib . .bindings . .insert(Ident::with_dummy_span(param.ident.name), Res::Err); . } . GenericParamKind::Lifetime => {} . } -- line 589 ---------------------------------------- -- line 593 ---------------------------------------- . // another type parameter. For ADTs, we consider it . // well-defined only after all of the ADT type parameters have . // been provided. Therefore, we do not allow use of `Self` . // anywhere in ADT type parameter defaults. . // . // (We however cannot ban `Self` for defaults on *all* generic . // lists; e.g. trait generics can usefully refer to `Self`, . // such as in the case of `trait Add`.) 444 ( 0.00%) if self.diagnostic_metadata.current_self_item.is_some() { . // (`Some` if + only if we are in ADT's generics.) . forward_ty_ban_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), Res::Err); . } . . for param in &generics.params { 772 ( 0.00%) match param.kind { . GenericParamKind::Lifetime => self.visit_generic_param(param), . GenericParamKind::Type { ref default } => { . for bound in ¶m.bounds { . self.visit_param_bound(bound); . } . 696 ( 0.00%) if let Some(ref ty) = default { . self.ribs[TypeNS].push(forward_ty_ban_rib); . self.ribs[ValueNS].push(forward_const_ban_rib); . self.visit_ty(ty); . forward_const_ban_rib = self.ribs[ValueNS].pop().unwrap(); . forward_ty_ban_rib = self.ribs[TypeNS].pop().unwrap(); . } . . // Allow all following defaults to refer to this type parameter. 348 ( 0.00%) forward_ty_ban_rib.bindings.remove(&Ident::with_dummy_span(param.ident.name)); . } . GenericParamKind::Const { ref ty, kw_span: _, ref default } => { . // Const parameters can't have param bounds. . assert!(param.bounds.is_empty()); . . self.ribs[TypeNS].push(Rib::new(ConstParamTyRibKind)); . self.ribs[ValueNS].push(Rib::new(ConstParamTyRibKind)); . self.visit_ty(ty); -- line 631 ---------------------------------------- -- line 645 ---------------------------------------- . .bindings . .remove(&Ident::with_dummy_span(param.ident.name)); . } . } . } . for p in &generics.where_clause.predicates { . self.visit_where_predicate(p); . } 3,552 ( 0.00%) } . 3,456 ( 0.00%) fn visit_generic_arg(&mut self, arg: &'ast GenericArg) { . debug!("visit_generic_arg({:?})", arg); . let prev = replace(&mut self.diagnostic_metadata.currently_processing_generics, true); 1,954 ( 0.00%) match arg { . GenericArg::Type(ref ty) => { . // We parse const arguments as path types as we cannot distinguish them during . // parsing. We try to resolve that ambiguity by attempting resolution the type . // namespace first, and if that fails we try again in the value namespace. If . // resolution in the value namespace succeeds, we have an generic const argument on . // our hands. 658 ( 0.00%) if let TyKind::Path(ref qself, ref path) = ty.kind { . // We cannot disambiguate multi-segment paths right now as that requires type . // checking. 941 ( 0.00%) if path.segments.len() == 1 && path.segments[0].args.is_none() { . let mut check_ns = |ns| { . self.resolve_ident_in_lexical_scope( 466 ( 0.00%) path.segments[0].ident, . ns, . None, . path.span, . ) . .is_some() . }; 233 ( 0.00%) if !check_ns(TypeNS) && check_ns(ValueNS) { . // This must be equivalent to `visit_anon_const`, but we cannot call it . // directly due to visitor lifetimes so we have to copy-paste some code. . // . // Note that we might not be inside of an repeat expression here, . // but considering that `IsRepeatExpr` is only relevant for . // non-trivial constants this is doesn't matter. . self.with_constant_rib(IsRepeatExpr::No, true, None, |this| { . this.smart_resolve_path( -- line 686 ---------------------------------------- -- line 697 ---------------------------------------- . }); . . self.diagnostic_metadata.currently_processing_generics = prev; . return; . } . } . } . 1,316 ( 0.00%) self.visit_ty(ty); . } . GenericArg::Lifetime(lt) => self.visit_lifetime(lt), . GenericArg::Const(ct) => self.visit_anon_const(ct), . } . self.diagnostic_metadata.currently_processing_generics = prev; 3,456 ( 0.00%) } . . fn visit_where_predicate(&mut self, p: &'ast WherePredicate) { . debug!("visit_where_predicate {:?}", p); . let previous_value = . replace(&mut self.diagnostic_metadata.current_where_predicate, Some(p)); 108 ( 0.00%) visit::walk_where_predicate(self, p); 20 ( 0.00%) self.diagnostic_metadata.current_where_predicate = previous_value; . } . } . . impl<'a: 'ast, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { 9 ( 0.00%) fn new(resolver: &'b mut Resolver<'a>) -> LateResolutionVisitor<'a, 'b, 'ast> { . // During late resolution we only track the module component of the parent scope, . // although it may be useful to track other components as well for diagnostics. 1 ( 0.00%) let graph_root = resolver.graph_root; . let parent_scope = ParentScope::module(graph_root, resolver); . let start_rib_kind = ModuleRibKind(graph_root); 30 ( 0.00%) LateResolutionVisitor { . r: resolver, . parent_scope, . ribs: PerNS { 2 ( 0.00%) value_ns: vec![Rib::new(start_rib_kind)], 2 ( 0.00%) type_ns: vec![Rib::new(start_rib_kind)], 2 ( 0.00%) macro_ns: vec![Rib::new(start_rib_kind)], . }, . label_ribs: Vec::new(), . current_trait_ref: None, . diagnostic_metadata: DiagnosticMetadata::default(), . // errors at module scope should always be reported . in_func_body: false, . } 9 ( 0.00%) } . . fn resolve_ident_in_lexical_scope( . &mut self, . ident: Ident, . ns: Namespace, . record_used_id: Option, . path_span: Span, . ) -> Option> { 12,612 ( 0.00%) self.r.resolve_ident_in_lexical_scope( . ident, . ns, 1,246 ( 0.00%) &self.parent_scope, . record_used_id, . path_span, . &self.ribs[ns], . ) . } . . fn resolve_path( . &mut self, . path: &[Segment], . opt_ns: Option, // `None` indicates a module path in import . record_used: bool, . path_span: Span, . crate_lint: CrateLint, . ) -> PathResult<'a> { 68,289 ( 0.00%) self.r.resolve_path_with_ribs( . path, . opt_ns, 109 ( 0.00%) &self.parent_scope, . record_used, . path_span, . crate_lint, 109 ( 0.00%) Some(&self.ribs), . ) . } . . // AST resolution . // . // We maintain a list of value ribs and type ribs. . // . // Simultaneously, we keep track of the current position in the module -- line 785 ---------------------------------------- -- line 798 ---------------------------------------- . . /// Do some `work` within a new innermost rib of the given `kind` in the given namespace (`ns`). . fn with_rib( . &mut self, . ns: Namespace, . kind: RibKind<'a>, . work: impl FnOnce(&mut Self) -> T, . ) -> T { 1,217 ( 0.00%) self.ribs[ns].push(Rib::new(kind)); . let ret = work(self); . self.ribs[ns].pop(); . ret . } . . fn with_scope(&mut self, id: NodeId, f: impl FnOnce(&mut Self) -> T) -> T { 144 ( 0.00%) if let Some(module) = self.r.get_module(self.r.local_def_id(id).to_def_id()) { . // Move down in the graph. . let orig_module = replace(&mut self.parent_scope.module, module); . self.with_rib(ValueNS, ModuleRibKind(module), |this| { . this.with_rib(TypeNS, ModuleRibKind(module), |this| { . let ret = f(this); 18 ( 0.00%) this.parent_scope.module = orig_module; . ret . }) . }) . } else { . f(self) . } . } . -- line 827 ---------------------------------------- -- line 898 ---------------------------------------- . } . } . . true . } . . fn resolve_adt(&mut self, item: &'ast Item, generics: &'ast Generics) { . debug!("resolve_adt"); 44 ( 0.00%) self.with_current_self_item(item, |this| { . this.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { . let item_def_id = this.r.local_def_id(item.id).to_def_id(); . this.with_self_rib(Res::SelfTy(None, Some((item_def_id, false))), |this| { 66 ( 0.00%) visit::walk_item(this, item); . }); . }); . }); . } . 747 ( 0.00%) fn future_proof_import(&mut self, use_tree: &UseTree) { . let segments = &use_tree.prefix.segments; 83 ( 0.00%) if !segments.is_empty() { 166 ( 0.00%) let ident = segments[0].ident; 896 ( 0.00%) if ident.is_path_segment_keyword() || ident.span.rust_2015() { . return; . } . . let nss = match use_tree.kind { . UseTreeKind::Simple(..) if segments.len() == 1 => &[TypeNS, ValueNS][..], . _ => &[TypeNS], . }; . let report_error = |this: &Self, ns| { -- line 928 ---------------------------------------- -- line 952 ---------------------------------------- . None => {} . } . } . } else if let UseTreeKind::Nested(use_trees) = &use_tree.kind { . for (use_tree, _) in use_trees { . self.future_proof_import(use_tree); . } . } 664 ( 0.00%) } . 3,568 ( 0.00%) fn resolve_item(&mut self, item: &'ast Item) { . let name = item.ident.name; . debug!("(resolving item) resolving {} ({:?})", name, item.kind); . 2,676 ( 0.00%) match item.kind { . ItemKind::TyAlias(box TyAlias { ref generics, .. }) . | ItemKind::Fn(box Fn { ref generics, .. }) => { 404 ( 0.00%) self.compute_num_lifetime_params(item.id, generics); . self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { 303 ( 0.00%) visit::walk_item(this, item) . }); . } . 10 ( 0.00%) ItemKind::Enum(_, ref generics) . | ItemKind::Struct(_, ref generics) . | ItemKind::Union(_, ref generics) => { 110 ( 0.00%) self.compute_num_lifetime_params(item.id, generics); . self.resolve_adt(item, generics); . } . . ItemKind::Impl(box Impl { 121 ( 0.00%) ref generics, . ref of_trait, . ref self_ty, . items: ref impl_items, . .. . }) => { 484 ( 0.00%) self.compute_num_lifetime_params(item.id, generics); 121 ( 0.00%) self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items); . } . 2 ( 0.00%) ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => { 8 ( 0.00%) self.compute_num_lifetime_params(item.id, generics); . // Create a new rib for the trait-wide type parameters. . self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { 4 ( 0.00%) let local_def_id = this.r.local_def_id(item.id).to_def_id(); . this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| { 4 ( 0.00%) this.visit_generics(generics); . walk_list!(this, visit_param_bound, bounds); . 9 ( 0.00%) let walk_assoc_item = |this: &mut Self, generics, item| { . this.with_generic_param_rib(generics, AssocItemRibKind, |this| { 4 ( 0.00%) visit::walk_assoc_item(this, item, AssocCtxt::Trait) . }); 8 ( 0.00%) }; . . this.with_trait_items(items, |this| { . for item in items { 8 ( 0.00%) match &item.kind { . AssocItemKind::Const(_, ty, default) => { . this.visit_ty(ty); . // Only impose the restrictions of `ConstRibKind` for an . // actual constant expression in a provided default. . if let Some(expr) = default { . // We allow arbitrary const expressions inside of associated consts, . // even if they are potentially not const evaluatable. . // -- line 1018 ---------------------------------------- -- line 1021 ---------------------------------------- . this.with_constant_rib( . IsRepeatExpr::No, . true, . None, . |this| this.visit_expr(expr), . ); . } . } 2 ( 0.00%) AssocItemKind::Fn(box Fn { generics, .. }) => { 3 ( 0.00%) walk_assoc_item(this, generics, item); . } . AssocItemKind::TyAlias(box TyAlias { generics, .. }) => { . walk_assoc_item(this, generics, item); . } . AssocItemKind::MacCall(_) => { . panic!("unexpanded macro in resolve!") . } . }; -- line 1038 ---------------------------------------- -- line 1050 ---------------------------------------- . this.with_self_rib(Res::SelfTy(Some(local_def_id), None), |this| { . this.visit_generics(generics); . walk_list!(this, visit_param_bound, bounds); . }); . }); . } . . ItemKind::Mod(..) | ItemKind::ForeignMod(_) => { 18 ( 0.00%) self.with_scope(item.id, |this| { 54 ( 0.00%) visit::walk_item(this, item); . }); . } . 372 ( 0.00%) ItemKind::Static(ref ty, _, ref expr) | ItemKind::Const(_, ref ty, ref expr) => { . self.with_item_rib(HasGenericParams::No, |this| { 93 ( 0.00%) this.visit_ty(ty); 186 ( 0.00%) if let Some(expr) = expr { 558 ( 0.00%) let constant_item_kind = match item.kind { . ItemKind::Const(..) => ConstantItemKind::Const, . ItemKind::Static(..) => ConstantItemKind::Static, . _ => unreachable!(), . }; . // We already forbid generic params because of the above item rib, . // so it doesn't matter whether this is a trivial constant. . this.with_constant_rib( . IsRepeatExpr::No, . true, 465 ( 0.00%) Some((item.ident, constant_item_kind)), . |this| this.visit_expr(expr), . ); . } . }); . } . 83 ( 0.00%) ItemKind::Use(ref use_tree) => { 747 ( 0.00%) self.future_proof_import(use_tree); . } . . ItemKind::ExternCrate(..) | ItemKind::MacroDef(..) => { . // do nothing, these are just around to be encoded . } . . ItemKind::GlobalAsm(_) => { . visit::walk_item(self, item); . } . . ItemKind::MacCall(_) => panic!("unexpanded macro in resolve!"), . } 2,904 ( 0.00%) } . . fn with_generic_param_rib<'c, F>(&'c mut self, generics: &'c Generics, kind: RibKind<'a>, f: F) . where . F: FnOnce(&mut Self), . { . debug!("with_generic_param_rib"); 444 ( 0.00%) let mut function_type_rib = Rib::new(kind); . let mut function_value_rib = Rib::new(kind); . let mut seen_bindings = FxHashMap::default(); . . // We also can't shadow bindings from the parent item . if let AssocItemRibKind = kind { 1 ( 0.00%) let mut add_bindings_for_ns = |ns| { . let parent_rib = self.ribs[ns] . .iter() 988 ( 0.00%) .rfind(|r| matches!(r.kind, ItemRibKind(_))) . .expect("associated item outside of an item"); . seen_bindings 524 ( 0.00%) .extend(parent_rib.bindings.iter().map(|(ident, _)| (*ident, ident.span))); . }; . add_bindings_for_ns(ValueNS); . add_bindings_for_ns(TypeNS); . } . . for param in &generics.params { 995 ( 0.00%) if let GenericParamKind::Lifetime { .. } = param.kind { . continue; . } . 494 ( 0.00%) let ident = param.ident.normalize_to_macros_2_0(); . debug!("with_generic_param_rib: {}", param.id); . 232 ( 0.00%) match seen_bindings.entry(ident) { . Entry::Occupied(entry) => { . let span = *entry.get(); . let err = ResolutionError::NameAlreadyUsedInParameterList(ident.name, span); . self.report_error(param.ident.span, err); . } . Entry::Vacant(entry) => { 116 ( 0.00%) entry.insert(param.ident.span); . } . } . . // Plain insert (no renaming). 580 ( 0.00%) let (rib, def_kind) = match param.kind { . GenericParamKind::Type { .. } => (&mut function_type_rib, DefKind::TyParam), . GenericParamKind::Const { .. } => (&mut function_value_rib, DefKind::ConstParam), . _ => unreachable!(), . }; 464 ( 0.00%) let res = Res::Def(def_kind, self.r.local_def_id(param.id).to_def_id()); 348 ( 0.00%) self.r.record_partial_res(param.id, PartialRes::new(res)); . rib.bindings.insert(ident, res); . } . 5,964 ( 0.00%) self.ribs[ValueNS].push(function_value_rib); 3,552 ( 0.00%) self.ribs[TypeNS].push(function_type_rib); . . f(self); . . self.ribs[TypeNS].pop(); . self.ribs[ValueNS].pop(); . } . . fn with_label_rib(&mut self, kind: RibKind<'a>, f: impl FnOnce(&mut Self)) { 604 ( 0.00%) self.label_ribs.push(Rib::new(kind)); . f(self); . self.label_ribs.pop(); . } . . fn with_item_rib(&mut self, has_generic_params: HasGenericParams, f: impl FnOnce(&mut Self)) { . let kind = ItemRibKind(has_generic_params); . self.with_rib(ValueNS, kind, |this| this.with_rib(TypeNS, kind, f)) . } -- line 1171 ---------------------------------------- -- line 1195 ---------------------------------------- . }, . ) . }); . } . . fn with_current_self_type(&mut self, self_type: &Ty, f: impl FnOnce(&mut Self) -> T) -> T { . // Handle nested impls (inside fn bodies) . let previous_value = 121 ( 0.00%) replace(&mut self.diagnostic_metadata.current_self_type, Some(self_type.clone())); . let result = f(self); 3,267 ( 0.00%) self.diagnostic_metadata.current_self_type = previous_value; . result . } . . fn with_current_self_item(&mut self, self_item: &Item, f: impl FnOnce(&mut Self) -> T) -> T { . let previous_value = . replace(&mut self.diagnostic_metadata.current_self_item, Some(self_item.id)); . let result = f(self); 44 ( 0.00%) self.diagnostic_metadata.current_self_item = previous_value; . result . } . . /// When evaluating a `trait` use its associated types' idents for suggestions in E0412. . fn with_trait_items( . &mut self, . trait_items: &'ast [P], . f: impl FnOnce(&mut Self) -> T, . ) -> T { . let trait_assoc_items = . replace(&mut self.diagnostic_metadata.current_trait_assoc_items, Some(&trait_items)); . let result = f(self); 6 ( 0.00%) self.diagnostic_metadata.current_trait_assoc_items = trait_assoc_items; . result . } . . /// This is called to resolve a trait reference from an `impl` (i.e., `impl Trait for Foo`). 1,089 ( 0.00%) fn with_optional_trait_ref( . &mut self, . opt_trait_ref: Option<&TraitRef>, . f: impl FnOnce(&mut Self, Option) -> T, . ) -> T { 121 ( 0.00%) let mut new_val = None; . let mut new_id = None; 242 ( 0.00%) if let Some(trait_ref) = opt_trait_ref { . let path: Vec<_> = Segment::from_path(&trait_ref.path); 1,635 ( 0.00%) let res = self.smart_resolve_path_fragment( 109 ( 0.00%) trait_ref.ref_id, . None, . &path, 109 ( 0.00%) trait_ref.path.span, 109 ( 0.00%) PathSource::Trait(AliasPossibility::No), . CrateLint::SimplePath(trait_ref.ref_id), . ); . let res = res.base_res(); 109 ( 0.00%) if res != Res::Err { 1,417 ( 0.00%) if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.resolve_path( . &path, . Some(TypeNS), . true, . trait_ref.path.span, 109 ( 0.00%) CrateLint::SimplePath(trait_ref.ref_id), . ) { . new_id = Some(res.def_id()); 1,090 ( 0.00%) new_val = Some((module, trait_ref.clone())); . } . } . } . let original_trait_ref = replace(&mut self.current_trait_ref, new_val); 847 ( 0.00%) let result = f(self, new_id); 2,178 ( 0.00%) self.current_trait_ref = original_trait_ref; . result 968 ( 0.00%) } . . fn with_self_rib_ns(&mut self, ns: Namespace, self_res: Res, f: impl FnOnce(&mut Self)) { . let mut self_type_rib = Rib::new(NormalRibKind); . . // Plain insert (no renaming, since types are not currently hygienic) . self_type_rib.bindings.insert(Ident::with_dummy_span(kw::SelfUpper), self_res); 3,120 ( 0.00%) self.ribs[ns].push(self_type_rib); . f(self); . self.ribs[ns].pop(); . } . . fn with_self_rib(&mut self, self_res: Res, f: impl FnOnce(&mut Self)) { . self.with_self_rib_ns(TypeNS, self_res, f) . } . -- line 1281 ---------------------------------------- -- line 1288 ---------------------------------------- . impl_items: &'ast [P], . ) { . debug!("resolve_implementation"); . // If applicable, create a rib for the type parameters. . self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| { . // Dummy self type for better errors if `Self` is used in the trait path. . this.with_self_rib(Res::SelfTy(None, None), |this| { . // Resolve the trait reference, if necessary. 1,210 ( 0.00%) this.with_optional_trait_ref(opt_trait_reference.as_ref(), |this, trait_id| { 242 ( 0.00%) let item_def_id = this.r.local_def_id(item_id); . . // Register the trait definitions from here. 242 ( 0.00%) if let Some(trait_id) = trait_id { 436 ( 0.00%) this.r.trait_impls.entry(trait_id).or_default().push(item_def_id); . } . . let item_def_id = item_def_id.to_def_id(); 121 ( 0.00%) this.with_self_rib(Res::SelfTy(trait_id, Some((item_def_id, false))), |this| { 121 ( 0.00%) if let Some(trait_ref) = opt_trait_reference.as_ref() { . // Resolve type arguments in the trait path. . visit::walk_trait_ref(this, trait_ref); . } . // Resolve the self type. 363 ( 0.00%) this.visit_ty(self_type); . // Resolve the generic parameters. 121 ( 0.00%) this.visit_generics(generics); . // Resolve the items within the impl. . this.with_current_self_type(self_type, |this| { . this.with_self_rib_ns(ValueNS, Res::SelfCtor(item_def_id), |this| { . debug!("resolve_implementation with_self_rib_ns(ValueNS, ...)"); 121 ( 0.00%) for item in impl_items { . use crate::ResolutionError::*; 1,182 ( 0.00%) match &item.kind { . AssocItemKind::Const(_default, _ty, _expr) => { . debug!("resolve_implementation AssocItemKind::Const"); . // If this is a trait impl, ensure the const . // exists in trait . this.check_trait_item( . item.id, . item.ident, . &item.kind, -- line 1328 ---------------------------------------- -- line 1344 ---------------------------------------- . visit::walk_assoc_item( . this, . item, . AssocCtxt::Impl, . ) . }, . ); . } 191 ( 0.00%) AssocItemKind::Fn(box Fn { generics, .. }) => { . debug!("resolve_implementation AssocItemKind::Fn"); . // We also need a new scope for the impl item type parameters. . this.with_generic_param_rib( . generics, . AssocItemRibKind, . |this| { . // If this is a trait impl, ensure the method . // exists in trait . this.check_trait_item( 191 ( 0.00%) item.id, 382 ( 0.00%) item.ident, . &item.kind, . ValueNS, 573 ( 0.00%) item.span, . |i, s, c| MethodNotMemberOfTrait(i, s, c), . ); . 382 ( 0.00%) visit::walk_assoc_item( . this, . item, . AssocCtxt::Impl, . ) . }, . ); . } . AssocItemKind::TyAlias(box TyAlias { 6 ( 0.00%) generics, .. . }) => { . debug!("resolve_implementation AssocItemKind::TyAlias"); . // We also need a new scope for the impl item type parameters. . this.with_generic_param_rib( . generics, . AssocItemRibKind, . |this| { . // If this is a trait impl, ensure the type . // exists in trait . this.check_trait_item( 6 ( 0.00%) item.id, 12 ( 0.00%) item.ident, . &item.kind, . TypeNS, 18 ( 0.00%) item.span, . |i, s, c| TypeNotMemberOfTrait(i, s, c), . ); . 12 ( 0.00%) visit::walk_assoc_item( . this, . item, . AssocCtxt::Impl, . ) . }, . ); . } . AssocItemKind::MacCall(_) => { -- line 1406 ---------------------------------------- -- line 1423 ---------------------------------------- . kind: &AssocItemKind, . ns: Namespace, . span: Span, . err: F, . ) where . F: FnOnce(Ident, &str, Option) -> ResolutionError<'_>, . { . // If there is a TraitRef in scope for an impl, then the method must be in the trait. 394 ( 0.00%) let Some((module, _)) = &self.current_trait_ref else { return; }; 558 ( 0.00%) ident.span.normalize_to_macros_2_0_and_adjust(module.expansion); 459 ( 0.00%) let key = self.r.new_key(ident, ns); 930 ( 0.00%) let mut binding = self.r.resolution(module, key).try_borrow().ok().and_then(|r| r.binding); . debug!(?binding); 93 ( 0.00%) if binding.is_none() { . // We could not find the trait item in the correct namespace. . // Check the other namespace to report an error. . let ns = match ns { . ValueNS => TypeNS, . TypeNS => ValueNS, . _ => ns, . }; . let key = self.r.new_key(ident, ns); -- line 1444 ---------------------------------------- -- line 1449 ---------------------------------------- . // We could not find the method: report an error. . let candidate = self.find_similarly_named_assoc_item(ident.name, kind); . let path = &self.current_trait_ref.as_ref().unwrap().1.path; . self.report_error(span, err(ident, &path_names_to_string(path), candidate)); . return; . }; . . let res = binding.res(); 186 ( 0.00%) let Res::Def(def_kind, _) = res else { bug!() }; 645 ( 0.00%) match (def_kind, kind) { . (DefKind::AssocTy, AssocItemKind::TyAlias(..)) . | (DefKind::AssocFn, AssocItemKind::Fn(..)) . | (DefKind::AssocConst, AssocItemKind::Const(..)) => { 1,302 ( 0.00%) self.r.record_partial_res(id, PartialRes::new(res)); . return; . } . _ => {} . } . . // The method kind does not correspond to what appeared in the trait, report. . let path = &self.current_trait_ref.as_ref().unwrap().1.path; . let (code, kind) = match kind { -- line 1470 ---------------------------------------- -- line 1480 ---------------------------------------- . kind, . code, . trait_path: path_names_to_string(path), . trait_item_span: binding.span, . }, . ); . } . 2,772 ( 0.00%) fn resolve_params(&mut self, params: &'ast [Param]) { 1,540 ( 0.00%) let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())]; 1,848 ( 0.00%) for Param { pat, ty, .. } in params { . self.resolve_pattern(pat, PatternSource::FnParam, &mut bindings); 1,768 ( 0.00%) self.visit_ty(ty); . debug!("(resolving function / closure) recorded parameter"); . } 2,464 ( 0.00%) } . . fn resolve_local(&mut self, local: &'ast Local) { . debug!("resolving local ({:?})", local); . // Resolve the type. 258 ( 0.00%) walk_list!(self, visit_ty, &local.ty); . . // Resolve the initializer. 888 ( 0.00%) if let Some((init, els)) = local.kind.init_else_opt() { . self.visit_expr(init); . . // Resolve the `else` block 408 ( 0.00%) if let Some(els) = els { . self.visit_block(els); . } . } . . // Resolve the pattern. . self.resolve_pattern_top(&local.pat, PatternSource::Let); . } . . /// build a map from pattern identifiers to binding-info's. . /// this is done hygienically. This could arise for a macro . /// that expands into an or-pattern where one 'x' was from the . /// user and one 'x' came from the macro. . fn binding_mode_map(&mut self, pat: &Pat) -> BindingMap { . let mut binding_map = FxHashMap::default(); . 60 ( 0.00%) pat.walk(&mut |pat| { 92 ( 0.00%) match pat.kind { 16 ( 0.00%) PatKind::Ident(binding_mode, ident, ref sub_pat) 48 ( 0.00%) if sub_pat.is_some() || self.is_base_res_local(pat.id) => . { 24 ( 0.00%) binding_map.insert(ident, BindingInfo { span: ident.span, binding_mode }); . } . PatKind::Or(ref ps) => { . // Check the consistency of this or-pattern and . // then add all bindings to the larger map. . for bm in self.check_consistent_bindings(ps) { . binding_map.extend(bm); . } . return false; -- line 1536 ---------------------------------------- -- line 1540 ---------------------------------------- . . true . }); . . binding_map . } . . fn is_base_res_local(&self, nid: NodeId) -> bool { 32 ( 0.00%) matches!(self.r.partial_res_map.get(&nid).map(|res| res.base_res()), Some(Res::Local(..))) . } . . /// Checks that all of the arms in an or-pattern have exactly the . /// same set of bindings, with the same binding modes for each. 54 ( 0.00%) fn check_consistent_bindings(&mut self, pats: &[P]) -> Vec { . let mut missing_vars = FxHashMap::default(); . let mut inconsistent_vars = FxHashMap::default(); . . // 1) Compute the binding maps of all arms. . let maps = pats.iter().map(|pat| self.binding_mode_map(pat)).collect::>(); . . // 2) Record any missing bindings or binding mode inconsistencies. . for (map_outer, pat_outer) in pats.iter().enumerate().map(|(idx, pat)| (&maps[idx], pat)) { . // Check against all arms except for the same pattern which is always self-consistent. . let inners = pats . .iter() . .enumerate() 24 ( 0.00%) .filter(|(_, pat)| pat.id != pat_outer.id) . .flat_map(|(idx, _)| maps[idx].iter()) 24 ( 0.00%) .map(|(key, binding)| (key.name, map_outer.get(&key), binding)); . 48 ( 0.00%) for (name, info, &binding_inner) in inners { 8 ( 0.00%) match info { . None => { . // The inner binding is missing in the outer. . let binding_error = . missing_vars.entry(name).or_insert_with(|| BindingError { . name, . origin: BTreeSet::new(), . target: BTreeSet::new(), . could_be_path: name.as_str().starts_with(char::is_uppercase), . }); . binding_error.origin.insert(binding_inner.span); . binding_error.target.insert(pat_outer.span); . } . Some(binding_outer) => { 24 ( 0.00%) if binding_outer.binding_mode != binding_inner.binding_mode { . // The binding modes in the outer and inner bindings differ. . inconsistent_vars . .entry(name) . .or_insert((binding_inner.span, binding_outer.span)); . } . } . } . } . } . . // 3) Report all missing variables we found. . let mut missing_vars = missing_vars.iter_mut().collect::>(); . missing_vars.sort_by_key(|(sym, _err)| sym.as_str()); . 36 ( 0.00%) for (name, mut v) in missing_vars { . if inconsistent_vars.contains_key(name) { . v.could_be_path = false; . } . self.report_error( . *v.origin.iter().next().unwrap(), . ResolutionError::VariableNotBoundInPattern(v), . ); . } . . // 4) Report all inconsistencies in binding modes we found. . let mut inconsistent_vars = inconsistent_vars.iter().collect::>(); . inconsistent_vars.sort(); 24 ( 0.00%) for (name, v) in inconsistent_vars { . self.report_error(v.0, ResolutionError::VariableBoundWithDifferentMode(*name, v.1)); . } . . // 5) Finally bubble up all the binding maps. . maps 54 ( 0.00%) } . . /// Check the consistency of the outermost or-patterns. . fn check_consistent_bindings_top(&mut self, pat: &'ast Pat) { 7,258 ( 0.00%) pat.walk(&mut |pat| match pat.kind { . PatKind::Or(ref ps) => { 18 ( 0.00%) self.check_consistent_bindings(ps); . false . } . _ => true, . }) . } . . fn resolve_arm(&mut self, arm: &'ast Arm) { . self.with_rib(ValueNS, NormalRibKind, |this| { . this.resolve_pattern_top(&arm.pat, PatternSource::Match); 166 ( 0.00%) walk_list!(this, visit_expr, &arm.guard); . this.visit_expr(&arm.body); . }); . } . . /// Arising from `source`, resolve a top level pattern. . fn resolve_pattern_top(&mut self, pat: &'ast Pat, pat_src: PatternSource) { 1,904 ( 0.00%) let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())]; . self.resolve_pattern(pat, pat_src, &mut bindings); . } . . fn resolve_pattern( . &mut self, . pat: &'ast Pat, . pat_src: PatternSource, . bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet); 1]>, . ) { . // We walk the pattern before declaring the pattern's inner bindings, . // so that we avoid resolving a literal expression to a binding defined . // by the pattern. 2,568 ( 0.00%) visit::walk_pat(self, pat); . self.resolve_pattern_inner(pat, pat_src, bindings); . // This has to happen *after* we determine which pat_idents are variants: . self.check_consistent_bindings_top(pat); . } . . /// Resolve bindings in a pattern. This is a helper to `resolve_pattern`. . /// . /// ### `bindings` -- line 1663 ---------------------------------------- -- line 1679 ---------------------------------------- . /// See the implementation and `fresh_binding` for more details. . fn resolve_pattern_inner( . &mut self, . pat: &Pat, . pat_src: PatternSource, . bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet); 1]>, . ) { . // Visit all direct subpatterns of this pattern. 6,894 ( 0.00%) pat.walk(&mut |pat| { . debug!("resolve_pattern pat={:?} node={:?}", pat, pat.kind); 6,155 ( 0.00%) match pat.kind { 3,444 ( 0.00%) PatKind::Ident(bmode, ident, ref sub) => { . // First try to resolve the identifier as some existing entity, . // then fall back to a fresh binding. . let has_sub = sub.is_some(); 9,471 ( 0.00%) let res = self . .try_resolve_as_non_binding(pat_src, pat, bmode, ident, has_sub) 9,405 ( 0.00%) .unwrap_or_else(|| self.fresh_binding(ident, pat.id, pat_src, bindings)); 6,027 ( 0.00%) self.r.record_partial_res(pat.id, PartialRes::new(res)); 2,583 ( 0.00%) self.r.record_pat_span(pat.id, pat.span); . } 162 ( 0.00%) PatKind::TupleStruct(ref qself, ref path, ref sub_patterns) => { 324 ( 0.00%) self.smart_resolve_path( 81 ( 0.00%) pat.id, . qself.as_ref(), . path, 405 ( 0.00%) PathSource::TupleStruct( 81 ( 0.00%) pat.span, 92 ( 0.00%) self.r.arenas.alloc_pattern_spans(sub_patterns.iter().map(|p| p.span)), . ), . ); . } 36 ( 0.00%) PatKind::Path(ref qself, ref path) => { 90 ( 0.00%) self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Pat); . } 136 ( 0.00%) PatKind::Struct(ref qself, ref path, ..) => { 340 ( 0.00%) self.smart_resolve_path(pat.id, qself.as_ref(), path, PathSource::Struct); . } . PatKind::Or(ref ps) => { . // Add a new set of bindings to the stack. `Or` here records that when a . // binding already exists in this set, it should not result in an error because . // `V1(a) | V2(a)` must be allowed and are checked for consistency later. 12 ( 0.00%) bindings.push((PatBoundCtx::Or, Default::default())); . for p in ps { . // Now we need to switch back to a product context so that each . // part of the or-pattern internally rejects already bound names. . // For example, `V1(a) | V2(a, a)` and `V1(a, a) | V2(a)` are bad. 24 ( 0.00%) bindings.push((PatBoundCtx::Product, Default::default())); 36 ( 0.00%) self.resolve_pattern_inner(p, pat_src, bindings); . // Move up the non-overlapping bindings to the or-pattern. . // Existing bindings just get "merged". 48 ( 0.00%) let collected = bindings.pop().unwrap().1; . bindings.last_mut().unwrap().1.extend(collected); . } . // This or-pattern itself can itself be part of a product, . // e.g. `(V1(a) | V2(a), a)` or `(a, V1(a) | V2(a))`. . // Both cases bind `a` again in a product pattern and must be rejected. 36 ( 0.00%) let collected = bindings.pop().unwrap().1; . bindings.last_mut().unwrap().1.extend(collected); . . // Prevent visiting `ps` as we've already done so above. . return false; . } . _ => {} . } . true . }); . } . 10,260 ( 0.00%) fn fresh_binding( . &mut self, . ident: Ident, . pat_id: NodeId, . pat_src: PatternSource, . bindings: &mut SmallVec<[(PatBoundCtx, FxHashSet); 1]>, . ) -> Res { . // Add the binding to the local ribs, if it doesn't already exist in the bindings map. . // (We must not add it if it's in the bindings map because that breaks the assumptions . // later passes make about or-patterns.) 4,275 ( 0.00%) let ident = ident.normalize_to_macro_rules(); . . let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident)); . // Already bound in a product pattern? e.g. `(a, a)` which is not allowed. . let already_bound_and = bound_iter.clone().any(|(ctx, _)| *ctx == PatBoundCtx::Product); . // Already bound in an or-pattern? e.g. `V1(a) | V2(a)`. . // This is *required* for consistency which is checked later. . let already_bound_or = bound_iter.any(|(ctx, _)| *ctx == PatBoundCtx::Or); . 855 ( 0.00%) if already_bound_and { . // Overlap in a product pattern somewhere; report an error. . use ResolutionError::*; . let error = match pat_src { . // `fn f(a: u8, a: u8)`: . PatternSource::FnParam => IdentifierBoundMoreThanOnceInParameterList, . // `Variant(a, a)`: . _ => IdentifierBoundMoreThanOnceInSamePattern, . }; . self.report_error(ident.span, error(ident.name)); . } . . // Record as bound if it's valid: . let ident_valid = ident.name != kw::Empty; 855 ( 0.00%) if ident_valid { 1,710 ( 0.00%) bindings.last_mut().unwrap().1.insert(ident); . } . 855 ( 0.00%) if already_bound_or { . // `Variant1(a) | Variant2(a)`, ok . // Reuse definition from the first `a`. 24 ( 0.00%) self.innermost_rib_bindings(ValueNS)[&ident] . } else { . let res = Res::Local(pat_id); . if ident_valid { . // A completely fresh binding add to the set if it's valid. 1,702 ( 0.00%) self.innermost_rib_bindings(ValueNS).insert(ident, res); . } 6,808 ( 0.00%) res . } 7,695 ( 0.00%) } . . fn innermost_rib_bindings(&mut self, ns: Namespace) -> &mut IdentMap { 4 ( 0.00%) &mut self.ribs[ns].last_mut().unwrap().bindings . } . 11,193 ( 0.00%) fn try_resolve_as_non_binding( . &mut self, . pat_src: PatternSource, . pat: &Pat, . bm: BindingMode, . ident: Ident, . has_sub: bool, . ) -> Option { . // An immutable (no `mut`) by-value (no `ref`) binding pattern without . // a sub pattern (no `@ $pat`) is syntactically ambiguous as it could . // also be interpreted as a path to e.g. a constant, variant, etc. 1,722 ( 0.00%) let is_syntactic_ambiguity = !has_sub && bm == BindingMode::ByValue(Mutability::Not); . . let ls_binding = self.resolve_ident_in_lexical_scope(ident, ValueNS, None, pat.span)?; 224 ( 0.00%) let (res, binding) = match ls_binding { . LexicalScopeBinding::Item(binding) 32 ( 0.00%) if is_syntactic_ambiguity && binding.is_ambiguity() => . { . // For ambiguous bindings we don't know all their definitions and cannot check . // whether they can be shadowed by fresh bindings or not, so force an error. . // issues/33118#issuecomment-233962221 (see below) still applies here, . // but we have to ignore it for backward compatibility. . self.r.record_use(ident, binding, false); . return None; . } 144 ( 0.00%) LexicalScopeBinding::Item(binding) => (binding.res(), Some(binding)), 72 ( 0.00%) LexicalScopeBinding::Res(res) => (res, None), . }; . 166 ( 0.00%) match res { . Res::SelfCtor(_) // See #70549. . | Res::Def( . DefKind::Ctor(_, CtorKind::Const) | DefKind::Const | DefKind::ConstParam, . _, . ) if is_syntactic_ambiguity => { . // Disambiguate in favor of a unit struct/variant or constant pattern. 12 ( 0.00%) if let Some(binding) = binding { 36 ( 0.00%) self.r.record_use(ident, binding, false); . } 30 ( 0.00%) Some(res) . } . Res::Def(DefKind::Ctor(..) | DefKind::Const | DefKind::Static, _) => { . // This is unambiguously a fresh binding, either syntactically . // (e.g., `IDENT @ PAT` or `ref IDENT`) or because `IDENT` resolves . // to something unusable as a pattern (e.g., constructor function), . // but we still conservatively report an error, see . // issues/33118#issuecomment-233962221 for one reason why. . let binding = binding.expect("no binding for a ctor or static"); -- line 1850 ---------------------------------------- -- line 1882 ---------------------------------------- . None . } . _ => span_bug!( . ident.span, . "unexpected resolution for an identifier in pattern: {:?}", . res, . ), . } 7,749 ( 0.00%) } . . // High-level and context dependent path resolution routine. . // Resolves the path and records the resolution into definition map. . // If resolution fails tries several techniques to find likely . // resolution candidates, suggest imports or other help, and report . // errors in user friendly way. 46,908 ( 0.00%) fn smart_resolve_path( . &mut self, . id: NodeId, . qself: Option<&QSelf>, . path: &Path, . source: PathSource<'ast>, . ) { 59,925 ( 0.00%) self.smart_resolve_path_fragment( . id, . qself, . &Segment::from_path(path), 3,995 ( 0.00%) path.span, 15,722 ( 0.00%) source, . CrateLint::SimplePath(id), . ); . } . 57,456 ( 0.00%) fn smart_resolve_path_fragment( . &mut self, . id: NodeId, . qself: Option<&QSelf>, . path: &[Segment], . span: Span, . source: PathSource<'ast>, . crate_lint: CrateLint, . ) -> PartialRes { . tracing::debug!( . "smart_resolve_path_fragment(id={:?}, qself={:?}, path={:?})", . id, . qself, . path . ); 32,832 ( 0.00%) let ns = source.namespace(); . 24,624 ( 0.00%) let report_errors = |this: &mut Self, res: Option| { . if this.should_report_errs() { . let (err, candidates) = this.smart_resolve_report_errors(path, span, source, res); . . let def_id = this.parent_scope.module.nearest_parent_mod(); . let instead = res.is_some(); . let suggestion = . if res.is_none() { this.report_missing_type_error(path) } else { None }; . // get_from_node_id -- line 1939 ---------------------------------------- -- line 2014 ---------------------------------------- . err.cancel(); . } . . // We don't return `Some(parent_err)` here, because the error will . // be already printed as part of the `use` injections . None . }; . 90,288 ( 0.00%) let partial_res = match self.resolve_qpath_anywhere( . id, . qself, . path, . ns, . span, . source.defer_to_typeck(), . crate_lint, . ) { 23,820 ( 0.00%) Ok(Some(partial_res)) if partial_res.unresolved_segments() == 0 => { 27,321 ( 0.00%) if source.is_expected(partial_res.base_res()) || partial_res.base_res() == Res::Err . { 23,418 ( 0.00%) partial_res . } else { . report_errors(self, Some(partial_res.base_res())) . } . } . 1,005 ( 0.00%) Ok(Some(partial_res)) if source.defer_to_typeck() => { . // Not fully resolved associated item `T::A::B` or `::A::B` . // or `::A::B`. If `B` should be resolved in value namespace then . // it needs to be added to the trait map. 201 ( 0.00%) if ns == ValueNS { 975 ( 0.00%) let item_name = path.last().unwrap().ident; . let traits = self.traits_in_scope(item_name, ns); . self.r.trait_map.insert(id, traits); . } . 1,011 ( 0.00%) if PrimTy::from_name(path[0].ident.name).is_some() { . let mut std_path = Vec::with_capacity(1 + path.len()); . . std_path.push(Segment::from_ident(Ident::with_dummy_span(sym::std))); . std_path.extend(path); . if let PathResult::Module(_) | PathResult::NonModule(_) = . self.resolve_path(&std_path, Some(ns), false, span, CrateLint::No) . { . // Check if we wrote `str::from_utf8` instead of `std::str::from_utf8` -- line 2058 ---------------------------------------- -- line 2059 ---------------------------------------- . let item_span = . path.iter().last().map_or(span, |segment| segment.ident.span); . . self.r.confused_type_with_std_module.insert(item_span, span); . self.r.confused_type_with_std_module.insert(span, span); . } . } . 1,206 ( 0.00%) partial_res . } . . Err(err) => { . if let Some(err) = report_errors_for_call(self, err) { . self.report_error(err.span, err.node); . } . . PartialRes::new(Res::Err) . } . . _ => report_errors(self, None), . }; . 8,208 ( 0.00%) if !matches!(source, PathSource::TraitItem(..)) { . // Avoid recording definition of `A::B` in `::B::C`. 16,416 ( 0.00%) self.r.record_partial_res(id, partial_res); . } . . partial_res 32,832 ( 0.00%) } . . fn self_type_is_available(&mut self, span: Span) -> bool { . let binding = self.resolve_ident_in_lexical_scope( . Ident::with_dummy_span(kw::SelfUpper), . TypeNS, . None, . span, . ); -- line 2095 ---------------------------------------- -- line 2113 ---------------------------------------- . . #[inline] . /// If we're actually rustdoc then avoid giving a name resolution error for `cfg()` items. . fn should_report_errs(&self) -> bool { . !(self.r.session.opts.actually_rustdoc && self.in_func_body) . } . . // Resolve in alternative namespaces if resolution in the primary namespace fails. 53,352 ( 0.00%) fn resolve_qpath_anywhere( . &mut self, . id: NodeId, . qself: Option<&QSelf>, . path: &[Segment], . primary_ns: Namespace, . span: Span, . defer_to_typeck: bool, . crate_lint: CrateLint, . ) -> Result, Spanned>> { . let mut fin_res = None; . 28,728 ( 0.00%) for (i, &ns) in [primary_ns, TypeNS, ValueNS].iter().enumerate() { 8,208 ( 0.00%) if i == 0 || ns != primary_ns { 16,416 ( 0.00%) match self.resolve_qpath(id, qself, path, ns, span, crate_lint)? { . Some(partial_res) 25,026 ( 0.00%) if partial_res.unresolved_segments() == 0 || defer_to_typeck => . { 49,248 ( 0.00%) return Ok(Some(partial_res)); . } . partial_res => { . if fin_res.is_none() { . fin_res = partial_res; . } . } . } . } -- line 2147 ---------------------------------------- -- line 2155 ---------------------------------------- . if let Ok((_, res)) = . self.r.resolve_macro_path(&path, None, &self.parent_scope, false, false) . { . return Ok(Some(PartialRes::new(res))); . } . } . . Ok(fin_res) 32,832 ( 0.00%) } . . /// Handles paths that may refer to associated items. . fn resolve_qpath( . &mut self, . id: NodeId, . qself: Option<&QSelf>, . path: &[Segment], . ns: Namespace, -- line 2171 ---------------------------------------- -- line 2172 ---------------------------------------- . span: Span, . crate_lint: CrateLint, . ) -> Result, Spanned>> { . debug!( . "resolve_qpath(id={:?}, qself={:?}, path={:?}, ns={:?}, span={:?})", . id, qself, path, ns, span, . ); . 4,104 ( 0.00%) if let Some(qself) = qself { . if qself.position == 0 { . // This is a case like `::B`, where there is no . // trait to resolve. In that case, we leave the `B` . // segment to be resolved by type-check. . return Ok(Some(PartialRes::with_unresolved_segments( . Res::Def(DefKind::Mod, DefId::local(CRATE_DEF_INDEX)), . path.len(), . ))); -- line 2188 ---------------------------------------- -- line 2216 ---------------------------------------- . // have to be resolved by type-check, since that requires doing . // trait resolution. . return Ok(Some(PartialRes::with_unresolved_segments( . partial_res.base_res(), . partial_res.unresolved_segments() + path.len() - qself.position - 1, . ))); . } . 25,390 ( 0.00%) let result = match self.resolve_path(&path, Some(ns), true, span, crate_lint) { 48,373 ( 0.00%) PathResult::NonModule(path_res) => path_res, 1,532 ( 0.00%) PathResult::Module(ModuleOrUniformRoot::Module(module)) if !module.is_normal() => { . PartialRes::new(module.res().unwrap()) . } . // In `a(::assoc_item)*` `a` cannot be a module. If `a` does resolve to a module we . // don't report an error right away, but try to fallback to a primitive type. . // So, we are still able to successfully resolve something like . // . // use std::u8; // bring module u8 in scope . // fn f() -> u8 { // OK, resolves to primitive u8, not to std::u8 . // u8::max_value() // OK, resolves to associated function ::max_value, . // // not to non-existent std::u8::max_value . // } . // . // Such behavior is required for backward compatibility. . // The same fallback is used when `a` resolves to nothing. . PathResult::Module(ModuleOrUniformRoot::Module(_)) | PathResult::Failed { .. } 26 ( 0.00%) if (ns == TypeNS || path.len() > 1) 104 ( 0.00%) && PrimTy::from_name(path[0].ident.name).is_some() => . { 52 ( 0.00%) let prim = PrimTy::from_name(path[0].ident.name).unwrap(); . PartialRes::with_unresolved_segments(Res::PrimTy(prim), path.len() - 1) . } . PathResult::Module(ModuleOrUniformRoot::Module(module)) => { . PartialRes::new(module.res().unwrap()) . } . PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => { . return Err(respan(span, ResolutionError::FailedToResolve { label, suggestion })); . } . PathResult::Module(..) | PathResult::Failed { .. } => return Ok(None), . PathResult::Indeterminate => bug!("indeterminate path result in resolve_qpath"), 20,494 ( 0.00%) }; . 10,176 ( 0.00%) if path.len() > 1 . && result.base_res() != Res::Err 1,204 ( 0.00%) && path[0].ident.name != kw::PathRoot . && path[0].ident.name != kw::DollarCrate . { . let unqualified_result = { 1,660 ( 0.00%) match self.resolve_path( 1,660 ( 0.00%) &[*path.last().unwrap()], . Some(ns), . false, . span, . CrateLint::No, . ) { 545 ( 0.00%) PathResult::NonModule(path_res) => path_res.base_res(), 9 ( 0.00%) PathResult::Module(ModuleOrUniformRoot::Module(module)) => { . module.res().unwrap() . } 856 ( 0.00%) _ => return Ok(Some(result)), . } . }; 590 ( 0.00%) if result.base_res() == unqualified_result { . let lint = lint::builtin::UNUSED_QUALIFICATIONS; . self.r.lint_buffer.buffer_lint(lint, id, span, "unnecessary qualification") . } . } . 15,560 ( 0.00%) Ok(Some(result)) . } . . fn with_resolved_label(&mut self, label: Option

(self, predicate: P) -> Self . where . T: ~const Drop, . P: ~const FnOnce(&T) -> bool, . P: ~const Drop, . { 3,360 ( 0.00%) if let Some(x) = self { 1,835 ( 0.00%) if predicate(&x) { . return Some(x); . } . } . None 276 ( 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, . { 5,416 ( 0.00%) match self { 4,466 ( 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, . { 1,403,529 ( 0.03%) match self { 10,340 ( 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, . { 59,337 ( 0.00%) if let None = *self { 138,401 ( 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, . { 625,693 ( 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. 6 ( 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 { 1,768 ( 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 25,698 ( 0.00%) match self { 398,356 ( 0.01%) Some(&v) => Some(v), 2,048 ( 0.00%) None => None, . } 15 ( 0.00%) } . . /// Maps an `Option<&T>` to an `Option` by cloning the contents of the . /// option. . /// . /// # Examples . /// . /// ``` . /// let x = 12; -- line 1732 ---------------------------------------- -- line 1733 ---------------------------------------- . /// let opt_x = Some(&x); . /// assert_eq!(opt_x, Some(&12)); . /// let cloned = opt_x.cloned(); . /// assert_eq!(cloned, Some(12)); . /// ``` . #[must_use = "`self` will be dropped if the result is not used"] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_option_cloned", issue = "91582")] 13,022 ( 0.00%) pub const fn cloned(self) -> Option . where . T: ~const Clone, . { 104,190 ( 0.00%) match self { 946,917 ( 0.02%) Some(t) => Some(t.clone()), 8,252 ( 0.00%) None => None, . } 28,152 ( 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,200,676 ( 0.02%) match self { 38,086 ( 0.00%) Some(x) => Some(x.clone()), 1,768 ( 0.00%) None => None, . } 378,653 ( 0.01%) } . . #[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) { 25,634 ( 0.00%) match self.opt { . Some(_) => (1, Some(1)), . None => (0, Some(0)), . } . } . } . . impl DoubleEndedIterator for Item { . #[inline] -- line 2022 ---------------------------------------- -- line 2136 ---------------------------------------- . type Item = A; . . #[inline] . fn next(&mut self) -> Option { . self.inner.next() . } . #[inline] . fn size_hint(&self) -> (usize, Option) { 17 ( 0.00%) self.inner.size_hint() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DoubleEndedIterator for IntoIter { . #[inline] . fn next_back(&mut self) -> Option { . self.inner.next_back() -- line 2152 ---------------------------------------- -- 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) 2,210 ( 0.00%) } . . #[inline] . fn branch(self) -> ControlFlow { 2,741,711 ( 0.06%) match self { 24,517 ( 0.00%) Some(v) => ControlFlow::Continue(v), . None => ControlFlow::Break(None), . } . } . } . . #[unstable(feature = "try_trait_v2", issue = "84277")] . #[rustc_const_unstable(feature = "const_convert", issue = "88674")] . impl const ops::FromResidual for Option { . #[inline] . fn from_residual(residual: Option) -> Self { . match residual { 324,638 ( 0.01%) None => None, . } . } . } . . #[unstable(feature = "try_trait_v2_residual", issue = "91285")] . impl ops::Residual for Option { . type TryType = Option; . } -- line 2274 ---------------------------------------- 10,021,015 ( 0.21%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/scope.rs -------------------------------------------------------------------------------- Ir -- line 143 ---------------------------------------- . . /// local to drop . local: Local, . . /// Whether this is a value Drop or a StorageDead. . kind: DropKind, . } . 5,933 ( 0.00%) #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] . pub(crate) enum DropKind { . Value, . Storage, . } . . #[derive(Debug)] . struct BreakableScope<'tcx> { . /// Region scope of the loop -- line 159 ---------------------------------------- -- line 218 ---------------------------------------- . /// * clang doesn't emit llvm.lifetime.end for C++ unwinding . /// * LLVM's memory dependency analysis can't handle it atm . /// * polluting the cleanup MIR with StorageDead creates . /// landing pads even though there's no actual destructors . /// * freeing up stack space has no effect during unwinding . /// Note that for generators we do emit StorageDeads, for the . /// use of optimizations in the MIR generator transform. . fn needs_cleanup(&self) -> bool { 5,870 ( 0.00%) self.drops.iter().any(|drop| match drop.kind { . DropKind::Value => true, . DropKind::Storage => false, . }) . } . . fn invalidate_cache(&mut self) { 818 ( 0.00%) self.cached_unwind_block = None; . self.cached_generator_drop_block = None; . } . } . . /// A trait that determined how [DropTree] creates its blocks and . /// links to any entry nodes. . trait DropTreeBuilder<'tcx> { . /// Create a new block for the tree. This should call either -- line 241 ---------------------------------------- -- line 243 ---------------------------------------- . fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock; . . /// Links a block outside the drop tree, `from`, to the block `to` inside . /// the drop tree. . fn add_entry(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock); . } . . impl DropTree { 896 ( 0.00%) fn new() -> Self { . // The root node of the tree doesn't represent a drop, but instead . // represents the block in the tree that should be jumped to once all . // of the required drops have been performed. . let fake_source_info = SourceInfo::outermost(DUMMY_SP); . let fake_data = . DropData { source_info: fake_source_info, local: Local::MAX, kind: DropKind::Storage }; . let drop_idx = DropIdx::MAX; . let drops = IndexVec::from_elem_n((fake_data, drop_idx), 1); 1,792 ( 0.00%) Self { drops, entry_points: Vec::new(), previous_drops: FxHashMap::default() } 1,344 ( 0.00%) } . 70 ( 0.00%) fn add_drop(&mut self, drop: DropData, next: DropIdx) -> DropIdx { . let drops = &mut self.drops; 3,746 ( 0.00%) *self . .previous_drops 14 ( 0.00%) .entry((next, drop.local, drop.kind)) . .or_insert_with(|| drops.push((drop, next))) 56 ( 0.00%) } . . fn add_entry(&mut self, from: BasicBlock, to: DropIdx) { . debug_assert!(to < self.drops.next_index()); . self.entry_points.push((to, from)); . } . . /// Builds the MIR for a given drop tree. . /// . /// `blocks` should have the same length as `self.drops`, and may have its . /// first value set to some already existing block. 6,792 ( 0.00%) fn build_mir<'tcx, T: DropTreeBuilder<'tcx>>( . &mut self, . cfg: &mut CFG<'tcx>, . blocks: &mut IndexVec>, . ) { . debug!("DropTree::build_mir(drops = {:#?})", self); 3,396 ( 0.00%) assert_eq!(blocks.len(), self.drops.len()); . . self.assign_blocks::(cfg, blocks); 9,339 ( 0.00%) self.link_blocks(cfg, blocks) . } . . /// Assign blocks for all of the drops in the drop tree that need them. . fn assign_blocks<'tcx, T: DropTreeBuilder<'tcx>>( . &mut self, . cfg: &mut CFG<'tcx>, . blocks: &mut IndexVec>, . ) { -- line 297 ---------------------------------------- -- line 307 ---------------------------------------- . Shares(DropIdx), . // This drop has more than one way of being reached, or it is . // branched to from outside the tree, or its predecessor is a . // `Value` drop. . Own, . } . . let mut needs_block = IndexVec::from_elem(Block::None, &self.drops); 849 ( 0.00%) if blocks[ROOT_NODE].is_some() { . // In some cases (such as drops for `continue`) the root node . // already has a block. In this case, make sure that we don't . // override it. 19 ( 0.00%) needs_block[ROOT_NODE] = Block::Own; . } . . // Sort so that we only need to check the last value. . let entry_points = &mut self.entry_points; . entry_points.sort(); . . for (drop_idx, drop_data) in self.drops.iter_enumerated().rev() { 876 ( 0.00%) if entry_points.last().map_or(false, |entry_point| entry_point.0 == drop_idx) { . let block = *blocks[drop_idx].get_or_insert_with(|| T::make_block(cfg)); 1,418 ( 0.00%) needs_block[drop_idx] = Block::Own; 2,290 ( 0.00%) while entry_points.last().map_or(false, |entry_point| entry_point.0 == drop_idx) { . let entry_block = entry_points.pop().unwrap().1; . T::add_entry(cfg, entry_block, block); . } . } 11,984 ( 0.00%) match needs_block[drop_idx] { . Block::None => continue, . Block::Own => { . blocks[drop_idx].get_or_insert_with(|| T::make_block(cfg)); . } . Block::Shares(pred) => { 435 ( 0.00%) blocks[drop_idx] = blocks[pred]; . } . } 1,834 ( 0.00%) if let DropKind::Value = drop_data.0.kind { 314 ( 0.00%) needs_block[drop_data.1] = Block::Own; 603 ( 0.00%) } else if drop_idx != ROOT_NODE { 1,349 ( 0.00%) match &mut needs_block[drop_data.1] { 312 ( 0.00%) pred @ Block::None => *pred = Block::Shares(drop_idx), . pred @ Block::Shares(_) => *pred = Block::Own, . Block::Own => (), . } . } . } . . debug!("assign_blocks: blocks = {:#?}", blocks); 849 ( 0.00%) assert!(entry_points.is_empty()); . } . 5,943 ( 0.00%) fn link_blocks<'tcx>( . &self, . cfg: &mut CFG<'tcx>, . blocks: &IndexVec>, . ) { . for (drop_idx, drop_data) in self.drops.iter_enumerated().rev() { 5,800 ( 0.00%) let Some(block) = blocks[drop_idx] else { continue }; 1,834 ( 0.00%) match drop_data.0.kind { . DropKind::Value => { . let terminator = TerminatorKind::Drop { 628 ( 0.00%) target: blocks[drop_data.1].unwrap(), . // The caller will handle this if needed. . unwind: None, 314 ( 0.00%) place: drop_data.0.local.into(), . }; 942 ( 0.00%) cfg.terminate(block, drop_data.0.source_info, terminator); . } . // Root nodes don't correspond to a drop. 603 ( 0.00%) DropKind::Storage if drop_idx == ROOT_NODE => {} . DropKind::Storage => { . let stmt = Statement { . source_info: drop_data.0.source_info, 166 ( 0.00%) kind: StatementKind::StorageDead(drop_data.0.local), . }; 1,826 ( 0.00%) cfg.push(block, stmt); 332 ( 0.00%) let target = blocks[drop_data.1].unwrap(); 166 ( 0.00%) if target != block { . // Diagnostics don't use this `Span` but debuginfo . // might. Since we don't want breakpoints to be placed . // here, especially when this is on an unwind path, we . // use `DUMMY_SP`. . let source_info = SourceInfo { span: DUMMY_SP, ..drop_data.0.source_info }; . let terminator = TerminatorKind::Goto { target }; 21 ( 0.00%) cfg.terminate(block, source_info, terminator); . } . } . } . } 6,792 ( 0.00%) } . } . . impl<'tcx> Scopes<'tcx> { 1,604 ( 0.00%) pub(crate) fn new() -> Self { 7,619 ( 0.00%) Self { . scopes: Vec::new(), . breakable_scopes: Vec::new(), . if_then_scope: None, . unwind_drops: DropTree::new(), . generator_drops: DropTree::new(), . } 2,005 ( 0.00%) } . 57 ( 0.00%) fn push_scope(&mut self, region_scope: (region::Scope, SourceInfo), vis_scope: SourceScope) { . debug!("push_scope({:?})", region_scope); 1,326,975 ( 0.03%) self.scopes.push(Scope { . source_scope: vis_scope, 19 ( 0.00%) region_scope: region_scope.0, . drops: vec![], . moved_locals: vec![], . cached_unwind_block: None, . cached_generator_drop_block: None, . }); 57 ( 0.00%) } . 447,156 ( 0.01%) fn pop_scope(&mut self, region_scope: (region::Scope, SourceInfo)) -> Scope { . let scope = self.scopes.pop().unwrap(); 447,156 ( 0.01%) assert_eq!(scope.region_scope, region_scope.0); . scope 745,260 ( 0.02%) } . . fn scope_index(&self, region_scope: region::Scope, span: Span) -> usize { . self.scopes . .iter() . .rposition(|scope| scope.region_scope == region_scope) . .unwrap_or_else(|| span_bug!(span, "region_scope {:?} does not enclose", region_scope)) . } . . /// Returns the topmost active scope, which is known to be alive until . /// the next scope expression. . fn topmost(&self) -> region::Scope { 16,096 ( 0.00%) self.scopes.last().expect("topmost_scope: no scopes present").region_scope . } . } . . impl<'a, 'tcx> Builder<'a, 'tcx> { . // Adding and removing scopes . // ========================== . // Start a breakable scope, which tracks where `continue`, `break` and . // `return` should branch to. 152 ( 0.00%) crate fn in_breakable_scope( . &mut self, . loop_block: Option, . break_destination: Place<'tcx>, . span: Span, . f: F, . ) -> BlockAnd<()> . where . F: FnOnce(&mut Builder<'a, 'tcx>) -> Option>, . { . let region_scope = self.scopes.topmost(); 3,270 ( 0.00%) let scope = BreakableScope { . region_scope, . break_destination, 346 ( 0.00%) break_drops: DropTree::new(), 19 ( 0.00%) continue_drops: loop_block.map(|_| DropTree::new()), . }; 6,365 ( 0.00%) self.scopes.breakable_scopes.push(scope); 95 ( 0.00%) let normal_exit_block = f(self); . let breakable_scope = self.scopes.breakable_scopes.pop().unwrap(); 365 ( 0.00%) assert!(breakable_scope.region_scope == region_scope); 4,905 ( 0.00%) let break_block = self.build_exit_tree(breakable_scope.break_drops, None); 654 ( 0.00%) if let Some(drops) = breakable_scope.continue_drops { 285 ( 0.00%) self.build_exit_tree(drops, loop_block); . } 672 ( 0.00%) match (normal_exit_block, break_block) { . (Some(block), None) | (None, Some(block)) => block, 1 ( 0.00%) (None, None) => self.cfg.start_new_block().unit(), . (Some(normal_block), Some(exit_block)) => { 34 ( 0.00%) let target = self.cfg.start_new_block(); . let source_info = self.source_info(span); . self.cfg.terminate( . unpack!(normal_block), . source_info, . TerminatorKind::Goto { target }, . ); . self.cfg.terminate( . unpack!(exit_block), . source_info, . TerminatorKind::Goto { target }, . ); . target.unit() . } . } 171 ( 0.00%) } . . /// Start an if-then scope which tracks drop for `if` expressions and `if` . /// guards. . /// . /// For an if-let chain: . /// . /// if let Some(x) = a && let Some(y) = b && let Some(z) = c { ... } . /// -- line 500 ---------------------------------------- -- line 510 ---------------------------------------- . crate fn in_if_then_scope( . &mut self, . region_scope: region::Scope, . f: F, . ) -> (BasicBlock, BasicBlock) . where . F: FnOnce(&mut Builder<'a, 'tcx>) -> BlockAnd<()>, . { 102 ( 0.00%) let scope = IfThenScope { region_scope, else_drops: DropTree::new() }; . let previous_scope = mem::replace(&mut self.scopes.if_then_scope, Some(scope)); . . let then_block = unpack!(f(self)); . . let if_then_scope = mem::replace(&mut self.scopes.if_then_scope, previous_scope).unwrap(); 102 ( 0.00%) assert!(if_then_scope.region_scope == region_scope); . 408 ( 0.00%) let else_block = self 1,224 ( 0.00%) .build_exit_tree(if_then_scope.else_drops, None) 102 ( 0.00%) .map_or_else(|| self.cfg.start_new_block(), |else_block_and| unpack!(else_block_and)); . . (then_block, else_block) . } . . crate fn in_opt_scope( . &mut self, . opt_scope: Option<(region::Scope, SourceInfo)>, . f: F, . ) -> BlockAnd . where . F: FnOnce(&mut Builder<'a, 'tcx>) -> BlockAnd, . { . debug!("in_opt_scope(opt_scope={:?})", opt_scope); 624 ( 0.00%) if let Some(region_scope) = opt_scope { . self.push_scope(region_scope); . } . let mut block; . let rv = unpack!(block = f(self)); 1,043 ( 0.00%) if let Some(region_scope) = opt_scope { 4,837 ( 0.00%) unpack!(block = self.pop_scope(region_scope, block)); . } . debug!("in_scope: exiting opt_scope={:?} block={:?}", opt_scope, block); . block.and(rv) . } . . /// Convenience wrapper that pushes a scope and then executes `f` . /// to build its contents, popping the scope afterwards. 29,097 ( 0.00%) crate fn in_scope( . &mut self, . region_scope: (region::Scope, SourceInfo), . lint_level: LintLevel, . f: F, . ) -> BlockAnd . where . F: FnOnce(&mut Builder<'a, 'tcx>) -> BlockAnd, . { . debug!("in_scope(region_scope={:?})", region_scope); 9,806 ( 0.00%) let source_scope = self.source_scope; . let tcx = self.tcx; 299,360 ( 0.01%) if let LintLevel::Explicit(current_hir_id) = lint_level { . // Use `maybe_lint_level_root_bounded` with `root_lint_level` as a bound . // to avoid adding Hir dependences on our parents. . // We estimate the true lint roots here to avoid creating a lot of source scopes. . 873,003 ( 0.02%) let parent_root = tcx.maybe_lint_level_root_bounded( 149,703 ( 0.00%) self.source_scopes[source_scope].local_data.as_ref().assert_crate_local().lint_root, 291,834 ( 0.01%) self.hir_id, . ); 880,807 ( 0.02%) let current_root = tcx.maybe_lint_level_root_bounded(current_hir_id, self.hir_id); . 437,751 ( 0.01%) if parent_root != current_root { 48 ( 0.00%) self.source_scope = self.new_source_scope( 8 ( 0.00%) region_scope.1.span, . LintLevel::Explicit(current_root), . None, . ); . } . } . self.push_scope(region_scope); . let mut block; 740,589 ( 0.02%) let rv = unpack!(block = f(self)); 1,339,694 ( 0.03%) unpack!(block = self.pop_scope(region_scope, block)); 151,325 ( 0.00%) self.source_scope = source_scope; . debug!("in_scope: exiting region_scope={:?} block={:?}", region_scope, block); 13,251 ( 0.00%) block.and(rv) 21,312 ( 0.00%) } . . /// Push a scope onto the stack. You can then build code in this . /// scope and call `pop_scope` afterwards. Note that these two . /// calls must be paired; using `in_scope` as a convenience . /// wrapper maybe preferable. . crate fn push_scope(&mut self, region_scope: (region::Scope, SourceInfo)) { 10,617 ( 0.00%) self.scopes.push_scope(region_scope, self.source_scope); . } . . /// Pops a scope, which should have region scope `region_scope`, . /// adding any drops onto the end of `block` that are needed. . /// This must match 1-to-1 with `push_scope`. 894,312 ( 0.02%) crate fn pop_scope( . &mut self, . region_scope: (region::Scope, SourceInfo), . mut block: BasicBlock, . ) -> BlockAnd<()> { . debug!("pop_scope({:?}, {:?})", region_scope, block); . . block = self.leave_top_scope(block); . 1,192,416 ( 0.02%) self.scopes.pop_scope(region_scope); . . block.unit() 1,192,416 ( 0.02%) } . . /// Sets up the drops for breaking from `block` to `target`. 564 ( 0.00%) crate fn break_scope( . &mut self, . mut block: BasicBlock, . value: Option<&Expr<'tcx>>, . target: BreakableTarget, . source_info: SourceInfo, . ) -> BlockAnd<()> { . let span = source_info.span; . -- line 630 ---------------------------------------- -- line 631 ---------------------------------------- . let get_scope_index = |scope: region::Scope| { . // find the loop-scope by its `region::Scope`. . self.scopes . .breakable_scopes . .iter() . .rposition(|breakable_scope| breakable_scope.region_scope == scope) . .unwrap_or_else(|| span_bug!(span, "no enclosing breakable scope found")) . }; 374 ( 0.00%) let (break_index, destination) = match target { . BreakableTarget::Return => { . let scope = &self.scopes.breakable_scopes[0]; 92 ( 0.00%) if scope.break_destination != Place::return_place() { . span_bug!(span, "`return` in item with no return scope"); . } . (0, Some(scope.break_destination)) . } . BreakableTarget::Break(scope) => { . let break_index = get_scope_index(scope); . let scope = &self.scopes.breakable_scopes[break_index]; . (break_index, Some(scope.break_destination)) -- line 650 ---------------------------------------- -- line 651 ---------------------------------------- . } . BreakableTarget::Continue(scope) => { . let break_index = get_scope_index(scope); . (break_index, None) . } . }; . . if let Some(destination) = destination { 92 ( 0.00%) if let Some(value) = value { . debug!("stmt_expr Break val block_context.push(SubExpr)"); . self.block_context.push(BlockFrame::SubExpr); 147 ( 0.00%) unpack!(block = self.expr_into_dest(destination, block, value)); . self.block_context.pop(); . } else { 225 ( 0.00%) self.cfg.push_assign_unit(block, source_info, destination, self.tcx) . } . } else { 1 ( 0.00%) assert!(value.is_none(), "`return` and `break` should have a destination"); 6 ( 0.00%) if self.tcx.sess.instrument_coverage() { . // Unlike `break` and `return`, which push an `Assign` statement to MIR, from which . // a Coverage code region can be generated, `continue` needs no `Assign`; but . // without one, the `InstrumentCoverage` MIR pass cannot generate a code region for . // `continue`. Coverage will be missing unless we add a dummy `Assign` to MIR. . self.add_dummy_assignment(&span, block, source_info); . } . } . 235 ( 0.00%) let region_scope = self.scopes.breakable_scopes[break_index].region_scope; . let scope_index = self.scopes.scope_index(region_scope, span); 47 ( 0.00%) let drops = if destination.is_some() { 92 ( 0.00%) &mut self.scopes.breakable_scopes[break_index].break_drops . } else { . self.scopes.breakable_scopes[break_index].continue_drops.as_mut().unwrap() . }; . let mut drop_idx = ROOT_NODE; 94 ( 0.00%) for scope in &self.scopes.scopes[scope_index + 1..] { . for drop in &scope.drops { 1,880 ( 0.00%) drop_idx = drops.add_drop(*drop, drop_idx); . } . } . drops.add_entry(block, drop_idx); . . // `build_drop_tree` doesn't have access to our source_info, so we . // create a dummy terminator now. `TerminatorKind::Resume` is used . // because MIR type checking will panic if it hasn't been overwritten. . self.cfg.terminate(block, source_info, TerminatorKind::Resume); . 423 ( 0.00%) self.cfg.start_new_block().unit() . } . 1,224 ( 0.00%) crate fn break_for_else( . &mut self, . block: BasicBlock, . target: region::Scope, . source_info: SourceInfo, . ) { . let scope_index = self.scopes.scope_index(target, source_info.span); . let if_then_scope = self . .scopes . .if_then_scope . .as_mut() . .unwrap_or_else(|| span_bug!(source_info.span, "no if-then scope found")); . 306 ( 0.00%) assert_eq!(if_then_scope.region_scope, target, "breaking to incorrect scope"); . . let mut drop_idx = ROOT_NODE; . let drops = &mut if_then_scope.else_drops; 204 ( 0.00%) for scope in &self.scopes.scopes[scope_index + 1..] { . for drop in &scope.drops { . drop_idx = drops.add_drop(*drop, drop_idx); . } . } . drops.add_entry(block, drop_idx); . . // `build_drop_tree` doesn't have access to our source_info, so we . // create a dummy terminator now. `TerminatorKind::Resume` is used . // because MIR type checking will panic if it hasn't been overwritten. . self.cfg.terminate(block, source_info, TerminatorKind::Resume); 816 ( 0.00%) } . . // Add a dummy `Assign` statement to the CFG, with the span for the source code's `continue` . // statement. . fn add_dummy_assignment(&mut self, span: &Span, block: BasicBlock, source_info: SourceInfo) { . let local_decl = LocalDecl::new(self.tcx.mk_unit(), *span).internal(); . let temp_place = Place::from(self.local_decls.push(local_decl)); . self.cfg.push_assign_unit(block, source_info, temp_place, self.tcx); . } . . fn leave_top_scope(&mut self, block: BasicBlock) -> BasicBlock { . // If we are emitting a `drop` statement, we need to have the cached . // diverge cleanup pads ready in case that drop panics. . let needs_cleanup = self.scopes.scopes.last().map_or(false, |scope| scope.needs_cleanup()); 297,806 ( 0.01%) let is_generator = self.generator_kind.is_some(); 894 ( 0.00%) let unwind_to = if needs_cleanup { self.diverge_cleanup() } else { DropIdx::MAX }; . . let scope = self.scopes.scopes.last().expect("leave_top_scope called with no scopes"); 894,312 ( 0.02%) unpack!(build_scope_drops( 149,052 ( 0.00%) &mut self.cfg, 149,052 ( 0.00%) &mut self.scopes.unwind_drops, . scope, . block, . unwind_to, 149,052 ( 0.00%) is_generator && needs_cleanup, 149,052 ( 0.00%) self.arg_count, . )) . } . . /// Creates a new source scope, nested in the current one. 7,290 ( 0.00%) crate fn new_source_scope( . &mut self, . span: Span, . lint_level: LintLevel, . safety: Option, . ) -> SourceScope { 810 ( 0.00%) let parent = self.source_scope; . debug!( . "new_source_scope({:?}, {:?}, {:?}) - parent({:?})={:?}", . span, . lint_level, . safety, . parent, . self.source_scopes.get(parent) . ); . let scope_local_data = SourceScopeLocalData { 1,620 ( 0.00%) lint_root: if let LintLevel::Explicit(lint_root) = lint_level { . lint_root . } else { 401 ( 0.00%) self.source_scopes[parent].local_data.as_ref().assert_crate_local().lint_root . }, 810 ( 0.00%) safety: safety.unwrap_or_else(|| { 1,155 ( 0.00%) self.source_scopes[parent].local_data.as_ref().assert_crate_local().safety . }), . }; . self.source_scopes.push(SourceScopeData { . span, . parent_scope: Some(parent), . inlined: None, . inlined_parent_scope: None, . local_data: ClearCrossCrate::Set(scope_local_data), . }) 7,290 ( 0.00%) } . . /// Given a span and the current source scope, make a SourceInfo. . crate fn source_info(&self, span: Span) -> SourceInfo { 311,289 ( 0.01%) SourceInfo { span, scope: self.source_scope } 2,703 ( 0.00%) } . . // Finding scopes . // ============== . /// Returns the scope that we should use as the lifetime of an . /// operand. Basically, an operand must live until it is consumed. . /// This is similar to, but not quite the same as, the temporary . /// scope (which can be larger or smaller). . /// -- line 804 ---------------------------------------- -- line 823 ---------------------------------------- . // Scheduling drops . // ================ . crate fn schedule_drop_storage_and_value( . &mut self, . span: Span, . region_scope: region::Scope, . local: Local, . ) { 9 ( 0.00%) self.schedule_drop(span, region_scope, local, DropKind::Storage); 7 ( 0.00%) self.schedule_drop(span, region_scope, local, DropKind::Value); . } . . /// Indicates that `place` should be dropped on exit from `region_scope`. . /// . /// When called with `DropKind::Storage`, `place` shouldn't be the return . /// place, or a function parameter. 191,984 ( 0.00%) crate fn schedule_drop( . &mut self, . span: Span, . region_scope: region::Scope, . local: Local, . drop_kind: DropKind, . ) { 23,998 ( 0.00%) let needs_drop = match drop_kind { . DropKind::Value => { 50,056 ( 0.00%) if !self.local_decls[local].ty.needs_drop(self.tcx, self.param_env) { . return; . } . true . } . DropKind::Storage => { 11,484 ( 0.00%) if local.index() <= self.arg_count { . span_bug!( . span, . "`schedule_drop` called with local {:?} and arg_count {}", . local, . self.arg_count, . ) . } . false -- line 862 ---------------------------------------- -- line 906 ---------------------------------------- . // cache of outer scope stays intact. . // . // Since we only cache drops for the unwind path and the generator drop . // path, we only need to invalidate the cache for drops that happen on . // the unwind or generator drop paths. This means that for . // non-generators we don't need to invalidate caches for `DropKind::Storage`. . let invalidate_caches = needs_drop || self.generator_kind.is_some(); . for scope in self.scopes.scopes.iter_mut().rev() { 12,214 ( 0.00%) if invalidate_caches { . scope.invalidate_cache(); . } . 7,392 ( 0.00%) if scope.region_scope == region_scope { 36,642 ( 0.00%) let region_scope_span = region_scope.span(self.tcx, &self.region_scope_tree); . // Attribute scope exit drops to scope's closing brace. 24,428 ( 0.00%) let scope_end = self.tcx.sess.source_map().end_point(region_scope_span); . . scope.drops.push(DropData { 6,107 ( 0.00%) source_info: SourceInfo { span: scope_end, scope: scope.source_scope }, . local, . kind: drop_kind, . }); . . return; . } . } . . span_bug!(span, "region scope {:?} not in scope to drop {:?}", region_scope, local); 95,992 ( 0.00%) } . . /// Indicates that the "local operand" stored in `local` is . /// *moved* at some point during execution (see `local_scope` for . /// more information about what a "local operand" is -- in short, . /// it's an intermediate operand created as part of preparing some . /// MIR instruction). We use this information to suppress . /// redundant drops on the non-unwind paths. This results in less . /// MIR, but also avoids spurious borrow check errors -- line 942 ---------------------------------------- -- line 965 ---------------------------------------- . /// However, `_X` is still registered to be dropped, and so if we . /// do nothing else, we would generate a `DROP(_X)` that occurs . /// after the call. This will later be optimized out by the . /// drop-elaboation code, but in the meantime it can lead to . /// spurious borrow-check errors -- the problem, ironically, is . /// not the `DROP(_X)` itself, but the (spurious) unwind pathways . /// that it creates. See #64391 for an example. . crate fn record_operands_moved(&mut self, operands: &[Operand<'tcx>]) { 1,876 ( 0.00%) let local_scope = self.local_scope(); . let scope = self.scopes.scopes.last_mut().unwrap(); . 2,814 ( 0.00%) assert_eq!(scope.region_scope, local_scope, "local scope is not the topmost scope!",); . . // look for moves of a local variable, like `MOVE(_X)` 3,048 ( 0.00%) let locals_moved = operands.iter().flat_map(|operand| match operand { . Operand::Copy(_) | Operand::Constant(_) => None, . Operand::Move(place) => place.as_local(), . }); . 4,690 ( 0.00%) for local in locals_moved { . // check if we have a Drop for this operand and -- if so . // -- add it to the list of moved operands. Note that this . // local might not have been an operand created for this . // call, it could come from other places too. . if scope.drops.iter().any(|drop| drop.local == local && drop.kind == DropKind::Value) { . scope.moved_locals.push(local); . } . } . } . . // Other . // ===== . /// Returns the [DropIdx] for the innermost drop if the function unwound at . /// this point. The `DropIdx` will be created if it doesn't already exist. 10,512 ( 0.00%) fn diverge_cleanup(&mut self) -> DropIdx { 1,314 ( 0.00%) let is_generator = self.generator_kind.is_some(); . let (uncached_scope, mut cached_drop) = self . .scopes . .scopes . .iter() . .enumerate() . .rev() . .find_map(|(scope_idx, scope)| { 8,375 ( 0.00%) scope.cached_unwind_block.map(|cached_block| (scope_idx + 1, cached_block)) . }) . .unwrap_or((0, ROOT_NODE)); . . for scope in &mut self.scopes.scopes[uncached_scope..] { . for drop in &scope.drops { 18,942 ( 0.00%) if is_generator || drop.kind == DropKind::Value { 4,167 ( 0.00%) cached_drop = self.scopes.unwind_drops.add_drop(*drop, cached_drop); . } . } 5,276 ( 0.00%) scope.cached_unwind_block = Some(cached_drop); . } . . cached_drop 11,826 ( 0.00%) } . . /// Prepares to create a path that performs all required cleanup for a . /// terminator that can unwind at the given basic block. . /// . /// This path terminates in Resume. The path isn't created until after all . /// of the non-unwind paths in this item have been lowered. . crate fn diverge_from(&mut self, start: BasicBlock) { . debug_assert!( -- line 1030 ---------------------------------------- -- line 1034 ---------------------------------------- . | TerminatorKind::Call { .. } . | TerminatorKind::DropAndReplace { .. } . | TerminatorKind::FalseUnwind { .. } . | TerminatorKind::InlineAsm { .. } . ), . "diverge_from called on block with terminator that cannot unwind." . ); . 3,036 ( 0.00%) let next_drop = self.diverge_cleanup(); . self.scopes.unwind_drops.add_entry(start, next_drop); . } . . /// Sets up a path that performs all required cleanup for dropping a . /// generator, starting from the given block that ends in . /// [TerminatorKind::Yield]. . /// . /// This path terminates in GeneratorDrop. -- line 1050 ---------------------------------------- -- line 1081 ---------------------------------------- . crate fn build_drop_and_replace( . &mut self, . block: BasicBlock, . span: Span, . place: Place<'tcx>, . value: Operand<'tcx>, . ) -> BlockAnd<()> { . let source_info = self.source_info(span); 14 ( 0.00%) let next_target = self.cfg.start_new_block(); . . self.cfg.terminate( . block, . source_info, . TerminatorKind::DropAndReplace { place, value, target: next_target, unwind: None }, . ); . self.diverge_from(block); . . next_target.unit() . } . . /// Creates an `Assert` terminator and return the success block. . /// If the boolean condition operand is not the expected value, . /// a runtime panic will be caused with the given message. 624 ( 0.00%) crate fn assert( . &mut self, . block: BasicBlock, . cond: Operand<'tcx>, . expected: bool, . msg: AssertMessage<'tcx>, . span: Span, . ) -> BasicBlock { . let source_info = self.source_info(span); 96 ( 0.00%) let success_block = self.cfg.start_new_block(); . . self.cfg.terminate( . block, . source_info, 192 ( 0.00%) TerminatorKind::Assert { cond, expected, msg, target: success_block, cleanup: None }, . ); . self.diverge_from(block); . . success_block 384 ( 0.00%) } . . /// Unschedules any drops in the top scope. . /// . /// This is only needed for `match` arm scopes, because they have one . /// entrance per pattern, but only one exit. . crate fn clear_top_scope(&mut self, region_scope: region::Scope) { . let top_scope = self.scopes.scopes.last_mut().unwrap(); . 48 ( 0.00%) assert_eq!(top_scope.region_scope, region_scope); . . top_scope.drops.clear(); . top_scope.invalidate_cache(); . } . } . . /// Builds drops for `pop_scope` and `leave_top_scope`. 1,639,572 ( 0.03%) fn build_scope_drops<'tcx>( . cfg: &mut CFG<'tcx>, . unwind_drops: &mut DropTree, . scope: &Scope, . mut block: BasicBlock, . mut unwind_to: DropIdx, . storage_dead_on_unwind: bool, . arg_count: usize, . ) -> BlockAnd<()> { -- line 1148 ---------------------------------------- -- line 1163 ---------------------------------------- . // another set of arrows). . // . // For generators, we unwind from a drop on a local to its StorageDead . // statement. For other functions we don't worry about StorageDead. The . // drops for the unwind path should have already been generated by . // `diverge_cleanup_gen`. . . for drop_data in scope.drops.iter().rev() { 12,325 ( 0.00%) let source_info = drop_data.source_info; 6,102 ( 0.00%) let local = drop_data.local; . 12,204 ( 0.00%) match drop_data.kind { . DropKind::Value => { . // `unwind_to` should drop the value that we're about to . // schedule. If dropping this value panics, then we continue . // with the *next* value on the unwind path. . debug_assert_eq!(unwind_drops.drops[unwind_to].0.local, drop_data.local); . debug_assert_eq!(unwind_drops.drops[unwind_to].0.kind, drop_data.kind); 2,184 ( 0.00%) unwind_to = unwind_drops.drops[unwind_to].1; . . // If the operand has been moved, and we are not on an unwind . // path, then don't generate the drop. (We only take this into . // account for non-unwind paths so as not to disturb the . // caching mechanism.) . if scope.moved_locals.iter().any(|&o| o == local) { . continue; . } . . unwind_drops.add_entry(block, unwind_to); . 1,132 ( 0.00%) let next = cfg.start_new_block(); . cfg.terminate( . block, . source_info, . TerminatorKind::Drop { place: local.into(), target: next, unwind: None }, . ); . block = next; . } . DropKind::Storage => { 11,476 ( 0.00%) if storage_dead_on_unwind { . debug_assert_eq!(unwind_drops.drops[unwind_to].0.local, drop_data.local); . debug_assert_eq!(unwind_drops.drops[unwind_to].0.kind, drop_data.kind); . unwind_to = unwind_drops.drops[unwind_to].1; . } . // Only temps and vars need their storage dead. 11,476 ( 0.00%) assert!(local.index() > arg_count); 57,380 ( 0.00%) cfg.push(block, Statement { source_info, kind: StatementKind::StorageDead(local) }); . } . } . } . block.unit() 1,341,468 ( 0.03%) } . . impl<'a, 'tcx: 'a> Builder<'a, 'tcx> { . /// Build a drop tree for a breakable scope. . /// . /// If `continue_block` is `Some`, then the tree is for `continue` inside a . /// loop. Otherwise this is for `break` or `return`. 4,480 ( 0.00%) fn build_exit_tree( . &mut self, . mut drops: DropTree, . continue_block: Option, . ) -> Option> { 896 ( 0.00%) let mut blocks = IndexVec::from_elem(None, &drops.drops); 448 ( 0.00%) blocks[ROOT_NODE] = continue_block; . 1,792 ( 0.00%) drops.build_mir::(&mut self.cfg, &mut blocks); . . // Link the exit drop tree to unwind drop tree. . if drops.drops.iter().any(|(drop, _)| drop.kind == DropKind::Value) { 8 ( 0.00%) let unwind_target = self.diverge_cleanup(); . let mut unwind_indices = IndexVec::from_elem_n(unwind_target, 1); . for (drop_idx, drop_data) in drops.drops.iter_enumerated().skip(1) { 40 ( 0.00%) match drop_data.0.kind { . DropKind::Storage => { 13 ( 0.00%) if self.generator_kind.is_some() { . let unwind_drop = self . .scopes . .unwind_drops . .add_drop(drop_data.0, unwind_indices[drop_data.1]); . unwind_indices.push(unwind_drop); . } else { 13 ( 0.00%) unwind_indices.push(unwind_indices[drop_data.1]); . } . } . DropKind::Value => { 14 ( 0.00%) let unwind_drop = self . .scopes . .unwind_drops 49 ( 0.00%) .add_drop(drop_data.0, unwind_indices[drop_data.1]); . self.scopes . .unwind_drops 21 ( 0.00%) .add_entry(blocks[drop_idx].unwrap(), unwind_indices[drop_data.1]); . unwind_indices.push(unwind_drop); . } . } . } . } 448 ( 0.00%) blocks[ROOT_NODE].map(BasicBlock::unit) 4,928 ( 0.00%) } . . /// Build the unwind and generator drop trees. 3,208 ( 0.00%) crate fn build_drop_trees(&mut self) { 401 ( 0.00%) if self.generator_kind.is_some() { . self.build_generator_drop_trees(); . } else { 1,203 ( 0.00%) Self::build_unwind_tree( 401 ( 0.00%) &mut self.cfg, 401 ( 0.00%) &mut self.scopes.unwind_drops, 401 ( 0.00%) self.fn_span, 802 ( 0.00%) &mut None, . ); . } 3,208 ( 0.00%) } . . fn build_generator_drop_trees(&mut self) { . // Build the drop tree for dropping the generator while it's suspended. . let drops = &mut self.scopes.generator_drops; . let cfg = &mut self.cfg; . let fn_span = self.fn_span; . let mut blocks = IndexVec::from_elem(None, &drops.drops); . drops.build_mir::(cfg, &mut blocks); -- line 1284 ---------------------------------------- -- line 1306 ---------------------------------------- . if let DropKind::Value = drop_data.0.kind { . debug_assert!(drop_data.1 < drops.drops.next_index()); . drops.entry_points.push((drop_data.1, blocks[drop_idx].unwrap())); . } . } . Self::build_unwind_tree(cfg, drops, fn_span, resume_block); . } . 4,010 ( 0.00%) fn build_unwind_tree( . cfg: &mut CFG<'tcx>, . drops: &mut DropTree, . fn_span: Span, . resume_block: &mut Option, . ) { 802 ( 0.00%) let mut blocks = IndexVec::from_elem(None, &drops.drops); 1,203 ( 0.00%) blocks[ROOT_NODE] = *resume_block; 1,203 ( 0.00%) drops.build_mir::(cfg, &mut blocks); 1,604 ( 0.00%) if let (None, Some(resume)) = (*resume_block, blocks[ROOT_NODE]) { . cfg.terminate(resume, SourceInfo::outermost(fn_span), TerminatorKind::Resume); . 562 ( 0.00%) *resume_block = blocks[ROOT_NODE]; . } 2,807 ( 0.00%) } . } . . // DropTreeBuilder implementations. . . struct ExitScopes; . . impl<'tcx> DropTreeBuilder<'tcx> for ExitScopes { . fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock { 330 ( 0.00%) cfg.start_new_block() . } . fn add_entry(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock) { 2,384 ( 0.00%) cfg.block_data_mut(from).terminator_mut().kind = TerminatorKind::Goto { target: to }; . } . } . . struct GeneratorDrop; . . impl<'tcx> DropTreeBuilder<'tcx> for GeneratorDrop { . fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock { . cfg.start_new_block() -- line 1348 ---------------------------------------- -- line 1364 ---------------------------------------- . struct Unwind; . . impl<'tcx> DropTreeBuilder<'tcx> for Unwind { . fn make_block(cfg: &mut CFG<'tcx>) -> BasicBlock { . cfg.start_new_cleanup_block() . } . fn add_entry(cfg: &mut CFG<'tcx>, from: BasicBlock, to: BasicBlock) { . let term = &mut cfg.block_data_mut(from).terminator_mut(); 6,510 ( 0.00%) match &mut term.kind { . TerminatorKind::Drop { unwind, .. } . | TerminatorKind::DropAndReplace { unwind, .. } . | TerminatorKind::FalseUnwind { unwind, .. } 1,876 ( 0.00%) | TerminatorKind::Call { cleanup: unwind, .. } . | TerminatorKind::Assert { cleanup: unwind, .. } . | TerminatorKind::InlineAsm { cleanup: unwind, .. } => { 1,302 ( 0.00%) *unwind = Some(to); . } . TerminatorKind::Goto { .. } . | TerminatorKind::SwitchInt { .. } . | TerminatorKind::Resume . | TerminatorKind::Abort . | TerminatorKind::Return . | TerminatorKind::Unreachable . | TerminatorKind::Yield { .. } -- line 1387 ---------------------------------------- 527,921 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/fn_ctxt/_impl.rs -------------------------------------------------------------------------------- Ir -- line 40 ---------------------------------------- . . use std::collections::hash_map::Entry; . use std::iter; . use std::slice; . . impl<'a, 'tcx> FnCtxt<'a, 'tcx> { . /// Produces warning on the given node, if the current point in the . /// function is unreachable, and there hasn't been another warning. 2,617,686 ( 0.05%) pub(in super::super) fn warn_if_unreachable(&self, id: hir::HirId, span: Span, kind: &str) { . // FIXME: Combine these two 'if' expressions into one once . // let chains are implemented 583,878 ( 0.01%) if let Diverges::Always { span: orig_span, custom_note } = self.diverges.get() { . // If span arose from a desugaring of `if` or `while`, then it is the condition itself, . // which diverges, that we are about to lint on. This gives suboptimal diagnostics. . // Instead, stop here so that the `if`- or `while`-expression's block is linted instead. . if !span.is_desugaring(DesugaringKind::CondTemporary) . && !span.is_desugaring(DesugaringKind::Async) . && !orig_span.is_desugaring(DesugaringKind::Await) . { . self.diverges.set(Diverges::WarnedAlways); -- line 59 ---------------------------------------- -- line 68 ---------------------------------------- . orig_span, . custom_note . .unwrap_or("any code following this expression is unreachable"), . ) . .emit(); . }) . } . } 2,035,978 ( 0.04%) } . . /// Resolves type and const variables in `ty` if possible. Unlike the infcx . /// version (resolve_vars_if_possible), this version will . /// also select obligations if it seems useful, in an effort . /// to get more type information. 2,012,724 ( 0.04%) pub(in super::super) fn resolve_vars_with_obligations(&self, ty: Ty<'tcx>) -> Ty<'tcx> { . self.resolve_vars_with_obligations_and_mutate_fulfillment(ty, |_| {}) 2,300,256 ( 0.05%) } . . #[instrument(skip(self, mutate_fulfillment_errors), level = "debug")] . pub(in super::super) fn resolve_vars_with_obligations_and_mutate_fulfillment( . &self, . mut ty: Ty<'tcx>, . mutate_fulfillment_errors: impl Fn(&mut Vec>), . ) -> Ty<'tcx> { . // No Infer()? Nothing needs doing. 288,502 ( 0.01%) if !ty.has_infer_types_or_consts() { . debug!("no inference var, nothing needs doing"); . return ty; . } . . // If `ty` is a type variable, see whether we already know what it is. . ty = self.resolve_vars_if_possible(ty); 2,924 ( 0.00%) if !ty.has_infer_types_or_consts() { . debug!(?ty); . return ty; . } . . // If not, try resolving pending obligations as much as . // possible. This can help substantially when there are . // indirect dependencies that don't seem worth tracking . // precisely. -- line 108 ---------------------------------------- -- line 129 ---------------------------------------- . let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut(); . deferred_call_resolutions.remove(&closure_def_id).unwrap_or_default() . } . . pub fn tag(&self) -> String { . format!("{:p}", self) . } . 15,120 ( 0.00%) pub fn local_ty(&self, span: Span, nid: hir::HirId) -> LocalTy<'tcx> { . self.locals.borrow().get(&nid).cloned().unwrap_or_else(|| { . span_bug!(span, "no type for local variable {}", self.tcx.hir().node_to_string(nid)) . }) 18,144 ( 0.00%) } . . #[inline] 1,043,119 ( 0.02%) pub fn write_ty(&self, id: hir::HirId, ty: Ty<'tcx>) { . debug!("write_ty({:?}, {:?}) in fcx {}", id, self.resolve_vars_if_possible(ty), self.tag()); 300,166 ( 0.01%) self.typeck_results.borrow_mut().node_types_mut().insert(id, ty); . 150,083 ( 0.00%) if ty.references_error() { . self.has_errors.set(true); . self.set_tainted_by_errors(); . } 1,192,136 ( 0.02%) } . . pub fn write_field_index(&self, hir_id: hir::HirId, index: usize) { 3,416 ( 0.00%) self.typeck_results.borrow_mut().field_indices_mut().insert(hir_id, index); . } . . pub(in super::super) fn write_resolution( . &self, . hir_id: hir::HirId, . r: Result<(DefKind, DefId), ErrorReported>, . ) { 1,108 ( 0.00%) self.typeck_results.borrow_mut().type_dependent_defs_mut().insert(hir_id, r); . } . 5,868 ( 0.00%) pub fn write_method_call(&self, hir_id: hir::HirId, method: MethodCallee<'tcx>) { . debug!("write_method_call(hir_id={:?}, method={:?})", hir_id, method); 1,304 ( 0.00%) self.write_resolution(hir_id, Ok((DefKind::AssocFn, method.def_id))); 4,564 ( 0.00%) self.write_substs(hir_id, method.substs); . . // When the method is confirmed, the `method.substs` includes . // parameters from not just the method, but also the impl of . // the method -- in particular, the `Self` type will be fully . // resolved. However, those are not something that the "user . // specified" -- i.e., those types come from the inferred type . // of the receiver, not something the user wrote. So when we . // create the user-substs, we want to replace those earlier . // types with just the types that the user actually wrote -- . // that is, those that appear on the *method itself*. . // . // As an example, if the user wrote something like . // `foo.bar::(...)` -- the `Self` type here will be the . // type of `foo` (possibly adjusted), but we don't want to . // include that. We want just the `[_, u32]` part. 652 ( 0.00%) if !method.substs.is_empty() { 607 ( 0.00%) let method_generics = self.tcx.generics_of(method.def_id); 1,159 ( 0.00%) if !method_generics.params.is_empty() { 385 ( 0.00%) let user_type_annotation = self.infcx.probe(|_| { . let user_substs = UserSubsts { 440 ( 0.00%) substs: InternalSubsts::for_item(self.tcx, method.def_id, |param, _| { 258 ( 0.00%) let i = param.index as usize; 258 ( 0.00%) if i < method_generics.parent_count { 260 ( 0.00%) self.infcx.var_for_def(DUMMY_SP, param) . } else { 231 ( 0.00%) method.substs[i] . } . }), . user_self_ty: None, // not relevant here . }; . . self.infcx.canonicalize_user_type_annotation(UserType::TypeOf( 165 ( 0.00%) method.def_id, . user_substs, . )) . }); . . debug!("write_method_call: user_type_annotation={:?}", user_type_annotation); 715 ( 0.00%) self.write_user_type_annotation(hir_id, user_type_annotation); . } . } 5,216 ( 0.00%) } . 9,402 ( 0.00%) pub fn write_substs(&self, node_id: hir::HirId, substs: SubstsRef<'tcx>) { 1,567 ( 0.00%) if !substs.is_empty() { . debug!("write_substs({:?}, {:?}) in fcx {}", node_id, substs, self.tag()); . 2,192 ( 0.00%) self.typeck_results.borrow_mut().node_substs_mut().insert(node_id, substs); . } 10,969 ( 0.00%) } . . /// Given the substs that we just converted from the HIR, try to . /// canonicalize them and store them as user-given substitutions . /// (i.e., substitutions that must be respected by the NLL check). . /// . /// This should be invoked **before any unifications have . /// occurred**, so that annotations like `Vec<_>` are preserved . /// properly. -- line 227 ---------------------------------------- -- line 230 ---------------------------------------- . &self, . hir_id: hir::HirId, . def_id: DefId, . substs: SubstsRef<'tcx>, . user_self_ty: Option>, . ) { . debug!("fcx {}", self.tag()); . 6 ( 0.00%) if Self::can_contain_user_lifetime_bounds((substs, user_self_ty)) { 8,118 ( 0.00%) let canonicalized = self.infcx.canonicalize_user_type_annotation(UserType::TypeOf( . def_id, . UserSubsts { substs, user_self_ty }, . )); . debug!(?canonicalized); 9,594 ( 0.00%) self.write_user_type_annotation(hir_id, canonicalized); . } . } . 13,481 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub fn write_user_type_annotation( . &self, . hir_id: hir::HirId, . canonical_user_type_annotation: CanonicalUserType<'tcx>, . ) { . debug!("fcx {}", self.tag()); . 3,172 ( 0.00%) if !canonical_user_type_annotation.is_identity() { 576 ( 0.00%) self.typeck_results . .borrow_mut() . .user_provided_types_mut() 2,304 ( 0.00%) .insert(hir_id, canonical_user_type_annotation); . } else { . debug!("skipping identity substs"); . } . } . 101,575 ( 0.00%) #[instrument(skip(self, expr), level = "debug")] . pub fn apply_adjustments(&self, expr: &hir::Expr<'_>, adj: Vec>) { . debug!("expr = {:#?}", expr); . 5,975 ( 0.00%) if adj.is_empty() { . return; . } . . for a in &adj { 8,604 ( 0.00%) if let Adjust::NeverToAny = a.kind { 216 ( 0.00%) if a.target.is_ty_var() { 30 ( 0.00%) self.diverging_type_vars.borrow_mut().insert(a.target); . debug!("apply_adjustments: adding `{:?}` as diverging type var", a.target); . } . } . } . . let autoborrow_mut = adj.iter().any(|adj| { 20,868 ( 0.00%) matches!( 1,740 ( 0.00%) adj, . &Adjustment { . kind: Adjust::Borrow(AutoBorrow::Ref(_, AutoBorrowMutability::Mut { .. })), . .. . } . ) . }); . 13,122 ( 0.00%) match self.typeck_results.borrow_mut().adjustments_mut().entry(expr.hir_id) { . Entry::Vacant(entry) => { . entry.insert(adj); . } . Entry::Occupied(mut entry) => { . debug!(" - composing on top of {:?}", entry.get()); . match (&entry.get()[..], &adj[..]) { . // Applying any adjustment on top of a NeverToAny . // is a valid NeverToAny adjustment, because it can't -- line 301 ---------------------------------------- -- line 324 ---------------------------------------- . }; . *entry.get_mut() = adj; . } . } . . // If there is an mutable auto-borrow, it is equivalent to `&mut `. . // In this case implicit use of `Deref` and `Index` within `` should . // instead be `DerefMut` and `IndexMut`, so fix those up. 6,561 ( 0.00%) if autoborrow_mut { 1,120 ( 0.00%) self.convert_place_derefs_to_mutable(expr); . } . } . . /// Basically whenever we are converting from a type scheme into . /// the fn body space, we always want to normalize associated . /// types as well. This function combines the two. . fn instantiate_type_scheme(&self, span: Span, substs: SubstsRef<'tcx>, value: T) -> T . where . T: TypeFoldable<'tcx>, . { . debug!("instantiate_type_scheme(value={:?}, substs={:?})", value, substs); 1,105 ( 0.00%) let value = value.subst(self.tcx, substs); . let result = self.normalize_associated_types_in(span, value); . debug!("instantiate_type_scheme = {:?}", result); . result . } . . /// As `instantiate_type_scheme`, but for the bounds found in a . /// generic type scheme. . pub(in super::super) fn instantiate_bounds( . &self, . span: Span, . def_id: DefId, . substs: SubstsRef<'tcx>, . ) -> (ty::InstantiatedPredicates<'tcx>, Vec) { 1,333 ( 0.00%) let bounds = self.tcx.predicates_of(def_id); 463 ( 0.00%) let spans: Vec = bounds.predicates.iter().map(|(_, span)| *span).collect(); 5,332 ( 0.00%) let result = bounds.instantiate(self.tcx, substs); . let result = self.normalize_associated_types_in(span, result); . debug!( . "instantiate_bounds(bounds={:?}, substs={:?}) = {:?}, {:?}", . bounds, substs, result, spans, . ); 7,998 ( 0.00%) (result, spans) . } . . /// Replaces the opaque types from the given value with type variables, . /// and records the `OpaqueTypeMap` for later use during writeback. See . /// `InferCtxt::instantiate_opaque_types` for more details. 2,464 ( 0.00%) #[instrument(skip(self, value_span), level = "debug")] 2,156 ( 0.00%) pub(in super::super) fn instantiate_opaque_types_from_value>( . &self, . value: T, . value_span: Span, . ) -> T { . self.register_infer_ok_obligations(self.instantiate_opaque_types( 308 ( 0.00%) self.body_id, 308 ( 0.00%) self.param_env, . value, . value_span, . )) . } . . /// Convenience method which tracks extra diagnostic information for normalization . /// that occurs as a result of WF checking. The `hir_id` is the `HirId` of the hir item . /// whose type is being wf-checked - this is used to construct a more precise span if -- line 389 ---------------------------------------- -- line 395 ---------------------------------------- . &self, . span: Span, . value: T, . loc: WellFormedLoc, . ) -> T . where . T: TypeFoldable<'tcx>, . { 2,646 ( 0.00%) self.inh.normalize_associated_types_in_with_cause( 1,632 ( 0.00%) ObligationCause::new(span, self.body_id, ObligationCauseCode::WellFormed(Some(loc))), 3,066 ( 0.00%) self.param_env, . value, . ) . } . . pub(in super::super) fn normalize_associated_types_in(&self, span: Span, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 84,163 ( 0.00%) self.inh.normalize_associated_types_in(span, self.body_id, self.param_env, value) . } . . pub(in super::super) fn normalize_associated_types_in_as_infer_ok( . &self, . span: Span, . value: T, . ) -> InferOk<'tcx, T> . where . T: TypeFoldable<'tcx>, . { 2,277 ( 0.00%) self.inh.partially_normalize_associated_types_in( 2,893 ( 0.00%) ObligationCause::misc(span, self.body_id), 1,091 ( 0.00%) self.param_env, 2,462 ( 0.00%) value, . ) . } . . pub fn require_type_meets( . &self, . ty: Ty<'tcx>, . span: Span, . code: traits::ObligationCauseCode<'tcx>, . def_id: DefId, . ) { 36,967 ( 0.00%) self.register_bound(ty, def_id, traits::ObligationCause::new(span, self.body_id, code)); . } . 13,456 ( 0.00%) pub fn require_type_is_sized( . &self, . ty: Ty<'tcx>, . span: Span, . code: traits::ObligationCauseCode<'tcx>, . ) { 2,913 ( 0.00%) if !ty.references_error() { 14,565 ( 0.00%) let lang_item = self.tcx.require_lang_item(LangItem::Sized, None); . self.require_type_meets(ty, span, code, lang_item); . } 13,456 ( 0.00%) } . 6,155 ( 0.00%) pub fn require_type_is_sized_deferred( . &self, . ty: Ty<'tcx>, . span: Span, . code: traits::ObligationCauseCode<'tcx>, . ) { 1,231 ( 0.00%) if !ty.references_error() { 9,848 ( 0.00%) self.deferred_sized_obligations.borrow_mut().push((ty, span, code)); . } 6,155 ( 0.00%) } . 15,280 ( 0.00%) pub fn register_bound( . &self, . ty: Ty<'tcx>, . def_id: DefId, . cause: traits::ObligationCause<'tcx>, . ) { 3,056 ( 0.00%) if !ty.references_error() { 21,392 ( 0.00%) self.fulfillment_cx.borrow_mut().register_bound( . self, 3,056 ( 0.00%) self.param_env, . ty, . def_id, 12,224 ( 0.00%) cause, . ); . } 15,280 ( 0.00%) } . . pub fn to_ty(&self, ast_t: &hir::Ty<'_>) -> Ty<'tcx> { . let t = >::ast_ty_to_ty(self, ast_t); 198 ( 0.00%) self.register_wf_obligation(t.into(), ast_t.span, traits::MiscObligation); . t . } . 80 ( 0.00%) pub fn to_ty_saving_user_provided_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> { . let ty = self.to_ty(ast_ty); . debug!("to_ty_saving_user_provided_ty: ty={:?}", ty); . . if Self::can_contain_user_lifetime_bounds(ty) { . let c_ty = self.infcx.canonicalize_response(UserType::Ty(ty)); . debug!("to_ty_saving_user_provided_ty: c_ty={:?}", c_ty); . self.typeck_results.borrow_mut().user_provided_types_mut().insert(ast_ty.hir_id, c_ty); . } . . ty 80 ( 0.00%) } . . pub fn array_length_to_const(&self, length: &hir::ArrayLen) -> &'tcx ty::Const<'tcx> { . match length { . &hir::ArrayLen::Infer(_, span) => self.ct_infer(self.tcx.types.usize, None, span), . hir::ArrayLen::Body(anon_const) => self.to_const(anon_const), . } . } . -- line 507 ---------------------------------------- -- line 540 ---------------------------------------- . // which hopefully will be fixed by the time you see this comment, dear . // reader, although I have my doubts). Also pass in types with inference . // types, because they may be repeated. Other sorts of things are already . // sufficiently enforced with erased regions. =) . fn can_contain_user_lifetime_bounds(t: T) -> bool . where . T: TypeFoldable<'tcx>, . { 86 ( 0.00%) t.has_free_regions() || t.has_projections() || t.has_infer_types() . } . 1,060,976 ( 0.02%) pub fn node_ty(&self, id: hir::HirId) -> Ty<'tcx> { 1,515,680 ( 0.03%) match self.typeck_results.borrow().node_types().get(id) { 303,136 ( 0.01%) Some(&t) => t, . None if self.is_tainted_by_errors() => self.tcx.ty_error(), . None => { . bug!( . "no type for node {}: {} in fcx {}", . id, . self.tcx.hir().node_to_string(id), . self.tag() . ); . } . } 909,408 ( 0.02%) } . . pub fn node_ty_opt(&self, id: hir::HirId) -> Option> { . match self.typeck_results.borrow().node_types().get(id) { . Some(&t) => Some(t), . None if self.is_tainted_by_errors() => Some(self.tcx.ty_error()), . None => None, . } . } . . /// Registers an obligation for checking later, during regionck, that `arg` is well-formed. 36,850 ( 0.00%) pub fn register_wf_obligation( . &self, . arg: subst::GenericArg<'tcx>, . span: Span, . code: traits::ObligationCauseCode<'tcx>, . ) { . // WF obligations never themselves fail, so no real need to give a detailed cause: 33,289 ( 0.00%) let cause = traits::ObligationCause::new(span, self.body_id, code); 3,685 ( 0.00%) self.register_predicate(traits::Obligation::new( 14,988 ( 0.00%) cause, 3,747 ( 0.00%) self.param_env, 14,988 ( 0.00%) ty::Binder::dummy(ty::PredicateKind::WellFormed(arg)).to_predicate(self.tcx), . )); 29,480 ( 0.00%) } . . /// Registers obligations that all `substs` are well-formed. . pub fn add_wf_bounds(&self, substs: SubstsRef<'tcx>, expr: &hir::Expr<'_>) { 13,600 ( 0.00%) for arg in substs.iter().filter(|arg| { . matches!(arg.unpack(), GenericArgKind::Type(..) | GenericArgKind::Const(..)) . }) { 4,482 ( 0.00%) self.register_wf_obligation(arg, expr.span, traits::MiscObligation); . } . } . . // FIXME(arielb1): use this instead of field.ty everywhere . // Only for fields! Returns for methods> . // Indifferent to privacy flags . pub fn field_ty( . &self, . span: Span, . field: &'tcx ty::FieldDef, . substs: SubstsRef<'tcx>, . ) -> Ty<'tcx> { 5,208 ( 0.00%) self.normalize_associated_types_in(span, &field.ty(self.tcx, substs)) . } . 3,456 ( 0.00%) pub(in super::super) fn resolve_generator_interiors(&self, def_id: DefId) { . let mut generators = self.deferred_generator_interiors.borrow_mut(); 2,688 ( 0.00%) for (body_id, interior, kind) in generators.drain(..) { . self.select_obligations_where_possible(false, |_| {}); . crate::check::generator_interior::resolve_interior( . self, def_id, body_id, interior, kind, . ); . } 3,072 ( 0.00%) } . 22,374 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub(in super::super) fn select_all_obligations_or_error(&self) { 7,458 ( 0.00%) let errors = self.fulfillment_cx.borrow_mut().select_all_or_error(&self); . 2,486 ( 0.00%) if !errors.is_empty() { . self.report_fulfillment_errors(&errors, self.inh.body_id, false); . } . } . . /// Select as many obligations as we can at present. 1,920 ( 0.00%) pub(in super::super) fn select_obligations_where_possible( . &self, . fallback_has_occurred: bool, . mutate_fulfillment_errors: impl Fn(&mut Vec>), . ) { 13,812 ( 0.00%) let mut result = self.fulfillment_cx.borrow_mut().select_where_possible(self); 4,212 ( 0.00%) if !result.is_empty() { . mutate_fulfillment_errors(&mut result); . self.report_fulfillment_errors(&result, self.inh.body_id, fallback_has_occurred); . } 2,304 ( 0.00%) } . . /// For the overloaded place expressions (`*x`, `x[3]`), the trait . /// returns a type of `&T`, but the actual type we assign to the . /// *expression* is `T`. So this function just peels off the return . /// type by one layer to yield `T`. . pub(in super::super) fn make_overloaded_place_return_type( . &self, . method: MethodCallee<'tcx>, . ) -> ty::TypeAndMut<'tcx> { . // extract method return type, which will be &T; 56 ( 0.00%) let ret_ty = method.sig.output(); . . // method returns &T, but the type as visible to user is T, so deref 84 ( 0.00%) ret_ty.builtin_deref(true).unwrap() . } . 1,302 ( 0.00%) #[instrument(skip(self), level = "debug")] . fn self_type_matches_expected_vid( . &self, . trait_ref: ty::PolyTraitRef<'tcx>, . expected_vid: ty::TyVid, . ) -> bool { 558 ( 0.00%) let self_ty = self.shallow_resolve(trait_ref.skip_binder().self_ty()); . debug!(?self_ty); . 740 ( 0.00%) match *self_ty.kind() { 180 ( 0.00%) ty::Infer(ty::TyVar(found_vid)) => { . // FIXME: consider using `sub_root_var` here so we . // can see through subtyping. 180 ( 0.00%) let found_vid = self.root_var(found_vid); . debug!("self_type_matches_expected_vid - found_vid={:?}", found_vid); . expected_vid == found_vid . } . _ => false, . } . } . 180 ( 0.00%) #[instrument(skip(self), level = "debug")] 210 ( 0.00%) pub(in super::super) fn obligations_for_self_ty<'b>( . &'b self, . self_ty: ty::TyVid, . ) -> impl Iterator, traits::PredicateObligation<'tcx>)> . + Captures<'tcx> . + 'b { . // FIXME: consider using `sub_root_var` here so we . // can see through subtyping. 90 ( 0.00%) let ty_var_root = self.root_var(self_ty); . trace!("pending_obligations = {:#?}", self.fulfillment_cx.borrow().pending_obligations()); . 120 ( 0.00%) self.fulfillment_cx . .borrow() . .pending_obligations() . .into_iter() 1,356 ( 0.00%) .filter_map(move |obligation| { 226 ( 0.00%) let bound_predicate = obligation.predicate.kind(); 2,486 ( 0.00%) match bound_predicate.skip_binder() { 144 ( 0.00%) ty::PredicateKind::Projection(data) => Some(( 72 ( 0.00%) bound_predicate.rebind(data).required_poly_trait_ref(self.tcx), 216 ( 0.00%) obligation, . )), . ty::PredicateKind::Trait(data) => { 3,900 ( 0.00%) Some((bound_predicate.rebind(data).to_poly_trait_ref(), obligation)) . } . ty::PredicateKind::Subtype(..) => None, . ty::PredicateKind::Coerce(..) => None, . ty::PredicateKind::RegionOutlives(..) => None, . ty::PredicateKind::TypeOutlives(..) => None, . ty::PredicateKind::WellFormed(..) => None, . ty::PredicateKind::ObjectSafe(..) => None, . ty::PredicateKind::ConstEvaluatable(..) => None, -- line 711 ---------------------------------------- -- line 716 ---------------------------------------- . // possibly be referring to the current closure, . // because we haven't produced the `Closure` for . // this closure yet; this is exactly why the other . // code is looking for a self type of an unresolved . // inference variable. . ty::PredicateKind::ClosureKind(..) => None, . ty::PredicateKind::TypeWellFormedFromEnv(..) => None, . } 1,130 ( 0.00%) }) 1,400 ( 0.00%) .filter(move |(tr, _)| self.self_type_matches_expected_vid(*tr, ty_var_root)) . } . . pub(in super::super) fn type_var_is_sized(&self, self_ty: ty::TyVid) -> bool { . self.obligations_for_self_ty(self_ty) . .any(|(tr, _)| Some(tr.def_id()) == self.tcx.lang_items().sized_trait()) . } . . pub(in super::super) fn err_args(&self, len: usize) -> Vec> { -- line 733 ---------------------------------------- -- line 739 ---------------------------------------- . #[instrument(skip(self, call_span), level = "debug")] . pub(in super::super) fn expected_inputs_for_expected_output( . &self, . call_span: Span, . expected_ret: Expectation<'tcx>, . formal_ret: Ty<'tcx>, . formal_args: &[Ty<'tcx>], . ) -> Vec> { 4,122 ( 0.00%) let formal_ret = self.resolve_vars_with_obligations(formal_ret); . let ret_ty = match expected_ret.only_has_type(self) { 945 ( 0.00%) Some(ret) => ret, . None => return Vec::new(), . }; 945 ( 0.00%) let expect_args = self 10,616 ( 0.00%) .fudge_inference_if_ok(|| { . // Attempt to apply a subtyping relationship between the formal . // return type (likely containing type variables if the function . // is polymorphic) and the expected return type. . // No argument expectations are produced if unification fails. 945 ( 0.00%) let origin = self.misc(call_span); 3,780 ( 0.00%) let ures = self.at(&origin, self.param_env).sup(ret_ty, &formal_ret); . . // FIXME(#27336) can't use ? here, Try::from_error doesn't default . // to identity so the resulting type is not constrained. 2,835 ( 0.00%) match ures { . Ok(ok) => { . // Process any obligations locally as much as . // we can. We don't care if some things turn . // out unconstrained or ambiguous, as we're . // just trying to get hints here. . let errors = self.save_and_restore_in_snapshot_flag(|_| { 5,580 ( 0.00%) let mut fulfill = >::new(self.tcx); 4,346 ( 0.00%) for obligation in ok.obligations { 930 ( 0.00%) fulfill.register_predicate_obligation(self, obligation); . } 1,860 ( 0.00%) fulfill.select_where_possible(self) . }); . 930 ( 0.00%) if !errors.is_empty() { . return Err(()); . } . } . Err(_) => return Err(()), . } . . // Record all the argument types, with the substitutions . // produced from the above subtyping unification. 2,790 ( 0.00%) Ok(formal_args.iter().map(|&ty| self.resolve_vars_if_possible(ty)).collect()) . }) . .unwrap_or_default(); . debug!(?formal_args, ?formal_ret, ?expect_args, ?expected_ret); 2,172 ( 0.00%) expect_args . } . 1,131 ( 0.00%) pub(in super::super) fn resolve_lang_item_path( . &self, . lang_item: hir::LangItem, . span: Span, . hir_id: hir::HirId, . expr_hir_id: Option, . ) -> (Res, Ty<'tcx>) { 870 ( 0.00%) let def_id = self.tcx.require_lang_item(lang_item, Some(span)); 522 ( 0.00%) let def_kind = self.tcx.def_kind(def_id); . 522 ( 0.00%) let item_ty = if let DefKind::Variant = def_kind { 120 ( 0.00%) self.tcx.type_of(self.tcx.parent(def_id).expect("variant w/out parent")) . } else { . self.tcx.type_of(def_id) . }; 435 ( 0.00%) let substs = self.infcx.fresh_substs_for_item(span, def_id); 87 ( 0.00%) let ty = item_ty.subst(self.tcx, substs); . 174 ( 0.00%) self.write_resolution(hir_id, Ok((def_kind, def_id))); 609 ( 0.00%) self.add_required_obligations_with_code( . span, . def_id, . &substs, 770 ( 0.00%) match lang_item { . hir::LangItem::IntoFutureIntoFuture => { . ObligationCauseCode::AwaitableExpr(expr_hir_id) . } . hir::LangItem::IteratorNext | hir::LangItem::IntoIterIntoIter => { 44 ( 0.00%) ObligationCauseCode::ForLoopIterator . } . hir::LangItem::TryTraitFromOutput . | hir::LangItem::TryTraitFromResidual 24 ( 0.00%) | hir::LangItem::TryTraitBranch => ObligationCauseCode::QuestionMark, 171 ( 0.00%) _ => traits::ItemObligation(def_id), . }, . ); 609 ( 0.00%) (Res::Def(def_kind, def_id), ty) 696 ( 0.00%) } . . /// Resolves an associated value path into a base type and associated constant, or method . /// resolution. The newly resolved definition is written into `type_dependent_defs`. 23,830 ( 0.00%) pub fn resolve_ty_and_res_fully_qualified_call( . &self, . qpath: &'tcx QPath<'tcx>, . hir_id: hir::HirId, . span: Span, . ) -> (Res, Option>, &'tcx [hir::PathSegment<'tcx>]) { . debug!( . "resolve_ty_and_res_fully_qualified_call: qpath={:?} hir_id={:?} span={:?}", . qpath, hir_id, span . ); 7,539 ( 0.00%) let (ty, qself, item_segment) = match *qpath { . QPath::Resolved(ref opt_qself, ref path) => { 15,316 ( 0.00%) return ( 10,940 ( 0.00%) path.res, . opt_qself.as_ref().map(|qself| self.to_ty(qself)), 2,188 ( 0.00%) path.segments, . ); . } . QPath::TypeRelative(ref qself, ref segment) => { . // Don't use `self.to_ty`, since this will register a WF obligation. . // If we're trying to call a non-existent method on a trait . // (e.g. `MyTrait::missing_method`), then resolution will . // give us a `QPath::TypeRelative` with a trait object as . // `qself`. In that case, we want to avoid registering a WF obligation . // for `dyn MyTrait`, since we don't actually need the trait . // to be object-safe. . // We manually call `register_wf_obligation` in the success path . // below. 195 ( 0.00%) (>::ast_ty_to_ty_in_path(self, qself), qself, segment) . } . QPath::LangItem(..) => { . bug!("`resolve_ty_and_res_fully_qualified_call` called on `LangItem`") . } . }; 1,950 ( 0.00%) if let Some(&cached_result) = self.typeck_results.borrow().type_dependent_defs().get(hir_id) . { . self.register_wf_obligation(ty.into(), qself.span, traits::WellFormed(None)); . // Return directly on cache hit. This is useful to avoid doubly reporting . // errors with default match binding modes. See #44614. . let def = cached_result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)); . return (def, Some(ty), slice::from_ref(&**item_segment)); . } 780 ( 0.00%) let item_name = item_segment.ident; 2,535 ( 0.00%) let result = self 975 ( 0.00%) .resolve_fully_qualified_call(span, item_name, ty, qself.span, hir_id) . .or_else(|error| { . let result = match error { . method::MethodError::PrivateMatch(kind, def_id, _) => Ok((kind, def_id)), . _ => Err(ErrorReported), . }; . . // If we have a path like `MyTrait::missing_method`, then don't register . // a WF obligation for `dyn MyTrait` when method lookup fails. Otherwise, -- line 886 ---------------------------------------- -- line 899 ---------------------------------------- . None, . ) { . e.emit(); . } . } . result . }); . 195 ( 0.00%) if result.is_ok() { 1,365 ( 0.00%) self.register_wf_obligation(ty.into(), qself.span, traits::WellFormed(None)); . } . . // Write back the new resolution. 390 ( 0.00%) self.write_resolution(hir_id, result); 2,340 ( 0.00%) ( . result.map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), . Some(ty), . slice::from_ref(&**item_segment), . ) 21,447 ( 0.00%) } . . /// Given a function `Node`, return its `FnDecl` if it exists, or `None` otherwise. . pub(in super::super) fn get_node_fn_decl( . &self, . node: Node<'tcx>, . ) -> Option<(&'tcx hir::FnDecl<'tcx>, Ident, bool)> { 296 ( 0.00%) match node { 20 ( 0.00%) Node::Item(&hir::Item { ident, kind: hir::ItemKind::Fn(ref sig, ..), .. }) => { . // This is less than ideal, it will not suggest a return type span on any . // method called `main`, regardless of whether it is actually the entry point, . // but it will still present it as the reason for the expected type. . Some((&sig.decl, ident, ident.name != sym::main)) . } . Node::TraitItem(&hir::TraitItem { . ident, . kind: hir::TraitItemKind::Fn(ref sig, ..), . .. . }) => Some((&sig.decl, ident, true)), . Node::ImplItem(&hir::ImplItem { . ident, 66 ( 0.00%) kind: hir::ImplItemKind::Fn(ref sig, ..), . .. 128 ( 0.00%) }) => Some((&sig.decl, ident, false)), . _ => None, . } . } . . /// Given a `HirId`, return the `FnDecl` of the method it is enclosed by and whether a . /// suggestion can be made, `None` otherwise. 8 ( 0.00%) pub fn get_fn_decl(&self, blk_id: hir::HirId) -> Option<(&'tcx hir::FnDecl<'tcx>, bool)> { . // Get enclosing Fn, if it is a function or a trait method, unless there's a `loop` or . // `while` before reaching it, as block tail returns are not available in them. 10 ( 0.00%) self.tcx.hir().get_return_block(blk_id).and_then(|blk_id| { 10 ( 0.00%) let parent = self.tcx.hir().get(blk_id); . self.get_node_fn_decl(parent).map(|(fn_decl, _, is_main)| (fn_decl, is_main)) . }) 10 ( 0.00%) } . . pub(in super::super) fn note_internal_mutation_in_method( . &self, . err: &mut DiagnosticBuilder<'_>, . expr: &hir::Expr<'_>, . expected: Ty<'tcx>, . found: Ty<'tcx>, . ) { -- line 963 ---------------------------------------- -- line 1031 ---------------------------------------- . err.help(&format!( . "if the expected type is due to type inference, cast the expected `fn` to a function \ . pointer: `{} as {}`", . self.tcx.def_path_str_with_substs(did, substs), . sig . )); . } . 245 ( 0.00%) pub(in super::super) fn could_remove_semicolon( . &self, . blk: &'tcx hir::Block<'tcx>, . expected_ty: Ty<'tcx>, . ) -> Option<(Span, StatementAsExpression)> { . // Be helpful when the user wrote `{... expr;}` and . // taking the `;` off is enough to fix the error. 70 ( 0.00%) let last_stmt = blk.stmts.last()?; 70 ( 0.00%) let last_expr = match last_stmt.kind { . hir::StmtKind::Semi(ref e) => e, . _ => return None, . }; 112 ( 0.00%) let last_expr_ty = self.node_ty(last_expr.hir_id); 84 ( 0.00%) let needs_box = match (last_expr_ty.kind(), expected_ty.kind()) { . (ty::Opaque(last_def_id, _), ty::Opaque(exp_def_id, _)) . if last_def_id == exp_def_id => . { . StatementAsExpression::CorrectType . } . (ty::Opaque(last_def_id, last_bounds), ty::Opaque(exp_def_id, exp_bounds)) => { . debug!( . "both opaque, likely future {:?} {:?} {:?} {:?}", -- line 1060 ---------------------------------------- -- line 1098 ---------------------------------------- . { . StatementAsExpression::NeedsBoxing . } . _ => StatementAsExpression::CorrectType, . } . } . _ => StatementAsExpression::CorrectType, . }; 140 ( 0.00%) if (matches!(last_expr_ty.kind(), ty::Error(_)) 140 ( 0.00%) || self.can_sub(self.param_env, last_expr_ty, expected_ty).is_err()) . && matches!(needs_box, StatementAsExpression::CorrectType) . { . return None; . } 52 ( 0.00%) let span = if last_stmt.span.from_expansion() { . let mac_call = original_sp(last_stmt.span, blk.span); . self.tcx.sess.source_map().mac_call_stmt_semi_span(mac_call)? . } else { 78 ( 0.00%) last_stmt.span.with_lo(last_stmt.span.hi() - BytePos(1)) . }; . Some((span, needs_box)) 350 ( 0.00%) } . . // Instantiates the given path, which must refer to an item with the given . // number of type parameters and type. 19,064 ( 0.00%) #[instrument(skip(self, span), level = "debug")] 28,596 ( 0.00%) pub fn instantiate_value_path( . &self, . segments: &[hir::PathSegment<'_>], . self_ty: Option>, . res: Res, . span: Span, . hir_id: hir::HirId, . ) -> (Ty<'tcx>, Res) { 7,149 ( 0.00%) let tcx = self.tcx; . 13,745 ( 0.00%) let path_segs = match res { . Res::Local(_) | Res::SelfCtor(_) => vec![], 16,470 ( 0.00%) Res::Def(kind, def_id) => >::def_ids_for_value_path_segments( . self, segments, self_ty, kind, def_id, . ), . _ => bug!("instantiate_value_path on {:?}", res), . }; . . let mut user_self_ty = None; 4,766 ( 0.00%) let mut is_alias_variant_ctor = false; 12,011 ( 0.00%) match res { . Res::Def(DefKind::Ctor(CtorOf::Variant, _), _) . if let Some(self_ty) = self_ty => . { . let adt_def = self_ty.ty_adt_def().unwrap(); . user_self_ty = Some(UserSelfTy { impl_def_id: adt_def.did, self_ty }); . is_alias_variant_ctor = true; . } 604 ( 0.00%) Res::Def(DefKind::AssocFn | DefKind::AssocConst, def_id) => { 604 ( 0.00%) let container = tcx.associated_item(def_id).container; . debug!(?def_id, ?container); 906 ( 0.00%) match container { . ty::TraitContainer(trait_did) => { 1,120 ( 0.00%) callee::check_legal_trait_for_method_call(tcx, span, None, span, trait_did) . } . ty::ImplContainer(impl_def_id) => { 380 ( 0.00%) if segments.len() == 1 { . // `::assoc` will end up here, and so . // can `T::assoc`. It this came from an . // inherent impl, we need to record the . // `T` for posterity (see `UserSelfTy` for . // details). . let self_ty = self_ty.expect("UFCS sugared assoc missing Self"); . user_self_ty = Some(UserSelfTy { impl_def_id, self_ty }); . } -- line 1168 ---------------------------------------- -- line 1173 ---------------------------------------- . } . . // Now that we have categorized what space the parameters for each . // segment belong to, let's sort out the parameters that the user . // provided (if any) into their appropriate spaces. We'll also report . // errors if type parameters are provided in an inappropriate place. . . let generic_segs: FxHashSet<_> = path_segs.iter().map(|PathSeg(_, index)| index).collect(); 9,532 ( 0.00%) let generics_has_err = >::prohibit_generics( . self, 3,736 ( 0.00%) segments.iter().enumerate().filter_map(|(index, seg)| { 9,516 ( 0.00%) if !generic_segs.contains(&index) || is_alias_variant_ctor { . Some(seg) . } else { . None . } . }), . ); . 11,553 ( 0.00%) if let Res::Local(hid) = res { 2,936 ( 0.00%) let ty = self.local_ty(span, hid).decl_ty; . let ty = self.normalize_associated_types_in(span, ty); 5,872 ( 0.00%) self.write_ty(hir_id, ty); 8,808 ( 0.00%) return (ty, res); . } . 4,575 ( 0.00%) if generics_has_err { . // Don't try to infer type parameters when prohibited generic arguments were given. . user_self_ty = None; . } . . // Now we have to compare the types that the user *actually* . // provided against the types that were *expected*. If the user . // did not provide any types, then we want to substitute inference . // variables. If the user provided some types, we may still need . // to add defaults. If the user provided *too many* types, that's . // a problem. . . let mut infer_args_for_err = FxHashSet::default(); . . let mut explicit_late_bound = ExplicitLateBound::No; 1,022 ( 0.00%) for &PathSeg(def_id, index) in &path_segs { 8,663 ( 0.00%) let seg = &segments[index]; . let generics = tcx.generics_of(def_id); . . // Argument-position `impl Trait` is treated as a normal generic . // parameter internally, but we don't allow users to specify the . // parameter's value explicitly, so we have to do some error- . // checking here. 10,220 ( 0.00%) let arg_count = >::check_generic_arg_count_for_call( . tcx, . span, . def_id, . &generics, . seg, . IsMethodCall::No, . ); . 6,132 ( 0.00%) if let ExplicitLateBound::Yes = arg_count.explicit_late_bound { . explicit_late_bound = ExplicitLateBound::Yes; . } . 5,110 ( 0.00%) if let Err(GenericArgCountMismatch { reported: Some(_), .. }) = arg_count.correct { . infer_args_for_err.insert(index); . self.set_tainted_by_errors(); // See issue #53251. . } . } . . let has_self = path_segs . .last() 1,830 ( 0.00%) .map(|PathSeg(def_id, _)| tcx.generics_of(*def_id).has_self) . .unwrap_or(false); . 12,810 ( 0.00%) let (res, self_ctor_substs) = if let Res::SelfCtor(impl_def_id) = res { . let ty = self.normalize_ty(span, tcx.at(span).type_of(impl_def_id)); . match *ty.kind() { . ty::Adt(adt_def, substs) if adt_def.has_ctor() => { . let variant = adt_def.non_enum_variant(); . let ctor_def_id = variant.ctor_def_id.unwrap(); . ( . Res::Def(DefKind::Ctor(CtorOf::Struct, variant.ctor_kind), ctor_def_id), . Some(substs), -- line 1254 ---------------------------------------- -- line 1275 ---------------------------------------- . } . } . err.emit(); . . return (tcx.ty_error(), res); . } . } . } else { 9,150 ( 0.00%) (res, None) . }; . let def_id = res.def_id(); . . // The things we are substituting into the type should not contain . // escaping late-bound regions, and nor should the base type scheme. . let ty = tcx.type_of(def_id); . 4,575 ( 0.00%) let arg_count = GenericArgCountResult { 1,830 ( 0.00%) explicit_late_bound, 915 ( 0.00%) correct: if infer_args_for_err.is_empty() { . Ok(()) . } else { . Err(GenericArgCountMismatch::default()) . }, . }; . . struct CreateCtorSubstsContext<'a, 'tcx> { . fcx: &'a FnCtxt<'a, 'tcx>, -- line 1301 ---------------------------------------- -- line 1304 ---------------------------------------- . infer_args_for_err: &'a FxHashSet, . segments: &'a [hir::PathSegment<'a>], . } . impl<'tcx, 'a> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for CreateCtorSubstsContext<'a, 'tcx> { . fn args_for_def_id( . &mut self, . def_id: DefId, . ) -> (Option<&'a hir::GenericArgs<'a>>, bool) { 2,044 ( 0.00%) if let Some(&PathSeg(_, index)) = 3,108 ( 0.00%) self.path_segs.iter().find(|&PathSeg(did, _)| *did == def_id) . { . // If we've encountered an `impl Trait`-related error, we're just . // going to infer the arguments for better error messages. 6,132 ( 0.00%) if !self.infer_args_for_err.contains(&index) { . // Check whether the user has provided generic arguments. 8,176 ( 0.00%) if let Some(ref data) = self.segments[index].args { . return (Some(data), self.segments[index].infer_args); . } . } 5,110 ( 0.00%) return (None, self.segments[index].infer_args); . } . . (None, true) . } . . fn provided_kind( . &mut self, . param: &ty::GenericParamDef, -- line 1331 ---------------------------------------- -- line 1347 ---------------------------------------- . (GenericParamDefKind::Const { .. }, GenericArg::Infer(inf)) => { . let tcx = self.fcx.tcx(); . self.fcx.ct_infer(tcx.type_of(param.def_id), Some(param), inf.span).into() . } . _ => unreachable!(), . } . } . 5,464 ( 0.00%) fn inferred_kind( . &mut self, . substs: Option<&[subst::GenericArg<'tcx>]>, . param: &ty::GenericParamDef, . infer_args: bool, . ) -> subst::GenericArg<'tcx> { 683 ( 0.00%) let tcx = self.fcx.tcx(); 2,977 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { 219 ( 0.00%) self.fcx.re_infer(Some(param), self.span).unwrap().into() . } . GenericParamDefKind::Type { has_default, .. } => { 928 ( 0.00%) if !infer_args && has_default { . // If we have a default, then we it doesn't matter that we're not . // inferring the type arguments: we provide the default where any . // is missing. . let default = tcx.type_of(param.def_id); . self.fcx . .normalize_ty( . self.span, . default.subst_spanned(tcx, substs.unwrap(), Some(self.span)), -- line 1375 ---------------------------------------- -- line 1392 ---------------------------------------- . self.fcx.var_for_def(self.span, param) . } . } . } . } . } . . let substs = self_ctor_substs.unwrap_or_else(|| { 11,895 ( 0.00%) >::create_substs_for_generic_args( . tcx, . def_id, . &[], . has_self, . self_ty, . &arg_count, 11,895 ( 0.00%) &mut CreateCtorSubstsContext { . fcx: self, . span, . path_segs: &path_segs, . infer_args_for_err: &infer_args_for_err, . segments, . }, . ) . }); . assert!(!substs.has_escaping_bound_vars()); 915 ( 0.00%) assert!(!ty.has_escaping_bound_vars()); . . // First, store the "user substs" for later. 3,660 ( 0.00%) self.write_user_type_annotation_from_substs(hir_id, def_id, substs, user_self_ty); . . self.add_required_obligations(span, def_id, &substs); . . // Substitute the values for the type parameters into the type of . // the referenced item. . let ty_substituted = self.instantiate_type_scheme(span, &substs, ty); . 2,935 ( 0.00%) if let Some(UserSelfTy { impl_def_id, self_ty }) = user_self_ty { . // In the case of `Foo::method` and `>::method`, if `method` . // is inherent, there is no `Self` parameter; instead, the impl needs . // type parameters, which we can infer by unifying the provided `Self` . // with the substituted impl type. . // This also occurs for an enum variant on a type alias. . let ty = tcx.type_of(impl_def_id); . 380 ( 0.00%) let impl_ty = self.instantiate_type_scheme(span, &substs, ty); 950 ( 0.00%) match self.at(&self.misc(span), self.param_env).eq(impl_ty, self_ty) { 570 ( 0.00%) Ok(ok) => self.register_infer_ok_obligations(ok), . Err(_) => { . self.tcx.sess.delay_span_bug( . span, . &format!( . "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?", . self_ty, . impl_ty, . ), . ); . } . } . } . . debug!("instantiate_value_path: type of {:?} is {:?}", hir_id, ty_substituted); 3,660 ( 0.00%) self.write_substs(hir_id, substs); . 5,490 ( 0.00%) (ty_substituted, res) . } . . /// Add all the obligations that are required, substituting and normalized appropriately. . crate fn add_required_obligations(&self, span: Span, def_id: DefId, substs: &SubstsRef<'tcx>) { 4,731 ( 0.00%) self.add_required_obligations_with_code( . span, . def_id, . substs, 7,145 ( 0.00%) traits::ItemObligation(def_id), . ) . } . 23,994 ( 0.00%) #[tracing::instrument(level = "debug", skip(self, span, def_id, substs))] . fn add_required_obligations_with_code( . &self, . span: Span, . def_id: DefId, . substs: &SubstsRef<'tcx>, . code: ObligationCauseCode<'tcx>, . ) { 3,999 ( 0.00%) let (bounds, _) = self.instantiate_bounds(span, def_id, &substs); . 25,784 ( 0.00%) for obligation in traits::predicates_for_generics( 11,997 ( 0.00%) traits::ObligationCause::new(span, self.body_id, code), 1,333 ( 0.00%) self.param_env, 11,997 ( 0.00%) bounds, . ) { 6,265 ( 0.00%) self.register_predicate(obligation); . } . } . . /// Resolves `typ` by a single level if `typ` is a type variable. . /// If no resolution is possible, then an error is reported. . /// Numeric inference variables may be left unresolved. 23,265 ( 0.00%) pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> { 7,755 ( 0.00%) let ty = self.resolve_vars_with_obligations(ty); 2,585 ( 0.00%) if !ty.is_ty_var() { . ty . } else { . if !self.is_tainted_by_errors() { . self.emit_inference_failure_err((**self).body_id, sp, ty.into(), vec![], E0282) . .note("type must be known at this point") . .emit(); . } . let err = self.tcx.ty_error(); . self.demand_suptype(sp, err, ty); . err . } 23,265 ( 0.00%) } . . pub(in super::super) fn with_breakable_ctxt R, R>( . &self, . id: hir::HirId, . ctxt: BreakableCtxt<'tcx>, . f: F, . ) -> (BreakableCtxt<'tcx>, R) { . let index; . { . let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); 643 ( 0.00%) index = enclosing_breakables.stack.len(); . enclosing_breakables.by_id.insert(id, index); 5,144 ( 0.00%) enclosing_breakables.stack.push(ctxt); . } . let result = f(); . let ctxt = { . let mut enclosing_breakables = self.enclosing_breakables.borrow_mut(); . debug_assert!(enclosing_breakables.stack.len() == index + 1); . enclosing_breakables.by_id.remove(&id).expect("missing breakable context"); . enclosing_breakables.stack.pop().expect("missing breakable context") . }; 3,896 ( 0.00%) (ctxt, result) . } . . /// Instantiate a QueryResponse in a probe context, without a . /// good ObligationCause. 7,271 ( 0.00%) pub(in super::super) fn probe_instantiate_query_response( . &self, . span: Span, . original_values: &OriginalQueryValues<'tcx>, . query_result: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>, . ) -> InferResult<'tcx, Ty<'tcx>> { 3,966 ( 0.00%) self.instantiate_query_response_and_region_obligations( 4,627 ( 0.00%) &traits::ObligationCause::misc(span, self.body_id), 661 ( 0.00%) self.param_env, . original_values, . query_result, . ) 5,949 ( 0.00%) } . . /// Returns `true` if an expression is contained inside the LHS of an assignment expression. . pub(in super::super) fn expr_in_place(&self, mut expr_id: hir::HirId) -> bool { . let mut contained_in_place = false; . . while let hir::Node::Expr(parent_expr) = . self.tcx.hir().get(self.tcx.hir().get_parent_node(expr_id)) . { -- line 1551 ---------------------------------------- 246,728 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_parse/src/parser/attr.rs -------------------------------------------------------------------------------- Ir -- line 28 ---------------------------------------- . enum OuterAttributeType { . DocComment, . DocBlockComment, . Attribute, . } . . impl<'a> Parser<'a> { . /// Parses attributes that appear before an item. 1,298,160 ( 0.03%) pub(super) fn parse_outer_attributes(&mut self) -> PResult<'a, AttrWrapper> { . let mut attrs: Vec = Vec::new(); . let mut just_parsed_doc_comment = false; 721,200 ( 0.01%) let start_pos = self.token_cursor.num_next_calls; . loop { 729,185 ( 0.01%) let attr = if self.check(&token::Pound) { 2,478 ( 0.00%) let inner_error_reason = if just_parsed_doc_comment { . "an inner attribute is not permitted following an outer doc comment" . } else if !attrs.is_empty() { . "an inner attribute is not permitted following an outer attribute" . } else { . DEFAULT_UNEXPECTED_INNER_ATTR_ERR_MSG . }; . let inner_parse_policy = InnerAttrPolicy::Forbidden { . reason: inner_error_reason, . saw_doc_comment: just_parsed_doc_comment, 282 ( 0.00%) prev_attr_sp: attrs.last().map(|a| a.span), . }; . just_parsed_doc_comment = false; 1,416 ( 0.00%) Some(self.parse_attribute(inner_parse_policy)?) 292,740 ( 0.01%) } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind { 1,420 ( 0.00%) if attr_style != ast::AttrStyle::Outer { . let span = self.token.span; . let mut err = self.sess.span_diagnostic.struct_span_err_with_code( . span, . "expected outer doc comment", . error_code!(E0753), . ); . if let Some(replacement_span) = self.annotate_following_item_if_applicable( . &mut err, -- line 65 ---------------------------------------- -- line 77 ---------------------------------------- . replacement_span, . "you might have meant to write a regular comment", . String::new(), . rustc_errors::Applicability::MachineApplicable, . ); . } . err.emit(); . } 2,840 ( 0.00%) self.bump(); . just_parsed_doc_comment = true; . // Always make an outer attribute - this allows us to recover from a misplaced . // inner attribute. 34,080 ( 0.00%) Some(attr::mk_doc_comment( . comment_kind, . ast::AttrStyle::Outer, . data, 1,420 ( 0.00%) self.prev_token.span, . )) . } else { . None . }; . 3,194 ( 0.00%) if let Some(attr) = attr { 28,746 ( 0.00%) attrs.push(attr); . } else { . break; . } . } 1,009,680 ( 0.02%) Ok(AttrWrapper::new(attrs.into(), start_pos)) 1,153,920 ( 0.02%) } . . /// Matches `attribute = # ! [ meta_item ]`. . /// `inner_parse_policy` prescribes how to handle inner attributes. . // Public for rustfmt usage. 1,800 ( 0.00%) pub fn parse_attribute( . &mut self, . inner_parse_policy: InnerAttrPolicy<'_>, . ) -> PResult<'a, ast::Attribute> { . debug!( . "parse_attribute: inner_parse_policy={:?} self.token={:?}", . inner_parse_policy, self.token . ); 900 ( 0.00%) let lo = self.token.span; . // Attributes can't have attributes of their own [Editor's note: not with that attitude] . self.collect_tokens_no_attrs(|this| { . if this.eat(&token::Pound) { . let style = if this.eat(&token::Not) { . ast::AttrStyle::Inner . } else { . ast::AttrStyle::Outer . }; . 540 ( 0.00%) this.expect(&token::OpenDelim(token::Bracket))?; 720 ( 0.00%) let item = this.parse_attr_item(false)?; 540 ( 0.00%) this.expect(&token::CloseDelim(token::Bracket))?; 540 ( 0.00%) let attr_sp = lo.to(this.prev_token.span); . . // Emit error if inner attribute is encountered and forbidden. 360 ( 0.00%) if style == ast::AttrStyle::Inner { 24 ( 0.00%) this.error_on_forbidden_inner_attr(attr_sp, inner_parse_policy); . } . 5,940 ( 0.00%) Ok(attr::mk_attr_from_item(item, None, style, attr_sp)) . } else { . let token_str = pprust::token_to_string(&this.token); . let msg = &format!("expected `#`, found `{}`", token_str); . Err(this.struct_span_err(this.token.span, msg)) . } . }) 1,620 ( 0.00%) } . . fn annotate_following_item_if_applicable( . &self, . err: &mut DiagnosticBuilder<'_>, . span: Span, . attr_type: OuterAttributeType, . ) -> Option { . let mut snapshot = self.clone(); -- line 154 ---------------------------------------- -- line 209 ---------------------------------------- . Err(mut item_err) => { . item_err.cancel(); . } . Ok(None) => {} . } . Some(replacement_span) . } . 21 ( 0.00%) pub(super) fn error_on_forbidden_inner_attr(&self, attr_sp: Span, policy: InnerAttrPolicy<'_>) { 9 ( 0.00%) if let InnerAttrPolicy::Forbidden { reason, saw_doc_comment, prev_attr_sp } = policy { . let prev_attr_note = . if saw_doc_comment { "previous doc comment" } else { "previous outer attribute" }; . . let mut diag = self.struct_span_err(attr_sp, reason); . . if let Some(prev_attr_sp) = prev_attr_sp { . diag.span_label(attr_sp, "not permitted following an outer attribute") . .span_label(prev_attr_sp, prev_attr_note); -- line 226 ---------------------------------------- -- line 237 ---------------------------------------- . OuterAttributeType::Attribute, . ) . .is_some() . { . diag.note("outer attributes, like `#[test]`, annotate the item following them"); . }; . diag.emit(); . } 24 ( 0.00%) } . . /// Parses an inner part of an attribute (the path and following tokens). . /// The tokens must be either a delimited token stream, or empty token stream, . /// or the "legacy" key-value form. . /// PATH `(` TOKEN_STREAM `)` . /// PATH `[` TOKEN_STREAM `]` . /// PATH `{` TOKEN_STREAM `}` . /// PATH . /// PATH `=` UNSUFFIXED_LIT . /// The delimiters or `=` are still put into the resulting token stream. 1,800 ( 0.00%) pub fn parse_attr_item(&mut self, capture_tokens: bool) -> PResult<'a, ast::AttrItem> { 360 ( 0.00%) let item = match self.token.kind { . token::Interpolated(ref nt) => match **nt { . Nonterminal::NtMeta(ref item) => Some(item.clone().into_inner()), . _ => None, . }, . _ => None, . }; 2,160 ( 0.00%) Ok(if let Some(item) = item { . self.bump(); . item . } else { 1,080 ( 0.00%) let do_parse = |this: &mut Self| { 360 ( 0.00%) let path = this.parse_path(PathStyle::Mod)?; . let args = this.parse_attr_args()?; 1,620 ( 0.00%) Ok(ast::AttrItem { path, args, tokens: None }) 720 ( 0.00%) }; . // Attr items don't have attributes 720 ( 0.00%) if capture_tokens { self.collect_tokens_no_attrs(do_parse) } else { do_parse(self) }? . }) 2,700 ( 0.00%) } . . /// Parses attributes that appear after the opening of an item. These should . /// be preceded by an exclamation mark, but we accept and warn about one . /// terminated by a semicolon. . /// . /// Matches `inner_attrs*`. 5,064 ( 0.00%) crate fn parse_inner_attributes(&mut self) -> PResult<'a, Vec> { . let mut attrs: Vec = vec![]; . loop { 695 ( 0.00%) let start_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap(); . // Only try to parse if it is an inner attribute (has `!`). 3,485 ( 0.00%) let attr = if self.check(&token::Pound) && self.look_ahead(1, |t| t == &token::Not) { 15 ( 0.00%) Some(self.parse_attribute(InnerAttrPolicy::Permitted)?) 1,384 ( 0.00%) } else if let token::DocComment(comment_kind, attr_style, data) = self.token.kind { 71 ( 0.00%) if attr_style == ast::AttrStyle::Inner { 118 ( 0.00%) self.bump(); 1,475 ( 0.00%) Some(attr::mk_doc_comment(comment_kind, attr_style, data, self.prev_token.span)) . } else { . None . } . } else { . None . }; 1,302 ( 0.00%) if let Some(attr) = attr { 62 ( 0.00%) let end_pos: u32 = self.token_cursor.num_next_calls.try_into().unwrap(); . // If we are currently capturing tokens, mark the location of this inner attribute. . // If capturing ends up creating a `LazyTokenStream`, we will include . // this replace range with it, removing the inner attribute from the final . // `AttrAnnotatedTokenStream`. Inner attributes are stored in the parsed AST note. . // During macro expansion, they are selectively inserted back into the . // token stream (the first inner attribute is remoevd each time we invoke the . // corresponding macro). . let range = start_pos..end_pos; 186 ( 0.00%) if let Capturing::Yes = self.capture_state.capturing { . self.capture_state.inner_attr_ranges.insert(attr.id, (range, vec![])); . } 992 ( 0.00%) attrs.push(attr); . } else { . break; . } . } 3,798 ( 0.00%) Ok(attrs) 5,697 ( 0.00%) } . 1,155 ( 0.00%) crate fn parse_unsuffixed_lit(&mut self) -> PResult<'a, ast::Lit> { 187 ( 0.00%) let lit = self.parse_lit()?; . debug!("checking if {:?} is unusuffixed", lit); . 33 ( 0.00%) if !lit.kind.is_unsuffixed() { . self.struct_span_err(lit.span, "suffixed literals are not allowed in attributes") . .help( . "instead of using a suffixed literal (`1u8`, `1.0f32`, etc.), \ . use an unsuffixed version (`1`, `1.0`, etc.)", . ) . .emit(); . } . 77 ( 0.00%) Ok(lit) 990 ( 0.00%) } . . /// Parses `cfg_attr(pred, attr_item_list)` where `attr_item_list` is comma-delimited. . pub fn parse_cfg_attr(&mut self) -> PResult<'a, (ast::MetaItem, Vec<(ast::AttrItem, Span)>)> { . let cfg_predicate = self.parse_meta_item()?; . self.expect(&token::Comma)?; . . // Presumably, the majority of the time there will only be one attr. . let mut expanded_attrs = Vec::with_capacity(1); -- line 343 ---------------------------------------- -- line 349 ---------------------------------------- . break; . } . } . . Ok((cfg_predicate, expanded_attrs)) . } . . /// Matches `COMMASEP(meta_item_inner)`. 729 ( 0.00%) crate fn parse_meta_seq_top(&mut self) -> PResult<'a, Vec> { . // Presumably, the majority of the time there will only be one attr. . let mut nmis = Vec::with_capacity(1); 770 ( 0.00%) while self.token.kind != token::Eof { 616 ( 0.00%) nmis.push(self.parse_meta_item_inner()?); . if !self.eat(&token::Comma) { . break; . } . } 648 ( 0.00%) Ok(nmis) 648 ( 0.00%) } . . /// Matches the following grammar (per RFC 1559). . /// . /// meta_item : PATH ( '=' UNSUFFIXED_LIT | '(' meta_item_inner? ')' )? ; . /// meta_item_inner : (meta_item | UNSUFFIXED_LIT) (',' meta_item_inner)? ; 1,413 ( 0.00%) pub fn parse_meta_item(&mut self) -> PResult<'a, ast::MetaItem> { 314 ( 0.00%) let nt_meta = match self.token.kind { . token::Interpolated(ref nt) => match **nt { . token::NtMeta(ref e) => Some(e.clone()), . _ => None, . }, . _ => None, . }; . . if let Some(item) = nt_meta { -- line 382 ---------------------------------------- -- line 384 ---------------------------------------- . Some(meta) => { . self.bump(); . Ok(meta) . } . None => self.unexpected(), . }; . } . 314 ( 0.00%) let lo = self.token.span; 157 ( 0.00%) let path = self.parse_path(PathStyle::Mod)?; 314 ( 0.00%) let kind = self.parse_meta_item_kind()?; 314 ( 0.00%) let span = lo.to(self.prev_token.span); 4,396 ( 0.00%) Ok(ast::MetaItem { path, kind, span }) 1,413 ( 0.00%) } . . crate fn parse_meta_item_kind(&mut self) -> PResult<'a, ast::MetaItemKind> { 942 ( 0.00%) Ok(if self.eat(&token::Eq) { 22 ( 0.00%) ast::MetaItemKind::NameValue(self.parse_unsuffixed_lit()?) 730 ( 0.00%) } else if self.check(&token::OpenDelim(token::Paren)) { . // Matches `meta_seq = ( COMMASEP(meta_item_inner) )`. . let (list, _) = self.parse_paren_comma_seq(|p| p.parse_meta_item_inner())?; . ast::MetaItemKind::List(list) . } else { . ast::MetaItemKind::Word . }) . } . . /// Matches `meta_item_inner : (meta_item | UNSUFFIXED_LIT) ;`. 1,386 ( 0.00%) fn parse_meta_item_inner(&mut self) -> PResult<'a, ast::NestedMetaItem> { 462 ( 0.00%) match self.parse_unsuffixed_lit() { . Ok(lit) => return Ok(ast::NestedMetaItem::Literal(lit)), 616 ( 0.00%) Err(ref mut err) => err.cancel(), 308 ( 0.00%) } . 616 ( 0.00%) match self.parse_meta_item() { 2,310 ( 0.00%) Ok(mi) => return Ok(ast::NestedMetaItem::MetaItem(mi)), . Err(ref mut err) => err.cancel(), . } . . let found = pprust::token_to_string(&self.token); . let msg = format!("expected unsuffixed literal or identifier, found `{}`", found); . Err(self.struct_span_err(self.token.span, &msg)) 1,078 ( 0.00%) } . } . 1,631 ( 0.00%) pub fn maybe_needs_tokens(attrs: &[ast::Attribute]) -> bool { . // One of the attributes may either itself be a macro, . // or expand to macro attributes (`cfg_attr`). . attrs.iter().any(|attr| { 14,783 ( 0.00%) if attr.is_doc_comment() { . return false; . } 676 ( 0.00%) attr.ident().map_or(true, |ident| { 672 ( 0.00%) ident.name == sym::cfg_attr || !rustc_feature::is_builtin_attr_name(ident.name) . }) . }) 2,097 ( 0.00%) } 1,468 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast_pretty/src/pprust/state.rs -------------------------------------------------------------------------------- Ir -- line 35 ---------------------------------------- . Item(&'a ast::Item), . SubItem(ast::NodeId), . Expr(&'a ast::Expr), . Pat(&'a ast::Pat), . Crate(&'a ast::Crate), . } . . pub trait PpAnn { 182 ( 0.00%) fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {} . fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {} . } . . #[derive(Copy, Clone)] . pub struct NoAnn; . . impl PpAnn for NoAnn {} . -- line 51 ---------------------------------------- -- line 257 ---------------------------------------- . . fn commasep(&mut self, b: Breaks, elts: &[T], op: F) . where . F: FnMut(&mut Self, &T), . { . self.strsep(",", false, b, elts, op) . } . 2,916,361 ( 0.06%) fn maybe_print_comment(&mut self, pos: BytePos) -> bool { . let mut has_comment = false; . while let Some(ref cmnt) = self.next_comment() { . if cmnt.pos < pos { . has_comment = true; . self.print_comment(cmnt); . } else { . break; . } . } . has_comment 3,333,322 ( 0.07%) } . . fn print_comment(&mut self, cmnt: &Comment) { . match cmnt.style { . CommentStyle::Mixed => { . if !self.is_beginning_of_line() { . self.zerobreak(); . } . if let Some((last, lines)) = cmnt.lines.split_last() { -- line 284 ---------------------------------------- -- line 344 ---------------------------------------- . } . } . . fn next_comment(&mut self) -> Option { . self.comments().as_mut().and_then(|c| c.next()) . } . . fn maybe_print_trailing_comment(&mut self, span: rustc_span::Span, next_pos: Option) { 276,250 ( 0.01%) if let Some(cmnts) = self.comments() { . if let Some(cmnt) = cmnts.trailing_comment(span, next_pos) { . self.print_comment(&cmnt); . } . } . } . . fn print_remaining_comments(&mut self) { . // If there aren't any remaining comments, then we need to manually -- line 360 ---------------------------------------- -- line 390 ---------------------------------------- . self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, true) . } . . fn print_inner_attributes_no_trailing_hardbreak(&mut self, attrs: &[ast::Attribute]) -> bool { . self.print_either_attributes(attrs, ast::AttrStyle::Inner, false, false) . } . . fn print_outer_attributes(&mut self, attrs: &[ast::Attribute]) -> bool { 557,952 ( 0.01%) self.print_either_attributes(attrs, ast::AttrStyle::Outer, false, true) . } . . fn print_inner_attributes_inline(&mut self, attrs: &[ast::Attribute]) -> bool { . self.print_either_attributes(attrs, ast::AttrStyle::Inner, true, true) . } . . fn print_outer_attributes_inline(&mut self, attrs: &[ast::Attribute]) -> bool { . self.print_either_attributes(attrs, ast::AttrStyle::Outer, true, true) . } . 976,416 ( 0.02%) fn print_either_attributes( . &mut self, . attrs: &[ast::Attribute], . kind: ast::AttrStyle, . is_inline: bool, . trailing_hardbreak: bool, . ) -> bool { . let mut printed = false; . for attr in attrs { -- line 417 ---------------------------------------- -- line 422 ---------------------------------------- . } . printed = true; . } . } . if printed && trailing_hardbreak && !is_inline { . self.hardbreak_if_not_bol(); . } . printed 1,115,904 ( 0.02%) } . . fn print_attribute(&mut self, attr: &ast::Attribute) { . self.print_attribute_inline(attr, false) . } . . fn print_attribute_inline(&mut self, attr: &ast::Attribute, is_inline: bool) { . if !is_inline { . self.hardbreak_if_not_bol(); -- line 438 ---------------------------------------- -- line 625 ---------------------------------------- . true, . sp, . ); . if macro_def.body.need_semicolon() { . self.word(";"); . } . } . 1,716 ( 0.00%) fn print_path(&mut self, path: &ast::Path, colons_before_params: bool, depth: usize) { 936 ( 0.00%) self.maybe_print_comment(path.span.lo()); . 624 ( 0.00%) for (i, segment) in path.segments[..path.segments.len() - depth].iter().enumerate() { . if i > 0 { . self.word("::") . } . self.print_path_segment(segment, colons_before_params); . } 1,248 ( 0.00%) } . . fn print_path_segment(&mut self, segment: &ast::PathSegment, colons_before_params: bool) { 156 ( 0.00%) if segment.ident.name != kw::PathRoot { 624 ( 0.00%) self.print_ident(segment.ident); 468 ( 0.00%) if let Some(ref args) = segment.args { . self.print_generic_args(args, colons_before_params); . } . } . } . . fn head>>(&mut self, w: S) { . let w = w.into(); . // Outer-box is consistent. -- line 655 ---------------------------------------- -- line 716 ---------------------------------------- . } . } . . /// Print the token kind precisely, without converting `$crate` into its respective crate name. . fn token_kind_to_string(&self, tok: &TokenKind) -> Cow<'static, str> { . self.token_kind_to_string_ext(tok, None) . } . 924 ( 0.00%) fn token_kind_to_string_ext( . &self, . tok: &TokenKind, . convert_dollar_crate: Option, . ) -> Cow<'static, str> { 770 ( 0.00%) match *tok { . token::Eq => "=".into(), . token::Lt => "<".into(), . token::Le => "<=".into(), . token::EqEq => "==".into(), . token::Ne => "!=".into(), . token::Ge => ">=".into(), . token::Gt => ">".into(), . token::Not => "!".into(), -- line 737 ---------------------------------------- -- line 765 ---------------------------------------- . token::Dollar => "$".into(), . token::Question => "?".into(), . token::SingleQuote => "'".into(), . . /* Literals */ . token::Literal(lit) => literal_to_string(lit).into(), . . /* Name components */ 462 ( 0.00%) token::Ident(s, is_raw) => { 154 ( 0.00%) IdentPrinter::new(s, is_raw, convert_dollar_crate).to_string().into() . } . token::Lifetime(s) => s.to_string().into(), . . /* Other */ . token::DocComment(comment_kind, attr_style, data) => { . doc_comment_to_string(comment_kind, attr_style, data).into() . } . token::Eof => "".into(), . . token::Interpolated(ref nt) => self.nonterminal_to_string(nt).into(), . } 770 ( 0.00%) } . . /// Print the token precisely, without converting `$crate` into its respective crate name. . fn token_to_string(&self, token: &Token) -> Cow<'static, str> { . self.token_to_string_ext(token, false) . } . . fn token_to_string_ext(&self, token: &Token, convert_dollar_crate: bool) -> Cow<'static, str> { 154 ( 0.00%) let convert_dollar_crate = convert_dollar_crate.then_some(token.span); 462 ( 0.00%) self.token_kind_to_string_ext(&token.kind, convert_dollar_crate) . } . . fn ty_to_string(&self, ty: &ast::Ty) -> String { . Self::to_string(|s| s.print_type(ty)) . } . . fn bounds_to_string(&self, bounds: &[ast::GenericBound]) -> String { . Self::to_string(|s| s.print_type_bounds("", bounds)) . } . . fn pat_to_string(&self, pat: &ast::Pat) -> String { . Self::to_string(|s| s.print_pat(pat)) . } . . fn expr_to_string(&self, e: &ast::Expr) -> String { 6 ( 0.00%) Self::to_string(|s| s.print_expr(e)) . } . . fn tt_to_string(&self, tt: &TokenTree) -> String { . Self::to_string(|s| s.print_tt(tt, false)) . } . . fn tts_to_string(&self, tokens: &TokenStream) -> String { . Self::to_string(|s| s.print_tts(tokens, false)) -- line 819 ---------------------------------------- -- line 827 ---------------------------------------- . Self::to_string(|s| s.print_item(i)) . } . . fn generic_params_to_string(&self, generic_params: &[ast::GenericParam]) -> String { . Self::to_string(|s| s.print_generic_params(generic_params)) . } . . fn path_to_string(&self, p: &ast::Path) -> String { 1,057 ( 0.00%) Self::to_string(|s| s.print_path(p, false, 0)) . } . . fn path_segment_to_string(&self, p: &ast::PathSegment) -> String { . Self::to_string(|s| s.print_path_segment(p, false)) . } . . fn vis_to_string(&self, v: &ast::Visibility) -> String { . Self::to_string(|s| s.print_visibility(v)) -- line 843 ---------------------------------------- -- line 864 ---------------------------------------- . fn attribute_to_string(&self, attr: &ast::Attribute) -> String { . Self::to_string(|s| s.print_attribute(attr)) . } . . fn param_to_string(&self, arg: &ast::Param) -> String { . Self::to_string(|s| s.print_param(arg, false)) . } . 918 ( 0.00%) fn to_string(f: impl FnOnce(&mut State<'_>)) -> String { . let mut printer = State::new(); . f(&mut printer); 918 ( 0.00%) printer.s.eof() 765 ( 0.00%) } . } . . impl<'a> PrintState<'a> for State<'a> { . fn comments(&mut self) -> &mut Option> { . &mut self.comments . } . 1,440 ( 0.00%) fn print_ident(&mut self, ident: Ident) { 1,280 ( 0.00%) self.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string()); 960 ( 0.00%) self.ann.post(self, AnnNode::Ident(&ident)) 800 ( 0.00%) } . . fn print_generic_args(&mut self, args: &ast::GenericArgs, colons_before_params: bool) { . if colons_before_params { . self.word("::") . } . . match *args { . ast::GenericArgs::AngleBracketed(ref data) => { -- line 895 ---------------------------------------- -- line 908 ---------------------------------------- . self.print_fn_ret_ty(&data.output); . } . } . } . } . . impl<'a> State<'a> { . pub fn new() -> State<'a> { 4,909 ( 0.00%) State { s: pp::Printer::new(), comments: None, ann: &NoAnn } . } . 40 ( 0.00%) crate fn commasep_cmnt(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G) . where . F: FnMut(&mut State<'_>, &T), . G: FnMut(&T) -> rustc_span::Span, . { 16 ( 0.00%) self.rbox(0, b); . let len = elts.len(); . let mut i = 0; . for elt in elts { 6 ( 0.00%) self.maybe_print_comment(get_span(elt).hi()); . op(self, elt); . i += 1; 4 ( 0.00%) if i < len { . self.word(","); . self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi())); . self.space_if_not_bol(); . } . } 36 ( 0.00%) self.end(); . } . . crate fn commasep_exprs(&mut self, b: Breaks, exprs: &[P]) { 18 ( 0.00%) self.commasep_cmnt(b, exprs, |s, e| s.print_expr(e), |e| e.span) . } . . pub fn print_opt_lifetime(&mut self, lifetime: &Option) { . if let Some(lt) = *lifetime { . self.print_lifetime(lt); . self.nbsp(); . } . } -- line 949 ---------------------------------------- 2,029 ( 0.00%) -------------------------------------------------------------------------------- -- 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, . } . 266 ( 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() 171 ( 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 { 314,381 ( 0.01%) self.override_span.unwrap_or_else(|| Span::with_root_ctxt(lo, hi)) . } . . /// Returns the next token, and info about preceding whitespace, if any. 2,136,561 ( 0.04%) fn next_token(&mut self) -> (Spacing, Token) { . let mut spacing = Spacing::Joint; . . // Skip `#!` at the start of the file 610,446 ( 0.01%) let start_src_index = self.src_index(self.pos); 915,669 ( 0.02%) let text: &str = &self.src[start_src_index..self.end_src_index]; . let is_beginning_of_file = self.pos == self.start_pos; 305,223 ( 0.01%) if is_beginning_of_file { 76 ( 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 { 605,959 ( 0.01%) let start_src_index = self.src_index(self.pos); 1,366,773 ( 0.03%) let text: &str = &self.src[start_src_index..self.end_src_index]; . 455,591 ( 0.01%) if text.is_empty() { . let span = self.mk_sp(self.pos, self.pos); 95 ( 0.00%) return (spacing, Token::new(token::Eof, span)); . } . 1,366,716 ( 0.03%) let token = rustc_lexer::first_token(text); . 911,144 ( 0.02%) let start = self.pos; 455,572 ( 0.01%) self.pos = self.pos + BytePos::from_usize(token.len); . . debug!("next_token: {:?}({:?})", token.kind, self.str_from(start)); . 3,650,492 ( 0.07%) match self.cook_lexer_token(token.kind, start) { 2,441,632 ( 0.05%) Some(kind) => { . let span = self.mk_sp(start, self.pos); 1,831,224 ( 0.04%) return (spacing, Token::new(kind, span)); . } . None => spacing = Spacing::Alone, . } . } 2,747,007 ( 0.06%) } . . /// Report a fatal lexical error with a given span. . fn fatal_span(&self, sp: Span, m: &str) -> FatalError { . self.sess.span_diagnostic.span_fatal(sp, m) . } . . /// Report a lexical error with a given span. . fn err_span(&self, sp: Span, m: &str) { -- line 110 ---------------------------------------- -- line 130 ---------------------------------------- . ) -> DiagnosticBuilder<'a> { . self.sess . .span_diagnostic . .struct_span_fatal(self.mk_sp(from_pos, to_pos), &format!("{}: {}", m, escaped_char(c))) . } . . /// Detect usages of Unicode codepoints changing the direction of the text on screen and loudly . /// complain about it. 1,414 ( 0.00%) fn lint_unicode_text_flow(&self, start: BytePos) { . // Opening delimiter of the length 2 is not included into the comment text. . let content_start = start + BytePos(2); . let content = self.str_from(content_start); . if contains_text_flow_control_chars(content) { . let span = self.mk_sp(start, self.pos); . self.sess.buffer_lint_with_diagnostic( . &TEXT_DIRECTION_CODEPOINT_IN_COMMENT, . span, . ast::CRATE_NODE_ID, . "unicode codepoint changing visible direction of text present in comment", . BuiltinLintDiagnostics::UnicodeTextFlow(span, content.to_string()), . ); . } 1,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 { 2,277,860 ( 0.05%) Some(match token { 1,680 ( 0.00%) rustc_lexer::TokenKind::LineComment { doc_style } => { . // Skip non-doc comments 7,797 ( 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); 7,395 ( 0.00%) self.cook_doc_comment(content_start, content, CommentKind::Line, doc_style) . } 2 ( 0.00%) rustc_lexer::TokenKind::BlockComment { doc_style, terminated } => { 1 ( 0.00%) if !terminated { . let msg = match doc_style { . Some(_) => "unterminated block doc-comment", . None => "unterminated block comment", . }; . let last_bpos = self.pos; . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start, last_bpos), . msg, . error_code!(E0758), . ); . } . . // Skip non-doc comments 1 ( 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 and closing delimiter of the length 2 . // are not included into the symbol. -- line 196 ---------------------------------------- -- 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 => { 36,556 ( 0.00%) let is_raw_ident = token == rustc_lexer::TokenKind::RawIdent; 45,695 ( 0.00%) let is_unknown_prefix = token == rustc_lexer::TokenKind::UnknownPrefix; . let mut ident_start = start; 18,278 ( 0.00%) if is_raw_ident { . ident_start = ident_start + BytePos(2); . } 27,417 ( 0.00%) if is_unknown_prefix { . self.report_unknown_prefix(start); . } 45,695 ( 0.00%) let sym = nfc_normalize(self.str_from(ident_start)); . let span = self.mk_sp(start, self.pos); 36,556 ( 0.00%) self.sess.symbol_gallery.insert(sym, span); 18,278 ( 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); . } 63,973 ( 0.00%) token::Ident(sym, is_raw_ident) . } . rustc_lexer::TokenKind::InvalidIdent . // Do not recover an identifier with emoji if the codepoint is a confusable . // with a recoverable substitution token, like `➖`. . if UNICODE_ARRAY . .iter() . .find(|&&(c, _, _)| { . let sym = self.str_from(start); -- line 232 ---------------------------------------- -- line 234 ---------------------------------------- . }) . .is_none() => . { . let sym = nfc_normalize(self.str_from(start)); . let span = self.mk_sp(start, self.pos); . self.sess.bad_unicode_identifiers.borrow_mut().entry(sym).or_default().push(span); . token::Ident(sym, false) . } 2,218,960 ( 0.05%) 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); 416,055 ( 0.01%) 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 . }; 1,109,480 ( 0.02%) token::Literal(token::Lit { kind, symbol, suffix }) . } 502 ( 0.00%) rustc_lexer::TokenKind::Lifetime { starts_with_number } => { . // Include the leading `'` in the real identifier, for macro . // expansion purposes. See #12512 for the gory details of why . // this is necessary. . let lifetime_name = self.str_from(start); 251 ( 0.00%) if starts_with_number { . self.err_span_(start, self.pos, "lifetimes cannot start with a number"); . } 753 ( 0.00%) let ident = Symbol::intern(lifetime_name); 1,004 ( 0.00%) token::Lifetime(ident) . } . rustc_lexer::TokenKind::Semi => token::Semi, . rustc_lexer::TokenKind::Comma => token::Comma, . rustc_lexer::TokenKind::Dot => token::Dot, . rustc_lexer::TokenKind::OpenParen => token::OpenDelim(token::Paren), . rustc_lexer::TokenKind::CloseParen => token::CloseDelim(token::Paren), . rustc_lexer::TokenKind::OpenBrace => token::OpenDelim(token::Brace), . rustc_lexer::TokenKind::CloseBrace => token::CloseDelim(token::Brace), -- line 291 ---------------------------------------- -- line 324 ---------------------------------------- . err.help("source files must contain UTF-8 encoded text, unexpected null bytes might occur when a different encoding is used"); . } . err.emit(); . token? . } . }) . } . 17,748 ( 0.00%) fn cook_doc_comment( . &self, . content_start: BytePos, . content: &str, . comment_kind: CommentKind, . doc_style: DocStyle, . ) -> TokenKind { 1,479 ( 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, . }; . 4,437 ( 0.00%) token::DocComment(comment_kind, attr_style, Symbol::intern(content)) 22,185 ( 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 { 25 ( 0.00%) rustc_lexer::LiteralKind::Char { terminated } => { 25 ( 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' ' . } 428 ( 0.00%) rustc_lexer::LiteralKind::Str { terminated } => { 428 ( 0.00%) if !terminated { . self.sess.span_diagnostic.span_fatal_with_code( . self.mk_sp(start, suffix_start), . "unterminated double quote string", . error_code!(E0765), . ) . } . (token::Str, Mode::Str, 1, 1) // " " . } -- line 397 ---------------------------------------- -- line 403 ---------------------------------------- . error_code!(E0766), . ) . } . (token::ByteStr, Mode::ByteStr, 2, 1) // b" " . } . rustc_lexer::LiteralKind::RawStr { n_hashes, err } => { . self.report_raw_str_error(start, err); . let n = u32::from(n_hashes); 10 ( 0.00%) (token::StrRaw(n_hashes), Mode::RawStr, 2 + n, 1 + n) // r##" "## . } . rustc_lexer::LiteralKind::RawByteStr { n_hashes, err } => { . self.report_raw_str_error(start, err); . let n = u32::from(n_hashes); . (token::ByteStrRaw(n_hashes), Mode::RawByteStr, 3 + n, 1 + n) // br##" "## . } 276,460 ( 0.01%) rustc_lexer::LiteralKind::Int { base, empty_int } => { 138,230 ( 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); 414,690 ( 0.01%) (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); 1,365 ( 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 { 69,619 ( 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); 973,070 ( 0.02%) Symbol::intern(self.str_from_to(start, end)) . } . . /// Slice of the source text spanning from `start` up to but excluding `end`. 150,211 ( 0.00%) fn str_from_to(&self, start: BytePos, end: BytePos) -> &str { . &self.src[self.src_index(start)..self.src_index(end)] 600,844 ( 0.01%) } . . fn report_raw_str_error(&self, start: BytePos, opt_err: Option) { 4 ( 0.00%) match opt_err { . Some(RawStrError::InvalidStarter { bad_char }) => { . self.report_non_started_raw_string(start, bad_char) . } . Some(RawStrError::NoTerminator { expected, found, possible_terminator_offset }) => self . .report_unterminated_raw_string(start, expected, possible_terminator_offset, found), . Some(RawStrError::TooManyDelimiters { found }) => { . self.report_too_many_hashes(start, found) . } -- line 496 ---------------------------------------- -- line 609 ---------------------------------------- . fn validate_literal_escape( . &self, . mode: Mode, . content_start: BytePos, . content_end: BytePos, . prefix_len: u32, . postfix_len: u32, . ) { 2,730 ( 0.00%) let lit_content = self.str_from_to(content_start, content_end); 59,162 ( 0.00%) unescape::unescape_literal(lit_content, mode, &mut |range, result| { . // Here we only check for errors. The actual unescaping is done later. 12,288 ( 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, . ); . } 55,296 ( 0.00%) }); . } . . fn validate_int_literal(&self, base: Base, content_start: BytePos, content_end: BytePos) { 552,920 ( 0.01%) 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)); . } . } . } . } . 82,251 ( 0.00%) pub fn nfc_normalize(string: &str) -> Symbol { . use unicode_normalization::{is_nfc_quick, IsNormalized, UnicodeNormalization}; 18,278 ( 0.00%) match is_nfc_quick(string.chars()) { 91,390 ( 0.00%) IsNormalized::Yes => Symbol::intern(string), . _ => { . let normalized_str: String = string.chars().nfc().collect(); . Symbol::intern(&normalized_str) . } . } . } 1,795,539 ( 0.04%) -------------------------------------------------------------------------------- -- 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 { 2,370 ( 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 { 1,096 ( 0.00%) match self { . 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 84 ---------------------------------------- -- 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. 186 ( 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 { 14,260 ( 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>> { 4,105 ( 0.00%) if mplace.layout.is_unsized() { . // Don't touch unsized . return Ok(None); . } . 11,769 ( 0.00%) let alloc = match self.get_alloc(mplace)? { 19,615 ( 0.00%) Some(ptr) => ptr, . None => { . return Ok(Some(ImmTy { . // zero-sized type . imm: Scalar::ZST.into(), . layout: mplace.layout, . })); . } . }; . 25,370 ( 0.00%) match mplace.layout.abi { . Abi::Scalar(..) => { 825 ( 0.00%) let scalar = alloc.read_scalar(alloc_range(Size::ZERO, mplace.layout.size))?; . Ok(Some(ImmTy { imm: scalar.into(), layout: mplace.layout })) . } 9,021 ( 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); 6,014 ( 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))?; 9,021 ( 0.00%) let b_val = alloc.read_scalar(alloc_range(b_offset, b_size))?; 15,035 ( 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. 1,297,323 ( 0.03%) pub fn try_read_immediate( . &self, . src: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Result, MPlaceTy<'tcx, M::PointerTag>>> { 2,594,646 ( 0.05%) Ok(match src.try_as_mplace() { . Ok(ref mplace) => { 7,846 ( 0.00%) if let Some(val) = self.try_read_immediate_from_mplace(mplace)? { . Ok(val) . } else { . Err(*mplace) . } . } 1,402,240 ( 0.03%) Err(val) => Ok(val), . }) 1,297,323 ( 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>> { 25,916 ( 0.00%) if let Ok(imm) = self.try_read_immediate(op)? { 37,608 ( 0.00%) Ok(imm) . } else { . span_bug!(self.cur_span(), "primitive read failed for type: {:?}", op.layout.ty); . } . } . . /// Read a scalar from a place . pub fn read_scalar( . &self, -- line 330 ---------------------------------------- -- 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 25,480 ( 0.00%) 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)?; 28,028 ( 0.00%) 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 }) 22,932 ( 0.00%) } . . 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 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 18,927 ( 0.00%) 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)?; 91 ( 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)? . }; 27,339 ( 0.00%) Ok(OpTy { op, layout }) 16,824 ( 0.00%) } . . /// 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>> { 1,464 ( 0.00%) let op = match **place { . Place::Ptr(mplace) => Operand::Indirect(mplace), . Place::Local { frame, local } => { 6,588 ( 0.00%) *self.access_local(&self.stack()[frame], local, None)? . } . }; 5,124 ( 0.00%) Ok(OpTy { op, layout: place.layout }) . } . . // Evaluate a place with the goal of reading from it. This lets us sometimes . // avoid allocations. 9,480 ( 0.00%) 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. 1,185 ( 0.00%) let layout = if place.projection.is_empty() { layout } else { None }; . 3,555 ( 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, . )); 3,555 ( 0.00%) Ok(op) 10,665 ( 0.00%) } . . /// 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] 1,254,573 ( 0.03%) pub fn eval_operand( . &self, . mir_op: &mir::Operand<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { . use rustc_middle::mir::Operand::*; 278,794 ( 0.01%) let op = match *mir_op { . // FIXME: do some more logic on `move` to invalidate the old location 5,925 ( 0.00%) Copy(place) | Move(place) => self.eval_place_to_op(place, layout)?, . . Constant(ref constant) => { . let val = 2,073,180 ( 0.04%) 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); 1,812,161 ( 0.04%) Ok(op) 836,382 ( 0.02%) } . . /// 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). 1,659,636 ( 0.03%) pub fn const_to_op( . &self, . val: &ty::Const<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 691,515 ( 0.01%) 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) . } 1,383,030 ( 0.03%) ty::ConstKind::Value(val_val) => self.const_val_to_op(val_val, val.ty, layout), . } 1,244,727 ( 0.03%) } . . pub fn mir_const_to_op( . &self, . val: &mir::ConstantKind<'tcx>, . layout: Option>, . ) -> InterpResult<'tcx, OpTy<'tcx, M::PointerTag>> { 276,606 ( 0.01%) match val { 553,212 ( 0.01%) mir::ConstantKind::Ty(ct) => self.const_to_op(ct, layout), . mir::ConstantKind::Val(val, ty) => self.const_val_to_op(*val, ty, layout), . } . } . 1,383,030 ( 0.03%) 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, _> { 829,272 ( 0.02%) Ok(match scalar { . Scalar::Ptr(ptr, size) => Scalar::Ptr(self.global_base_pointer(ptr)?, size), 413,811 ( 0.01%) Scalar::Int(int) => Scalar::Int(int), . }) . }; 414,084 ( 0.01%) let layout = from_known_layout(self.tcx, self.param_env, layout, || self.layout_of(ty))?; 415,091 ( 0.01%) 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)) . } 1,243,908 ( 0.03%) ConstValue::Scalar(x) => Operand::Immediate(tag_scalar(x)?.into()), 273 ( 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( 273 ( 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, . )) . } . }; 2,904,363 ( 0.06%) Ok(OpTy { op, layout }) 1,106,424 ( 0.02%) } . . /// 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)! . pub fn read_discriminant( . &self, . op: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, (Scalar, VariantIdx)> { . trace!("read_discriminant_value {:#?}", op.layout); -- line 638 ---------------------------------------- 2,461,790 ( 0.05%) -------------------------------------------------------------------------------- -- 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. 34,459 ( 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. 4,244 ( 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. 366 ( 0.00%) relocations: Relocations, . /// Denotes which part of this allocation is initialized. 2 ( 0.00%) init_mask: InitMask, . /// The alignment of the allocation to detect unaligned reads. . /// (`Align` guarantees that this is a power of two.) 1,179 ( 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. 459 ( 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] 148,117 ( 0.00%) pub fn subrange(self, subrange: AllocRange) -> AllocRange { . let sub_start = self.start + subrange.start; . let range = alloc_range(sub_start, subrange.size); 148,117 ( 0.00%) assert!(range.end() <= self.end(), "access outside the bounds for given AllocRange"); . range 444,351 ( 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()); 1,488 ( 0.00%) Self { . bytes, . relocations: Relocations::new(), 558 ( 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. 10,076 ( 0.00%) 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() }; 12,824 ( 0.00%) Ok(Allocation { . bytes, . relocations: Relocations::new(), 2,748 ( 0.00%) init_mask: InitMask::new(size, false), . align, . mutability: Mutability::Mut, . extra: (), . }) 8,244 ( 0.00%) } . } . . 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 { 148,788 ( 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. 106,800 ( 0.00%) fn get_bytes_internal( . &self, . cx: &impl HasDataLayout, . range: AllocRange, . check_init_and_ptr: bool, . ) -> AllocResult<&[u8]> { 17,800 ( 0.00%) if check_init_and_ptr { 728 ( 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)?; . } . 35,600 ( 0.00%) Ok(&self.bytes[range.start.bytes_usize()..range.end().bytes_usize()]) 80,100 ( 0.00%) } . . /// 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]> { 364 ( 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]> { 25,043 ( 0.00%) 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. 1,534,390 ( 0.03%) pub fn get_bytes_mut( . &mut self, . cx: &impl HasDataLayout, . range: AllocRange, . ) -> AllocResult<&mut [u8]> { . self.mark_init(range, true); 697,450 ( 0.01%) self.clear_relocations(cx, range)?; . 557,960 ( 0.01%) Ok(&mut self.bytes[range.start.bytes_usize()..range.end().bytes_usize()]) 1,115,920 ( 0.02%) } . . /// A raw pointer variant of `get_bytes_mut` that avoids invalidating existing aliases into this memory. 1,001 ( 0.00%) pub fn get_bytes_mut_ptr( . &mut self, . cx: &impl HasDataLayout, . range: AllocRange, . ) -> AllocResult<*mut [u8]> { . self.mark_init(range, true); 455 ( 0.00%) self.clear_relocations(cx, range)?; . 182 ( 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()); 182 ( 0.00%) let len = range.end().bytes_usize() - range.start.bytes_usize(); 364 ( 0.00%) Ok(ptr::slice_from_raw_parts_mut(begin_ptr, len)) 728 ( 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 315 ---------------------------------------- . &self, . cx: &impl HasDataLayout, . range: AllocRange, . allow_uninit_and_ptr: bool, . ) -> AllocResult { . // Check bounds and relocations on the edges. . self.get_bytes_with_uninit_and_ptr(cx, range)?; . // Check uninit and ptr. 3,576 ( 0.00%) if !allow_uninit_and_ptr { 7,152 ( 0.00%) self.check_init(range)?; . self.check_relocations(cx, range)?; . } . Ok(()) . } . . /// 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. 88,907 ( 0.00%) 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. 6,839 ( 0.00%) let bits = read_target_uint(cx.data_layout().endian, bytes).unwrap(); . // See if we got a pointer. 6,839 ( 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)); 19,160 ( 0.00%) return Ok(ScalarMaybeUninit::from_pointer(ptr, cx)); . } . } . // We don't. Just return the bits. 18,042 ( 0.00%) Ok(ScalarMaybeUninit::Scalar(Scalar::from_uint(bits, range.size))) 61,551 ( 0.00%) } . . /// 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. 976,430 ( 0.02%) pub fn write_scalar( . &mut self, . cx: &impl HasDataLayout, . range: AllocRange, . val: ScalarMaybeUninit, . ) -> AllocResult { 139,490 ( 0.00%) assert!(self.mutability == Mutability::Mut); . 418,470 ( 0.01%) 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. 557,960 ( 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), . }; . 418,470 ( 0.01%) let endian = cx.data_layout().endian; 418,470 ( 0.01%) let dst = self.get_bytes_mut(cx, range)?; . write_target_uint(endian, dst, bytes).unwrap(); . . // See if we have to also write a relocation. 417,556 ( 0.01%) if let Some(provenance) = provenance { 3,656 ( 0.00%) self.relocations.0.insert(range.start, provenance); . } . . Ok(()) 1,255,410 ( 0.03%) } . } . . /// Relocations. . impl Allocation { . /// Returns all relocations overlapping with the given pointer-offset pair. 476,961 ( 0.01%) 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. 477,234 ( 0.01%) let start = range.start.bytes().saturating_sub(cx.data_layout().pointer_size.bytes() - 1); . self.relocations.range(Size::from_bytes(start)..range.end()) 635,948 ( 0.01%) } . . /// Checks that there are no relocations overlapping with the given range. . #[inline(always)] . fn check_relocations(&self, cx: &impl HasDataLayout, range: AllocRange) -> AllocResult { 116,436 ( 0.00%) 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. 1,535,391 ( 0.03%) 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. 697,905 ( 0.01%) let relocations = self.get_relocations(cx, range); 139,581 ( 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(()) 977,067 ( 0.02%) } . . /// 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 { 2,204 ( 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 { 910 ( 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); 91 ( 0.00%) if relocations.is_empty() { . return AllocationRelocations { relative_relocations: Vec::new() }; . } . 91 ( 0.00%) let size = src.size; 273 ( 0.00%) let mut new_relocations = Vec::with_capacity(relocations.len() * (count as usize)); . 91 ( 0.00%) for i in 0..count { . new_relocations.extend(relocations.iter().map(|&(offset, reloc)| { . // compute offset for current repetition 728 ( 0.00%) let dest_offset = dest + size * i; // `Size` operations . ( . // shift offsets from source allocation to destination allocation 182 ( 0.00%) (offset + dest_offset) - src.start, // `Size` operations . reloc, . ) . })); . } . 637 ( 0.00%) AllocationRelocations { relative_relocations: new_relocations } 819 ( 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. 637 ( 0.00%) pub fn mark_relocation_range(&mut self, relocations: AllocationRelocations) { 364 ( 0.00%) self.relocations.0.insert_presorted(relocations.relative_relocations); 728 ( 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(); 580,678 ( 0.01%) let a = bits / InitMask::BLOCK_SIZE; 281,348 ( 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(); 4,240 ( 0.00%) Size::from_bytes(block * InitMask::BLOCK_SIZE + bit) . } . 4,408 ( 0.00%) pub fn new(size: Size, state: bool) -> Self { 2,204 ( 0.00%) let mut m = InitMask { blocks: vec![], len: Size::ZERO }; 1,102 ( 0.00%) m.grow(size, state); . m 5,510 ( 0.00%) } . 1,116,648 ( 0.02%) pub fn set_range(&mut self, start: Size, end: Size, new_state: bool) { 279,162 ( 0.01%) let len = self.len; 139,581 ( 0.00%) if end > len { . self.grow(end - len, new_state); . } 1,395,810 ( 0.03%) self.set_range_inbounds(start, end, new_state); . } . 562,696 ( 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); 281,348 ( 0.01%) if blocka == blockb { . // First set all bits except the first `bita`, . // then unset the last `64 - bitb` bits. 274,244 ( 0.01%) let range = if bitb == 0 { . u64::MAX << bita . } else { 959,854 ( 0.02%) (u64::MAX << bita) & (u64::MAX >> (64 - bitb)) . }; 274,244 ( 0.01%) if new_state { 136,795 ( 0.00%) self.blocks[blocka] |= range; . } else { 654 ( 0.00%) self.blocks[blocka] &= !range; . } . return; . } . // across block boundaries 7,104 ( 0.00%) if new_state { . // Set `bita..64` to `1`. 9,186 ( 0.00%) self.blocks[blocka] |= u64::MAX << bita; . // Set `0..bitb` to `1`. 6,124 ( 0.00%) if bitb != 0 { 230 ( 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,960 ( 0.00%) self.blocks[blocka] &= !(u64::MAX << bita); . // Set `0..bitb` to `0`. 980 ( 0.00%) if bitb != 0 { 1,578 ( 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 { 2,539 ( 0.00%) self.blocks[block] = 0; . } . } 281,348 ( 0.01%) } . . #[inline] . pub fn get(&self, i: Size) -> bool { . let (block, bit) = Self::bit_index(i); 637 ( 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); . } . } . 6,612 ( 0.00%) pub fn grow(&mut self, amount: Size, new_state: bool) { 2,204 ( 0.00%) if amount.bytes() == 0 { . return; . } . let unused_trailing_bits = 8,016 ( 0.00%) u64::try_from(self.blocks.len()).unwrap() * Self::BLOCK_SIZE - self.len.bytes(); 2,004 ( 0.00%) if amount.bytes() > unused_trailing_bits { 3,006 ( 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()), . ); . } 1,002 ( 0.00%) let start = self.len; . self.len += amount; 9,018 ( 0.00%) self.set_range_inbounds(start, start + amount, new_state); // `Size` operation 700 ( 0.00%) } . . /// Returns the index of the first bit in `start..end` (end-exclusive) that is equal to is_init. 17,800 ( 0.00%) 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 35,600 ( 0.00%) let bits = if is_init { bits } else { !bits }; . // Mask off unused start bits. . // 0b11000100 . // & 0b11111000 . // bits = 0b11000000 26,700 ( 0.00%) let bits = bits & (!0 << start_bit); . // Find set bit, if any. . // bit = trailing_zeros(0b11000000) . // bit = 6 47,024 ( 0.00%) if bits == 0 { . None . } else { . let bit = bits.trailing_zeros(); . Some(InitMask::size_from_bit_index(block, bit)) . } . } . 8,900 ( 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,040 ( 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). 1,560 ( 0.00%) for (&bits, block) in init_mask.blocks[start_block + 1..end_block_inclusive + 1] . .iter() . .zip(start_block + 1..) . { . if let Some(i) = search_block(bits, block, 0, is_init) { . // If this is the last block, we may find a matching bit after `end`. . // . // For example, we shouldn't successfully find bit (4), because it's after `end`: . // -- line 842 ---------------------------------------- -- line 879 ---------------------------------------- . "optimized implementation of find_bit is wrong for start={:?} end={:?} is_init={} init_mask={:#?}", . start, . end, . is_init, . self . ); . . result 17,800 ( 0.00%) } . } . . /// 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> { 10,779 ( 0.00%) if end > self.len { . return Err(self.len..end); . } . 44,045 ( 0.00%) let uninit_start = self.find_bit(start, end, false); . 17,618 ( 0.00%) 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<'_> { 91 ( 0.00%) assert!(end <= self.len); . 91 ( 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 { 91 ( 0.00%) if self.start >= self.end { . return None; . } . . let end_of_chunk = 455 ( 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 = 364 ( 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. 17,730 ( 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 . })) . }) 15,760 ( 0.00%) } . . pub fn mark_init(&mut self, range: AllocRange, is_init: bool) { 279,162 ( 0.01%) if range.size.bytes() == 0 { . return; . } 139,581 ( 0.00%) assert!(self.mutability == Mutability::Mut); 558,324 ( 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. 182 ( 0.00%) !self.initial && self.ranges.len() == 1 91 ( 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::>()`. 637 ( 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 1063 ---------------------------------------- . 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. . for chunk in chunks { 182 ( 0.00%) let len = chunk.range().end.bytes() - chunk.range().start.bytes(); . ranges.push(len); . } . 637 ( 0.00%) InitMaskCompressed { ranges, initial } 728 ( 0.00%) } . . /// Applies multiple instances of the run-length encoding to the initialization mask. 1,001 ( 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`. 182 ( 0.00%) if defined.ranges.len() <= 1 { 910 ( 0.00%) self.init_mask.set_range_inbounds( . range.start, . range.start + range.size * repeat, // `Size` operations 91 ( 0.00%) defined.initial, . ); . return; . } . . for mut j in 0..repeat { . j *= range.size.bytes(); . j += range.start.bytes(); . let mut cur = defined.initial; -- line 1099 ---------------------------------------- 1,391,447 ( 0.03%) -------------------------------------------------------------------------------- -- 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")] 276,086 ( 0.01%) pub fn from_str_radix(src: &str, radix: u32) -> Result { 138,043 ( 0.00%) from_str_radix(src, radix) 414,129 ( 0.01%) } . . /// 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 { 98,250 ( 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 { 349,578 ( 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 { 1,457,660 ( 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 { 28,982,155 ( 0.59%) intrinsics::rotate_left(self, n as $SelfT) . } . . /// Shifts the bits to the right by a specified amount, `n`, . /// wrapping the truncated bits to the beginning of the resulting . /// integer. . /// . /// Please note this isn't the same operation as the `>>` shifting operator! . /// -- line 220 ---------------------------------------- -- line 430 ---------------------------------------- . #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[inline] . pub const fn checked_add(self, rhs: Self) -> Option { 2 ( 0.00%) let (a, b) = self.overflowing_add(rhs); . if unlikely!(b) {None} else {Some(a)} . } . . /// Unchecked integer addition. Computes `self + rhs`, assuming overflow . /// cannot occur. . /// . /// # Safety . /// -- line 446 ---------------------------------------- -- line 456 ---------------------------------------- . )] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] . #[inline(always)] . pub const unsafe fn unchecked_add(self, rhs: Self) -> Self { . // SAFETY: the caller must uphold the safety contract for . // `unchecked_add`. 2,105,991 ( 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`. 38,230 ( 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 { 205,375 ( 0.00%) intrinsics::saturating_add(self, rhs) . } . . /// Saturating addition with a signed integer. Computes `self + rhs`, . /// saturating at the numeric bounds instead of overflowing. . /// . /// # Examples . /// . /// Basic usage: -- line 1051 ---------------------------------------- -- line 1084 ---------------------------------------- . #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")] . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[must_use = "this returns the result of the operation, \ . without modifying the original"] . #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] . #[inline(always)] . pub const fn saturating_sub(self, rhs: Self) -> Self { 320,110 ( 0.01%) 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 { 19,759,646 ( 0.41%) 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 { 8,771,688 ( 0.18%) 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 { 16,894,893 ( 0.35%) 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) { 4,062,668 ( 0.08%) 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) { 611,038 ( 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) { 3,631,194 ( 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 { 168 ( 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 { 6,172 ( 0.00%) if self <= 1 { return 0; } . 17,816 ( 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. 53,313 ( 0.00%) let z = unsafe { intrinsics::ctlz_nonzero(p) }; 17,879 ( 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 { 29,416 ( 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 ---------------------------------------- 362,790 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/flags.rs -------------------------------------------------------------------------------- Ir -- line 11 ---------------------------------------- . } . . impl FlagComputation { . fn new() -> FlagComputation { . FlagComputation { flags: TypeFlags::empty(), outer_exclusive_binder: ty::INNERMOST } . } . . #[allow(rustc::usage_of_ty_tykind)] 185,045 ( 0.00%) pub fn for_kind(kind: &ty::TyKind<'_>) -> FlagComputation { 26,435 ( 0.00%) let mut result = FlagComputation::new(); . result.add_kind(kind); . result 264,350 ( 0.01%) } . 76,985 ( 0.00%) pub fn for_predicate<'tcx>(binder: ty::Binder<'tcx, ty::PredicateKind<'_>>) -> FlagComputation { . let mut result = FlagComputation::new(); . result.add_predicate(binder); . result 107,779 ( 0.00%) } . 558,500 ( 0.01%) pub fn for_const(c: &ty::Const<'_>) -> TypeFlags { 698,193 ( 0.01%) let mut result = FlagComputation::new(); 694,557 ( 0.01%) result.add_const(c); 279,790 ( 0.01%) result.flags 558,500 ( 0.01%) } . 552 ( 0.00%) pub fn for_unevaluated_const(uv: ty::Unevaluated<'_>) -> TypeFlags { 552 ( 0.00%) let mut result = FlagComputation::new(); 552 ( 0.00%) result.add_unevaluated_const(uv); . result.flags 1,104 ( 0.00%) } . . fn add_flags(&mut self, flags: TypeFlags) { 902,107 ( 0.02%) self.flags = self.flags | flags; . } . . /// indicates that `self` refers to something at binding level `binder` . fn add_bound_var(&mut self, binder: ty::DebruijnIndex) { 3,041 ( 0.00%) let exclusive_binder = binder.shifted_in(1); . self.add_exclusive_binder(exclusive_binder); . } . . /// indicates that `self` refers to something *inside* binding . /// level `binder` -- not bound by `binder`, but bound by the next . /// binder internal to it . fn add_exclusive_binder(&mut self, exclusive_binder: ty::DebruijnIndex) { 951,956 ( 0.02%) self.outer_exclusive_binder = self.outer_exclusive_binder.max(exclusive_binder); . } . . /// Adds the flags/depth from a set of types that appear within the current type, but within a . /// region binder. . fn bound_computation(&mut self, value: ty::Binder<'_, T>, f: F) . where . F: FnOnce(&mut Self, T), . { 15,623 ( 0.00%) let mut computation = FlagComputation::new(); . 15,623 ( 0.00%) if !value.bound_vars().is_empty() { 312 ( 0.00%) computation.flags = computation.flags | TypeFlags::HAS_RE_LATE_BOUND; . } . . f(&mut computation, value.skip_binder()); . 14,905 ( 0.00%) self.add_flags(computation.flags); . . // The types that contributed to `computation` occurred within . // a region binder, so subtract one from the region depth . // within when adding the depth to `self`. 14,905 ( 0.00%) let outer_exclusive_binder = computation.outer_exclusive_binder; 15,593 ( 0.00%) if outer_exclusive_binder > ty::INNERMOST { 3,364 ( 0.00%) self.add_exclusive_binder(outer_exclusive_binder.shifted_out(1)); . } // otherwise, this binder captures nothing . } . . #[allow(rustc::usage_of_ty_tykind)] . fn add_kind(&mut self, kind: &ty::TyKind<'_>) { 132,175 ( 0.00%) match kind { . &ty::Bool . | &ty::Char . | &ty::Int(_) . | &ty::Float(_) . | &ty::Uint(_) . | &ty::Never . | &ty::Str . | &ty::Foreign(..) => {} -- line 95 ---------------------------------------- -- line 116 ---------------------------------------- . self.add_ty(substs.yield_ty()); . self.add_ty(substs.tupled_upvars_ty()); . } . . &ty::GeneratorWitness(ts) => { . self.bound_computation(ts, |flags, ts| flags.add_tys(ts)); . } . 269 ( 0.00%) &ty::Closure(_, substs) => { . let substs = substs.as_closure(); . let should_remove_further_specializable = . !self.flags.contains(TypeFlags::STILL_FURTHER_SPECIALIZABLE); 269 ( 0.00%) self.add_substs(substs.parent_substs()); . if should_remove_further_specializable { . self.flags -= TypeFlags::STILL_FURTHER_SPECIALIZABLE; . } . 269 ( 0.00%) self.add_ty(substs.sig_as_fn_ptr_ty()); 269 ( 0.00%) self.add_ty(substs.kind_ty()); 269 ( 0.00%) self.add_ty(substs.tupled_upvars_ty()); . } . 11 ( 0.00%) &ty::Bound(debruijn, _) => { . self.add_bound_var(debruijn); . } . . &ty::Placeholder(..) => { . self.add_flags(TypeFlags::HAS_TY_PLACEHOLDER); . self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); . } . . &ty::Infer(infer) => { . self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); 350 ( 0.00%) match infer { . ty::FreshTy(_) | ty::FreshIntTy(_) | ty::FreshFloatTy(_) => { . self.add_flags(TypeFlags::HAS_TY_FRESH) . } . . ty::TyVar(_) | ty::IntVar(_) | ty::FloatVar(_) => { . self.add_flags(TypeFlags::HAS_TY_INFER) . } . } . } . . &ty::Adt(_, substs) => { . self.add_substs(substs); . } . 652 ( 0.00%) &ty::Projection(data) => { . self.add_flags(TypeFlags::HAS_TY_PROJECTION); . self.add_projection_ty(data); . } . . &ty::Opaque(_, substs) => { . self.add_flags(TypeFlags::HAS_TY_OPAQUE); . self.add_substs(substs); . } . 579 ( 0.00%) &ty::Dynamic(obj, r) => { 452 ( 0.00%) for predicate in obj.iter() { 518 ( 0.00%) self.bound_computation(predicate, |computation, predicate| match predicate { 386 ( 0.00%) ty::ExistentialPredicate::Trait(tr) => computation.add_substs(tr.substs), . ty::ExistentialPredicate::Projection(p) => { . computation.add_existential_projection(&p); . } . ty::ExistentialPredicate::AutoTrait(_) => {} . }); . } . . self.add_region(r); . } . 752 ( 0.00%) &ty::Array(tt, len) => { 376 ( 0.00%) self.add_ty(tt); 752 ( 0.00%) self.add_const(len); . } . . &ty::Slice(tt) => self.add_ty(tt), . . &ty::RawPtr(ref m) => { . self.add_ty(m.ty); . } . 26,076 ( 0.00%) &ty::Ref(r, ty, _) => { . self.add_region(r); 13,038 ( 0.00%) self.add_ty(ty); . } . . &ty::Tuple(ref substs) => { 1,998 ( 0.00%) self.add_substs(substs); . } . . &ty::FnDef(_, substs) => { . self.add_substs(substs); . } . 2,210 ( 0.00%) &ty::FnPtr(fn_sig) => self.bound_computation(fn_sig, |computation, fn_sig| { . computation.add_tys(fn_sig.inputs()); 1,105 ( 0.00%) computation.add_ty(fn_sig.output()); . }), . } . } . . fn add_predicate(&mut self, binder: ty::Binder<'_, ty::PredicateKind<'_>>) { 92,382 ( 0.00%) self.bound_computation(binder, |computation, atom| computation.add_predicate_atom(atom)); . } . . fn add_predicate_atom(&mut self, atom: ty::PredicateKind<'_>) { 76,985 ( 0.00%) match atom { . ty::PredicateKind::Trait(trait_pred) => { 18,348 ( 0.00%) self.add_substs(trait_pred.trait_ref.substs); . } . ty::PredicateKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => { . self.add_region(a); . self.add_region(b); . } . ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, region)) => { 1,312 ( 0.00%) self.add_ty(ty); . self.add_region(region); . } . ty::PredicateKind::Subtype(ty::SubtypePredicate { a_is_expected: _, a, b }) => { . self.add_ty(a); . self.add_ty(b); . } . ty::PredicateKind::Coerce(ty::CoercePredicate { a, b }) => { . self.add_ty(a); . self.add_ty(b); . } . ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => { . self.add_projection_ty(projection_ty); 998 ( 0.00%) match term { 499 ( 0.00%) Term::Ty(ty) => self.add_ty(ty), . Term::Const(c) => self.add_const(c), . } . } 11,145 ( 0.00%) ty::PredicateKind::WellFormed(arg) => { 11,145 ( 0.00%) self.add_substs(slice::from_ref(&arg)); . } . ty::PredicateKind::ObjectSafe(_def_id) => {} . ty::PredicateKind::ClosureKind(_def_id, substs, _kind) => { 258 ( 0.00%) self.add_substs(substs); . } . ty::PredicateKind::ConstEvaluatable(uv) => { . self.add_unevaluated_const(uv); . } . ty::PredicateKind::ConstEquate(expected, found) => { . self.add_const(expected); . self.add_const(found); . } -- line 264 ---------------------------------------- -- line 269 ---------------------------------------- . } . . fn add_ty(&mut self, ty: Ty<'_>) { . self.add_flags(ty.flags()); . self.add_exclusive_binder(ty.outer_exclusive_binder); . } . . fn add_tys(&mut self, tys: &[Ty<'_>]) { 2,183 ( 0.00%) for &ty in tys { 2,183 ( 0.00%) self.add_ty(ty); . } . } . . fn add_region(&mut self, r: ty::Region<'_>) { . self.add_flags(r.type_flags()); 20,840 ( 0.00%) if let ty::ReLateBound(debruijn, _) = *r { . self.add_bound_var(debruijn); . } . } . 1,674,400 ( 0.03%) fn add_const(&mut self, c: &ty::Const<'_>) { 837,200 ( 0.02%) self.add_ty(c.ty); 2,093,000 ( 0.04%) match c.val { 917 ( 0.00%) ty::ConstKind::Unevaluated(unevaluated) => self.add_unevaluated_const(unevaluated), . ty::ConstKind::Infer(infer) => { . self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); 168 ( 0.00%) match infer { . InferConst::Fresh(_) => self.add_flags(TypeFlags::HAS_CT_FRESH), . InferConst::Var(_) => self.add_flags(TypeFlags::HAS_CT_INFER), . } . } . ty::ConstKind::Bound(debruijn, _) => { . self.add_bound_var(debruijn); . } . ty::ConstKind::Param(_) => { -- line 303 ---------------------------------------- -- line 306 ---------------------------------------- . } . ty::ConstKind::Placeholder(_) => { . self.add_flags(TypeFlags::HAS_CT_PLACEHOLDER); . self.add_flags(TypeFlags::STILL_FURTHER_SPECIALIZABLE); . } . ty::ConstKind::Value(_) => {} . ty::ConstKind::Error(_) => self.add_flags(TypeFlags::HAS_ERROR), . } 1,674,400 ( 0.03%) } . . fn add_unevaluated_const

(&mut self, ct: ty::Unevaluated<'_, P>) { 2,938 ( 0.00%) self.add_substs(ct.substs); . self.add_flags(TypeFlags::HAS_CT_PROJECTION); . } . . fn add_existential_projection(&mut self, projection: &ty::ExistentialProjection<'_>) { 60 ( 0.00%) self.add_substs(projection.substs); 60 ( 0.00%) match projection.term { 30 ( 0.00%) ty::Term::Ty(ty) => self.add_ty(ty), . ty::Term::Const(ct) => self.add_const(ct), . } . } . . fn add_projection_ty(&mut self, projection_ty: ty::ProjectionTy<'_>) { 499 ( 0.00%) self.add_substs(projection_ty.substs); . } . 183,071 ( 0.00%) fn add_substs(&mut self, substs: &[GenericArg<'_>]) { . for kind in substs { 33,616 ( 0.00%) match kind.unpack() { 55,774 ( 0.00%) GenericArgKind::Type(ty) => self.add_ty(ty), . GenericArgKind::Lifetime(lt) => self.add_region(lt), 104 ( 0.00%) GenericArgKind::Const(ct) => self.add_const(ct), . } . } 209,224 ( 0.00%) } . } 101,238 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_hir/src/intravisit.rs -------------------------------------------------------------------------------- Ir -- line 48 ---------------------------------------- . } . } . . impl<'v, 'hir, V> ItemLikeVisitor<'hir> for DeepVisitor<'v, V> . where . V: Visitor<'hir>, . { . fn visit_item(&mut self, item: &'hir Item<'hir>) { 5,904 ( 0.00%) self.visitor.visit_item(item); . } . . fn visit_trait_item(&mut self, trait_item: &'hir TraitItem<'hir>) { 3 ( 0.00%) self.visitor.visit_trait_item(trait_item); . } . . fn visit_impl_item(&mut self, impl_item: &'hir ImplItem<'hir>) { 1,182 ( 0.00%) self.visitor.visit_impl_item(impl_item); . } . . fn visit_foreign_item(&mut self, foreign_item: &'hir ForeignItem<'hir>) { . self.visitor.visit_foreign_item(foreign_item); . } . } . . pub trait IntoVisitor<'hir> { -- line 72 ---------------------------------------- -- line 106 ---------------------------------------- . Method(Ident, &'a FnSig<'a>, Option<&'a Visibility<'a>>), . . /// `|x, y| {}` . Closure, . } . . impl<'a> FnKind<'a> { . pub fn header(&self) -> Option<&FnHeader> { 1,255 ( 0.00%) match *self { 100 ( 0.00%) FnKind::ItemFn(_, _, ref header, _) => Some(header), 573 ( 0.00%) FnKind::Method(_, ref sig, _) => Some(&sig.header), . FnKind::Closure => None, . } . } . . pub fn constness(self) -> Constness { 582 ( 0.00%) self.header().map_or(Constness::NotConst, |header| header.constness) 291 ( 0.00%) } . . pub fn asyncness(self) -> IsAsync { . self.header().map_or(IsAsync::NotAsync, |header| header.asyncness) . } . } . . /// An abstract representation of the HIR `rustc_middle::hir::map::Map`. . pub trait Map<'hir> { -- line 131 ---------------------------------------- -- line 248 ---------------------------------------- . /// Invoked when a nested item is encountered. By default does . /// nothing unless you override `nested_visit_map` to return other than . /// `None`, in which case it will walk the item. **You probably . /// don't want to override this method** -- instead, override . /// `nested_visit_map` or use the "shallow" or "deep" visit . /// patterns described on `itemlikevisit::ItemLikeVisitor`. The only . /// reason to override this method is if you want a nested pattern . /// but cannot supply a `Map`; see `nested_visit_map` for advice. 7,872 ( 0.00%) fn visit_nested_item(&mut self, id: ItemId) { . if Self::NestedFilter::INTER { 19,186 ( 0.00%) let item = self.nested_visit_map().item(id); 8,856 ( 0.00%) self.visit_item(item); . } 7,872 ( 0.00%) } . . /// Like `visit_nested_item()`, but for trait items. See . /// `visit_nested_item()` for advice on when to override this . /// method. 23 ( 0.00%) fn visit_nested_trait_item(&mut self, id: TraitItemId) { . if Self::NestedFilter::INTER { 39 ( 0.00%) let item = self.nested_visit_map().trait_item(id); 6 ( 0.00%) self.visit_trait_item(item); . } 23 ( 0.00%) } . . /// Like `visit_nested_item()`, but for impl items. See . /// `visit_nested_item()` for advice on when to override this . /// method. 3,152 ( 0.00%) fn visit_nested_impl_item(&mut self, id: ImplItemId) { . if Self::NestedFilter::INTER { 7,683 ( 0.00%) let item = self.nested_visit_map().impl_item(id); 1,773 ( 0.00%) self.visit_impl_item(item); . } 3,152 ( 0.00%) } . . /// Like `visit_nested_item()`, but for foreign items. See . /// `visit_nested_item()` for advice on when to override this . /// method. . fn visit_nested_foreign_item(&mut self, id: ForeignItemId) { . if Self::NestedFilter::INTER { . let item = self.nested_visit_map().foreign_item(id); . self.visit_foreign_item(item); . } . } . . /// Invoked to visit the body of a function, method or closure. Like . /// visit_nested_item, does nothing by default unless you override . /// `nested_visit_map` to return other than `None`, in which case it will walk . /// the body. 3,365 ( 0.00%) fn visit_nested_body(&mut self, id: BodyId) { . if Self::NestedFilter::INTRA { 36,957 ( 0.00%) let body = self.nested_visit_map().body(id); 1,296 ( 0.00%) self.visit_body(body); . } 3,365 ( 0.00%) } . . fn visit_param(&mut self, param: &'v Param<'v>) { . walk_param(self, param) . } . . /// Visits the top-level item and (optionally) nested items / impl items. See . /// `visit_nested_item` for details. . fn visit_item(&mut self, i: &'v Item<'v>) { 12,738 ( 0.00%) walk_item(self, i) . } . . fn visit_body(&mut self, b: &'v Body<'v>) { 4,507 ( 0.00%) walk_body(self, b); . } . . /// When invoking `visit_all_item_likes()`, you need to supply an . /// item-like visitor. This method converts an "intra-visit" . /// visitor into an item-like visitor that walks the entire tree. . /// If you use this, you probably don't want to process the . /// contents of nested item-like things, since the outer loop will . /// visit them as well. -- line 323 ---------------------------------------- -- line 332 ---------------------------------------- . } . fn visit_name(&mut self, _span: Span, _name: Symbol) { . // Nothing to do. . } . fn visit_ident(&mut self, ident: Ident) { . walk_ident(self, ident) . } . fn visit_mod(&mut self, m: &'v Mod<'v>, _s: Span, n: HirId) { 181 ( 0.00%) walk_mod(self, m, n) . } . fn visit_foreign_item(&mut self, i: &'v ForeignItem<'v>) { . walk_foreign_item(self, i) . } . fn visit_local(&mut self, l: &'v Local<'v>) { 2,220 ( 0.00%) walk_local(self, l) . } . fn visit_block(&mut self, b: &'v Block<'v>) { . walk_block(self, b) . } . fn visit_stmt(&mut self, s: &'v Stmt<'v>) { 15,624 ( 0.00%) walk_stmt(self, s) . } . fn visit_arm(&mut self, a: &'v Arm<'v>) { 2,488 ( 0.00%) walk_arm(self, a) . } . fn visit_pat(&mut self, p: &'v Pat<'v>) { 72,921 ( 0.00%) walk_pat(self, p) . } . fn visit_array_length(&mut self, len: &'v ArrayLen) { . walk_array_len(self, len) . } . fn visit_anon_const(&mut self, c: &'v AnonConst) { . walk_anon_const(self, c) . } . fn visit_expr(&mut self, ex: &'v Expr<'v>) { 5,439,120 ( 0.11%) walk_expr(self, ex) . } . fn visit_let_expr(&mut self, lex: &'v Let<'v>) { 810 ( 0.00%) walk_let_expr(self, lex) . } . fn visit_ty(&mut self, t: &'v Ty<'v>) { 110,988 ( 0.00%) walk_ty(self, t) . } . fn visit_generic_param(&mut self, p: &'v GenericParam<'v>) { 8,439 ( 0.00%) walk_generic_param(self, p) . } . fn visit_const_param_default(&mut self, _param: HirId, ct: &'v AnonConst) { . walk_const_param_default(self, ct) . } . fn visit_generics(&mut self, g: &'v Generics<'v>) { 2,304 ( 0.00%) walk_generics(self, g) . } . fn visit_where_predicate(&mut self, predicate: &'v WherePredicate<'v>) { 1,557 ( 0.00%) walk_where_predicate(self, predicate) . } . fn visit_fn_decl(&mut self, fd: &'v FnDecl<'v>) { 1,463 ( 0.00%) walk_fn_decl(self, fd) . } . fn visit_fn(&mut self, fk: FnKind<'v>, fd: &'v FnDecl<'v>, b: BodyId, s: Span, id: HirId) { 58,836 ( 0.00%) walk_fn(self, fk, fd, b, s, id) . } . fn visit_use(&mut self, path: &'v Path<'v>, hir_id: HirId) { . walk_use(self, path, hir_id) . } . fn visit_trait_item(&mut self, ti: &'v TraitItem<'v>) { 47 ( 0.00%) walk_trait_item(self, ti) . } . fn visit_trait_item_ref(&mut self, ii: &'v TraitItemRef) { 3 ( 0.00%) walk_trait_item_ref(self, ii) . } . fn visit_impl_item(&mut self, ii: &'v ImplItem<'v>) { 9,862 ( 0.00%) walk_impl_item(self, ii) . } . fn visit_foreign_item_ref(&mut self, ii: &'v ForeignItemRef) { . walk_foreign_item_ref(self, ii) . } . fn visit_impl_item_ref(&mut self, ii: &'v ImplItemRef) { 788 ( 0.00%) walk_impl_item_ref(self, ii) . } 1,199 ( 0.00%) fn visit_trait_ref(&mut self, t: &'v TraitRef<'v>) { 3,592 ( 0.00%) walk_trait_ref(self, t) 872 ( 0.00%) } . fn visit_param_bound(&mut self, bounds: &'v GenericBound<'v>) { 9,976 ( 0.00%) walk_param_bound(self, bounds) . } . fn visit_poly_trait_ref(&mut self, t: &'v PolyTraitRef<'v>, m: TraitBoundModifier) { 251 ( 0.00%) walk_poly_trait_ref(self, t, m) . } . fn visit_variant_data( . &mut self, . s: &'v VariantData<'v>, . _: Symbol, . _: &'v Generics<'v>, . _parent_id: HirId, . _: Span, . ) { 1,860 ( 0.00%) walk_struct_def(self, s) . } . fn visit_field_def(&mut self, s: &'v FieldDef<'v>) { 186 ( 0.00%) walk_field_def(self, s) . } . fn visit_enum_def( . &mut self, . enum_definition: &'v EnumDef<'v>, . generics: &'v Generics<'v>, . item_id: HirId, . _: Span, . ) { 492 ( 0.00%) walk_enum_def(self, enum_definition, generics, item_id) . } . fn visit_variant(&mut self, v: &'v Variant<'v>, g: &'v Generics<'v>, item_id: HirId) { 924 ( 0.00%) walk_variant(self, v, g, item_id) . } . fn visit_label(&mut self, label: &'v Label) { . walk_label(self, label) . } . fn visit_infer(&mut self, inf: &'v InferArg) { . walk_inf(self, inf); . } 17,945 ( 0.00%) fn visit_generic_arg(&mut self, generic_arg: &'v GenericArg<'v>) { 116,463 ( 0.00%) match generic_arg { 72 ( 0.00%) GenericArg::Lifetime(lt) => self.visit_lifetime(lt), 5,313 ( 0.00%) GenericArg::Type(ty) => self.visit_ty(ty), . GenericArg::Const(ct) => self.visit_anon_const(&ct.value), . GenericArg::Infer(inf) => self.visit_infer(inf), . } 13,505 ( 0.00%) } . fn visit_lifetime(&mut self, lifetime: &'v Lifetime) { . walk_lifetime(self, lifetime) . } . fn visit_qpath(&mut self, qpath: &'v QPath<'v>, id: HirId, span: Span) { 992,704 ( 0.02%) walk_qpath(self, qpath, id, span) . } 10,180 ( 0.00%) fn visit_path(&mut self, path: &'v Path<'v>, _id: HirId) { 101,810 ( 0.00%) walk_path(self, path) 11,938 ( 0.00%) } 10,361 ( 0.00%) fn visit_path_segment(&mut self, path_span: Span, path_segment: &'v PathSegment<'v>) { . walk_path_segment(self, path_span, path_segment) 11,076 ( 0.00%) } 44,607 ( 0.00%) fn visit_generic_args(&mut self, path_span: Span, generic_args: &'v GenericArgs<'v>) { 236 ( 0.00%) walk_generic_args(self, path_span, generic_args) 39,442 ( 0.00%) } . fn visit_assoc_type_binding(&mut self, type_binding: &'v TypeBinding<'v>) { 1,761 ( 0.00%) walk_assoc_type_binding(self, type_binding) . } . fn visit_attribute(&mut self, _id: HirId, _attr: &'v Attribute) {} . fn visit_vis(&mut self, vis: &'v Visibility<'v>) { 4,044 ( 0.00%) walk_vis(self, vis) . } . fn visit_associated_item_kind(&mut self, kind: &'v AssocItemKind) { . walk_associated_item_kind(self, kind); . } . fn visit_defaultness(&mut self, defaultness: &'v Defaultness) { . walk_defaultness(self, defaultness); . } . } . 133 ( 0.00%) pub fn walk_mod<'v, V: Visitor<'v>>(visitor: &mut V, module: &'v Mod<'v>, mod_hir_id: HirId) { . visitor.visit_id(mod_hir_id); 6,668 ( 0.00%) for &item_id in module.item_ids { 1,964 ( 0.00%) visitor.visit_nested_item(item_id); . } 152 ( 0.00%) } . 14,456 ( 0.00%) pub fn walk_body<'v, V: Visitor<'v>>(visitor: &mut V, body: &'v Body<'v>) { 16,531 ( 0.00%) walk_list!(visitor, visit_param, body.params); 28,820 ( 0.00%) visitor.visit_expr(&body.value); 7,296 ( 0.00%) } . 10,212 ( 0.00%) pub fn walk_local<'v, V: Visitor<'v>>(visitor: &mut V, local: &'v Local<'v>) { . // Intentionally visiting the expr first - the initialization expr . // dominates the local's definition. 12,954 ( 0.00%) walk_list!(visitor, visit_expr, &local.init); 888 ( 0.00%) visitor.visit_id(local.hir_id); 8,492 ( 0.00%) visitor.visit_pat(&local.pat); 7,478 ( 0.00%) walk_list!(visitor, visit_ty, &local.ty); 8,304 ( 0.00%) } . . pub fn walk_ident<'v, V: Visitor<'v>>(visitor: &mut V, ident: Ident) { . visitor.visit_name(ident.span, ident.name); . } . . pub fn walk_label<'v, V: Visitor<'v>>(visitor: &mut V, label: &'v Label) { . visitor.visit_ident(label.ident); . } . . pub fn walk_lifetime<'v, V: Visitor<'v>>(visitor: &mut V, lifetime: &'v Lifetime) { 2,583 ( 0.00%) visitor.visit_id(lifetime.hir_id); 1,731 ( 0.00%) match lifetime.name { 357 ( 0.00%) LifetimeName::Param(ParamName::Plain(ident)) => { . visitor.visit_ident(ident); . } . LifetimeName::Param(ParamName::Fresh(_)) . | LifetimeName::Param(ParamName::Error) . | LifetimeName::Static . | LifetimeName::Error . | LifetimeName::Implicit(_) . | LifetimeName::ImplicitObjectLifetimeDefault . | LifetimeName::Underscore => {} . } . } . 333 ( 0.00%) pub fn walk_poly_trait_ref<'v, V: Visitor<'v>>( . visitor: &mut V, . trait_ref: &'v PolyTraitRef<'v>, . _modifier: TraitBoundModifier, . ) { . walk_list!(visitor, visit_generic_param, trait_ref.bound_generic_params); 2,570 ( 0.00%) visitor.visit_trait_ref(&trait_ref.trait_ref); 296 ( 0.00%) } . 3,172 ( 0.00%) pub fn walk_trait_ref<'v, V: Visitor<'v>>(visitor: &mut V, trait_ref: &'v TraitRef<'v>) { 2,755 ( 0.00%) visitor.visit_id(trait_ref.hir_ref_id); 11,795 ( 0.00%) visitor.visit_path(&trait_ref.path, trait_ref.hir_ref_id) 3,624 ( 0.00%) } . . pub fn walk_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v Param<'v>) { 1,768 ( 0.00%) visitor.visit_id(param.hir_id); 18,017 ( 0.00%) visitor.visit_pat(¶m.pat); . } . 120,831 ( 0.00%) pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) { 2,952 ( 0.00%) visitor.visit_vis(&item.vis); 1,476 ( 0.00%) visitor.visit_ident(item.ident); 67,220 ( 0.00%) match item.kind { 2 ( 0.00%) ItemKind::ExternCrate(orig_name) => { . visitor.visit_id(item.hir_id()); 4 ( 0.00%) if let Some(orig_name) = orig_name { . visitor.visit_name(item.span, orig_name); . } . } . ItemKind::Use(ref path, _) => { 4,566 ( 0.00%) visitor.visit_use(path, item.hir_id()); . } . ItemKind::Static(ref typ, _, body) | ItemKind::Const(ref typ, body) => { 279 ( 0.00%) visitor.visit_id(item.hir_id()); 3,627 ( 0.00%) visitor.visit_ty(typ); 6,882 ( 0.00%) visitor.visit_nested_body(body); . } 10,188 ( 0.00%) ItemKind::Fn(ref sig, ref generics, body_id) => visitor.visit_fn( 10,900 ( 0.00%) FnKind::ItemFn(item.ident, generics, sig.header, &item.vis), 2,796 ( 0.00%) &sig.decl, . body_id, 400 ( 0.00%) item.span, 1,200 ( 0.00%) item.hir_id(), . ), . ItemKind::Macro(_) => { . visitor.visit_id(item.hir_id()); . } 18 ( 0.00%) ItemKind::Mod(ref module) => { . // `visit_mod()` takes care of visiting the `Item`'s `HirId`. . visitor.visit_mod(module, item.span, item.hir_id()) . } . ItemKind::ForeignMod { abi: _, items } => { . visitor.visit_id(item.hir_id()); . walk_list!(visitor, visit_foreign_item_ref, items); . } . ItemKind::GlobalAsm(asm) => { . visitor.visit_id(item.hir_id()); . walk_inline_asm(visitor, asm); . } 6 ( 0.00%) ItemKind::TyAlias(ref ty, ref generics) => { 3 ( 0.00%) visitor.visit_id(item.hir_id()); 32 ( 0.00%) visitor.visit_ty(ty); 20 ( 0.00%) visitor.visit_generics(generics) . } . ItemKind::OpaqueTy(OpaqueTy { ref generics, bounds, .. }) => { . visitor.visit_id(item.hir_id()); . walk_generics(visitor, generics); . walk_list!(visitor, visit_param_bound, bounds); . } 91 ( 0.00%) ItemKind::Enum(ref enum_definition, ref generics) => { 90 ( 0.00%) visitor.visit_generics(generics); . // `visit_enum_def()` takes care of visiting the `Item`'s `HirId`. 71 ( 0.00%) visitor.visit_enum_def(enum_definition, generics, item.hir_id(), item.span) . } . ItemKind::Impl(Impl { . unsafety: _, . defaultness: _, . polarity: _, . constness: _, . defaultness_span: _, 847 ( 0.00%) ref generics, 218 ( 0.00%) ref of_trait, . ref self_ty, 4,356 ( 0.00%) items, . }) => { 363 ( 0.00%) visitor.visit_id(item.hir_id()); 726 ( 0.00%) visitor.visit_generics(generics); 4,260 ( 0.00%) walk_list!(visitor, visit_trait_ref, of_trait); 4,235 ( 0.00%) visitor.visit_ty(self_ty); . walk_list!(visitor, visit_impl_item_ref, items); . } . ItemKind::Struct(ref struct_definition, ref generics) . | ItemKind::Union(ref struct_definition, ref generics) => { 94 ( 0.00%) visitor.visit_generics(generics); 48 ( 0.00%) visitor.visit_id(item.hir_id()); 84 ( 0.00%) visitor.visit_variant_data( . struct_definition, 12 ( 0.00%) item.ident.name, . generics, . item.hir_id(), 12 ( 0.00%) item.span, . ); . } 261 ( 0.00%) ItemKind::Trait(.., ref generics, bounds, trait_item_refs) => { 6 ( 0.00%) visitor.visit_id(item.hir_id()); 16 ( 0.00%) visitor.visit_generics(generics); 20 ( 0.00%) walk_list!(visitor, visit_param_bound, bounds); . walk_list!(visitor, visit_trait_item_ref, trait_item_refs); . } . ItemKind::TraitAlias(ref generics, bounds) => { . visitor.visit_id(item.hir_id()); . visitor.visit_generics(generics); . walk_list!(visitor, visit_param_bound, bounds); . } . } 73,016 ( 0.00%) } . . fn walk_inline_asm<'v, V: Visitor<'v>>(visitor: &mut V, asm: &'v InlineAsm<'v>) { . for (op, _op_sp) in asm.operands { . match op { . InlineAsmOperand::In { expr, .. } . | InlineAsmOperand::InOut { expr, .. } . | InlineAsmOperand::Sym { expr, .. } => visitor.visit_expr(expr), . InlineAsmOperand::Out { expr, .. } => { -- line 657 ---------------------------------------- -- line 667 ---------------------------------------- . } . InlineAsmOperand::Const { anon_const } => visitor.visit_anon_const(anon_const), . } . } . } . . pub fn walk_use<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path<'v>, hir_id: HirId) { . visitor.visit_id(hir_id); 9,200 ( 0.00%) visitor.visit_path(path, hir_id); . } . 307 ( 0.00%) pub fn walk_enum_def<'v, V: Visitor<'v>>( . visitor: &mut V, . enum_definition: &'v EnumDef<'v>, . generics: &'v Generics<'v>, . item_id: HirId, . ) { . visitor.visit_id(item_id); 796 ( 0.00%) walk_list!(visitor, visit_variant, enum_definition.variants, generics, item_id); 328 ( 0.00%) } . 1,892 ( 0.00%) pub fn walk_variant<'v, V: Visitor<'v>>( . visitor: &mut V, . variant: &'v Variant<'v>, . generics: &'v Generics<'v>, . parent_item_id: HirId, . ) { 88 ( 0.00%) visitor.visit_ident(variant.ident); 88 ( 0.00%) visitor.visit_id(variant.id); 154 ( 0.00%) visitor.visit_variant_data( . &variant.data, . variant.ident.name, . generics, . parent_item_id, 22 ( 0.00%) variant.span, . ); 546 ( 0.00%) walk_list!(visitor, visit_anon_const, &variant.disr_expr); 1,672 ( 0.00%) } . 475,393 ( 0.01%) pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v>) { 85,112 ( 0.00%) visitor.visit_id(typ.hir_id); . 293,634 ( 0.01%) match typ.kind { 184 ( 0.00%) TyKind::Slice(ref ty) => visitor.visit_ty(ty), 168 ( 0.00%) TyKind::Ptr(ref mutable_type) => visitor.visit_ty(&mutable_type.ty), 8,914 ( 0.00%) TyKind::Rptr(ref lifetime, ref mutable_type) => { 742 ( 0.00%) visitor.visit_lifetime(lifetime); 3,068 ( 0.00%) visitor.visit_ty(&mutable_type.ty) . } . TyKind::Never => {} 1,334 ( 0.00%) TyKind::Tup(tuple_element_types) => { 390 ( 0.00%) walk_list!(visitor, visit_ty, tuple_element_types); . } . TyKind::BareFn(ref function_declaration) => { . walk_list!(visitor, visit_generic_param, function_declaration.generic_params); . visitor.visit_fn_decl(&function_declaration.decl); . } 43,298 ( 0.00%) TyKind::Path(ref qpath) => { 59,338 ( 0.00%) visitor.visit_qpath(qpath, typ.hir_id, typ.span); . } . TyKind::OpaqueDef(item_id, lifetimes) => { . visitor.visit_nested_item(item_id); . walk_list!(visitor, visit_generic_arg, lifetimes); . } . TyKind::Array(ref ty, ref length) => { . visitor.visit_ty(ty); . visitor.visit_array_length(length) . } 33 ( 0.00%) TyKind::TraitObject(bounds, ref lifetime, _syntax) => { . for bound in bounds { . visitor.visit_poly_trait_ref(bound, TraitBoundModifier::None); . } 10 ( 0.00%) visitor.visit_lifetime(lifetime); . } . TyKind::Typeof(ref expression) => visitor.visit_anon_const(expression), . TyKind::Infer | TyKind::Err => {} . } 68,264 ( 0.00%) } . . pub fn walk_inf<'v, V: Visitor<'v>>(visitor: &mut V, inf: &'v InferArg) { . visitor.visit_id(inf.hir_id); . } . 1,098,051 ( 0.02%) pub fn walk_qpath<'v, V: Visitor<'v>>( . visitor: &mut V, . qpath: &'v QPath<'v>, . id: HirId, . span: Span, . ) { 445,762 ( 0.01%) match *qpath { . QPath::Resolved(ref maybe_qself, ref path) => { 132,080 ( 0.00%) walk_list!(visitor, visit_ty, maybe_qself); 174,654 ( 0.00%) visitor.visit_path(path, id) . } . QPath::TypeRelative(ref qself, ref segment) => { 8,729 ( 0.00%) visitor.visit_ty(qself); 10,770 ( 0.00%) visitor.visit_path_segment(span, segment); . } . QPath::LangItem(..) => {} . } 935,012 ( 0.02%) } . 79,730 ( 0.00%) pub fn walk_path<'v, V: Visitor<'v>>(visitor: &mut V, path: &'v Path<'v>) { . for segment in path.segments { 32,328 ( 0.00%) visitor.visit_path_segment(path.span, segment); . } 92,920 ( 0.00%) } . 1,125 ( 0.00%) pub fn walk_path_segment<'v, V: Visitor<'v>>( . visitor: &mut V, . path_span: Span, . segment: &'v PathSegment<'v>, . ) { 24,505 ( 0.00%) visitor.visit_ident(segment.ident); 47,373 ( 0.00%) walk_list!(visitor, visit_id, segment.hir_id); 760,218 ( 0.02%) if let Some(ref args) = segment.args { 20,643 ( 0.00%) visitor.visit_generic_args(path_span, args); . } 1,350 ( 0.00%) } . 781 ( 0.00%) pub fn walk_generic_args<'v, V: Visitor<'v>>( . visitor: &mut V, . _path_span: Span, . generic_args: &'v GenericArgs<'v>, . ) { 9,225 ( 0.00%) walk_list!(visitor, visit_generic_arg, generic_args.args); 19,133 ( 0.00%) walk_list!(visitor, visit_assoc_type_binding, generic_args.bindings); 689 ( 0.00%) } . 5,056 ( 0.00%) pub fn walk_assoc_type_binding<'v, V: Visitor<'v>>( . visitor: &mut V, . type_binding: &'v TypeBinding<'v>, . ) { 84 ( 0.00%) visitor.visit_id(type_binding.hir_id); 63 ( 0.00%) visitor.visit_ident(type_binding.ident); 865 ( 0.00%) visitor.visit_generic_args(type_binding.span, type_binding.gen_args); 1,178 ( 0.00%) match type_binding.kind { 1,178 ( 0.00%) TypeBindingKind::Equality { ref term } => match term { 796 ( 0.00%) Term::Ty(ref ty) => visitor.visit_ty(ty), . Term::Const(ref c) => visitor.visit_anon_const(c), . }, . TypeBindingKind::Constraint { bounds } => walk_list!(visitor, visit_param_bound, bounds), . } 315 ( 0.00%) } . 397,358 ( 0.01%) pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat<'v>) { 35,068 ( 0.00%) visitor.visit_id(pattern.hir_id); 227,075 ( 0.00%) match pattern.kind { 7,971 ( 0.00%) PatKind::TupleStruct(ref qpath, children, _) => { 3,519 ( 0.00%) visitor.visit_qpath(qpath, pattern.hir_id, pattern.span); 2,160 ( 0.00%) walk_list!(visitor, visit_pat, children); . } 714 ( 0.00%) PatKind::Path(ref qpath) => { 2,102 ( 0.00%) visitor.visit_qpath(qpath, pattern.hir_id, pattern.span); . } 9,541 ( 0.00%) PatKind::Struct(ref qpath, fields, _) => { 4,209 ( 0.00%) visitor.visit_qpath(qpath, pattern.hir_id, pattern.span); . for field in fields { 684 ( 0.00%) visitor.visit_id(field.hir_id); 684 ( 0.00%) visitor.visit_ident(field.ident); 7,765 ( 0.00%) visitor.visit_pat(&field.pat) . } . } 216 ( 0.00%) PatKind::Or(pats) => walk_list!(visitor, visit_pat, pats), . PatKind::Tuple(tuple_elements, _) => { 1,854 ( 0.00%) walk_list!(visitor, visit_pat, tuple_elements); . } . PatKind::Box(ref subpattern) | PatKind::Ref(ref subpattern, _) => { 1,118 ( 0.00%) visitor.visit_pat(subpattern) . } 3,496 ( 0.00%) PatKind::Binding(_, _hir_id, ident, ref optional_subpattern) => { . visitor.visit_ident(ident); 27,357 ( 0.00%) walk_list!(visitor, visit_pat, optional_subpattern); . } 602 ( 0.00%) PatKind::Lit(ref expression) => visitor.visit_expr(expression), . PatKind::Range(ref lower_bound, ref upper_bound, _) => { . walk_list!(visitor, visit_expr, lower_bound); . walk_list!(visitor, visit_expr, upper_bound); . } . PatKind::Wild => (), . PatKind::Slice(prepatterns, ref slice_pattern, postpatterns) => { . walk_list!(visitor, visit_pat, prepatterns); . walk_list!(visitor, visit_pat, slice_pattern); . walk_list!(visitor, visit_pat, postpatterns); . } . } 336,760 ( 0.01%) } . . pub fn walk_foreign_item<'v, V: Visitor<'v>>(visitor: &mut V, foreign_item: &'v ForeignItem<'v>) { . visitor.visit_id(foreign_item.hir_id()); . visitor.visit_vis(&foreign_item.vis); . visitor.visit_ident(foreign_item.ident); . . match foreign_item.kind { . ForeignItemKind::Fn(ref function_declaration, param_names, ref generics) => { -- line 861 ---------------------------------------- -- line 865 ---------------------------------------- . visitor.visit_ident(param_name); . } . } . ForeignItemKind::Static(ref typ, _) => visitor.visit_ty(typ), . ForeignItemKind::Type => (), . } . } . 26,520 ( 0.00%) pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v GenericBound<'v>) { 9,506 ( 0.00%) match *bound { 258 ( 0.00%) GenericBound::Trait(ref typ, modifier) => { 1,120 ( 0.00%) visitor.visit_poly_trait_ref(typ, modifier); . } . GenericBound::LangItemTrait(_, span, hir_id, args) => { . visitor.visit_id(hir_id); . visitor.visit_generic_args(span, args); . } . GenericBound::Outlives(ref lifetime) => visitor.visit_lifetime(lifetime), . } 16,702 ( 0.00%) } . 31,144 ( 0.00%) pub fn walk_generic_param<'v, V: Visitor<'v>>(visitor: &mut V, param: &'v GenericParam<'v>) { 720 ( 0.00%) visitor.visit_id(param.hir_id); 360 ( 0.00%) match param.name { 540 ( 0.00%) ParamName::Plain(ident) => visitor.visit_ident(ident), . ParamName::Error | ParamName::Fresh(_) => {} . } 21,463 ( 0.00%) match param.kind { . GenericParamKind::Lifetime { .. } => {} 3,602 ( 0.00%) GenericParamKind::Type { ref default, .. } => walk_list!(visitor, visit_ty, default), . GenericParamKind::Const { ref ty, ref default } => { . visitor.visit_ty(ty); . if let Some(ref default) = default { . visitor.visit_const_param_default(param.hir_id, default); . } . } . } 5,005 ( 0.00%) walk_list!(visitor, visit_param_bound, param.bounds); 27,431 ( 0.00%) } . . pub fn walk_const_param_default<'v, V: Visitor<'v>>(visitor: &mut V, ct: &'v AnonConst) { . visitor.visit_anon_const(ct) . } . 11,995 ( 0.00%) pub fn walk_generics<'v, V: Visitor<'v>>(visitor: &mut V, generics: &'v Generics<'v>) { 4,164 ( 0.00%) walk_list!(visitor, visit_generic_param, generics.params); 12,270 ( 0.00%) walk_list!(visitor, visit_where_predicate, generics.where_clause.predicates); 10,662 ( 0.00%) } . 5,031 ( 0.00%) pub fn walk_where_predicate<'v, V: Visitor<'v>>( . visitor: &mut V, . predicate: &'v WherePredicate<'v>, . ) { 1,677 ( 0.00%) match *predicate { . WherePredicate::BoundPredicate(WhereBoundPredicate { . ref bounded_ty, 1,138 ( 0.00%) bounds, 1,158 ( 0.00%) bound_generic_params, . .. . }) => { 599 ( 0.00%) visitor.visit_ty(bounded_ty); . walk_list!(visitor, visit_param_bound, bounds); . walk_list!(visitor, visit_generic_param, bound_generic_params); . } . WherePredicate::RegionPredicate(WhereRegionPredicate { ref lifetime, bounds, .. }) => { . visitor.visit_lifetime(lifetime); . walk_list!(visitor, visit_param_bound, bounds); . } . WherePredicate::EqPredicate(WhereEqPredicate { . hir_id, ref lhs_ty, ref rhs_ty, .. . }) => { . visitor.visit_id(hir_id); . visitor.visit_ty(lhs_ty); . visitor.visit_ty(rhs_ty); . } . } 4,472 ( 0.00%) } . . pub fn walk_fn_ret_ty<'v, V: Visitor<'v>>(visitor: &mut V, ret_ty: &'v FnRetTy<'v>) { 17,176 ( 0.00%) if let FnRetTy::Return(ref output_ty) = *ret_ty { 9,150 ( 0.00%) visitor.visit_ty(output_ty) . } . } . 6,552 ( 0.00%) pub fn walk_fn_decl<'v, V: Visitor<'v>>(visitor: &mut V, function_declaration: &'v FnDecl<'v>) { 8,246 ( 0.00%) for ty in function_declaration.inputs { 2,721 ( 0.00%) visitor.visit_ty(ty) . } . walk_fn_ret_ty(visitor, &function_declaration.output) 3,536 ( 0.00%) } . . pub fn walk_fn_kind<'v, V: Visitor<'v>>(visitor: &mut V, function_kind: FnKind<'v>) { 12,090 ( 0.00%) match function_kind { . FnKind::ItemFn(_, generics, ..) => { 988 ( 0.00%) visitor.visit_generics(generics); . } . FnKind::Method(..) | FnKind::Closure => {} . } . } . 63,922 ( 0.00%) pub fn walk_fn<'v, V: Visitor<'v>>( . visitor: &mut V, . function_kind: FnKind<'v>, . function_declaration: &'v FnDecl<'v>, . body_id: BodyId, . _span: Span, . id: HirId, . ) { . visitor.visit_id(id); . visitor.visit_fn_decl(function_declaration); . walk_fn_kind(visitor, function_kind); 11,882 ( 0.00%) visitor.visit_nested_body(body_id) 36,720 ( 0.00%) } . 238 ( 0.00%) pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v TraitItem<'v>) { 3 ( 0.00%) visitor.visit_ident(trait_item.ident); 3 ( 0.00%) visitor.visit_generics(&trait_item.generics); 189 ( 0.00%) match trait_item.kind { . TraitItemKind::Const(ref ty, default) => { . visitor.visit_id(trait_item.hir_id()); . visitor.visit_ty(ty); . walk_list!(visitor, visit_nested_body, default); . } 4 ( 0.00%) TraitItemKind::Fn(ref sig, TraitFn::Required(param_names)) => { 3 ( 0.00%) visitor.visit_id(trait_item.hir_id()); 27 ( 0.00%) visitor.visit_fn_decl(&sig.decl); 6 ( 0.00%) for ¶m_name in param_names { . visitor.visit_ident(param_name); . } . } . TraitItemKind::Fn(ref sig, TraitFn::Provided(body_id)) => { . visitor.visit_fn( . FnKind::Method(trait_item.ident, sig, None), . &sig.decl, . body_id, -- line 999 ---------------------------------------- -- line 1002 ---------------------------------------- . ); . } . TraitItemKind::Type(bounds, ref default) => { . visitor.visit_id(trait_item.hir_id()); . walk_list!(visitor, visit_param_bound, bounds); . walk_list!(visitor, visit_ty, default); . } . } 8 ( 0.00%) } . 8 ( 0.00%) pub fn walk_trait_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, trait_item_ref: &'v TraitItemRef) { . // N.B., deliberately force a compilation error if/when new fields are added. 14 ( 0.00%) let TraitItemRef { id, ident, ref kind, span: _, ref defaultness } = *trait_item_ref; 7 ( 0.00%) visitor.visit_nested_trait_item(id); . visitor.visit_ident(ident); . visitor.visit_associated_item_kind(kind); . visitor.visit_defaultness(defaultness); 8 ( 0.00%) } . 46,711 ( 0.00%) pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplItem<'v>) { . // N.B., deliberately force a compilation error if/when new fields are added. 2,024 ( 0.00%) let ImplItem { def_id: _, ident, ref vis, ref defaultness, ref generics, ref kind, span: _ } = . *impl_item; . . visitor.visit_ident(ident); 197 ( 0.00%) visitor.visit_vis(vis); . visitor.visit_defaultness(defaultness); 1,935 ( 0.00%) visitor.visit_generics(generics); 26,750 ( 0.00%) match *kind { . ImplItemKind::Const(ref ty, body) => { . visitor.visit_id(impl_item.hir_id()); . visitor.visit_ty(ty); . visitor.visit_nested_body(body); . } 13,594 ( 0.00%) ImplItemKind::Fn(ref sig, body_id) => { 3,056 ( 0.00%) visitor.visit_fn( 17,647 ( 0.00%) FnKind::Method(impl_item.ident, sig, Some(&impl_item.vis)), 5,188 ( 0.00%) &sig.decl, . body_id, 764 ( 0.00%) impl_item.span, 2,292 ( 0.00%) impl_item.hir_id(), . ); . } . ImplItemKind::TyAlias(ref ty) => { 18 ( 0.00%) visitor.visit_id(impl_item.hir_id()); 258 ( 0.00%) visitor.visit_ty(ty); . } . } 34,807 ( 0.00%) } . . pub fn walk_foreign_item_ref<'v, V: Visitor<'v>>( . visitor: &mut V, . foreign_item_ref: &'v ForeignItemRef, . ) { . // N.B., deliberately force a compilation error if/when new fields are added. . let ForeignItemRef { id, ident, span: _ } = *foreign_item_ref; . visitor.visit_nested_foreign_item(id); . visitor.visit_ident(ident); . } . 1,576 ( 0.00%) pub fn walk_impl_item_ref<'v, V: Visitor<'v>>(visitor: &mut V, impl_item_ref: &'v ImplItemRef) { . // N.B., deliberately force a compilation error if/when new fields are added. 2,758 ( 0.00%) let ImplItemRef { id, ident, ref kind, span: _, ref defaultness, trait_item_def_id: _ } = . *impl_item_ref; 985 ( 0.00%) visitor.visit_nested_impl_item(id); . visitor.visit_ident(ident); . visitor.visit_associated_item_kind(kind); . visitor.visit_defaultness(defaultness); 1,576 ( 0.00%) } . 3,264 ( 0.00%) pub fn walk_struct_def<'v, V: Visitor<'v>>( . visitor: &mut V, . struct_definition: &'v VariantData<'v>, . ) { 2,122 ( 0.00%) walk_list!(visitor, visit_id, struct_definition.ctor_hir_id()); 3,097 ( 0.00%) walk_list!(visitor, visit_field_def, struct_definition.fields()); 2,890 ( 0.00%) } . 248 ( 0.00%) pub fn walk_field_def<'v, V: Visitor<'v>>(visitor: &mut V, field: &'v FieldDef<'v>) { 248 ( 0.00%) visitor.visit_id(field.hir_id); 186 ( 0.00%) visitor.visit_vis(&field.vis); 186 ( 0.00%) visitor.visit_ident(field.ident); 2,141 ( 0.00%) visitor.visit_ty(&field.ty); . } . 75,414 ( 0.00%) pub fn walk_block<'v, V: Visitor<'v>>(visitor: &mut V, block: &'v Block<'v>) { 2,496 ( 0.00%) visitor.visit_id(block.hir_id); 20,753 ( 0.00%) walk_list!(visitor, visit_stmt, block.stmts); 53,278 ( 0.00%) walk_list!(visitor, visit_expr, &block.expr); 23,212 ( 0.00%) } . 34,848 ( 0.00%) pub fn walk_stmt<'v, V: Visitor<'v>>(visitor: &mut V, statement: &'v Stmt<'v>) { 1,752 ( 0.00%) visitor.visit_id(statement.hir_id); 75,493 ( 0.00%) match statement.kind { 10,922 ( 0.00%) StmtKind::Local(ref local) => visitor.visit_local(local), 29 ( 0.00%) StmtKind::Item(item) => visitor.visit_nested_item(item), . StmtKind::Expr(ref expression) | StmtKind::Semi(ref expression) => { 17,960 ( 0.00%) visitor.visit_expr(expression) . } . } 19,292 ( 0.00%) } . . pub fn walk_array_len<'v, V: Visitor<'v>>(visitor: &mut V, len: &'v ArrayLen) { . match len { . &ArrayLen::Infer(hir_id, _span) => visitor.visit_id(hir_id), . ArrayLen::Body(c) => visitor.visit_anon_const(c), . } . } . . pub fn walk_anon_const<'v, V: Visitor<'v>>(visitor: &mut V, constant: &'v AnonConst) { . visitor.visit_id(constant.hir_id); . visitor.visit_nested_body(constant.body); . } . 690 ( 0.00%) pub fn walk_let_expr<'v, V: Visitor<'v>>(visitor: &mut V, let_expr: &'v Let<'v>) { . // match the visit order in walk_local 1,022 ( 0.00%) visitor.visit_expr(let_expr.init); 60 ( 0.00%) visitor.visit_id(let_expr.hir_id); 676 ( 0.00%) visitor.visit_pat(let_expr.pat); 1,608 ( 0.00%) walk_list!(visitor, visit_ty, let_expr.ty); 600 ( 0.00%) } . 44,791,736 ( 0.92%) pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr<'v>) { 9,604,238 ( 0.20%) visitor.visit_id(expression.hir_id); 24,719,420 ( 0.51%) match expression.kind { . ExprKind::Box(ref subexpression) => visitor.visit_expr(subexpression), . ExprKind::Array(subexpressions) => { 6,632,907 ( 0.14%) walk_list!(visitor, visit_expr, subexpressions); . } . ExprKind::ConstBlock(ref anon_const) => visitor.visit_anon_const(anon_const), . ExprKind::Repeat(ref element, ref count) => { . visitor.visit_expr(element); . visitor.visit_array_length(count) . } 19,554 ( 0.00%) ExprKind::Struct(ref qpath, fields, ref optional_base) => { 18,934 ( 0.00%) visitor.visit_qpath(qpath, expression.hir_id, expression.span); . for field in fields { 3,904 ( 0.00%) visitor.visit_id(field.hir_id); 2,928 ( 0.00%) visitor.visit_ident(field.ident); 65,549 ( 0.00%) visitor.visit_expr(&field.expr) . } 4,563 ( 0.00%) walk_list!(visitor, visit_expr, optional_base); . } . ExprKind::Tup(subexpressions) => { 12,672 ( 0.00%) walk_list!(visitor, visit_expr, subexpressions); . } 34,368 ( 0.00%) ExprKind::Call(ref callee_expression, arguments) => { 30,158 ( 0.00%) visitor.visit_expr(callee_expression); 42,572 ( 0.00%) walk_list!(visitor, visit_expr, arguments); . } 30,754 ( 0.00%) ExprKind::MethodCall(ref segment, arguments, _) => { 19,355 ( 0.00%) visitor.visit_path_segment(expression.span, segment); 44,600 ( 0.00%) walk_list!(visitor, visit_expr, arguments); . } 3,104 ( 0.00%) ExprKind::Binary(_, ref left_expression, ref right_expression) => { 14,767 ( 0.00%) visitor.visit_expr(left_expression); 6,835 ( 0.00%) visitor.visit_expr(right_expression) . } . ExprKind::AddrOf(_, _, ref subexpression) | ExprKind::Unary(_, ref subexpression) => { 5,100 ( 0.00%) visitor.visit_expr(subexpression) . } . ExprKind::Cast(ref subexpression, ref typ) | ExprKind::Type(ref subexpression, ref typ) => { 692 ( 0.00%) visitor.visit_expr(subexpression); 636 ( 0.00%) visitor.visit_ty(typ) . } 1,166 ( 0.00%) ExprKind::DropTemps(ref subexpression) => { 294 ( 0.00%) visitor.visit_expr(subexpression); . } 526 ( 0.00%) ExprKind::Let(ref let_expr) => visitor.visit_let_expr(let_expr), . ExprKind::If(ref cond, ref then, ref else_opt) => { 8,257 ( 0.00%) visitor.visit_expr(cond); 6,452 ( 0.00%) visitor.visit_expr(then); 1,523 ( 0.00%) walk_list!(visitor, visit_expr, else_opt); . } . ExprKind::Loop(ref block, ref opt_label, _, _) => { 19 ( 0.00%) walk_list!(visitor, visit_label, opt_label); 912 ( 0.00%) visitor.visit_block(block); . } 5,509 ( 0.00%) ExprKind::Match(ref subexpression, arms, _) => { 7,463 ( 0.00%) visitor.visit_expr(subexpression); 2,492 ( 0.00%) walk_list!(visitor, visit_arm, arms); . } 963 ( 0.00%) ExprKind::Closure(_, ref function_declaration, body, _fn_decl_span, _gen) => visitor . .visit_fn( 17 ( 0.00%) FnKind::Closure, 526 ( 0.00%) function_declaration, . body, 119 ( 0.00%) expression.span, 102 ( 0.00%) expression.hir_id, . ), . ExprKind::Block(ref block, ref opt_label) => { 605 ( 0.00%) walk_list!(visitor, visit_label, opt_label); 22,528 ( 0.00%) visitor.visit_block(block); . } 447 ( 0.00%) ExprKind::Assign(ref lhs, ref rhs, _) => { 480 ( 0.00%) visitor.visit_expr(rhs); 64 ( 0.00%) visitor.visit_expr(lhs) . } 280 ( 0.00%) ExprKind::AssignOp(_, ref left_expression, ref right_expression) => { 300 ( 0.00%) visitor.visit_expr(right_expression); 40 ( 0.00%) visitor.visit_expr(left_expression); . } 5,973 ( 0.00%) ExprKind::Field(ref subexpression, ident) => { 1,496 ( 0.00%) visitor.visit_expr(subexpression); . visitor.visit_ident(ident); . } 364 ( 0.00%) ExprKind::Index(ref main_expression, ref index_expression) => { 962 ( 0.00%) visitor.visit_expr(main_expression); 52 ( 0.00%) visitor.visit_expr(index_expression) . } 70,226 ( 0.00%) ExprKind::Path(ref qpath) => { 213,038 ( 0.00%) visitor.visit_qpath(qpath, expression.hir_id, expression.span); . } . ExprKind::Break(ref destination, ref opt_expr) => { 23 ( 0.00%) walk_list!(visitor, visit_label, &destination.label); 343 ( 0.00%) walk_list!(visitor, visit_expr, opt_expr); . } . ExprKind::Continue(ref destination) => { 1 ( 0.00%) walk_list!(visitor, visit_label, &destination.label); . } . ExprKind::Ret(ref optional_expression) => { 362 ( 0.00%) walk_list!(visitor, visit_expr, optional_expression); . } . ExprKind::InlineAsm(ref asm) => { . walk_inline_asm(visitor, asm); . } . ExprKind::Yield(ref subexpression, _) => { . visitor.visit_expr(subexpression); . } . ExprKind::Lit(_) | ExprKind::Err => {} . } 38,309,416 ( 0.79%) } . 12,220 ( 0.00%) pub fn walk_arm<'v, V: Visitor<'v>>(visitor: &mut V, arm: &'v Arm<'v>) { 828 ( 0.00%) visitor.visit_id(arm.hir_id); 13,494 ( 0.00%) visitor.visit_pat(&arm.pat); 43,913 ( 0.00%) if let Some(ref g) = arm.guard { . match g { . Guard::If(ref e) => visitor.visit_expr(e), . Guard::IfLet(ref pat, ref e) => { . visitor.visit_pat(pat); . visitor.visit_expr(e); . } . } . } 15,726 ( 0.00%) visitor.visit_expr(&arm.body); 4,968 ( 0.00%) } . 12,634 ( 0.00%) pub fn walk_vis<'v, V: Visitor<'v>>(visitor: &mut V, vis: &'v Visibility<'v>) { 38,635 ( 0.00%) if let VisibilityKind::Restricted { ref path, hir_id } = vis.node { . visitor.visit_id(hir_id); . visitor.visit_path(path, hir_id) . } 14,868 ( 0.00%) } . . pub fn walk_associated_item_kind<'v, V: Visitor<'v>>(_: &mut V, _: &'v AssocItemKind) { . // No visitable content here: this fn exists so you can call it if . // the right thing to do, should content be added in the future, . // would be to walk it. . } . . pub fn walk_defaultness<'v, V: Visitor<'v>>(_: &mut V, _: &'v Defaultness) { -- line 1263 ---------------------------------------- 1,633,435 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_trait_selection/src/traits/structural_match.rs -------------------------------------------------------------------------------- Ir -- line 42 ---------------------------------------- . /// reachable from a constant's type to implement the . /// structural-match traits, which essentially say that . /// the implementation of `PartialEq::eq` behaves *equivalently* to a . /// comparison against the unfolded structure. . /// . /// For more background on why Rust has this requirement, and issues . /// that arose when the requirement was not enforced completely, see . /// Rust RFC 1445, rust-lang/rust#61188, and rust-lang/rust#62307. 1,658,070 ( 0.03%) pub fn search_for_structural_match_violation<'tcx>( . span: Span, . tcx: TyCtxt<'tcx>, . ty: Ty<'tcx>, . ) -> Option> { . // FIXME: we should instead pass in an `infcx` from the outside. 1,658,070 ( 0.03%) tcx.infer_ctxt().enter(|infcx| { 11,330,145 ( 0.23%) ty.visit_with(&mut Search { infcx, span, seen: FxHashSet::default() }).break_value() . }) 1,934,415 ( 0.04%) } . . /// This method returns true if and only if `adt_ty` itself has been marked as . /// eligible for structural-match: namely, if it implements both . /// `StructuralPartialEq` and `StructuralEq` (which are respectively injected by . /// `#[derive(PartialEq)]` and `#[derive(Eq)]`). . /// . /// Note that this does *not* recursively check if the substructure of `adt_ty` . /// implements the traits. 11 ( 0.00%) fn type_marked_structural<'tcx>( . infcx: &InferCtxt<'_, 'tcx>, . adt_ty: Ty<'tcx>, . cause: ObligationCause<'tcx>, . ) -> bool { . let mut fulfillment_cx = traits::FulfillmentContext::new(); . // require `#[derive(PartialEq)]` . let structural_peq_def_id = 11 ( 0.00%) infcx.tcx.require_lang_item(LangItem::StructuralPeq, Some(cause.span)); 10 ( 0.00%) fulfillment_cx.register_bound( . infcx, . ty::ParamEnv::empty(), . adt_ty, . structural_peq_def_id, . cause.clone(), . ); . // for now, require `#[derive(Eq)]`. (Doing so is a hack to work around . // the type `for<'a> fn(&'a ())` failing to implement `Eq` itself.) . let structural_teq_def_id = 5 ( 0.00%) infcx.tcx.require_lang_item(LangItem::StructuralTeq, Some(cause.span)); 8 ( 0.00%) fulfillment_cx.register_bound( . infcx, . ty::ParamEnv::empty(), . adt_ty, . structural_teq_def_id, 4 ( 0.00%) cause, . ); . . // We deliberately skip *reporting* fulfillment errors (via . // `report_fulfillment_errors`), for two reasons: . // . // 1. The error messages would mention `std::marker::StructuralPartialEq` . // (a trait which is solely meant as an implementation detail . // for now), and . // . // 2. We are sometimes doing future-incompatibility lints for . // now, so we do not want unconditional errors here. 2 ( 0.00%) fulfillment_cx.select_all_or_error(infcx).is_empty() 9 ( 0.00%) } . . /// This implements the traversal over the structure of a given type to try to . /// find instances of ADTs (specifically structs or enums) that do not implement . /// the structural-match traits (`StructuralPartialEq` and `StructuralEq`). . struct Search<'a, 'tcx> { . span: Span, . . infcx: InferCtxt<'a, 'tcx>, -- line 114 ---------------------------------------- -- line 126 ---------------------------------------- . fn type_marked_structural(&self, adt_ty: Ty<'tcx>) -> bool { . adt_ty.is_structural_eq_shallow(self.tcx()) . } . } . . impl<'a, 'tcx> TypeVisitor<'tcx> for Search<'a, 'tcx> { . type BreakTy = NonStructuralMatchTy<'tcx>; . 2,768,120 ( 0.06%) fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow { . debug!("Search visiting ty: {:?}", ty); . 1,660,872 ( 0.03%) let (adt_def, substs) = match *ty.kind() { 550 ( 0.00%) ty::Adt(adt_def, substs) => (adt_def, substs), . ty::Param(_) => { . return ControlFlow::Break(NonStructuralMatchTy::Param); . } . ty::Dynamic(..) => { . return ControlFlow::Break(NonStructuralMatchTy::Dynamic); . } . ty::Foreign(_) => { . return ControlFlow::Break(NonStructuralMatchTy::Foreign); -- line 146 ---------------------------------------- -- line 190 ---------------------------------------- . // These primitive types are always structural match. . // . // `Never` is kind of special here, but as it is not inhabitable, this should be fine. . return ControlFlow::CONTINUE; . } . . ty::Array(..) | ty::Slice(_) | ty::Ref(..) | ty::Tuple(..) => { . // First check all contained types and then tell the caller to continue searching. 930 ( 0.00%) return ty.super_visit_with(self); . } . ty::Infer(_) | ty::Placeholder(_) | ty::Bound(..) => { . bug!("unexpected type during structural-match checking: {:?}", ty); . } . ty::Error(_) => { . self.tcx().sess.delay_span_bug(self.span, "ty::Error in structural-match check"); . // We still want to check other types after encountering an error, . // as this may still emit relevant errors. . return ControlFlow::CONTINUE; . } . }; . 1,100 ( 0.00%) if !self.seen.insert(adt_def.did) { . debug!("Search already seen adt_def: {:?}", adt_def); . return ControlFlow::CONTINUE; . } . 550 ( 0.00%) if !self.type_marked_structural(ty) { . debug!("Search found ty: {:?}", ty); . return ControlFlow::Break(NonStructuralMatchTy::Adt(&adt_def)); . } . . // structural-match does not care about the . // instantiation of the generics in an ADT (it . // instead looks directly at its fields outside . // this match), so we skip super_visit_with. -- line 224 ---------------------------------------- -- line 231 ---------------------------------------- . // even though we skip super_visit_with, we must recur on . // fields of ADT. . let tcx = self.tcx(); . adt_def.all_fields().map(|field| field.ty(tcx, substs)).try_for_each(|field_ty| { . let ty = self.tcx().normalize_erasing_regions(ty::ParamEnv::empty(), field_ty); . debug!("structural-match ADT: field_ty={:?}, ty={:?}", field_ty, ty); . ty.visit_with(self) . }) 2,491,308 ( 0.05%) } . } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) providers.has_structural_eq_impls = |tcx, ty| { 5 ( 0.00%) tcx.infer_ctxt().enter(|infcx| { . let cause = ObligationCause::dummy(); 6 ( 0.00%) type_marked_structural(&infcx, ty, cause) 1 ( 0.00%) }) 1 ( 0.00%) }; . } 2,764,394 ( 0.06%) -------------------------------------------------------------------------------- -- 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 { 3,871 ( 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 4,424 ( 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 { 1,404,673 ( 0.03%) 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 { 1,579,761 ( 0.03%) 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 { 43,023 ( 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 { 3,410,373 ( 0.07%) 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 ] . 1,940 ( 0.00%) if self.tail <= self.head { . // A . // Nop 393 ( 0.00%) } else if self.head < old_capacity - self.tail { . // B . unsafe { 12 ( 0.00%) self.copy_nonoverlapping(old_capacity, 0, self.head); . } 180 ( 0.00%) self.head += old_capacity; . debug_assert!(self.head > self.tail); . } else { . // C 64 ( 0.00%) let new_tail = new_capacity - (old_capacity - self.tail); . unsafe { 2 ( 0.00%) self.copy_nonoverlapping(new_tail, self.tail, old_capacity - self.tail); . } 32 ( 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 { 3,580 ( 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 { 614 ( 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")] 8,388 ( 0.00%) pub fn with_capacity_in(capacity: usize, alloc: A) -> VecDeque { 5,310 ( 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(); . 11,986 ( 0.00%) VecDeque { tail: 0, head: 0, buf: RawVec::with_capacity_in(cap, alloc) } 12,582 ( 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> { 5,379,600 ( 0.11%) 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> { 2,508,130 ( 0.05%) 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")] 760 ( 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 { 190 ( 0.00%) if len > self.len() { . return; . } . let num_dropped = self.len() - len; . let (front, back) = self.as_mut_slices(); 190 ( 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 _; 95 ( 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); . } . } 760 ( 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 { 3,455 ( 0.00%) let head = self.head; 3,455 ( 0.00%) let tail = self.tail; 4,530 ( 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 { 2,452,798 ( 0.05%) 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 { 4,697,528 ( 0.10%) 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) { 190 ( 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> { 138,766 ( 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 { 750,085 ( 0.02%) if self.is_empty() { . None . } else { . let tail = self.tail; 1,445,267 ( 0.03%) self.tail = self.wrap_add(self.tail, 1); 14,372 ( 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 { 408,157 ( 0.01%) if self.is_empty() { . None . } else { 674,987 ( 0.01%) 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")] 2,804,952 ( 0.06%) pub fn push_back(&mut self, value: T) { 3,410,357 ( 0.07%) if self.is_full() { 851 ( 0.00%) self.grow(); . } . 477 ( 0.00%) let head = self.head; 1,137,260 ( 0.02%) self.head = self.wrap_add(self.head, 1); 435,545 ( 0.01%) unsafe { self.buffer_write(head, value) } 2,804,952 ( 0.06%) } . . #[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)] 2,862 ( 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(); 1,431 ( 0.00%) self.buf.reserve_exact(old_cap, old_cap); 2,385 ( 0.00%) assert!(self.cap() == old_cap * 2); . unsafe { . self.handle_capacity_increase(old_cap); . } . debug_assert!(!self.is_full()); 2,862 ( 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()); 5,981,949 ( 0.12%) 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 10,141,410 ( 0.21%) (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 { 1,064 ( 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() { 1,149 ( 0.00%) if self.len() == self.capacity() { . let (lower, _) = iter.size_hint(); . self.reserve(lower.saturating_add(1)); . } . . let head = self.head; 269 ( 0.00%) self.head = self.wrap_add(self.head, 1); . unsafe { 144 ( 0.00%) self.buffer_write(head, element); . } . } 1,216 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, elem: T) { . self.push_back(elem); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { -- line 2937 ---------------------------------------- 1,953,636 ( 0.04%) -------------------------------------------------------------------------------- -- 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, . }; . 70,855 ( 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 { 20,032 ( 0.00%) match self { 14,196 ( 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 { 142,774 ( 0.00%) match self { . Self::Meta(_) => true, . Self::None | Self::Poison => false, . } . } . } . . #[derive(Copy, Clone, Hash, PartialEq, Eq, HashStable, Debug)] . pub struct MemPlace { . /// The pointer can be a pure integer, with the `None` tag. 177 ( 0.00%) pub ptr: Pointer>, 354 ( 0.00%) pub align: Align, . /// Metadata for unsized places. Interpretation is up to the type. . /// Must not be present for sized types, but can be missing for unsized types . /// (e.g., `extern type`). . pub meta: MemPlaceMeta, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(MemPlace, 48); -- line 68 ---------------------------------------- -- line 93 ---------------------------------------- . type Target = Place; . #[inline(always)] . fn deref(&self) -> &Place { . &self.place . } . } . . /// A MemPlace with its layout. Constructing it is only possible in this module. 1,239 ( 0.00%) #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)] . pub struct MPlaceTy<'tcx, Tag: Provenance = AllocId> { . mplace: MemPlace, . pub layout: TyAndLayout<'tcx>, . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(MPlaceTy<'_>, 64); . -- line 109 ---------------------------------------- -- 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 { 6,696 ( 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 { 13,710 ( 0.00%) match self.meta { 9,597 ( 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> { 1,536,326 ( 0.03%) Ok(MPlaceTy { mplace: self.mplace.offset(offset, meta, cx)?, layout }) . } . . #[inline] . pub fn from_aligned_ptr(ptr: Pointer>, layout: TyAndLayout<'tcx>) -> Self { 372 ( 0.00%) MPlaceTy { mplace: MemPlace::from_ptr(ptr, layout.align.abi), layout } . } . . #[inline] 2,918 ( 0.00%) pub(super) fn len(&self, cx: &impl HasDataLayout) -> InterpResult<'tcx, u64> { 18,770 ( 0.00%) if self.layout.is_unsized() { . // We need to consult `meta` metadata 29,314 ( 0.00%) match self.layout.ty.kind() { 10,012 ( 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!) 8 ( 0.00%) match self.layout.fields { 8 ( 0.00%) FieldsShape::Array { count, .. } => Ok(count), . _ => bug!("len not supported on sized type {:?}", self.layout.ty), . } . } 5,836 ( 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>> { 302,866 ( 0.01%) match **self { 131,790 ( 0.00%) Operand::Indirect(mplace) => Ok(MPlaceTy { mplace, layout: self.layout }), . Operand::Immediate(_) if self.layout.is_zst() => Ok(MPlaceTy::dangling(self.layout)), 981,568 ( 0.02%) 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`. 43,800 ( 0.00%) pub fn ref_to_mplace( . &self, . val: &ImmTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { . let pointee_type = 13,140 ( 0.00%) val.layout.ty.builtin_deref(true).expect("`ref_to_mplace` called on non-ptr type").ty; 13,140 ( 0.00%) let layout = self.layout_of(pointee_type)?; 21,900 ( 0.00%) let (ptr, meta) = match **val { 2,746 ( 0.00%) Immediate::Scalar(ptr) => (ptr, MemPlaceMeta::None), 21,049 ( 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. 4,380 ( 0.00%) align: layout.align.abi, . meta, . }; 74,460 ( 0.00%) Ok(MPlaceTy { mplace, layout }) 39,420 ( 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. 8,052 ( 0.00%) pub fn deref_operand( . &self, . src: &OpTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 2,196 ( 0.00%) let val = self.read_immediate(src)?; . trace!("deref to {} on {:?}", val.layout.ty, *val); 1,464 ( 0.00%) let mplace = self.ref_to_mplace(&val)?; 3,660 ( 0.00%) self.check_mplace_access(mplace, CheckInAllocMsg::DerefTest)?; 8,052 ( 0.00%) Ok(mplace) 6,588 ( 0.00%) } . . #[inline] . pub(super) fn get_alloc( . &self, . place: &MPlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, Option>> { . assert!(!place.layout.is_unsized()); 3,923 ( 0.00%) assert!(!place.meta.has_meta()); 3,923 ( 0.00%) let size = place.layout.size; 35,307 ( 0.00%) 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>> { 138,851 ( 0.00%) assert!(!place.layout.is_unsized()); 138,851 ( 0.00%) assert!(!place.meta.has_meta()); 138,851 ( 0.00%) let size = place.layout.size; 833,106 ( 0.02%) 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)? 732 ( 0.00%) .unwrap_or((mplace.layout.size, mplace.layout.align.abi)); 732 ( 0.00%) assert!(mplace.mplace.align <= align, "dynamic alignment less strict than static one?"); 732 ( 0.00%) let align = M::enforce_alignment(&self.memory.extra).then_some(align); 2,196 ( 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>> { 566,672 ( 0.01%) let offset = base.layout.fields.offset(field); 423,548 ( 0.01%) let field_layout = base.layout.field(self, field); . . // Offset may need adjustment for unsized fields. 710,342 ( 0.01%) 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 2,912 ( 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`. 29,180 ( 0.00%) pub(super) fn mplace_array_fields<'a>( . &self, . base: &'a MPlaceTy<'tcx, Tag>, . ) -> InterpResult<'tcx, impl Iterator>> + 'a> . { 11,672 ( 0.00%) let len = base.len(self)?; // also asserts that we have a type where this makes sense 8,754 ( 0.00%) let stride = match base.layout.fields { 2,918 ( 0.00%) FieldsShape::Array { stride, .. } => stride, . _ => span_bug!(self.cur_span(), "mplace_array_fields: expected an array layout"), . }; 5,836 ( 0.00%) let layout = base.layout.field(self, 0); 2,918 ( 0.00%) let dl = &self.tcx.data_layout; . // `Size` multiplication 849,686 ( 0.02%) Ok((0..len).map(move |i| base.offset(stride * i, MemPlaceMeta::None, layout, dl))) 26,262 ( 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 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. 1,387,560 ( 0.03%) 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. 138,756 ( 0.00%) let mplace = self.force_allocation(base)?; 1,665,072 ( 0.03%) Ok(self.mplace_field(&mplace, field)?.into()) 1,110,048 ( 0.02%) } . . 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 586 ---------------------------------------- . . /// 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::*; 21,900 ( 0.00%) Ok(match proj_elem { 3,640 ( 0.00%) Field(field, _) => self.place_field(base, field.index())?, . Downcast(_, variant) => self.place_downcast(base, variant)?, 5,856 ( 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`. 37,272 ( 0.00%) pub fn eval_place( . &mut self, . place: mir::Place<'tcx>, . ) -> InterpResult<'tcx, PlaceTy<'tcx, M::PointerTag>> { 23,295 ( 0.00%) 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)?, . }; . 2,920 ( 0.00%) for elem in place.projection.iter() { 1,460 ( 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, . )); 83,862 ( 0.00%) Ok(place_ty) 37,272 ( 0.00%) } . . /// Write an immediate to a place . #[inline(always)] . pub fn write_immediate( . &mut self, . src: Immediate, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 20,288 ( 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. 140,863 ( 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. 281,726 ( 0.01%) let mplace = match dest.place { 4,024 ( 0.00%) Place::Local { frame, local } => { . match M::access_local_mut(self, frame, local)? { . Ok(local) => { . // Local can be updated in-place. 20,120 ( 0.00%) *local = LocalValue::Live(Operand::Immediate(src)); . return Ok(()); . } . Err(mplace) => { . // The local is in memory, go on below. . mplace . } . } . } 833,106 ( 0.02%) Place::Ptr(mplace) => mplace, // already referring to memory . }; 1,249,659 ( 0.03%) let dest = MPlaceTy { mplace, layout: dest.layout }; . . // This is already in memory, write there. 1,527,361 ( 0.03%) self.write_immediate_to_mplace_no_validate(src, &dest) 281,726 ( 0.01%) } . . /// Write an immediate to memory. . /// If you use this you are responsible for validating that things got copied at the . /// right type. 1,388,510 ( 0.03%) 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 138,851 ( 0.00%) let tcx = *self.tcx; 277,702 ( 0.01%) let mut alloc = match self.get_alloc_mut(dest)? { 694,255 ( 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! 277,702 ( 0.01%) match value { . Immediate::Scalar(scalar) => { 276,424 ( 0.01%) match dest.layout.abi { . Abi::Scalar(_) => {} // fine . _ => span_bug!( . self.cur_span(), . "write_immediate_to_mplace: invalid Scalar layout: {:#?}", . dest.layout . ), . } 1,243,908 ( 0.03%) 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. 1,278 ( 0.00%) let (a, b) = match dest.layout.abi { 1,917 ( 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. . 6,390 ( 0.00%) alloc.write_scalar(alloc_range(Size::ZERO, a_size), a_val)?; 5,112 ( 0.00%) alloc.write_scalar(alloc_range(b_offset, b_size), b_val) . } . } 1,110,808 ( 0.02%) } . . /// 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> { 833,947 ( 0.02%) 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. 1,112,280 ( 0.02%) 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. 2,502,630 ( 0.05%) 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. 695,175 ( 0.01%) let src = match self.try_read_immediate(src)? { . Ok(src_val) => { 138,944 ( 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`. 1,806,272 ( 0.04%) return self.write_immediate_no_validate(*src_val, dest); . } 728 ( 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! 1,183 ( 0.00%) let (dest, size) = self.force_allocation_maybe_sized(dest, src.meta)?; . let size = size.unwrap_or_else(|| { 273 ( 0.00%) assert!( . !dest.layout.is_unsized(), . "Cannot copy into already initialized unsized place" . ); 91 ( 0.00%) dest.layout.size . }); 91 ( 0.00%) assert_eq!(src.meta, dest.meta, "Can only copy between equally-sized instances"); . 91 ( 0.00%) self.memory 273 ( 0.00%) .copy(src.ptr, src.align, dest.ptr, dest.align, size, /*nonoverlapping*/ true) 1,112,280 ( 0.02%) } . . /// Copies the data from an operand to a place. The layouts may disagree, but they must . /// have the same size. 1,488 ( 0.00%) pub fn copy_op_transmute( . &mut self, . src: &OpTy<'tcx, M::PointerTag>, . dest: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx> { 3,348 ( 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. 1,261,962 ( 0.03%) pub fn force_allocation_maybe_sized( . &mut self, . place: &PlaceTy<'tcx, M::PointerTag>, . meta: MemPlaceMeta, . ) -> InterpResult<'tcx, (MPlaceTy<'tcx, M::PointerTag>, Option)> { 1,402,180 ( 0.03%) let (mplace, size) = match place.place { 139,395 ( 0.00%) Place::Local { frame, local } => { 278,790 ( 0.01%) match M::access_local_mut(self, frame, local)? { 6,570 ( 0.00%) 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 = 3,650 ( 0.00%) self.layout_of_local(&self.stack()[frame], local, None)?; . // We also need to support unsized types, and hence cannot use `allocate`. 2,920 ( 0.00%) let (size, align) = self . .size_and_align_of(&meta, &local_layout)? . .expect("Cannot allocate for non-dyn-sized type"); 5,110 ( 0.00%) let ptr = self.memory.allocate(size, align, MemoryKind::Stack)?; . let mplace = MemPlace { ptr: ptr.into(), align, meta }; 3,650 ( 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. 13,870 ( 0.00%) *M::access_local_mut(self, frame, local).unwrap().unwrap() = . LocalValue::Live(Operand::Indirect(mplace)); 5,110 ( 0.00%) (mplace, Some(size)) . } 1,386,650 ( 0.03%) Err(mplace) => (mplace, None), // this already was an indirect local . } . } 10,699 ( 0.00%) Place::Ptr(mplace) => (mplace, None), . }; . // Return with the original layout, so that the caller can go on 1,682,616 ( 0.03%) Ok((MPlaceTy { mplace, layout: place.layout }, size)) 1,121,744 ( 0.02%) } . . #[inline(always)] . pub fn force_allocation( . &mut self, . place: &PlaceTy<'tcx, M::PointerTag>, . ) -> InterpResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> { 1,257,030 ( 0.03%) 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>> { 1,302 ( 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 1084 ---------------------------------------- . self.write_immediate(*tag_val, &niche_dest)?; . } . } . } . . Ok(()) . } . 1,674 ( 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` 558 ( 0.00%) let _ = self.tcx.global_alloc(raw.alloc_id); . let ptr = self.global_base_pointer(Pointer::from(raw.alloc_id))?; 558 ( 0.00%) let layout = self.layout_of(raw.ty)?; 1,116 ( 0.00%) Ok(MPlaceTy::from_aligned_ptr(ptr.into(), layout)) 1,302 ( 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 ---------------------------------------- 1,458,307 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/bitmask.rs -------------------------------------------------------------------------------- Ir -- line 17 ---------------------------------------- . pub struct BitMask(pub BitMaskWord); . . #[allow(clippy::use_self)] . impl BitMask { . /// Returns a new `BitMask` with all bits inverted. . #[inline] . #[must_use] . pub fn invert(self) -> Self { 505,872 ( 0.01%) BitMask(self.0 ^ BITMASK_MASK) . } . . /// Flip the bit in the mask for the entry at the given index. . /// . /// Returns the bit's previous state. . #[inline] . #[allow(clippy::cast_ptr_alignment)] . #[cfg(feature = "raw")] -- line 33 ---------------------------------------- -- line 38 ---------------------------------------- . // The bit was set if the bit is now 0. . self.0 & mask == 0 . } . . /// Returns a new `BitMask` with the lowest bit removed. . #[inline] . #[must_use] . pub fn remove_lowest_bit(self) -> Self { 345,833 ( 0.01%) BitMask(self.0 & (self.0 - 1)) . } . /// Returns whether the `BitMask` has at least one set bit. . #[inline] . pub fn any_bit_set(self) -> bool { 3,569,085 ( 0.07%) self.0 != 0 . } . . /// Returns the first set bit in the `BitMask`, if there is one. . #[inline] . pub fn lowest_set_bit(self) -> Option { 41,567,116 ( 0.85%) if self.0 == 0 { . None . } else { . Some(unsafe { self.lowest_set_bit_nonzero() }) . } . } . . /// Returns the first set bit in the `BitMask`, if there is one. The . /// bitmask must not be empty. . #[inline] . #[cfg(feature = "nightly")] . pub unsafe fn lowest_set_bit_nonzero(self) -> usize { 22,135 ( 0.00%) intrinsics::cttz_nonzero(self.0) as usize / BITMASK_STRIDE . } . #[inline] . #[cfg(not(feature = "nightly"))] . pub unsafe fn lowest_set_bit_nonzero(self) -> usize { . self.trailing_zeros() . } . . /// Returns the number of trailing zeroes in the `BitMask`. -- line 77 ---------------------------------------- -- line 110 ---------------------------------------- . /// bits. . pub struct BitMaskIter(BitMask); . . impl Iterator for BitMaskIter { . type Item = usize; . . #[inline] . fn next(&mut self) -> Option { 6,878,197 ( 0.14%) let bit = self.0.lowest_set_bit()?; . self.0 = self.0.remove_lowest_bit(); . Some(bit) . } . } 53,922 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/levels.rs -------------------------------------------------------------------------------- Ir -- line 20 ---------------------------------------- . Level, Lint, LintId, . }; . use rustc_session::parse::feature_err; . use rustc_session::Session; . use rustc_span::symbol::{sym, Symbol}; . use rustc_span::{source_map::MultiSpan, Span, DUMMY_SP}; . use tracing::debug; . 9 ( 0.00%) fn lint_levels(tcx: TyCtxt<'_>, (): ()) -> LintLevelMap { . let store = unerased_lint_store(tcx); . let levels = 6 ( 0.00%) LintLevelsBuilder::new(tcx.sess, false, &store, &tcx.resolutions(()).registered_tools); 13 ( 0.00%) let mut builder = LintLevelMapBuilder { levels, tcx }; 3 ( 0.00%) let krate = tcx.hir().krate(); . 2 ( 0.00%) builder.levels.id_to_set.reserve(krate.owners.len() + 1); . 8 ( 0.00%) let push = builder.levels.push(tcx.hir().attrs(hir::CRATE_HIR_ID), true); . builder.levels.register_id(hir::CRATE_HIR_ID); . tcx.hir().walk_toplevel_module(&mut builder); . builder.levels.pop(push); . 16 ( 0.00%) builder.levels.build_map() 9 ( 0.00%) } . . pub struct LintLevelsBuilder<'s> { . sess: &'s Session, . sets: LintLevelSets, . id_to_set: FxHashMap, . cur: LintStackIndex, . warn_about_weird_lints: bool, . store: &'s LintStore, -- line 51 ---------------------------------------- -- line 53 ---------------------------------------- . } . . pub struct BuilderPush { . prev: LintStackIndex, . pub changed: bool, . } . . impl<'s> LintLevelsBuilder<'s> { 273 ( 0.00%) pub fn new( . sess: &'s Session, . warn_about_weird_lints: bool, . store: &'s LintStore, . registered_tools: &'s RegisteredTools, . ) -> Self { 231 ( 0.00%) let mut builder = LintLevelsBuilder { . sess, 21 ( 0.00%) sets: LintLevelSets::new(), . cur: COMMAND_LINE, . id_to_set: Default::default(), . warn_about_weird_lints, . store, . registered_tools, . }; . builder.process_command_line(sess, store); 63 ( 0.00%) assert_eq!(builder.sets.list.len(), 1); . builder 189 ( 0.00%) } . . pub(crate) fn sess(&self) -> &Session { 8,446 ( 0.00%) self.sess . } . . pub(crate) fn lint_store(&self) -> &LintStore { . self.store . } . . fn process_command_line(&mut self, sess: &Session, store: &LintStore) { . let mut specs = FxHashMap::default(); 42 ( 0.00%) self.sets.lint_cap = sess.opts.lint_cap.unwrap_or(Level::Forbid); . 42 ( 0.00%) for &(ref lint_name, level) in &sess.opts.lint_opts { 210 ( 0.00%) store.check_lint_name_cmdline(sess, &lint_name, level, self.registered_tools); . let orig_level = level; 84 ( 0.00%) let lint_flag_val = Symbol::intern(lint_name); . 210 ( 0.00%) let ids = match store.find_lints(&lint_name) { 168 ( 0.00%) Ok(ids) => ids, . Err(_) => continue, // errors handled in check_lint_name_cmdline above . }; 126 ( 0.00%) for id in ids { . // ForceWarn and Forbid cannot be overriden . if let Some((Level::ForceWarn | Level::Forbid, _)) = specs.get(&id) { . continue; . } . 168 ( 0.00%) self.check_gated_lint(id, DUMMY_SP); . let src = LintLevelSource::CommandLine(lint_flag_val, orig_level); 84 ( 0.00%) specs.insert(id, (level, src)); . } . } . 168 ( 0.00%) self.cur = self.sets.list.push(LintSet { specs, parent: COMMAND_LINE }); . } . . /// Attempts to insert the `id` to `level_src` map entry. If unsuccessful . /// (e.g. if a forbid was already inserted on the same scope), then emits a . /// diagnostic with no change to `specs`. 2,783 ( 0.00%) fn insert_spec( . &mut self, . specs: &mut FxHashMap, . id: LintId, 1,518 ( 0.00%) (level, src): LevelAndSource, . ) { 1,265 ( 0.00%) let (old_level, old_src) = 1,771 ( 0.00%) self.sets.get_lint_level(id.lint, self.cur, Some(&specs), &self.sess); . // Setting to a non-forbid level is an error if the lint previously had . // a forbid level. Note that this is not necessarily true even with a . // `#[forbid(..)]` attribute present, as that is overriden by `--cap-lints`. . // . // This means that this only errors if we're truly lowering the lint . // level from forbid. 253 ( 0.00%) if level != Level::Forbid { 1,012 ( 0.00%) if let Level::Forbid = old_level { . // Backwards compatibility check: . // . // We used to not consider `forbid(lint_group)` . // as preventing `allow(lint)` for some lint `lint` in . // `lint_group`. For now, issue a future-compatibility . // warning for this case. . let id_name = id.lint.name_lower(); . let fcw_warning = match old_src { -- line 143 ---------------------------------------- -- line 202 ---------------------------------------- . if !fcw_warning { . return; . } . } . } . if let Level::ForceWarn = old_level { . specs.insert(id, (old_level, old_src)); . } else { 1,012 ( 0.00%) specs.insert(id, (level, src)); . } 2,024 ( 0.00%) } . . /// Pushes a list of AST lint attributes onto this context. . /// . /// This function will return a `BuilderPush` object which should be passed . /// to `pop` when this scope for the attributes provided is exited. . /// . /// This function will perform a number of tasks: . /// . /// * It'll validate all lint-related attributes in `attrs` . /// * It'll mark all lint-related attributes as used . /// * Lint levels will be updated based on the attributes provided . /// * Lint attributes are validated, e.g., a `#[forbid]` can't be switched to . /// `#[allow]` . /// . /// Don't forget to call `pop`! 3,528,960 ( 0.07%) pub(crate) fn push(&mut self, attrs: &[ast::Attribute], is_crate_node: bool) -> BuilderPush { . let mut specs = FxHashMap::default(); 882,240 ( 0.02%) let sess = self.sess; 441,120 ( 0.01%) let bad_attr = |span| struct_span_err!(sess, span, E0452, "malformed lint attribute input"); . for attr in attrs { 35,742 ( 0.00%) let Some(level) = Level::from_symbol(attr.name_or_empty()) else { . continue . }; . 1,359 ( 0.00%) let Some(mut metas) = attr.meta_item_list() else { . continue . }; . 151 ( 0.00%) if metas.is_empty() { . // FIXME (#55112): issue unused-attributes lint for `#[level()]` . continue; . } . . // Before processing the lint names, look for a reason (RFC 2383) . // at the end. . let mut reason = None; 151 ( 0.00%) let tail_li = &metas[metas.len() - 1]; 453 ( 0.00%) if let Some(item) = tail_li.meta_item() { 755 ( 0.00%) match item.kind { . ast::MetaItemKind::Word => {} // actual lint names handled later . ast::MetaItemKind::NameValue(ref name_value) => { . if item.path == sym::reason { . // FIXME (#55112): issue unused-attributes lint if we thereby . // don't have any lint names (`#[level(reason = "foo")]`) . if let ast::LitKind::Str(rationale, _) = name_value.kind { . if !self.sess.features_untracked().lint_reasons { . feature_err( -- line 259 ---------------------------------------- -- line 279 ---------------------------------------- . } . } . ast::MetaItemKind::List(_) => { . bad_attr(item.span).span_label(item.span, "bad attribute argument").emit(); . } . } . } . 3,322 ( 0.00%) for li in metas { 604 ( 0.00%) let sp = li.span(); 302 ( 0.00%) let mut meta_item = match li { 2,718 ( 0.00%) ast::NestedMetaItem::MetaItem(meta_item) if meta_item.is_word() => meta_item, . _ => { . let mut err = bad_attr(sp); . let mut add_label = true; . if let Some(item) = li.meta_item() { . if let ast::MetaItemKind::NameValue(_) = item.kind { . if item.path == sym::reason { . err.span_label(sp, "reason in lint attribute must come last"); . add_label = false; -- line 298 ---------------------------------------- -- line 301 ---------------------------------------- . } . if add_label { . err.span_label(sp, "bad attribute argument"); . } . err.emit(); . continue; . } . }; 453 ( 0.00%) let tool_ident = if meta_item.path.segments.len() > 1 { 72 ( 0.00%) Some(meta_item.path.segments.remove(0).ident) . } else { 133 ( 0.00%) None . }; 151 ( 0.00%) let tool_name = tool_ident.map(|ident| ident.name); 453 ( 0.00%) let name = pprust::path_to_string(&meta_item.path); . let lint_result = 755 ( 0.00%) self.store.check_lint_name(&name, tool_name, self.registered_tools); 525 ( 0.00%) match &lint_result { . CheckLintNameResult::Ok(ids) => { . let src = LintLevelSource::Node( . meta_item.path.segments.last().expect("empty lint name").ident.name, . sp, . reason, . ); 639 ( 0.00%) for &id in *ids { 1,265 ( 0.00%) self.check_gated_lint(id, attr.span); 3,036 ( 0.00%) self.insert_spec(&mut specs, id, (level, src)); . } . } . . CheckLintNameResult::Tool(result) => { 90 ( 0.00%) match *result { . Ok(ids) => { . let complete_name = . &format!("{}::{}", tool_ident.unwrap().name, name); . let src = LintLevelSource::Node( . Symbol::intern(complete_name), . sp, . reason, . ); -- line 340 ---------------------------------------- -- line 454 ---------------------------------------- . } . db.emit(); . }); . } . } . // If this lint was renamed, apply the new lint instead of ignoring the attribute. . // This happens outside of the match because the new lint should be applied even if . // we don't warn about the name change. 755 ( 0.00%) if let CheckLintNameResult::Warning(_, Some(new_name)) = lint_result { . // Ignore any errors or warnings that happen because the new name is inaccurate . // NOTE: `new_name` already includes the tool name, so we don't have to add it again. . if let CheckLintNameResult::Ok(ids) = . self.store.check_lint_name(&new_name, None, self.registered_tools) . { . let src = LintLevelSource::Node(Symbol::intern(&new_name), sp, reason); . for &id in ids { . self.check_gated_lint(id, attr.span); . self.insert_spec(&mut specs, id, (level, src)); . } . } else { . panic!("renamed lint does not exist: {}", new_name); . } . } 604 ( 0.00%) } . } . 882,240 ( 0.02%) if !is_crate_node { 500 ( 0.00%) for (id, &(level, ref src)) in specs.iter() { 750 ( 0.00%) if !id.lint.crate_level_only { . continue; . } . . let LintLevelSource::Node(lint_attr_name, lint_attr_span, _) = *src else { . continue . }; . . let lint = builtin::UNUSED_ATTRIBUTES; -- line 490 ---------------------------------------- -- line 505 ---------------------------------------- . db.emit(); . }, . ); . // don't set a separate error for every lint in the group . break; . } . } . 441,120 ( 0.01%) let prev = self.cur; 441,120 ( 0.01%) if !specs.is_empty() { 798 ( 0.00%) self.cur = self.sets.list.push(LintSet { specs, parent: prev }); . } . . BuilderPush { prev, changed: prev != self.cur } 3,970,080 ( 0.08%) } . . /// Checks if the lint is gated on a feature that is not enabled. 2,065 ( 0.00%) fn check_gated_lint(&self, lint_id: LintId, span: Span) { 885 ( 0.00%) if let Some(feature) = lint_id.lint.feature_gate { . if !self.sess.features_untracked().enabled(feature) { . feature_err( . &self.sess.parse_sess, . feature, . span, . &format!("the `{}` lint is unstable", lint_id.lint.name_lower()), . ) . .emit(); . } . } 2,360 ( 0.00%) } . . /// Called after `push` when the scope of a set of attributes are exited. . pub fn pop(&mut self, push: BuilderPush) { 579,011 ( 0.01%) self.cur = push.prev; 293,896 ( 0.01%) } . . /// Find the lint level for a lint. 130 ( 0.00%) pub fn lint_level(&self, lint: &'static Lint) -> (Level, LintLevelSource) { 541 ( 0.00%) self.sets.get_lint_level(lint, self.cur, None, self.sess) 195 ( 0.00%) } . . /// Used to emit a lint-related diagnostic based on the current state of . /// this lint context. 763 ( 0.00%) pub fn struct_lint( . &self, . lint: &'static Lint, . span: Option, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { 592 ( 0.00%) let (level, src) = self.lint_level(lint); 82 ( 0.00%) struct_lint_level(self.sess, lint, level, src, span, decorate) 487 ( 0.00%) } . . /// Registers the ID provided with the current set of lints stored in . /// this context. . pub fn register_id(&mut self, id: HirId) { 128 ( 0.00%) self.id_to_set.insert(id, self.cur); . } . . pub fn build_map(self) -> LintLevelMap { 8 ( 0.00%) LintLevelMap { sets: self.sets, id_to_set: self.id_to_set } . } . } . . struct LintLevelMapBuilder<'tcx> { . levels: LintLevelsBuilder<'tcx>, . tcx: TyCtxt<'tcx>, . } . . impl LintLevelMapBuilder<'_> { . fn with_lint_attrs(&mut self, id: hir::HirId, f: F) . where . F: FnOnce(&mut Self), . { . let is_crate_hir = id == hir::CRATE_HIR_ID; 870,048 ( 0.02%) let attrs = self.tcx.hir().attrs(id); 870,738 ( 0.02%) let push = self.levels.push(attrs, is_crate_hir); 145,180 ( 0.00%) if push.changed { . self.levels.register_id(id); . } . f(self); . self.levels.pop(push); . } . } . . impl<'tcx> intravisit::Visitor<'tcx> for LintLevelMapBuilder<'tcx> { . type NestedFilter = nested_filter::All; . . fn nested_visit_map(&mut self) -> Self::Map { 1,091 ( 0.00%) self.tcx.hir() . } . . fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { 884 ( 0.00%) self.with_lint_attrs(param.hir_id, |builder| { . intravisit::walk_param(builder, param); . }); . } . . fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) { 492 ( 0.00%) self.with_lint_attrs(it.hir_id(), |builder| { 1,476 ( 0.00%) intravisit::walk_item(builder, it); . }); . } . . fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) { . self.with_lint_attrs(it.hir_id(), |builder| { . intravisit::walk_foreign_item(builder, it); . }) . } . . fn visit_stmt(&mut self, e: &'tcx hir::Stmt<'tcx>) { . // We will call `with_lint_attrs` when we walk . // the `StmtKind`. The outer statement itself doesn't . // define the lint levels. 1,314 ( 0.00%) intravisit::walk_stmt(self, e); . } . 756 ( 0.00%) fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { 286,966 ( 0.01%) self.with_lint_attrs(e.hir_id, |builder| { 570,516 ( 0.01%) intravisit::walk_expr(builder, e); . }) 672 ( 0.00%) } . . fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) { 186 ( 0.00%) self.with_lint_attrs(s.hir_id, |builder| { . intravisit::walk_field_def(builder, s); . }) . } . . fn visit_variant( . &mut self, . v: &'tcx hir::Variant<'tcx>, . g: &'tcx hir::Generics<'tcx>, . item_id: hir::HirId, . ) { 44 ( 0.00%) self.with_lint_attrs(v.id, |builder| { . intravisit::walk_variant(builder, v, g, item_id); . }) . } . . fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { 444 ( 0.00%) self.with_lint_attrs(l.hir_id, |builder| { 888 ( 0.00%) intravisit::walk_local(builder, l); . }) . } . . fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) { 414 ( 0.00%) self.with_lint_attrs(a.hir_id, |builder| { 828 ( 0.00%) intravisit::walk_arm(builder, a); . }) . } . . fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { 1 ( 0.00%) self.with_lint_attrs(trait_item.hir_id(), |builder| { 3 ( 0.00%) intravisit::walk_trait_item(builder, trait_item); . }); . } . . fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { 197 ( 0.00%) self.with_lint_attrs(impl_item.hir_id(), |builder| { 591 ( 0.00%) intravisit::walk_impl_item(builder, impl_item); . }); . } . } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) providers.lint_levels = lint_levels; . } 444,931 ( 0.01%) -------------------------------------------------------------------------------- -- 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. . /// 461,624 ( 0.01%) #[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 { 7,114 ( 0.00%) base_or_index: u32, 2,128 ( 0.00%) len_or_tag: u16, 3,304 ( 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 { 560,415 ( 0.01%) if lo > hi { . std::mem::swap(&mut lo, &mut hi); . } . 1,120,758 ( 0.02%) let (base, len, ctxt2) = (lo.0, hi.0 - lo.0, ctxt.as_u32()); . 3,544,837 ( 0.07%) 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 = 260 ( 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,420,418 ( 0.03%) } . . #[inline] . pub fn data(self) -> SpanData { . let data = self.data_untracked(); 12 ( 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 { 8,078,438 ( 0.17%) 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), 7,572,030 ( 0.16%) hi: BytePos(self.base_or_index + self.len_or_tag as u32), . ctxt: SyntaxContext::from_u32(self.ctxt_or_zero as u32), . parent: None, . } . } else { . // Interned format. . debug_assert!(self.ctxt_or_zero == 0); 16 ( 0.00%) let index = self.base_or_index; 85 ( 0.00%) with_span_interner(|interner| interner.spans[index as usize]) . } 3,089,545 ( 0.06%) } . } . 4 ( 0.00%) #[derive(Default)] . pub struct SpanInterner { . spans: FxIndexSet, . } . . impl SpanInterner { 63 ( 0.00%) fn intern(&mut self, span_data: &SpanData) -> u32 { 84 ( 0.00%) let (index, _) = self.spans.insert_full(*span_data); . index as u32 84 ( 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())) . } 4,980,140 ( 0.10%) -------------------------------------------------------------------------------- -- 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)] 4,028,666 ( 0.08%) pub fn rustc_entry(&mut self, key: K) -> RustcEntry<'_, K, V, A> { . let hash = make_insert_hash(&self.hash_builder, &key); 891 ( 0.00%) if let Some(elem) = self.table.find(hash, |q| q.0.eq(&key)) { 925,272 ( 0.02%) RustcEntry::Occupied(RustcOccupiedEntry { 57,454 ( 0.00%) key: Some(key), . elem, . table: &mut self.table, . }) . } else { . // Ideally we would put this in VacantEntry::insert, but Entry is not . // generic over the BuildHasher and adding a generic parameter would be . // a breaking change. . self.reserve(1); . 318,522 ( 0.01%) RustcEntry::Vacant(RustcVacantEntry { . hash, 95,941 ( 0.00%) key, . table: &mut self.table, . }) . } 3,211,529 ( 0.07%) } . } . . /// A view into a single entry in a map, which may either be vacant or occupied. . /// . /// This `enum` is constructed from the [`entry`] method on [`HashMap`]. . /// . /// [`HashMap`]: struct.HashMap.html . /// [`entry`]: struct.HashMap.html#method.rustc_entry -- line 62 ---------------------------------------- -- line 405 ---------------------------------------- . /// if let RustcEntry::Occupied(o) = map.rustc_entry("poneyland") { . /// *o.into_mut() += 10; . /// } . /// . /// assert_eq!(map["poneyland"], 22); . /// ``` . #[cfg_attr(feature = "inline-more", inline)] . pub fn into_mut(self) -> &'a mut V { 7,031 ( 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)] 14,571 ( 0.00%) pub fn insert(self, value: V) -> &'a mut V { . unsafe { 58,794 ( 0.00%) let bucket = self.table.insert_no_grow(self.hash, (self.key, value)); 6,002 ( 0.00%) &mut bucket.as_mut().1 . } 20,126 ( 0.00%) } . . /// Sets the value of the entry with the RustcVacantEntry's key, . /// and returns a RustcOccupiedEntry. . /// . /// # Examples . /// . /// ``` . /// use hashbrown::HashMap; -- line 589 ---------------------------------------- 1,123,092 ( 0.02%) -------------------------------------------------------------------------------- -- 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,471 ( 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 { 2,418 ( 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] 6,624 ( 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`. 2,208 ( 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. 1,656 ( 0.00%) Ok(M::tag_alloc_base_pointer(self, Pointer::new(alloc_id, offset))) 4,416 ( 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() . } . 8,244 ( 0.00%) pub fn allocate( . &mut self, . size: Size, . align: Align, . kind: MemoryKind, . ) -> InterpResult<'static, Pointer> { 3,664 ( 0.00%) let alloc = Allocation::uninit(size, align, M::PANIC_ON_ALLOC_FAIL)?; 8,244 ( 0.00%) Ok(self.allocate_with(alloc, kind)) 6,412 ( 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 { 1,832 ( 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)); 21,984 ( 0.00%) 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) = 556,132 ( 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> { 28,460 ( 0.00%) self.check_and_deref_ptr(ptr, size, Some(align), msg, |alloc_id, _, _| { 13,864 ( 0.00%) let check = match msg { . CheckInAllocMsg::DerefTest | CheckInAllocMsg::MemoryAccessTest => { . AllocCheck::Dereferenceable . } . CheckInAllocMsg::PointerArithmeticTest | CheckInAllocMsg::InboundsTest => { . AllocCheck::Live . } . }; 6,932 ( 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. 48,524 ( 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> { 6,932 ( 0.00%) fn check_offset_align(offset: u64, align: Align) -> InterpResult<'static> { 17,330 ( 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, . }) . } 10,398 ( 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. 311,440 ( 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. 6,932 ( 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. 6,932 ( 0.00%) if alloc_align.bytes() < align.bytes() { . throw_ub!(AlignmentCheckFailed { has: alloc_align, required: align }); . } 17,330 ( 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) } . } . }) 51,990 ( 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`. 68,178 ( 0.00%) fn get_global_alloc( . &self, . id: AllocId, . is_write: bool, . ) -> InterpResult<'tcx, Cow<'tcx, Allocation>> { 55,782 ( 0.00%) let (alloc, def_id) = match self.tcx.get_global_alloc(id) { 6,198 ( 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)) . } . }; 49,584 ( 0.00%) 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), . ); 24,792 ( 0.00%) Ok(alloc) 49,584 ( 0.00%) } . . /// Gives raw access to the `Allocation`, without bounds or alignment checks. . /// The caller is responsible for calling the access hooks! 25,520 ( 0.00%) 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, || { 24,792 ( 0.00%) let alloc = self.get_global_alloc(id, /*is_write*/ false).map_err(Err)?; 12,396 ( 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 364 ( 0.00%) match a { . Ok(a) => Ok(&a.1), . Err(a) => a, . } 19,140 ( 0.00%) } . . /// "Safe" (bounds and align-checked) allocation access. 75,468 ( 0.00%) 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| { 25,156 ( 0.00%) let alloc = self.get_raw(alloc_id)?; . Ok((alloc.size(), alloc.align, (alloc_id, offset, ptr, alloc))) . }, . )?; 12,578 ( 0.00%) 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)?; 41,251 ( 0.00%) 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`. 1,188 ( 0.00%) Ok(None) . } 56,601 ( 0.00%) } . . /// 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. 1,111,536 ( 0.02%) 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`.) 138,942 ( 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())); . } . 138,942 ( 0.00%) let (_kind, alloc) = self.alloc_map.get_mut(id).unwrap(); 138,942 ( 0.00%) if alloc.mutability == Mutability::Not { . throw_ub!(WriteToReadOnly(id)) . } 555,768 ( 0.01%) Ok((alloc, &mut self.extra)) 694,710 ( 0.01%) } . . /// "Safe" (bounds and align-checked) allocation access. 1,666,212 ( 0.03%) 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)?; 277,702 ( 0.01%) 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`. 416,553 ( 0.01%) 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)?; 833,106 ( 0.02%) Ok(Some(AllocRefMut { alloc, range, tcx, alloc_id })) . } else { . Ok(None) . } 1,249,659 ( 0.03%) } . . /// 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`. 1,567,489 ( 0.03%) 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 712,495 ( 0.01%) if let Some((_, alloc)) = self.alloc_map.get(id) { 139,579 ( 0.00%) return Ok((alloc.size(), alloc.align)); . } . . // # Function pointers . // (both global from `alloc_map` and local from `extra_fn_ptr_map`) 11,680 ( 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. 32,120 ( 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)) . } 2,920 ( 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. 5,840 ( 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)) . } . } . } 1,139,992 ( 0.02%) } . 11,680 ( 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 { 14,600 ( 0.00%) match self.tcx.get_global_alloc(id) { . Some(GlobalAlloc::Function(instance)) => Some(FnVal::Instance(instance)), 2,920 ( 0.00%) _ => None, . } . } 11,680 ( 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> { 1,255,410 ( 0.03%) pub fn write_scalar( . &mut self, . range: AllocRange, . val: ScalarMaybeUninit, . ) -> InterpResult<'tcx> { 697,450 ( 0.01%) Ok(self . .alloc 1,534,390 ( 0.03%) .write_scalar(&self.tcx, self.range.subrange(range), val) . .map_err(|e| e.to_interp_error(self.alloc_id))?) 836,940 ( 0.02%) } . . 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> { 24,056 ( 0.00%) pub fn read_scalar(&self, range: AllocRange) -> InterpResult<'tcx, ScalarMaybeUninit> { 66,208 ( 0.00%) Ok(self . .alloc 44,041 ( 0.00%) .read_scalar(&self.tcx, self.range.subrange(range)) . .map_err(|e| e.to_interp_error(self.alloc_id))?) 24,056 ( 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)) . } . 19,668 ( 0.00%) pub fn check_bytes(&self, range: AllocRange, allow_uninit_and_ptr: bool) -> InterpResult<'tcx> { 1,788 ( 0.00%) Ok(self . .alloc 12,516 ( 0.00%) .check_bytes(&self.tcx, self.range.subrange(range), allow_uninit_and_ptr) . .map_err(|e| e.to_interp_error(self.alloc_id))?) 14,304 ( 0.00%) } . } . . 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. 728 ( 0.00%) pub fn read_bytes( . &self, . ptr: Pointer>, . size: Size, . ) -> InterpResult<'tcx, &[u8]> { 546 ( 0.00%) let alloc_ref = match self.get(ptr, size, Align::ONE)? { 1,092 ( 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.) 364 ( 0.00%) Ok(alloc_ref . .alloc 546 ( 0.00%) .get_bytes(&alloc_ref.tcx, alloc_ref.range) . .map_err(|e| e.to_interp_error(alloc_ref.alloc_id))?) 728 ( 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> { 455 ( 0.00%) self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping) . } . 1,183 ( 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> { 182 ( 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. 182 ( 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, . }; 364 ( 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. 182 ( 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 = 1,092 ( 0.00%) src_alloc.prepare_relocation_copy(self, src_range, dest_offset, num_copies); . // Prepare a copy of the initialization mask. 364 ( 0.00%) let compressed = src_alloc.compress_uninit_range(src_range); . . // Destination alloc preparations and access hooks. 273 ( 0.00%) let (dest_alloc, extra) = self.get_raw_mut(dest_alloc_id)?; 273 ( 0.00%) let dest_range = alloc_range(dest_offset, size * num_copies); . M::memory_written(extra, &mut dest_alloc.extra, dest.provenance, dest_range)?; 364 ( 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(); . 273 ( 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 { 91 ( 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, 273 ( 0.00%) dest_bytes.add((size * i).bytes_usize()), // `Size` multiplication . size.bytes_usize(), . ); . } . } . } . . // now fill in all the "init" data 455 ( 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 819 ( 0.00%) dest_alloc.mark_relocation_range(relocations); . . Ok(()) 819 ( 0.00%) } . } . . /// Machine pointer introspection. . impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> Memory<'mir, 'tcx, M> { 4,380 ( 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. 21,900 ( 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 . } . } 8,760 ( 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 ---------------------------------------- 1,048,519 ( 0.02%) -------------------------------------------------------------------------------- -- 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. 384 ( 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. 384 ( 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 }, . } 768 ( 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> { 1,421,305 ( 0.03%) fn new() -> InferCtxtInner<'tcx> { 9,664,874 ( 0.20%) 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(), 852,783 ( 0.02%) region_constraint_storage: Some(RegionConstraintStorage::new()), . region_obligations: vec![], . opaque_types: Default::default(), . opaque_types_vars: Default::default(), . } 1,705,566 ( 0.03%) } . . #[inline] . pub fn region_obligations(&self) -> &[(hir::HirId, RegionObligation<'tcx>)] { . &self.region_obligations . } . . #[inline] . pub fn projection_cache(&mut self) -> traits::ProjectionCache<'_, 'tcx> { 1,738 ( 0.00%) self.projection_cache.with_log(&mut self.undo_log) . } . . #[inline] . fn type_variables(&mut self) -> type_variable::TypeVariableTable<'_, 'tcx> { 218,557 ( 0.00%) self.type_variable_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn int_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::IntVid, . &mut ut::UnificationStorage, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 5,335 ( 0.00%) self.int_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . fn float_unification_table( . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::FloatVid, -- line 258 ---------------------------------------- -- line 268 ---------------------------------------- . &mut self, . ) -> ut::UnificationTable< . ut::InPlace< . ty::ConstVid<'tcx>, . &mut ut::UnificationStorage>, . &mut InferCtxtUndoLogs<'tcx>, . >, . > { 1,142 ( 0.00%) self.const_unification_storage.with_log(&mut self.undo_log) . } . . #[inline] . pub fn unwrap_region_constraints(&mut self) -> RegionConstraintCollector<'_, 'tcx> { 70,006 ( 0.00%) self.region_constraint_storage . .as_mut() . .expect("region constraints already solved") 86,222 ( 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. 118,768 ( 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 116,489 ( 0.00%) #[derive(Clone, Debug)] . pub enum SubregionOrigin<'tcx> { . /// Arose from a subtyping relation 5,984 ( 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. 1,666 ( 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 1,383 ( 0.00%) DataBorrowed(Ty<'tcx>, Span), . . /// (&'a &'b T) where a >= b 1,256 ( 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> { 284,261 ( 0.01%) fn infer_ctxt(self) -> InferCtxtBuilder<'tcx> { 852,783 ( 0.02%) InferCtxtBuilder { tcx: self, defining_use_anchor: None, fresh_typeck_results: None } 284,261 ( 0.01%) } . } . . 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. 8,280 ( 0.00%) pub fn with_fresh_in_progress_typeck_results(mut self, table_owner: LocalDefId) -> Self { 10,120 ( 0.00%) self.fresh_typeck_results = Some(RefCell::new(ty::TypeckResults::new(table_owner))); 4,600 ( 0.00%) self.with_opaque_type_inference(table_owner) 6,440 ( 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. 802 ( 0.00%) pub fn with_opaque_type_inference(mut self, defining_use_anchor: LocalDefId) -> Self { 401 ( 0.00%) self.defining_use_anchor = Some(defining_use_anchor); 2,642 ( 0.00%) self 1,203 ( 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`). 14,732 ( 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| { 22,474 ( 0.00%) let (value, subst) = 1,436 ( 0.00%) infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical); 32,852 ( 0.00%) f(infcx, value, subst) . }) 15,897 ( 0.00%) } . 2,526,304 ( 0.05%) pub fn enter(&mut self, f: impl for<'a> FnOnce(InferCtxt<'a, 'tcx>) -> R) -> R { 1,127,796 ( 0.02%) let InferCtxtBuilder { tcx, defining_use_anchor, ref fresh_typeck_results } = *self; . let in_progress_typeck_results = fresh_typeck_results.as_ref(); 7,796,501 ( 0.16%) f(InferCtxt { . tcx, . defining_use_anchor, . in_progress_typeck_results, 284,261 ( 0.01%) 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), 284,261 ( 0.01%) 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), . }) 2,804,959 ( 0.06%) } . } . . 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 { 561 ( 0.00%) let InferOk { value, obligations } = self; 2,398 ( 0.00%) for obligation in obligations { 403 ( 0.00%) fulfill_cx.register_predicate_obligation(infcx, obligation); . } . value . } . } . . impl<'tcx> InferOk<'tcx, ()> { 8,372 ( 0.00%) pub fn into_obligations(self) -> PredicateObligations<'tcx> { 33,488 ( 0.00%) self.obligations 8,372 ( 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() 14,219 ( 0.00%) } . 116,744 ( 0.00%) pub fn freshen>(&self, t: T) -> T { 131,337 ( 0.00%) t.fold_with(&mut self.freshener()) 131,337 ( 0.00%) } . . /// 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`. 232 ( 0.00%) pub fn type_var_origin(&'a self, ty: Ty<'tcx>) -> Option { 464 ( 0.00%) match *ty.kind() { 116 ( 0.00%) ty::Infer(ty::TyVar(vid)) => { 464 ( 0.00%) Some(*self.inner.borrow_mut().type_variables().var_origin(vid)) . } . _ => None, . } 464 ( 0.00%) } . 14,593 ( 0.00%) pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, false) 14,593 ( 0.00%) } . . /// Like `freshener`, but does not replace `'static` regions. 48,680 ( 0.00%) pub fn freshener_keep_static<'b>(&'b self) -> TypeFreshener<'b, 'tcx> { . freshen::TypeFreshener::new(self, true) 48,680 ( 0.00%) } . 1,748 ( 0.00%) pub fn unsolved_variables(&self) -> Vec> { 874 ( 0.00%) let mut inner = self.inner.borrow_mut(); 874 ( 0.00%) let mut vars: Vec> = inner . .type_variables() . .unsolved_variables() . .into_iter() 230 ( 0.00%) .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 }) 168 ( 0.00%) .filter(|&vid| inner.int_unification_table().probe_value(vid).is_none()) . .map(|v| self.tcx.mk_int_var(v)), . ); . 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 3,059 ( 0.00%) } . 29,089 ( 0.00%) fn combine_fields( . &'a self, . trace: TypeTrace<'tcx>, . param_env: ty::ParamEnv<'tcx>, . ) -> CombineFields<'a, 'tcx> { 116,432 ( 0.00%) CombineFields { . infcx: self, 291,080 ( 0.01%) trace, . cause: None, . param_env, . obligations: PredicateObligations::new(), . } 29,089 ( 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); 5,580 ( 0.00%) let result = func(self); . self.in_snapshot.set(flag); . result . } . 147,082 ( 0.00%) 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(); . 441,246 ( 0.01%) 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. 73,541 ( 0.00%) _in_progress_typeck_results: self . .in_progress_typeck_results . .map(|typeck_results| typeck_results.borrow()), . } 294,164 ( 0.01%) } . 226,556 ( 0.00%) #[instrument(skip(self, snapshot), level = "debug")] . fn rollback_to(&self, cause: &str, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 20,596 ( 0.00%) undo_snapshot, 20,596 ( 0.00%) region_constraints_snapshot, 20,596 ( 0.00%) universe, 20,596 ( 0.00%) was_in_snapshot, 41,192 ( 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(); 20,596 ( 0.00%) inner.rollback_to(undo_snapshot); . inner.unwrap_region_constraints().rollback_to(region_constraints_snapshot); . } . 794,175 ( 0.02%) #[instrument(skip(self, snapshot), level = "debug")] . fn commit_from(&self, snapshot: CombinedSnapshot<'a, 'tcx>) { . let CombinedSnapshot { 52,945 ( 0.00%) undo_snapshot, . region_constraints_snapshot: _, . universe: _, 52,945 ( 0.00%) was_in_snapshot, 105,890 ( 0.00%) _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. 33,358 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 40,953 ( 0.00%) pub fn commit_unconditionally(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 3,723 ( 0.00%) let snapshot = self.start_snapshot(); 11,921 ( 0.00%) let r = f(&snapshot); 26,061 ( 0.00%) self.commit_from(snapshot); 22,187 ( 0.00%) r . } . . /// Execute `f` and commit the bindings if closure `f` returns `Ok(_)`. 340,146 ( 0.01%) #[instrument(skip(self, f), level = "debug")] 419,160 ( 0.01%) pub fn commit_if_ok(&self, f: F) -> Result . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> Result, . { 62,872 ( 0.00%) let snapshot = self.start_snapshot(); 193,158 ( 0.00%) let r = f(&snapshot); . debug!("commit_if_ok() -- r.is_ok() = {}", r.is_ok()); 63,527 ( 0.00%) match r { . Ok(_) => { 356,060 ( 0.01%) self.commit_from(snapshot); . } . Err(_) => { 86,423 ( 0.00%) self.rollback_to("commit_if_ok -- error", snapshot); . } . } 360,779 ( 0.01%) r . } . . /// Execute `f` then unroll any bindings it creates. 83,293 ( 0.00%) #[instrument(skip(self, f), level = "debug")] 95,419 ( 0.00%) pub fn probe(&self, f: F) -> R . where . F: FnOnce(&CombinedSnapshot<'a, 'tcx>) -> R, . { 23,052 ( 0.00%) let snapshot = self.start_snapshot(); 37,060 ( 0.00%) let r = f(&snapshot); 108,956 ( 0.00%) self.rollback_to("probe", snapshot); 19,809 ( 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 9,196 ( 0.00%) pub fn region_constraints_added_in_snapshot( . &self, . snapshot: &CombinedSnapshot<'a, 'tcx>, . ) -> Option { 18,392 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() . .region_constraints_added_in_snapshot(&snapshot.undo_snapshot) 13,794 ( 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); . } . 336 ( 0.00%) pub fn can_sub(&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).sub(a, b).map(|InferOk { obligations: _, .. }| { . // Ignore obligations, since we are unrolling . // everything anyway. . }) . }) 252 ( 0.00%) } . 4,128 ( 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. . }) . }) 3,096 ( 0.00%) } . 51,710 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub fn sub_regions( . &self, . origin: SubregionOrigin<'tcx>, . a: ty::Region<'tcx>, . b: ty::Region<'tcx>, . ) { 46,539 ( 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 969 ---------------------------------------- . /// to `subtype_predicate` -- that is, "coercing" `a` to `b` winds up . /// actually requiring `a <: b`. This is of course a valid coercion, . /// but it's not as flexible as `FnCtxt::coerce` would be. . /// . /// (We may refactor this in the future, but there are a number of . /// practical obstacles. Among other things, `FnCtxt::coerce` presently . /// records adjustments that are required on the HIR in order to perform . /// the coercion, and we don't currently have a way to manage that.) 6 ( 0.00%) pub fn coerce_predicate( . &self, . cause: &ObligationCause<'tcx>, . param_env: ty::ParamEnv<'tcx>, . predicate: ty::PolyCoercePredicate<'tcx>, . ) -> Option> { 4 ( 0.00%) 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, . }); 10 ( 0.00%) self.subtype_predicate(cause, param_env, subtype_predicate) 8 ( 0.00%) } . 1,536 ( 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. 128 ( 0.00%) let r_a = self.shallow_resolve(predicate.skip_binder().a); 128 ( 0.00%) let r_b = self.shallow_resolve(predicate.skip_binder().b); 930 ( 0.00%) match (r_a.kind(), r_b.kind()) { 218 ( 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); 218 ( 0.00%) return None; . } . _ => {} . } . . Some(self.commit_if_ok(|_snapshot| { 19 ( 0.00%) let ty::SubtypePredicate { a_is_expected, a, b } = . self.replace_bound_vars_with_placeholders(predicate); . 38 ( 0.00%) let ok = self.at(cause, param_env).sub_exp(a_is_expected, a, b)?; . . Ok(ok.unit()) . })) 1,152 ( 0.00%) } . 16,692 ( 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) . }); 13,910 ( 0.00%) self.sub_regions(origin, r_b, r_a); // `b : a` ==> `a <= b` . Ok(()) . }) 11,128 ( 0.00%) } . . /// Number of type variables created so far. 53 ( 0.00%) pub fn num_ty_vars(&self) -> usize { . self.inner.borrow_mut().type_variables().num_vars() 106 ( 0.00%) } . 12,752 ( 0.00%) pub fn next_ty_var_id(&self, origin: TypeVariableOrigin) -> TyVid { 63,760 ( 0.00%) self.inner.borrow_mut().type_variables().new_var(self.universe(), origin) 19,128 ( 0.00%) } . 12,320 ( 0.00%) pub fn next_ty_var(&self, origin: TypeVariableOrigin) -> Ty<'tcx> { 44,422 ( 0.00%) self.tcx.mk_ty_var(self.next_ty_var_id(origin)) 18,480 ( 0.00%) } . 848 ( 0.00%) pub fn next_ty_var_in_universe( . &self, . origin: TypeVariableOrigin, . universe: ty::UniverseIndex, . ) -> Ty<'tcx> { 4,664 ( 0.00%) let vid = self.inner.borrow_mut().type_variables().new_var(universe, origin); 424 ( 0.00%) self.tcx.mk_ty_var(vid) 1,272 ( 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 1090 ---------------------------------------- . pub fn next_const_var_id(&self, origin: ConstVariableOrigin) -> ConstVid<'tcx> { . self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }) . } . . fn next_int_var_id(&self) -> IntVid { 275 ( 0.00%) self.inner.borrow_mut().int_unification_table().new_key(None) . } . 165 ( 0.00%) pub fn next_int_var(&self) -> Ty<'tcx> { . self.tcx.mk_int_var(self.next_int_var_id()) 220 ( 0.00%) } . . fn next_float_var_id(&self) -> FloatVid { . self.inner.borrow_mut().float_unification_table().new_key(None) . } . . 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. 6,690 ( 0.00%) pub fn next_region_var(&self, origin: RegionVariableOrigin) -> ty::Region<'tcx> { 185,242 ( 0.00%) self.next_region_var_in_universe(origin, self.universe()) 13,380 ( 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. 74,112 ( 0.00%) pub fn next_region_var_in_universe( . &self, . origin: RegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { . let region_var = 481,728 ( 0.01%) self.inner.borrow_mut().unwrap_region_constraints().new_region_var(universe, origin); 185,280 ( 0.00%) self.tcx.mk_region(ty::ReVar(region_var)) 111,168 ( 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. 6,796 ( 0.00%) pub fn universe_of_region(&self, r: ty::Region<'tcx>) -> ty::UniverseIndex { . self.inner.borrow_mut().unwrap_region_constraints().universe(r) 10,194 ( 0.00%) } . . /// Number of region variables created so far. 3,242 ( 0.00%) pub fn num_region_vars(&self) -> usize { . self.inner.borrow_mut().unwrap_region_constraints().num_region_vars() 4,863 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 18,066 ( 0.00%) pub fn next_nll_region_var(&self, origin: NllRegionVariableOrigin) -> ty::Region<'tcx> { . self.next_region_var(RegionVariableOrigin::Nll(origin)) 36,132 ( 0.00%) } . . /// Just a convenient wrapper of `next_region_var` for using during NLL. 122 ( 0.00%) pub fn next_nll_region_var_in_universe( . &self, . origin: NllRegionVariableOrigin, . universe: ty::UniverseIndex, . ) -> ty::Region<'tcx> { 1,014 ( 0.00%) self.next_region_var_in_universe(RegionVariableOrigin::Nll(origin), universe) 244 ( 0.00%) } . 100,888 ( 0.00%) pub fn var_for_def(&self, span: Span, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 52,581 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { . // Create a region inference variable for the given . // region parameter definition. 5,237 ( 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)`. 29,348 ( 0.00%) let ty_var_id = self.inner.borrow_mut().type_variables().new_var( . self.universe(), 36,685 ( 0.00%) TypeVariableOrigin { . kind: TypeVariableOriginKind::TypeParameterDefinition( 7,337 ( 0.00%) param.name, 7,337 ( 0.00%) Some(param.def_id), . ), . span, . }, . ); . 7,337 ( 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, . }; . let const_var_id = 407 ( 0.00%) self.inner.borrow_mut().const_unification_table().new_key(ConstVarValue { . origin, . val: ConstVariableValue::Unknown { universe: self.universe() }, . }); 37 ( 0.00%) self.tcx.mk_const_var(const_var_id, self.tcx.type_of(param.def_id)).into() . } . } 296 ( 0.00%) } . . /// Given a set of generics defined on a type or impl, returns a substitution mapping each . /// type/region parameter to a fresh inference variable. 18,177 ( 0.00%) pub fn fresh_substs_for_item(&self, span: Span, def_id: DefId) -> SubstsRef<'tcx> { 95,399 ( 0.00%) InternalSubsts::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) 12,118 ( 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). 1,000 ( 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() . ); . 21,362 ( 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() 1,500 ( 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`. 20,839 ( 0.00%) pub fn resolve_regions( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) -> Vec> { 56,563 ( 0.00%) let (var_infos, data) = { . let mut inner = self.inner.borrow_mut(); . let inner = &mut *inner; 2,977 ( 0.00%) assert!( 8,931 ( 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() 2,977 ( 0.00%) }; . . let region_rels = 2,977 ( 0.00%) &RegionRelations::new(self.tcx, region_context, outlives_env.free_region_map()); . 26,793 ( 0.00%) let (lexical_region_resolutions, errors) = 71,448 ( 0.00%) lexical_region_resolve::resolve(region_rels, var_infos, data, mode); . 11,908 ( 0.00%) let old_value = self.lexical_region_resolutions.replace(Some(lexical_region_resolutions)); 2,977 ( 0.00%) assert!(old_value.is_none()); . . errors 26,793 ( 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`. 29,770 ( 0.00%) pub fn resolve_regions_and_report_errors( . &self, . region_context: DefId, . outlives_env: &OutlivesEnvironment<'tcx>, . mode: RegionckMode, . ) { 5,954 ( 0.00%) let errors = self.resolve_regions(region_context, outlives_env, mode); . 8,931 ( 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. 5,954 ( 0.00%) self.report_region_errors(&errors); . } 14,885 ( 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(); 7,348 ( 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. 2,005 ( 0.00%) pub fn take_region_var_origins(&self) -> VarInfos { . let mut inner = self.inner.borrow_mut(); 7,619 ( 0.00%) let (var_infos, data) = inner . .region_constraint_storage . .take() . .expect("regions already resolved") . .with_log(&mut inner.undo_log) 401 ( 0.00%) .into_infos_and_data(); 401 ( 0.00%) assert!(data.is_empty()); . var_infos 3,208 ( 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)`. 3,646 ( 0.00%) pub fn probe_ty_var(&self, vid: TyVid) -> Result, ty::UniverseIndex> { . use self::type_variable::TypeVariableValue; . 10,938 ( 0.00%) match self.inner.borrow_mut().type_variables().probe(vid) { . TypeVariableValue::Known { value } => Ok(value), . TypeVariableValue::Unknown { universe } => Err(universe), . } 12,761 ( 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>, . { 401,426 ( 0.01%) value.fold_with(&mut ShallowResolver { infcx: self }) . } . 4,772 ( 0.00%) pub fn root_var(&self, var: ty::TyVid) -> ty::TyVid { . self.inner.borrow_mut().type_variables().root_var(var) 7,158 ( 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. 616 ( 0.00%) pub fn resolve_vars_if_possible(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { 516,775 ( 0.01%) if !value.needs_infer() { 84,369 ( 0.00%) return value; // Avoid duplicated subst-folding. . } 96,200 ( 0.00%) let mut r = resolve::OpportunisticVarResolver::new(self); 115,771 ( 0.00%) value.fold_with(&mut r) 770 ( 0.00%) } . . /// 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)> . where -- line 1415 ---------------------------------------- -- 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) . } . 6,210 ( 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 = 56,274 ( 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 }, . ) . }; 114,423 ( 0.00%) self.tcx.replace_bound_vars(value, fld_r, fld_t, fld_c) 4,140 ( 0.00%) } . . /// See the [`region_constraints::RegionConstraintCollector::verify_generic_bound`] method. 7,760 ( 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); . 2,910 ( 0.00%) self.inner . .borrow_mut() . .unwrap_region_constraints() 16,490 ( 0.00%) .verify_generic_bound(origin, kind, a, bound); 6,790 ( 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. 484 ( 0.00%) pub fn closure_kind(&self, closure_substs: SubstsRef<'tcx>) -> Option { 968 ( 0.00%) let closure_kind_ty = closure_substs.as_closure().kind_ty(); . let closure_kind_ty = self.shallow_resolve(closure_kind_ty); 726 ( 0.00%) closure_kind_ty.to_opt_closure_kind() . } . . /// Clears the selection, evaluation, and projection caches. This is useful when . /// repeatedly attempting to select an `Obligation` while changing only . /// 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 { 511,105 ( 0.01%) self.universe.get() 356,834 ( 0.01%) } . . /// Creates and return a fresh universe that extends all previous . /// universes. Updates `self.universe` to that new universe. 280 ( 0.00%) pub fn create_next_universe(&self) -> ty::UniverseIndex { 480 ( 0.00%) let u = self.universe.get().next_universe(); . self.universe.set(u); . u 280 ( 0.00%) } . . /// Resolves and evaluates a constant. . /// . /// The constant can be located on a trait like `::C`, in which case the given . /// substitutions and environment are used to resolve the constant. Alternatively if the . /// constant has generic parameters in scope the substitutions are used to evaluate the value of . /// the constant. For example in `fn foo() { let _ = [0; bar::()]; }` the repeat count . /// constant `bar::()` requires a substitution for `T`, if the substitution for `T` is still -- line 1576 ---------------------------------------- -- 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`. 2,212,512 ( 0.05%) fn shallow_resolve_ty(&self, typ: Ty<'tcx>) -> Ty<'tcx> { 807,831 ( 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`. 236,044 ( 0.00%) let known = self.inner.borrow_mut().type_variables().probe(v).known(); . known.map_or(typ, |t| self.shallow_resolve_ty(t)) . } . 5,916 ( 0.00%) ty::Infer(ty::IntVar(v)) => self . .inner . .borrow_mut() . .int_unification_table() . .probe_value(v) 1,452 ( 0.00%) .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . ty::Infer(ty::FloatVar(v)) => self . .inner . .borrow_mut() . .float_unification_table() . .probe_value(v) . .map(|v| v.to_type(self.tcx)) . .unwrap_or(typ), . . _ => typ, . } 2,489,076 ( 0.05%) } . . /// `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))`. 98,187 ( 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 . // `ty::Infer(_)`. 1,958 ( 0.00%) self.inner.borrow_mut().int_unification_table().inlined_probe_value(v).is_some() . } . . TyOrConstInferVar::TyFloat(v) => { . // If `probe_value` returns a value it's always a . // `ty::Float(_)`, which never matches a `ty::Infer(_)`. . // . // Not `inlined_probe_value(v)` because this call site is colder. . self.inner.borrow_mut().float_unification_table().probe_value(v).is_some() -- line 1688 ---------------------------------------- -- 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`). 2,214 ( 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, . } 2,214 ( 0.00%) } . . /// Tries to extract an inference variable from a type, returns `None` . /// for types other than `ty::Infer(_)` (or `InferTy::Fresh*`). 202 ( 0.00%) pub fn maybe_from_ty(ty: Ty<'tcx>) -> Option { 21,296 ( 0.00%) match *ty.kind() { 4,654 ( 0.00%) ty::Infer(ty::TyVar(v)) => Some(TyOrConstInferVar::Ty(v)), 70 ( 0.00%) ty::Infer(ty::IntVar(v)) => Some(TyOrConstInferVar::TyInt(v)), . ty::Infer(ty::FloatVar(v)) => Some(TyOrConstInferVar::TyFloat(v)), . _ => None, . } 202 ( 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> { 494,801 ( 0.01%) self.infcx.shallow_resolve_ty(ty) . } . 928 ( 0.00%) fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { 598 ( 0.00%) if let ty::Const { val: ty::ConstKind::Infer(InferConst::Var(vid)), .. } = ct { 335 ( 0.00%) self.infcx . .inner . .borrow_mut() . .const_unification_table() 201 ( 0.00%) .probe_value(*vid) . .val . .known() . .unwrap_or(ct) . } else { . ct . } 1,160 ( 0.00%) } . } . . impl<'tcx> TypeTrace<'tcx> { . pub fn span(&self) -> Span { 88 ( 0.00%) self.cause.span . } . . pub fn types( . cause: &ObligationCause<'tcx>, . a_is_expected: bool, . a: Ty<'tcx>, . b: Ty<'tcx>, . ) -> TypeTrace<'tcx> { -- line 1792 ---------------------------------------- -- line 1800 ---------------------------------------- . b: &'tcx ty::Const<'tcx>, . ) -> TypeTrace<'tcx> { . TypeTrace { cause: cause.clone(), values: Consts(ExpectedFound::new(a_is_expected, a, b)) } . } . } . . impl<'tcx> SubregionOrigin<'tcx> { . pub fn span(&self) -> Span { 220 ( 0.00%) match *self { 44 ( 0.00%) Subtype(ref a) => a.span(), . RelateObjectBound(a) => a, . RelateParamBound(a, ..) => a, . RelateRegionParamBound(a) => a, . Reborrow(a) => a, . ReborrowUpvar(a, _) => a, . DataBorrowed(_, a) => a, . ReferenceOutlivesReferent(_, a) => a, . CompareImplMethodObligation { span, .. } => span, -- line 1817 ---------------------------------------- -- line 1818 ---------------------------------------- . CompareImplTypeObligation { span, .. } => span, . } . } . . pub fn from_obligation_cause(cause: &traits::ObligationCause<'tcx>, default: F) -> Self . where . F: FnOnce() -> Self, . { 17,062 ( 0.00%) match *cause.code() { 2,143 ( 0.00%) traits::ObligationCauseCode::ReferenceOutlivesReferent(ref_type) => { 10,715 ( 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 ---------------------------------------- 753,426 ( 0.02%) -------------------------------------------------------------------------------- -- 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) { 698 ( 0.00%) let old = self.replace(val); 1,612 ( 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. 119,785 ( 0.00%) 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 { 940,380 ( 0.02%) 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 { 1,419,837 ( 0.03%) RefCell { 586,662 ( 0.01%) 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. 2,468 ( 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] 2,860 ( 0.00%) pub fn borrow(&self) -> Ref<'_, T> { . self.try_borrow().expect("already mutably borrowed") 8,580 ( 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] 13,976 ( 0.00%) pub fn borrow_mut(&self) -> RefMut<'_, T> { . self.try_borrow_mut().expect("already borrowed") 41,928 ( 0.00%) } . . /// 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> { 1,162,409 ( 0.02%) let b = borrow.get().wrapping_add(1); 755,801 ( 0.02%) 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) { 691,949 ( 0.01%) let borrow = self.borrow.get(); . debug_assert!(is_reading(borrow)); 1,381,837 ( 0.03%) 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) { 5,752,389 ( 0.12%) let borrow = self.borrow.get(); . debug_assert!(is_writing(borrow)); 11,428,708 ( 0.23%) 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. 13,358,192 ( 0.27%) 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 { 521 ( 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! 7,560,473 ( 0.16%) 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 ---------------------------------------- 11,360,430 ( 0.23%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_infer/src/infer/region_constraints/mod.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . use std::collections::BTreeMap; . use std::ops::Range; . use std::{cmp, fmt, mem}; . . mod leak_check; . . pub use rustc_middle::infer::MemberConstraint; . 3,126,871 ( 0.06%) #[derive(Default)] . pub struct RegionConstraintStorage<'tcx> { . /// For each `RegionVid`, the corresponding `RegionVariableOrigin`. . var_infos: IndexVec, . . data: RegionConstraintData<'tcx>, . . /// For a given pair of regions (R1, R2), maps to a region R3 that . /// is designated as their LUB (edges R1 <= R3 and R2 <= R3 -- line 39 ---------------------------------------- -- line 64 ---------------------------------------- . storage: &'a mut RegionConstraintStorage<'tcx>, . undo_log: &'a mut InferCtxtUndoLogs<'tcx>, . } . . impl<'tcx> std::ops::Deref for RegionConstraintCollector<'_, 'tcx> { . type Target = RegionConstraintStorage<'tcx>; . #[inline] . fn deref(&self) -> &RegionConstraintStorage<'tcx> { 3,953 ( 0.00%) self.storage . } . } . . impl<'tcx> std::ops::DerefMut for RegionConstraintCollector<'_, 'tcx> { . #[inline] . fn deref_mut(&mut self) -> &mut RegionConstraintStorage<'tcx> { 37,100 ( 0.00%) self.storage . } . } . . pub type VarInfos = IndexVec; . . /// The full set of region constraints gathered up by the collector. . /// Describes constraints between the region variables and other . /// regions, as well as other conditions that must be verified, or . /// assumptions that can be made. 1,150,556 ( 0.02%) #[derive(Debug, Default, Clone)] . pub struct RegionConstraintData<'tcx> { . /// Constraints of the form `A <= B`, where either `A` or `B` can . /// be a region variable (or neither, as it happens). . pub constraints: BTreeMap, SubregionOrigin<'tcx>>, . . /// Constraints of the form `R0 member of [R1, ..., Rn]`, meaning that . /// `R0` must be equal to one of the regions `R1..Rn`. These occur . /// with `impl Trait` quite frequently. -- line 97 ---------------------------------------- -- line 122 ---------------------------------------- . /// This hashmap is used to avoid that naive scenario. Basically . /// we record the fact that `'a <= 'b` is implied by the fn . /// signature, and then ignore the constraint when solving . /// equations. This is a bit of a hack but seems to work. . pub givens: FxHashSet<(Region<'tcx>, ty::RegionVid)>, . } . . /// Represents a constraint that influences the inference process. 1,155,416 ( 0.02%) #[derive(Clone, Copy, PartialEq, Eq, Debug, PartialOrd, Ord)] . pub enum Constraint<'tcx> { . /// A region variable is a subregion of another. 271,574 ( 0.01%) VarSubVar(RegionVid, RegionVid), . . /// A concrete region is a subregion of region variable. 52,380 ( 0.00%) RegSubVar(Region<'tcx>, RegionVid), . . /// A region variable is a subregion of a concrete region. This does not . /// directly affect inference, but instead is checked after . /// inference is complete. 17,138 ( 0.00%) VarSubReg(RegionVid, Region<'tcx>), . . /// A constraint where neither side is a variable. This does not . /// directly affect inference, but instead is checked after . /// inference is complete. 3,280 ( 0.00%) RegSubReg(Region<'tcx>, Region<'tcx>), . } . . impl Constraint<'_> { . pub fn involves_placeholders(&self) -> bool { 1,935 ( 0.00%) match self { . Constraint::VarSubVar(_, _) => false, . Constraint::VarSubReg(_, r) | Constraint::RegSubVar(r, _) => r.is_placeholder(), . Constraint::RegSubReg(r, s) => r.is_placeholder() || s.is_placeholder(), . } . } . } . . #[derive(Debug, Clone)] -- line 159 ---------------------------------------- -- line 263 ---------------------------------------- . /// In other words, if we meet *all* bounds in `B`, that suffices. . /// This is used when *some* bound in `B` is known to suffice, but . /// we don't know which. . AllBounds(Vec>), . } . . #[derive(Copy, Clone, PartialEq, Eq, Hash)] . pub(crate) struct TwoRegions<'tcx> { 39 ( 0.00%) a: Region<'tcx>, 44 ( 0.00%) b: Region<'tcx>, . } . . #[derive(Copy, Clone, PartialEq)] . pub(crate) enum UndoLog<'tcx> { . /// We added `RegionVid`. . AddVar(RegionVid), . . /// We added the given `constraint`. -- line 280 ---------------------------------------- -- line 304 ---------------------------------------- . pub universe: ty::UniverseIndex, . } . . pub struct RegionSnapshot { . any_unifications: bool, . } . . impl<'tcx> RegionConstraintStorage<'tcx> { 568,522 ( 0.01%) pub fn new() -> Self { . Self::default() 568,522 ( 0.01%) } . . #[inline] . pub(crate) fn with_log<'a>( . &'a mut self, . undo_log: &'a mut InferCtxtUndoLogs<'tcx>, . ) -> RegionConstraintCollector<'a, 'tcx> { . RegionConstraintCollector { storage: self, undo_log } . } . . fn rollback_undo_entry(&mut self, undo_entry: UndoLog<'tcx>) { 67,552 ( 0.00%) match undo_entry { . AddVar(vid) => { . self.var_infos.pop().unwrap(); 22,628 ( 0.00%) assert_eq!(self.var_infos.len(), vid.index() as usize); . } 7,852 ( 0.00%) AddConstraint(ref constraint) => { 31,408 ( 0.00%) self.data.constraints.remove(constraint); . } . AddVerify(index) => { . self.data.verifys.pop(); . assert_eq!(self.data.verifys.len(), index); . } . AddGiven(sub, sup) => { . self.data.givens.remove(&(sub, sup)); . } -- line 339 ---------------------------------------- -- line 348 ---------------------------------------- . } . . impl<'tcx> RegionConstraintCollector<'_, 'tcx> { . pub fn num_region_vars(&self) -> usize { . self.var_infos.len() . } . . pub fn region_constraint_data(&self) -> &RegionConstraintData<'tcx> { 1,837 ( 0.00%) &self.data 1,837 ( 0.00%) } . . /// Once all the constraints have been gathered, extract out the final data. . /// . /// Not legal during a snapshot. . pub fn into_infos_and_data(self) -> (VarInfos, RegionConstraintData<'tcx>) { 3,378 ( 0.00%) assert!(!UndoLogs::>::in_snapshot(&self.undo_log)); . (mem::take(&mut self.storage.var_infos), mem::take(&mut self.storage.data)) . } . . /// Takes (and clears) the current set of constraints. Note that . /// the set of variables remains intact, but all relationships . /// between them are reset. This is used during NLL checking to . /// grab the set of constraints that arose from a particular . /// operation. -- line 371 ---------------------------------------- -- line 418 ---------------------------------------- . . pub fn start_snapshot(&mut self) -> RegionSnapshot { . debug!("RegionConstraintCollector: start_snapshot"); . RegionSnapshot { any_unifications: self.any_unifications } . } . . pub fn rollback_to(&mut self, snapshot: RegionSnapshot) { . debug!("RegionConstraintCollector: rollback_to({:?})", snapshot); 20,596 ( 0.00%) self.any_unifications = snapshot.any_unifications; . } . 222,600 ( 0.00%) pub fn new_region_var( . &mut self, . universe: ty::UniverseIndex, . origin: RegionVariableOrigin, . ) -> RegionVid { 37,100 ( 0.00%) let vid = self.var_infos.push(RegionVariableInfo { origin, universe }); . 111,300 ( 0.00%) let u_vid = self.unification_table().new_key(UnifiedRegion(None)); 37,100 ( 0.00%) assert_eq!(vid, u_vid.vid); . self.undo_log.push(AddVar(vid)); . debug!("created new region variable {:?} in {:?} with origin {:?}", vid, universe, origin); . vid 296,800 ( 0.01%) } . . /// Returns the universe for the given variable. . pub fn var_universe(&self, vid: RegionVid) -> ty::UniverseIndex { 23,708 ( 0.00%) self.var_infos[vid].universe . } . . /// Returns the origin for the given variable. . pub fn var_origin(&self, vid: RegionVid) -> RegionVariableOrigin { . self.var_infos[vid].origin . } . . fn add_constraint(&mut self, constraint: Constraint<'tcx>, origin: SubregionOrigin<'tcx>) { . // cannot add constraints once regions are resolved . debug!("RegionConstraintCollector: add_constraint({:?})", constraint); . . // never overwrite an existing (constraint, origin) - only insert one if it isn't . // present in the map yet. This prevents origins from outside the snapshot being . // replaced with "less informative" origins e.g., during calls to `can_eq` . let undo_log = &mut self.undo_log; 222,872 ( 0.00%) self.storage.data.constraints.entry(constraint).or_insert_with(|| { 125,400 ( 0.00%) undo_log.push(AddConstraint(constraint)); 83,600 ( 0.00%) origin . }); . } . . fn add_verify(&mut self, verify: Verify<'tcx>) { . // cannot add verifys once regions are resolved . debug!("RegionConstraintCollector: add_verify({:?})", verify); . . // skip no-op cases known to be satisfied 1,940 ( 0.00%) if let VerifyBound::AllBounds(ref bs) = verify.bound { . if bs.is_empty() { . return; . } . } . 970 ( 0.00%) let index = self.data.verifys.len(); 14,550 ( 0.00%) self.data.verifys.push(verify); 970 ( 0.00%) self.undo_log.push(AddVerify(index)); . } . . pub fn add_given(&mut self, sub: Region<'tcx>, sup: ty::RegionVid) { . // cannot add givens once regions are resolved . if self.data.givens.insert((sub, sup)) { . debug!("add_given({:?} <= {:?})", sub, sup); . . self.undo_log.push(AddGiven(sub, sup)); . } . } . 94,590 ( 0.00%) pub fn make_eqregion( . &mut self, . origin: SubregionOrigin<'tcx>, . sub: Region<'tcx>, . sup: Region<'tcx>, . ) { 47,295 ( 0.00%) if sub != sup { . // Eventually, it would be nice to add direct support for . // equating regions. 47,168 ( 0.00%) self.make_subregion(origin.clone(), sub, sup); 53,064 ( 0.00%) self.make_subregion(origin, sup, sub); . 29,498 ( 0.00%) match (sub, sup) { 14,979 ( 0.00%) (&ty::ReVar(sub), &ty::ReVar(sup)) => { . debug!("make_eqregion: unifying {:?} with {:?}", sub, sup); 24,965 ( 0.00%) self.unification_table().union(sub, sup); . self.any_unifications = true; . } . (&ty::ReVar(vid), value) | (value, &ty::ReVar(vid)) => { . debug!("make_eqregion: unifying {:?} with {:?}", vid, value); 3,540 ( 0.00%) self.unification_table().union_value(vid, UnifiedRegion(Some(value))); . self.any_unifications = true; . } . (_, _) => {} . } . } 41,272 ( 0.00%) } . . pub fn member_constraint( . &mut self, . opaque_type_def_id: DefId, . definition_span: Span, . hidden_ty: Ty<'tcx>, . member_region: ty::Region<'tcx>, . choice_regions: &Lrc>>, -- line 526 ---------------------------------------- -- line 535 ---------------------------------------- . opaque_type_def_id, . definition_span, . hidden_ty, . member_region, . choice_regions: choice_regions.clone(), . }); . } . 310,476 ( 0.01%) #[instrument(skip(self, origin), level = "debug")] . pub fn make_subregion( . &mut self, . origin: SubregionOrigin<'tcx>, . sub: Region<'tcx>, . sup: Region<'tcx>, . ) { . // cannot add constraints once regions are resolved . debug!("origin = {:#?}", origin); . 224,550 ( 0.00%) match (sub, sup) { . (&ReLateBound(..), _) | (_, &ReLateBound(..)) => { . span_bug!(origin.span(), "cannot relate bound region: {:?} <= {:?}", sub, sup); . } . (_, &ReStatic) => { . // all regions are subregions of static, so we can ignore this . } 15,935 ( 0.00%) (&ReVar(sub_id), &ReVar(sup_id)) => { 111,545 ( 0.00%) self.add_constraint(Constraint::VarSubVar(sub_id, sup_id), origin); . } . (_, &ReVar(sup_id)) => { 19,873 ( 0.00%) self.add_constraint(Constraint::RegSubVar(sub, sup_id), origin); . } 1,900 ( 0.00%) (&ReVar(sub_id), _) => { 13,300 ( 0.00%) self.add_constraint(Constraint::VarSubReg(sub_id, sup), origin); . } . _ => { 4,319 ( 0.00%) self.add_constraint(Constraint::RegSubReg(sub, sup), origin); . } . } . } . 4,850 ( 0.00%) pub fn verify_generic_bound( . &mut self, . origin: SubregionOrigin<'tcx>, . kind: GenericKind<'tcx>, . sub: Region<'tcx>, . bound: VerifyBound<'tcx>, . ) { 12,610 ( 0.00%) self.add_verify(Verify { kind, origin, region: sub, bound }); 4,850 ( 0.00%) } . . pub fn lub_regions( . &mut self, . tcx: TyCtxt<'tcx>, . origin: SubregionOrigin<'tcx>, . a: Region<'tcx>, . b: Region<'tcx>, . ) -> Region<'tcx> { -- line 591 ---------------------------------------- -- line 599 ---------------------------------------- . _ if a == b => { . a // LUB(a,a) = a . } . . _ => self.combine_vars(tcx, Lub, a, b, origin), . } . } . 368 ( 0.00%) pub fn glb_regions( . &mut self, . tcx: TyCtxt<'tcx>, . origin: SubregionOrigin<'tcx>, . a: Region<'tcx>, . b: Region<'tcx>, . ) -> Region<'tcx> { . // cannot add constraints once regions are resolved . debug!("RegionConstraintCollector: glb_regions({:?}, {:?})", a, b); 182 ( 0.00%) match (a, b) { . (&ReStatic, r) | (r, &ReStatic) => { . r // static lives longer than everything else . } . 88 ( 0.00%) _ if a == b => { . a // GLB(a,a) = a . } . 528 ( 0.00%) _ => self.combine_vars(tcx, Glb, a, b, origin), . } 368 ( 0.00%) } . . /// Resolves the passed RegionVid to the root RegionVid in the unification table . pub fn opportunistic_resolve_var(&mut self, rid: ty::RegionVid) -> ty::RegionVid { 34,292 ( 0.00%) self.unification_table().find(rid).vid . } . . /// If the Region is a `ReVar`, then resolves it either to the root value in . /// the unification table, if it exists, or to the root `ReVar` in the table. . /// If the Region is not a `ReVar`, just returns the Region itself. . pub fn opportunistic_resolve_region( . &mut self, . tcx: TyCtxt<'tcx>, -- line 639 ---------------------------------------- -- line 647 ---------------------------------------- . tcx.reuse_or_mk_region(region, ty::ReVar(root)) . }) . } . _ => region, . } . } . . fn combine_map(&mut self, t: CombineMapType) -> &mut CombineMap<'tcx> { 352 ( 0.00%) match t { . Glb => &mut self.glbs, . Lub => &mut self.lubs, . } . } . 528 ( 0.00%) fn combine_vars( . &mut self, . tcx: TyCtxt<'tcx>, . t: CombineMapType, . a: Region<'tcx>, . b: Region<'tcx>, . origin: SubregionOrigin<'tcx>, . ) -> Region<'tcx> { . let vars = TwoRegions { a, b }; . if let Some(&c) = self.combine_map(t).get(&vars) { . return tcx.mk_region(ReVar(c)); . } . let a_universe = self.universe(a); . let b_universe = self.universe(b); . let c_universe = cmp::max(a_universe, b_universe); 220 ( 0.00%) let c = self.new_region_var(c_universe, MiscVariable(origin.span())); . self.combine_map(t).insert(vars, c); 44 ( 0.00%) self.undo_log.push(AddCombination(t, vars)); 220 ( 0.00%) let new_r = tcx.mk_region(ReVar(c)); 352 ( 0.00%) for old_r in [a, b] { 88 ( 0.00%) match t { 748 ( 0.00%) Glb => self.make_subregion(origin.clone(), new_r, old_r), . Lub => self.make_subregion(origin.clone(), old_r, new_r), . } . } . debug!("combine_vars() c={:?}", c); . new_r 396 ( 0.00%) } . . pub fn universe(&self, region: Region<'tcx>) -> ty::UniverseIndex { 21,160 ( 0.00%) match *region { . ty::ReStatic | ty::ReErased | ty::ReFree(..) | ty::ReEarlyBound(..) => { . ty::UniverseIndex::ROOT . } . ty::ReEmpty(ui) => ui, . ty::RePlaceholder(placeholder) => placeholder.universe, 2,709 ( 0.00%) ty::ReVar(vid) => self.var_universe(vid), . ty::ReLateBound(..) => bug!("universe(): encountered bound region {:?}", region), . } . } . 4,650 ( 0.00%) pub fn vars_since_snapshot( . &self, . value_count: usize, . ) -> (Range, Vec) { . let range = RegionVid::from(value_count)..RegionVid::from(self.unification_table.len()); 5,580 ( 0.00%) ( . range.clone(), . (range.start.index()..range.end.index()) . .map(|index| self.var_infos[ty::RegionVid::from(index)].origin) . .collect(), . ) 5,580 ( 0.00%) } . . /// See `InferCtxt::region_constraints_added_in_snapshot`. 13,794 ( 0.00%) pub fn region_constraints_added_in_snapshot(&self, mark: &Snapshot<'tcx>) -> Option { 4,598 ( 0.00%) self.undo_log . .region_constraints_in_snapshot(mark) 2,365 ( 0.00%) .map(|&elt| match elt { 680 ( 0.00%) AddConstraint(constraint) => Some(constraint.involves_placeholders()), . _ => None, . }) . .max() . .unwrap_or(None) 18,392 ( 0.00%) } . . #[inline] . fn unification_table(&mut self) -> super::UnificationTable<'_, 'tcx, RegionVidKey<'tcx>> { 103,102 ( 0.00%) ut::UnificationTable::with_log(&mut self.storage.unification_table, self.undo_log) . } . } . . impl fmt::Debug for RegionSnapshot { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "RegionSnapshot") . } . } -- line 737 ---------------------------------------- -- line 750 ---------------------------------------- . match *self { . GenericKind::Param(ref p) => write!(f, "{}", p), . GenericKind::Projection(ref p) => write!(f, "{}", p), . } . } . } . . impl<'tcx> GenericKind<'tcx> { 770 ( 0.00%) pub fn to_ty(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 17,374 ( 0.00%) match *self { 1,355 ( 0.00%) GenericKind::Param(ref p) => p.to_ty(tcx), . GenericKind::Projection(ref p) => tcx.mk_projection(p.item_def_id, p.substs), . } 770 ( 0.00%) } . } . . impl<'tcx> VerifyBound<'tcx> { . pub fn must_hold(&self) -> bool { . match self { . VerifyBound::IfEq(..) => false, . VerifyBound::OutlivedBy(ty::ReStatic) => true, . VerifyBound::OutlivedBy(_) => false, -- line 771 ---------------------------------------- -- line 796 ---------------------------------------- . } . } . . impl<'tcx> RegionConstraintData<'tcx> { . /// Returns `true` if this region constraint data contains no constraints, and `false` . /// otherwise. . pub fn is_empty(&self) -> bool { . let RegionConstraintData { constraints, member_constraints, verifys, givens } = self; 1,203 ( 0.00%) constraints.is_empty() . && member_constraints.is_empty() . && verifys.is_empty() . && givens.is_empty() . } . } . . impl<'tcx> Rollback> for RegionConstraintStorage<'tcx> { 67,550 ( 0.00%) fn reverse(&mut self, undo: UndoLog<'tcx>) { 54,040 ( 0.00%) self.rollback_undo_entry(undo) 67,550 ( 0.00%) } . } 852,437 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/caching_source_map_view.rs -------------------------------------------------------------------------------- Ir -- line 27 ---------------------------------------- . impl CacheEntry { . #[inline] . fn update( . &mut self, . new_file_and_idx: Option<(Lrc, usize)>, . pos: BytePos, . time_stamp: usize, . ) { 17,253 ( 0.00%) if let Some((file, file_idx)) = new_file_and_idx { 4,474 ( 0.00%) self.file = file; 5,789 ( 0.00%) self.file_index = file_idx; . } . 11,611 ( 0.00%) let line_index = self.file.lookup_line(pos).unwrap(); . let line_bounds = self.file.line_bounds(line_index); 30,064 ( 0.00%) self.line_number = line_index + 1; 44,512 ( 0.00%) self.line = line_bounds; . self.touch(time_stamp); . } . . #[inline] . fn touch(&mut self, time_stamp: usize) { 638,795 ( 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> { 2,274 ( 0.00%) pub fn new(source_map: &'sm SourceMap) -> CachingSourceMapView<'sm> { . let files = source_map.files(); 1,137 ( 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, . }; . 5,685 ( 0.00%) CachingSourceMapView { . source_map, 7,959 ( 0.00%) line_cache: [entry.clone(), entry.clone(), entry], . time_stamp: 0, . } 4,548 ( 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)) . } . 2,284,709 ( 0.05%) pub fn span_data_to_lines_and_cols( . &mut self, . span_data: &SpanData, . ) -> Option<(Lrc, usize, BytePos, usize, BytePos)> { 1,305,548 ( 0.03%) self.time_stamp += 1; . . // Check if lo and hi are in the cached lines. 326,387 ( 0.01%) let lo_cache_idx = self.cache_entry_index(span_data.lo); 326,387 ( 0.01%) let hi_cache_idx = self.cache_entry_index(span_data.hi); . 625,022 ( 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 = { 624,816 ( 0.01%) let lo = &self.line_cache[lo_cache_idx as usize]; . let hi = &self.line_cache[hi_cache_idx as usize]; . 1,874,448 ( 0.04%) if lo.file_index != hi.file_index { . return None; . } . . ( 624,816 ( 0.01%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 312,408 ( 0.01%) hi.line_number, . span_data.hi - hi.line.start, . ) . }; . 312,408 ( 0.01%) self.line_cache[lo_cache_idx as usize].touch(self.time_stamp); 312,408 ( 0.01%) self.line_cache[hi_cache_idx as usize].touch(self.time_stamp); . 1,249,632 ( 0.03%) return Some(result); . } . . // No cache hit or cache hit for only one of span lo and hi. 27,752 ( 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. 111,556 ( 0.00%) let new_file_and_idx = if !file_contains(&self.line_cache[oldest].file, span_data.lo) { 11,840 ( 0.00%) let new_file_and_idx = self.file_for_position(span_data.lo)?; 14,208 ( 0.00%) if !file_contains(&new_file_and_idx.0, span_data.hi) { . return None; . } . 9,472 ( 0.00%) Some(new_file_and_idx) . } else { . let file = &self.line_cache[oldest].file; 34,833 ( 0.00%) if !file_contains(&file, span_data.hi) { . return None; . } . 34,833 ( 0.00%) None . }; . . // Update the cache entries. 69,895 ( 0.00%) let (lo_idx, hi_idx) = match (lo_cache_idx, hi_cache_idx) { . // Oldest cache entry is for span_data.lo line. . (-1, -1) => { . let lo = &mut self.line_cache[oldest]; . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); . 36,717 ( 0.00%) if !lo.line.contains(&span_data.hi) { . let new_file_and_idx = Some((lo.file.clone(), lo.file_index)); . let next_oldest = self.oldest_cache_entry_index_avoid(oldest); . let hi = &mut self.line_cache[next_oldest]; . hi.update(new_file_and_idx, span_data.hi, self.time_stamp); . (oldest, next_oldest) . } else { . (oldest, oldest) . } . } . // Oldest cache entry is for span_data.lo line. . (-1, _) => { . let lo = &mut self.line_cache[oldest]; . lo.update(new_file_and_idx, span_data.lo, self.time_stamp); 206 ( 0.00%) let hi = &mut self.line_cache[hi_cache_idx as usize]; 309 ( 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]; 1,637 ( 0.00%) hi.update(new_file_and_idx, span_data.hi, self.time_stamp); 3,274 ( 0.00%) let lo = &mut self.line_cache[lo_cache_idx as usize]; 6,548 ( 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. 27,958 ( 0.00%) assert!(span_data.lo >= lo.line.start); 13,979 ( 0.00%) assert!(span_data.lo <= lo.line.end); 27,958 ( 0.00%) assert!(span_data.hi >= hi.line.start); 13,979 ( 0.00%) assert!(span_data.hi <= hi.line.end); 69,895 ( 0.00%) assert!(lo.file.contains(span_data.lo)); 41,937 ( 0.00%) assert!(lo.file.contains(span_data.hi)); 41,937 ( 0.00%) assert_eq!(lo.file_index, hi.file_index); . 41,937 ( 0.00%) Some(( 13,979 ( 0.00%) lo.file.clone(), . lo.line_number, . span_data.lo - lo.line.start, 13,979 ( 0.00%) hi.line_number, . span_data.hi - hi.line.start, . )) 2,937,483 ( 0.06%) } . . fn cache_entry_index(&self, pos: BytePos) -> isize { . for (idx, cache_entry) in self.line_cache.iter().enumerate() { 3,872,810 ( 0.08%) 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() { 73,434 ( 0.00%) if self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp { . oldest = idx; . } . } . . oldest . } . . fn oldest_cache_entry_index_avoid(&self, avoid_idx: usize) -> usize { . let mut oldest = if avoid_idx != 0 { 0 } else { 1 }; . . for idx in 0..self.line_cache.len() { 17,005 ( 0.00%) if idx != avoid_idx 9,050 ( 0.00%) && self.line_cache[idx].time_stamp < self.line_cache[oldest].time_stamp . { . oldest = idx; . } . } . . oldest . } . 11,840 ( 0.00%) fn file_for_position(&self, pos: BytePos) -> Option<(Lrc, usize)> { 2,368 ( 0.00%) if !self.source_map.files().is_empty() { 4,736 ( 0.00%) let file_idx = self.source_map.lookup_source_file_idx(pos); . let file = &self.source_map.files()[file_idx]; . 18,944 ( 0.00%) if file_contains(file, pos) { . return Some((file.clone(), file_idx)); . } . } . . None 11,840 ( 0.00%) } . } . . #[inline] . fn file_contains(file: &SourceFile, pos: BytePos) -> bool { . // `SourceMap::lookup_source_file_idx` and `SourceFile::contains` both consider the position . // one past the end of a file to belong to it. Normally, that's what we want. But for the . // purposes of converting a byte position to a line and column number, we can't come up with a . // line and column number if the file is empty, because an empty file doesn't contain any -- line 290 ---------------------------------------- 3,474,151 ( 0.07%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/alloc/src/collections/btree/map.rs -------------------------------------------------------------------------------- Ir -- line 165 ---------------------------------------- . #[rustc_insignificant_dtor] . pub struct BTreeMap { . root: Option>, . length: usize, . } . . #[stable(feature = "btree_drop", since = "1.7.0")] . unsafe impl<#[may_dangle] K, #[may_dangle] V> Drop for BTreeMap { 2,131,348 ( 0.04%) fn drop(&mut self) { . drop(unsafe { ptr::read(self) }.into_iter()) 2,138,105 ( 0.04%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for BTreeMap { . fn clone(&self) -> BTreeMap { 42 ( 0.00%) fn clone_subtree<'a, K: Clone, V: Clone>( . node: NodeRef, K, V, marker::LeafOrInternal>, . ) -> BTreeMap . where . K: 'a, . V: 'a, . { 5 ( 0.00%) match node.force() { . Leaf(leaf) => { 15 ( 0.00%) let mut out_tree = BTreeMap { root: Some(Root::new()), length: 0 }; . . { . let root = out_tree.root.as_mut().unwrap(); // unwrap succeeds because we just wrapped . let mut out_node = match root.borrow_mut().force() { . Leaf(leaf) => leaf, . Internal(_) => unreachable!(), . }; . . let mut in_edge = leaf.first_edge(); . while let Ok(kv) = in_edge.right_kv() { . let (k, v) = kv.into_kv(); . in_edge = kv.right_edge(); . 13 ( 0.00%) out_node.push(k.clone(), v.clone()); 33 ( 0.00%) out_tree.length += 1; . } . } . 23 ( 0.00%) out_tree . } . Internal(internal) => { . let mut out_tree = clone_subtree(internal.first_edge().descend()); . . { . let out_root = BTreeMap::ensure_is_owned(&mut out_tree.root); . let mut out_node = out_root.push_internal_level(); . let mut in_edge = internal.first_edge(); -- line 217 ---------------------------------------- -- line 235 ---------------------------------------- . out_node.push(k, v, subroot.unwrap_or_else(Root::new)); . out_tree.length += 1 + sublength; . } . } . . out_tree . } . } 40 ( 0.00%) } . 6 ( 0.00%) if self.is_empty() { . BTreeMap::new() . } else { 14 ( 0.00%) clone_subtree(self.root.as_ref().unwrap().reborrow()) // unwrap succeeds because not empty . } . } . } . . impl super::Recover for BTreeMap . where . K: Borrow + Ord, . Q: Ord, -- line 256 ---------------------------------------- -- line 515 ---------------------------------------- . /// . /// // entries can now be inserted into the empty map . /// map.insert(1, "a"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")] . #[must_use] . pub const fn new() -> BTreeMap { 395,217 ( 0.01%) BTreeMap { root: None, length: 0 } . } . . /// Clears the map, removing all elements. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 531 ---------------------------------------- -- line 560 ---------------------------------------- . /// assert_eq!(map.get(&2), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn get(&self, key: &Q) -> Option<&V> . where . K: Borrow + Ord, . Q: Ord, . { 115 ( 0.00%) let root_node = self.root.as_ref()?.reborrow(); 264 ( 0.00%) match root_node.search_tree(key) { 4 ( 0.00%) Found(handle) => Some(handle.into_kv().1), . GoDown(_) => None, . } . } . . /// Returns the key-value pair corresponding to the supplied key. . /// . /// The supplied key may be any borrowed form of the map's key type, but the ordering . /// on the borrowed form *must* match the ordering on the key type. -- line 578 ---------------------------------------- -- line 848 ---------------------------------------- . /// assert_eq!(map.insert(37, "a"), None); . /// assert_eq!(map.is_empty(), false); . /// . /// map.insert(37, "b"); . /// assert_eq!(map.insert(37, "c"), Some("b")); . /// assert_eq!(map[&37], "c"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 1,628 ( 0.00%) pub fn insert(&mut self, key: K, value: V) -> Option . where . K: Ord, . { . match self.entry(key) { . Occupied(mut entry) => Some(entry.insert(value)), . Vacant(entry) => { 1,640 ( 0.00%) entry.insert(value); 2 ( 0.00%) None . } . } 1,092 ( 0.00%) } . . /// Tries to insert a key-value pair into the map, and returns . /// a mutable reference to the value in the entry. . /// . /// If the map already had this key present, nothing is updated, and . /// an error containing the occupied entry and the value is returned. . /// . /// # Examples -- line 875 ---------------------------------------- -- line 914 ---------------------------------------- . /// use std::collections::BTreeMap; . /// . /// let mut map = BTreeMap::new(); . /// map.insert(1, "a"); . /// assert_eq!(map.remove(&1), Some("a")); . /// assert_eq!(map.remove(&1), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 62,816 ( 0.00%) pub fn remove(&mut self, key: &Q) -> Option . where . K: Borrow + Ord, . Q: Ord, . { 39,260 ( 0.00%) self.remove_entry(key).map(|(_, v)| v) 70,668 ( 0.00%) } . . /// Removes a key from the map, returning the stored key and value if the key . /// was previously in the map. . /// . /// The key may be any borrowed form of the map's key type, but the ordering . /// on the borrowed form *must* match the ordering on the key type. . /// . /// # Examples -- line 936 ---------------------------------------- -- line 947 ---------------------------------------- . /// ``` . #[stable(feature = "btreemap_remove_entry", since = "1.45.0")] . pub fn remove_entry(&mut self, key: &Q) -> Option<(K, V)> . where . K: Borrow + Ord, . Q: Ord, . { . let (map, dormant_map) = DormantMutRef::new(self); 7,856 ( 0.00%) let root_node = map.root.as_mut()?.borrow_mut(); 39,280 ( 0.00%) match root_node.search_tree(key) { . Found(handle) => { 15,704 ( 0.00%) Some(OccupiedEntry { handle, dormant_map, _marker: PhantomData }.remove_entry()) 7,852 ( 0.00%) } . GoDown(_) => None, . } . } . . /// Retains only the elements specified by the predicate. . /// . /// In other words, remove all pairs `(k, v)` such that `f(&k, &mut v)` returns `false`. . /// The elements are visited in ascending key order. -- line 967 ---------------------------------------- -- line 1135 ---------------------------------------- . /// // count the number of occurrences of letters in the vec . /// for x in ["a", "b", "a", "c", "a", "b"] { . /// *count.entry(x).or_insert(0) += 1; . /// } . /// . /// assert_eq!(count["a"], 3); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 10 ( 0.00%) pub fn entry(&mut self, key: K) -> Entry<'_, K, V> . where . K: Ord, . { . // FIXME(@porglezomp) Avoid allocating if we don't insert . let (map, dormant_map) = DormantMutRef::new(self); . let root_node = Self::ensure_is_owned(&mut map.root).borrow_mut(); 74,159 ( 0.00%) match root_node.search_tree(&key) { 552 ( 0.00%) Found(handle) => Occupied(OccupiedEntry { handle, dormant_map, _marker: PhantomData }), . GoDown(handle) => { 23,800 ( 0.00%) Vacant(VacantEntry { key, handle, dormant_map, _marker: PhantomData }) . } . } 9 ( 0.00%) } . . /// Splits the collection into two at the given key. Returns everything after the given key, . /// including the key. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 1164 ---------------------------------------- -- line 1307 ---------------------------------------- . } . . /// Makes a `BTreeMap` from a sorted iterator. . pub(crate) fn bulk_build_from_sorted_iter(iter: I) -> Self . where . K: Ord, . I: IntoIterator, . { 2 ( 0.00%) let mut root = Root::new(); 1 ( 0.00%) let mut length = 0; 5 ( 0.00%) root.bulk_push(DedupSortedIter::new(iter.into_iter()), &mut length); 2 ( 0.00%) BTreeMap { root: Some(root), length } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, K, V> IntoIterator for &'a BTreeMap { . type Item = (&'a K, &'a V); . type IntoIter = Iter<'a, K, V>; . -- line 1326 ---------------------------------------- -- line 1328 ---------------------------------------- . self.iter() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, K: 'a, V: 'a> Iterator for Iter<'a, K, V> { . type Item = (&'a K, &'a V); . 10 ( 0.00%) fn next(&mut self) -> Option<(&'a K, &'a V)> { 143,257 ( 0.00%) if self.length == 0 { . None . } else { 73,381 ( 0.00%) self.length -= 1; . Some(unsafe { self.range.next_unchecked() }) . } 16 ( 0.00%) } . . fn size_hint(&self) -> (usize, Option) { . (self.length, Some(self.length)) . } . . fn last(mut self) -> Option<(&'a K, &'a V)> { . self.next_back() . } -- line 1351 ---------------------------------------- -- line 1460 ---------------------------------------- . . #[stable(feature = "rust1", since = "1.0.0")] . impl IntoIterator for BTreeMap { . type Item = (K, V); . type IntoIter = IntoIter; . . fn into_iter(self) -> IntoIter { . let mut me = ManuallyDrop::new(self); 641,210 ( 0.01%) if let Some(root) = me.root.take() { . let full_range = root.into_dying().full_range(); . 6 ( 0.00%) IntoIter { range: full_range, length: me.length } . } else { 374,763 ( 0.01%) IntoIter { range: LazyLeafRange::none(), length: 0 } . } . } . } . . #[stable(feature = "btree_drop", since = "1.7.0")] . impl Drop for IntoIter { 3,862 ( 0.00%) fn drop(&mut self) { . struct DropGuard<'a, K, V>(&'a mut IntoIter); . . impl<'a, K, V> Drop for DropGuard<'a, K, V> { . fn drop(&mut self) { . // Continue the same loop we perform below. This only runs when unwinding, so we . // don't have to care about panics this time (they'll abort). . while let Some(kv) = self.0.dying_next() { . // SAFETY: we consume the dying handle immediately. . unsafe { kv.drop_key_val() }; . } . } . } . 132,670 ( 0.00%) while let Some(kv) = self.dying_next() { . let guard = DropGuard(self); . // SAFETY: we don't touch the tree before consuming the dying handle. 11,093 ( 0.00%) unsafe { kv.drop_key_val() }; . mem::forget(guard); . } 3,862 ( 0.00%) } . } . . impl IntoIter { . /// Core of a `next` method returning a dying KV handle, . /// invalidated by further calls to this function and some others. 179,801 ( 0.00%) fn dying_next( . &mut self, . ) -> Option, marker::KV>> { 711,717 ( 0.01%) if self.length == 0 { . self.range.deallocating_end(); 27,888 ( 0.00%) None . } else { 37,842 ( 0.00%) self.length -= 1; 49,082 ( 0.00%) Some(unsafe { self.range.deallocating_next_unchecked() }) . } 179,798 ( 0.00%) } . . /// Core of a `next_back` method returning a dying KV handle, . /// invalidated by further calls to this function and some others. . fn dying_next_back( . &mut self, . ) -> Option, marker::KV>> { . if self.length == 0 { . self.range.deallocating_end(); -- line 1524 ---------------------------------------- -- line 1529 ---------------------------------------- . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Iterator for IntoIter { . type Item = (K, V); . 1,652 ( 0.00%) fn next(&mut self) -> Option<(K, V)> { . // SAFETY: we consume the dying handle immediately. . self.dying_next().map(unsafe { |kv| kv.into_key_val() }) 1,888 ( 0.00%) } . . fn size_hint(&self) -> (usize, Option) { 102 ( 0.00%) (self.length, Some(self.length)) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl DoubleEndedIterator for IntoIter { . fn next_back(&mut self) -> Option<(K, V)> { . // SAFETY: we consume the dying handle immediately. . self.dying_next_back().map(unsafe { |kv| kv.into_key_val() }) -- line 1551 ---------------------------------------- -- line 1562 ---------------------------------------- . #[stable(feature = "fused", since = "1.26.0")] . impl FusedIterator for IntoIter {} . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, K, V> Iterator for Keys<'a, K, V> { . type Item = &'a K; . . fn next(&mut self) -> Option<&'a K> { 8 ( 0.00%) self.inner.next().map(|(k, _)| k) . } . . fn size_hint(&self) -> (usize, Option) { . self.inner.size_hint() . } . . fn last(mut self) -> Option<&'a K> { . self.next_back() -- line 1578 ---------------------------------------- -- line 2089 ---------------------------------------- . /// println!("{}: {}", key, value); . /// } . /// . /// let (first_key, first_value) = map.iter().next().unwrap(); . /// assert_eq!((*first_key, *first_value), (1, "a")); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn iter(&self) -> Iter<'_, K, V> { 97,158 ( 0.00%) if let Some(root) = &self.root { . let full_range = root.reborrow().full_range(); . 17 ( 0.00%) Iter { range: full_range, length: self.length } . } else { 6 ( 0.00%) Iter { range: LazyLeafRange::none(), length: 0 } . } . } . . /// Gets a mutable iterator over the entries of the map, sorted by key. . /// . /// # Examples . /// . /// Basic usage: -- line 2110 ---------------------------------------- -- line 2149 ---------------------------------------- . /// a.insert(2, "b"); . /// a.insert(1, "a"); . /// . /// let keys: Vec<_> = a.keys().cloned().collect(); . /// assert_eq!(keys, [1, 2]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn keys(&self) -> Keys<'_, K, V> { 1,395 ( 0.00%) Keys { inner: self.iter() } . } . . /// Gets an iterator over the values of the map, in order by key. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 2165 ---------------------------------------- -- line 2217 ---------------------------------------- . /// assert_eq!(a.len(), 0); . /// a.insert(1, "a"); . /// assert_eq!(a.len(), 1); . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")] . pub const fn len(&self) -> usize { 4 ( 0.00%) self.length . } . . /// Returns `true` if the map contains no elements. . /// . /// # Examples . /// . /// Basic usage: . /// -- line 2233 ---------------------------------------- -- line 2238 ---------------------------------------- . /// assert!(a.is_empty()); . /// a.insert(1, "a"); . /// assert!(!a.is_empty()); . /// ``` . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_unstable(feature = "const_btree_new", issue = "71835")] . pub const fn is_empty(&self) -> bool { 12,419 ( 0.00%) self.len() == 0 . } . . /// If the root node is the empty (non-allocated) root node, allocate our . /// own node. Is an associated function to avoid borrowing the entire BTreeMap. . fn ensure_is_owned(root: &mut Option>) -> &mut Root { . root.get_or_insert_with(Root::new) . } . } -- line 2254 ---------------------------------------- 73,064 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/fmt/mod.rs -------------------------------------------------------------------------------- Ir -- line 177 ---------------------------------------- . /// f.write_fmt(format_args!("{}", s)) . /// } . /// . /// let mut buf = String::new(); . /// writer(&mut buf, "world").unwrap(); . /// assert_eq!(&buf, "world"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 20 ( 0.00%) fn write_fmt(mut self: &mut Self, args: Arguments<'_>) -> Result { 26,650 ( 0.00%) write(&mut self, args) 20 ( 0.00%) } . } . . #[stable(feature = "fmt_write_blanket_impl", since = "1.4.0")] . impl Write for &mut W { 40,236 ( 0.00%) fn write_str(&mut self, s: &str) -> Result { 5,768 ( 0.00%) (**self).write_str(s) 40,236 ( 0.00%) } . 79 ( 0.00%) fn write_char(&mut self, c: char) -> Result { 79 ( 0.00%) (**self).write_char(c) 237 ( 0.00%) } . . fn write_fmt(&mut self, args: Arguments<'_>) -> Result { . (**self).write_fmt(args) . } . } . . /// Configuration for formatting. . /// -- line 206 ---------------------------------------- -- line 228 ---------------------------------------- . /// . /// This can be used as a micro-optimization in cases where a full `Arguments` . /// structure (as created by `format_args!`) is not necessary; `Arguments` . /// is a little more expensive to use in simple formatting scenarios. . /// . /// Currently not intended for use outside of the standard library. . #[unstable(feature = "fmt_internals", reason = "internal to standard library", issue = "none")] . #[doc(hidden)] 307,898 ( 0.01%) pub fn new(buf: &'a mut (dyn Write + 'a)) -> Formatter<'a> { 1,768,104 ( 0.04%) Formatter { . flags: 0, . fill: ' ', . align: rt::v1::Alignment::Unknown, . width: None, . precision: None, . buf, . } 153,949 ( 0.00%) } . } . . // NB. Argument is essentially an optimized partially applied formatting function, . // equivalent to `exists T.(&T, fn(&T, &mut Formatter<'_>) -> Result`. . . extern "C" { . type Opaque; . } -- line 253 ---------------------------------------- -- line 357 ---------------------------------------- . #[doc(hidden)] . #[inline] . #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")] . #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")] . pub const fn new_v1(pieces: &'a [&'static str], args: &'a [ArgumentV1<'a>]) -> Arguments<'a> { . if pieces.len() < args.len() || pieces.len() > args.len() + 1 { . panic!("invalid args"); . } 574,460 ( 0.01%) Arguments { pieces, fmt: None, args } . } . . /// This function is used to specify nonstandard formatting parameters. . /// . /// An `UnsafeArg` is required because the following invariants must be held . /// in order for this function to be safe: . /// 1. The `pieces` slice must be at least as long as `fmt`. . /// 2. Every [`rt::v1::Argument::position`] value within `fmt` must be a -- line 373 ---------------------------------------- -- line 379 ---------------------------------------- . #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")] . #[rustc_const_unstable(feature = "const_fmt_arguments_new", issue = "none")] . pub const fn new_v1_formatted( . pieces: &'a [&'static str], . args: &'a [ArgumentV1<'a>], . fmt: &'a [rt::v1::Argument], . _unsafe_arg: UnsafeArg, . ) -> Arguments<'a> { 86,610 ( 0.00%) Arguments { pieces, fmt: Some(fmt), args } . } . . /// Estimates the length of the formatted text. . /// . /// This is intended to be used for setting initial `String` capacity . /// when using `format!`. Note: this is neither the lower nor upper bound. . #[doc(hidden)] . #[inline] . #[unstable(feature = "fmt_internals", reason = "internal to format_args!", issue = "none")] . pub fn estimated_capacity(&self) -> usize { . let pieces_length: usize = self.pieces.iter().map(|x| x.len()).sum(); . 2,655 ( 0.00%) if self.args.is_empty() { . pieces_length 10,620 ( 0.00%) } else if !self.pieces.is_empty() && self.pieces[0].is_empty() && pieces_length < 16 { . // If the format string starts with an argument, . // don't preallocate anything, unless length . // of pieces is significant. . 0 . } else { . // There are some arguments, so any additional push . // will reallocate the string. To avoid that, . // we're "pre-doubling" the capacity here. -- line 410 ---------------------------------------- -- line 1146 ---------------------------------------- . /// let mut output = String::new(); . /// write!(&mut output, "Hello {}!", "world") . /// .expect("Error occurred while trying to write in String"); . /// assert_eq!(output, "Hello world!"); . /// ``` . /// . /// [`write!`]: crate::write! . #[stable(feature = "rust1", since = "1.0.0")] 1,266,615 ( 0.03%) pub fn write(output: &mut dyn Write, args: Arguments<'_>) -> Result { . let mut formatter = Formatter::new(output); . let mut idx = 0; . 422,205 ( 0.01%) match args.fmt { . None => { . // We can use default formatting parameters for all arguments. 140,734 ( 0.00%) for (i, arg) in args.args.iter().enumerate() { . // SAFETY: args.args and args.pieces come from the same Arguments, . // which guarantees the indexes are always within bounds. . let piece = unsafe { args.pieces.get_unchecked(i) }; 282,142 ( 0.01%) if !piece.is_empty() { 15,618 ( 0.00%) formatter.buf.write_str(*piece)?; . } 705,355 ( 0.01%) (arg.formatter)(arg.value, &mut formatter)?; . idx += 1; . } . } . Some(fmt) => { . // Every spec has a corresponding argument that is preceded by . // a string piece. . for (i, arg) in fmt.iter().enumerate() { . // SAFETY: fmt and args.pieces come from the same Arguments, . // which guarantees the indexes are always within bounds. . let piece = unsafe { args.pieces.get_unchecked(i) }; 4 ( 0.00%) if !piece.is_empty() { 12 ( 0.00%) formatter.buf.write_str(*piece)?; . } . // SAFETY: arg and args.args come from the same Arguments, . // which guarantees the indexes are always within bounds. 6 ( 0.00%) unsafe { run(&mut formatter, arg, args.args) }?; . idx += 1; . } . } . } . . // There can be only one trailing string piece left. 140,735 ( 0.00%) if let Some(piece) = args.pieces.get(idx) { 2,681 ( 0.00%) formatter.buf.write_str(*piece)?; . } . . Ok(()) 1,125,880 ( 0.02%) } . . unsafe fn run(fmt: &mut Formatter<'_>, arg: &rt::v1::Argument, args: &[ArgumentV1<'_>]) -> Result { 4 ( 0.00%) fmt.fill = arg.format.fill; 4 ( 0.00%) fmt.align = arg.format.align; 4 ( 0.00%) fmt.flags = arg.format.flags; . // SAFETY: arg and args come from the same Arguments, . // which guarantees the indexes are always within bounds. . unsafe { 8 ( 0.00%) fmt.width = getcount(args, &arg.format.width); 8 ( 0.00%) fmt.precision = getcount(args, &arg.format.precision); . } . . // Extract the correct argument . debug_assert!(arg.position < args.len()); . // SAFETY: arg and args come from the same Arguments, . // which guarantees its index is always within bounds. 2 ( 0.00%) let value = unsafe { args.get_unchecked(arg.position) }; . . // Then actually do some printing 6 ( 0.00%) (value.formatter)(value.value, fmt) . } . . unsafe fn getcount(args: &[ArgumentV1<'_>], cnt: &rt::v1::Count) -> Option { 14 ( 0.00%) match *cnt { . rt::v1::Count::Is(n) => Some(n), . rt::v1::Count::Implied => None, . rt::v1::Count::Param(i) => { . debug_assert!(i < args.len()); . // SAFETY: cnt and args come from the same Arguments, . // which guarantees this index is always within bounds. . unsafe { args.get_unchecked(i).as_usize() } . } -- line 1228 ---------------------------------------- -- line 1312 ---------------------------------------- . /// . /// assert_eq!(&format!("{}", Foo::new(2)), "2"); . /// assert_eq!(&format!("{}", Foo::new(-1)), "-1"); . /// assert_eq!(&format!("{}", Foo::new(0)), "0"); . /// assert_eq!(&format!("{:#}", Foo::new(-1)), "-Foo 1"); . /// assert_eq!(&format!("{:0>#8}", Foo::new(-1)), "00-Foo 1"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 174,228 ( 0.00%) pub fn pad_integral(&mut self, is_nonnegative: bool, prefix: &str, buf: &str) -> Result { . let mut width = buf.len(); . . let mut sign = None; 29,038 ( 0.00%) if !is_nonnegative { . sign = Some('-'); . width += 1; 14,519 ( 0.00%) } else if self.sign_plus() { . sign = Some('+'); 14,519 ( 0.00%) width += 1; . } . 14,519 ( 0.00%) let prefix = if self.alternate() { . width += prefix.chars().count(); . Some(prefix) . } else { . None . }; . . // Writes the sign if it exists, and then the prefix if it was requested . #[inline(never)] 87,114 ( 0.00%) fn write_prefix(f: &mut Formatter<'_>, sign: Option, prefix: Option<&str>) -> Result { 29,038 ( 0.00%) if let Some(c) = sign { . f.buf.write_char(c)?; . } 29,038 ( 0.00%) if let Some(prefix) = prefix { f.buf.write_str(prefix) } else { Ok(()) } 58,076 ( 0.00%) } . . // The `width` field is more of a `min-width` parameter at this point. 29,038 ( 0.00%) match self.width { . // If there's no minimum length requirements then we can just . // write the bytes. . None => { 101,626 ( 0.00%) write_prefix(self, sign, prefix)?; 72,590 ( 0.00%) self.buf.write_str(buf) . } . // Check if we're over the minimum width, if so then we can also . // just write the bytes. 3 ( 0.00%) Some(min) if width >= min => { 8 ( 0.00%) write_prefix(self, sign, prefix)?; 3 ( 0.00%) self.buf.write_str(buf) . } . // The sign and prefix goes before the padding if the fill character . // is zero . Some(min) if self.sign_aware_zero_pad() => { . let old_fill = crate::mem::replace(&mut self.fill, '0'); . let old_align = crate::mem::replace(&mut self.align, rt::v1::Alignment::Right); . write_prefix(self, sign, prefix)?; . let post_padding = self.padding(min - width, rt::v1::Alignment::Right)?; -- line 1368 ---------------------------------------- -- line 1406 ---------------------------------------- . /// formatter.pad("Foo") . /// } . /// } . /// . /// assert_eq!(&format!("{:<4}", Foo), "Foo "); . /// assert_eq!(&format!("{:0>4}", Foo), "0Foo"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 1,274,607 ( 0.03%) pub fn pad(&mut self, s: &str) -> Result { . // Make sure there's a fast path up front 424,869 ( 0.01%) if self.width.is_none() && self.precision.is_none() { . return self.buf.write_str(s); . } . // The `precision` field can be interpreted as a `max-width` for the . // string being formatted. . let s = if let Some(max) = self.precision { . // If our string is longer that the precision, then we must have . // truncation. However other flags like `fill`, `width` and `align` . // must act as always. -- line 1424 ---------------------------------------- -- line 1591 ---------------------------------------- . /// } . /// } . /// . /// assert_eq!(&format!("{}", Foo), "Foo"); . /// assert_eq!(&format!("{:0>8}", Foo), "Foo"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . pub fn write_str(&mut self, data: &str) -> Result { 3,105 ( 0.00%) self.buf.write_str(data) . } . . /// Writes some formatted information into this instance. . /// . /// # Examples . /// . /// ``` . /// use std::fmt; -- line 1607 ---------------------------------------- -- line 1613 ---------------------------------------- . /// formatter.write_fmt(format_args!("Foo {}", self.0)) . /// } . /// } . /// . /// assert_eq!(&format!("{}", Foo(-1)), "Foo -1"); . /// assert_eq!(&format!("{:0>8}", Foo(2)), "Foo 2"); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] 138,047 ( 0.00%) pub fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result { 1,656,564 ( 0.03%) write(self.buf, fmt) 276,094 ( 0.01%) } . . /// Flags for formatting . #[must_use] . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_deprecated( . since = "1.24.0", . reason = "use the `sign_plus`, `sign_minus`, `alternate`, \ . or `sign_aware_zero_pad` methods instead" -- line 1631 ---------------------------------------- -- line 1793 ---------------------------------------- . /// } . /// . /// assert_eq!(&format!("{:+}", Foo(23)), "Foo(+23)"); . /// assert_eq!(&format!("{}", Foo(23)), "Foo(23)"); . /// ``` . #[must_use] . #[stable(feature = "fmt_flags", since = "1.5.0")] . pub fn sign_plus(&self) -> bool { 43,557 ( 0.00%) self.flags & (1 << FlagV1::SignPlus as u32) != 0 . } . . /// Determines if the `-` flag was specified. . /// . /// # Examples . /// . /// ``` . /// use std::fmt; -- line 1809 ---------------------------------------- -- line 1850 ---------------------------------------- . /// } . /// . /// assert_eq!(&format!("{:#}", Foo(23)), "Foo(23)"); . /// assert_eq!(&format!("{}", Foo(23)), "23"); . /// ``` . #[must_use] . #[stable(feature = "fmt_flags", since = "1.5.0")] . pub fn alternate(&self) -> bool { 14,519 ( 0.00%) self.flags & (1 << FlagV1::Alternate as u32) != 0 . } . . /// Determines if the `0` flag was specified. . /// . /// # Examples . /// . /// ``` . /// use std::fmt; -- line 1866 ---------------------------------------- -- line 2076 ---------------------------------------- . . #[stable(since = "1.2.0", feature = "formatter_write")] . impl Write for Formatter<'_> { . fn write_str(&mut self, s: &str) -> Result { . self.buf.write_str(s) . } . . fn write_char(&mut self, c: char) -> Result { 6,114 ( 0.00%) self.buf.write_char(c) . } . . fn write_fmt(&mut self, args: Arguments<'_>) -> Result { . write(self.buf, args) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] -- line 2092 ---------------------------------------- -- line 2098 ---------------------------------------- . . // Implementations of the core formatting traits . . macro_rules! fmt_refs { . ($($tr:ident),*) => { . $( . #[stable(feature = "rust1", since = "1.0.0")] . impl $tr for &T { 8,424 ( 0.00%) fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) } . } . #[stable(feature = "rust1", since = "1.0.0")] . impl $tr for &mut T { . fn fmt(&self, f: &mut Formatter<'_>) -> Result { $tr::fmt(&**self, f) } . } . )* . } . } -- line 2114 ---------------------------------------- -- line 2166 ---------------------------------------- . } . f.write_str(&self[from..])?; . f.write_char('"') . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Display for str { 424,863 ( 0.01%) fn fmt(&self, f: &mut Formatter<'_>) -> Result { 283,250 ( 0.01%) f.pad(self) . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Debug for char { . fn fmt(&self, f: &mut Formatter<'_>) -> Result { . f.write_char('\'')?; . for c in self.escape_debug_ext(EscapeDebugExtArgs { -- line 2183 ---------------------------------------- -- line 2188 ---------------------------------------- . f.write_char(c)? . } . f.write_char('\'') . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Display for char { 22 ( 0.00%) fn fmt(&self, f: &mut Formatter<'_>) -> Result { 44 ( 0.00%) if f.width.is_none() && f.precision.is_none() { 22 ( 0.00%) f.write_char(*self) . } else { . f.pad(self.encode_utf8(&mut [0; 4])) . } . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl Pointer for *const T { -- line 2206 ---------------------------------------- 2,601,095 ( 0.05%) -------------------------------------------------------------------------------- -- 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) { 855 ( 0.00%) let (int, signed) = match *ty.kind() { 1,995 ( 0.00%) 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. 1,320 ( 0.00%) pub fn wrap_incr(self, tcx: TyCtxt<'tcx>) -> Self { 1,929 ( 0.00%) self.checked_add(tcx, 1).0 528 ( 0.00%) } 2,565 ( 0.00%) 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; 1,140 ( 0.00%) assert!(n < (i128::MAX as u128)); . let n = n as i128; 1,995 ( 0.00%) let oflo = val > max - n; 1,140 ( 0.00%) 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) . }; 1,140 ( 0.00%) (Self { val, ty: self.ty }, oflo) 2,565 ( 0.00%) } . } . . 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> { 3,320 ( 0.00%) 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, . } 371 ( 0.00%) } . . fn initial_discriminant<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Discr<'tcx> { . Discr { val: 0, ty: self.to_ty(tcx) } 792 ( 0.00%) } . 44 ( 0.00%) fn disr_incr<'tcx>(&self, tcx: TyCtxt<'tcx>, val: Option>) -> Option> { 80 ( 0.00%) if let Some(val) = val { 24 ( 0.00%) assert_eq!(self.to_ty(tcx), val.ty); 108 ( 0.00%) let (new, oflo) = val.checked_add(tcx, 1); 12 ( 0.00%) if oflo { None } else { Some(new) } . } else { . Some(self.initial_discriminant(tcx)) . } 44 ( 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() . } . 154 ( 0.00%) pub fn has_error_field(self, ty: Ty<'tcx>) -> bool { 88 ( 0.00%) if let ty::Adt(def, substs) = *ty.kind() { . for field in def.all_fields() { 186 ( 0.00%) let field_ty = field.ty(self, substs); 186 ( 0.00%) if let Error(_) = field_ty.kind() { . return true; . } . } . } . false 176 ( 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. 15,408 ( 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) 13,696 ( 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. 36,212 ( 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)) 29,628 ( 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> { 25,020 ( 0.00%) let recursion_limit = self.recursion_limit(); . for iteration in 0.. { 5,484 ( 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), . ); . } 37,019 ( 0.00%) match *ty.kind() { 548 ( 0.00%) ty::Adt(def, substs) => { 1,096 ( 0.00%) if !def.is_struct() { . break; . } 533 ( 0.00%) match def.non_enum_variant().fields.last() { 1,416 ( 0.00%) Some(f) => ty = f.ty(self, substs), . None => break, . } . } . 19 ( 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. 8,220 ( 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) . }) 5,480 ( 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 { 6,576 ( 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. 828 ( 0.00%) pub fn calculate_dtor( . self, . adt_did: DefId, . validate: impl Fn(Self, DefId) -> Result<(), ErrorReported>, . ) -> Option { 345 ( 0.00%) let drop_trait = self.lang_items().drop_trait()?; . self.ensure().coherent_trait(drop_trait); . 69 ( 0.00%) let ty = self.type_of(adt_did); 663 ( 0.00%) let (did, constness) = self.find_map_relevant_impl(drop_trait, ty, |impl_did| { 36 ( 0.00%) if let Some(item_id) = self.associated_item_def_ids(impl_did).first() { . if validate(self, impl_did).is_ok() { 42 ( 0.00%) return Some((*item_id, self.impl_constness(impl_did))); . } . } . None 78 ( 0.00%) })?; . . Some(ty::Destructor { did, constness }) 690 ( 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`. 759 ( 0.00%) pub fn destructor_constraints(self, def: &'tcx ty::AdtDef) -> Vec> { 357 ( 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 371 ---------------------------------------- . // . // impl<#[may_dangle] P0, P1, P2> Drop for S . // . // We want to return the parameters (X, Y). For that, we match . // up the item-substs with the substs on the impl ADT, . // , and then look up which of the impl substs refer to . // parameters marked as pure. . 12 ( 0.00%) let impl_substs = match *self.type_of(impl_def_id).kind() { 42 ( 0.00%) ty::Adt(def_, substs) if def_ == def => substs, . _ => bug!(), . }; . 12 ( 0.00%) let item_substs = match *self.type_of(def.did).kind() { 42 ( 0.00%) ty::Adt(def_, substs) if def_ == def => substs, . _ => bug!(), . }; . . let result = iter::zip(item_substs, impl_substs) . .filter(|&(_, k)| { 22 ( 0.00%) match k.unpack() { . GenericArgKind::Lifetime(&ty::RegionKind::ReEarlyBound(ref ebr)) => { . !impl_generics.region_param(ebr, self).pure_wrt_drop . } . GenericArgKind::Type(&ty::TyS { kind: ty::Param(ref pt), .. }) => { 33 ( 0.00%) !impl_generics.type_param(pt, self).pure_wrt_drop . } . GenericArgKind::Const(&ty::Const { . val: ty::ConstKind::Param(ref pc), .. . }) => !impl_generics.const_param(pc, self).pure_wrt_drop, . GenericArgKind::Lifetime(_) . | GenericArgKind::Type(_) . | GenericArgKind::Const(_) => { . // Not a type, const or region param: this should be reported -- line 404 ---------------------------------------- -- line 405 ---------------------------------------- . // as an error. . false . } . } . }) . .map(|(item_param, _)| item_param) . .collect(); . debug!("destructor_constraint({:?}) = {:?}", def.did, result); 30 ( 0.00%) result 678 ( 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. 1,401 ( 0.00%) pub fn is_closure(self, def_id: DefId) -> bool { 7,005 ( 0.00%) matches!(self.def_kind(def_id), DefKind::Closure | DefKind::Generator) 2,802 ( 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. 802 ( 0.00%) pub fn is_typeck_child(self, def_id: DefId) -> bool { 12,916 ( 0.00%) matches!( 13,802 ( 0.00%) self.def_kind(def_id), . DefKind::Closure | DefKind::Generator | DefKind::InlineConst . ) 1,604 ( 0.00%) } . . /// Returns `true` if `def_id` refers to a trait (i.e., `trait Foo { ... }`). 1,253 ( 0.00%) pub fn is_trait(self, def_id: DefId) -> bool { 1,253 ( 0.00%) self.def_kind(def_id) == DefKind::Trait 2,506 ( 0.00%) } . . /// Returns `true` if `def_id` refers to a trait alias (i.e., `trait Foo = ...;`), . /// and `false` otherwise. 3,291 ( 0.00%) pub fn is_trait_alias(self, def_id: DefId) -> bool { 3,291 ( 0.00%) self.def_kind(def_id) == DefKind::TraitAlias 6,582 ( 0.00%) } . . /// Returns `true` if this `DefId` refers to the implicit constructor for . /// a tuple struct like `struct Foo(u32)`, and `false` otherwise. 198 ( 0.00%) pub fn is_constructor(self, def_id: DefId) -> bool { 6,414 ( 0.00%) matches!(self.def_kind(def_id), DefKind::Ctor(..)) 396 ( 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. 30,870 ( 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 24,696 ( 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. . /// . /// Note that the return value is a late-bound region and hence . /// wrapped in a binder. 306 ( 0.00%) pub fn closure_env_ty( . self, . closure_def_id: DefId, . closure_substs: SubstsRef<'tcx>, . env_region: ty::RegionKind, . ) -> Option> { . let closure_ty = self.mk_closure(closure_def_id, closure_substs); . let closure_kind_ty = closure_substs.as_closure().kind_ty(); 102 ( 0.00%) let closure_kind = closure_kind_ty.to_opt_closure_kind()?; 128 ( 0.00%) let env_ty = match closure_kind { 28 ( 0.00%) ty::ClosureKind::Fn => self.mk_imm_ref(self.mk_region(env_region), closure_ty), 154 ( 0.00%) ty::ClosureKind::FnMut => self.mk_mut_ref(self.mk_region(env_region), closure_ty), . ty::ClosureKind::FnOnce => closure_ty, . }; . Some(env_ty) 272 ( 0.00%) } . . /// Returns `true` if the node pointed to by `def_id` is a `static` item. 3,906 ( 0.00%) pub fn is_static(self, def_id: DefId) -> bool { . self.static_mutability(def_id).is_some() 4,464 ( 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> { 81 ( 0.00%) self.tcx . } . . fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 210 ( 0.00%) if let ty::Opaque(def_id, substs) = t.kind { . self.expand_opaque_ty(def_id, substs).unwrap_or(t) 105 ( 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. 5,210 ( 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)) 4,168 ( 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. 85,005 ( 0.00%) pub fn is_sized(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { 47,225 ( 0.00%) self.is_trivially_sized(tcx_at.tcx) || tcx_at.is_sized_raw(param_env.and(self)) 56,670 ( 0.00%) } . . /// 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. 12,440,898 ( 0.26%) pub fn is_freeze(&'tcx self, tcx_at: TyCtxtAt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { 6,911,610 ( 0.14%) self.is_trivially_freeze() || tcx_at.is_freeze_raw(param_env.and(self)) 8,293,932 ( 0.17%) } . . /// 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. 6,911,670 ( 0.14%) fn is_trivially_unpin(&self) -> bool { 6,919,890 ( 0.14%) 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), 3,288 ( 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, . } 9,676,338 ( 0.20%) } . . /// 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] 62,890 ( 0.00%) pub fn needs_drop(&'tcx self, tcx: TyCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>) -> bool { . // Avoid querying in simple cases. 1,701,535 ( 0.03%) match needs_drop_components(self, &tcx.data_layout) { . Err(AlwaysRequiresDrop) => true, 1,130,164 ( 0.02%) Ok(components) => { . let query_ty = match *components { 567,036 ( 0.01%) [] => return false, . // If we've got a single component, call the query with that . // to increase the chance that we hit the query cache. 976 ( 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)) . } . } 56,601 ( 0.00%) } . . /// 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 { 2,192 ( 0.00%) 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 888 ---------------------------------------- . // FIXME(ecstaticmorse): Maybe we should `bug` here? This should probably only be . // called for known, fully-monomorphized types. . Projection(_) | Opaque(..) | Param(_) | Bound(..) | Placeholder(_) | Infer(_) => false, . . Foreign(_) | GeneratorWitness(..) | Error(_) => false, . } . } . 610 ( 0.00%) pub fn same_type(a: Ty<'tcx>, b: Ty<'tcx>) -> bool { 488 ( 0.00%) match (&a.kind(), &b.kind()) { . (&Adt(did_a, substs_a), &Adt(did_b, substs_b)) => { 610 ( 0.00%) if did_a != did_b { . return false; . } . . substs_a.types().zip(substs_b.types()).all(|(a, b)| Self::same_type(a, b)) . } . _ => a == b, . } 732 ( 0.00%) } . . /// Peel off all reference types in this type until there are none left. . /// . /// 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` 633 ( 0.00%) pub fn peel_refs(&'tcx self) -> Ty<'tcx> { . let mut ty = self; 2,048 ( 0.00%) while let Ref(_, inner_ty, _) = ty.kind() { 261 ( 0.00%) ty = inner_ty; . } . ty 633 ( 0.00%) } . . pub fn outer_exclusive_binder(&'tcx self) -> DebruijnIndex { 277 ( 0.00%) self.outer_exclusive_binder 277 ( 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. 1,983,177 ( 0.04%) pub fn needs_drop_components<'tcx>( . ty: Ty<'tcx>, . target_layout: &TargetDataLayout, . ) -> Result; 2]>, AlwaysRequiresDrop> { 1,699,866 ( 0.03%) 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) => { 222 ( 0.00%) match needs_drop_components(elem_ty, target_layout) { 176 ( 0.00%) Ok(v) if v.is_empty() => Ok(v), 160 ( 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()), 80 ( 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. 662 ( 0.00%) ty::Tuple(..) => ty.tuple_fields().try_fold(SmallVec::new(), move |mut acc, elem| { 2,178 ( 0.00%) acc.extend(needs_drop_components(elem, target_layout)?); 1,452 ( 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(..) 2,508 ( 0.00%) | ty::Generator(..) => Ok(smallvec![ty]), . } 1,699,866 ( 0.03%) } . 558 ( 0.00%) pub fn is_trivially_const_drop<'tcx>(ty: Ty<'tcx>) -> bool { 372 ( 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())), . } 744 ( 0.00%) } . . // Does the equivalent of . // ``` . // let v = self.iter().map(|p| p.fold_with(folder)).collect::>(); . // folder.tcx().intern_*(&v) . // ``` 262,765 ( 0.01%) 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 200,566 ( 0.00%) match iter.by_ref().enumerate().find_map(|(i, t)| match t.try_fold_with(folder) { 351,800 ( 0.01%) 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)?) . } 8,588 ( 0.00%) Ok(intern(folder.tcx(), &new_list)) . } . Some((_, Err(err))) => { . return Err(err); . } . None => Ok(list), . } 268,111 ( 0.01%) } . . #[derive(Copy, Clone, Debug, HashStable, TyEncodable, TyDecodable)] . pub struct AlwaysRequiresDrop; . . /// Normalizes all opaque types in the given value, replacing them . /// with their underlying types. 80 ( 0.00%) pub fn normalize_opaque_types<'tcx>( . tcx: TyCtxt<'tcx>, . val: &'tcx List>, . ) -> &'tcx List> { 140 ( 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) 100 ( 0.00%) } . . pub fn provide(providers: &mut ty::query::Providers) { 2 ( 0.00%) *providers = ty::query::Providers { normalize_opaque_types, ..*providers } . } 6,512,508 ( 0.13%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/check/writeback.rs -------------------------------------------------------------------------------- Ir -- line 30 ---------------------------------------- . // the final TypeckResults since all of the types should have been . // inferred once typeck is done. . // When type inference is running however, having to update the typeck . // typeck results every time a new type is inferred would be unreasonably slow, . // so instead all of the replacement happens at the end in . // resolve_type_vars_in_body, which creates a new TypeTables which . // doesn't contain any inference types. . impl<'a, 'tcx> FnCtxt<'a, 'tcx> { 3,456 ( 0.00%) pub fn resolve_type_vars_in_body( . &self, . body: &'tcx hir::Body<'tcx>, . ) -> &'tcx ty::TypeckResults<'tcx> { 3,840 ( 0.00%) let item_id = self.tcx.hir().body_owner(body.id()); 2,304 ( 0.00%) let item_def_id = self.tcx.hir().local_def_id(item_id); . . // This attribute causes us to dump some writeback information . // in the form of errors, which is used for unit tests. . let rustc_dump_user_substs = 2,304 ( 0.00%) self.tcx.has_attr(item_def_id.to_def_id(), sym::rustc_dump_user_substs); . . let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_substs); 1,536 ( 0.00%) for param in body.params { 3,807 ( 0.00%) wbcx.visit_node_id(param.pat.span, param.hir_id); . } . // Type only exists for constants and statics, not functions. 4,224 ( 0.00%) match self.tcx.hir().body_owner_kind(item_id) { . hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => { 465 ( 0.00%) wbcx.visit_node_id(body.value.span, item_id); . } . hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => (), . } . wbcx.visit_body(body); 384 ( 0.00%) wbcx.visit_min_capture_map(); 384 ( 0.00%) wbcx.eval_closure_size(); 384 ( 0.00%) wbcx.visit_fake_reads_map(); 384 ( 0.00%) wbcx.visit_closures(); 384 ( 0.00%) wbcx.visit_liberated_fn_sigs(); 384 ( 0.00%) wbcx.visit_fru_field_types(); 1,152 ( 0.00%) wbcx.visit_opaque_types(body.value.span); 384 ( 0.00%) wbcx.visit_coercion_casts(); 384 ( 0.00%) wbcx.visit_user_provided_tys(); 384 ( 0.00%) wbcx.visit_user_provided_sigs(); 384 ( 0.00%) wbcx.visit_generator_interior_types(); . . let used_trait_imports = 768 ( 0.00%) mem::take(&mut self.typeck_results.borrow_mut().used_trait_imports); . debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports); 768 ( 0.00%) wbcx.typeck_results.used_trait_imports = used_trait_imports; . 1,920 ( 0.00%) wbcx.typeck_results.treat_byte_string_as_slice = 384 ( 0.00%) mem::take(&mut self.typeck_results.borrow_mut().treat_byte_string_as_slice); . 1,152 ( 0.00%) if self.is_tainted_by_errors() { . // FIXME(eddyb) keep track of `ErrorReported` from where the error was emitted. . wbcx.typeck_results.tainted_by_errors = Some(ErrorReported); . } . . debug!("writeback: typeck results for {:?} are {:#?}", item_def_id, wbcx.typeck_results); . 768 ( 0.00%) self.tcx.arena.alloc(wbcx.typeck_results) 3,456 ( 0.00%) } . } . . /////////////////////////////////////////////////////////////////////////// . // The Writeback context. This visitor walks the HIR, checking the . // fn-specific typeck results to find references to types or regions. It . // resolves those regions to remove inference variables and writes the . // final result back into the master typeck results in the tcx. Here and . // there, it applies a few ad-hoc checks that were not convenient to -- line 98 ---------------------------------------- -- line 109 ---------------------------------------- . } . . impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { . fn new( . fcx: &'cx FnCtxt<'cx, 'tcx>, . body: &'tcx hir::Body<'tcx>, . rustc_dump_user_substs: bool, . ) -> WritebackCx<'cx, 'tcx> { 768 ( 0.00%) let owner = body.id().hir_id.owner; . 3,456 ( 0.00%) WritebackCx { . fcx, 1,536 ( 0.00%) typeck_results: ty::TypeckResults::new(owner), . body, . rustc_dump_user_substs, . } . } . . fn tcx(&self) -> TyCtxt<'tcx> { 890 ( 0.00%) self.fcx.tcx . } . . fn write_ty_to_typeck_results(&mut self, hir_id: hir::HirId, ty: Ty<'tcx>) { . debug!("write_ty_to_typeck_results({:?}, {:?})", hir_id, ty); 445,800 ( 0.01%) assert!(!ty.needs_infer() && !ty.has_placeholders() && !ty.has_free_regions()); 594,336 ( 0.01%) self.typeck_results.node_types_mut().insert(hir_id, ty); . } . . // Hacky hack: During type-checking, we treat *all* operators . // as potentially overloaded. But then, during writeback, if . // we observe that something like `a+b` is (known to be) . // operating on scalars, we clear the overload. . fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr<'_>) { 1,019,688 ( 0.02%) match e.kind { 6 ( 0.00%) hir::ExprKind::Unary(hir::UnOp::Neg | hir::UnOp::Not, inner) => { 24 ( 0.00%) let inner_ty = self.fcx.node_ty(inner.hir_id); . let inner_ty = self.fcx.resolve_vars_if_possible(inner_ty); . . if inner_ty.is_scalar() { 6 ( 0.00%) let mut typeck_results = self.fcx.typeck_results.borrow_mut(); 36 ( 0.00%) typeck_results.type_dependent_defs_mut().remove(e.hir_id); 12 ( 0.00%) typeck_results.node_substs_mut().remove(e.hir_id); . } . } . hir::ExprKind::Binary(ref op, lhs, rhs) | hir::ExprKind::AssignOp(ref op, lhs, rhs) => { 1,015 ( 0.00%) let lhs_ty = self.fcx.node_ty(lhs.hir_id); . let lhs_ty = self.fcx.resolve_vars_if_possible(lhs_ty); . 812 ( 0.00%) let rhs_ty = self.fcx.node_ty(rhs.hir_id); . let rhs_ty = self.fcx.resolve_vars_if_possible(rhs_ty); . . if lhs_ty.is_scalar() && rhs_ty.is_scalar() { 152 ( 0.00%) let mut typeck_results = self.fcx.typeck_results.borrow_mut(); 760 ( 0.00%) typeck_results.type_dependent_defs_mut().remove(e.hir_id); 152 ( 0.00%) typeck_results.node_substs_mut().remove(e.hir_id); . 344 ( 0.00%) match e.kind { . hir::ExprKind::Binary(..) => { 528 ( 0.00%) if !op.node.is_by_value() { 61 ( 0.00%) let mut adjustments = typeck_results.adjustments_mut(); 366 ( 0.00%) if let Some(a) = adjustments.get_mut(lhs.hir_id) { . a.pop(); . } 244 ( 0.00%) if let Some(a) = adjustments.get_mut(rhs.hir_id) { . a.pop(); . } . } . } . hir::ExprKind::AssignOp(..) 100 ( 0.00%) if let Some(a) = typeck_results.adjustments_mut().get_mut(lhs.hir_id) => . { . a.pop(); . } . _ => {} . } . } . } . _ => {} -- line 186 ---------------------------------------- -- line 187 ---------------------------------------- . } . } . . // Similar to operators, indexing is always assumed to be overloaded . // Here, correct cases where an indexing expression can be simplified . // to use builtin indexing because the index type is known to be . // usize-ish . fn fix_index_builtin_expr(&mut self, e: &hir::Expr<'_>) { 291,725 ( 0.01%) if let hir::ExprKind::Index(ref base, ref index) = e.kind { 52 ( 0.00%) let mut typeck_results = self.fcx.typeck_results.borrow_mut(); . . // All valid indexing looks like this; might encounter non-valid indexes at this point. 52 ( 0.00%) let base_ty = typeck_results 26 ( 0.00%) .expr_ty_adjusted_opt(base) . .map(|t| self.fcx.resolve_vars_if_possible(t).kind()); . if base_ty.is_none() { . // When encountering `return [0][0]` outside of a `fn` body we can encounter a base . // that isn't in the type table. We assume more relevant errors have already been . // emitted, so we delay an ICE if none have. (#64638) . self.tcx().sess.delay_span_bug(e.span, &format!("bad base: `{:?}`", base)); . } 52 ( 0.00%) if let Some(ty::Ref(_, base_ty, _)) = base_ty { 104 ( 0.00%) let index_ty = typeck_results.expr_ty_adjusted_opt(index).unwrap_or_else(|| { . // When encountering `return [0][0]` outside of a `fn` body we would attempt . // to access an unexistend index. We assume that more relevant errors will . // already have been emitted, so we only gate on this with an ICE if no . // error has been emitted. (#64638) . self.fcx.tcx.ty_error_with_message( . e.span, . &format!("bad index {:?} for base: `{:?}`", index, base), . ) . }); . let index_ty = self.fcx.resolve_vars_if_possible(index_ty); . 86 ( 0.00%) if base_ty.builtin_index().is_some() && index_ty == self.fcx.tcx.types.usize { . // Remove the method call record 24 ( 0.00%) typeck_results.type_dependent_defs_mut().remove(e.hir_id); 24 ( 0.00%) typeck_results.node_substs_mut().remove(e.hir_id); . 40 ( 0.00%) if let Some(a) = typeck_results.adjustments_mut().get_mut(base.hir_id) { . // Discard the need for a mutable borrow . . // Extra adjustment made when indexing causes a drop . // of size information - we need to get rid of it . // Since this is "after" the other adjustment to be . // discarded, we do an extra `pop()` 8 ( 0.00%) if let Some(Adjustment { . kind: Adjust::Pointer(PointerCast::Unsize), .. . }) = a.pop() . { . // So the borrow discard actually happens here . a.pop(); . } . } . } -- line 241 ---------------------------------------- -- line 248 ---------------------------------------- . // Impl of Visitor for Resolver . // . // This is the master code which walks the AST. It delegates most of . // the heavy lifting to the generic visit and resolve functions . // below. In general, a function is made into a `visitor` if it must . // traffic in node-ids or update typeck results in the type context etc. . . impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> { 1,310,202 ( 0.03%) fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { 145,578 ( 0.00%) self.fix_scalar_builtin_expr(e); . self.fix_index_builtin_expr(e); . 727,890 ( 0.01%) self.visit_node_id(e.span, e.hir_id); . 582,312 ( 0.01%) match e.kind { 34 ( 0.00%) hir::ExprKind::Closure(_, _, body, _, _) => { 102 ( 0.00%) let body = self.fcx.tcx.hir().body(body); 34 ( 0.00%) for param in body.params { 95 ( 0.00%) self.visit_node_id(e.span, param.hir_id); . } . . self.visit_body(body); . } 233 ( 0.00%) hir::ExprKind::Struct(_, fields, _) => { . for field in fields { 3,904 ( 0.00%) self.visit_field_id(field.hir_id); . } . } . hir::ExprKind::Field(..) => { 1,870 ( 0.00%) self.visit_field_id(e.hir_id); . } . hir::ExprKind::ConstBlock(anon_const) => { . self.visit_node_id(e.span, anon_const.hir_id); . . let body = self.tcx().hir().body(anon_const.body); . self.visit_body(body); . } . _ => {} . } . 436,734 ( 0.01%) intravisit::walk_expr(self, e); 1,164,624 ( 0.02%) } . 5,616 ( 0.00%) fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) { 2,496 ( 0.00%) self.visit_node_id(b.span, b.hir_id); . intravisit::walk_block(self, b); 792 ( 0.00%) } . 12,123 ( 0.00%) fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { 4,987 ( 0.00%) match p.kind { . hir::PatKind::Binding(..) => { 1,748 ( 0.00%) let typeck_results = self.fcx.typeck_results.borrow(); 2,622 ( 0.00%) if let Some(bm) = 6,992 ( 0.00%) typeck_results.extract_binding_mode(self.tcx().sess, p.hir_id, p.span) . { 2,622 ( 0.00%) self.typeck_results.pat_binding_modes_mut().insert(p.hir_id, bm); . } . } 98 ( 0.00%) hir::PatKind::Struct(_, fields, _) => { . for field in fields { 684 ( 0.00%) self.visit_field_id(field.hir_id); . } . } . _ => {} . }; . 5,388 ( 0.00%) self.visit_pat_adjustments(p.span, p.hir_id); . 6,735 ( 0.00%) self.visit_node_id(p.span, p.hir_id); 4,041 ( 0.00%) intravisit::walk_pat(self, p); 10,776 ( 0.00%) } . 1,776 ( 0.00%) fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { . intravisit::walk_local(self, l); 1,332 ( 0.00%) let var_ty = self.fcx.local_ty(l.span, l.hir_id).decl_ty; . let var_ty = self.resolve(var_ty, &l.span); . self.write_ty_to_typeck_results(l.hir_id, var_ty); . } . 1,834 ( 0.00%) fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) { 326 ( 0.00%) intravisit::walk_ty(self, hir_ty); 1,176 ( 0.00%) let ty = self.fcx.node_ty(hir_ty.hir_id); 262 ( 0.00%) let ty = self.resolve(ty, &hir_ty.span); . self.write_ty_to_typeck_results(hir_ty.hir_id, ty); . } . . fn visit_infer(&mut self, inf: &'tcx hir::InferArg) { . intravisit::walk_inf(self, inf); . // Ignore cases where the inference is a const. . if let Some(ty) = self.fcx.node_ty_opt(inf.hir_id) { . let ty = self.resolve(ty, &inf.span); . self.write_ty_to_typeck_results(inf.hir_id, ty); . } . } . } . . impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> { 2,688 ( 0.00%) fn eval_closure_size(&mut self) { . let mut res: FxHashMap> = Default::default(); 1,152 ( 0.00%) for (closure_def_id, data) in self.fcx.typeck_results.borrow().closure_size_eval.iter() { . let closure_hir_id = . self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local()); . . let data = self.resolve(*data, &closure_hir_id); . . res.insert(*closure_def_id, data); . } . 3,840 ( 0.00%) self.typeck_results.closure_size_eval = res; 3,072 ( 0.00%) } 2,688 ( 0.00%) fn visit_min_capture_map(&mut self) { . let mut min_captures_wb = ty::MinCaptureInformationMap::with_capacity_and_hasher( 768 ( 0.00%) self.fcx.typeck_results.borrow().closure_min_captures.len(), . Default::default(), . ); . for (closure_def_id, root_min_captures) in 768 ( 0.00%) self.fcx.typeck_results.borrow().closure_min_captures.iter() . { . let mut root_var_map_wb = ty::RootVariableMinCaptureList::with_capacity_and_hasher( . root_min_captures.len(), . Default::default(), . ); . for (var_hir_id, min_list) in root_min_captures.iter() { . let min_list_wb = min_list . .iter() . .map(|captured_place| { 27 ( 0.00%) let locatable = captured_place.info.path_expr_id.unwrap_or_else(|| { . self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local()) . }); . . self.resolve(captured_place.clone(), &locatable) . }) . .collect(); 18 ( 0.00%) root_var_map_wb.insert(*var_hir_id, min_list_wb); . } 16 ( 0.00%) min_captures_wb.insert(*closure_def_id, root_var_map_wb); . } . 3,456 ( 0.00%) self.typeck_results.closure_min_captures = min_captures_wb; 3,072 ( 0.00%) } . 2,688 ( 0.00%) fn visit_fake_reads_map(&mut self) { . let mut resolved_closure_fake_reads: FxHashMap< . DefId, . Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>, . > = Default::default(); . for (closure_def_id, fake_reads) in 768 ( 0.00%) self.fcx.typeck_results.borrow().closure_fake_reads.iter() . { . let mut resolved_fake_reads = Vec::<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>::new(); . for (place, cause, hir_id) in fake_reads.iter() { . let locatable = . self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local()); . . let resolved_fake_read = self.resolve(place.clone(), &locatable); . resolved_fake_reads.push((resolved_fake_read, *cause, *hir_id)); . } 34 ( 0.00%) resolved_closure_fake_reads.insert(*closure_def_id, resolved_fake_reads); . } 3,456 ( 0.00%) self.typeck_results.closure_fake_reads = resolved_closure_fake_reads; 3,072 ( 0.00%) } . 2,688 ( 0.00%) fn visit_closures(&mut self) { 768 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 1,152 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . 384 ( 0.00%) for (id, origin) in fcx_typeck_results.closure_kind_origins().iter() { 2 ( 0.00%) let hir_id = hir::HirId { owner: common_hir_owner, local_id: *id }; 2 ( 0.00%) let place_span = origin.0; . let place = self.resolve(origin.1.clone(), &place_span); 10 ( 0.00%) self.typeck_results.closure_kind_origins_mut().insert(hir_id, (place_span, place)); . } 3,072 ( 0.00%) } . 2,688 ( 0.00%) fn visit_coercion_casts(&mut self) { 768 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 384 ( 0.00%) let fcx_coercion_casts = fcx_typeck_results.coercion_casts(); 768 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . . for local_id in fcx_coercion_casts { 24 ( 0.00%) self.typeck_results.set_coercion_cast(*local_id); . } 3,072 ( 0.00%) } . 3,072 ( 0.00%) fn visit_user_provided_tys(&mut self) { 768 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 1,536 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . . let mut errors_buffer = Vec::new(); 996 ( 0.00%) for (&local_id, c_ty) in fcx_typeck_results.user_provided_types().iter() { . let hir_id = hir::HirId { owner: common_hir_owner, local_id }; . . if cfg!(debug_assertions) && c_ty.needs_infer() { . span_bug!( . hir_id.to_span(self.fcx.tcx), . "writeback: `{:?}` has inference variables", . c_ty . ); . }; . 2,754 ( 0.00%) self.typeck_results.user_provided_types_mut().insert(hir_id, *c_ty); . 2,052 ( 0.00%) if let ty::UserType::TypeOf(_, user_substs) = c_ty.value { 576 ( 0.00%) if self.rustc_dump_user_substs { . // This is a unit-testing mechanism. . let span = self.tcx().hir().span(hir_id); . // We need to buffer the errors in order to guarantee a consistent . // order when emitting them. . let err = self . .tcx() . .sess . .struct_span_err(span, &format!("user substs: {:?}", user_substs)); . err.buffer(&mut errors_buffer); . } . } . } . 384 ( 0.00%) if !errors_buffer.is_empty() { . errors_buffer.sort_by_key(|diag| diag.span.primary_span()); . for diag in errors_buffer.drain(..) { . self.tcx().sess.diagnostic().emit_diagnostic(&diag); . } . } 3,072 ( 0.00%) } . 2,688 ( 0.00%) fn visit_user_provided_sigs(&mut self) { 768 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 768 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . 34 ( 0.00%) for (&def_id, c_sig) in fcx_typeck_results.user_provided_sigs.iter() { . if cfg!(debug_assertions) && c_sig.needs_infer() { . span_bug!( . self.fcx.tcx.hir().span_if_local(def_id).unwrap(), . "writeback: `{:?}` has inference variables", . c_sig . ); . }; . 102 ( 0.00%) self.typeck_results.user_provided_sigs.insert(def_id, *c_sig); . } 3,072 ( 0.00%) } . 1,920 ( 0.00%) fn visit_generator_interior_types(&mut self) { 768 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 768 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); 2,304 ( 0.00%) self.typeck_results.generator_interior_types = 768 ( 0.00%) fcx_typeck_results.generator_interior_types.clone(); 2,304 ( 0.00%) } . 6,144 ( 0.00%) #[instrument(skip(self, span), level = "debug")] . fn visit_opaque_types(&mut self, span: Span) { 384 ( 0.00%) let opaque_types = self.fcx.infcx.inner.borrow().opaque_types.clone(); 1,536 ( 0.00%) for (opaque_type_key, opaque_defn) in opaque_types { . let hir_id = . self.tcx().hir().local_def_id_to_hir_id(opaque_type_key.def_id.expect_local()); . let instantiated_ty = self.resolve(opaque_defn.concrete_ty, &hir_id); . . debug_assert!(!instantiated_ty.has_escaping_bound_vars()); . . let opaque_type_key = self.fcx.fully_resolve(opaque_type_key).unwrap(); . -- line 510 ---------------------------------------- -- line 552 ---------------------------------------- . // in some other location, or we'll end up emitting an error due . // to the lack of defining usage . if !skip_add { . self.typeck_results.concrete_opaque_types.insert(opaque_type_key.def_id); . } . } . } . 9,126 ( 0.00%) fn visit_field_id(&mut self, hir_id: hir::HirId) { 7,605 ( 0.00%) if let Some(index) = self.fcx.typeck_results.borrow_mut().field_indices_mut().remove(hir_id) . { 4,563 ( 0.00%) self.typeck_results.field_indices_mut().insert(hir_id, index); . } 10,647 ( 0.00%) } . 2,665,512 ( 0.05%) #[instrument(skip(self, span), level = "debug")] . fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) { . // Export associated path extensions and method resolutions. 592,336 ( 0.01%) if let Some(def) = 444,252 ( 0.01%) self.fcx.typeck_results.borrow_mut().type_dependent_defs_mut().remove(hir_id) . { 1,636 ( 0.00%) self.typeck_results.type_dependent_defs_mut().insert(hir_id, def); . } . . // Resolve any borrowings for the node with id `node_id` . self.visit_adjustments(span, hir_id); . . // Resolve the type of the node with id `node_id` 592,336 ( 0.01%) let n_ty = self.fcx.node_ty(hir_id); . let n_ty = self.resolve(n_ty, &span); . self.write_ty_to_typeck_results(hir_id, n_ty); . debug!(?n_ty); . . // Resolve any substitutions 888,504 ( 0.02%) if let Some(substs) = self.fcx.typeck_results.borrow().node_substs_opt(hir_id) { . let substs = self.resolve(substs, &span); . debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs); . assert!(!substs.needs_infer() && !substs.has_placeholders()); 1,960 ( 0.00%) self.typeck_results.node_substs_mut().insert(hir_id, substs); . } . } . . #[instrument(skip(self, span), level = "debug")] . fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) { 444,252 ( 0.01%) let adjustment = self.fcx.typeck_results.borrow_mut().adjustments_mut().remove(hir_id); 740,420 ( 0.02%) match adjustment { . None => { . debug!("no adjustments for node"); . } . . Some(adjustment) => { 4,596 ( 0.00%) let resolved_adjustment = self.resolve(adjustment, &span); . debug!(?resolved_adjustment); 13,788 ( 0.00%) self.typeck_results.adjustments_mut().insert(hir_id, resolved_adjustment); . } . } . } . . #[instrument(skip(self, span), level = "debug")] . fn visit_pat_adjustments(&mut self, span: Span, hir_id: hir::HirId) { 4,041 ( 0.00%) let adjustment = self.fcx.typeck_results.borrow_mut().pat_adjustments_mut().remove(hir_id); 2,694 ( 0.00%) match adjustment { . None => { . debug!("no pat_adjustments for node"); . } . . Some(adjustment) => { . let resolved_adjustment = self.resolve(adjustment, &span); . debug!(?resolved_adjustment); . self.typeck_results.pat_adjustments_mut().insert(hir_id, resolved_adjustment); . } . } . } . 3,072 ( 0.00%) fn visit_liberated_fn_sigs(&mut self) { 768 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 1,536 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . 1,616 ( 0.00%) for (&local_id, &fn_sig) in fcx_typeck_results.liberated_fn_sigs().iter() { 924 ( 0.00%) let hir_id = hir::HirId { owner: common_hir_owner, local_id }; . let fn_sig = self.resolve(fn_sig, &hir_id); 924 ( 0.00%) self.typeck_results.liberated_fn_sigs_mut().insert(hir_id, fn_sig); . } 3,072 ( 0.00%) } . 3,072 ( 0.00%) fn visit_fru_field_types(&mut self) { 768 ( 0.00%) let fcx_typeck_results = self.fcx.typeck_results.borrow(); 1,536 ( 0.00%) assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner); . let common_hir_owner = fcx_typeck_results.hir_owner; . 384 ( 0.00%) for (&local_id, ftys) in fcx_typeck_results.fru_field_types().iter() { . let hir_id = hir::HirId { owner: common_hir_owner, local_id }; . let ftys = self.resolve(ftys.clone(), &hir_id); . self.typeck_results.fru_field_types_mut().insert(hir_id, ftys); . } 3,072 ( 0.00%) } . . fn resolve(&mut self, x: T, span: &dyn Locatable) -> T . where . T: TypeFoldable<'tcx>, . { 302,094 ( 0.01%) let mut resolver = Resolver::new(self.fcx, span, self.body); 2,131 ( 0.00%) let x = x.fold_with(&mut resolver); . if cfg!(debug_assertions) && x.needs_infer() { . span_bug!(span.to_span(self.fcx.tcx), "writeback: `{:?}` has inference variables", x); . } . . // We may have introduced e.g. `ty::Error`, if inference failed, make sure . // to mark the `TypeckResults` as tainted in that case, so that downstream . // users of the typeck results don't produce extra errors, or worse, ICEs. 317,337 ( 0.01%) if resolver.replaced_with_error { . // FIXME(eddyb) keep track of `ErrorReported` from where the error was emitted. . self.typeck_results.tainted_by_errors = Some(ErrorReported); . } . . x . } . } . -- line 671 ---------------------------------------- -- line 698 ---------------------------------------- . } . . impl<'cx, 'tcx> Resolver<'cx, 'tcx> { . fn new( . fcx: &'cx FnCtxt<'cx, 'tcx>, . span: &'cx dyn Locatable, . body: &'tcx hir::Body<'tcx>, . ) -> Resolver<'cx, 'tcx> { 1,516,846 ( 0.03%) Resolver { tcx: fcx.tcx, infcx: fcx, span, body, replaced_with_error: false } . } . . fn report_type_error(&self, t: Ty<'tcx>) { . if !self.tcx.sess.has_errors() { . self.infcx . .emit_inference_failure_err( . Some(self.body.id()), . self.span.to_span(self.tcx), -- line 714 ---------------------------------------- -- line 736 ---------------------------------------- . } . . struct EraseEarlyRegions<'tcx> { . tcx: TyCtxt<'tcx>, . } . . impl<'tcx> TypeFolder<'tcx> for EraseEarlyRegions<'tcx> { . fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { 10,038 ( 0.00%) self.tcx . } . fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> { 160,349 ( 0.00%) if ty.has_type_flags(ty::TypeFlags::HAS_FREE_REGIONS) { 15,551 ( 0.00%) ty.super_fold_with(self) . } else { . ty . } . } . fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { 21,836 ( 0.00%) if let ty::ReLateBound(..) = r { r } else { self.tcx.lifetimes.re_erased } . } . } . . impl<'cx, 'tcx> TypeFolder<'tcx> for Resolver<'cx, 'tcx> { . fn tcx<'a>(&'a self) -> TyCtxt<'tcx> { 1,181 ( 0.00%) self.tcx . } . 1,391,697 ( 0.03%) fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { 463,899 ( 0.01%) match self.infcx.fully_resolve(t) { . Ok(t) => { . // Do not anonymize late-bound regions . // (e.g. keep `for<'a>` named `for<'a>`). . // This allows NLL to generate error messages that . // refer to the higher-ranked lifetime names written by the user. 309,266 ( 0.01%) EraseEarlyRegions { tcx: self.infcx.tcx }.fold_ty(t) . } . Err(_) => { . debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable", t); . self.report_type_error(t); . self.replaced_with_error = true; . self.tcx().ty_error() . } . } 1,237,064 ( 0.03%) } . . fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> { . debug_assert!(!r.is_late_bound(), "Should not be resolving bound region."); 7,817 ( 0.00%) self.tcx.lifetimes.re_erased . } . . fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> { . match self.infcx.fully_resolve(ct) { . Ok(ct) => self.infcx.tcx.erase_regions(ct), . Err(_) => { . debug!("Resolver::fold_const: input const `{:?}` not fully resolvable", ct); . self.report_const_error(ct); -- line 791 ---------------------------------------- 1,957,762 ( 0.04%) -------------------------------------------------------------------------------- -- 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>; . 1,605,677 ( 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, . )> { 233,729 ( 0.00%) if let Some(result) = QueryTypeOp::try_fast_path(infcx.tcx, &query_key) { 841,082 ( 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. 12,784 ( 0.00%) let mut canonical_var_values = OriginalQueryValues::default(); 654 ( 0.00%) let old_param_env = query_key.param_env; . let canonical_self = 9,492 ( 0.00%) infcx.canonicalize_query_keep_static(query_key, &mut canonical_var_values); 65,164 ( 0.00%) let canonical_result = Self::perform_query(infcx.tcx, canonical_self)?; . 82,759 ( 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, . )?; . 106,363 ( 0.00%) Ok((value, Some(canonical_self), obligations, canonical_result.value.certainty)) 1,560,005 ( 0.03%) } . } . . impl<'tcx, Q> TypeOp<'tcx> for ParamEnvAnd<'tcx, Q> . where . Q: QueryTypeOp<'tcx>, . { . type Output = Q::QueryResponse; . 1,398,216 ( 0.03%) fn fully_perform(self, infcx: &InferCtxt<'_, 'tcx>) -> Fallible> { . let mut region_constraints = QueryRegionConstraints::default(); 1,060,701 ( 0.02%) let (output, canonicalized_query, mut obligations, _) = 189,232 ( 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. 174,792 ( 0.00%) while !obligations.is_empty() { . trace!("{:#?}", obligations); . let mut progress = false; 555 ( 0.00%) for obligation in std::mem::take(&mut obligations) { 160 ( 0.00%) let obligation = infcx.resolve_vars_if_possible(obligation); 640 ( 0.00%) match ProvePredicate::fully_perform_into( 160 ( 0.00%) obligation.param_env.and(ProvePredicate::new(obligation.predicate)), . infcx, . &mut region_constraints, . ) { 160 ( 0.00%) Ok(((), _, new, certainty)) => { . obligations.extend(new); . progress = true; 80 ( 0.00%) if let Certainty::Ambiguous = certainty { . obligations.push(obligation); . } . } . Err(_) => obligations.push(obligation), . } . } 30 ( 0.00%) if !progress { . return Err(NoSolution); . } . } . . // Promote the final query-region-constraints into a . // (optional) ref-counted vector: . let region_constraints = 699,108 ( 0.01%) if region_constraints.is_empty() { None } else { Some(Rc::new(region_constraints)) }; . 2,254,395 ( 0.05%) Ok(TypeOpOutput { output, constraints: region_constraints, canonicalized_query }) 1,747,770 ( 0.04%) } . } 1,222,602 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/early.rs -------------------------------------------------------------------------------- Ir -- line 34 ---------------------------------------- . }) } . . pub struct EarlyContextAndPass<'a, T: EarlyLintPass> { . context: EarlyContext<'a>, . pass: T, . } . . impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> { 2,789,442 ( 0.06%) fn check_id(&mut self, id: ast::NodeId) { 2,170,462 ( 0.04%) for early_lint in self.context.buffered.take(id) { 260 ( 0.00%) let BufferedEarlyLint { span, msg, node_id: _, lint_id, diagnostic } = early_lint; . self.context.lookup_with_diagnostics( . lint_id.lint, 65 ( 0.00%) Some(span), . |lint| lint.build(&msg).emit(), 650 ( 0.00%) diagnostic, . ); . } 2,479,504 ( 0.05%) } . . /// Merge the lints specified by any lint attributes into the . /// current lint context, call the provided function, then reset the . /// lints in effect to their previous state. . fn with_lint_attrs(&mut self, id: ast::NodeId, attrs: &'a [ast::Attribute], f: F) . where . F: FnOnce(&mut Self), . { . let is_crate_node = id == ast::CRATE_NODE_ID; 2,056,907 ( 0.04%) let push = self.context.builder.push(attrs, is_crate_node); 882,381 ( 0.02%) self.check_id(id); . self.enter_attrs(attrs); . f(self); . self.exit_attrs(attrs); 3,190,748 ( 0.07%) self.context.builder.pop(push); . } . . fn enter_attrs(&mut self, attrs: &'a [ast::Attribute]) { . debug!("early context: enter_attrs({:?})", attrs); 1,618,145 ( 0.03%) run_early_pass!(self, enter_lint_attrs, attrs); . } . . fn exit_attrs(&mut self, attrs: &'a [ast::Attribute]) { . debug!("early context: exit_attrs({:?})", attrs); 1,469,018 ( 0.03%) run_early_pass!(self, exit_lint_attrs, attrs); . } . } . . impl<'a, T: EarlyLintPass> ast_visit::Visitor<'a> for EarlyContextAndPass<'a, T> { . fn visit_param(&mut self, param: &'a ast::Param) { . self.with_lint_attrs(param.id, ¶m.attrs, |cx| { 2,888 ( 0.00%) run_early_pass!(cx, check_param, param); 2,166 ( 0.00%) ast_visit::walk_param(cx, param); . }); . } . . fn visit_item(&mut self, it: &'a ast::Item) { 820 ( 0.00%) self.with_lint_attrs(it.id, &it.attrs, |cx| { 3,280 ( 0.00%) run_early_pass!(cx, check_item, it); 2,460 ( 0.00%) ast_visit::walk_item(cx, it); 3,280 ( 0.00%) run_early_pass!(cx, check_item_post, it); . }) . } . . fn visit_foreign_item(&mut self, it: &'a ast::ForeignItem) { . self.with_lint_attrs(it.id, &it.attrs, |cx| { . run_early_pass!(cx, check_foreign_item, it); . ast_visit::walk_foreign_item(cx, it); . run_early_pass!(cx, check_foreign_item_post, it); . }) . } . . fn visit_pat(&mut self, p: &'a ast::Pat) { 8,998 ( 0.00%) run_early_pass!(self, check_pat, p); 6,108 ( 0.00%) self.check_id(p.id); 6,108 ( 0.00%) ast_visit::walk_pat(self, p); 7,910 ( 0.00%) run_early_pass!(self, check_pat_post, p); . } . . fn visit_anon_const(&mut self, c: &'a ast::AnonConst) { . run_early_pass!(self, check_anon_const, c); . self.check_id(c.id); . ast_visit::walk_anon_const(self, c); . } . 2,588,400 ( 0.05%) fn visit_expr(&mut self, e: &'a ast::Expr) { 287,786 ( 0.01%) self.with_lint_attrs(e.id, &e.attrs, |cx| { 1,151,144 ( 0.02%) run_early_pass!(cx, check_expr, e); 863,358 ( 0.02%) ast_visit::walk_expr(cx, e); . }) . } . . fn visit_expr_field(&mut self, f: &'a ast::ExprField) { . self.with_lint_attrs(f.id, &f.attrs, |cx| { . ast_visit::walk_expr_field(cx, f); . }) . } . 15,939 ( 0.00%) fn visit_stmt(&mut self, s: &'a ast::Stmt) { . // Add the statement's lint attributes to our . // current state when checking the statement itself. . // This allows us to handle attributes like . // `#[allow(unused_doc_comments)]`, which apply to . // sibling attributes on the same target . // . // Note that statements get their attributes from . // the AST struct that they wrap (e.g. an item) 8,855 ( 0.00%) self.with_lint_attrs(s.id, s.attrs(), |cx| { 7,084 ( 0.00%) run_early_pass!(cx, check_stmt, s); 5,313 ( 0.00%) cx.check_id(s.id); . }); . // The visitor for the AST struct wrapped . // by the statement (e.g. `Item`) will call . // `with_lint_attrs`, so do this walk . // outside of the above `with_lint_attrs` call 17,710 ( 0.00%) ast_visit::walk_stmt(self, s); . } . . fn visit_fn(&mut self, fk: ast_visit::FnKind<'a>, span: Span, id: ast::NodeId) { 9,199 ( 0.00%) run_early_pass!(self, check_fn, fk, span, id); 1,851 ( 0.00%) self.check_id(id); 6,673 ( 0.00%) ast_visit::walk_fn(self, fk, span); . . // Explicitly check for lints associated with 'closure_id', since . // it does not have a corresponding AST node . if let ast_visit::FnKind::Fn(_, _, sig, _, _) = fk { 998 ( 0.00%) if let ast::Async::Yes { closure_id, .. } = sig.header.asyncness { . self.check_id(closure_id); . } . } 8,721 ( 0.00%) run_early_pass!(self, check_fn_post, fk, span, id); . } . . fn visit_variant_data(&mut self, s: &'a ast::VariantData) { 300 ( 0.00%) run_early_pass!(self, check_struct_def, s); 288 ( 0.00%) if let Some(ctor_hir_id) = s.ctor_id() { 108 ( 0.00%) self.check_id(ctor_hir_id); . } 216 ( 0.00%) ast_visit::walk_struct_def(self, s); 313 ( 0.00%) run_early_pass!(self, check_struct_def_post, s); . } . . fn visit_field_def(&mut self, s: &'a ast::FieldDef) { . self.with_lint_attrs(s.id, &s.attrs, |cx| { 496 ( 0.00%) run_early_pass!(cx, check_field_def, s); 372 ( 0.00%) ast_visit::walk_field_def(cx, s); . }) . } . 423 ( 0.00%) fn visit_variant(&mut self, v: &'a ast::Variant) { 47 ( 0.00%) self.with_lint_attrs(v.id, &v.attrs, |cx| { 188 ( 0.00%) run_early_pass!(cx, check_variant, v); 141 ( 0.00%) ast_visit::walk_variant(cx, v); 188 ( 0.00%) run_early_pass!(cx, check_variant_post, v); . }) . } . . fn visit_ty(&mut self, t: &'a ast::Ty) { 9,795 ( 0.00%) run_early_pass!(self, check_ty, t); 7,467 ( 0.00%) self.check_id(t.id); 16,733 ( 0.00%) ast_visit::walk_ty(self, t); . } . . fn visit_ident(&mut self, ident: Ident) { 57,125 ( 0.00%) run_early_pass!(self, check_ident, ident); . } . . fn visit_local(&mut self, l: &'a ast::Local) { 442 ( 0.00%) self.with_lint_attrs(l.id, &l.attrs, |cx| { 1,768 ( 0.00%) run_early_pass!(cx, check_local, l); 1,326 ( 0.00%) ast_visit::walk_local(cx, l); . }) . } . . fn visit_block(&mut self, b: &'a ast::Block) { 4,564 ( 0.00%) run_early_pass!(self, check_block, b); 2,982 ( 0.00%) self.check_id(b.id); . ast_visit::walk_block(self, b); 6,167 ( 0.00%) run_early_pass!(self, check_block_post, b); . } . . fn visit_arm(&mut self, a: &'a ast::Arm) { . self.with_lint_attrs(a.id, &a.attrs, |cx| { 992 ( 0.00%) run_early_pass!(cx, check_arm, a); 744 ( 0.00%) ast_visit::walk_arm(cx, a); . }) . } . . fn visit_expr_post(&mut self, e: &'a ast::Expr) { 1,296,247 ( 0.03%) run_early_pass!(self, check_expr_post, e); . . // Explicitly check for lints associated with 'closure_id', since . // it does not have a corresponding AST node 1,439,006 ( 0.03%) match e.kind { . ast::ExprKind::Closure(_, ast::Async::Yes { closure_id, .. }, ..) . | ast::ExprKind::Async(_, closure_id, ..) => self.check_id(closure_id), . _ => {} . } . } . . fn visit_generic_arg(&mut self, arg: &'a ast::GenericArg) { 3,240 ( 0.00%) run_early_pass!(self, check_generic_arg, arg); 2,430 ( 0.00%) ast_visit::walk_generic_arg(self, arg); . } . . fn visit_generic_param(&mut self, param: &'a ast::GenericParam) { 1,276 ( 0.00%) run_early_pass!(self, check_generic_param, param); 1,276 ( 0.00%) ast_visit::walk_generic_param(self, param); . } . . fn visit_generics(&mut self, g: &'a ast::Generics) { 3,452 ( 0.00%) run_early_pass!(self, check_generics, g); . ast_visit::walk_generics(self, g); . } . . fn visit_where_predicate(&mut self, p: &'a ast::WherePredicate) { 168 ( 0.00%) run_early_pass!(self, check_where_predicate, p); 168 ( 0.00%) ast_visit::walk_where_predicate(self, p); . } . . fn visit_poly_trait_ref(&mut self, t: &'a ast::PolyTraitRef, m: &'a ast::TraitBoundModifier) { 780 ( 0.00%) run_early_pass!(self, check_poly_trait_ref, t, m); 163 ( 0.00%) ast_visit::walk_poly_trait_ref(self, t, m); . } . . fn visit_assoc_item(&mut self, item: &'a ast::AssocItem, ctxt: ast_visit::AssocCtxt) { 344 ( 0.00%) self.with_lint_attrs(item.id, &item.attrs, |cx| match ctxt { . ast_visit::AssocCtxt::Trait => { 8 ( 0.00%) run_early_pass!(cx, check_trait_item, item); 8 ( 0.00%) ast_visit::walk_assoc_item(cx, item, ctxt); 9 ( 0.00%) run_early_pass!(cx, check_trait_item_post, item); . } . ast_visit::AssocCtxt::Impl => { 1,368 ( 0.00%) run_early_pass!(cx, check_impl_item, item); 1,368 ( 0.00%) ast_visit::walk_assoc_item(cx, item, ctxt); 1,710 ( 0.00%) run_early_pass!(cx, check_impl_item_post, item); . } . }); . } . . fn visit_lifetime(&mut self, lt: &'a ast::Lifetime) { 1,466 ( 0.00%) run_early_pass!(self, check_lifetime, lt); 2,767 ( 0.00%) self.check_id(lt.id); . } . . fn visit_path(&mut self, p: &'a ast::Path, id: ast::NodeId) { 37,427 ( 0.00%) run_early_pass!(self, check_path, p, id); 22,406 ( 0.00%) self.check_id(id); . ast_visit::walk_path(self, p); . } . . fn visit_attribute(&mut self, attr: &'a ast::Attribute) { 13,516 ( 0.00%) run_early_pass!(self, check_attribute, attr); . } . . fn visit_mac_def(&mut self, mac: &'a ast::MacroDef, id: ast::NodeId) { 28 ( 0.00%) run_early_pass!(self, check_mac_def, mac, id); 32 ( 0.00%) self.check_id(id); . } . . fn visit_mac_call(&mut self, mac: &'a ast::MacCall) { 740 ( 0.00%) run_early_pass!(self, check_mac, mac); . ast_visit::walk_mac(self, mac); . } . } . . struct EarlyLintPassObjects<'a> { . lints: &'a mut [EarlyLintPassObject], . } . -- line 302 ---------------------------------------- -- line 337 ---------------------------------------- . fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>) . where . 'a: 'b; . } . . impl<'a> EarlyCheckNode<'a> for &'a ast::Crate { . fn id(self) -> ast::NodeId { . ast::CRATE_NODE_ID 4 ( 0.00%) } . fn attrs<'b>(self) -> &'b [ast::Attribute] . where . 'a: 'b, . { . &self.attrs 2 ( 0.00%) } . fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>) . where . 'a: 'b, . { 6 ( 0.00%) run_early_pass!(cx, check_crate, self); 3 ( 0.00%) ast_visit::walk_crate(cx, self); 6 ( 0.00%) run_early_pass!(cx, check_crate_post, self); . } . } . . impl<'a> EarlyCheckNode<'a> for (ast::NodeId, &'a [ast::Attribute], &'a [P]) { . fn id(self) -> ast::NodeId { 18 ( 0.00%) self.0 18 ( 0.00%) } . fn attrs<'b>(self) -> &'b [ast::Attribute] . where . 'a: 'b, . { 36 ( 0.00%) self.1 18 ( 0.00%) } 162 ( 0.00%) fn check<'b>(self, cx: &mut EarlyContextAndPass<'b, impl EarlyLintPass>) . where . 'a: 'b, . { . walk_list!(cx, visit_attribute, self.1); 18 ( 0.00%) walk_list!(cx, visit_item, self.2); 144 ( 0.00%) } . } . . fn early_lint_node<'a>( . sess: &Session, . warn_about_weird_lints: bool, . lint_store: &LintStore, . registered_tools: &RegisteredTools, . buffered: LintBuffer, . pass: impl EarlyLintPass, . check_node: impl EarlyCheckNode<'a>, . ) -> LintBuffer { 16 ( 0.00%) let mut cx = EarlyContextAndPass { 121 ( 0.00%) context: EarlyContext::new( . sess, . warn_about_weird_lints, . lint_store, . registered_tools, 80 ( 0.00%) buffered, . ), 4 ( 0.00%) pass, . }; . 456 ( 0.00%) cx.with_lint_attrs(check_node.id(), check_node.attrs(), |cx| check_node.check(cx)); 80 ( 0.00%) cx.context.buffered . } . 220 ( 0.00%) pub fn check_ast_node<'a>( . sess: &Session, . pre_expansion: bool, . lint_store: &LintStore, . registered_tools: &RegisteredTools, . lint_buffer: Option, . builtin_lints: impl EarlyLintPass, . check_node: impl EarlyCheckNode<'a>, . ) { . let passes = 120 ( 0.00%) if pre_expansion { &lint_store.pre_expansion_passes } else { &lint_store.early_passes }; . let mut passes: Vec<_> = passes.iter().map(|p| (p)()).collect(); 20 ( 0.00%) let mut buffered = lint_buffer.unwrap_or_default(); . 40 ( 0.00%) if !sess.opts.debugging_opts.no_interleave_lints { 80 ( 0.00%) buffered = early_lint_node( . sess, . pre_expansion, . lint_store, . registered_tools, . buffered, 4 ( 0.00%) builtin_lints, . check_node, . ); . 20 ( 0.00%) if !passes.is_empty() { . buffered = early_lint_node( . sess, . false, . lint_store, . registered_tools, . buffered, . EarlyLintPassObjects { lints: &mut passes[..] }, . check_node, -- line 438 ---------------------------------------- -- line 453 ---------------------------------------- . ) . }); . } . } . . // All of the buffered lints should have been emitted at this point. . // If not, that means that we somehow buffered a lint for a node id . // that was not lint-checked (perhaps it doesn't exist?). This is a bug. 220 ( 0.00%) for (id, lints) in buffered.map { . for early_lint in lints { . sess.delay_span_bug( . early_lint.span, . &format!( . "failed to process buffered lint here (dummy = {})", . id == ast::DUMMY_NODE_ID . ), . ); . } . } 162 ( 0.00%) } 3,665 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_borrowck/src/type_check/canonical.rs -------------------------------------------------------------------------------- Ir -- line 19 ---------------------------------------- . /// `op` and then executes all the further obligations that `op` . /// returns. This will yield a set of outlives constraints amongst . /// regions which are extracted and stored as having occurred at . /// `locations`. . /// . /// **Any `rustc_infer::infer` operations that might generate region . /// constraints should occur within this method so that those . /// constraints can be properly localized!** 1,433,082 ( 0.03%) #[instrument(skip(self, category, op), level = "trace")] 1,752,998 ( 0.04%) pub(super) fn fully_perform_op( . &mut self, . locations: Locations, . category: ConstraintCategory, . op: Op, . ) -> Fallible . where . Op: type_op::TypeOp<'tcx, Output = R>, . Canonical<'tcx, Op>: ToUniverseInfo<'tcx>, . { 860,133 ( 0.02%) let old_universe = self.infcx.universe(); . 524,719 ( 0.01%) let TypeOpOutput { output, constraints, canonicalized_query } = 703,304 ( 0.01%) op.fully_perform(self.infcx)?; . 346,100 ( 0.01%) if let Some(data) = &constraints { . self.push_region_constraints(locations, category, data); . } . 346,053 ( 0.01%) let universe = self.infcx.universe(); . 173,050 ( 0.00%) if old_universe != universe { 126 ( 0.00%) let universe_info = match canonicalized_query { 24 ( 0.00%) Some(canonicalized_query) => canonicalized_query.to_universe_info(old_universe), . None => UniverseInfo::other(), . }; . for u in old_universe..universe { 38 ( 0.00%) self.borrowck_context . .constraints . .universe_causes 114 ( 0.00%) .insert(u + 1, universe_info.clone()); . } . } . 188 ( 0.00%) Ok(output) . } . . pub(super) fn instantiate_canonical_with_fresh_inference_vars( . &mut self, . span: Span, . canonical: &Canonical<'tcx, T>, . ) -> T . where . T: TypeFoldable<'tcx>, . { 2,660 ( 0.00%) let (instantiated, _) = 1,347 ( 0.00%) self.infcx.instantiate_canonical_with_fresh_inference_vars(span, canonical); . 341 ( 0.00%) for u in 0..canonical.max_universe.as_u32() { . let info = UniverseInfo::other(); . self.borrowck_context . .constraints . .universe_causes . .insert(ty::UniverseIndex::from_u32(u), info); . } . . instantiated . } . 3,175 ( 0.00%) pub(super) fn prove_trait_ref( . &mut self, . trait_ref: ty::TraitRef<'tcx>, . locations: Locations, . category: ConstraintCategory, . ) { . self.prove_predicates( 32,107 ( 0.00%) Some(ty::Binder::dummy(ty::PredicateKind::Trait(ty::TraitPredicate { . trait_ref, . constness: ty::BoundConstness::NotConst, . polarity: ty::ImplPolarity::Positive, . }))), . locations, . category, . ); 2,540 ( 0.00%) } . 18,099 ( 0.00%) pub(super) fn normalize_and_prove_instantiated_predicates( . &mut self, . // Keep this parameter for now, in case we start using . // it in `ConstraintCategory` at some point. . _def_id: DefId, . instantiated_predicates: ty::InstantiatedPredicates<'tcx>, . locations: Locations, . ) { 22,121 ( 0.00%) for (predicate, span) in instantiated_predicates . .predicates . .into_iter() . .zip(instantiated_predicates.spans.into_iter()) . { . let predicate = self.normalize(predicate, locations); 10,160 ( 0.00%) self.prove_predicate(predicate, locations, ConstraintCategory::Predicate(span)); . } 16,088 ( 0.00%) } . . pub(super) fn prove_predicates( . &mut self, . predicates: impl IntoIterator>, . locations: Locations, . category: ConstraintCategory, . ) { 20,370 ( 0.00%) for predicate in predicates { . let predicate = predicate.to_predicate(self.tcx()); . debug!("prove_predicates(predicate={:?}, locations={:?})", predicate, locations,); . 109,518 ( 0.00%) self.prove_predicate(predicate, locations, category); . } . } . 229,820 ( 0.00%) #[instrument(skip(self), level = "debug")] . pub(super) fn prove_predicate( . &mut self, . predicate: ty::Predicate<'tcx>, . locations: Locations, . category: ConstraintCategory, . ) { 11,491 ( 0.00%) let param_env = self.param_env; . self.fully_perform_op( . locations, . category, 34,473 ( 0.00%) param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)), . ) . .unwrap_or_else(|NoSolution| { . span_mirbug!(self, NoSolution, "could not prove {:?}", predicate); . }) . } . 1,110,530 ( 0.02%) #[instrument(skip(self), level = "debug")] 1,744,828 ( 0.04%) pub(super) fn normalize(&mut self, value: T, location: impl NormalizeLocation) -> T . where . T: type_op::normalize::Normalizable<'tcx> + fmt::Display + Copy + 'tcx, . { 160,905 ( 0.00%) let param_env = self.param_env; 475,950 ( 0.01%) self.fully_perform_op( 1,584 ( 0.00%) location.to_locations(), . ConstraintCategory::Boring, 141 ( 0.00%) param_env.and(type_op::normalize::Normalize::new(value)), . ) . .unwrap_or_else(|NoSolution| { . span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value); . value . }) . } . } 195,474 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 84 ---------------------------------------- . pub struct SessionGlobals { . symbol_interner: symbol::Interner, . span_interner: Lock, . hygiene_data: Lock, . source_map: Lock>>, . } . . impl SessionGlobals { 12 ( 0.00%) pub fn new(edition: Edition) -> SessionGlobals { 50 ( 0.00%) SessionGlobals { 2 ( 0.00%) symbol_interner: symbol::Interner::fresh(), . span_interner: Lock::new(span_encoding::SpanInterner::default()), 6 ( 0.00%) hygiene_data: Lock::new(hygiene::HygieneData::new(edition)), . source_map: Lock::new(None), . } 10 ( 0.00%) } . } . . #[inline] . pub fn create_session_globals_then(edition: Edition, f: impl FnOnce() -> R) -> R { 1 ( 0.00%) assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 7 ( 0.00%) SESSION_GLOBALS.set(&session_globals, f) 1 ( 0.00%) } . . #[inline] . pub fn set_session_globals_then(session_globals: &SessionGlobals, f: impl FnOnce() -> R) -> R { . assert!( . !SESSION_GLOBALS.is_set(), . "SESSION_GLOBALS should never be overwritten! \ . Use another thread if you need another SessionGlobals" . ); -- line 119 ---------------------------------------- -- line 120 ---------------------------------------- . SESSION_GLOBALS.set(session_globals, f) . } . . #[inline] . pub fn create_default_session_if_not_set_then(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 4 ( 0.00%) create_session_if_not_set_then(edition::DEFAULT_EDITION, f) . } . . #[inline] . pub fn create_session_if_not_set_then(edition: Edition, f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 1 ( 0.00%) if !SESSION_GLOBALS.is_set() { 3 ( 0.00%) let session_globals = SessionGlobals::new(edition); 11 ( 0.00%) SESSION_GLOBALS.set(&session_globals, || SESSION_GLOBALS.with(f)) 1 ( 0.00%) } else { . SESSION_GLOBALS.with(f) . } . } . . #[inline] . pub fn with_session_globals(f: F) -> R . where . F: FnOnce(&SessionGlobals) -> R, . { 403,357 ( 0.01%) SESSION_GLOBALS.with(f) . } . . #[inline] . pub fn create_default_session_globals_then(f: impl FnOnce() -> R) -> R { . create_session_globals_then(edition::DEFAULT_EDITION, f) . } . . // If this ever becomes non thread-local, `decode_syntax_context` . // and `decode_expn_id` will need to be updated to handle concurrent . // deserialization. . scoped_tls::scoped_thread_local!(static SESSION_GLOBALS: SessionGlobals); . . // FIXME: We should use this enum or something like it to get rid of the . // use of magic `/rust/1.x/...` paths across the board. 49 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)] 1,064 ( 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 3,027 ( 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> { 38 ( 0.00%) encoder.emit_enum(|encoder| match *self { . RealFileName::LocalPath(ref local_path) => { 152 ( 0.00%) encoder.emit_enum_variant("LocalPath", 0, 1, |encoder| { . encoder.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?; . Ok(()) . }) . } . . RealFileName::Remapped { ref local_path, ref virtual_name } => encoder . .emit_enum_variant("Remapped", 1, 2, |encoder| { . // For privacy and build reproducibility, we must not embed host-dependant path in artifacts -- line 205 ---------------------------------------- -- line 224 ---------------------------------------- . p.as_ref().map(PathBuf::as_path) . } . } . } . . /// Returns the path suitable for reading from the file system on the local host, . /// if this information exists. . /// Avoid embedding this in build artifacts; see `remapped_path_if_available()` for that. 2 ( 0.00%) pub fn into_local_path(self) -> Option { 2 ( 0.00%) match self { . RealFileName::LocalPath(p) => Some(p), . RealFileName::Remapped { local_path: p, virtual_name: _ } => p, . } 3 ( 0.00%) } . . /// Returns the path suitable for embedding into build artifacts. This would still . /// be a local path if it has not been remapped. A remapped path will not correspond . /// to a valid file system path: see `local_path_if_available()` for something that . /// is more likely to return paths into the local host file system. . pub fn remapped_path_if_available(&self) -> &Path { 2,360 ( 0.00%) match self { . RealFileName::LocalPath(p) . | RealFileName::Remapped { local_path: _, virtual_name: p } => &p, . } 20 ( 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 { 19 ( 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> { 19 ( 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. 6,265 ( 0.00%) #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] 6,666 ( 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 { 133 ( 0.00%) fn from(p: PathBuf) -> Self { 38 ( 0.00%) assert!(!p.to_string_lossy().ends_with('>')); 114 ( 0.00%) FileName::Real(RealFileName::LocalPath(p)) 133 ( 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<'_> { 76 ( 0.00%) fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { . use FileName::*; 114 ( 0.00%) match *self.inner { . Real(ref name) => { 114 ( 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, ""), . } 95 ( 0.00%) } . } . . impl FileNameDisplay<'_> { . pub fn to_string_lossy(&self) -> Cow<'_, str> { . match self.inner { . FileName::Real(ref inner) => inner.to_string_lossy(self.display_pref), . _ => Cow::from(format!("{}", self)), . } . } . } . . impl FileName { . pub fn is_real(&self) -> bool { . use FileName::*; 1,094 ( 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. 19 ( 0.00%) pub fn prefer_local(&self) -> FileNameDisplay<'_> { . FileNameDisplay { inner: self, display_pref: FileNameDisplayPreference::Local } 38 ( 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 { 4 ( 0.00%) pub lo: BytePos, 4 ( 0.00%) pub hi: BytePos, . /// Information about where the macro came from, if this piece of . /// code was created by a macro expansion. 12 ( 0.00%) pub ctxt: SyntaxContext, 4 ( 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 { 1,141,209 ( 0.02%) self.lo.0 == 0 && self.hi.0 == 0 . } . /// Returns `true` if `self` fully encloses `other`. . pub fn contains(self, other: Self) -> bool { 1,230 ( 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 { 43,152 ( 0.00%) fn partial_cmp(&self, rhs: &Self) -> Option { 32,364 ( 0.00%) PartialOrd::partial_cmp(&self.data(), &rhs.data()) 43,152 ( 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] 61,857 ( 0.00%) pub fn with_lo(self, lo: BytePos) -> Span { . self.data().with_lo(lo) 41,238 ( 0.00%) } . #[inline] 1,996 ( 0.00%) pub fn hi(self) -> BytePos { . self.data().hi 1,996 ( 0.00%) } . #[inline] 9,513 ( 0.00%) pub fn with_hi(self, hi: BytePos) -> Span { . self.data().with_hi(hi) 6,342 ( 0.00%) } . #[inline] . pub fn ctxt(self) -> SyntaxContext { . self.data_untracked().ctxt . } . #[inline] 5,440 ( 0.00%) pub fn with_ctxt(self, ctxt: SyntaxContext) -> Span { . self.data_untracked().with_ctxt(ctxt) 3,264 ( 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] 12 ( 0.00%) pub fn from_expansion(self) -> bool { . self.ctxt() != SyntaxContext::root() 8 ( 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 600 ---------------------------------------- . /// Returns a new span representing an empty span at the beginning of this span. . #[inline] . pub fn shrink_to_lo(self) -> Span { . let span = self.data_untracked(); . span.with_hi(span.lo) . } . /// Returns a new span representing an empty span at the end of this span. . #[inline] 117 ( 0.00%) pub fn shrink_to_hi(self) -> Span { . let span = self.data_untracked(); . span.with_lo(span.hi) 78 ( 0.00%) } . . #[inline] . /// Returns `true` if `hi == lo`. . pub fn is_empty(self) -> bool { . let span = self.data_untracked(); . span.hi == span.lo . } . . /// Returns `self` if `self` is not the dummy span, and `other` otherwise. . pub fn substitute_dummy(self, other: Span) -> Span { . if self.is_dummy() { other } else { self } . } . . /// Returns `true` if `self` fully encloses `other`. 3,690 ( 0.00%) pub fn contains(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.contains(other) 2,460 ( 0.00%) } . . /// Returns `true` if `self` touches `other`. . pub fn overlaps(self, other: Span) -> bool { . let span = self.data(); . let other = other.data(); . span.lo < other.hi && other.lo < span.hi . } . -- line 638 ---------------------------------------- -- line 663 ---------------------------------------- . /// The `Span` for the tokens in the previous macro expansion from which `self` was generated, . /// if any. . pub fn parent_callsite(self) -> Option { . let expn_data = self.ctxt().outer_expn_data(); . if !expn_data.is_root() { Some(expn_data.call_site) } else { None } . } . . /// Walk down the expansion ancestors to find a span that's contained within `outer`. 2,350 ( 0.00%) pub fn find_ancestor_inside(mut self, outer: Span) -> Option { 1,175 ( 0.00%) while !outer.contains(self) { . self = self.parent_callsite()?; . } . Some(self) 2,585 ( 0.00%) } . . /// Edition of the crate from which this span came. 16,041 ( 0.00%) pub fn edition(self) -> edition::Edition { . self.ctxt().edition() 10,694 ( 0.00%) } . . #[inline] . pub fn rust_2015(self) -> bool { 3,239 ( 0.00%) self.edition() == edition::Edition::Edition2015 . } . . #[inline] . pub fn rust_2018(self) -> bool { 2,252 ( 0.00%) self.edition() >= edition::Edition::Edition2018 . } . . #[inline] . pub fn rust_2021(self) -> bool { 1,734 ( 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]`). 4,005 ( 0.00%) pub fn allows_unstable(self, feature: Symbol) -> bool { 801 ( 0.00%) self.ctxt() . .outer_expn_data() . .allow_internal_unstable . .map_or(false, |features| features.iter().any(|&f| f == feature)) 3,204 ( 0.00%) } . . /// Checks if this span arises from a compiler desugaring of kind `kind`. 6,776 ( 0.00%) pub fn is_desugaring(self, kind: DesugaringKind) -> bool { 5,808 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => k == kind, . _ => false, . } 4,840 ( 0.00%) } . . /// Returns the compiler desugaring that created this span, or `None` . /// if this span is not from a desugaring. 315 ( 0.00%) pub fn desugaring_kind(self) -> Option { 378 ( 0.00%) match self.ctxt().outer_expn_data().kind { . ExpnKind::Desugaring(k) => Some(k), . _ => None, . } 252 ( 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]`). 68 ( 0.00%) pub fn allows_unsafe(self) -> bool { 17 ( 0.00%) self.ctxt().outer_expn_data().allow_internal_unsafe 68 ( 0.00%) } . . pub fn macro_backtrace(mut self) -> impl Iterator { . let mut prev_span = DUMMY_SP; . std::iter::from_fn(move || { . loop { . let expn_data = self.ctxt().outer_expn_data(); . if expn_data.is_root() { . return None; -- line 752 ---------------------------------------- -- line 767 ---------------------------------------- . . /// Returns a `Span` that would enclose both `self` and `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^^^^ . /// ``` 1,796,080 ( 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. 325,684 ( 0.01%) if span_data.ctxt != end_data.ctxt { 876 ( 0.00%) if span_data.ctxt == SyntaxContext::root() { . return end; 808 ( 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 }, 1,136,905 ( 0.02%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 1,469,520 ( 0.03%) } . . /// Returns a `Span` between the end of `self` to the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^ . /// ``` 550 ( 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 }, 350 ( 0.00%) if span.parent == end.parent { span.parent } else { None }, . ) 400 ( 0.00%) } . . /// Returns a `Span` from the beginning of `self` until the beginning of `end`. . /// . /// ```text . /// ____ ___ . /// self lorem ipsum end . /// ^^^^^^^^^^^^^^^^^ . /// ``` 2,431 ( 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. 442 ( 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 }, 1,547 ( 0.00%) if span_data.parent == end_data.parent { span_data.parent } else { None }, . ) 1,989 ( 0.00%) } . 693 ( 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, . ) 441 ( 0.00%) } . . /// Equivalent of `Span::def_site` from the proc macro API, . /// except that the location is taken from the `self` span. . pub fn with_def_site_ctxt(self, expn_id: ExpnId) -> Span { 1,970 ( 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 { 16 ( 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). 11,916 ( 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)) 6,951 ( 0.00%) } . . #[inline] . pub fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> Span { . let span = self.data(); 23,130 ( 0.00%) 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] 67,653 ( 0.00%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { 45,102 ( 0.00%) let mut span = self.data(); 37,399 ( 0.00%) let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); 67,653 ( 0.00%) *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark 74,984 ( 0.00%) } . . #[inline] . pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option> { . let mut span = self.data(); . let mark = span.ctxt.glob_adjust(expn_id, glob_span); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } -- line 922 ---------------------------------------- -- line 929 ---------------------------------------- . ) -> Option> { . let mut span = self.data(); . let mark = span.ctxt.reverse_glob_adjust(expn_id, glob_span); . *self = Span::new(span.lo, span.hi, span.ctxt, span.parent); . mark . } . . #[inline] 35,664 ( 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()) 31,206 ( 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 { 4,065 ( 0.00%) MultiSpan { primary_spans: vec![primary_span], span_labels: vec![] } . } . . pub fn from_spans(mut vec: Vec) -> MultiSpan { . vec.sort(); 185 ( 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() 154 ( 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 { 4,065 ( 0.00%) fn from(span: Span) -> MultiSpan { . MultiSpan::from_span(span) 4,065 ( 0.00%) } . } . . impl From> for MultiSpan { 185 ( 0.00%) fn from(spans: Vec) -> MultiSpan { 148 ( 0.00%) MultiSpan::from_spans(spans) 185 ( 0.00%) } . } . . /// Identifies an offset of a multi-byte character in a `SourceFile`. 462 ( 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`. 463 ( 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 { 44 ( 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 { 556 ( 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; . 160 ( 0.00%) fn sub(self, rhs: BytePos) -> Self { 556 ( 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), . } 480 ( 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, . } . 57 ( 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> { 630 ( 0.00%) match self { . ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src), . _ => None, . } . } . } . . #[derive(Debug)] . pub struct OffsetOverflowError; . 1,078 ( 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. 114 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Debug)] 2,156 ( 0.00%) #[derive(HashStable_Generic, Encodable, Decodable)] . pub struct SourceFileHash { . pub kind: SourceFileHashAlgorithm, . value: [u8; 32], . } . . impl SourceFileHash { . pub fn new(kind: SourceFileHashAlgorithm, src: &str) -> SourceFileHash { . let mut hash = SourceFileHash { kind, value: Default::default() }; . let len = hash.hash_len(); . let value = &mut hash.value[..len]; . let data = src.as_bytes(); . match kind { . SourceFileHashAlgorithm::Md5 => { 57 ( 0.00%) value.copy_from_slice(&Md5::digest(data)); . } . SourceFileHashAlgorithm::Sha1 => { . value.copy_from_slice(&Sha1::digest(data)); . } . SourceFileHashAlgorithm::Sha256 => { . value.copy_from_slice(&Sha256::digest(data)); . } . } -- line 1321 ---------------------------------------- -- line 1329 ---------------------------------------- . . /// The bytes of the hash. . pub fn hash_bytes(&self) -> &[u8] { . let len = self.hash_len(); . &self.value[..len] . } . . fn hash_len(&self) -> usize { 57 ( 0.00%) match self.kind { . SourceFileHashAlgorithm::Md5 => 16, . SourceFileHashAlgorithm::Sha1 => 20, . SourceFileHashAlgorithm::Sha256 => 32, . } . } . } . . /// A single source in the [`SourceMap`]. 1,102 ( 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. 19 ( 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. 19 ( 0.00%) pub name_hash: u128, . /// Indicates which crate this `SourceFile` was imported from. 19 ( 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)?; . 76 ( 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 { 38 ( 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); . 38 ( 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))?; 57 ( 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))?; 209 ( 0.00%) s.emit_struct_field("cnum", false, |s| self.cnum.encode(s)) . }) . } . } . . impl Decodable for SourceFile { 4,851 ( 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); 539 ( 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 { 891,582 ( 0.02%) let diff = match bytes_per_diff { . 1 => d.read_u8() as u32, . 2 => d.read_u16() as u32, . 4 => d.read_u32(), . _ => unreachable!(), . }; . . line_start = line_start + BytePos(diff); . -- line 1480 ---------------------------------------- -- line 1483 ---------------------------------------- . } . . lines . }); . let multibyte_chars: Vec = . d.read_struct_field("multibyte_chars", |d| Decodable::decode(d)); . let non_narrow_chars: Vec = . d.read_struct_field("non_narrow_chars", |d| Decodable::decode(d)); 1,078 ( 0.00%) let name_hash: u128 = d.read_struct_field("name_hash", |d| Decodable::decode(d)); . let normalized_pos: Vec = . d.read_struct_field("normalized_pos", |d| Decodable::decode(d)); . let cnum: CrateNum = d.read_struct_field("cnum", |d| Decodable::decode(d)); 5,929 ( 0.00%) SourceFile { 4,312 ( 0.00%) name, . start_pos, . end_pos, . src: None, 2,156 ( 0.00%) src_hash, . // Unused - the metadata decoder will construct . // a new SourceFile, filling in `external_src` properly . external_src: Lock::new(ExternalSource::Unneeded), 2,156 ( 0.00%) lines, 2,156 ( 0.00%) multibyte_chars, 2,156 ( 0.00%) non_narrow_chars, 2,156 ( 0.00%) normalized_pos, . name_hash, . cnum, . } . }) 4,851 ( 0.00%) } . } . . impl fmt::Debug for SourceFile { . fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(fmt, "SourceFile({:?})", self.name) . } . } . . impl SourceFile { 209 ( 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); 57 ( 0.00%) let normalized_pos = normalize_src(&mut src, start_pos); . . let name_hash = { . let mut hasher: StableHasher = StableHasher::new(); 38 ( 0.00%) name.hash(&mut hasher); . hasher.finish::() . }; 38 ( 0.00%) let end_pos = start_pos.to_usize() + src.len(); 57 ( 0.00%) assert!(end_pos <= u32::MAX as usize); . 228 ( 0.00%) let (lines, multibyte_chars, non_narrow_chars) = 38 ( 0.00%) analyze_source_file::analyze_source_file(&src, start_pos); . 323 ( 0.00%) SourceFile { . name, . src: Some(Lrc::new(src)), 209 ( 0.00%) src_hash, . external_src: Lock::new(ExternalSource::Unneeded), . start_pos, . end_pos: Pos::from_usize(end_pos), 76 ( 0.00%) lines, 76 ( 0.00%) multibyte_chars, 76 ( 0.00%) non_narrow_chars, 76 ( 0.00%) normalized_pos, . name_hash, . cnum: LOCAL_CRATE, . } 171 ( 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. 2,331 ( 0.00%) pub fn add_external_src(&self, get_src: F) -> bool . where . F: FnOnce() -> Option, . { 333 ( 0.00%) if matches!( 666 ( 0.00%) *self.external_src.borrow(), . ExternalSource::Foreign { kind: ExternalSourceKind::AbsentOk, .. } . ) { . let src = get_src(); . let mut external_src = self.external_src.borrow_mut(); . // Check that no-one else have provided the source while we were getting it . if let ExternalSource::Foreign { . kind: src_kind @ ExternalSourceKind::AbsentOk, .. . } = &mut *external_src -- line 1582 ---------------------------------------- -- line 1592 ---------------------------------------- . *src_kind = ExternalSourceKind::AbsentErr; . } . . false . } else { . self.src.is_some() || external_src.get_source().is_some() . } . } else { 333 ( 0.00%) self.src.is_some() || self.external_src.borrow().get_source().is_some() . } 2,997 ( 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() 547 ( 0.00%) } . . pub fn is_imported(&self) -> bool { . self.src.is_none() 155,048 ( 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 { 19,875 ( 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 { 46,149 ( 0.00%) if self.is_empty() { . return self.start_pos..self.end_pos; . } . 31,701 ( 0.00%) assert!(line_index < self.lines.len()); 45,096 ( 0.00%) if line_index == (self.lines.len() - 1) { 106 ( 0.00%) self.lines[line_index]..self.end_pos . } else { 29,984 ( 0.00%) self.lines[line_index]..self.lines[line_index + 1] . } . } . . /// Returns whether or not the file contains the given `SourceMap` byte . /// position. The position one past the end of the file is considered to be . /// contained by the file. This implies that files for which `is_empty` . /// returns true still contain one byte position according to this function. . #[inline] -- line 1674 ---------------------------------------- -- line 1692 ---------------------------------------- . Err(i) if i == 0 => 0, . Err(i) => self.normalized_pos[i - 1].diff, . }; . . BytePos::from_u32(pos.0 - self.start_pos.0 + diff) . } . . /// Converts an absolute `BytePos` to a `CharPos` relative to the `SourceFile`. 2 ( 0.00%) pub fn bytepos_to_file_charpos(&self, bpos: BytePos) -> CharPos { . // The number of extra bytes due to multibyte chars in the `SourceFile`. . let mut total_extra_bytes = 0; . 6 ( 0.00%) for mbc in self.multibyte_chars.iter() { . debug!("{}-byte char at {:?}", mbc.bytes, mbc.pos); 4 ( 0.00%) if mbc.pos < bpos { . // Every character is at least one byte, so we only . // count the actual extra bytes. 12 ( 0.00%) total_extra_bytes += mbc.bytes as u32 - 1; . // We should never see a byte position in the middle of a . // character. 10 ( 0.00%) assert!(bpos.to_u32() >= mbc.pos.to_u32() + mbc.bytes as u32); . } else { . break; . } . } . 12 ( 0.00%) assert!(self.start_pos.to_u32() + total_extra_bytes <= bpos.to_u32()); 10 ( 0.00%) CharPos(bpos.to_usize() - self.start_pos.to_usize() - total_extra_bytes as usize) 4 ( 0.00%) } . . /// Looks up the file's (1-based) line number and (0-based `CharPos`) column offset, for a . /// given `BytePos`. 7 ( 0.00%) pub fn lookup_file_pos(&self, pos: BytePos) -> (usize, CharPos) { 2 ( 0.00%) let chpos = self.bytepos_to_file_charpos(pos); . match self.lookup_line(pos) { . Some(a) => { . let line = a + 1; // Line numbers start at 1 1 ( 0.00%) let linebpos = self.lines[a]; 2 ( 0.00%) let linechpos = self.bytepos_to_file_charpos(linebpos); . let col = chpos - linechpos; . debug!("byte pos {:?} is on the line at byte pos {:?}", pos, linebpos); . debug!("char pos {:?} is on the line at char pos {:?}", chpos, linechpos); . debug!("byte is on line: {}", line); 1 ( 0.00%) assert!(chpos >= linechpos); . (line, col) . } . None => (0, chpos), . } 8 ( 0.00%) } . . /// Looks up the file's (1-based) line number, (0-based `CharPos`) column offset, and (0-based) . /// column offset when displayed, for a given `BytePos`. 8 ( 0.00%) pub fn lookup_file_pos_with_col_display(&self, pos: BytePos) -> (usize, CharPos, usize) { 3 ( 0.00%) let (line, col_or_chpos) = self.lookup_file_pos(pos); 2 ( 0.00%) if line > 0 { . let col = col_or_chpos; 1 ( 0.00%) let linebpos = self.lines[line - 1]; . let col_display = { . let start_width_idx = self . .non_narrow_chars . .binary_search_by_key(&linebpos, |x| x.pos()) . .unwrap_or_else(|x| x); . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); . let special_chars = end_width_idx - start_width_idx; . let non_narrow: usize = self.non_narrow_chars[start_width_idx..end_width_idx] . .iter() . .map(|x| x.width()) . .sum(); 5 ( 0.00%) col.0 - special_chars + non_narrow . }; . (line, col, col_display) . } else { . let chpos = col_or_chpos; . let col_display = { . let end_width_idx = self . .non_narrow_chars . .binary_search_by_key(&pos, |x| x.pos()) . .unwrap_or_else(|x| x); . let non_narrow: usize = . self.non_narrow_chars[0..end_width_idx].iter().map(|x| x.width()).sum(); . chpos.0 - end_width_idx + non_narrow . }; . (0, chpos, col_display) . } 7 ( 0.00%) } . } . . /// Normalizes the source code and records the normalizations. 190 ( 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 171 ( 0.00%) } . . /// Removes UTF-8 BOM, if any. . fn remove_bom(src: &mut String, normalized_pos: &mut Vec) { 19 ( 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) { 19 ( 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])* 340,599 ( 0.01%) $vis struct $ident($inner_vis $inner_ty); . . impl Pos for $ident { . #[inline(always)] . fn from_usize(n: usize) -> $ident { 12,027 ( 0.00%) $ident(n as $inner_ty) . } . . #[inline(always)] . fn to_usize(&self) -> usize { 924,668 ( 0.02%) self.0 as usize . } . . #[inline(always)] . fn from_u32(n: u32) -> $ident { . $ident(n as $inner_ty) . } . . #[inline(always)] -- line 1903 ---------------------------------------- -- line 1906 ---------------------------------------- . } . } . . impl Add for $ident { . type Output = $ident; . . #[inline(always)] . fn add(self, rhs: $ident) -> $ident { 2,986,583 ( 0.06%) $ident(self.0 + rhs.0) . } . } . . impl Sub for $ident { . type Output = $ident; . . #[inline(always)] . fn sub(self, rhs: $ident) -> $ident { 6,076,307 ( 0.12%) $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 { 65 ( 0.00%) fn encode(&self, s: &mut S) -> Result<(), S::Error> { . s.emit_u32(self.0) 78 ( 0.00%) } . } . . impl Decodable for BytePos { . fn decode(d: &mut D) -> BytePos { 125,764 ( 0.00%) BytePos(d.read_u32()) . } . } . . // _____________________________________________________________________________ . // Loc, SourceFileAndLine, SourceFileAndBytePos . // . . /// A source code location used for error reporting. -- line 1962 ---------------------------------------- -- line 2037 ---------------------------------------- . pub source_len: usize, . pub begin_pos: BytePos, . pub end_pos: BytePos, . } . . /// Range inside of a `Span` used for diagnostics when we only have access to relative positions. . #[derive(Copy, Clone, PartialEq, Eq, Debug)] . pub struct InnerSpan { 3 ( 0.00%) pub start: usize, . pub end: usize, . } . . impl InnerSpan { 322 ( 0.00%) pub fn new(start: usize, end: usize) -> InnerSpan { . InnerSpan { start, end } 161 ( 0.00%) } . } . . /// Requirements for a `StableHashingContext` to be used in this crate. . /// . /// This is a hack to allow using the [`HashStable_Generic`] derive macro . /// instead of implementing everything in rustc_middle. . pub trait HashStableContext { . fn def_path_hash(&self, def_id: DefId) -> DefPathHash; -- line 2060 ---------------------------------------- -- line 2079 ---------------------------------------- . /// offsets into the `SourceMap`). Instead, we hash the (file name, line, column) . /// triple, which stays the same even if the containing `SourceFile` has moved . /// within the `SourceMap`. . /// . /// Also note that we are hashing byte offsets for the column, not unicode . /// codepoint offsets. For the purpose of the hash that's sufficient. . /// Also, hashing filenames is expensive so we avoid doing it twice when the . /// span starts and ends in the same file, which is almost always the case. 2,289,133 ( 0.05%) fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { . const TAG_VALID_SPAN: u8 = 0; . const TAG_INVALID_SPAN: u8 = 1; . const TAG_RELATIVE_SPAN: u8 = 2; . 342,287 ( 0.01%) if !ctx.hash_spans() { . return; . } . 1,946,846 ( 0.04%) let span = self.data_untracked(); 935,269 ( 0.02%) span.ctxt.hash_stable(ctx, hasher); 981,057 ( 0.02%) span.parent.hash_stable(ctx, hasher); . 654,670 ( 0.01%) if span.is_dummy() { . Hash::hash(&TAG_INVALID_SPAN, hasher); . return; . } . 652,774 ( 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. 1,305,548 ( 0.03%) let (file, line_lo, col_lo, line_hi, col_hi) = match ctx.span_data_to_lines_and_cols(&span) . { 652,774 ( 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. . 326,387 ( 0.01%) let col_lo_trunc = (col_lo.0 as u64) & 0xFF; . let line_lo_trunc = ((line_lo as u64) & 0xFF_FF_FF) << 8; . let col_hi_trunc = (col_hi.0 as u64) & 0xFF << 32; . let line_hi_trunc = ((line_hi as u64) & 0xFF_FF_FF) << 40; . let col_line = col_lo_trunc | line_lo_trunc | col_hi_trunc | line_hi_trunc; 326,387 ( 0.01%) let len = (span.hi - span.lo).0; . Hash::hash(&col_line, hasher); . Hash::hash(&len, hasher); 2,616,152 ( 0.05%) } . } 6,390,356 ( 0.13%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/str/mod.rs -------------------------------------------------------------------------------- Ir -- line 159 ---------------------------------------- . /// let s = "not empty"; . /// assert!(!s.is_empty()); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[rustc_const_stable(feature = "const_str_is_empty", since = "1.39.0")] . #[must_use] . #[inline] . pub const fn is_empty(&self) -> bool { 951,375 ( 0.02%) self.len() == 0 . } . . /// Checks that `index`-th byte is the first byte in a UTF-8 code point . /// sequence or the end of the string. . /// . /// The start and end of the string (when `index == self.len()`) are . /// considered to be boundaries. . /// -- line 175 ---------------------------------------- -- line 193 ---------------------------------------- . #[must_use] . #[stable(feature = "is_char_boundary", since = "1.9.0")] . #[inline] . pub fn is_char_boundary(&self, index: usize) -> bool { . // 0 is always ok. . // Test for 0 explicitly so that it can optimize out the check . // easily and skip reading string data for that case. . // Note that optimizing `self.get(..index)` relies on this. 3,673,703 ( 0.08%) if index == 0 { . return true; . } . 1,843,322 ( 0.04%) match self.as_bytes().get(index) { . // For `None` we have two options: . // . // - index == self.len() . // Empty strings are valid, so return true . // - index > self.len() . // In this case return false . // . // The check is placed exactly here, because it improves generated . // code on higher opt-levels. See PR #84751 for more details. 760,814 ( 0.02%) None => index == self.len(), . . // This is bit magic equivalent to: b < 128 || b >= 192 1,093,621 ( 0.02%) Some(&b) => (b as i8) >= -0x40, . } . } . . /// Converts a string slice to a byte slice. To convert the byte slice back . /// into a string slice, use the [`from_utf8`] function. . /// . /// # Examples . /// -- line 226 ---------------------------------------- -- line 808 ---------------------------------------- . /// . /// assert_eq!(None, iter.next()); . /// ``` . #[must_use = "this returns the split string as an iterator, \ . without modifying the original"] . #[stable(feature = "split_whitespace", since = "1.1.0")] . #[inline] . pub fn split_whitespace(&self) -> SplitWhitespace<'_> { 9 ( 0.00%) SplitWhitespace { inner: self.split(IsWhitespace).filter(IsNotEmpty) } . } . . /// Splits a string slice by ASCII whitespace. . /// . /// The iterator returned will return string slices that are sub-slices of . /// the original string slice, separated by any amount of ASCII whitespace. . /// . /// To split by Unicode `Whitespace` instead, use [`split_whitespace`]. -- line 824 ---------------------------------------- -- line 1056 ---------------------------------------- . /// ``` . /// let s = "Löwe 老虎 Léopard"; . /// let x: &[_] = &['1', '2']; . /// . /// assert_eq!(s.find(x), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 6 ( 0.00%) pub fn find<'a, P: Pattern<'a>>(&'a self, pat: P) -> Option { 1 ( 0.00%) pat.into_searcher(self).next_match().map(|(i, _)| i) 2 ( 0.00%) } . . /// Returns the byte index for the first character of the rightmost match of the pattern in . /// this string slice. . /// . /// Returns [`None`] if the pattern doesn't match. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. -- line 1074 ---------------------------------------- -- line 1102 ---------------------------------------- . /// ``` . /// let s = "Löwe 老虎 Léopard"; . /// let x: &[_] = &['1', '2']; . /// . /// assert_eq!(s.rfind(x), None); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] 6,416 ( 0.00%) pub fn rfind<'a, P>(&'a self, pat: P) -> Option . where . P: Pattern<'a, Searcher: ReverseSearcher<'a>>, . { . pat.into_searcher(self).next_match_back().map(|(i, _)| i) 6,416 ( 0.00%) } . . /// An iterator over substrings of this string slice, separated by . /// characters matched by a pattern. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. . /// . /// [`char`]: prim@char -- line 1123 ---------------------------------------- -- line 1225 ---------------------------------------- . /// ``` . /// . /// Use [`split_whitespace`] for this behavior. . /// . /// [`split_whitespace`]: str::split_whitespace . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn split<'a, P: Pattern<'a>>(&'a self, pat: P) -> Split<'a, P> { 3,792 ( 0.00%) Split(SplitInternal { . start: 0, . end: self.len(), . matcher: pat.into_searcher(self), . allow_trailing_empty: true, . finished: false, . }) . } . -- line 1241 ---------------------------------------- -- line 1472 ---------------------------------------- . /// . /// ``` . /// let v: Vec<&str> = "abc1defXghi".splitn(2, |c| c == '1' || c == 'X').collect(); . /// assert_eq!(v, ["abc", "defXghi"]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn splitn<'a, P: Pattern<'a>>(&'a self, n: usize, pat: P) -> SplitN<'a, P> { 177 ( 0.00%) SplitN(SplitNInternal { iter: self.split(pat).0, count: n }) . } . . /// An iterator over substrings of this string slice, separated by a . /// pattern, starting from the end of the string, restricted to returning . /// at most `n` items. . /// . /// If `n` substrings are returned, the last substring (the `n`th substring) . /// will contain the remainder of the string. -- line 1488 ---------------------------------------- -- line 1540 ---------------------------------------- . /// ``` . /// assert_eq!("cfg".split_once('='), None); . /// assert_eq!("cfg=foo".split_once('='), Some(("cfg", "foo"))); . /// assert_eq!("cfg=foo=bar".split_once('='), Some(("cfg", "foo=bar"))); . /// ``` . #[stable(feature = "str_split_once", since = "1.52.0")] . #[inline] . pub fn split_once<'a, P: Pattern<'a>>(&'a self, delimiter: P) -> Option<(&'a str, &'a str)> { 30 ( 0.00%) let (start, end) = delimiter.into_searcher(self).next_match()?; . // SAFETY: `Searcher` is known to return valid indices. . unsafe { Some((self.get_unchecked(..start), self.get_unchecked(end..))) } . } . . /// Splits the string on the last occurrence of the specified delimiter and . /// returns prefix before delimiter and suffix after delimiter. . /// . /// # Examples -- line 1556 ---------------------------------------- -- line 1749 ---------------------------------------- . /// . /// assert_eq!("Hello\tworld", s.trim()); . /// ``` . #[inline] . #[must_use = "this returns the trimmed string as a slice, \ . without modifying the original"] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn trim(&self) -> &str { 8 ( 0.00%) self.trim_matches(|c: char| c.is_whitespace()) . } . . /// Returns a string slice with leading whitespace removed. . /// . /// 'Whitespace' is defined according to the terms of the Unicode Derived . /// Core Property `White_Space`. . /// . /// # Text directionality -- line 1765 ---------------------------------------- -- line 1825 ---------------------------------------- . /// let s = " עברית "; . /// assert!(Some('ת') == s.trim_end().chars().rev().next()); . /// ``` . #[inline] . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "trim_direction", since = "1.30.0")] . pub fn trim_end(&self) -> &str { 316 ( 0.00%) self.trim_end_matches(|c: char| c.is_whitespace()) . } . . /// Returns a string slice with leading whitespace removed. . /// . /// 'Whitespace' is defined according to the terms of the Unicode Derived . /// Core Property `White_Space`. . /// . /// # Text directionality -- line 1841 ---------------------------------------- -- line 1945 ---------------------------------------- . /// A more complex pattern, using a closure: . /// . /// ``` . /// assert_eq!("1foo1barXX".trim_matches(|c| c == '1' || c == 'X'), "foo1bar"); . /// ``` . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "rust1", since = "1.0.0")] 10,952 ( 0.00%) pub fn trim_matches<'a, P>(&'a self, pat: P) -> &'a str . where . P: Pattern<'a, Searcher: DoubleEndedSearcher<'a>>, . { . let mut i = 0; . let mut j = 0; . let mut matcher = pat.into_searcher(self); . if let Some((a, b)) = matcher.next_reject() { . i = a; -- line 1961 ---------------------------------------- -- line 1962 ---------------------------------------- . j = b; // Remember earliest known match, correct it below if . // last match is different . } . if let Some((_, b)) = matcher.next_reject_back() { . j = b; . } . // SAFETY: `Searcher` is known to return valid indices. . unsafe { self.get_unchecked(i..j) } 10,952 ( 0.00%) } . . /// Returns a string slice with all prefixes that match a pattern . /// repeatedly removed. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. . /// . /// [`char`]: prim@char -- line 1978 ---------------------------------------- -- line 1994 ---------------------------------------- . /// assert_eq!("123foo1bar123".trim_start_matches(char::is_numeric), "foo1bar123"); . /// . /// let x: &[_] = &['1', '2']; . /// assert_eq!("12foo1bar12".trim_start_matches(x), "foo1bar12"); . /// ``` . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "trim_direction", since = "1.30.0")] 8,310 ( 0.00%) pub fn trim_start_matches<'a, P: Pattern<'a>>(&'a self, pat: P) -> &'a str { . let mut i = self.len(); . let mut matcher = pat.into_searcher(self); . if let Some((a, _)) = matcher.next_reject() { . i = a; . } . // SAFETY: `Searcher` is known to return valid indices. . unsafe { self.get_unchecked(i..self.len()) } 8,310 ( 0.00%) } . . /// Returns a string slice with the prefix removed. . /// . /// If the string starts with the pattern `prefix`, returns substring after the prefix, wrapped . /// in `Some`. Unlike `trim_start_matches`, this method removes the prefix exactly once. . /// . /// If the string does not start with `prefix`, returns `None`. . /// -- line 2018 ---------------------------------------- -- line 2098 ---------------------------------------- . /// A more complex pattern, using a closure: . /// . /// ``` . /// assert_eq!("1fooX".trim_end_matches(|c| c == '1' || c == 'X'), "1foo"); . /// ``` . #[must_use = "this returns the trimmed string as a new slice, \ . without modifying the original"] . #[stable(feature = "trim_direction", since = "1.30.0")] 2,844 ( 0.00%) pub fn trim_end_matches<'a, P>(&'a self, pat: P) -> &'a str . where . P: Pattern<'a, Searcher: ReverseSearcher<'a>>, . { . let mut j = 0; . let mut matcher = pat.into_searcher(self); . if let Some((_, b)) = matcher.next_reject_back() { . j = b; . } . // SAFETY: `Searcher` is known to return valid indices. . unsafe { self.get_unchecked(0..j) } 3,160 ( 0.00%) } . . /// Returns a string slice with all prefixes that match a pattern . /// repeatedly removed. . /// . /// The [pattern] can be a `&str`, [`char`], a slice of [`char`]s, or a . /// function or closure that determines if a character matches. . /// . /// [`char`]: prim@char -- line 2125 ---------------------------------------- -- line 2240 ---------------------------------------- . /// ``` . /// let nope = "j".parse::(); . /// . /// assert!(nope.is_err()); . /// ``` . #[inline] . #[stable(feature = "rust1", since = "1.0.0")] . pub fn parse(&self) -> Result { 150 ( 0.00%) FromStr::from_str(self) . } . . /// Checks if all characters in this string are within the ASCII range. . /// . /// # Examples . /// . /// ``` . /// let ascii = "hello!\n"; -- line 2256 ---------------------------------------- -- line 2374 ---------------------------------------- . /// Using `to_string`: . /// . /// ``` . /// assert_eq!("❤\n!".escape_debug().to_string(), "❤\\n!"); . /// ``` . #[must_use = "this returns the escaped string as an iterator, \ . without modifying the original"] . #[stable(feature = "str_escape", since = "1.34.0")] 20 ( 0.00%) pub fn escape_debug(&self) -> EscapeDebug<'_> { . let mut chars = self.chars(); 20 ( 0.00%) EscapeDebug { . inner: chars . .next() . .map(|first| first.escape_debug_ext(EscapeDebugExtArgs::ESCAPE_ALL)) . .into_iter() . .flatten() . .chain(chars.flat_map(CharEscapeDebugContinue)), . } 16 ( 0.00%) } . . /// Return an iterator that escapes each char in `self` with [`char::escape_default`]. . /// . /// # Examples . /// . /// As an iterator: . /// . /// ``` -- line 2400 ---------------------------------------- -- line 2420 ---------------------------------------- . /// Using `to_string`: . /// . /// ``` . /// assert_eq!("❤\n!".escape_default().to_string(), "\\u{2764}\\n!"); . /// ``` . #[must_use = "this returns the escaped string as an iterator, \ . without modifying the original"] . #[stable(feature = "str_escape", since = "1.34.0")] 220 ( 0.00%) pub fn escape_default(&self) -> EscapeDefault<'_> { 880 ( 0.00%) EscapeDefault { inner: self.chars().flat_map(CharEscapeDefault) } 220 ( 0.00%) } . . /// Return an iterator that escapes each char in `self` with [`char::escape_unicode`]. . /// . /// # Examples . /// . /// As an iterator: . /// . /// ``` -- line 2438 ---------------------------------------- 1,872 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/token.rs -------------------------------------------------------------------------------- Ir -- line 12 ---------------------------------------- . use rustc_data_structures::sync::Lrc; . use rustc_macros::HashStable_Generic; . use rustc_span::symbol::{kw, sym}; . use rustc_span::symbol::{Ident, Symbol}; . use rustc_span::{self, edition::Edition, Span, DUMMY_SP}; . use std::borrow::Cow; . use std::{fmt, mem}; . 20,656 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum CommentKind { . Line, . Block, . } . 235 ( 0.00%) #[derive(Clone, PartialEq, Encodable, Decodable, Hash, Debug, Copy)] . #[derive(HashStable_Generic)] . pub enum BinOpToken { . Plus, . Minus, . Star, . Slash, . Percent, . Caret, . And, . Or, . Shl, . Shr, . } . . /// A delimiter token. 156,616 ( 0.00%) #[derive(Clone, PartialEq, Eq, Encodable, Decodable, Hash, Debug, Copy)] . #[derive(HashStable_Generic)] . pub enum DelimToken { . /// A round parenthesis (i.e., `(` or `)`). . Paren, . /// A square bracket (i.e., `[` or `]`). . Bracket, . /// A curly brace (i.e., `{` or `}`). . Brace, . /// An empty delimiter. . NoDelim, . } . 2,489 ( 0.00%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum LitKind { . Bool, // AST only, must never appear in a `Token` . Byte, . Char, . Integer, . Float, . Str, . StrRaw(u16), // raw string delimited by `n` hash symbols . ByteStr, . ByteStrRaw(u16), // raw byte string delimited by `n` hash symbols . Err, . } . . /// A literal token. 291,790 ( 0.01%) #[derive(Clone, Copy, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Lit { . pub kind: LitKind, . pub symbol: Symbol, . pub suffix: Option, . } . . impl fmt::Display for Lit { 690,140 ( 0.01%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 1,242,252 ( 0.03%) let Lit { kind, symbol, suffix } = *self; . match kind { . Byte => write!(f, "b'{}'", symbol)?, . Char => write!(f, "'{}'", symbol)?, 273 ( 0.00%) Str => write!(f, "\"{}\"", symbol)?, . StrRaw(n) => write!( . f, . "r{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, . ByteStr => write!(f, "b\"{}\"", symbol)?, . ByteStrRaw(n) => write!( . f, . "br{delim}\"{string}\"{delim}", . delim = "#".repeat(n as usize), . string = symbol . )?, 413,811 ( 0.01%) Integer | Float | Bool | Err => write!(f, "{}", symbol)?, . } . 276,056 ( 0.01%) if let Some(suffix) = suffix { . write!(f, "{}", suffix)?; . } . . Ok(()) 690,140 ( 0.01%) } . } . . impl LitKind { . /// An English article for the literal token kind. . pub fn article(self) -> &'static str { . match self { . Integer | Err => "an", . _ => "a", -- line 113 ---------------------------------------- -- line 130 ---------------------------------------- . crate fn may_have_suffix(self) -> bool { . matches!(self, Integer | Float | Err) . } . } . . impl Lit { . pub fn new(kind: LitKind, symbol: Symbol, suffix: Option) -> Lit { . Lit { kind, symbol, suffix } 968,748 ( 0.02%) } . } . 168 ( 0.00%) pub fn ident_can_begin_expr(name: Symbol, span: Span, is_raw: bool) -> bool { 294 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 124 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [ . kw::Async, . kw::Do, . kw::Box, . kw::Break, . kw::Const, . kw::Continue, -- line 152 ---------------------------------------- -- line 161 ---------------------------------------- . kw::True, . kw::Try, . kw::Unsafe, . kw::While, . kw::Yield, . kw::Static, . ] . .contains(&name) 210 ( 0.00%) } . . fn ident_can_begin_type(name: Symbol, span: Span, is_raw: bool) -> bool { 1,932 ( 0.00%) let ident_token = Token::new(Ident(name, is_raw), span); . 806 ( 0.00%) !ident_token.is_reserved_ident() . || ident_token.is_path_segment_keyword() . || [kw::Underscore, kw::For, kw::Impl, kw::Fn, kw::Unsafe, kw::Extern, kw::Typeof, kw::Dyn] . .contains(&name) . } . 28,116,254 ( 0.58%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub enum TokenKind { . /* Expression-operator symbols. */ . Eq, . Lt, . Le, . EqEq, . Ne, . Ge, . Gt, . AndAnd, . OrOr, . Not, . Tilde, 25,089 ( 0.00%) BinOp(BinOpToken), 60 ( 0.00%) BinOpEq(BinOpToken), . . /* Structural symbols */ . At, . Dot, . DotDot, . DotDotDot, . DotDotEq, . Comma, -- line 203 ---------------------------------------- -- line 208 ---------------------------------------- . LArrow, . FatArrow, . Pound, . Dollar, . Question, . /// Used by proc macros for representing lifetimes, not generated by lexer right now. . SingleQuote, . /// An opening delimiter (e.g., `{`). 43,602 ( 0.00%) OpenDelim(DelimToken), . /// A closing delimiter (e.g., `}`). 840,303 ( 0.02%) CloseDelim(DelimToken), . . /* Literals */ 422,439 ( 0.01%) Literal(Lit), . . /// Identifier token. . /// Do not forget about `NtIdent` when you want to match on identifiers. . /// It's recommended to use `Token::(ident,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated identifiers in the same way. 20,248 ( 0.00%) Ident(Symbol, /* is_raw */ bool), . /// Lifetime identifier token. . /// Do not forget about `NtLifetime` when you want to match on lifetime identifiers. . /// It's recommended to use `Token::(lifetime,uninterpolate,uninterpolated_span)` to . /// treat regular and interpolated lifetime identifiers in the same way. 1,401 ( 0.00%) Lifetime(Symbol), . 398 ( 0.00%) Interpolated(Lrc), . . /// A doc comment token. . /// `Symbol` is the doc comment's data excluding its "quotes" (`///`, `/**`, etc) . /// similarly to symbols in string literal tokens. 4,437 ( 0.00%) DocComment(CommentKind, ast::AttrStyle, Symbol), . . Eof, . } . . // `TokenKind` is used a lot. Make sure it doesn't unintentionally get bigger. . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . rustc_data_structures::static_assert_size!(TokenKind, 16); . 1,357,172 ( 0.03%) #[derive(Clone, PartialEq, Encodable, Decodable, Debug, HashStable_Generic)] . pub struct Token { 9,285 ( 0.00%) pub kind: TokenKind, 48 ( 0.00%) pub span: Span, . } . . impl TokenKind { . pub fn lit(kind: LitKind, symbol: Symbol, suffix: Option) -> TokenKind { . Literal(Lit::new(kind, symbol, suffix)) . } . . // An approximation to proc-macro-style single-character operators used by rustc parser. . // If the operator token can be broken into two tokens, the first of which is single-character, . // then this function performs that operation, otherwise it returns `None`. 3,032 ( 0.00%) pub fn break_two_token_op(&self) -> Option<(TokenKind, TokenKind)> { 13,457 ( 0.00%) Some(match *self { . Le => (Lt, Eq), . EqEq => (Eq, Eq), . Ne => (Not, Eq), . Ge => (Gt, Eq), . AndAnd => (BinOp(And), BinOp(And)), . OrOr => (BinOp(Or), BinOp(Or)), . BinOp(Shl) => (Lt, Lt), . BinOp(Shr) => (Gt, Gt), -- line 271 ---------------------------------------- -- line 280 ---------------------------------------- . BinOpEq(Shl) => (Lt, Le), . BinOpEq(Shr) => (Gt, Ge), . DotDot => (Dot, Dot), . DotDotDot => (Dot, DotDot), . ModSep => (Colon, Colon), . RArrow => (BinOp(Minus), Gt), . LArrow => (Lt, BinOp(Minus)), . FatArrow => (Eq, Gt), 2,781 ( 0.00%) _ => return None, . }) 3,032 ( 0.00%) } . . /// Returns tokens that are likely to be typed accidentally instead of the current token. . /// Enables better error recovery when the wrong token is found. . pub fn similar_tokens(&self) -> Option> { . match *self { . Comma => Some(vec![Dot, Lt, Semi]), . Semi => Some(vec![Colon, Comma]), . FatArrow => Some(vec![Eq, RArrow]), . _ => None, . } . } . . pub fn should_end_const_arg(&self) -> bool { 1,688 ( 0.00%) matches!(self, Gt | Ge | BinOp(Shr) | BinOpEq(Shr)) 326 ( 0.00%) } . } . . impl Token { 307,365 ( 0.01%) pub fn new(kind: TokenKind, span: Span) -> Self { 930,685 ( 0.02%) Token { kind, span } 307,365 ( 0.01%) } . . /// Some token that will be thrown away later. 2,378 ( 0.00%) pub fn dummy() -> Self { . Token::new(TokenKind::Question, DUMMY_SP) 2,378 ( 0.00%) } . . /// Recovers a `Token` from an `Ident`. This creates a raw identifier if necessary. . pub fn from_ast_ident(ident: Ident) -> Self { 1,000 ( 0.00%) Token::new(Ident(ident.name, ident.is_raw_guess()), ident.span) . } . . /// Return this token by value and leave a dummy token in its place. 298,474 ( 0.01%) pub fn take(&mut self) -> Self { . mem::replace(self, Token::dummy()) 298,474 ( 0.01%) } . . /// For interpolated tokens, returns a span of the fragment to which the interpolated . /// token refers. For all other tokens this is just a regular span. . /// It is particularly important to use this for identifiers and lifetimes . /// for which spans affect name resolution and edition checks. . /// Note that keywords are also identifiers, so they should use this . /// if they keep spans or perform edition checks. . pub fn uninterpolated_span(&self) -> Span { 2,100 ( 0.00%) match &self.kind { . Interpolated(nt) => nt.span(), 1,050 ( 0.00%) _ => self.span, . } 1,050 ( 0.00%) } . . pub fn is_op(&self) -> bool { 895,422 ( 0.02%) !matches!( 298,474 ( 0.01%) self.kind, . OpenDelim(..) . | CloseDelim(..) . | Literal(..) . | DocComment(..) . | Ident(..) . | Lifetime(..) . | Interpolated(..) . | Eof . ) 298,474 ( 0.01%) } . . pub fn is_like_plus(&self) -> bool { 10,872 ( 0.00%) matches!(self.kind, BinOp(Plus) | BinOpEq(Plus)) 2,126 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of an expression. 65 ( 0.00%) pub fn can_begin_expr(&self) -> bool { 325 ( 0.00%) match self.uninterpolate().kind { 378 ( 0.00%) Ident(name, is_raw) => 126 ( 0.00%) ident_can_begin_expr(name, self.span, is_raw), // value name or keyword . OpenDelim(..) | // tuple, array or block . Literal(..) | // literal . Not | // operator not . BinOp(Minus) | // unary minus . BinOp(Star) | // dereference . BinOp(Or) | OrOr | // closure . BinOp(And) | // reference . AndAnd | // double reference -- line 371 ---------------------------------------- -- line 376 ---------------------------------------- . Lifetime(..) | // labeled loop . Pound => true, // expression attributes . Interpolated(ref nt) => matches!(**nt, NtLiteral(..) | . NtExpr(..) | . NtBlock(..) | . NtPath(..)), . _ => false, . } 130 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a type. 1,420 ( 0.00%) pub fn can_begin_type(&self) -> bool { 1,917 ( 0.00%) match self.uninterpolate().kind { 2,898 ( 0.00%) Ident(name, is_raw) => 322 ( 0.00%) ident_can_begin_type(name, self.span, is_raw), // type name or keyword . OpenDelim(Paren) | // tuple . OpenDelim(Bracket) | // array . Not | // never . BinOp(Star) | // raw pointer . BinOp(And) | // reference . AndAnd | // double reference . Question | // maybe bound in trait object . Lifetime(..) | // lifetime bound in trait object . Lt | BinOp(Shl) | // associated path . ModSep => true, // global path . Interpolated(ref nt) => matches!(**nt, NtTy(..) | NtPath(..)), . _ => false, . } 2,130 ( 0.00%) } . . /// Returns `true` if the token can appear at the start of a const param. . pub fn can_begin_const_arg(&self) -> bool { 1,515 ( 0.00%) match self.kind { . OpenDelim(Brace) => true, . Interpolated(ref nt) => matches!(**nt, NtExpr(..) | NtBlock(..) | NtLiteral(..)), 303 ( 0.00%) _ => self.can_begin_literal_maybe_minus(), . } . } . . /// Returns `true` if the token can appear at the start of a generic bound. 3 ( 0.00%) pub fn can_begin_bound(&self) -> bool { 3 ( 0.00%) self.is_path_start() . || self.is_lifetime() . || self.is_keyword(kw::For) . || self == &Question . || self == &OpenDelim(Paren) 4 ( 0.00%) } . . /// Returns `true` if the token is any literal. . pub fn is_lit(&self) -> bool { . matches!(self.kind, Literal(..)) . } . . /// Returns `true` if the token is any literal, a minus (which can prefix a literal, . /// for example a '-42', or one of the boolean idents). . /// . /// In other words, would this token be a valid start of `parse_literal_maybe_minus`? . /// . /// Keep this in sync with and `Lit::from_token`, excluding unary negation. 306 ( 0.00%) pub fn can_begin_literal_maybe_minus(&self) -> bool { 3,053 ( 0.00%) match self.uninterpolate().kind { . Literal(..) | BinOp(Minus) => true, 1,212 ( 0.00%) Ident(name, false) if name.is_bool_lit() => true, . Interpolated(ref nt) => match &**nt { . NtLiteral(_) => true, . NtExpr(e) => match &e.kind { . ast::ExprKind::Lit(_) => true, . ast::ExprKind::Unary(ast::UnOp::Neg, e) => { . matches!(&e.kind, ast::ExprKind::Lit(_)) . } . _ => false, . }, . _ => false, . }, . _ => false, . } 612 ( 0.00%) } . . // A convenience function for matching on identifiers during parsing. . // Turns interpolated identifier (`$i: ident`) or lifetime (`$l: lifetime`) token . // into the regular identifier or lifetime token it refers to, . // otherwise returns the original token. 143,284 ( 0.00%) pub fn uninterpolate(&self) -> Cow<'_, Token> { 1,621,003 ( 0.03%) match &self.kind { 2,820 ( 0.00%) Interpolated(nt) => match **nt { 904 ( 0.00%) NtIdent(ident, is_raw) => { 2,260 ( 0.00%) Cow::Owned(Token::new(Ident(ident.name, is_raw), ident.span)) . } . NtLifetime(ident) => Cow::Owned(Token::new(Lifetime(ident.name), ident.span)), . _ => Cow::Borrowed(self), . }, . _ => Cow::Borrowed(self), . } 143,284 ( 0.00%) } . . /// Returns an identifier if this token is an identifier. 440,442 ( 0.01%) pub fn ident(&self) -> Option<(Ident, /* is_raw */ bool)> { . let token = self.uninterpolate(); 995,087 ( 0.02%) match token.kind { 748,861 ( 0.02%) Ident(name, is_raw) => Some((Ident::new(name, token.span), is_raw)), . _ => None, . } 2,681,487 ( 0.06%) } . . /// Returns a lifetime identifier if this token is a lifetime. 1,025 ( 0.00%) pub fn lifetime(&self) -> Option { . let token = self.uninterpolate(); 5,550 ( 0.00%) match token.kind { 3,678 ( 0.00%) Lifetime(name) => Some(Ident::new(name, token.span)), . _ => None, . } 7,175 ( 0.00%) } . . /// Returns `true` if the token is an identifier. . pub fn is_ident(&self) -> bool { . self.ident().is_some() 1,756 ( 0.00%) } . . /// Returns `true` if the token is a lifetime. 1,750 ( 0.00%) pub fn is_lifetime(&self) -> bool { . self.lifetime().is_some() 3,500 ( 0.00%) } . . /// Returns `true` if the token is an identifier whose name is the given . /// string slice. 1,514 ( 0.00%) pub fn is_ident_named(&self, name: Symbol) -> bool { . self.ident().map_or(false, |(ident, _)| ident.name == name) 3,028 ( 0.00%) } . . /// Returns `true` if the token is an interpolated path. . fn is_path(&self) -> bool { 13,896 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtPath(..) = **nt { . return true; . } . } . false . } . . /// Would `maybe_whole_expr` in `parser.rs` return `Ok(..)`? -- line 515 ---------------------------------------- -- line 522 ---------------------------------------- . } . } . . false . } . . // Is the token an interpolated block (`$b:block`)? . pub fn is_whole_block(&self) -> bool { 140 ( 0.00%) if let Interpolated(ref nt) = self.kind { . if let NtBlock(..) = **nt { . return true; . } . } . false 70 ( 0.00%) } . . /// Returns `true` if the token is either the `mut` or `const` keyword. . pub fn is_mutability(&self) -> bool { . self.is_keyword(kw::Mut) || self.is_keyword(kw::Const) . } . 1,082 ( 0.00%) pub fn is_qpath_start(&self) -> bool { 8,030 ( 0.00%) self == &Lt || self == &BinOp(Shl) . } . 14,656 ( 0.00%) pub fn is_path_start(&self) -> bool { 21,114 ( 0.00%) self == &ModSep . || self.is_qpath_start() . || self.is_path() . || self.is_path_segment_keyword() 2,862 ( 0.00%) || self.is_ident() && !self.is_reserved_ident() 18,320 ( 0.00%) } . . /// Returns `true` if the token is a given keyword, `kw`. 44,279 ( 0.00%) pub fn is_keyword(&self, kw: Symbol) -> bool { . self.is_non_raw_ident_where(|id| id.name == kw) 88,558 ( 0.00%) } . 620 ( 0.00%) pub fn is_path_segment_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_path_segment_keyword) . } . . // Returns true for reserved identifiers used internally for elided lifetimes, . // unnamed method parameters, crate root module, error recovery etc. 154 ( 0.00%) pub fn is_special_ident(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_special) . } . . /// Returns `true` if the token is a keyword used in the language. 154 ( 0.00%) pub fn is_used_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_used_keyword) . } . . /// Returns `true` if the token is a keyword reserved for possible future use. 154 ( 0.00%) pub fn is_unused_keyword(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_unused_keyword) . } . . /// Returns `true` if the token is either a special identifier or a keyword. . pub fn is_reserved_ident(&self) -> bool { . self.is_non_raw_ident_where(Ident::is_reserved) . } . . /// Returns `true` if the token is the identifier `true` or `false`. 636 ( 0.00%) pub fn is_bool_lit(&self) -> bool { 1,272 ( 0.00%) self.is_non_raw_ident_where(|id| id.name.is_bool_lit()) . } . . pub fn is_numeric_lit(&self) -> bool { . matches!( . self.kind, . Literal(Lit { kind: LitKind::Integer, .. }) | Literal(Lit { kind: LitKind::Float, .. }) . ) . } . . /// Returns `true` if the token is a non-raw identifier for which `pred` holds. 20 ( 0.00%) pub fn is_non_raw_ident_where(&self, pred: impl FnOnce(Ident) -> bool) -> bool { 2,254,177 ( 0.05%) match self.ident() { 2,807 ( 0.00%) Some((id, false)) => pred(id), . _ => false, . } 25 ( 0.00%) } . 1,447,520 ( 0.03%) pub fn glue(&self, joint: &Token) -> Option { 723,760 ( 0.01%) let kind = match self.kind { 668 ( 0.00%) Eq => match joint.kind { . Eq => EqEq, . Gt => FatArrow, . _ => return None, . }, 28 ( 0.00%) Lt => match joint.kind { . Eq => Le, . Lt => BinOp(Shl), . Le => BinOpEq(Shl), . BinOp(Minus) => LArrow, . _ => return None, . }, 868 ( 0.00%) Gt => match joint.kind { . Eq => Ge, . Gt => BinOp(Shr), . Ge => BinOpEq(Shr), . _ => return None, . }, 46 ( 0.00%) Not => match joint.kind { . Eq => Ne, . _ => return None, . }, 2,405 ( 0.00%) BinOp(op) => match joint.kind { . Eq => BinOpEq(op), 22 ( 0.00%) BinOp(And) if op == And => AndAnd, 9 ( 0.00%) BinOp(Or) if op == Or => OrOr, 170 ( 0.00%) Gt if op == Minus => RArrow, . _ => return None, . }, 153 ( 0.00%) Dot => match joint.kind { . Dot => DotDot, . DotDot => DotDotDot, . _ => return None, . }, . DotDot => match joint.kind { . Dot => DotDotDot, . Eq => DotDotEq, . _ => return None, . }, 1,890 ( 0.00%) Colon => match joint.kind { . Colon => ModSep, . _ => return None, . }, . SingleQuote => match joint.kind { . Ident(name, false) => Lifetime(Symbol::intern(&format!("'{}", name))), . _ => return None, . }, . . Le | EqEq | Ne | Ge | AndAnd | OrOr | Tilde | BinOpEq(..) | At | DotDotDot . | DotDotEq | Comma | Semi | ModSep | RArrow | LArrow | FatArrow | Pound | Dollar . | Question | OpenDelim(..) | CloseDelim(..) | Literal(..) | Ident(..) . | Lifetime(..) | Interpolated(..) | DocComment(..) | Eof => return None, . }; . 18,837 ( 0.00%) Some(Token::new(kind, self.span.to(joint.span))) 1,302,768 ( 0.03%) } . } . . impl PartialEq for Token { . fn eq(&self, rhs: &TokenKind) -> bool { 1,252,807 ( 0.03%) self.kind == *rhs . } . } . . #[derive(Clone, Encodable, Decodable)] . /// For interpolation during macro expansion. . pub enum Nonterminal { . NtItem(P), . NtBlock(P), -- line 675 ---------------------------------------- -- line 711 ---------------------------------------- . Path, . Vis, . TT, . } . . impl NonterminalKind { . /// The `edition` closure is used to get the edition for the given symbol. Doing . /// `span.edition()` is expensive, so we do it lazily. 300 ( 0.00%) pub fn from_symbol( . symbol: Symbol, . edition: impl FnOnce() -> Edition, . ) -> Option { 672 ( 0.00%) Some(match symbol { . sym::item => NonterminalKind::Item, . sym::block => NonterminalKind::Block, . sym::stmt => NonterminalKind::Stmt, . sym::pat => match edition() { . Edition::Edition2015 | Edition::Edition2018 => { . NonterminalKind::PatParam { inferred: true } . } . Edition::Edition2021 => NonterminalKind::PatWithOr, -- line 731 ---------------------------------------- -- line 737 ---------------------------------------- . sym::lifetime => NonterminalKind::Lifetime, . sym::literal => NonterminalKind::Literal, . sym::meta => NonterminalKind::Meta, . sym::path => NonterminalKind::Path, . sym::vis => NonterminalKind::Vis, . sym::tt => NonterminalKind::TT, . _ => return None, . }) 300 ( 0.00%) } . fn symbol(self) -> Symbol { . match self { . NonterminalKind::Item => sym::item, . NonterminalKind::Block => sym::block, . NonterminalKind::Stmt => sym::stmt, . NonterminalKind::PatParam { inferred: false } => sym::pat_param, . NonterminalKind::PatParam { inferred: true } | NonterminalKind::PatWithOr => sym::pat, . NonterminalKind::Expr => sym::expr, -- line 753 ---------------------------------------- 10,067,602 ( 0.21%) -------------------------------------------------------------------------------- -- 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 { 839,834 ( 0.02%) 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> { 2,834 ( 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> { 800 ( 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,242 ( 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> { 2,863,379 ( 0.06%) 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> { 425,136 ( 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 { 600,366 ( 0.01%) 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 { 19 ( 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 556 ---------------------------------------- . /// [`as_mut_ptr`]: slice::as_mut_ptr . #[stable(feature = "slice_ptr_range", since = "1.48.0")] . #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")] . #[inline] . pub const fn as_mut_ptr_range(&mut self) -> Range<*mut T> { . let start = self.as_mut_ptr(); . // SAFETY: See as_ptr_range() above for why `add` here is safe. . let end = unsafe { start.add(self.len()) }; 1 ( 0.00%) start..end . } . . /// Swaps two elements in the slice. . /// . /// # Arguments . /// . /// * a - The index of the first element . /// * b - The index of the second element -- line 572 ---------------------------------------- -- 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) { 2,780 ( 0.00%) let _ = &self[a]; 10,438 ( 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 644 ---------------------------------------- . /// ``` . /// let mut v = [1, 2, 3]; . /// v.reverse(); . /// assert!(v == [3, 2, 1]); . /// ``` . #[stable(feature = "rust1", since = "1.0.0")] . #[inline] . pub fn reverse(&mut self) { 2 ( 0.00%) let half_len = self.len() / 2; . let Range { start, end } = self.as_mut_ptr_range(); . . // These slices will skip the middle item for an odd length, . // since that one doesn't need to move. . let (front_half, back_half) = . // SAFETY: Both are subparts of the original slice, so the memory . // range is valid, and they don't overlap because they're each only . // half (or less) of the original slice. -- line 660 ---------------------------------------- -- 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 { 728 ( 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]) { 41,508 ( 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. 3,207 ( 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, . { 3,012 ( 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(); 11,623 ( 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()); 2,394 ( 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; 4,382,720 ( 0.09%) while left < right { 2,049,143 ( 0.04%) 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. 225,250 ( 0.00%) 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. 575,203 ( 0.01%) if cmp == Less { 1,005,204 ( 0.02%) left = mid + 1; 280,872 ( 0.01%) } else if cmp == Greater { . right = mid; . } else { . // SAFETY: same as the `get_unchecked` above . unsafe { crate::intrinsics::assume(mid < self.len()) }; . return Ok(mid); . } . 1,645,261 ( 0.03%) 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, . ); . } . 49,068 ( 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! 7,358 ( 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::()) }; 7,358 ( 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), 7,358 ( 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 ---------------------------------------- 3,991,752 ( 0.08%) -------------------------------------------------------------------------------- -- 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. 30,191 ( 0.00%) ensure_sufficient_stack(|| self.mirror_expr_inner(expr)) . } . 792 ( 0.00%) crate fn mirror_exprs(&mut self, exprs: &'tcx [hir::Expr<'tcx>]) -> Box<[ExprId]> { 419,367 ( 0.01%) exprs.iter().map(|expr| self.mirror_expr_inner(expr)).collect() 1,584 ( 0.00%) } . 1,309,392 ( 0.03%) pub(super) fn mirror_expr_inner(&mut self, hir_expr: &'tcx hir::Expr<'tcx>) -> ExprId { 1,018,416 ( 0.02%) 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); . 581,952 ( 0.01%) let mut expr = self.make_mirror_unadjusted(hir_expr); . 872,928 ( 0.02%) let adjustment_span = match self.adjustment_span { 5,290 ( 0.00%) Some((hir_id, span)) if hir_id == hir_expr.hir_id => Some(span), . _ => None, . }; . . // Now apply adjustments, if any. 581,952 ( 0.01%) for adjustment in self.typeck_results.expr_adjustments(hir_expr) { . debug!("make_mirror: expr={:?} applying adjustment={:?}", expr, adjustment); 8,624 ( 0.00%) let span = expr.span; 29,869 ( 0.00%) expr = 76,806 ( 0.00%) self.apply_adjustment(hir_expr, expr, adjustment, adjustment_span.unwrap_or(span)); . } . . // Next, wrap this up in the expr's scope. 1,891,344 ( 0.04%) expr = Expr { . temp_lifetime, 143,332 ( 0.00%) ty: expr.ty, 145,488 ( 0.00%) span: hir_expr.span, . kind: ExprKind::Scope { . region_scope: expr_scope, 2,618,784 ( 0.05%) value: self.thir.exprs.push(expr), 290,976 ( 0.01%) lint_level: LintLevel::Explicit(hir_expr.hir_id), . }, . }; . . // Finally, create a destruction scope, if any. 436,464 ( 0.01%) if let Some(region_scope) = 290,976 ( 0.01%) self.region_scope_tree.opt_destruction_scope(hir_expr.hir_id.local_id) . { 11,016 ( 0.00%) expr = Expr { . temp_lifetime, . ty: expr.ty, 918 ( 0.00%) span: hir_expr.span, . kind: ExprKind::Scope { . region_scope, 12,852 ( 0.00%) value: self.thir.exprs.push(expr), . lint_level: LintLevel::Inherited, . }, . }; . } . . // OK, all done! 3,200,736 ( 0.07%) self.thir.exprs.push(expr) 1,309,392 ( 0.03%) } . . fn apply_adjustment( . &mut self, . hir_expr: &'tcx hir::Expr<'tcx>, . mut expr: Expr<'tcx>, . adjustment: &Adjustment<'tcx>, . mut span: Span, . ) -> Expr<'tcx> { 8,534 ( 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>| { 4,788 ( 0.00%) if let ExprKind::Block { body } = &expr.kind { 3 ( 0.00%) if let Some(last_expr) = body.expr { 3 ( 0.00%) span = self.thir[last_expr].span; 2 ( 0.00%) expr.span = span; . } . } . }; . 38,929 ( 0.00%) let kind = match adjustment.kind { . Adjust::Pointer(PointerCast::Unsize) => { . adjust_span(&mut expr); 10,795 ( 0.00%) ExprKind::Pointer { cast: PointerCast::Unsize, source: self.thir.exprs.push(expr) } . } 799 ( 0.00%) Adjust::Pointer(cast) => ExprKind::Pointer { cast, source: self.thir.exprs.push(expr) }, 1,326 ( 0.00%) Adjust::NeverToAny => ExprKind::NeverToAny { source: self.thir.exprs.push(expr) }, . Adjust::Deref(None) => { . adjust_span(&mut expr); 29,903 ( 0.00%) ExprKind::Deref { arg: self.thir.exprs.push(expr) } . } 100 ( 0.00%) Adjust::Deref(Some(deref)) => { . // We don't need to do call adjust_span here since . // deref coercions always start with a built-in deref. 125 ( 0.00%) let call = deref.method_call(self.tcx(), expr.ty); . 150 ( 0.00%) expr = Expr { . temp_lifetime, 25 ( 0.00%) ty: self . .tcx 50 ( 0.00%) .mk_ref(deref.region, ty::TypeAndMut { ty: expr.ty, mutbl: deref.mutbl }), . span, . kind: ExprKind::Borrow { . borrow_kind: deref.mutbl.to_borrow_kind(), 375 ( 0.00%) arg: self.thir.exprs.push(expr), . }, . }; . 525 ( 0.00%) let expr = Box::new([self.thir.exprs.push(expr)]); . 325 ( 0.00%) self.overloaded_place(hir_expr, adjustment.target, Some(call), expr, deref.span) . } 6,820 ( 0.00%) Adjust::Borrow(AutoBorrow::Ref(_, m)) => ExprKind::Borrow { . borrow_kind: m.to_borrow_kind(), 23,870 ( 0.00%) arg: self.thir.exprs.push(expr), . }, . Adjust::Borrow(AutoBorrow::RawPtr(mutability)) => { 324 ( 0.00%) ExprKind::AddressOf { mutability, arg: self.thir.exprs.push(expr) } . } . }; . 81,073 ( 0.00%) Expr { temp_lifetime, ty: adjustment.target, span, kind } . } . 1,454,880 ( 0.03%) fn make_mirror_unadjusted(&mut self, expr: &'tcx hir::Expr<'tcx>) -> Expr<'tcx> { 581,952 ( 0.01%) let expr_ty = self.typeck_results().expr_ty(expr); 145,488 ( 0.00%) let expr_span = expr.span; 727,440 ( 0.01%) let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); . 875,752 ( 0.02%) let kind = match expr.kind { . // Here comes the interesting stuff: 1,326 ( 0.00%) hir::ExprKind::MethodCall(segment, ref args, fn_span) => { . // Rewrite a.b(c) into UFCS form like Trait::b(a, c) 3,094 ( 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. 1,768 ( 0.00%) let old_adjustment_span = self.adjustment_span.replace((args[0].hir_id, expr_span)); . tracing::info!("Using method span: {:?}", expr.span); 442 ( 0.00%) let args = self.mirror_exprs(args); 884 ( 0.00%) self.adjustment_span = old_adjustment_span; 3,094 ( 0.00%) ExprKind::Call { 442 ( 0.00%) ty: expr.ty, 6,188 ( 0.00%) fun: self.thir.exprs.push(expr), . args, . from_hir_call: true, . fn_span, . } . } . . hir::ExprKind::Call(ref fun, ref args) => { 1,888 ( 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)) . 152 ( 0.00%) let method = self.method_callee(expr, fun.span, None); . 79 ( 0.00%) let arg_tys = args.iter().map(|e| self.typeck_results().expr_ty_adjusted(e)); . let tupled_args = Expr { 38 ( 0.00%) ty: self.tcx.mk_tup(arg_tys), . temp_lifetime, 19 ( 0.00%) span: expr.span, 76 ( 0.00%) kind: ExprKind::Tuple { fields: self.mirror_exprs(args) }, . }; 247 ( 0.00%) let tupled_args = self.thir.exprs.push(tupled_args); . 95 ( 0.00%) ExprKind::Call { 38 ( 0.00%) ty: method.ty, 361 ( 0.00%) fun: self.thir.exprs.push(method), 76 ( 0.00%) args: Box::new([self.mirror_expr(fun), tupled_args]), . from_hir_call: true, 38 ( 0.00%) fn_span: expr.span, . } . } else { . let adt_data = 2,265 ( 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. 1,441 ( 0.00%) expr_ty.ty_adt_def().and_then(|adt_def| match path.res { 152 ( 0.00%) Res::Def(DefKind::Ctor(_, CtorKind::Fn), ctor_id) => { 304 ( 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 . }; 456 ( 0.00%) if let Some((adt_def, index)) = adt_data { 380 ( 0.00%) let substs = self.typeck_results().node_substs(fun.hir_id); 228 ( 0.00%) let user_provided_types = self.typeck_results().user_provided_types(); . let user_ty = 380 ( 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); . 76 ( 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 { 1,508 ( 0.00%) ExprKind::Call { 2,037 ( 0.00%) ty: self.typeck_results().node_type(fun.hir_id), 377 ( 0.00%) fun: self.mirror_expr(fun), 1,508 ( 0.00%) args: self.mirror_exprs(args), . from_hir_call: true, 377 ( 0.00%) fn_span: expr.span, . } . } . } . } . . hir::ExprKind::AddrOf(hir::BorrowKind::Ref, mutbl, ref arg) => { 5,065 ( 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) } . } . 8,470 ( 0.00%) hir::ExprKind::Block(ref blk, _) => ExprKind::Block { body: self.mirror_block(blk) }, . . hir::ExprKind::Assign(ref lhs, ref rhs, _) => { 192 ( 0.00%) ExprKind::Assign { lhs: self.mirror_expr(lhs), rhs: self.mirror_expr(rhs) } . } . 20 ( 0.00%) hir::ExprKind::AssignOp(op, ref lhs, ref rhs) => { 80 ( 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 { 100 ( 0.00%) ExprKind::AssignOp { 60 ( 0.00%) op: bin_op(op.node), 20 ( 0.00%) lhs: self.mirror_expr(lhs), 20 ( 0.00%) rhs: self.mirror_expr(rhs), . } . } . } . 138,450 ( 0.00%) hir::ExprKind::Lit(ref lit) => ExprKind::Literal { 553,800 ( 0.01%) literal: self.const_eval_literal(&lit.node, expr_ty, lit.span, false), . user_ty: None, . const_id: None, . }, . 183 ( 0.00%) hir::ExprKind::Binary(op, ref lhs, ref rhs) => { 732 ( 0.00%) if self.typeck_results().is_method_call(expr) { 51 ( 0.00%) let lhs = self.mirror_expr(lhs); 51 ( 0.00%) let rhs = self.mirror_expr(rhs); . self.overloaded_operator(expr, Box::new([lhs, rhs])) . } else { . // FIXME overflow 454 ( 0.00%) match op.node { 148 ( 0.00%) hir::BinOpKind::And => ExprKind::LogicalOp { . op: LogicalOp::And, 37 ( 0.00%) lhs: self.mirror_expr(lhs), 37 ( 0.00%) rhs: self.mirror_expr(rhs), . }, 40 ( 0.00%) hir::BinOpKind::Or => ExprKind::LogicalOp { . op: LogicalOp::Or, 10 ( 0.00%) lhs: self.mirror_expr(lhs), 10 ( 0.00%) rhs: self.mirror_expr(rhs), . }, . _ => { 340 ( 0.00%) let op = bin_op(op.node); 425 ( 0.00%) ExprKind::Binary { . op, 85 ( 0.00%) lhs: self.mirror_expr(lhs), 85 ( 0.00%) rhs: self.mirror_expr(rhs), . } . } . } . } . } . . hir::ExprKind::Index(ref lhs, ref index) => { 130 ( 0.00%) if self.typeck_results().is_method_call(expr) { . let lhs = self.mirror_expr(lhs); . let index = self.mirror_expr(index); 286 ( 0.00%) self.overloaded_place(expr, expr_ty, None, Box::new([lhs, index]), expr.span) . } else { 16 ( 0.00%) ExprKind::Index { lhs: self.mirror_expr(lhs), index: self.mirror_expr(index) } . } . } . . hir::ExprKind::Unary(hir::UnOp::Deref, ref arg) => { 1,280 ( 0.00%) if self.typeck_results().is_method_call(expr) { . let arg = self.mirror_expr(arg); 18 ( 0.00%) self.overloaded_place(expr, expr_ty, None, Box::new([arg]), expr.span) . } else { 762 ( 0.00%) ExprKind::Deref { arg: self.mirror_expr(arg) } . } . } . . hir::ExprKind::Unary(hir::UnOp::Not, ref arg) => { 30 ( 0.00%) if self.typeck_results().is_method_call(expr) { . let arg = self.mirror_expr(arg); . self.overloaded_operator(expr, Box::new([arg])) . } else { 18 ( 0.00%) ExprKind::Unary { op: UnOp::Not, arg: self.mirror_expr(arg) } . } . } . . hir::ExprKind::Unary(hir::UnOp::Neg, ref arg) => { . if self.typeck_results().is_method_call(expr) { . let arg = self.mirror_expr(arg); . self.overloaded_operator(expr, Box::new([arg])) . } else if let hir::ExprKind::Lit(ref lit) = arg.kind { -- line 362 ---------------------------------------- -- line 365 ---------------------------------------- . user_ty: None, . const_id: None, . } . } else { . ExprKind::Unary { op: UnOp::Neg, arg: self.mirror_expr(arg) } . } . } . 466 ( 0.00%) hir::ExprKind::Struct(ref qpath, ref fields, ref base) => match expr_ty.kind() { 466 ( 0.00%) ty::Adt(adt, substs) => match adt.adt_kind() { . AdtKind::Struct | AdtKind::Union => { 669 ( 0.00%) let user_provided_types = self.typeck_results().user_provided_types(); 892 ( 0.00%) let user_ty = user_provided_types.get(expr.hir_id).copied(); . debug!("make_mirror_unadjusted: (struct/union) user_ty={:?}", user_ty); 892 ( 0.00%) ExprKind::Adt(Box::new(Adt { 446 ( 0.00%) adt_def: adt, . variant_index: VariantIdx::new(0), 446 ( 0.00%) substs, . user_ty, 446 ( 0.00%) fields: self.field_refs(fields), 892 ( 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(), . }), . })) . } . AdtKind::Enum => { 60 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, expr.hir_id); 40 ( 0.00%) match res { 30 ( 0.00%) Res::Def(DefKind::Variant, variant_id) => { 10 ( 0.00%) assert!(base.is_none()); . 30 ( 0.00%) let index = adt.variant_index_with_id(variant_id); . let user_provided_types = 40 ( 0.00%) self.typeck_results().user_provided_types(); 40 ( 0.00%) let user_ty = user_provided_types.get(expr.hir_id).copied(); . debug!("make_mirror_unadjusted: (variant) user_ty={:?}", user_ty); . ExprKind::Adt(Box::new(Adt { 10 ( 0.00%) adt_def: adt, . variant_index: index, 20 ( 0.00%) substs, . user_ty, 20 ( 0.00%) fields: self.field_refs(fields), . base: None, . })) . } . _ => { . span_bug!(expr.span, "unexpected res: {:?}", res); . } . } . } . }, . _ => { . span_bug!(expr.span, "unexpected type for struct literal: {:?}", expr_ty); . } . }, . . hir::ExprKind::Closure(..) => { 51 ( 0.00%) let closure_ty = self.typeck_results().expr_ty(expr); 51 ( 0.00%) let (def_id, substs, movability) = match *closure_ty.kind() { . ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs), None), . ty::Generator(def_id, substs, movability) => { . (def_id, UpvarSubsts::Generator(substs), Some(movability)) . } . _ => { . span_bug!(expr.span, "closure expr w/o closure type: {:?}", closure_ty); . } . }; . 102 ( 0.00%) let upvars = self . .typeck_results . .closure_min_captures_flattened(def_id) . .zip(substs.upvar_tys()) . .map(|(captured_place, ty)| { 45 ( 0.00%) let upvars = self.capture_upvar(expr, captured_place, ty); 126 ( 0.00%) self.thir.exprs.push(upvars) . }) . .collect(); . . // Convert the closure fake reads, if any, from hir `Place` to ExprRef 17 ( 0.00%) let fake_reads = match self.typeck_results.closure_fake_reads.get(&def_id) { . Some(fake_reads) => fake_reads . .iter() . .map(|(place, cause, hir_id)| { . let expr = self.convert_captured_hir_place(expr, place.clone()); . (self.thir.exprs.push(expr), *cause, *hir_id) . }) . .collect(), . None => Vec::new(), . }; . 323 ( 0.00%) ExprKind::Closure { closure_id: def_id, substs, upvars, movability, fake_reads } . } . 2,232 ( 0.00%) hir::ExprKind::Path(ref qpath) => { 8,928 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, expr.hir_id); 8,928 ( 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 581 ---------------------------------------- . let count = match ty.kind() { . ty::Array(_, ct) => ct, . _ => span_bug!(expr.span, "unexpected repeat expr ty: {:?}", ty), . }; . . ExprKind::Repeat { value: self.mirror_expr(v), count } . } . hir::ExprKind::Ret(ref v) => { 69 ( 0.00%) ExprKind::Return { value: v.as_ref().map(|v| self.mirror_expr(v)) } . } 69 ( 0.00%) hir::ExprKind::Break(dest, ref value) => match dest.target_id { 115 ( 0.00%) Ok(target_id) => ExprKind::Break { . label: region::Scope { id: target_id.local_id, data: region::ScopeData::Node }, . value: value.as_ref().map(|value| self.mirror_expr(value)), . }, . Err(err) => bug!("invalid loop id for break: {}", err), . }, 3 ( 0.00%) hir::ExprKind::Continue(dest) => match dest.target_id { 4 ( 0.00%) Ok(loop_id) => ExprKind::Continue { . label: region::Scope { id: loop_id.local_id, data: region::ScopeData::Node }, . }, . Err(err) => bug!("invalid loop id for continue: {}", err), . }, 120 ( 0.00%) hir::ExprKind::Let(let_expr) => ExprKind::Let { 15 ( 0.00%) expr: self.mirror_expr(let_expr.init), 45 ( 0.00%) pat: self.pattern_from_hir(let_expr.pat), . }, 1,122 ( 0.00%) hir::ExprKind::If(cond, then, else_opt) => ExprKind::If { . if_then_scope: region::Scope { 102 ( 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)), . }, 575 ( 0.00%) hir::ExprKind::Match(ref discr, ref arms, _) => ExprKind::Match { 115 ( 0.00%) scrutinee: self.mirror_expr(discr), 736 ( 0.00%) arms: arms.iter().map(|a| self.convert_arm(a)).collect(), . }, . hir::ExprKind::Loop(ref body, ..) => { 95 ( 0.00%) let block_ty = self.typeck_results().node_type(body.hir_id); 114 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(body.hir_id.local_id); 76 ( 0.00%) let block = self.mirror_block(body); 285 ( 0.00%) let body = self.thir.exprs.push(Expr { . ty: block_ty, . temp_lifetime, 19 ( 0.00%) span: block.span, 152 ( 0.00%) kind: ExprKind::Block { body: block }, . }); 57 ( 0.00%) ExprKind::Loop { body } . } 1,496 ( 0.00%) hir::ExprKind::Field(ref source, ..) => ExprKind::Field { 374 ( 0.00%) lhs: self.mirror_expr(source), 2,244 ( 0.00%) name: Field::new(self.tcx.field_index(expr.hir_id, self.typeck_results)), . }, . hir::ExprKind::Cast(ref source, ref cast_ty) => { . // Check for a user-given type annotation on this `cast` 40 ( 0.00%) let user_provided_types = self.typeck_results.user_provided_types(); 60 ( 0.00%) let user_ty = user_provided_types.get(cast_ty.hir_id); . . debug!( . "cast({:?}) has ty w/ hir_id {:?} and user provided ty {:?}", . expr, cast_ty.hir_id, user_ty, . ); . . // Check to see if this cast is a "coercion cast", where the cast is actually done . // using a coercion (or is a no-op). 60 ( 0.00%) let cast = if self.typeck_results().is_coercion_cast(source.hir_id) { . // Convert the lexpr to a vexpr. 6 ( 0.00%) ExprKind::Use { source: self.mirror_expr(source) } 12 ( 0.00%) } else if self.typeck_results().expr_ty(source).is_region_ptr() { . // Special cased so that we can type check that the element . // type of the source matches the pointed to type of the . // destination. . ExprKind::Pointer { . source: self.mirror_expr(source), . cast: PointerCast::ArrayToPointer, . } . } else { -- line 660 ---------------------------------------- -- line 664 ---------------------------------------- . // enum's layout (or its tag type) to compute it during const eval . // Example: . // enum Foo { . // A, . // B = A as isize + 4, . // } . // The correct solution would be to add symbolic computations to miri, . // so we wouldn't have to compute and store the actual value 16 ( 0.00%) let var = if let hir::ExprKind::Path(ref qpath) = source.kind { 24 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, source.hir_id); 28 ( 0.00%) self.typeck_results().node_type(source.hir_id).ty_adt_def().and_then( . |adt_def| match res { . Res::Def( . DefKind::Ctor(CtorOf::Variant, CtorKind::Const), . variant_ctor_id, . ) => { . let idx = adt_def.variant_index_with_ctor_id(variant_ctor_id); . let (d, o) = adt_def.discriminant_def_for_variant(idx); . use rustc_middle::ty::util::IntTypeExt; -- line 682 ---------------------------------------- -- line 686 ---------------------------------------- . } . _ => None, . }, . ) . } else { . None . }; . 12 ( 0.00%) let source = if let Some((did, offset, var_ty)) = var { . let mk_const = |literal| Expr { . temp_lifetime, . ty: var_ty, . span: expr.span, . kind: ExprKind::Literal { literal, user_ty: None, const_id: None }, . }; . let offset = self.thir.exprs.push(mk_const(ty::Const::from_bits( . self.tcx, -- line 702 ---------------------------------------- -- line 723 ---------------------------------------- . ty: var_ty, . span: expr.span, . kind: bin, . }) . } . None => offset, . } . } else { 4 ( 0.00%) self.mirror_expr(source) . }; . . ExprKind::Cast { source: source } . }; . 20 ( 0.00%) if let Some(user_ty) = user_ty { . // NOTE: Creating a new Expr and wrapping a Cast inside of it may be . // inefficient, revisit this when performance becomes an issue. . let cast_expr = self.thir.exprs.push(Expr { . temp_lifetime, . ty: expr_ty, . span: expr.span, . kind: cast, . }); . debug!("make_mirror_unadjusted: (cast) user_ty={:?}", user_ty); . . ExprKind::ValueTypeAscription { source: cast_expr, user_ty: Some(*user_ty) } . } else { 40 ( 0.00%) cast . } . } . hir::ExprKind::Type(ref source, ref ty) => { . let user_provided_types = self.typeck_results.user_provided_types(); . let user_ty = user_provided_types.get(ty.hir_id).copied(); . debug!("make_mirror_unadjusted: (type) user_ty={:?}", user_ty); . 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) => { 392 ( 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) => { 2,925 ( 0.00%) ExprKind::Array { fields: self.mirror_exprs(fields) } . } 680 ( 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!(), . }; . 4,946,592 ( 0.10%) Expr { temp_lifetime, ty: expr_ty, span: expr.span, kind } 1,163,904 ( 0.02%) } . 10,296 ( 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); 6,864 ( 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, _) => { 8,008 ( 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 6,864 ( 0.00%) } . 7,293 ( 0.00%) fn method_callee( . &mut self, . expr: &hir::Expr<'_>, . span: Span, . overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>, . ) -> Expr<'tcx> { 3,366 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); 4,488 ( 0.00%) let (def_id, substs, user_ty) = match overloaded_callee { . Some((def_id, substs)) => (def_id, substs, None), . None => { . let (kind, def_id) = 4,824 ( 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") . }); 8,040 ( 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); 8,040 ( 0.00%) (def_id, self.typeck_results().node_substs(expr.hir_id), user_ty) . } . }; . let ty = self.tcx().mk_fn_def(def_id, substs); 7,293 ( 0.00%) Expr { . temp_lifetime, . ty, . span, . kind: ExprKind::Literal { . literal: ty::Const::zero_sized(self.tcx(), ty), 3,366 ( 0.00%) user_ty, . const_id: None, . }, . } 4,488 ( 0.00%) } . 1,863 ( 0.00%) fn convert_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) -> ArmId { 1,656 ( 0.00%) let arm = Arm { 621 ( 0.00%) pattern: self.pattern_from_hir(&arm.pat), . guard: arm.guard.as_ref().map(|g| match g { . 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)) . } . }), 207 ( 0.00%) body: self.mirror_expr(arm.body), 414 ( 0.00%) lint_level: LintLevel::Explicit(arm.hir_id), . scope: region::Scope { id: arm.hir_id.local_id, data: region::ScopeData::Node }, 207 ( 0.00%) span: arm.span, . }; 3,105 ( 0.00%) self.thir.arms.push(arm) 1,863 ( 0.00%) } . . fn convert_path_expr(&mut self, expr: &'tcx hir::Expr<'tcx>, res: Res) -> ExprKind<'tcx> { 15,624 ( 0.00%) let substs = self.typeck_results().node_substs(expr.hir_id); 16,404 ( 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(..) => { 4,250 ( 0.00%) let user_ty = self.user_substs_applied_to_res(expr.hir_id, res); . debug!("convert_path_expr: user_ty={:?}", user_ty); 425 ( 0.00%) ExprKind::Literal { . literal: ty::Const::zero_sized( 850 ( 0.00%) self.tcx, 1,275 ( 0.00%) self.typeck_results().node_type(expr.hir_id), . ), 3,400 ( 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) => { 1,647 ( 0.00%) let user_ty = self.user_substs_applied_to_res(expr.hir_id, res); . debug!("convert_path_expr: (const) user_ty={:?}", user_ty); 915 ( 0.00%) ExprKind::Literal { 2,196 ( 0.00%) literal: self.tcx.mk_const(ty::Const { . val: ty::ConstKind::Unevaluated(ty::Unevaluated::new( . ty::WithOptConstParam::unknown(def_id), . substs, . )), 549 ( 0.00%) ty: self.typeck_results().node_type(expr.hir_id), . }), 1,464 ( 0.00%) user_ty, . const_id: Some(def_id), . } . } . 780 ( 0.00%) Res::Def(DefKind::Ctor(_, CtorKind::Const), def_id) => { 780 ( 0.00%) let user_provided_types = self.typeck_results.user_provided_types(); 624 ( 0.00%) let user_provided_type = user_provided_types.get(expr.hir_id).copied(); . debug!("convert_path_expr: user_provided_type={:?}", user_provided_type); 624 ( 0.00%) let ty = self.typeck_results().node_type(expr.hir_id); 312 ( 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 { 156 ( 0.00%) adt_def, 780 ( 0.00%) variant_index: adt_def.variant_index_with_ctor_id(def_id), 156 ( 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 }), . } . } . 11,744 ( 0.00%) Res::Local(var_hir_id) => self.convert_var(var_hir_id), . . _ => span_bug!(expr.span, "res `{:?}` not yet implemented", res), . } . } . 14,770 ( 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 . ); . 16 ( 0.00%) if is_upvar { 63 ( 0.00%) ExprKind::UpvarRef { closure_def_id: self.body_owner, var_hir_id } . } else { 4,404 ( 0.00%) ExprKind::VarRef { id: var_hir_id } . } 11,816 ( 0.00%) } . 561 ( 0.00%) fn overloaded_operator( . &mut self, . expr: &'tcx hir::Expr<'tcx>, . args: Box<[ExprId]>, . ) -> ExprKind<'tcx> { 357 ( 0.00%) let fun = self.method_callee(expr, expr.span, None); 765 ( 0.00%) let fun = self.thir.exprs.push(fun); 357 ( 0.00%) ExprKind::Call { 255 ( 0.00%) ty: self.thir[fun].ty, . fun, . args, . from_hir_call: false, . fn_span: expr.span, . } 408 ( 0.00%) } . 686 ( 0.00%) fn overloaded_place( . &mut self, . expr: &'tcx hir::Expr<'tcx>, . place_ty: Ty<'tcx>, . overloaded_callee: Option<(DefId, SubstsRef<'tcx>)>, . args: Box<[ExprId]>, . span: Span, . ) -> ExprKind<'tcx> { . // For an overloaded *x or x[y] expression of type T, the method . // call returns an &T and we must add the deref so that the types . // line up (this is because `*x` and `x[y]` represent places): . . // Reconstruct the output assuming it's a reference with the . // same region and mutability as the receiver. This holds for . // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`. 392 ( 0.00%) let (region, mutbl) = match *self.thir[args[0]].ty.kind() { 98 ( 0.00%) ty::Ref(region, _, mutbl) => (region, mutbl), . _ => span_bug!(span, "overloaded_place: receiver is not a reference"), . }; 49 ( 0.00%) let ref_ty = self.tcx.mk_ref(region, ty::TypeAndMut { ty: place_ty, mutbl }); . . // construct the complete expression `foo()` for the overloaded call, . // which will yield the &T type 196 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(expr.hir_id.local_id); 294 ( 0.00%) let fun = self.method_callee(expr, span, overloaded_callee); 686 ( 0.00%) let fun = self.thir.exprs.push(fun); 294 ( 0.00%) let fun_ty = self.thir[fun].ty; 686 ( 0.00%) let ref_expr = self.thir.exprs.push(Expr { . temp_lifetime, . ty: ref_ty, . span, . kind: ExprKind::Call { ty: fun_ty, fun, args, from_hir_call: false, fn_span: span }, . }); . . // construct and return a deref wrapper `*foo()` 98 ( 0.00%) ExprKind::Deref { arg: ref_expr } 392 ( 0.00%) } . 99 ( 0.00%) fn convert_captured_hir_place( . &mut self, . closure_expr: &'tcx hir::Expr<'tcx>, . place: HirPlace<'tcx>, . ) -> Expr<'tcx> { 36 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id); . let var_ty = place.base_ty; . . // The result of capture analysis in `rustc_typeck/check/upvar.rs`represents a captured path . // as it's seen for use within the closure and not at the time of closure creation. . // . // That is we see expect to see it start from a captured upvar and not something that is local . // to the closure's parent. 18 ( 0.00%) let var_hir_id = match place.base { 18 ( 0.00%) HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id, . base => bug!("Expected an upvar, found {:?}", base), . }; . 153 ( 0.00%) let mut captured_place_expr = Expr { . temp_lifetime, . ty: var_ty, 9 ( 0.00%) span: closure_expr.span, 45 ( 0.00%) kind: self.convert_var(var_hir_id), . }; . . for proj in place.projections.iter() { . let kind = match proj.kind { . HirProjectionKind::Deref => { . ExprKind::Deref { arg: self.thir.exprs.push(captured_place_expr) } . } . HirProjectionKind::Field(field, ..) => { -- line 1071 ---------------------------------------- -- line 1082 ---------------------------------------- . } . }; . . captured_place_expr = . Expr { temp_lifetime, ty: proj.ty, span: closure_expr.span, kind }; . } . . captured_place_expr 81 ( 0.00%) } . 90 ( 0.00%) fn capture_upvar( . &mut self, . closure_expr: &'tcx hir::Expr<'tcx>, . captured_place: &'tcx ty::CapturedPlace<'tcx>, . upvar_ty: Ty<'tcx>, . ) -> Expr<'tcx> { . let upvar_capture = captured_place.info.capture_kind; . let captured_place_expr = 63 ( 0.00%) self.convert_captured_hir_place(closure_expr, captured_place.place.clone()); 27 ( 0.00%) let temp_lifetime = self.region_scope_tree.temporary_scope(closure_expr.hir_id.local_id); . 18 ( 0.00%) match upvar_capture { 30 ( 0.00%) ty::UpvarCapture::ByValue => captured_place_expr, . ty::UpvarCapture::ByRef(upvar_borrow) => { 35 ( 0.00%) let borrow_kind = match upvar_borrow { . ty::BorrowKind::ImmBorrow => BorrowKind::Shared, . ty::BorrowKind::UniqueImmBorrow => BorrowKind::Unique, . ty::BorrowKind::MutBorrow => BorrowKind::Mut { allow_two_phase_borrow: false }, . }; 49 ( 0.00%) Expr { . temp_lifetime, . ty: upvar_ty, 7 ( 0.00%) span: closure_expr.span, . kind: ExprKind::Borrow { . borrow_kind, 105 ( 0.00%) arg: self.thir.exprs.push(captured_place_expr), . }, . } . } . } 81 ( 0.00%) } . . /// 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 { 2,928 ( 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; 11,935 ( 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, . } . } . } . . impl ToBorrowKind for hir::Mutability { . fn to_borrow_kind(&self) -> BorrowKind { 50 ( 0.00%) match *self { . hir::Mutability::Mut => BorrowKind::Mut { allow_two_phase_borrow: false }, . hir::Mutability::Not => BorrowKind::Shared, . } . } . } . 210 ( 0.00%) fn bin_op(op: hir::BinOpKind) -> BinOp { 945 ( 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), . } 210 ( 0.00%) } 2,166,210 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/util/literal.rs -------------------------------------------------------------------------------- Ir -- line 19 ---------------------------------------- . InvalidFloatSuffix, . NonDecimalFloat(u32), . IntTooLarge, . } . . impl LitKind { . /// Converts literal token into a semantic literal. . fn from_lit_token(lit: token::Lit) -> Result { 138,419 ( 0.00%) let token::Lit { kind, symbol, suffix } = lit; 138,419 ( 0.00%) if suffix.is_some() && !kind.may_have_suffix() { . return Err(LitError::InvalidSuffix); . } . 694,983 ( 0.01%) Ok(match kind { . token::Bool => { 108 ( 0.00%) assert!(symbol.is_bool_lit()); . LitKind::Bool(symbol == kw::True) . } . token::Byte => { . return unescape_byte(symbol.as_str()) . .map(LitKind::Byte) . .map_err(|_| LitError::LexerError); . } . token::Char => { 60 ( 0.00%) return unescape_char(symbol.as_str()) . .map(LitKind::Char) . .map_err(|_| LitError::LexerError); . } . . // There are some valid suffixes for integer and float literals, . // so all the handling is done internally. 414,129 ( 0.01%) token::Integer => return integer_lit(symbol, suffix), . token::Float => return float_lit(symbol, suffix), . . token::Str => { . // If there are no characters requiring special treatment we can . // reuse the symbol from the token. Otherwise, we must generate a . // new symbol because the string in the LitKind is different to the . // string in the token. 996 ( 0.00%) let s = symbol.as_str(); . let symbol = . if s.contains(&['\\', '\r']) { . let mut buf = String::with_capacity(s.len()); 44 ( 0.00%) let mut error = Ok(()); 176 ( 0.00%) unescape_literal(&s, Mode::Str, &mut |_, unescaped_char| { 1,082 ( 0.00%) match unescaped_char { 1,082 ( 0.00%) Ok(c) => buf.push(c), . Err(err) => { . if err.is_fatal() { . error = Err(LitError::LexerError); . } . } . } . }); 66 ( 0.00%) error?; 22 ( 0.00%) Symbol::intern(&buf) . } else { 620 ( 0.00%) symbol . }; 1,660 ( 0.00%) LitKind::Str(symbol, ast::StrStyle::Cooked) . } . token::StrRaw(n) => { . // Ditto. 6 ( 0.00%) let s = symbol.as_str(); . let symbol = 2 ( 0.00%) if s.contains('\r') { . let mut buf = String::with_capacity(s.len()); . let mut error = Ok(()); . unescape_literal(&s, Mode::RawStr, &mut |_, unescaped_char| { . match unescaped_char { . Ok(c) => buf.push(c), . Err(err) => { . if err.is_fatal() { . error = Err(LitError::LexerError); . } . } . } . }); . error?; . Symbol::intern(&buf) . } else { 4 ( 0.00%) symbol . }; 10 ( 0.00%) LitKind::Str(symbol, ast::StrStyle::Raw(n)) . } . token::ByteStr => { . let s = symbol.as_str(); . let mut buf = Vec::with_capacity(s.len()); . let mut error = Ok(()); . unescape_byte_literal(&s, Mode::ByteStr, &mut |_, unescaped_byte| { . match unescaped_byte { . Ok(c) => buf.push(c), -- line 110 ---------------------------------------- -- line 138 ---------------------------------------- . } else { . symbol.to_string().into_bytes() . }; . . LitKind::ByteStr(bytes.into()) . } . token::Err => LitKind::Err(symbol), . }) 138,058 ( 0.00%) } . . /// Attempts to recover a token from semantic literal. . /// This function is used when the original token doesn't exist (e.g. the literal is created . /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing). 830,286 ( 0.02%) pub fn to_lit_token(&self) -> token::Lit { 692,345 ( 0.01%) let (kind, symbol, suffix) = match *self { 660 ( 0.00%) LitKind::Str(symbol, ast::StrStyle::Cooked) => { . // Don't re-intern unless the escaped string is different. 880 ( 0.00%) let s = symbol.as_str(); 440 ( 0.00%) let escaped = s.escape_default().to_string(); 458 ( 0.00%) let symbol = if s == escaped { symbol } else { Symbol::intern(&escaped) }; . (token::Str, symbol, None) . } . LitKind::Str(symbol, ast::StrStyle::Raw(n)) => (token::StrRaw(n), symbol, None), . LitKind::ByteStr(ref bytes) => { . let string = bytes . .iter() . .cloned() . .flat_map(ascii::escape_default) -- line 165 ---------------------------------------- -- line 166 ---------------------------------------- . .map(Into::::into) . .collect::(); . (token::ByteStr, Symbol::intern(&string), None) . } . LitKind::Byte(byte) => { . let string: String = ascii::escape_default(byte).map(Into::::into).collect(); . (token::Byte, Symbol::intern(&string), None) . } 126 ( 0.00%) LitKind::Char(ch) => { . let string: String = ch.escape_default().map(Into::::into).collect(); 126 ( 0.00%) (token::Char, Symbol::intern(&string), None) . } 690,335 ( 0.01%) LitKind::Int(n, ty) => { 414,201 ( 0.01%) let suffix = match ty { . ast::LitIntType::Unsigned(ty) => Some(ty.name()), . ast::LitIntType::Signed(ty) => Some(ty.name()), . ast::LitIntType::Unsuffixed => None, . }; 690,335 ( 0.01%) (token::Integer, sym::integer(n), suffix) . } . LitKind::Float(symbol, ty) => { . let suffix = match ty { . ast::LitFloatType::Suffixed(ty) => Some(ty.name()), . ast::LitFloatType::Unsuffixed => None, . }; . (token::Float, symbol, suffix) . } 93 ( 0.00%) LitKind::Bool(value) => { 124 ( 0.00%) let symbol = if value { kw::True } else { kw::False }; . (token::Bool, symbol, None) . } . LitKind::Err(symbol) => (token::Err, symbol, None), . }; . . token::Lit::new(kind, symbol, suffix) 968,667 ( 0.02%) } . } . . impl Lit { . /// Converts literal token into an AST literal. 1,937,866 ( 0.04%) pub fn from_lit_token(token: token::Lit, span: Span) -> Result { 830,514 ( 0.02%) Ok(Lit { token, kind: LitKind::from_lit_token(token)?, span }) 1,245,771 ( 0.03%) } . . /// Converts arbitrary token into an AST literal. . /// . /// Keep this in sync with `Token::can_begin_literal_or_bool` excluding unary negation. 1,251,432 ( 0.03%) pub fn from_token(token: &Token) -> Result { 421,736 ( 0.01%) let lit = match token.uninterpolate().kind { 4,017 ( 0.00%) token::Ident(name, false) if name.is_bool_lit() => { . token::Lit::new(token::Bool, name, None) . } 553,568 ( 0.01%) token::Literal(lit) => lit, . token::Interpolated(ref nt) => { . if let token::NtExpr(expr) | token::NtLiteral(expr) = &**nt { . if let ast::ExprKind::Lit(lit) = &expr.kind { . return Ok(lit.clone()); . } . } . return Err(LitError::NotLiteral); . } . _ => return Err(LitError::NotLiteral), . }; . 415,257 ( 0.01%) Lit::from_lit_token(lit, token.span) 1,251,432 ( 0.03%) } . . /// Attempts to recover an AST literal from semantic literal. . /// This function is used when the original token doesn't exist (e.g. the literal is created . /// by an AST-based macro) or unavailable (e.g. from HIR pretty-printing). 2,118 ( 0.00%) pub fn from_lit_kind(kind: LitKind, span: Span) -> Lit { 3,177 ( 0.00%) Lit { token: kind.to_lit_token(), kind, span } 1,765 ( 0.00%) } . . /// Losslessly convert an AST literal into a token. . pub fn to_token(&self) -> Token { . let kind = match self.token.kind { . token::Bool => token::Ident(self.token.symbol, false), . _ => token::Literal(self.token), . }; . Token::new(kind, self.span) . } . } . 1,242,387 ( 0.03%) fn strip_underscores(symbol: Symbol) -> Symbol { . // Do not allocate a new string unless necessary. 414,129 ( 0.01%) let s = symbol.as_str(); 138,043 ( 0.00%) if s.contains('_') { . let mut s = s.to_string(); . s.retain(|c| c != '_'); . return Symbol::intern(&s); . } 138,043 ( 0.00%) symbol 1,242,387 ( 0.03%) } . . fn filtered_float_lit( . symbol: Symbol, . suffix: Option, . base: u32, . ) -> Result { . debug!("filtered_float_lit: {:?}, {:?}, {:?}", symbol, suffix, base); . if base != 10 { -- line 267 ---------------------------------------- -- line 280 ---------------------------------------- . }) . } . . fn float_lit(symbol: Symbol, suffix: Option) -> Result { . debug!("float_lit: {:?}, {:?}", symbol, suffix); . filtered_float_lit(strip_underscores(symbol), suffix, 10) . } . 1,242,387 ( 0.03%) fn integer_lit(symbol: Symbol, suffix: Option) -> Result { . debug!("integer_lit: {:?}, {:?}", symbol, suffix); 552,172 ( 0.01%) let symbol = strip_underscores(symbol); 690,215 ( 0.01%) let s = symbol.as_str(); . 67,035 ( 0.00%) let base = match s.as_bytes() { 276,086 ( 0.01%) [b'0', b'x', ..] => 16, . [b'0', b'o', ..] => 8, . [b'0', b'b', ..] => 2, . _ => 10, . }; . 276,086 ( 0.01%) let ty = match suffix { . Some(suf) => match suf { . sym::isize => ast::LitIntType::Signed(ast::IntTy::Isize), . sym::i8 => ast::LitIntType::Signed(ast::IntTy::I8), . sym::i16 => ast::LitIntType::Signed(ast::IntTy::I16), . sym::i32 => ast::LitIntType::Signed(ast::IntTy::I32), . sym::i64 => ast::LitIntType::Signed(ast::IntTy::I64), . sym::i128 => ast::LitIntType::Signed(ast::IntTy::I128), . sym::usize => ast::LitIntType::Unsigned(ast::UintTy::Usize), -- line 308 ---------------------------------------- -- line 314 ---------------------------------------- . // `1f64` and `2f32` etc. are valid float literals, and . // `fxxx` looks more like an invalid float literal than invalid integer literal. . _ if suf.as_str().starts_with('f') => return filtered_float_lit(symbol, suffix, base), . _ => return Err(LitError::InvalidIntSuffix), . }, . _ => ast::LitIntType::Unsuffixed, . }; . 276,086 ( 0.01%) let s = &s[if base != 10 { 2 } else { 0 }..]; 552,172 ( 0.01%) u128::from_str_radix(s, base).map(|i| LitKind::Int(i, ty)).map_err(|_| { . // Small bases are lexed as if they were base 10, e.g, the string . // might be `0b10201`. This will cause the conversion above to fail, . // but these kinds of errors are already reported by the lexer. . let from_lexer = . base < 10 && s.chars().any(|c| c.to_digit(10).map_or(false, |d| d >= base)); . if from_lexer { LitError::LexerError } else { LitError::IntTooLarge } . }) 1,242,387 ( 0.03%) } 1,931,867 ( 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 { 51,114 ( 0.00%) &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, ()> { 6,621 ( 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> { . vec![] . } . . fn simple<'tcx>(kind: Adjust<'tcx>) -> impl FnOnce(Ty<'tcx>) -> Vec> { 307 ( 0.00%) move |target| vec![Adjustment { kind, target }] . } . . /// This always returns `Ok(...)`. . fn success<'tcx>( . adj: Vec>, . target: Ty<'tcx>, . obligations: traits::PredicateObligations<'tcx>, . ) -> CoerceResult<'tcx> { 11,941 ( 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 { 35,948 ( 0.00%) Coerce { fcx, cause, allow_two_phase, use_lub: false } . } . 84,337 ( 0.00%) 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(|_| { 15,334 ( 0.00%) if self.use_lub { 236 ( 0.00%) self.at(&self.cause, self.fcx.param_env).lub(b, a) . } else { 15,098 ( 0.00%) self.at(&self.cause, self.fcx.param_env) . .sup(b, a) . .map(|InferOk { value: (), obligations }| InferOk { value: a, obligations }) . } . }) 61,336 ( 0.00%) } . . /// Unify two types (using sub or lub) and produce a specific coercion. 11,828 ( 0.00%) fn unify_and(&self, a: Ty<'tcx>, b: Ty<'tcx>, f: F) -> CoerceResult<'tcx> . where . F: FnOnce(Ty<'tcx>) -> Vec>, . { 18,643 ( 0.00%) self.unify(&a, &b) 15,730 ( 0.00%) .and_then(|InferOk { value: ty, obligations }| success(f(ty), ty, obligations)) 8,871 ( 0.00%) } . 95,025 ( 0.00%) #[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): 4,525 ( 0.00%) let a = self.shallow_resolve(a); 4,525 ( 0.00%) let b = self.shallow_resolve(b); . debug!("Coerce.tys({:?} => {:?})", a, b); . . // Just ignore error types. 9,050 ( 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: 4,525 ( 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. 4,576 ( 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)); 16,514 ( 0.00%) match unsize { . Ok(_) => { . debug!("coerce: unsize successful"); 9,525 ( 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. 17,517 ( 0.00%) match *b.kind() { 18 ( 0.00%) ty::RawPtr(mt_b) => { 108 ( 0.00%) return self.coerce_unsafe_ptr(a, b, mt_b.mutbl); . } 1,538 ( 0.00%) ty::Ref(r_b, _, mutbl_b) => { 4,614 ( 0.00%) return self.coerce_borrowed_pointer(a, b, r_b, mutbl_b); . } . _ => {} . } . 20,976 ( 0.00%) 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. 288 ( 0.00%) self.coerce_from_fn_item(a, b) . } . ty::FnPtr(a_f) => { . // We permit coercion of fn pointers to drop the . // unsafe qualifier. . self.coerce_from_fn_pointer(a, a_f, b) . } 57 ( 0.00%) 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. 152 ( 0.00%) self.coerce_closure_to_fn(a, closure_def_id_a, substs_a, b) . } . _ => { . // Otherwise, just use unification rules. 14,785 ( 0.00%) self.unify_and(a, b, identity) . } . } 9,050 ( 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>, . make_adjustments: impl FnOnce(Ty<'tcx>) -> Vec>, . ) -> CoerceResult<'tcx> { . debug!("coerce_from_inference_variable(a={:?}, b={:?})", a, b); 8 ( 0.00%) assert!(a.is_ty_var() && self.infcx.shallow_resolve(a) == a); 8 ( 0.00%) assert!(self.infcx.shallow_resolve(b) == b); . 12 ( 0.00%) if b.is_ty_var() { . // Two unresolved type variables: create a `Coerce` predicate. 6 ( 0.00%) let target_ty = if self.use_lub { . self.infcx.next_ty_var(TypeVariableOrigin { . kind: TypeVariableOriginKind::LatticeVariable, . span: self.cause.span, . }) . } else { . b . }; . . let mut obligations = Vec::with_capacity(2); . for &source_ty in &[a, b] { 4 ( 0.00%) if source_ty != target_ty { . obligations.push(Obligation::new( . self.cause.clone(), 2 ( 0.00%) self.param_env, 8 ( 0.00%) ty::Binder::dummy(ty::PredicateKind::Coerce(ty::CoercePredicate { . a: source_ty, . b: target_ty, . })) . .to_predicate(self.tcx()), . )); . } . } . . debug!( . "coerce_from_inference_variable: two inference variables, target_ty={:?}, obligations={:?}", . target_ty, obligations . ); . let adjustments = make_adjustments(target_ty); 12 ( 0.00%) InferResult::Ok(InferOk { value: (adjustments, target_ty), obligations }) . } else { . // One unresolved type variable: just apply subtyping, we may be able . // 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. 7,690 ( 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. . 1,538 ( 0.00%) let (r_a, mt_a) = match *a.kind() { 2,307 ( 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), . }; . 1,538 ( 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; . 3,088 ( 0.00%) for (referent_ty, autoderefs) in autoderef.by_ref() { 3,088 ( 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. 1,550 ( 0.00%) let r = if !self.use_lub { . r_b // [2] above 6 ( 0.00%) } else if autoderefs == 1 { . r_a // [3] above . } else { 1 ( 0.00%) if r_borrow_var.is_none() { . // create var lazily, at most once . let coercion = Coercion(span); 5 ( 0.00%) let r = self.next_region_var(coercion); . r_borrow_var = Some(r); // [4] above . } . r_borrow_var.unwrap() . }; 775 ( 0.00%) let derefd_ty_a = self.tcx.mk_ref( . r, . TypeAndMut { . ty: referent_ty, . mutbl: mutbl_b, // [1] above . }, . ); 5,425 ( 0.00%) match self.unify(derefd_ty_a, b) { . Ok(ok) => { 3,076 ( 0.00%) found = Some(ok); . break; . } 18 ( 0.00%) Err(err) => { 6 ( 0.00%) if first_error.is_none() { 30 ( 0.00%) 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. 6,152 ( 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); . } . }; . 1,854 ( 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. 434 ( 0.00%) assert_eq!(mutbl_b, hir::Mutability::Not); // can only coerce &T -> &U 868 ( 0.00%) return success(vec![], ty, obligations); . } . 3,864 ( 0.00%) let InferOk { value: mut adjustments, obligations: o } = 552 ( 0.00%) self.adjust_steps_as_infer_ok(&autoderef); . obligations.extend(o); 10,488 ( 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. 1,104 ( 0.00%) let r_borrow = match ty.kind() { . ty::Ref(r_borrow, _, _) => r_borrow, . _ => span_bug!(span, "expected a ref type, got {:?}", ty), . }; 2,208 ( 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 { 552 ( 0.00%) kind: Adjust::Borrow(AutoBorrow::Ref(r_borrow, mutbl)), . target: ty, . }); . . debug!("coerce_borrowed_pointer: succeeded ty={:?} adjustments={:?}", ty, adjustments); . 4,416 ( 0.00%) success(adjustments, ty, obligations) 6,152 ( 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. 4,552 ( 0.00%) if source.is_ty_var() { . debug!("coerce_unsized: source is a TyVar, bailing out"); . return Err(TypeError::Mismatch); . } 5,678 ( 0.00%) if target.is_ty_var() { . debug!("coerce_unsized: target is a TyVar, bailing out"); . return Err(TypeError::Mismatch); . } . . let traits = 46,128 ( 0.00%) (self.tcx.lang_items().unsize_trait(), self.tcx.lang_items().coerce_unsized_trait()); 15,376 ( 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`. 11,984 ( 0.00%) let reborrow = match (source.kind(), target.kind()) { 4,206 ( 0.00%) (&ty::Ref(_, ty_a, mutbl_a), &ty::Ref(_, _, mutbl_b)) => { . coerce_mutbls(mutbl_a, mutbl_b)?; . 1,402 ( 0.00%) let coercion = Coercion(self.cause.span); 7,010 ( 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)), 1,402 ( 0.00%) target: self . .tcx . .mk_ref(r_borrow, ty::TypeAndMut { mutbl: mutbl_b, ty: ty_a }), . }, . )) . } 54 ( 0.00%) (&ty::Ref(_, ty_a, mt_a), &ty::RawPtr(ty::TypeAndMut { mutbl: mt_b, .. })) => { . coerce_mutbls(mt_a, mt_b)?; . . Some(( . Adjustment { kind: Adjust::Deref(None), target: ty_a }, . Adjustment { . kind: Adjust::Borrow(AutoBorrow::RawPtr(mt_b)), 18 ( 0.00%) target: self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mt_b, ty: ty_a }), . }, . )) . } . _ => None, . }; . 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, 3,844 ( 0.00%) span: self.cause.span, . }; 19,220 ( 0.00%) let coerce_target = self.next_ty_var(origin); 15,376 ( 0.00%) let mut coercion = self.unify_and(coerce_target, target, |target| { . let unsize = Adjustment { kind: Adjust::Pointer(PointerCast::Unsize), target }; 7,688 ( 0.00%) match reborrow { 12,120 ( 0.00%) None => vec![unsize], 19,880 ( 0.00%) Some((ref deref, ref autoref)) => vec![deref.clone(), autoref.clone(), unsize], . } . })?; . 3,844 ( 0.00%) let mut selcx = traits::SelectionContext::new(self); . . // Create an obligation for `Source: CoerceUnsized`. . let cause = ObligationCause::new( 7,688 ( 0.00%) self.cause.span, 7,688 ( 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. 53,816 ( 0.00%) let mut queue: SmallVec<[_; 4]> = smallvec![traits::predicate_for_trait_def( 7,688 ( 0.00%) self.tcx, 3,844 ( 0.00%) self.fcx.param_env, 19,220 ( 0.00%) cause, . coerce_unsized_did, . 0, . coerce_source, 19,220 ( 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]; 14,780 ( 0.00%) while !queue.is_empty() { . let obligation = queue.remove(0); . debug!("coerce_unsized resolve step: {:?}", obligation); 6,755 ( 0.00%) let bound_predicate = obligation.predicate.kind(); 33,775 ( 0.00%) let trait_pred = match bound_predicate.skip_binder() { 32,694 ( 0.00%) ty::PredicateKind::Trait(trait_pred) if traits.contains(&trait_pred.def_id()) => { 48,105 ( 0.00%) if unsize_did == trait_pred.def_id() { 9,006 ( 0.00%) let self_ty = trait_pred.self_ty(); 6,004 ( 0.00%) let unsize_ty = trait_pred.trait_ref.substs[1].expect_ty(); 7,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; . } . } 9,006 ( 0.00%) if let ty::Tuple(..) = unsize_ty.kind() { . debug!("coerce_unsized: found unsized tuple coercion"); . has_unsized_tuple_coercion = true; . } . } 10,690 ( 0.00%) bound_predicate.rebind(trait_pred) . } . _ => { 8,460 ( 0.00%) coercion.obligations.push(obligation); . continue; . } . }; 58,795 ( 0.00%) match selcx.select(&obligation.with(trait_pred)) { . // Uncertain or unimplemented. . Ok(None) => { 2,197 ( 0.00%) if trait_pred.def_id() == unsize_did { 1,014 ( 0.00%) let trait_pred = self.resolve_vars_if_possible(trait_pred); 338 ( 0.00%) let self_ty = trait_pred.skip_binder().self_ty(); 1,014 ( 0.00%) let unsize_ty = trait_pred.skip_binder().trait_ref.substs[1].expect_ty(); . debug!("coerce_unsized: ambiguous unsize case for {:?}", trait_pred); 338 ( 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"); 18,240 ( 0.00%) 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. . } . 40,584 ( 0.00%) Ok(Some(impl_source)) => queue.extend(impl_source.nested_obligations()), . } 6,418 ( 0.00%) } . 1,270 ( 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(); . } . 1,270 ( 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(); . } . 6,985 ( 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, . normal: G, . ) -> CoerceResult<'tcx> . where . F: FnOnce(Ty<'tcx>) -> Vec>, . G: FnOnce(Ty<'tcx>) -> Vec>, . { 94 ( 0.00%) if let ty::FnPtr(fn_ty_b) = b.kind() { 188 ( 0.00%) if let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) = 94 ( 0.00%) (fn_ty_a.unsafety(), fn_ty_b.unsafety()) . { . let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a); . return self.unify_and(unsafe_a, b, to_unsafe); . } . } . self.unify_and(a, b, normal) . } . -- line 747 ---------------------------------------- -- line 762 ---------------------------------------- . a, . fn_ty_a, . b, . simple(Adjust::Pointer(PointerCast::UnsafeFnPointer)), . identity, . ) . } . 480 ( 0.00%) fn coerce_from_fn_item(&self, a: Ty<'tcx>, b: Ty<'tcx>) -> CoerceResult<'tcx> { . //! Attempts to coerce from the type of a Rust function item . //! into a closure or a `proc`. . . let b = self.shallow_resolve(b); 240 ( 0.00%) let InferOk { value: b, mut obligations } = 48 ( 0.00%) self.normalize_associated_types_in_as_infer_ok(self.cause.span, b); . debug!("coerce_from_fn_item(a={:?}, b={:?})", a, b); . 96 ( 0.00%) match b.kind() { . ty::FnPtr(b_sig) => { 188 ( 0.00%) let a_sig = a.fn_sig(self.tcx); . // Intrinsics are not coercible to function pointers 94 ( 0.00%) if a_sig.abi() == Abi::RustIntrinsic || a_sig.abi() == Abi::PlatformIntrinsic { . return Err(TypeError::IntrinsicCast); . } . . // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396). 282 ( 0.00%) if let ty::FnDef(def_id, _) = *a.kind() { 188 ( 0.00%) if b_sig.unsafety() == hir::Unsafety::Normal 47 ( 0.00%) && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty() . { . return Err(TypeError::TargetFeatureCast(def_id)); . } . } . 329 ( 0.00%) let InferOk { value: a_sig, obligations: o1 } = 188 ( 0.00%) self.normalize_associated_types_in_as_infer_ok(self.cause.span, a_sig); . obligations.extend(o1); . 47 ( 0.00%) let a_fn_pointer = self.tcx.mk_fn_ptr(a_sig); 188 ( 0.00%) let InferOk { value, obligations: o2 } = self.coerce_from_safe_fn( . a_fn_pointer, 235 ( 0.00%) a_sig, . b, . |unsafe_ty| { . vec![ . Adjustment { . kind: Adjust::Pointer(PointerCast::ReifyFnPointer), . target: a_fn_pointer, . }, . Adjustment { -- line 811 ---------------------------------------- -- line 813 ---------------------------------------- . target: unsafe_ty, . }, . ] . }, . simple(Adjust::Pointer(PointerCast::ReifyFnPointer)), . )?; . . obligations.extend(o2); 705 ( 0.00%) Ok(InferOk { value, obligations }) . } . _ => self.unify_and(a, b, identity), . } 384 ( 0.00%) } . 266 ( 0.00%) fn coerce_closure_to_fn( . &self, . a: Ty<'tcx>, . closure_def_id_a: DefId, . substs_a: SubstsRef<'tcx>, . b: Ty<'tcx>, . ) -> CoerceResult<'tcx> { . //! Attempts to coerce from the type of a non-capturing closure . //! into a function pointer. . //! . . let b = self.shallow_resolve(b); . 38 ( 0.00%) match b.kind() { . // At this point we haven't done capture analysis, which means . // that the ClosureSubsts just contains an inference variable instead . // of tuple of captured types. . // . // All we care here is if any variable is being captured and not the exact paths, . // so we check `upvars_mentioned` for root variables being captured. . ty::FnPtr(fn_ty) . if self -- line 848 ---------------------------------------- -- line 864 ---------------------------------------- . self.unify_and( . pointer_ty, . b, . simple(Adjust::Pointer(PointerCast::ClosureFnPointer(unsafety))), . ) . } . _ => self.unify_and(a, b, identity), . } 152 ( 0.00%) } . 198 ( 0.00%) fn coerce_unsafe_ptr( . &self, . a: Ty<'tcx>, . b: Ty<'tcx>, . mutbl_b: hir::Mutability, . ) -> CoerceResult<'tcx> { . debug!("coerce_unsafe_ptr(a={:?}, b={:?})", a, b); . 90 ( 0.00%) let (is_ref, mt_a) = match *a.kind() { 54 ( 0.00%) ty::Ref(_, ty, mutbl) => (true, ty::TypeAndMut { ty, mutbl }), . ty::RawPtr(mt) => (false, mt), . _ => return self.unify_and(a, b, identity), . }; 18 ( 0.00%) coerce_mutbls(mt_a.mutbl, mutbl_b)?; . . // Check that the types which they point at are compatible. 18 ( 0.00%) let a_unsafe = self.tcx.mk_ptr(ty::TypeAndMut { mutbl: mutbl_b, ty: mt_a.ty }); . // Although references and unsafe ptrs have the same . // representation, we still register an Adjust::DerefRef so that . // regionck knows that the region for `a` must be valid here. 36 ( 0.00%) if is_ref { . self.unify_and(a_unsafe, b, |target| { 144 ( 0.00%) vec![ . Adjustment { kind: Adjust::Deref(None), target: mt_a.ty }, . Adjustment { kind: Adjust::Borrow(AutoBorrow::RawPtr(mutbl_b)), target }, . ] . }) . } else if mt_a.mutbl != mutbl_b { . self.unify_and(a_unsafe, b, simple(Adjust::Pointer(PointerCast::MutToConstPointer))) . } else { . self.unify_and(a_unsafe, b, identity) . } 144 ( 0.00%) } . } . . 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. 62,174 ( 0.00%) 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>> { 13,323 ( 0.00%) let source = self.resolve_vars_with_obligations(expr_ty); . debug!("coercion::try({:?}: {:?} -> {:?})", expr, source, target); . . let cause = 4,441 ( 0.00%) cause.unwrap_or_else(|| self.cause(expr.span, ObligationCauseCode::ExprAssignable)); . let coerce = Coerce::new(self, cause, allow_two_phase); 53,272 ( 0.00%) let ok = self.commit_if_ok(|_| coerce.coerce(source, target))?; . 17,748 ( 0.00%) let (adjustments, _) = self.register_infer_ok_obligations(ok); 44,370 ( 0.00%) self.apply_adjustments(expr, adjustments); 13,311 ( 0.00%) Ok(if expr_ty.references_error() { self.tcx.ty_error() } else { target }) 39,969 ( 0.00%) } . . /// 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. 1,792,375 ( 0.04%) 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, . { 827,250 ( 0.02%) let prev_ty = self.resolve_vars_with_obligations(prev_ty); 413,625 ( 0.01%) 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. 137,875 ( 0.00%) if prev_ty == new_ty { 137,731 ( 0.00%) return Ok(prev_ty); . } . . // Special-case that coercion alone cannot handle: . // Function items or non-capturing closures of differing IDs or InternalSubsts. 672 ( 0.00%) let (a_sig, b_sig) = { 672 ( 0.00%) let is_capturing_closure = |ty| { 336 ( 0.00%) if let &ty::Closure(closure_def_id, _substs) = ty { . self.tcx.upvars_mentioned(closure_def_id.expect_local()).is_some() . } else { . false . } 672 ( 0.00%) }; 944 ( 0.00%) if is_capturing_closure(prev_ty.kind()) || is_capturing_closure(new_ty.kind()) { . (None, None) . } else { 504 ( 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), . } . } . }; 336 ( 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); 84 ( 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; 672 ( 0.00%) if !self.typeck_results.borrow().adjustments().contains_key(new.hir_id) { 5,197 ( 0.00%) let result = self.commit_if_ok(|_| coerce.coerce(new_ty, prev_ty)); 168 ( 0.00%) match result { . Ok(ok) => { 672 ( 0.00%) let (adjustments, target) = self.register_infer_ok_obligations(ok); 672 ( 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, . ); 168 ( 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) . } . } 1,240,875 ( 0.03%) } . } . . /// 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 { 4,346 ( 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. 1,658,220 ( 0.03%) pub fn coerce<'a>( . &mut self, . fcx: &FnCtxt<'a, 'tcx>, . cause: &ObligationCause<'tcx>, . expression: &'tcx hir::Expr<'tcx>, . expression_ty: Ty<'tcx>, . ) { 7,628 ( 0.00%) self.coerce_inner(fcx, cause, Some(expression), expression_ty, None, false) 1,105,480 ( 0.02%) } . . /// 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, . ) { 970 ( 0.00%) self.coerce_inner( . fcx, . cause, . None, 108 ( 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`. 28,014 ( 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. 139,587 ( 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. 558,076 ( 0.01%) 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. 4,002 ( 0.00%) let result = if let Some(expression) = expression { 418,233 ( 0.01%) 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 13,824 ( 0.00%) fcx.try_coerce( . expression, . expression_ty, . self.expected_ty, . AllowTwoPhase::No, 6,144 ( 0.00%) Some(cause.clone()), . ) . } else { 275,750 ( 0.01%) match self.expressions { 168 ( 0.00%) Expressions::Dynamic(ref exprs) => fcx.try_find_coercion_lub( . cause, . exprs, . self.merged_ty(), . expression, . expression_ty, . ), 826,838 ( 0.02%) Expressions::UpFront(ref coercion_sites) => fcx.try_find_coercion_lub( . cause, 413,373 ( 0.01%) &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. 108 ( 0.00%) assert!(expression_ty.is_unit(), "if let hack without unit type"); 216 ( 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 . }) . }; . 279,106 ( 0.01%) match result { 139,627 ( 0.00%) Ok(v) => { 139,411 ( 0.00%) self.final_ty = Some(v); . if let Some(e) = expression { 278,822 ( 0.01%) match self.expressions { . Expressions::Dynamic(ref mut buffer) => buffer.push(e), 277,834 ( 0.01%) 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 554,936 ( 0.01%) assert_eq!( 416,751 ( 0.01%) coercion_sites[self.pushed].as_coercion_site().hir_id, . e.hir_id . ); . } . } 558,138 ( 0.01%) 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 . } . 2,816 ( 0.00%) pub fn complete<'a>(self, fcx: &FnCtxt<'a, 'tcx>) -> Ty<'tcx> { 4,908 ( 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 `!`. 66 ( 0.00%) assert_eq!(self.pushed, 0); 33 ( 0.00%) fcx.tcx.types.never . } 3,520 ( 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<'_> { 525 ( 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<'_> { 414 ( 0.00%) &self.body . } . } 713,176 ( 0.01%) -------------------------------------------------------------------------------- -- 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)] 1,878,840 ( 0.04%) fn intern_ty(&self, kind: TyKind<'tcx>) -> Ty<'tcx> { . self.type_ 1,174,275 ( 0.02%) .intern(kind, |kind| { 52,870 ( 0.00%) let flags = super::flags::FlagComputation::for_kind(&kind); . . let ty_struct = TyS { 105,740 ( 0.00%) kind, . flags: flags.flags, . outer_exclusive_binder: flags.outer_exclusive_binder, . }; . . Interned(self.arena.alloc(ty_struct)) . }) . .0 2,113,695 ( 0.04%) } . . #[inline(never)] 516,280 ( 0.01%) fn intern_predicate( . &self, . kind: Binder<'tcx, PredicateKind<'tcx>>, . ) -> &'tcx PredicateInner<'tcx> { . self.predicate 451,745 ( 0.01%) .intern(kind, |kind| { 92,382 ( 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 580,815 ( 0.01%) } . } . . 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) { 2,261,898 ( 0.05%) 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) . } . 1,520,891 ( 0.03%) pub fn get(&self, id: hir::HirId) -> Option<&V> { 304,295 ( 0.01%) validate_hir_id_for_typeck_results(self.hir_owner, id); 304,295 ( 0.01%) self.data.get(&id.local_id) 1,216,904 ( 0.02%) } . . 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; . 1,848 ( 0.00%) fn index(&self, key: hir::HirId) -> &V { . self.get(key).expect("LocalTableInContext: key not found") 1,232 ( 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> { 7,824 ( 0.00%) pub fn new(hir_owner: LocalDefId) -> TypeckResults<'tcx> { 92,584 ( 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(), . } 7,824 ( 0.00%) } . . /// Returns the final resolution of a `QPath` in an `Expr` or `Pat` node. 27,531 ( 0.00%) pub fn qpath_res(&self, qpath: &hir::QPath<'_>, id: hir::HirId) -> Res { 18,354 ( 0.00%) match *qpath { 49,026 ( 0.00%) hir::QPath::Resolved(_, ref path) => path.res, . hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self . .type_dependent_def(id) 6,036 ( 0.00%) .map_or(Res::Err, |(kind, def_id)| Res::Def(kind, def_id)), . } 45,885 ( 0.00%) } . 195 ( 0.00%) pub fn type_dependent_defs( . &self, . ) -> LocalTableInContext<'_, Result<(DefKind, DefId), ErrorReported>> { 1,696 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.type_dependent_defs } 195 ( 0.00%) } . 2,190 ( 0.00%) pub fn type_dependent_def(&self, id: HirId) -> Option<(DefKind, DefId)> { 4,576 ( 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()) 4,380 ( 0.00%) } . 5,520 ( 0.00%) pub fn type_dependent_def_id(&self, id: HirId) -> Option { . self.type_dependent_def(id).map(|(_, def_id)| def_id) 5,520 ( 0.00%) } . 149,998 ( 0.00%) pub fn type_dependent_defs_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Result<(DefKind, DefId), ErrorReported>> { 149,998 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.type_dependent_defs } 149,998 ( 0.00%) } . . pub fn field_indices(&self) -> LocalTableInContext<'_, usize> { 4,465 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.field_indices } 595 ( 0.00%) } . . pub fn field_indices_mut(&mut self) -> LocalTableInContextMut<'_, usize> { 9,126 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.field_indices } 4,563 ( 0.00%) } . . pub fn user_provided_types(&self) -> LocalTableInContext<'_, CanonicalUserType<'tcx>> { 4,854 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.user_provided_types } 2,427 ( 0.00%) } . . pub fn user_provided_types_mut( . &mut self, . ) -> LocalTableInContextMut<'_, CanonicalUserType<'tcx>> { 1,224 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.user_provided_types } 612 ( 0.00%) } . . pub fn node_types(&self) -> LocalTableInContext<'_, Ty<'tcx>> { 303,136 ( 0.01%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.node_types } 151,568 ( 0.00%) } . . pub fn node_types_mut(&mut self) -> LocalTableInContextMut<'_, Ty<'tcx>> { 597,366 ( 0.01%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_types } 298,683 ( 0.01%) } . 3,505,944 ( 0.07%) pub fn node_type(&self, id: hir::HirId) -> Ty<'tcx> { 584,324 ( 0.01%) self.node_type_opt(id).unwrap_or_else(|| { . bug!("node_type: no type for node `{}`", tls::with(|tcx| tcx.hir().node_to_string(id))) . }) 2,921,620 ( 0.06%) } . 733,020 ( 0.02%) pub fn node_type_opt(&self, id: hir::HirId) -> Option> { 733,020 ( 0.02%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_types.get(&id.local_id).cloned() 1,466,040 ( 0.03%) } . . pub fn node_substs_mut(&mut self) -> LocalTableInContextMut<'_, SubstsRef<'tcx>> { 4,476 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_substs } 2,238 ( 0.00%) } . 152,420 ( 0.00%) pub fn node_substs(&self, id: hir::HirId) -> SubstsRef<'tcx> { 152,420 ( 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()) 304,840 ( 0.01%) } . 148,084 ( 0.00%) pub fn node_substs_opt(&self, id: hir::HirId) -> Option> { 148,084 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, id); . self.node_substs.get(&id.local_id).cloned() 296,168 ( 0.01%) } . . // 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> { 3,316 ( 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> { 590,189 ( 0.01%) self.node_type(expr.hir_id) . } . . pub fn expr_ty_opt(&self, expr: &hir::Expr<'_>) -> Option> { 592,358 ( 0.01%) self.node_type_opt(expr.hir_id) . } . . pub fn adjustments(&self) -> LocalTableInContext<'_, Vec>> { 294,734 ( 0.01%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.adjustments } 147,367 ( 0.00%) } . . pub fn adjustments_mut( . &mut self, . ) -> LocalTableInContextMut<'_, Vec>> { 307,094 ( 0.01%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.adjustments } 153,547 ( 0.00%) } . 294,135 ( 0.01%) pub fn expr_adjustments(&self, expr: &hir::Expr<'_>) -> &[ty::adjustment::Adjustment<'tcx>] { 588,270 ( 0.01%) validate_hir_id_for_typeck_results(self.hir_owner, expr.hir_id); . self.adjustments.get(&expr.hir_id.local_id).map_or(&[], |a| &a[..]) 588,270 ( 0.01%) } . . /// Returns the type of `expr`, considering any `Adjustment` . /// entry recorded for that expression. 2,555 ( 0.00%) pub fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> Ty<'tcx> { 511 ( 0.00%) self.expr_adjustments(expr).last().map_or_else(|| self.expr_ty(expr), |adj| adj.target) 1,232 ( 0.00%) } . 535 ( 0.00%) pub fn expr_ty_adjusted_opt(&self, expr: &hir::Expr<'_>) -> Option> { 107 ( 0.00%) self.expr_adjustments(expr).last().map(|adj| adj.target).or_else(|| self.expr_ty_opt(expr)) 324 ( 0.00%) } . 1,501 ( 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. 3,002 ( 0.00%) if let hir::ExprKind::Path(_) = expr.kind { . return false; . } . 3,602 ( 0.00%) matches!(self.type_dependent_defs().get(expr.hir_id), Some(Ok((DefKind::AssocFn, _)))) 3,002 ( 0.00%) } . 7,902 ( 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 . }) 10,536 ( 0.00%) } . . pub fn pat_binding_modes(&self) -> LocalTableInContext<'_, BindingMode> { 6,696 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_binding_modes } 2,031 ( 0.00%) } . . pub fn pat_binding_modes_mut(&mut self) -> LocalTableInContextMut<'_, BindingMode> { 3,496 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_binding_modes } 1,748 ( 0.00%) } . . pub fn pat_adjustments(&self) -> LocalTableInContext<'_, Vec>> { 8,826 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.pat_adjustments } 4,413 ( 0.00%) } . . pub fn pat_adjustments_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { 2,694 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.pat_adjustments } 1,347 ( 0.00%) } . . /// For a given closure, returns the iterator of `ty::CapturedPlace`s that are captured . /// by the closure. 1,940 ( 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() 2,425 ( 0.00%) } . . pub fn closure_kind_origins(&self) -> LocalTableInContext<'_, (Span, HirPlace<'tcx>)> { 768 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.closure_kind_origins } 384 ( 0.00%) } . . pub fn closure_kind_origins_mut( . &mut self, . ) -> LocalTableInContextMut<'_, (Span, HirPlace<'tcx>)> { 4 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.closure_kind_origins } 2 ( 0.00%) } . . pub fn liberated_fn_sigs(&self) -> LocalTableInContext<'_, ty::FnSig<'tcx>> { 2,000 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.liberated_fn_sigs } 1,000 ( 0.00%) } . . pub fn liberated_fn_sigs_mut(&mut self) -> LocalTableInContextMut<'_, ty::FnSig<'tcx>> { 1,232 ( 0.00%) LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.liberated_fn_sigs } 616 ( 0.00%) } . . pub fn fru_field_types(&self) -> LocalTableInContext<'_, Vec>> { 768 ( 0.00%) LocalTableInContext { hir_owner: self.hir_owner, data: &self.fru_field_types } 384 ( 0.00%) } . . pub fn fru_field_types_mut(&mut self) -> LocalTableInContextMut<'_, Vec>> { . LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.fru_field_types } . } . 30 ( 0.00%) pub fn is_coercion_cast(&self, hir_id: hir::HirId) -> bool { 10 ( 0.00%) validate_hir_id_for_typeck_results(self.hir_owner, hir_id); . self.coercion_casts.contains(&hir_id.local_id) 20 ( 0.00%) } . . pub fn set_coercion_cast(&mut self, id: ItemLocalId) { . self.coercion_casts.insert(id); . } . . pub fn coercion_casts(&self) -> &ItemLocalSet { 384 ( 0.00%) &self.coercion_casts 384 ( 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>; . 264 ( 0.00%) #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable, TypeFoldable, Lift)] . pub struct CanonicalUserTypeAnnotation<'tcx> { . pub user_ty: CanonicalUserType<'tcx>, . pub span: Span, 324 ( 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. 793 ( 0.00%) pub fn is_identity(&self) -> bool { 1,586 ( 0.00%) match self.value { . UserType::Ty(_) => false, . UserType::TypeOf(_, user_substs) => { 793 ( 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() { 1,336 ( 0.00%) GenericArgKind::Type(ty) => match ty.kind() { . ty::Bound(debruijn, b) => { . // We only allow a `ty::INNERMOST` index in substitutions. 655 ( 0.00%) assert_eq!(*debruijn, ty::INNERMOST); . cvar == b.var . } . _ => false, . }, . 282 ( 0.00%) GenericArgKind::Lifetime(r) => match r { . ty::ReLateBound(debruijn, br) => { . // We only allow a `ty::INNERMOST` index in substitutions. . assert_eq!(*debruijn, ty::INNERMOST); . cvar == br.var . } . _ => false, . }, . -- line 867 ---------------------------------------- -- line 872 ---------------------------------------- . cvar == b . } . _ => false, . }, . } . }) . } . } 1,586 ( 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. 1,944 ( 0.00%) #[derive(Copy, Clone, Debug, PartialEq, TyEncodable, TyDecodable)] 9,115 ( 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> { 19,760 ( 0.00%) pub fn typeck_opt_const_arg( . self, . def: ty::WithOptConstParam, . ) -> &'tcx TypeckResults<'tcx> { 7,904 ( 0.00%) if let Some(param_did) = def.const_param_did { . self.typeck_const_arg((def.did, param_did)) . } else { . self.typeck(def.did) . } 15,808 ( 0.00%) } . 1,203 ( 0.00%) pub fn alloc_steal_thir(self, thir: Thir<'tcx>) -> &'tcx Steal> { 401 ( 0.00%) self.arena.alloc(Steal::new(thir)) 1,604 ( 0.00%) } . 6,480 ( 0.00%) pub fn alloc_steal_mir(self, mir: Body<'tcx>) -> &'tcx Steal> { 1,296 ( 0.00%) self.arena.alloc(Steal::new(mir)) 9,072 ( 0.00%) } . 1,604 ( 0.00%) pub fn alloc_steal_promoted( . self, . promoted: IndexVec>, . ) -> &'tcx Steal>> { 401 ( 0.00%) self.arena.alloc(Steal::new(promoted)) 2,005 ( 0.00%) } . 630 ( 0.00%) pub fn alloc_adt_def( . self, . did: DefId, . kind: AdtKind, . variants: IndexVec, . repr: ReprOptions, . ) -> &'tcx ty::AdtDef { 1,120 ( 0.00%) self.intern_adt_def(ty::AdtDef::new(self, did, kind, variants, repr)) 280 ( 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? 6,456 ( 0.00%) pub fn layout_scalar_valid_range(self, def_id: DefId) -> (Bound, Bound) { 3,228 ( 0.00%) let attrs = self.get_attrs(def_id); 13,719 ( 0.00%) let get = |name| { 3,228 ( 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); 16 ( 0.00%) if let Some( . &[ . ast::NestedMetaItem::Literal(ast::Lit { 8 ( 0.00%) kind: ast::LitKind::Int(a, _), .. . }), . ], 4 ( 0.00%) ) = 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 . } 16,140 ( 0.00%) }; 4,842 ( 0.00%) ( 4,842 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_start), 2,421 ( 0.00%) get(sym::rustc_layout_scalar_valid_range_end), . ) 6,456 ( 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 }) . } . 154 ( 0.00%) pub fn consider_optimizing String>(self, msg: T) -> bool { 22 ( 0.00%) let cname = self.crate_name(LOCAL_CRATE); 176 ( 0.00%) self.sess.consider_optimizing(cname.as_str(), msg) 176 ( 0.00%) } . . /// Obtain all lang items of this crate and all dependencies (recursively) 497,945 ( 0.01%) pub fn lang_items(self) -> &'tcx rustc_hir::lang_items::LanguageItems { . self.get_lang_items(()) 640,215 ( 0.01%) } . . /// 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. 133 ( 0.00%) pub fn get_diagnostic_item(self, name: Symbol) -> Option { . self.all_diagnostic_items(()).name_to_id.get(&name).copied() 152 ( 0.00%) } . . /// Obtain the diagnostic item's name 10,206 ( 0.00%) pub fn get_diagnostic_name(self, id: DefId) -> Option { . self.diagnostic_items(id.krate).id_to_name.get(&id).copied() 11,664 ( 0.00%) } . . /// Check whether the diagnostic item with the given `name` has the given `DefId`. 20,622 ( 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) 23,568 ( 0.00%) } . 5,446 ( 0.00%) pub fn stability(self) -> &'tcx stability::Index<'tcx> { . self.stability_index(()) 7,002 ( 0.00%) } . 234,024 ( 0.00%) pub fn features(self) -> &'tcx rustc_feature::Features { . self.features_query(()) 267,456 ( 0.01%) } . 18 ( 0.00%) pub fn def_key(self, id: DefId) -> rustc_hir::definitions::DefKey { . // Accessing the DefKey is ok, since it is part of DefPathHash. 8,828 ( 0.00%) if let Some(id) = id.as_local() { . self.untracked_resolutions.definitions.def_key(id) . } else { 4,343 ( 0.00%) self.untracked_resolutions.cstore.def_key(id) . } 36 ( 0.00%) } . . /// 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`. . pub fn def_path(self, id: DefId) -> rustc_hir::definitions::DefPath { . // Accessing the DefPath is ok, since it is part of DefPathHash. -- line 1274 ---------------------------------------- -- 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. 2,966 ( 0.00%) if let Some(def_id) = def_id.as_local() { . self.untracked_resolutions.definitions.def_path_hash(def_id) . } else { 200 ( 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 { 44,018 ( 0.00%) &*self.untracked_resolutions.cstore 22,009 ( 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> { 94 ( 0.00%) let resolutions = &self.gcx.untracked_resolutions; 469 ( 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.) 768 ( 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=...` . 1,152 ( 0.00%) if self.features().nll { . return BorrowckMode::Mir; . } . 384 ( 0.00%) self.sess.opts.borrowck_mode 1,536 ( 0.00%) } . . /// If `true`, we should use lazy normalization for constants, otherwise . /// we still evaluate them eagerly. . #[inline] . pub fn lazy_normalization(self) -> bool { 4 ( 0.00%) let features = self.features(); . // Note: We only use lazy normalization for generic const expressions. . features.generic_const_exprs . } . . #[inline] . pub fn local_crate_exports_generics(self) -> bool { . debug_assert!(self.sess.opts.share_generics()); . -- line 1440 ---------------------------------------- -- 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")`). 3,795 ( 0.00%) pub fn article_and_description(self, def_id: DefId) -> (&'static str, &'static str) { 2,760 ( 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"), . }, 6,210 ( 0.00%) def_kind => (def_kind.article(), def_kind.descr(def_id)), . } 3,105 ( 0.00%) } . . pub fn type_length_limit(self) -> Limit { . self.limits(()).type_length_limit . } . 179,872 ( 0.00%) pub fn recursion_limit(self) -> Limit { . self.limits(()).recursion_limit 205,568 ( 0.00%) } . . pub fn move_size_limit(self) -> Limit { . self.limits(()).move_size_limit . } . 2,604 ( 0.00%) pub fn const_eval_limit(self) -> Limit { . self.limits(()).const_eval_limit 2,976 ( 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(); 59,103 ( 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(); 244,217 ( 0.01%) 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 { 120,786 ( 0.00%) assert!(ptr_eq(context.tcx.gcx, tcx.gcx)); . let context: &ImplicitCtxt<'_, '_> = mem::transmute(context); 120,556 ( 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> { 213,319 ( 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)`. 86,004 ( 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>> { 51,380 ( 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)`. 28,668 ( 0.00%) self.0.kind.hash(s) . } . } . . impl<'tcx, T> Borrow<[T]> for Interned<'tcx, List> { . fn borrow<'a>(&'a self) -> &'a [T] { 200,993 ( 0.00%) &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)`. 36,568 ( 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 { 88,808 ( 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)`. 35,475 ( 0.00%) self.0.hash(s) . } . } . . impl<'tcx> TyCtxt<'tcx> { 769,113 ( 0.02%) pub fn $method(self, v: $ty) -> &'tcx $ty { 409,128 ( 0.01%) self.interners.$name.intern(v, |v| { 8,054 ( 0.00%) Interned(self.interners.arena.alloc(v)) . }).0 864,288 ( 0.02%) } . })+ . } . } . . 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> { 2,241,115 ( 0.05%) $(pub fn $method(self, v: &[$ty]) -> &'tcx List<$ty> { . self.interners.$field.intern_ref(v, || { . Interned(List::from_arena(&*self.arena, v)) . }).0 2,004,012 ( 0.04%) })+ . } . ); . } . . 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> { 86,528 ( 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> { 1,668,256 ( 0.03%) self.interners.intern_ty(st) . } . . #[inline] . pub fn mk_predicate(self, binder: Binder<'tcx, PredicateKind<'tcx>>) -> Predicate<'tcx> { 710,785 ( 0.01%) let inner = self.interners.intern_predicate(binder); . Predicate { inner } . } . . #[inline] 1,357,904 ( 0.03%) pub fn reuse_or_mk_predicate( . self, . pred: Predicate<'tcx>, . binder: Binder<'tcx, PredicateKind<'tcx>>, . ) -> Predicate<'tcx> { 133,937 ( 0.00%) if pred.kind() != binder { self.mk_predicate(binder) } else { pred } 1,357,904 ( 0.03%) } . . pub fn mk_mach_int(self, tm: IntTy) -> Ty<'tcx> { 104 ( 0.00%) 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, . IntTy::I128 => self.types.i128, . } 104 ( 0.00%) } . . pub fn mk_mach_uint(self, tm: UintTy) -> Ty<'tcx> { 417 ( 0.00%) match tm { . UintTy::Usize => self.types.usize, . UintTy::U8 => self.types.u8, . UintTy::U16 => self.types.u16, . UintTy::U32 => self.types.u32, . UintTy::U64 => self.types.u64, . UintTy::U128 => self.types.u128, . } 417 ( 0.00%) } . . pub fn mk_mach_float(self, tm: FloatTy) -> Ty<'tcx> { . match tm { . FloatTy::F32 => self.types.f32, . FloatTy::F64 => self.types.f64, . } . } . . #[inline] . pub fn mk_static_str(self) -> Ty<'tcx> { 516 ( 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] 13,455 ( 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))) 14,040 ( 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> { 352 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 641 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) . } . . pub fn mk_tup], Ty<'tcx>>>(self, iter: I) -> I::Output { 9,074 ( 0.00%) iter.intern_with(|ts| { 4,963 ( 0.00%) let kinds: Vec<_> = ts.iter().map(|&t| GenericArg::from(t)).collect(); 11,735 ( 0.00%) self.mk_ty(Tuple(self.intern_substs(&kinds))) 8,064 ( 0.00%) }) . } . . #[inline] . pub fn mk_unit(self) -> Ty<'tcx> { 241 ( 0.00%) self.types.unit . } . . #[inline] . pub fn mk_diverging_default(self) -> Ty<'tcx> { 16 ( 0.00%) 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> { 1,188 ( 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 2412 ---------------------------------------- . . #[inline] . pub fn mk_ty_var(self, v: TyVid) -> Ty<'tcx> { . self.mk_ty_infer(TyVar(v)) . } . . #[inline] . pub fn mk_const_var(self, v: ConstVid<'tcx>, ty: Ty<'tcx>) -> &'tcx Const<'tcx> { 222 ( 0.00%) self.mk_const(ty::Const { val: ty::ConstKind::Infer(InferConst::Var(v)), ty }) . } . . #[inline] . pub fn mk_int_var(self, v: IntVid) -> Ty<'tcx> { . self.mk_ty_infer(IntVar(v)) . } . . #[inline] -- line 2428 ---------------------------------------- -- 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 }) . } . 9,450 ( 0.00%) pub fn mk_param_from_def(self, param: &ty::GenericParamDef) -> GenericArg<'tcx> { 5,746 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => { 3,012 ( 0.00%) self.mk_region(ty::ReEarlyBound(param.to_early_bound_region_data())).into() . } 1,696 ( 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() . } . } 9,450 ( 0.00%) } . . #[inline] . pub fn mk_opaque(self, def_id: DefId, substs: SubstsRef<'tcx>) -> Ty<'tcx> { . self.mk_ty(Opaque(def_id, substs)) . } . 823 ( 0.00%) pub fn mk_place_field(self, place: Place<'tcx>, f: Field, ty: Ty<'tcx>) -> Place<'tcx> { 823 ( 0.00%) self.mk_place_elem(place, PlaceElem::Field(f, ty)) 1,646 ( 0.00%) } . . pub fn mk_place_deref(self, place: Place<'tcx>) -> Place<'tcx> { . self.mk_place_elem(place, PlaceElem::Deref) . } . 6 ( 0.00%) pub fn mk_place_downcast( . self, . place: Place<'tcx>, . adt_def: &'tcx AdtDef, . variant_index: VariantIdx, . ) -> Place<'tcx> { 6 ( 0.00%) self.mk_place_elem( . place, 12 ( 0.00%) PlaceElem::Downcast(Some(adt_def.variants[variant_index].name), variant_index), . ) 12 ( 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. 7,461 ( 0.00%) 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) } 8,290 ( 0.00%) } . 2,597 ( 0.00%) pub fn intern_poly_existential_predicates( . self, . eps: &[ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . ) -> &'tcx List>> { 371 ( 0.00%) assert!(!eps.is_empty()); . assert!( . eps.array_windows() 310 ( 0.00%) .all(|[a, b]| a.skip_binder().stable_cmp(self, &b.skip_binder()) . != Ordering::Greater) . ); 1,484 ( 0.00%) self._intern_poly_existential_predicates(eps) 2,968 ( 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. 5,575 ( 0.00%) if preds.is_empty() { . // The macro-generated method below asserts we don't intern an empty slice. . List::empty() . } else { 3,148 ( 0.00%) self._intern_predicates(preds) . } 4,920 ( 0.00%) } . . pub fn intern_type_list(self, ts: &[Ty<'tcx>]) -> &'tcx List> { 22,122 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_type_list(ts) } 144 ( 0.00%) } . . pub fn intern_substs(self, ts: &[GenericArg<'tcx>]) -> &'tcx List> { 372,378 ( 0.01%) if ts.is_empty() { List::empty() } else { self._intern_substs(ts) } 14,094 ( 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> { 9,567 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_place_elems(ts) } 3,414 ( 0.00%) } . . pub fn intern_canonical_var_infos( . self, . ts: &[CanonicalVarInfo<'tcx>], . ) -> CanonicalVarInfos<'tcx> { 20,623 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) } 710 ( 0.00%) } . . pub fn intern_bound_variable_kinds( . self, . ts: &[ty::BoundVariableKind], . ) -> &'tcx List { 7,128 ( 0.00%) if ts.is_empty() { List::empty() } else { self._intern_bound_variable_kinds(ts) } 11,654 ( 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 { 2,413 ( 0.00%) inputs_and_output: self.intern_type_list(xs), 441 ( 0.00%) c_variadic, 644 ( 0.00%) unsafety, 476 ( 0.00%) abi, 160 ( 0.00%) }) . } . . pub fn mk_poly_existential_predicates< . I: InternAs< . [ty::Binder<'tcx, ExistentialPredicate<'tcx>>], . &'tcx List>>, . >, . >( . self, . iter: I, . ) -> I::Output { 1,530 ( 0.00%) iter.intern_with(|xs| self.intern_poly_existential_predicates(xs)) . } . . pub fn mk_predicates], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 2 ( 0.00%) iter.intern_with(|xs| self.intern_predicates(xs)) . } . . pub fn mk_type_list], &'tcx List>>>(self, iter: I) -> I::Output { 2,722 ( 0.00%) iter.intern_with(|xs| self.intern_type_list(xs)) . } . . pub fn mk_substs], &'tcx List>>>( . self, . iter: I, . ) -> I::Output { 234,294 ( 0.00%) 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)) . } . 16,444 ( 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())) 32,888 ( 0.00%) } . . pub fn mk_bound_variable_kinds< . I: InternAs<[ty::BoundVariableKind], &'tcx List>, . >( . self, . iter: I, . ) -> I::Output { 38,235 ( 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. 2,049,026 ( 0.04%) pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId { 2,049,026 ( 0.04%) let hir = self.hir(); . loop { 3,134,322 ( 0.06%) if id == bound { . return bound; . } . 3,760,536 ( 0.08%) 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); 2,256,168 ( 0.05%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 2,927,180 ( 0.06%) } . 9,816 ( 0.00%) pub fn lint_level_at_node( . self, . lint: &'static Lint, . mut id: hir::HirId, . ) -> (Level, LintLevelSource) { . let sets = self.lint_levels(()); . loop { 64,257 ( 0.00%) if let Some(pair) = sets.level_and_source(lint, id, self.sess) { . return pair; . } 5,231 ( 0.00%) let next = self.hir().get_parent_node(id); 15,693 ( 0.00%) if next == id { . bug!("lint traversal reached the root of the crate"); . } . id = next; . } 9,816 ( 0.00%) } . 518 ( 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>), . ) { 4,983 ( 0.00%) let (level, src) = self.lint_level_at_node(lint, hir_id); 1,391 ( 0.00%) struct_lint_level(self.sess, lint, level, src, Some(span.into()), decorate); 296 ( 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); . } . 4,459 ( 0.00%) pub fn in_scope_traits(self, id: HirId) -> Option<&'tcx [TraitCandidate]> { 1,274 ( 0.00%) let map = self.in_scope_traits_map(id.owner)?; . let candidates = map.get(&id.local_id)?; 1,274 ( 0.00%) Some(&*candidates) 5,096 ( 0.00%) } . 10,451 ( 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()) 13,437 ( 0.00%) } . 1,179 ( 0.00%) pub fn is_late_bound(self, id: HirId) -> bool { . self.is_late_bound_map(id.owner) 64 ( 0.00%) .map_or(false, |(owner, set)| owner == id.owner && set.contains(&id.local_id)) 1,048 ( 0.00%) } . 8,288 ( 0.00%) pub fn object_lifetime_defaults(self, id: HirId) -> Option> { . self.object_lifetime_defaults_map(id.owner) 10,656 ( 0.00%) } . 5,985 ( 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(), . ) 5,985 ( 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 380 ( 0.00%) pub fn is_const_fn(self, def_id: DefId) -> bool { 38 ( 0.00%) if self.is_const_fn_raw(def_id) { 10 ( 0.00%) match self.lookup_const_stability(def_id) { 20 ( 0.00%) Some(stability) if stability.level.is_unstable() => { . // has a `rustc_const_unstable` attribute, check whether the user enabled the . // corresponding feature gate. 8 ( 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 . } 342 ( 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; 82,848 ( 0.00%) fn intern_with(self, f: F) -> Self::Output . where . F: FnOnce(&[T]) -> R, . { 797,009 ( 0.02%) E::intern_with(self, f) 85,779 ( 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; 127,006 ( 0.00%) 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`. 160,043 ( 0.00%) match iter.size_hint() { . (0, Some(0)) => { 3 ( 0.00%) assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { . let t0 = iter.next().unwrap(); 1 ( 0.00%) assert!(iter.next().is_none()); 20,095 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { . let t0 = iter.next().unwrap(); . let t1 = iter.next().unwrap(); 224 ( 0.00%) assert!(iter.next().is_none()); 18,924 ( 0.00%) f(&[t0, t1]) . } 888 ( 0.00%) _ => f(&iter.collect::>()), . } 113,050 ( 0.00%) } . } . . impl<'a, T, R> InternIteratorElement for &'a T . where . T: Clone + 'a, . { . type Output = R; 3,695 ( 0.00%) fn intern_with, F: FnOnce(&[T]) -> R>(iter: I, f: F) -> Self::Output { . // This code isn't hot. 64 ( 0.00%) f(&iter.cloned().collect::>()) 3,014 ( 0.00%) } . } . . impl InternIteratorElement for Result { . type Output = Result; 252,149 ( 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. 204,806 ( 0.00%) Ok(match iter.size_hint() { . (0, Some(0)) => { . assert!(iter.next().is_none()); . f(&[]) . } . (1, Some(1)) => { 912 ( 0.00%) let t0 = iter.next().unwrap()?; . assert!(iter.next().is_none()); 16,363 ( 0.00%) f(&[t0]) . } . (2, Some(2)) => { 456 ( 0.00%) let t0 = iter.next().unwrap()?; 456 ( 0.00%) let t1 = iter.next().unwrap()?; 459 ( 0.00%) assert!(iter.next().is_none()); 24,066 ( 0.00%) f(&[t0, t1]) . } 2,466 ( 0.00%) _ => f(&iter.collect::, _>>()?), . }) 283,986 ( 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 { 120,786 ( 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 = 6,208 ( 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()) . }; . } 3,053,440 ( 0.06%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/hygiene.rs -------------------------------------------------------------------------------- Ir -- line 40 ---------------------------------------- . use rustc_macros::HashStable_Generic; . use rustc_serialize::{Decodable, Decoder, Encodable, Encoder}; . use std::fmt; . use std::hash::Hash; . use tracing::*; . . /// A `SyntaxContext` represents a chain of pairs `(ExpnId, Transparency)` named "marks". . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 1,146,079 ( 0.02%) pub struct SyntaxContext(u32); . 3,817 ( 0.00%) #[derive(Debug, Encodable, Decodable, Clone)] . pub struct SyntaxContextData { 61 ( 0.00%) outer_expn: ExpnId, 183 ( 0.00%) outer_transparency: Transparency, . parent: SyntaxContext, . /// This context, but with all transparent and semi-transparent expansions filtered away. . opaque: SyntaxContext, . /// This context, but with all transparent expansions filtered away. . opaque_and_semitransparent: SyntaxContext, . /// Name of the crate to which `$crate` with this context would resolve. . dollar_crate_name: Symbol, . } -- line 61 ---------------------------------------- -- line 65 ---------------------------------------- . pub struct ExpnIndex { . ENCODABLE = custom . } . } . . /// A unique ID associated with a macro invocation and expansion. . #[derive(Clone, Copy, PartialEq, Eq, Hash)] . pub struct ExpnId { 1,325 ( 0.00%) pub krate: CrateNum, 46,902 ( 0.00%) pub local_id: ExpnIndex, . } . . impl fmt::Debug for ExpnId { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . // Generate crate_::{{expn_}}. . write!(f, "{:?}::{{{{expn{}}}}}", self.krate, self.local_id.private) . } . } -- line 82 ---------------------------------------- -- line 106 ---------------------------------------- . // or ensure that this method is always invoked with the same . // `NodeIdHashingMode` . // . // Note that we require that `hash_spans` be set according to the global . // `-Z incremental-ignore-spans` option. Normally, this option is disabled, . // which will cause us to require that this method always be called with `Span` hashing . // enabled. . HashingControls { hash_spans, node_id_hashing_mode: _ } 32,558 ( 0.00%) if hash_spans == !ctx.debug_opts_incremental_ignore_spans() => {} . other => panic!("Attempted hashing of {msg} with non-default HashingControls: {:?}", other), . } . } . . /// A unique hash value associated to an expansion. . #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Encodable, Decodable, HashStable_Generic)] 444 ( 0.00%) pub struct ExpnHash(Fingerprint); . . impl ExpnHash { . /// Returns the [StableCrateId] identifying the crate this [ExpnHash] . /// originates from. . #[inline] . pub fn stable_crate_id(self) -> StableCrateId { . StableCrateId(self.0.as_value().0) . } -- line 129 ---------------------------------------- -- line 138 ---------------------------------------- . . #[inline] . pub fn is_root(self) -> bool { . self.0 == Fingerprint::ZERO . } . . /// Builds a new [ExpnHash] with the given [StableCrateId] and . /// `local_hash`, where `local_hash` must be unique within its crate. 564 ( 0.00%) fn new(stable_crate_id: StableCrateId, local_hash: u64) -> ExpnHash { . ExpnHash(Fingerprint::new(stable_crate_id.0, local_hash)) 282 ( 0.00%) } . } . . /// A property of a macro expansion that determines how identifiers . /// produced by that expansion are resolved. 63,148 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Hash, Debug, Encodable, Decodable)] . #[derive(HashStable_Generic)] . pub enum Transparency { . /// Identifier produced by a transparent expansion is always resolved at call-site. . /// Call-site spans in procedural macros, hygiene opt-out in `macro` should use this. . Transparent, . /// Identifier produced by a semi-transparent expansion may be resolved . /// either at call-site or at definition-site. . /// If it's a local variable, label or `$crate` then it's resolved at def-site. -- line 161 ---------------------------------------- -- line 169 ---------------------------------------- . } . . impl LocalExpnId { . /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST. . pub const ROOT: LocalExpnId = LocalExpnId::from_u32(0); . . pub fn from_raw(idx: ExpnIndex) -> LocalExpnId { . LocalExpnId::from_u32(idx.as_u32()) 32,350 ( 0.00%) } . . pub fn as_raw(self) -> ExpnIndex { . ExpnIndex::from_u32(self.as_u32()) 11,036 ( 0.00%) } . . pub fn fresh_empty() -> LocalExpnId { . HygieneData::with(|data| { . let expn_id = data.local_expn_data.push(None); . let _eid = data.local_expn_hashes.push(ExpnHash(Fingerprint::ZERO)); . debug_assert_eq!(expn_id, _eid); . expn_id . }) . } . . pub fn fresh(mut expn_data: ExpnData, ctx: impl HashStableContext) -> LocalExpnId { . debug_assert_eq!(expn_data.parent.krate, LOCAL_CRATE); 960 ( 0.00%) let expn_hash = update_disambiguator(&mut expn_data, ctx); . HygieneData::with(|data| { 1,360 ( 0.00%) let expn_id = data.local_expn_data.push(Some(expn_data)); . let _eid = data.local_expn_hashes.push(expn_hash); . debug_assert_eq!(expn_id, _eid); 272 ( 0.00%) let _old_id = data.expn_hash_to_expn_id.insert(expn_hash, expn_id.to_expn_id()); . debug_assert!(_old_id.is_none()); . expn_id . }) . } . . #[inline] . pub fn expn_hash(self) -> ExpnHash { . HygieneData::with(|data| data.local_expn_hash(self)) . } . . #[inline] . pub fn expn_data(self) -> ExpnData { 408 ( 0.00%) HygieneData::with(|data| data.local_expn_data(self).clone()) . } . . #[inline] . pub fn to_expn_id(self) -> ExpnId { 11,981 ( 0.00%) ExpnId { krate: LOCAL_CRATE, local_id: self.as_raw() } . } . . #[inline] . pub fn set_expn_data(self, mut expn_data: ExpnData, ctx: impl HashStableContext) { . debug_assert_eq!(expn_data.parent.krate, LOCAL_CRATE); 2,336 ( 0.00%) let expn_hash = update_disambiguator(&mut expn_data, ctx); . HygieneData::with(|data| { 292 ( 0.00%) let old_expn_data = &mut data.local_expn_data[self]; 292 ( 0.00%) assert!(old_expn_data.is_none(), "expansion data is reset for an expansion ID"); 1,460 ( 0.00%) *old_expn_data = Some(expn_data); . debug_assert_eq!(data.local_expn_hashes[self].0, Fingerprint::ZERO); 584 ( 0.00%) data.local_expn_hashes[self] = expn_hash; 438 ( 0.00%) let _old_id = data.expn_hash_to_expn_id.insert(expn_hash, self.to_expn_id()); . debug_assert!(_old_id.is_none()); . }); . } . . #[inline] . pub fn is_descendant_of(self, ancestor: LocalExpnId) -> bool { . self.to_expn_id().is_descendant_of(ancestor.to_expn_id()) . } -- line 238 ---------------------------------------- -- line 259 ---------------------------------------- . } . } . . impl ExpnId { . /// The ID of the theoretical expansion that generates freshly parsed, unexpanded AST. . /// Invariant: we do not create any ExpnId with local_id == 0 and krate != 0. . pub const fn root() -> ExpnId { . ExpnId { krate: LOCAL_CRATE, local_id: ExpnIndex::from_u32(0) } 65,172 ( 0.00%) } . . #[inline] . pub fn expn_hash(self) -> ExpnHash { . HygieneData::with(|data| data.expn_hash(self)) . } . . #[inline] . pub fn from_hash(hash: ExpnHash) -> Option { . HygieneData::with(|data| data.expn_hash_to_expn_id.get(&hash).copied()) . } . . #[inline] . pub fn as_local(self) -> Option { 44,625 ( 0.00%) if self.krate == LOCAL_CRATE { Some(LocalExpnId::from_raw(self.local_id)) } else { None } . } . . #[inline] . #[track_caller] . pub fn expect_local(self) -> LocalExpnId { . self.as_local().unwrap() . } . . #[inline] . pub fn expn_data(self) -> ExpnData { 2,520 ( 0.00%) HygieneData::with(|data| data.expn_data(self).clone()) . } . . #[inline] . pub fn is_descendant_of(self, ancestor: ExpnId) -> bool { . // a few "fast path" cases to avoid locking HygieneData 12 ( 0.00%) if ancestor == ExpnId::root() || ancestor == self { . return true; . } . if ancestor.krate != self.krate { . return false; . } . HygieneData::with(|data| data.is_descendant_of(self, ancestor)) . } . . /// `expn_id.outer_expn_is_descendant_of(ctxt)` is equivalent to but faster than . /// `expn_id.is_descendant_of(ctxt.outer_expn())`. 14,552 ( 0.00%) pub fn outer_expn_is_descendant_of(self, ctxt: SyntaxContext) -> bool { . HygieneData::with(|data| data.is_descendant_of(self, data.outer_expn(ctxt))) 7,276 ( 0.00%) } . . /// Returns span for the macro which originally caused this expansion to happen. . /// . /// Stops backtracing at include! boundary. . pub fn expansion_cause(mut self) -> Option { . let mut last_macro = None; . loop { . let expn_data = self.expn_data(); -- line 319 ---------------------------------------- -- line 348 ---------------------------------------- . /// This is used by `update_disambiguator` to keep track of which `ExpnData`s . /// would have collisions without a disambiguator. . /// The keys of this map are always computed with `ExpnData.disambiguator` . /// set to 0. . expn_data_disambiguators: FxHashMap, . } . . impl HygieneData { 10 ( 0.00%) crate fn new(edition: Edition) -> Self { . let root_data = ExpnData::default( . ExpnKind::Root, . DUMMY_SP, . edition, . Some(CRATE_DEF_ID.to_def_id()), . None, . ); . 50 ( 0.00%) HygieneData { . local_expn_data: IndexVec::from_elem_n(Some(root_data), 1), . local_expn_hashes: IndexVec::from_elem_n(ExpnHash(Fingerprint::ZERO), 1), . foreign_expn_data: FxHashMap::default(), . foreign_expn_hashes: FxHashMap::default(), . expn_hash_to_expn_id: std::iter::once((ExpnHash(Fingerprint::ZERO), ExpnId::root())) . .collect(), 8 ( 0.00%) syntax_context_data: vec![SyntaxContextData { . outer_expn: ExpnId::root(), . outer_transparency: Transparency::Opaque, . parent: SyntaxContext(0), . opaque: SyntaxContext(0), . opaque_and_semitransparent: SyntaxContext(0), . dollar_crate_name: kw::DollarCrate, . }], . syntax_context_map: FxHashMap::default(), . expn_data_disambiguators: FxHashMap::default(), . } 10 ( 0.00%) } . 2,728 ( 0.00%) pub fn with T>(f: F) -> T { 40,499 ( 0.00%) with_session_globals(|session_globals| f(&mut *session_globals.hygiene_data.borrow_mut())) 2,745 ( 0.00%) } . . #[inline] . fn local_expn_hash(&self, expn_id: LocalExpnId) -> ExpnHash { . self.local_expn_hashes[expn_id] . } . . #[inline] . fn expn_hash(&self, expn_id: ExpnId) -> ExpnHash { . match expn_id.as_local() { . Some(expn_id) => self.local_expn_hashes[expn_id], . None => self.foreign_expn_hashes[&expn_id], . } . } . 748 ( 0.00%) fn local_expn_data(&self, expn_id: LocalExpnId) -> &ExpnData { . self.local_expn_data[expn_id].as_ref().expect("no expansion data for an expansion ID") 748 ( 0.00%) } . 21,163 ( 0.00%) fn expn_data(&self, expn_id: ExpnId) -> &ExpnData { 63,489 ( 0.00%) if let Some(expn_id) = expn_id.as_local() { . self.local_expn_data[expn_id].as_ref().expect("no expansion data for an expansion ID") . } else { . &self.foreign_expn_data[&expn_id] . } 42,326 ( 0.00%) } . . fn is_descendant_of(&self, mut expn_id: ExpnId, ancestor: ExpnId) -> bool { . // a couple "fast path" cases to avoid traversing parents in the loop below 16,862 ( 0.00%) if ancestor == ExpnId::root() { . return true; . } 1,620 ( 0.00%) if expn_id.krate != ancestor.krate { . return false; . } . loop { 923 ( 0.00%) if expn_id == ancestor { . return true; . } 923 ( 0.00%) if expn_id == ExpnId::root() { . return false; . } . expn_id = self.expn_data(expn_id).parent; . } 444 ( 0.00%) } . 18,316 ( 0.00%) fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext { 157,240 ( 0.00%) self.syntax_context_data[ctxt.0 as usize].opaque 18,316 ( 0.00%) } . 7,448 ( 0.00%) fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext { 26,419 ( 0.00%) self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent 7,448 ( 0.00%) } . 9,758 ( 0.00%) fn outer_expn(&self, ctxt: SyntaxContext) -> ExpnId { 177,065 ( 0.00%) self.syntax_context_data[ctxt.0 as usize].outer_expn 9,758 ( 0.00%) } . 31,422 ( 0.00%) fn outer_mark(&self, ctxt: SyntaxContext) -> (ExpnId, Transparency) { 16,664 ( 0.00%) let data = &self.syntax_context_data[ctxt.0 as usize]; 70,313 ( 0.00%) (data.outer_expn, data.outer_transparency) 48,086 ( 0.00%) } . . fn parent_ctxt(&self, ctxt: SyntaxContext) -> SyntaxContext { 3,749 ( 0.00%) self.syntax_context_data[ctxt.0 as usize].parent . } . . fn remove_mark(&self, ctxt: &mut SyntaxContext) -> (ExpnId, Transparency) { 444 ( 0.00%) let outer_mark = self.outer_mark(*ctxt); 3,972 ( 0.00%) *ctxt = self.parent_ctxt(*ctxt); . outer_mark . } . 7,832 ( 0.00%) fn marks(&self, mut ctxt: SyntaxContext) -> Vec<(ExpnId, Transparency)> { . let mut marks = Vec::new(); 1,932 ( 0.00%) while ctxt != SyntaxContext::root() { . debug!("marks: getting parent of {:?}", ctxt); . marks.push(self.outer_mark(ctxt)); . ctxt = self.parent_ctxt(ctxt); . } . marks.reverse(); . marks 8,811 ( 0.00%) } . . fn walk_chain(&self, mut span: Span, to: SyntaxContext) -> Span { . debug!("walk_chain({:?}, {:?})", span, to); . debug!("walk_chain: span ctxt = {:?}", span.ctxt()); . while span.from_expansion() && span.ctxt() != to { . let outer_expn = self.outer_expn(span.ctxt()); . debug!("walk_chain({:?}): outer_expn={:?}", span, outer_expn); . let expn_data = self.expn_data(outer_expn); . debug!("walk_chain({:?}): expn_data={:?}", span, expn_data); . span = expn_data.call_site; . } . span . } . 120,480 ( 0.00%) fn adjust(&self, ctxt: &mut SyntaxContext, expn_id: ExpnId) -> Option { . let mut scope = None; 36,144 ( 0.00%) while !self.is_descendant_of(expn_id, self.outer_expn(*ctxt)) { . scope = Some(self.remove_mark(ctxt).0); . } . scope 120,480 ( 0.00%) } . 33,282 ( 0.00%) fn apply_mark( . &mut self, . ctxt: SyntaxContext, . expn_id: ExpnId, . transparency: Transparency, . ) -> SyntaxContext { 7,396 ( 0.00%) assert_ne!(expn_id, ExpnId::root()); 3,698 ( 0.00%) if transparency == Transparency::Opaque { 5,910 ( 0.00%) return self.apply_mark_internal(ctxt, expn_id, transparency); . } . 18,991 ( 0.00%) let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt(); 2,713 ( 0.00%) let mut call_site_ctxt = if transparency == Transparency::SemiTransparent { . self.normalize_to_macros_2_0(call_site_ctxt) . } else { . self.normalize_to_macro_rules(call_site_ctxt) . }; . 2,713 ( 0.00%) if call_site_ctxt == SyntaxContext::root() { 8,082 ( 0.00%) return self.apply_mark_internal(ctxt, expn_id, transparency); . } . . // Otherwise, `expn_id` is a macros 1.0 definition and the call site is in a . // macros 2.0 expansion, i.e., a macros 1.0 invocation is in a macros 2.0 definition. . // . // In this case, the tokens from the macros 1.0 definition inherit the hygiene . // at their invocation. That is, we pretend that the macros 1.0 definition . // was defined at its invocation (i.e., inside the macros 2.0 definition) . // so that the macros 2.0 definition remains hygienic. . // . // See the example at `test/ui/hygiene/legacy_interaction.rs`. 171 ( 0.00%) for (expn_id, transparency) in self.marks(ctxt) { . call_site_ctxt = self.apply_mark_internal(call_site_ctxt, expn_id, transparency); . } 76 ( 0.00%) self.apply_mark_internal(call_site_ctxt, expn_id, transparency) . } . 29,584 ( 0.00%) fn apply_mark_internal( . &mut self, . ctxt: SyntaxContext, . expn_id: ExpnId, . transparency: Transparency, . ) -> SyntaxContext { . let syntax_context_data = &mut self.syntax_context_data; 22,188 ( 0.00%) let mut opaque = syntax_context_data[ctxt.0 as usize].opaque; . let mut opaque_and_semitransparent = 3,698 ( 0.00%) syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent; . 3,698 ( 0.00%) if transparency >= Transparency::Opaque { . let parent = opaque; 9,850 ( 0.00%) opaque = *self . .syntax_context_map . .entry((parent, expn_id, transparency)) . .or_insert_with(|| { 83 ( 0.00%) let new_opaque = SyntaxContext(syntax_context_data.len() as u32); . syntax_context_data.push(SyntaxContextData { . outer_expn: expn_id, . outer_transparency: transparency, . parent, . opaque: new_opaque, . opaque_and_semitransparent: new_opaque, . dollar_crate_name: kw::DollarCrate, . }); . new_opaque . }); . } . 2,856 ( 0.00%) if transparency >= Transparency::SemiTransparent { . let parent = opaque_and_semitransparent; 10,665 ( 0.00%) opaque_and_semitransparent = *self . .syntax_context_map . .entry((parent, expn_id, transparency)) . .or_insert_with(|| { . let new_opaque_and_semitransparent = 43 ( 0.00%) SyntaxContext(syntax_context_data.len() as u32); . syntax_context_data.push(SyntaxContextData { . outer_expn: expn_id, . outer_transparency: transparency, . parent, . opaque, . opaque_and_semitransparent: new_opaque_and_semitransparent, . dollar_crate_name: kw::DollarCrate, . }); . new_opaque_and_semitransparent . }); . } . . let parent = ctxt; 7,396 ( 0.00%) *self.syntax_context_map.entry((parent, expn_id, transparency)).or_insert_with(|| { . let new_opaque_and_semitransparent_and_transparent = 286 ( 0.00%) SyntaxContext(syntax_context_data.len() as u32); . syntax_context_data.push(SyntaxContextData { . outer_expn: expn_id, . outer_transparency: transparency, . parent, . opaque, . opaque_and_semitransparent, . dollar_crate_name: kw::DollarCrate, . }); . new_opaque_and_semitransparent_and_transparent . }) 29,584 ( 0.00%) } . } . . pub fn clear_syntax_context_map() { 5 ( 0.00%) HygieneData::with(|data| data.syntax_context_map = FxHashMap::default()); . } . . pub fn walk_chain(span: Span, to: SyntaxContext) -> Span { . HygieneData::with(|data| data.walk_chain(span, to)) . } . 984 ( 0.00%) pub fn update_dollar_crate_names(mut get_name: impl FnMut(SyntaxContext) -> Symbol) { . // The new contexts that need updating are at the end of the list and have `$crate` as a name. . let (len, to_update) = HygieneData::with(|data| { . ( 164 ( 0.00%) data.syntax_context_data.len(), . data.syntax_context_data . .iter() . .rev() . .take_while(|scdata| scdata.dollar_crate_name == kw::DollarCrate) . .count(), . ) . }); . // The callback must be called from outside of the `HygieneData` lock, . // since it will try to acquire it too. 492 ( 0.00%) let range_to_update = len - to_update..len; . let names: Vec<_> = . range_to_update.clone().map(|idx| get_name(SyntaxContext::from_u32(idx as u32))).collect(); . HygieneData::with(|data| { 328 ( 0.00%) range_to_update.zip(names).for_each(|(idx, name)| { 136 ( 0.00%) data.syntax_context_data[idx].dollar_crate_name = name; . }) . }) 984 ( 0.00%) } . . pub fn debug_hygiene_data(verbose: bool) -> String { . HygieneData::with(|data| { . if verbose { . format!("{:#?}", data) . } else { . let mut s = String::from(""); . s.push_str("Expansions:"); -- line 634 ---------------------------------------- -- line 674 ---------------------------------------- . } . . #[inline] . crate fn from_u32(raw: u32) -> SyntaxContext { . SyntaxContext(raw) . } . . /// Extend a syntax context with a given expansion and transparency. 15,420 ( 0.00%) crate fn apply_mark(self, expn_id: ExpnId, transparency: Transparency) -> SyntaxContext { 7,126 ( 0.00%) HygieneData::with(|data| data.apply_mark(self, expn_id, transparency)) 5,140 ( 0.00%) } . . /// Pulls a single mark off of the syntax context. This effectively moves the . /// context up one macro definition level. That is, if we have a nested macro . /// definition as follows: . /// . /// ```rust . /// macro_rules! f { . /// macro_rules! g { -- line 692 ---------------------------------------- -- line 694 ---------------------------------------- . /// } . /// } . /// ``` . /// . /// and we have a SyntaxContext that is referring to something declared by an invocation . /// of g (call it g1), calling remove_mark will result in the SyntaxContext for the . /// invocation of f that created g1. . /// Returns the mark that was removed. 444 ( 0.00%) pub fn remove_mark(&mut self) -> ExpnId { . HygieneData::with(|data| data.remove_mark(self).0) . } . 3,840 ( 0.00%) pub fn marks(self) -> Vec<(ExpnId, Transparency)> { 1,920 ( 0.00%) HygieneData::with(|data| data.marks(self)) 3,840 ( 0.00%) } . . /// Adjust this context for resolution in a scope created by the given expansion. . /// For example, consider the following three resolutions of `f`: . /// . /// ```rust . /// mod foo { pub fn f() {} } // `f`'s `SyntaxContext` is empty. . /// m!(f); . /// macro m($f:ident) { -- line 716 ---------------------------------------- -- line 726 ---------------------------------------- . /// //| and it resolves to `::bar::f`. . /// bar::$f(); // `f`'s `SyntaxContext` is empty. . /// //^ Since `mod bar` is not outside this expansion, `adjust` does not change `$f`, . /// //| and it resolves to `::bar::$f`. . /// } . /// ``` . /// This returns the expansion whose definition scope we use to privacy check the resolution, . /// or `None` if we privacy check as usual (i.e., not w.r.t. a macro definition scope). 14,092 ( 0.00%) pub fn adjust(&mut self, expn_id: ExpnId) -> Option { 7,046 ( 0.00%) HygieneData::with(|data| data.adjust(self, expn_id)) 7,046 ( 0.00%) } . . /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0. 30,068 ( 0.00%) pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { . HygieneData::with(|data| { 15,034 ( 0.00%) *self = data.normalize_to_macros_2_0(*self); 22,551 ( 0.00%) data.adjust(self, expn_id) . }) 15,034 ( 0.00%) } . . /// Adjust this context for resolution in a scope created by the given expansion . /// via a glob import with the given `SyntaxContext`. . /// For example: . /// . /// ```rust . /// m!(f); . /// macro m($i:ident) { -- line 752 ---------------------------------------- -- line 811 ---------------------------------------- . let scope = marks.last().map(|mark| mark.0); . while let Some((expn_id, transparency)) = marks.pop() { . *self = data.apply_mark(*self, expn_id, transparency); . } . Some(scope) . }) . } . 6,048 ( 0.00%) pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool { . HygieneData::with(|data| { 1,008 ( 0.00%) let mut self_normalized = data.normalize_to_macros_2_0(self); 5,040 ( 0.00%) data.adjust(&mut self_normalized, expn_id); 1,008 ( 0.00%) self_normalized == data.normalize_to_macros_2_0(other) . }) 2,016 ( 0.00%) } . . #[inline] . pub fn normalize_to_macros_2_0(self) -> SyntaxContext { 9,158 ( 0.00%) HygieneData::with(|data| data.normalize_to_macros_2_0(self)) . } . . #[inline] . pub fn normalize_to_macro_rules(self) -> SyntaxContext { 3,724 ( 0.00%) HygieneData::with(|data| data.normalize_to_macro_rules(self)) . } . . #[inline] . pub fn outer_expn(self) -> ExpnId { . HygieneData::with(|data| data.outer_expn(self)) . } . . /// `ctxt.outer_expn_data()` is equivalent to but faster than . /// `ctxt.outer_expn().expn_data()`. . #[inline] . pub fn outer_expn_data(self) -> ExpnData { 28,093 ( 0.00%) HygieneData::with(|data| data.expn_data(data.outer_expn(self)).clone()) . } . . #[inline] . pub fn outer_mark(self) -> (ExpnId, Transparency) { 27,667 ( 0.00%) HygieneData::with(|data| data.outer_mark(self)) . } . . pub fn dollar_crate_name(self) -> Symbol { . HygieneData::with(|data| data.syntax_context_data[self.0 as usize].dollar_crate_name) . } . 8,088 ( 0.00%) pub fn edition(self) -> Edition { 28,176 ( 0.00%) HygieneData::with(|data| data.expn_data(data.outer_expn(self)).edition) 8,088 ( 0.00%) } . } . . impl fmt::Debug for SyntaxContext { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . write!(f, "#{}", self.0) . } . } . -- line 868 ---------------------------------------- -- line 877 ---------------------------------------- . } . . pub fn fresh_expansion_with_transparency( . self, . expn_data: ExpnData, . transparency: Transparency, . ctx: impl HashStableContext, . ) -> Span { 2,160 ( 0.00%) let expn_id = LocalExpnId::fresh(expn_data, ctx).to_expn_id(); . HygieneData::with(|data| { 810 ( 0.00%) self.with_ctxt(data.apply_mark(SyntaxContext::root(), expn_id, transparency)) . }) . } . . /// Reuses the span but adds information like the kind of the desugaring and features that are . /// allowed inside this span. 1,485 ( 0.00%) pub fn mark_with_reason( . self, . allow_internal_unstable: Option>, . reason: DesugaringKind, . edition: Edition, . ctx: impl HashStableContext, . ) -> Span { 2,160 ( 0.00%) let expn_data = ExpnData { 270 ( 0.00%) allow_internal_unstable, 1,215 ( 0.00%) ..ExpnData::default(ExpnKind::Desugaring(reason), self, edition, None, None) . }; . self.fresh_expansion(expn_data, ctx) 1,080 ( 0.00%) } . } . . /// A subset of properties from both macro definition and macro call available through global data. . /// Avoid using this if you have access to the original definition or call structures. 127,478 ( 0.00%) #[derive(Clone, Debug, Encodable, Decodable, HashStable_Generic)] . pub struct ExpnData { . // --- The part unique to each expansion. . /// The kind of this expansion - macro or compiler desugaring. . pub kind: ExpnKind, . /// The expansion that produced this expansion. 18,864 ( 0.00%) pub parent: ExpnId, . /// The location of the actual macro invocation or syntax sugar , e.g. . /// `let x = foo!();` or `if let Some(y) = x {}` . /// . /// This may recursively refer to other macro invocations, e.g., if . /// `foo!()` invoked `bar!()` internally, and there was an . /// expression inside `bar!`; the call_site of the expression in . /// the expansion would point to the `bar!` invocation; that . /// call_site span would have its own ExpnData, with the call_site -- line 924 ---------------------------------------- -- line 929 ---------------------------------------- . /// that have identical `ExpnData`s. This violates the contract of `HashStable` . /// - the two `ExpnId`s are not equal, but their `Fingerprint`s are equal . /// (since the numerical `ExpnId` value is not considered by the `HashStable` . /// implementation). . /// . /// The `disambiguator` field is set by `update_disambiguator` when two distinct . /// `ExpnId`s would end up with the same `Fingerprint`. Since `ExpnData` includes . /// a `krate` field, this value only needs to be unique within a single crate. 9,432 ( 0.00%) disambiguator: u32, . . // --- The part specific to the macro/desugaring definition. . // --- It may be reasonable to share this part between expansions with the same definition, . // --- but such sharing is known to bring some minor inconveniences without also bringing . // --- noticeable perf improvements (PR #62898). . /// The span of the macro definition (possibly dummy). . /// This span serves only informational purpose and is not used for resolution. . pub def_site: Span, . /// List of `#[unstable]`/feature-gated features that the macro is allowed to use . /// internally without forcing the whole crate to opt-in . /// to them. 272 ( 0.00%) pub allow_internal_unstable: Option>, . /// Whether the macro is allowed to use `unsafe` internally . /// even if the user crate has `#![forbid(unsafe_code)]`. . pub allow_internal_unsafe: bool, . /// Enables the macro helper hack (`ident!(...)` -> `$crate::ident!(...)`) . /// for a given macro. . pub local_inner_macros: bool, . /// Edition of the crate in which the macro is defined. 9,432 ( 0.00%) pub edition: Edition, . /// The `DefId` of the macro being invoked, . /// if this `ExpnData` corresponds to a macro invocation 9,432 ( 0.00%) pub macro_def_id: Option, . /// The normal module (`mod`) in which the expanded macro was defined. . pub parent_module: Option, . } . . impl !PartialEq for ExpnData {} . impl !Hash for ExpnData {} . . impl ExpnData { 1,898 ( 0.00%) pub fn new( . kind: ExpnKind, . parent: ExpnId, . call_site: Span, . def_site: Span, . allow_internal_unstable: Option>, . allow_internal_unsafe: bool, . local_inner_macros: bool, . edition: Edition, . macro_def_id: Option, . parent_module: Option, . ) -> ExpnData { 2,044 ( 0.00%) ExpnData { . kind, . parent, . call_site, . def_site, . allow_internal_unstable, . allow_internal_unsafe, . local_inner_macros, . edition, . macro_def_id, . parent_module, . disambiguator: 0, . } 730 ( 0.00%) } . . /// Constructs expansion data with default properties. 405 ( 0.00%) pub fn default( . kind: ExpnKind, . call_site: Span, . edition: Edition, . macro_def_id: Option, . parent_module: Option, . ) -> ExpnData { 1,620 ( 0.00%) ExpnData { . kind, . parent: ExpnId::root(), . call_site, . def_site: DUMMY_SP, . allow_internal_unstable: None, . allow_internal_unsafe: false, . local_inner_macros: false, . edition, . macro_def_id, . parent_module, . disambiguator: 0, . } 135 ( 0.00%) } . 6 ( 0.00%) pub fn allow_unstable( . kind: ExpnKind, . call_site: Span, . edition: Edition, . allow_internal_unstable: Lrc<[Symbol]>, . macro_def_id: Option, . parent_module: Option, . ) -> ExpnData { 13 ( 0.00%) ExpnData { . allow_internal_unstable: Some(allow_internal_unstable), . ..ExpnData::default(kind, call_site, edition, macro_def_id, parent_module) . } 2 ( 0.00%) } . . #[inline] . pub fn is_root(&self) -> bool { . matches!(self.kind, ExpnKind::Root) . } . . #[inline] 2,574 ( 0.00%) fn hash_expn(&self, ctx: &mut impl HashStableContext) -> u64 { . let mut hasher = StableHasher::new(); . self.hash_stable(ctx, &mut hasher); . hasher.finish() 2,288 ( 0.00%) } . } . . /// Expansion kind. 127,813 ( 0.00%) #[derive(Clone, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum ExpnKind { . /// No expansion, aka root expansion. Only `ExpnId::root()` has this kind. . Root, . /// Expansion produced by a macro. 7,763 ( 0.00%) Macro(MacroKind, Symbol), . /// Transform done by the compiler on the AST. 51 ( 0.00%) AstPass(AstPass), . /// Desugaring done by the compiler during HIR lowering. 1,182 ( 0.00%) Desugaring(DesugaringKind), . /// MIR inlining . Inlined, . } . . impl ExpnKind { . pub fn descr(&self) -> String { . match *self { . ExpnKind::Root => kw::PathRoot.to_string(), -- line 1064 ---------------------------------------- -- line 1070 ---------------------------------------- . ExpnKind::AstPass(kind) => kind.descr().to_string(), . ExpnKind::Desugaring(kind) => format!("desugaring of {}", kind.descr()), . ExpnKind::Inlined => "inlined source".to_string(), . } . } . } . . /// The kind of macro invocation or definition. 5,452 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, Encodable, Decodable, Hash, Debug)] 24 ( 0.00%) #[derive(HashStable_Generic)] . pub enum MacroKind { . /// A bang macro `foo!()`. . Bang, . /// An attribute macro `#[foo]`. . Attr, . /// A derive macro `#[derive(Foo)]` . Derive, . } . . impl MacroKind { . pub fn descr(self) -> &'static str { 8 ( 0.00%) match self { . MacroKind::Bang => "macro", . MacroKind::Attr => "attribute macro", . MacroKind::Derive => "derive macro", . } 4 ( 0.00%) } . . pub fn descr_expected(self) -> &'static str { . match self { . MacroKind::Attr => "attribute", . _ => self.descr(), . } . } . . pub fn article(self) -> &'static str { 12 ( 0.00%) match self { . MacroKind::Attr => "an", . _ => "a", . } 4 ( 0.00%) } . } . . /// The kind of AST transform. . #[derive(Clone, Copy, Debug, PartialEq, Encodable, Decodable, HashStable_Generic)] . pub enum AstPass { . StdImports, . TestHarness, . ProcMacroHarness, -- line 1118 ---------------------------------------- -- line 1161 ---------------------------------------- . DesugaringKind::OpaqueTy => "`impl Trait`", . DesugaringKind::ForLoop => "`for` loop", . DesugaringKind::LetElse => "`let...else`", . DesugaringKind::WhileLoop => "`while` loop", . } . } . } . 7 ( 0.00%) #[derive(Default)] . pub struct HygieneEncodeContext { . /// All `SyntaxContexts` for which we have written `SyntaxContextData` into crate metadata. . /// This is `None` after we finish encoding `SyntaxContexts`, to ensure . /// that we don't accidentally try to encode any more `SyntaxContexts` . serialized_ctxts: Lock>, . /// The `SyntaxContexts` that we have serialized (e.g. as a result of encoding `Spans`) . /// in the most recent 'round' of serializnig. Serializing `SyntaxContextData` . /// may cause us to serialize more `SyntaxContext`s, so serialize in a loop -- line 1177 ---------------------------------------- -- line 1180 ---------------------------------------- . . serialized_expns: Lock>, . . latest_expns: Lock>, . } . . impl HygieneEncodeContext { . /// Record the fact that we need to serialize the corresponding `ExpnData`. 5,660 ( 0.00%) pub fn schedule_expn_data_for_encoding(&self, expn: ExpnId) { 2,264 ( 0.00%) if !self.serialized_expns.lock().contains(&expn) { 2,162 ( 0.00%) self.latest_expns.lock().insert(expn); . } 4,528 ( 0.00%) } . 8 ( 0.00%) pub fn encode( . &self, . encoder: &mut T, . mut encode_ctxt: impl FnMut(&mut T, u32, &SyntaxContextData) -> Result<(), R>, . mut encode_expn: impl FnMut(&mut T, ExpnId, &ExpnData, ExpnHash) -> Result<(), R>, . ) -> Result<(), R> { . // When we serialize a `SyntaxContextData`, we may end up serializing . // a `SyntaxContext` that we haven't seen before 4 ( 0.00%) while !self.latest_ctxts.lock().is_empty() || !self.latest_expns.lock().is_empty() { . debug!( . "encode_hygiene: Serializing a round of {:?} SyntaxContextDatas: {:?}", . self.latest_ctxts.lock().len(), . self.latest_ctxts . ); . . // Consume the current round of SyntaxContexts. . // Drop the lock() temporary early . let latest_ctxts = { std::mem::take(&mut *self.latest_ctxts.lock()) }; . . // It's fine to iterate over a HashMap, because the serialization . // of the table that we insert data into doesn't depend on insertion . // order . for_all_ctxts_in(latest_ctxts.into_iter(), |index, ctxt, data| { 122 ( 0.00%) if self.serialized_ctxts.lock().insert(ctxt) { . encode_ctxt(encoder, index, data)?; . } . Ok(()) . })?; . . let latest_expns = { std::mem::take(&mut *self.latest_expns.lock()) }; . . for_all_expns_in(latest_expns.into_iter(), |expn, data, hash| { 392 ( 0.00%) if self.serialized_expns.lock().insert(expn) { . encode_expn(encoder, expn, data, hash)?; . } . Ok(()) . })?; . } . debug!("encode_hygiene: Done serializing SyntaxContextData"); . Ok(()) 8 ( 0.00%) } . } . . #[derive(Default)] . /// Additional information used to assist in decoding hygiene data . pub struct HygieneDecodeContext { . // Maps serialized `SyntaxContext` ids to a `SyntaxContext` in the current . // global `HygieneData`. When we deserialize a `SyntaxContext`, we need to create . // a new id in the global `HygieneData`. This map tracks the ID we end up picking, -- line 1242 ---------------------------------------- -- line 1257 ---------------------------------------- . . let _old_id = hygiene_data.expn_hash_to_expn_id.insert(hash, expn_id); . debug_assert!(_old_id.is_none()); . expn_id . }) . } . . /// Register an expansion which has been decoded from the metadata of a foreign crate. 408 ( 0.00%) pub fn register_expn_id( . krate: CrateNum, . local_id: ExpnIndex, . data: ExpnData, . hash: ExpnHash, . ) -> ExpnId { . debug_assert!(data.parent == ExpnId::root() || krate == data.parent.krate); 408 ( 0.00%) let expn_id = ExpnId { krate, local_id }; . HygieneData::with(|hygiene_data| { 408 ( 0.00%) let _old_data = hygiene_data.foreign_expn_data.insert(expn_id, data); . debug_assert!(_old_data.is_none()); 680 ( 0.00%) let _old_hash = hygiene_data.foreign_expn_hashes.insert(expn_id, hash); . debug_assert!(_old_hash.is_none()); 544 ( 0.00%) let _old_id = hygiene_data.expn_hash_to_expn_id.insert(hash, expn_id); . debug_assert!(_old_id.is_none()); . }); . expn_id 544 ( 0.00%) } . . /// Decode an expansion from the metadata of a foreign crate. . pub fn decode_expn_id( . krate: CrateNum, . index: u32, . decode_data: impl FnOnce(ExpnId) -> (ExpnData, ExpnHash), . ) -> ExpnId { 1,430 ( 0.00%) if index == 0 { . debug!("decode_expn_id: deserialized root"); 818 ( 0.00%) return ExpnId::root(); . } . . let index = ExpnIndex::from_u32(index); . . // This function is used to decode metadata, so it cannot decode information about LOCAL_CRATE. . debug_assert_ne!(krate, LOCAL_CRATE); 612 ( 0.00%) let expn_id = ExpnId { krate, local_id: index }; . . // Fast path if the expansion has already been decoded. 612 ( 0.00%) if HygieneData::with(|hygiene_data| hygiene_data.foreign_expn_data.contains_key(&expn_id)) { 510 ( 0.00%) return expn_id; . } . . // Don't decode the data inside `HygieneData::with`, since we need to recursively decode . // other ExpnIds 952 ( 0.00%) let (expn_data, hash) = decode_data(expn_id); . 1,224 ( 0.00%) register_expn_id(krate, index, expn_data, hash) . } . . // Decodes `SyntaxContext`, using the provided `HygieneDecodeContext` . // to track which `SyntaxContext`s we have already decoded. . // The provided closure will be invoked to deserialize a `SyntaxContextData` . // if we haven't already seen the id of the `SyntaxContext` we are deserializing. . pub fn decode_syntax_context SyntaxContextData>( . d: &mut D, . context: &HygieneDecodeContext, . decode_data: F, . ) -> SyntaxContext { 20,484 ( 0.00%) let raw_id: u32 = Decodable::decode(d); 40,968 ( 0.00%) if raw_id == 0 { . debug!("decode_syntax_context: deserialized root"); . // The root is special . return SyntaxContext::root(); . } . . let outer_ctxts = &context.remapped_ctxts; . . // Ensure that the lock() temporary is dropped early . { 1,313 ( 0.00%) if let Some(ctxt) = outer_ctxts.lock().get(raw_id as usize).copied().flatten() { . return ctxt; . } . } . . // Allocate and store SyntaxContext id *before* calling the decoder function, . // as the SyntaxContextData may reference itself. 112 ( 0.00%) let new_ctxt = HygieneData::with(|hygiene_data| { 112 ( 0.00%) let new_ctxt = SyntaxContext(hygiene_data.syntax_context_data.len() as u32); . // Push a dummy SyntaxContextData to ensure that nobody else can get the . // same ID as us. This will be overwritten after call `decode_Data` . hygiene_data.syntax_context_data.push(SyntaxContextData { 112 ( 0.00%) outer_expn: ExpnId::root(), . outer_transparency: Transparency::Transparent, . parent: SyntaxContext::root(), . opaque: SyntaxContext::root(), . opaque_and_semitransparent: SyntaxContext::root(), . dollar_crate_name: kw::Empty, . }); . let mut ctxts = outer_ctxts.lock(); . let new_len = raw_id as usize + 1; 336 ( 0.00%) if ctxts.len() < new_len { . ctxts.resize(new_len, None); . } 224 ( 0.00%) ctxts[raw_id as usize] = Some(new_ctxt); . drop(ctxts); . new_ctxt . }); . . // Don't try to decode data while holding the lock, since we need to . // be able to recursively decode a SyntaxContext 224 ( 0.00%) let mut ctxt_data = decode_data(d, raw_id); . // Reset `dollar_crate_name` so that it will be updated by `update_dollar_crate_names` . // We don't care what the encoding crate set this to - we want to resolve it . // from the perspective of the current compilation session 224 ( 0.00%) ctxt_data.dollar_crate_name = kw::DollarCrate; . . // Overwrite the dummy data with our decoded SyntaxContextData . HygieneData::with(|hygiene_data| { . let dummy = std::mem::replace( 112 ( 0.00%) &mut hygiene_data.syntax_context_data[new_ctxt.as_u32() as usize], . ctxt_data, . ); . // Make sure nothing weird happening while `decode_data` was running 112 ( 0.00%) assert_eq!(dummy.dollar_crate_name, kw::Empty); . }); . 224 ( 0.00%) new_ctxt . } . . fn for_all_ctxts_in Result<(), E>>( . ctxts: impl Iterator, . mut f: F, . ) -> Result<(), E> { . let all_data: Vec<_> = HygieneData::with(|data| { 124 ( 0.00%) ctxts.map(|ctxt| (ctxt, data.syntax_context_data[ctxt.0 as usize].clone())).collect() . }); 549 ( 0.00%) for (ctxt, data) in all_data.into_iter() { . f(ctxt.0, ctxt, &data)?; . } . Ok(()) . } . . fn for_all_expns_in( . expns: impl Iterator, . mut f: impl FnMut(ExpnId, &ExpnData, ExpnHash) -> Result<(), E>, . ) -> Result<(), E> { . let all_data: Vec<_> = HygieneData::with(|data| { 1,764 ( 0.00%) expns.map(|expn| (expn, data.expn_data(expn).clone(), data.expn_hash(expn))).collect() . }); 1,480 ( 0.00%) for (expn, data, hash) in all_data.into_iter() { . f(expn, &data, hash)?; . } . Ok(()) . } . . impl Encodable for LocalExpnId { . fn encode(&self, e: &mut E) -> Result<(), E::Error> { . self.to_expn_id().encode(e) -- line 1411 ---------------------------------------- -- line 1430 ---------------------------------------- . } . } . . pub fn raw_encode_syntax_context( . ctxt: SyntaxContext, . context: &HygieneEncodeContext, . e: &mut E, . ) -> Result<(), E::Error> { 309,600 ( 0.01%) if !context.serialized_ctxts.lock().contains(&ctxt) { 154,453 ( 0.00%) context.latest_ctxts.lock().insert(ctxt); . } . ctxt.0.encode(e) . } . . impl Encodable for SyntaxContext { . default fn encode(&self, _: &mut E) -> Result<(), E::Error> { . panic!("cannot encode `SyntaxContext` with `{}`", std::any::type_name::()); . } -- line 1447 ---------------------------------------- -- line 1457 ---------------------------------------- . /// such that the `Fingerprint` of the `ExpnData` does not collide with . /// any other `ExpnIds`. . /// . /// This method is called only when an `ExpnData` is first associated . /// with an `ExpnId` (when the `ExpnId` is initially constructed, or via . /// `set_expn_data`). It is *not* called for foreign `ExpnId`s deserialized . /// from another crate's metadata - since `ExpnHash` includes the stable crate id, . /// collisions are only possible between `ExpnId`s within the same crate. 1,323 ( 0.00%) fn update_disambiguator(expn_data: &mut ExpnData, mut ctx: impl HashStableContext) -> ExpnHash { . // This disambiguator should not have been set yet. 564 ( 0.00%) assert_eq!( . expn_data.disambiguator, 0, . "Already set disambiguator for ExpnData: {:?}", . expn_data . ); 564 ( 0.00%) assert_default_hashing_controls(&ctx, "ExpnData (disambiguator)"); 1,275 ( 0.00%) let mut expn_hash = expn_data.hash_expn(&mut ctx); . . let disambiguator = HygieneData::with(|data| { . // If this is the first ExpnData with a given hash, then keep our . // disambiguator at 0 (the default u32 value) . let disambig = data.expn_data_disambiguators.entry(expn_hash).or_default(); 282 ( 0.00%) let disambiguator = *disambig; 1,128 ( 0.00%) *disambig += 1; . disambiguator . }); . 564 ( 0.00%) if disambiguator != 0 { . debug!("Set disambiguator for expn_data={:?} expn_hash={:?}", expn_data, expn_hash); . 12 ( 0.00%) expn_data.disambiguator = disambiguator; 4 ( 0.00%) expn_hash = expn_data.hash_expn(&mut ctx); . . // Verify that the new disambiguator makes the hash unique . #[cfg(debug_assertions)] . HygieneData::with(|data| { . assert_eq!( . data.expn_data_disambiguators.get(&expn_hash), . None, . "Hash collision after disambiguator update!", . ); . }); . } . 564 ( 0.00%) ExpnHash::new(ctx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(), expn_hash) 1,323 ( 0.00%) } . . impl HashStable for SyntaxContext { 2,493,420 ( 0.05%) fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { . const TAG_EXPANSION: u8 = 0; . const TAG_NO_EXPANSION: u8 = 1; . 638,770 ( 0.01%) if *self == SyntaxContext::root() { . TAG_NO_EXPANSION.hash_stable(ctx, hasher); . } else { . TAG_EXPANSION.hash_stable(ctx, hasher); 7,510 ( 0.00%) let (expn_id, transparency) = self.outer_mark(); 46,442 ( 0.00%) expn_id.hash_stable(ctx, hasher); . transparency.hash_stable(ctx, hasher); . } 2,476,512 ( 0.05%) } . } . . impl HashStable for ExpnId { 28,287 ( 0.00%) fn hash_stable(&self, ctx: &mut CTX, hasher: &mut StableHasher) { . assert_default_hashing_controls(ctx, "ExpnId"); 63,988 ( 0.00%) let hash = if *self == ExpnId::root() { . // Avoid fetching TLS storage for a trivial often-used value. . Fingerprint::ZERO . } else { . self.expn_hash().0 . }; . . hash.hash_stable(ctx, hasher); 20,205 ( 0.00%) } . } 784,307 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/sty.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . use std::cmp::Ordering; . use std::marker::PhantomData; . use std::ops::Range; . use ty::util::IntTypeExt; . . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] . #[derive(HashStable, TypeFoldable, Lift)] . pub struct TypeAndMut<'tcx> { 493 ( 0.00%) pub ty: Ty<'tcx>, 2,465 ( 0.00%) 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 { 15,857 ( 0.00%) pub scope: DefId, 29,466 ( 0.00%) pub bound_region: BoundRegionKind, . } . 203,203 ( 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) 9,974 ( 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. 292 ( 0.00%) BrNamed(DefId, Symbol), . . /// Anonymous region for the implicit env pointer parameter . /// to a closure . BrEnv, . } . 672 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . #[derive(HashStable)] . pub struct BoundRegion { 46,320 ( 0.00%) pub var: BoundVar, 40,366 ( 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. 10,107,138 ( 0.21%) #[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. 997,075 ( 0.02%) 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]`. 53,331 ( 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`. 819,974 ( 0.02%) 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`. 13,135 ( 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. 1,491 ( 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 330 ---------------------------------------- . pub closure_kind_ty: T, . pub closure_sig_as_fn_ptr_ty: T, . pub tupled_upvars_ty: T, . } . . impl<'tcx> ClosureSubsts<'tcx> { . /// Construct `ClosureSubsts` from `ClosureSubstsParts`, containing `Substs` . /// for the closure parent, alongside additional closure-specific components. 17 ( 0.00%) pub fn new( . tcx: TyCtxt<'tcx>, . parts: ClosureSubstsParts<'tcx, Ty<'tcx>>, . ) -> ClosureSubsts<'tcx> { . ClosureSubsts { . substs: tcx.mk_substs( 34 ( 0.00%) parts.parent_substs.iter().copied().chain( 68 ( 0.00%) [parts.closure_kind_ty, parts.closure_sig_as_fn_ptr_ty, parts.tupled_upvars_ty] . .iter() . .map(|&ty| ty.into()), . ), . ), . } 34 ( 0.00%) } . . /// Divides the closure substs into their respective components. . /// The ordering assumed here must match that used by `ClosureSubsts::new` above. 321 ( 0.00%) fn split(self) -> ClosureSubstsParts<'tcx, GenericArg<'tcx>> { . match self.substs[..] { 3,200 ( 0.00%) [ 859 ( 0.00%) ref parent_substs @ .., 875 ( 0.00%) closure_kind_ty, 456 ( 0.00%) closure_sig_as_fn_ptr_ty, 590 ( 0.00%) tupled_upvars_ty, 1,284 ( 0.00%) ] => ClosureSubstsParts { . parent_substs, . closure_kind_ty, . closure_sig_as_fn_ptr_ty, . tupled_upvars_ty, . }, . _ => bug!("closure substs missing synthetics"), . } 963 ( 0.00%) } . . /// Returns `true` only if enough of the synthetic types are known to . /// allow using all of the methods on `ClosureSubsts` without panicking. . /// . /// Used primarily by `ty::print::pretty` to be able to handle closure . /// types that haven't had their synthetic types substituted in. . pub fn is_valid(self) -> bool { . self.substs.len() >= 3 -- line 378 ---------------------------------------- -- line 383 ---------------------------------------- . pub fn parent_substs(self) -> &'tcx [GenericArg<'tcx>] { . self.split().parent_substs . } . . /// Returns an iterator over the list of types of captured paths by the closure. . /// In case there was a type error in figuring out the types of the captured path, an . /// empty iterator is returned. . #[inline] 54 ( 0.00%) pub fn upvar_tys(self) -> impl Iterator> + 'tcx { 102 ( 0.00%) match self.tupled_upvars_ty().kind() { . TyKind::Error(_) => None, 68 ( 0.00%) TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()), . TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"), . ty => bug!("Unexpected representation of upvar types tuple {:?}", ty), . } . .into_iter() . .flatten() 36 ( 0.00%) } . . /// Returns the tuple type representing the upvars for this closure. . #[inline] . pub fn tupled_upvars_ty(self) -> Ty<'tcx> { 1,452 ( 0.00%) self.split().tupled_upvars_ty.expect_ty() . } . . /// Returns the closure kind for this closure; may return a type . /// variable during inference. To get the closure kind during . /// inference, use `infcx.closure_kind(substs)`. 243 ( 0.00%) pub fn kind_ty(self) -> Ty<'tcx> { . self.split().closure_kind_ty.expect_ty() 486 ( 0.00%) } . . /// Returns the `fn` pointer type representing the closure signature for this . /// closure. . // FIXME(eddyb) this should be unnecessary, as the shallowly resolved . // type is known at the time of the creation of `ClosureSubsts`, . // see `rustc_typeck::check::closure`. . pub fn sig_as_fn_ptr_ty(self) -> Ty<'tcx> { . self.split().closure_sig_as_fn_ptr_ty.expect_ty() . } . . /// Returns the closure kind for this closure; only usable outside . /// of an inference context, because in that context we know that . /// there are no type variables. . /// . /// If you have an inference context, use `infcx.closure_kind()`. 8 ( 0.00%) pub fn kind(self) -> ty::ClosureKind { 8 ( 0.00%) self.kind_ty().to_opt_closure_kind().unwrap() 16 ( 0.00%) } . . /// Extracts the signature from the closure. 187 ( 0.00%) pub fn sig(self) -> ty::PolyFnSig<'tcx> { . let ty = self.sig_as_fn_ptr_ty(); 374 ( 0.00%) match ty.kind() { 748 ( 0.00%) ty::FnPtr(sig) => *sig, . _ => bug!("closure_sig_as_fn_ptr_ty is not a fn-ptr: {:?}", ty.kind()), . } 561 ( 0.00%) } . } . . /// Similar to `ClosureSubsts`; see the above documentation for more. . #[derive(Copy, Clone, Debug, TypeFoldable)] . pub struct GeneratorSubsts<'tcx> { . pub substs: SubstsRef<'tcx>, . } . -- line 448 ---------------------------------------- -- line 676 ---------------------------------------- . } . . impl<'tcx> UpvarSubsts<'tcx> { . /// Returns an iterator over the list of types of captured paths by the closure/generator. . /// In case there was a type error in figuring out the types of the captured path, an . /// empty iterator is returned. . #[inline] . pub fn upvar_tys(self) -> impl Iterator> + 'tcx { 50 ( 0.00%) let tupled_tys = match self { 67 ( 0.00%) UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), . UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), . }; . 109 ( 0.00%) match tupled_tys.kind() { . TyKind::Error(_) => None, 92 ( 0.00%) TyKind::Tuple(..) => Some(self.tupled_upvars_ty().tuple_fields()), . TyKind::Infer(_) => bug!("upvar_tys called before capture types are inferred"), . ty => bug!("Unexpected representation of upvar types tuple {:?}", ty), . } . .into_iter() . .flatten() . } . . #[inline] . pub fn tupled_upvars_ty(self) -> Ty<'tcx> { 84 ( 0.00%) match self { 93 ( 0.00%) UpvarSubsts::Closure(substs) => substs.as_closure().tupled_upvars_ty(), . UpvarSubsts::Generator(substs) => substs.as_generator().tupled_upvars_ty(), . } . } . } . . /// An inline const is modeled like . /// . /// const InlineConst<'l0...'li, T0...Tj, R>: R; -- line 710 ---------------------------------------- -- line 760 ---------------------------------------- . } . . /// Returns the type of this inline const. . pub fn ty(self) -> Ty<'tcx> { . self.split().ty.expect_ty() . } . } . 12,607 ( 0.00%) #[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Ord, Eq, Hash, TyEncodable, TyDecodable)] 11,869 ( 0.00%) #[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. 830 ( 0.00%) pub fn stable_cmp(&self, tcx: TyCtxt<'tcx>, other: &Self) -> Ordering { . use self::ExistentialPredicate::*; 1,088 ( 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, . } 996 ( 0.00%) } . } . . impl<'tcx> Binder<'tcx, ExistentialPredicate<'tcx>> { 1,467 ( 0.00%) pub fn with_self_ty(&self, tcx: TyCtxt<'tcx>, self_ty: Ty<'tcx>) -> ty::Predicate<'tcx> { . use crate::ty::ToPredicate; 831 ( 0.00%) match self.skip_binder() { . ExistentialPredicate::Trait(tr) => { . self.rebind(tr).with_self_ty(tcx, self_ty).without_const().to_predicate(tcx) . } . ExistentialPredicate::Projection(p) => { 4 ( 0.00%) self.rebind(p.with_self_ty(tcx, self_ty)).to_predicate(tcx) . } . ExistentialPredicate::AutoTrait(did) => { . let trait_ref = self.rebind(ty::TraitRef { . def_id: did, . substs: tcx.mk_substs_trait(self_ty, &[]), . }); . trait_ref.without_const().to_predicate(tcx) . } . } 1,304 ( 0.00%) } . } . . impl<'tcx> List>> { . /// Returns the "principal `DefId`" of this set of existential predicates. . /// . /// A Rust trait object type consists (in addition to a lifetime bound) . /// of a set of trait bounds, which are separated into any number . /// of auto-trait bounds, and at most one non-auto-trait bound. The -- line 826 ---------------------------------------- -- 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>> { 477 ( 0.00%) self[0] 477 ( 0.00%) .map_bound(|this| match this { . ExistentialPredicate::Trait(tr) => Some(tr), . _ => None, . }) . .transpose() . } . 157 ( 0.00%) pub fn principal_def_id(&self) -> Option { . self.principal().map(|trait_ref| trait_ref.skip_binder().def_id) 314 ( 0.00%) } . . #[inline] . pub fn projection_bounds<'a>( . &'a self, . ) -> impl Iterator>> + 'a { . self.iter().filter_map(|predicate| { . predicate 8 ( 0.00%) .map_bound(|pred| match pred { 4 ( 0.00%) ExistentialPredicate::Projection(projection) => Some(projection), . _ => None, . }) . .transpose() . }) . } . . #[inline] . pub fn auto_traits<'a>(&'a self) -> impl Iterator + 'a { -- line 875 ---------------------------------------- -- 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. 21,694 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 1,255,508 ( 0.03%) #[derive(HashStable, TypeFoldable)] . pub struct TraitRef<'tcx> { 633 ( 0.00%) pub def_id: DefId, 643,245 ( 0.01%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> TraitRef<'tcx> { 949 ( 0.00%) pub fn new(def_id: DefId, substs: SubstsRef<'tcx>) -> TraitRef<'tcx> { . TraitRef { def_id, substs } 3,796 ( 0.00%) } . . /// Returns a `TraitRef` of the form `P0: Foo` where `Pi` . /// are the parameters defined on trait. 558 ( 0.00%) pub fn identity(tcx: TyCtxt<'tcx>, def_id: DefId) -> Binder<'tcx, TraitRef<'tcx>> { 248 ( 0.00%) ty::Binder::dummy(TraitRef { . def_id, 372 ( 0.00%) substs: InternalSubsts::identity_for_item(tcx, def_id), . }) 496 ( 0.00%) } . . #[inline] . pub fn self_ty(&self) -> Ty<'tcx> { . self.substs.type_at(0) . } . 816 ( 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); . 102 ( 0.00%) ty::TraitRef { def_id: trait_id, substs: tcx.intern_substs(&substs[..defs.params.len()]) } 1,122 ( 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 { 939 ( 0.00%) self.skip_binder().def_id 313 ( 0.00%) } . 801 ( 0.00%) pub fn to_poly_trait_predicate(&self) -> ty::PolyTraitPredicate<'tcx> { 1,602 ( 0.00%) self.map_bound(|trait_ref| ty::TraitPredicate { . trait_ref, . constness: ty::BoundConstness::NotConst, . polarity: ty::ImplPolarity::Positive, . }) 801 ( 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). 44 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 5,359 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ExistentialTraitRef<'tcx> { 724 ( 0.00%) pub def_id: DefId, 6,096 ( 0.00%) pub substs: SubstsRef<'tcx>, . } . . impl<'tcx> ExistentialTraitRef<'tcx> { 28 ( 0.00%) pub fn erase_self_ty( . tcx: TyCtxt<'tcx>, . trait_ref: ty::TraitRef<'tcx>, . ) -> ty::ExistentialTraitRef<'tcx> { . // Assert there is a Self. . trait_ref.substs.type_at(0); . . ty::ExistentialTraitRef { . def_id: trait_ref.def_id, . substs: tcx.intern_substs(&trait_ref.substs[1..]), . } 28 ( 0.00%) } . . /// Object types don't have a self type specified. Therefore, when . /// 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::TraitRef<'tcx> { . // otherwise the escaping vars would be captured by the binder . // debug_assert!(!self_ty.has_escaping_bound_vars()); -- line 985 ---------------------------------------- -- 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)) . } . } . 15,498 ( 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. 15,561 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] 228,671 ( 0.00%) 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. 16,337 ( 0.00%) pub fn dummy(value: T) -> Binder<'tcx, T> { 75,054 ( 0.00%) assert!(!value.has_escaping_bound_vars()); 162,969 ( 0.00%) Binder(value, ty::List::empty()) 16,245 ( 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); . } 17,175 ( 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 { 636,413 ( 0.01%) self.0 . } . . pub fn bound_vars(&self) -> &'tcx List { 3,191 ( 0.00%) self.1 . } . . pub fn as_ref(&self) -> Binder<'tcx, &T> { 4,876 ( 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 1085 ---------------------------------------- . . pub fn map_bound_ref>(&self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(&T) -> U, . { . self.as_ref().map_bound(f) . } . 212 ( 0.00%) pub fn map_bound>(self, f: F) -> Binder<'tcx, U> . where . F: FnOnce(T) -> U, . { 14,329 ( 0.00%) let value = f(self.0); . if cfg!(debug_assertions) { . let mut validator = ValidateBoundVars::new(self.1); . value.visit_with(&mut validator); . } 143,747 ( 0.00%) Binder(value, self.1) 204 ( 0.00%) } . . 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); . } 7,786 ( 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); . } 12,569 ( 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>, . { 117,225 ( 0.00%) if self.0.has_escaping_bound_vars() { None } else { Some(self.skip_binder()) } 240 ( 0.00%) } . . /// 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. . pub fn split(self, f: F) -> (Binder<'tcx, U>, Binder<'tcx, V>) -- line 1160 ---------------------------------------- -- 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`. 393 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 31,230 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ProjectionTy<'tcx> { . /// The parameters of the associated item. 6,421 ( 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`. 13,265 ( 0.00%) pub item_def_id: DefId, . } . . impl<'tcx> ProjectionTy<'tcx> { 5,250 ( 0.00%) pub fn trait_def_id(&self, tcx: TyCtxt<'tcx>) -> DefId { 1,500 ( 0.00%) tcx.associated_item(self.item_def_id).container.id() 6,000 ( 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 1,386 ( 0.00%) pub fn trait_ref_and_own_substs( . &self, . tcx: TyCtxt<'tcx>, . ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) { 594 ( 0.00%) let def_id = tcx.associated_item(self.item_def_id).container.id(); . let trait_generics = tcx.generics_of(def_id); 990 ( 0.00%) ( . ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, trait_generics) }, . &self.substs[trait_generics.count()..], . ) 1,782 ( 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. 6,606 ( 0.00%) pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::TraitRef<'tcx> { 734 ( 0.00%) let def_id = self.trait_def_id(tcx); 734 ( 0.00%) ty::TraitRef { def_id, substs: self.substs.truncate_to(tcx, tcx.generics_of(def_id)) } 8,074 ( 0.00%) } . 1,505 ( 0.00%) pub fn self_ty(&self) -> Ty<'tcx> { 4,515 ( 0.00%) self.substs.type_at(0) 3,010 ( 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. 19,677 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] 12,399 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct FnSig<'tcx> { 1,850 ( 0.00%) pub inputs_and_output: &'tcx List>, 16,154 ( 0.00%) pub c_variadic: bool, 3,106 ( 0.00%) pub unsafety: hir::Unsafety, 15,772 ( 0.00%) pub abi: abi::Abi, . } . . impl<'tcx> FnSig<'tcx> { 12,711 ( 0.00%) pub fn inputs(&self) -> &'tcx [Ty<'tcx>] { 55,536 ( 0.00%) &self.inputs_and_output[..self.inputs_and_output.len() - 1] 25,422 ( 0.00%) } . 8,102 ( 0.00%) pub fn output(&self) -> Ty<'tcx> { 60,029 ( 0.00%) self.inputs_and_output[self.inputs_and_output.len() - 1] 16,204 ( 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>]> { 1,632 ( 0.00%) self.map_bound_ref_unchecked(|fn_sig| fn_sig.inputs()) . } . #[inline] . pub fn input(&self, index: usize) -> ty::Binder<'tcx, Ty<'tcx>> { 5,364 ( 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) 308 ( 0.00%) } . #[inline] . pub fn output(&self) -> ty::Binder<'tcx, Ty<'tcx>> { 3,202 ( 0.00%) self.map_bound_ref(|fn_sig| fn_sig.output()) . } . pub fn c_variadic(&self) -> bool { 614 ( 0.00%) self.skip_binder().c_variadic 307 ( 0.00%) } . pub fn unsafety(&self) -> hir::Unsafety { 2,158 ( 0.00%) self.skip_binder().unsafety 1,079 ( 0.00%) } . pub fn abi(&self) -> abi::Abi { 3,624 ( 0.00%) self.skip_binder().abi 906 ( 0.00%) } . } . . pub type CanonicalPolyFnSig<'tcx> = Canonical<'tcx, Binder<'tcx, FnSig<'tcx>>>; . 64 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . #[derive(HashStable)] . pub struct ParamTy { 88 ( 0.00%) pub index: u32, . pub name: Symbol, . } . . impl<'tcx> ParamTy { 232 ( 0.00%) pub fn new(index: u32, name: Symbol) -> ParamTy { . ParamTy { index, name } 116 ( 0.00%) } . . pub fn for_def(def: &ty::GenericParamDef) -> ParamTy { 128 ( 0.00%) ParamTy::new(def.index, def.name) 64 ( 0.00%) } . . #[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 { 86 ( 0.00%) pub index: u32, 86 ( 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 2,820,369 ( 0.06%) #[derive(Clone, PartialEq, Eq, Hash, Copy, TyEncodable, TyDecodable, PartialOrd, Ord)] 20 ( 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. 80,486 ( 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, . } . 15,794 ( 0.00%) #[derive(Copy, Clone, PartialEq, Eq, Hash, TyEncodable, TyDecodable, Debug, PartialOrd, Ord)] . pub struct EarlyBoundRegion { 15,370 ( 0.00%) pub def_id: DefId, 19,507 ( 0.00%) pub index: u32, 30,599 ( 0.00%) pub name: Symbol, . } . . /// A **`const`** **v**ariable **ID**. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, TyEncodable, TyDecodable)] . pub struct ConstVid<'tcx> { 814 ( 0.00%) pub index: u32, 75 ( 0.00%) pub phantom: PhantomData<&'tcx ()>, . } . . rustc_index::newtype_index! { . /// A **region** (lifetime) **v**ariable **ID**. . pub struct RegionVid { . DEBUG_FORMAT = custom, . } . } -- line 1505 ---------------------------------------- -- 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, 1,491 ( 0.00%) pub kind: BoundTyKind, . } . 25,428 ( 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 { . BoundTy { var, kind: BoundTyKind::Anon } . } . } . . /// A `ProjectionPredicate` for an `ExistentialTraitRef`. 13 ( 0.00%) #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, TyEncodable, TyDecodable)] 593 ( 0.00%) #[derive(HashStable, TypeFoldable)] . pub struct ExistentialProjection<'tcx> { 106 ( 0.00%) pub item_def_id: DefId, 664 ( 0.00%) pub substs: SubstsRef<'tcx>, 166 ( 0.00%) pub term: Term<'tcx>, . } . . pub type PolyExistentialProjection<'tcx> = Binder<'tcx, ExistentialProjection<'tcx>>; . . impl<'tcx> ExistentialProjection<'tcx> { . /// Extracts the underlying existential trait reference from this projection. . /// For example, if this is a projection of `exists T. ::Item == X`, . /// then this function would return an `exists T. T: Iterator` existential trait . /// reference. 119 ( 0.00%) pub fn trait_ref(&self, tcx: TyCtxt<'tcx>) -> ty::ExistentialTraitRef<'tcx> { 51 ( 0.00%) let def_id = tcx.associated_item(self.item_def_id).container.id(); 34 ( 0.00%) let subst_count = tcx.generics_of(def_id).count() - 1; 17 ( 0.00%) let substs = tcx.intern_substs(&self.substs[..subst_count]); . ty::ExistentialTraitRef { def_id, substs } 153 ( 0.00%) } . . pub fn with_self_ty( . &self, . tcx: TyCtxt<'tcx>, . self_ty: Ty<'tcx>, . ) -> ty::ProjectionPredicate<'tcx> { . // otherwise the escaping regions would be captured by the binders . debug_assert!(!self_ty.has_escaping_bound_vars()); -- line 1566 ---------------------------------------- -- line 1569 ---------------------------------------- . projection_ty: ty::ProjectionTy { . item_def_id: self.item_def_id, . substs: tcx.mk_substs_trait(self_ty, self.substs), . }, . term: self.term, . } . } . 20 ( 0.00%) pub fn erase_self_ty( . tcx: TyCtxt<'tcx>, . projection_predicate: ty::ProjectionPredicate<'tcx>, . ) -> Self { . // Assert there is a Self. 12 ( 0.00%) projection_predicate.projection_ty.substs.type_at(0); . 16 ( 0.00%) Self { 8 ( 0.00%) item_def_id: projection_predicate.projection_ty.item_def_id, . substs: tcx.intern_substs(&projection_predicate.projection_ty.substs[1..]), 4 ( 0.00%) term: projection_predicate.term, . } 28 ( 0.00%) } . } . . impl<'tcx> PolyExistentialProjection<'tcx> { 10 ( 0.00%) pub fn with_self_ty( . &self, . tcx: TyCtxt<'tcx>, . self_ty: Ty<'tcx>, . ) -> ty::PolyProjectionPredicate<'tcx> { 10 ( 0.00%) self.map_bound(|p| p.with_self_ty(tcx, self_ty)) 12 ( 0.00%) } . . pub fn item_def_id(&self) -> DefId { . self.skip_binder().item_def_id . } . } . . /// Region utilities . impl RegionKind { -- line 1607 ---------------------------------------- -- line 1616 ---------------------------------------- . RegionKind::RePlaceholder(placeholder) => placeholder.name.is_named(), . RegionKind::ReEmpty(_) => false, . RegionKind::ReErased => false, . } . } . . #[inline] . pub fn is_late_bound(&self) -> bool { 3,034 ( 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 { 77,280 ( 0.00%) match *self { . ty::ReLateBound(debruijn, _) => debruijn >= index, . _ => false, . } . } . . pub fn type_flags(&self) -> TypeFlags { . let mut flags = TypeFlags::empty(); . 106,823 ( 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 4,650 ( 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 { 1,710 ( 0.00%) match self.kind() { 357 ( 0.00%) Tuple(ref tys) => tys.is_empty(), . _ => false, . } . } . . #[inline] . pub fn is_never(&self) -> bool { 165,103 ( 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 { 311,079 ( 0.01%) matches!(self.kind(), Infer(TyVar(_))) . } . . #[inline] . pub fn ty_vid(&self) -> Option { 20,234 ( 0.00%) match self.kind() { 2,470 ( 0.00%) &Infer(TyVar(vid)) => Some(vid), . _ => None, . } . } . . #[inline] . pub fn is_ty_infer(&self) -> bool { 51 ( 0.00%) matches!(self.kind(), Infer(_)) . } . . #[inline] . pub fn is_phantom_data(&self) -> bool { . if let Adt(def, _) = self.kind() { def.is_phantom_data() } else { false } . } . . #[inline] -- line 1770 ---------------------------------------- -- line 1775 ---------------------------------------- . /// Returns `true` if this type is a `str`. . #[inline] . pub fn is_str(&self) -> bool { . *self.kind() == Str . } . . #[inline] . pub fn is_param(&self, index: u32) -> bool { 36 ( 0.00%) match self.kind() { . ty::Param(ref data) => data.index == index, . _ => false, . } . } . . #[inline] . pub fn is_slice(&self) -> bool { . match self.kind() { . RawPtr(TypeAndMut { ty, .. }) | Ref(_, ty, _) => matches!(ty.kind(), Slice(_) | Str), . _ => false, . } . } . . #[inline] . pub fn is_array(&self) -> bool { 90 ( 0.00%) matches!(self.kind(), Array(..)) . } . . #[inline] . pub fn is_simd(&self) -> bool { . match self.kind() { . Adt(def, _) => def.repr.simd(), . _ => false, . } . } . 1,170 ( 0.00%) pub fn sequence_element_type(&self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 2,340 ( 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), . } 1,170 ( 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 1838 ---------------------------------------- . } . } . _ => bug!("`simd_size_and_type` called on invalid type"), . } . } . . #[inline] . pub fn is_region_ptr(&self) -> bool { 4 ( 0.00%) matches!(self.kind(), Ref(..)) . } . . #[inline] . pub fn is_mutable_ptr(&self) -> bool { 3 ( 0.00%) matches!( 2 ( 0.00%) self.kind(), . RawPtr(TypeAndMut { mutbl: hir::Mutability::Mut, .. }) . | Ref(_, _, hir::Mutability::Mut) . ) . } . . /// Get the mutability of the reference or `None` when not a reference . #[inline] . pub fn ref_mutability(&self) -> Option { -- line 1860 ---------------------------------------- -- line 1861 ---------------------------------------- . match self.kind() { . Ref(_, _, mutability) => Some(*mutability), . _ => None, . } . } . . #[inline] . pub fn is_unsafe_ptr(&self) -> bool { 2,723 ( 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 { 310,614 ( 0.01%) match self.kind() { 5,177 ( 0.00%) Adt(def, _) => def.is_box(), . _ => false, . } . } . . /// Panics if called on any type other than `Box`. 2,314 ( 0.00%) pub fn boxed_ty(&self) -> Ty<'tcx> { 2,314 ( 0.00%) match self.kind() { 5,785 ( 0.00%) Adt(def, substs) if def.is_box() => substs.type_at(0), . _ => bug!("`boxed_ty` is called on non-box type {:?}", self), . } 2,314 ( 0.00%) } . . /// 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 { 533 ( 0.00%) matches!( 1,238 ( 0.00%) self.kind(), . Bool | Char . | Int(_) . | Float(_) . | Uint(_) . | FnDef(..) . | FnPtr(_) . | RawPtr(_) . | Infer(IntVar(_) | FloatVar(_)) . ) . } . . /// Returns `true` if this type is a floating point type. . #[inline] . pub fn is_floating_point(&self) -> bool { 6 ( 0.00%) matches!(self.kind(), Float(_) | Infer(FloatVar(_))) . } . . #[inline] . pub fn is_trait(&self) -> bool { . matches!(self.kind(), Dynamic(..)) . } . . #[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 { 4,395 ( 0.00%) matches!(self.kind(), Adt(adt_def, _) if adt_def.is_union()) . } . . #[inline] . pub fn is_closure(&self) -> bool { 1,156 ( 0.00%) matches!(self.kind(), Closure(..)) . } . . #[inline] . pub fn is_generator(&self) -> bool { 1,716 ( 0.00%) matches!(self.kind(), Generator(..)) . } . . #[inline] . pub fn is_integral(&self) -> bool { 2,740 ( 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 { 1,827 ( 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 { 975 ( 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. 14,652 ( 0.00%) pub fn builtin_deref(&self, explicit: bool) -> Option> { 83,888 ( 0.00%) match self.kind() { 3,290 ( 0.00%) Adt(def, _) if def.is_box() => { 3,152 ( 0.00%) Some(TypeAndMut { ty: self.boxed_ty(), mutbl: hir::Mutability::Not }) . } 36,166 ( 0.00%) Ref(_, ty, mutbl) => Some(TypeAndMut { ty, mutbl: *mutbl }), 12 ( 0.00%) RawPtr(mt) if explicit => Some(*mt), . _ => None, . } 29,304 ( 0.00%) } . . /// Returns the type of `ty[i]`. . pub fn builtin_index(&self) -> Option> { 144 ( 0.00%) match self.kind() { . Array(ty, _) | Slice(ty) => Some(ty), . _ => None, . } 30 ( 0.00%) } . 21,592 ( 0.00%) pub fn fn_sig(&self, tcx: TyCtxt<'tcx>) -> PolyFnSig<'tcx> { 10,796 ( 0.00%) match self.kind() { 8,097 ( 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), . } 24,291 ( 0.00%) } . . #[inline] . pub fn is_fn(&self) -> bool { 243 ( 0.00%) matches!(self.kind(), FnDef(..) | FnPtr(_)) . } . . #[inline] . pub fn is_fn_ptr(&self) -> bool { . matches!(self.kind(), FnPtr(_)) . } . . #[inline] . pub fn is_impl_trait(&self) -> bool { . matches!(self.kind(), Opaque(..)) . } . . #[inline] . pub fn ty_adt_def(&self) -> Option<&'tcx AdtDef> { 6,073 ( 0.00%) match self.kind() { . Adt(adt, _) => Some(adt), . _ => None, . } . } . . /// Iterates over tuple fields. . /// Panics when called on anything but a tuple. 64 ( 0.00%) pub fn tuple_fields(&self) -> impl DoubleEndedIterator> { 802 ( 0.00%) match self.kind() { 466 ( 0.00%) Tuple(substs) => substs.iter().map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 128 ( 0.00%) } . . /// Get the `i`-th element of a tuple. . /// Panics when called on anything but a tuple. 27 ( 0.00%) pub fn tuple_element_ty(&self, i: usize) -> Option> { 54 ( 0.00%) match self.kind() { 54 ( 0.00%) Tuple(substs) => substs.iter().nth(i).map(|field| field.expect_ty()), . _ => bug!("tuple_fields called on non-tuple"), . } 54 ( 0.00%) } . . /// If the type contains variants, returns the valid range of variant indices. . // . // FIXME: This requires the optimized MIR in the case of generators. . #[inline] . pub fn variant_range(&self, tcx: TyCtxt<'tcx>) -> Option> { . match self.kind() { . TyKind::Adt(adt, _) => Some(adt.variant_range()), -- line 2068 ---------------------------------------- -- line 2095 ---------------------------------------- . TyKind::Generator(def_id, substs, _) => { . Some(substs.as_generator().discriminant_for_variant(*def_id, tcx, variant_index)) . } . _ => None, . } . } . . /// Returns the type of the discriminant of this type. 2,510 ( 0.00%) pub fn discriminant_ty(&'tcx self, tcx: TyCtxt<'tcx>) -> Ty<'tcx> { 1,255 ( 0.00%) match self.kind() { 2,008 ( 0.00%) 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) . } . } 2,008 ( 0.00%) } . . /// 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 2200 ---------------------------------------- . /// function converts such a special type into the closure . /// kind. To go the other way, use . /// `tcx.closure_kind_ty(closure_kind)`. . /// . /// Note that during type checking, we use an inference variable . /// to represent the closure kind, because it has not yet been . /// inferred. Once upvar inference (in `rustc_typeck/src/check/upvar.rs`) . /// is complete, that type variable will be unified. 568 ( 0.00%) pub fn to_opt_closure_kind(&self) -> Option { 1,136 ( 0.00%) match self.kind() { 876 ( 0.00%) Int(int_ty) => match int_ty { . ty::IntTy::I8 => Some(ty::ClosureKind::Fn), . ty::IntTy::I16 => Some(ty::ClosureKind::FnMut), . ty::IntTy::I32 => Some(ty::ClosureKind::FnOnce), . _ => bug!("cannot convert type `{:?}` to a closure kind", self), . }, . . // "Bound" types appear in canonical queries when the . // closure type is not yet known . Bound(..) | Infer(_) => None, . . Error(_) => Some(ty::ClosureKind::Fn), . . _ => bug!("cannot convert type `{:?}` to a closure kind", self), . } 568 ( 0.00%) } . . /// Fast path helper for testing if a type is `Sized`. . /// . /// 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`. 158,616 ( 0.00%) pub fn is_trivially_sized(&self, tcx: TyCtxt<'tcx>) -> bool { 105,744 ( 0.00%) 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, . 2,923 ( 0.00%) ty::Tuple(tys) => tys.iter().all(|ty| ty.expect_ty().is_trivially_sized(tcx)), . 6,570 ( 0.00%) 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) . } . } 158,616 ( 0.00%) } . } . . /// 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. . /// . /// When in doubt, use `VarianceDiagInfo::default()` 21 ( 0.00%) #[derive(Copy, Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] . pub enum VarianceDiagInfo<'tcx> { . /// No additional information - this is the default. . /// We will not add any additional information to error messages. . #[default] . None, . /// We switched our variance because a generic argument occurs inside . /// the invariant generic argument of another type. . Invariant { -- line 2290 ---------------------------------------- -- 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. 42,700 ( 0.00%) pub fn xform(self, other: VarianceDiagInfo<'tcx>) -> VarianceDiagInfo<'tcx> { . // For now, just use the first `VarianceDiagInfo::Invariant` that we see 64,050 ( 0.00%) match self { . VarianceDiagInfo::None => other, . VarianceDiagInfo::Invariant { .. } => self, . } 21,350 ( 0.00%) } . } 10,655,085 ( 0.22%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_hir_pretty/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 37 ---------------------------------------- . ImplItem(hir::ImplItemId), . ForeignItem(hir::ForeignItemId), . Body(hir::BodyId), . BodyParamPat(hir::BodyId, usize), . } . . pub trait PpAnn { . fn nested(&self, _state: &mut State<'_>, _nested: Nested) {} 279,795 ( 0.01%) fn pre(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {} . fn post(&self, _state: &mut State<'_>, _node: AnnNode<'_>) {} . } . . pub struct NoAnn; . impl PpAnn for NoAnn {} . pub const NO_ANN: &dyn PpAnn = &NoAnn; . . /// Identical to the `PpAnn` implementation for `hir::Crate`, -- line 53 ---------------------------------------- -- line 124 ---------------------------------------- . } . } . . impl<'a> PrintState<'a> for State<'a> { . fn comments(&mut self) -> &mut Option> { . &mut self.comments . } . 7,371 ( 0.00%) fn print_ident(&mut self, ident: Ident) { 6,552 ( 0.00%) self.word(IdentPrinter::for_ast_ident(ident, ident.is_raw_guess()).to_string()); 4,914 ( 0.00%) self.ann.post(self, AnnNode::Name(&ident.name)) 4,095 ( 0.00%) } . . fn print_generic_args(&mut self, _: &ast::GenericArgs, _colons_before_params: bool) { . panic!("AST generic args printed by HIR pretty-printer"); . } . } . . pub const INDENT_UNIT: usize = 4; . -- line 143 ---------------------------------------- -- line 173 ---------------------------------------- . s: pp::Printer::new(), . comments: Some(Comments::new(sm, filename, input)), . attrs, . ann, . } . } . . fn attrs(&self, id: hir::HirId) -> &'a [ast::Attribute] { 418,464 ( 0.01%) (self.attrs)(id) . } . } . 1,023 ( 0.00%) pub fn to_string(ann: &dyn PpAnn, f: F) -> String . where . F: FnOnce(&mut State<'_>), . { 419,301 ( 0.01%) let mut printer = State { s: pp::Printer::new(), comments: None, attrs: &|_| &[], ann }; . f(&mut printer); 558 ( 0.00%) printer.s.eof() 744 ( 0.00%) } . . pub fn visibility_qualified>>(vis: &hir::Visibility<'_>, w: S) -> String { . to_string(NO_ANN, |s| { . s.print_visibility(vis); . s.word(w) . }) . } . -- line 200 ---------------------------------------- -- line 249 ---------------------------------------- . self.end(); // close the outer-box . } . } . . pub fn bclose(&mut self, span: rustc_span::Span) { . self.bclose_maybe_open(span, true) . } . 7,029 ( 0.00%) pub fn commasep_cmnt(&mut self, b: Breaks, elts: &[T], mut op: F, mut get_span: G) . where . F: FnMut(&mut State<'_>, &T), . G: FnMut(&T) -> rustc_span::Span, . { 2,281 ( 0.00%) self.rbox(0, b); . let len = elts.len(); . let mut i = 0; . for elt in elts { 416,268 ( 0.01%) self.maybe_print_comment(get_span(elt).hi()); . op(self, elt); . i += 1; 277,512 ( 0.01%) if i < len { . self.word(","); . self.maybe_print_trailing_comment(get_span(elt), Some(get_span(&elts[i]).hi())); 552,500 ( 0.01%) self.space_if_not_bol(); . } . } 6,024 ( 0.00%) self.end(); . } . . pub fn commasep_exprs(&mut self, b: Breaks, exprs: &[hir::Expr<'_>]) { 1,796,685 ( 0.04%) self.commasep_cmnt(b, exprs, |s, e| s.print_expr(&e), |e| e.span) . } . . pub fn print_mod(&mut self, _mod: &hir::Mod<'_>, attrs: &[ast::Attribute]) { . self.print_inner_attributes(attrs); . for &item_id in _mod.item_ids { . self.ann.nested(self, Nested::Item(item_id)); . } . } -- line 287 ---------------------------------------- -- line 1128 ---------------------------------------- . fn cond_needs_par(expr: &hir::Expr<'_>) -> bool { . match expr.kind { . hir::ExprKind::Break(..) | hir::ExprKind::Closure(..) | hir::ExprKind::Ret(..) => true, . _ => contains_exterior_struct_lit(expr), . } . } . . fn print_expr_vec(&mut self, exprs: &[hir::Expr<'_>]) { 1,644 ( 0.00%) self.ibox(INDENT_UNIT); . self.word("["); . self.commasep_exprs(Inconsistent, exprs); . self.word("]"); . self.end() . } . . fn print_expr_anon_const(&mut self, anon_const: &hir::AnonConst) { . self.ibox(INDENT_UNIT); -- line 1144 ---------------------------------------- -- line 1158 ---------------------------------------- . } . . fn print_expr_struct( . &mut self, . qpath: &hir::QPath<'_>, . fields: &[hir::ExprField<'_>], . wth: &Option<&hir::Expr<'_>>, . ) { 273 ( 0.00%) self.print_qpath(qpath, true); . self.word("{"); . self.commasep_cmnt( . Consistent, . fields, . |s, field| { 1,638 ( 0.00%) s.ibox(INDENT_UNIT); 1,092 ( 0.00%) if !field.is_shorthand { 2,184 ( 0.00%) s.print_ident(field.ident); . s.word_space(":"); . } 1,638 ( 0.00%) s.print_expr(&field.expr); 1,638 ( 0.00%) s.end() . }, 4,368 ( 0.00%) |f| f.span, . ); 273 ( 0.00%) match *wth { . Some(ref expr) => { . self.ibox(INDENT_UNIT); . if !fields.is_empty() { . self.word(","); . self.space(); . } . self.word(".."); . self.print_expr(&expr); . self.end(); . } . _ => { 91 ( 0.00%) if !fields.is_empty() { . self.word(",") . } . } . } . self.word("}"); . } . . fn print_expr_tup(&mut self, exprs: &[hir::Expr<'_>]) { 182 ( 0.00%) self.popen(); . self.commasep_exprs(Inconsistent, exprs); 182 ( 0.00%) if exprs.len() == 1 { . self.word(","); . } . self.pclose() . } . . fn print_expr_call(&mut self, func: &hir::Expr<'_>, args: &[hir::Expr<'_>]) { . let prec = match func.kind { . hir::ExprKind::Field(..) => parser::PREC_FORCE_PAREN, -- line 1213 ---------------------------------------- -- line 1269 ---------------------------------------- . . fn print_expr_addr_of( . &mut self, . kind: hir::BorrowKind, . mutability: hir::Mutability, . expr: &hir::Expr<'_>, . ) { . self.word("&"); 639 ( 0.00%) match kind { . hir::BorrowKind::Ref => self.print_mutability(mutability, false), . hir::BorrowKind::Raw => { . self.word_nbsp("raw"); . self.print_mutability(mutability, true); . } . } . self.print_expr_maybe_paren(expr, parser::PREC_PREFIX) . } . . fn print_literal(&mut self, lit: &hir::Lit) { 828,168 ( 0.02%) self.maybe_print_comment(lit.span.lo()); 552,112 ( 0.01%) self.word(lit.node.to_lit_token().to_string()) . } . . fn print_inline_asm(&mut self, asm: &hir::InlineAsm<'_>) { . enum AsmArg<'a> { . Template(String), . Operand(&'a hir::InlineAsmOperand<'a>), . Options(ast::InlineAsmOptions), . } -- line 1297 ---------------------------------------- -- line 1394 ---------------------------------------- . s.word(opt); . }); . s.pclose(); . } . }); . self.pclose(); . } . 1,255,392 ( 0.03%) pub fn print_expr(&mut self, expr: &hir::Expr<'_>) { 836,928 ( 0.02%) self.maybe_print_comment(expr.span.lo()); 278,976 ( 0.01%) self.print_outer_attributes(self.attrs(expr.hir_id)); 418,464 ( 0.01%) self.ibox(INDENT_UNIT); 836,928 ( 0.02%) self.ann.pre(self, AnnNode::Expr(expr)); 697,440 ( 0.01%) match expr.kind { . hir::ExprKind::Box(ref expr) => { . self.word_space("box"); . self.print_expr_maybe_paren(expr, parser::PREC_PREFIX); . } . hir::ExprKind::Array(ref exprs) => { 1,096 ( 0.00%) self.print_expr_vec(exprs); . } . hir::ExprKind::ConstBlock(ref anon_const) => { . self.print_expr_anon_const(anon_const); . } . hir::ExprKind::Repeat(ref element, ref count) => { . self.print_expr_repeat(&element, count); . } 364 ( 0.00%) hir::ExprKind::Struct(ref qpath, fields, ref wth) => { 91 ( 0.00%) self.print_expr_struct(qpath, fields, wth); . } . hir::ExprKind::Tup(ref exprs) => { 182 ( 0.00%) self.print_expr_tup(exprs); . } . hir::ExprKind::Call(ref func, ref args) => { . self.print_expr_call(&func, args); . } . hir::ExprKind::MethodCall(ref segment, ref args, _) => { . self.print_expr_method_call(segment, args); . } . hir::ExprKind::Binary(op, ref lhs, ref rhs) => { . self.print_expr_binary(op, &lhs, &rhs); . } . hir::ExprKind::Unary(op, ref expr) => { . self.print_expr_unary(op, &expr); . } 2,556 ( 0.00%) hir::ExprKind::AddrOf(k, m, ref expr) => { 639 ( 0.00%) self.print_expr_addr_of(k, m, &expr); . } . hir::ExprKind::Lit(ref lit) => { . self.print_literal(&lit); . } . hir::ExprKind::Cast(ref expr, ref ty) => { . let prec = AssocOp::As.precedence() as i8; . self.print_expr_maybe_paren(&expr, prec); . self.space(); -- line 1448 ---------------------------------------- -- line 1546 ---------------------------------------- . self.print_ident(ident); . } . hir::ExprKind::Index(ref expr, ref index) => { . self.print_expr_maybe_paren(&expr, parser::PREC_POSTFIX); . self.word("["); . self.print_expr(&index); . self.word("]"); . } 455 ( 0.00%) hir::ExprKind::Path(ref qpath) => self.print_qpath(qpath, true), . hir::ExprKind::Break(destination, ref opt_expr) => { . self.word("break"); . if let Some(label) = destination.label { . self.space(); . self.print_ident(label.ident); . } . if let Some(ref expr) = *opt_expr { . self.space(); -- line 1562 ---------------------------------------- -- line 1586 ---------------------------------------- . self.print_expr_maybe_paren(&expr, parser::PREC_JUMP); . } . hir::ExprKind::Err => { . self.popen(); . self.word("/*ERROR*/"); . self.pclose(); . } . } 836,928 ( 0.02%) self.ann.post(self, AnnNode::Expr(expr)); 278,976 ( 0.01%) self.end() 1,115,904 ( 0.02%) } . . pub fn print_local_decl(&mut self, loc: &hir::Local<'_>) { . self.print_pat(&loc.pat); . if let Some(ref ty) = loc.ty { . self.word_space(":"); . self.print_type(&ty); . } . } . . pub fn print_name(&mut self, name: Symbol) { . self.print_ident(Ident::with_dummy_span(name)) . } . 1,820 ( 0.00%) pub fn print_path(&mut self, path: &hir::Path<'_>, colons_before_params: bool) { 1,092 ( 0.00%) self.maybe_print_comment(path.span.lo()); . 182 ( 0.00%) for (i, segment) in path.segments.iter().enumerate() { . if i > 0 { . self.word("::") . } 910 ( 0.00%) if segment.ident.name != kw::PathRoot { 1,092 ( 0.00%) self.print_ident(segment.ident); 1,820 ( 0.00%) self.print_generic_args(segment.args(), segment.infer_args, colons_before_params); . } . } 1,456 ( 0.00%) } . . pub fn print_path_segment(&mut self, segment: &hir::PathSegment<'_>) { . if segment.ident.name != kw::PathRoot { . self.print_ident(segment.ident); . self.print_generic_args(segment.args(), segment.infer_args, false); . } . } . 1,820 ( 0.00%) pub fn print_qpath(&mut self, qpath: &hir::QPath<'_>, colons_before_params: bool) { 1,092 ( 0.00%) match *qpath { 2,002 ( 0.00%) hir::QPath::Resolved(None, ref path) => self.print_path(path, colons_before_params), . hir::QPath::Resolved(Some(ref qself), ref path) => { . self.word("<"); . self.print_type(qself); . self.space(); . self.word_space("as"); . . for (i, segment) in path.segments[..path.segments.len() - 1].iter().enumerate() { . if i > 0 { -- line 1641 ---------------------------------------- -- line 1684 ---------------------------------------- . hir::QPath::LangItem(lang_item, span, _) => { . self.word("#[lang = \""); . self.print_ident(Ident::new(lang_item.name(), span)); . self.word("\"]"); . } . } . } . 2,457 ( 0.00%) fn print_generic_args( . &mut self, . generic_args: &hir::GenericArgs<'_>, . infer_args: bool, . colons_before_params: bool, . ) { 546 ( 0.00%) if generic_args.parenthesized { . self.word("("); . self.commasep(Inconsistent, generic_args.inputs(), |s, ty| s.print_type(&ty)); . self.word(")"); . . self.space_if_not_bol(); . self.word_space("->"); . self.print_type(generic_args.bindings[0].ty()); . } else { 2,457 ( 0.00%) let start = if colons_before_params { "::<" } else { "<" }; . let empty = Cell::new(true); . let start_or_comma = |this: &mut Self| { . if empty.get() { . empty.set(false); . this.word(start) . } else { . this.word_space(",") . } . }; . . let mut nonelided_generic_args: bool = false; 273 ( 0.00%) let elide_lifetimes = generic_args.args.iter().all(|arg| match arg { . GenericArg::Lifetime(lt) => lt.is_elided(), . _ => { . nonelided_generic_args = true; . true . } . }); . . if nonelided_generic_args { -- line 1727 ---------------------------------------- -- line 1741 ---------------------------------------- . . // FIXME(eddyb): this would leak into error messages (e.g., . // "non-exhaustive patterns: `Some::<..>(_)` not covered"). . if infer_args && false { . start_or_comma(self); . self.word(".."); . } . 273 ( 0.00%) for binding in generic_args.bindings.iter() { . start_or_comma(self); . self.print_ident(binding.ident); . self.print_generic_args(binding.gen_args, false, false); . self.space(); . match generic_args.bindings[0].kind { . hir::TypeBindingKind::Equality { ref term } => { . self.word_space("="); . match term { -- line 1757 ---------------------------------------- -- line 1760 ---------------------------------------- . } . } . hir::TypeBindingKind::Constraint { bounds } => { . self.print_bounds(":", bounds); . } . } . } . 819 ( 0.00%) if !empty.get() { . self.word(">") . } . } 2,184 ( 0.00%) } . . pub fn print_pat(&mut self, pat: &hir::Pat<'_>) { . self.maybe_print_comment(pat.span.lo()); . self.ann.pre(self, AnnNode::Pat(pat)); . // Pat isn't normalized, but the beauty of it . // is that it doesn't matter . match pat.kind { . PatKind::Wild => self.word("_"), -- line 1780 ---------------------------------------- -- line 2232 ---------------------------------------- . self.word_space("="); . self.print_type(rhs_ty); . } . } . } . } . . pub fn print_mutability(&mut self, mutbl: hir::Mutability, print_const: bool) { 639 ( 0.00%) match mutbl { . hir::Mutability::Mut => self.word_nbsp("mut"), . hir::Mutability::Not => { . if print_const { . self.word_nbsp("const") . } . } . } . } -- line 2248 ---------------------------------------- 287,279 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_span/src/symbol.rs -------------------------------------------------------------------------------- Ir -- line 15 ---------------------------------------- . use std::str; . . use crate::{with_session_globals, Edition, Span, DUMMY_SP}; . . #[cfg(test)] . mod tests; . . // The proc macro code for this is in `compiler/rustc_macros/src/symbols.rs`. 8 ( 0.00%) symbols! { . // After modifying this list adjust `is_special`, `is_used_keyword`/`is_unused_keyword`, . // this should be rarely necessary though if the keywords are kept in alphabetic order. . Keywords { . // Special reserved identifiers used internally for elided lifetimes, . // unnamed method parameters, crate root module, error recovery etc. . Empty: "", . PathRoot: "{{root}}", . DollarCrate: "$crate", -- line 31 ---------------------------------------- -- line 1498 ---------------------------------------- . write_str, . writeln_macro, . x87_reg, . xer, . xmm_reg, . ymm_reg, . zmm_reg, . } 10 ( 0.00%) } . 90,366 ( 0.00%) #[derive(Copy, Clone, Eq, HashStable_Generic, Encodable, Decodable)] . pub struct Ident { . pub name: Symbol, . pub span: Span, . } . . impl Ident { . #[inline] . /// Constructs a new identifier from a symbol and a span. . pub const fn new(name: Symbol, span: Span) -> Ident { . Ident { name, span } 261,497 ( 0.01%) } . . /// Constructs a new identifier with a dummy span. . #[inline] . pub const fn with_dummy_span(name: Symbol) -> Ident { . Ident::new(name, DUMMY_SP) . } . . #[inline] . pub fn empty() -> Ident { . Ident::with_dummy_span(kw::Empty) . } . . /// Maps a string to an identifier with a dummy span. 3 ( 0.00%) pub fn from_str(string: &str) -> Ident { 3 ( 0.00%) Ident::with_dummy_span(Symbol::intern(string)) 12 ( 0.00%) } . . /// Maps a string and a span to an identifier. 496 ( 0.00%) pub fn from_str_and_span(string: &str, span: Span) -> Ident { 248 ( 0.00%) Ident::new(Symbol::intern(string), span) 496 ( 0.00%) } . . /// Replaces `lo` and `hi` with those from `span`, but keep hygiene context. 38,696 ( 0.00%) pub fn with_span_pos(self, span: Span) -> Ident { . Ident::new(self.name, span.with_ctxt(self.span.ctxt())) 24,185 ( 0.00%) } . 1,464 ( 0.00%) pub fn without_first_quote(self) -> Ident { 1,464 ( 0.00%) Ident::new(Symbol::intern(self.as_str().trim_start_matches('\'')), self.span) 915 ( 0.00%) } . . /// "Normalize" ident for use in comparisons using "item hygiene". . /// Identifiers with same string value become same if they came from the same macro 2.0 macro . /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from . /// different macro 2.0 macros. . /// Technically, this operation strips all non-opaque marks from ident's syntactic context. 145,125 ( 0.00%) pub fn normalize_to_macros_2_0(self) -> Ident { . Ident::new(self.name, self.span.normalize_to_macros_2_0()) 112,875 ( 0.00%) } . . /// "Normalize" ident for use in comparisons using "local variable hygiene". . /// Identifiers with same string value become same if they came from the same non-transparent . /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different . /// non-transparent macros. . /// Technically, this operation strips all transparent marks from ident's syntactic context. 15,939 ( 0.00%) pub fn normalize_to_macro_rules(self) -> Ident { . Ident::new(self.name, self.span.normalize_to_macro_rules()) 12,397 ( 0.00%) } . . /// Access the underlying string. This is a slowish operation because it . /// requires locking the symbol interner. . /// . /// Note that the lifetime of the return value is a lie. See . /// `Symbol::as_str()` for details. . pub fn as_str(&self) -> &str { 454 ( 0.00%) self.name.as_str() . } . } . . impl PartialEq for Ident { 45,372 ( 0.00%) fn eq(&self, rhs: &Self) -> bool { 113,522 ( 0.00%) self.name == rhs.name && self.span.ctxt() == rhs.span.ctxt() 60,496 ( 0.00%) } . } . . impl Hash for Ident { . fn hash(&self, state: &mut H) { 50 ( 0.00%) self.name.hash(state); 23,964 ( 0.00%) self.span.ctxt().hash(state); . } . } . . impl fmt::Debug for Ident { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Display::fmt(self, f)?; . fmt::Debug::fmt(&self.span.ctxt(), f) . } . } . . /// This implementation is supposed to be used in error messages, so it's expected to be identical . /// to printing the original identifier token written in source code (`token_to_string`), . /// except that AST identifiers don't keep the rawness flag, so we have to guess it. . impl fmt::Display for Ident { 720 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 901 ( 0.00%) fmt::Display::fmt(&IdentPrinter::new(self.name, self.is_raw_guess(), None), f) 720 ( 0.00%) } . } . . /// This is the most general way to print identifiers. . /// AST pretty-printer is used as a fallback for turning AST structures into token streams for . /// proc macros. Additionally, proc macros may stringify their input and expect it survive the . /// stringification (especially true for proc macro derives written between Rust 1.15 and 1.30). . /// So we need to somehow pretty-print `$crate` in a way preserving at least some of its . /// hygiene data, most importantly name of the crate it refers to. -- line 1613 ---------------------------------------- -- line 1622 ---------------------------------------- . is_raw: bool, . /// Span used for retrieving the crate name to which `$crate` refers to, . /// if this field is `None` then the `$crate` conversion doesn't happen. . convert_dollar_crate: Option, . } . . impl IdentPrinter { . /// The most general `IdentPrinter` constructor. Do not use this. 154 ( 0.00%) pub fn new(symbol: Symbol, is_raw: bool, convert_dollar_crate: Option) -> IdentPrinter { 5,438 ( 0.00%) IdentPrinter { symbol, is_raw, convert_dollar_crate } 154 ( 0.00%) } . . /// This implementation is supposed to be used when printing identifiers . /// as a part of pretty-printing for larger AST pieces. . /// Do not use this either. 1,958 ( 0.00%) pub fn for_ast_ident(ident: Ident, is_raw: bool) -> IdentPrinter { 1,958 ( 0.00%) IdentPrinter::new(ident.name, is_raw, Some(ident.span)) 979 ( 0.00%) } . } . . impl fmt::Display for IdentPrinter { 6,570 ( 0.00%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 2,628 ( 0.00%) if self.is_raw { . f.write_str("r#")?; 1,314 ( 0.00%) } else if self.symbol == kw::DollarCrate { . if let Some(span) = self.convert_dollar_crate { . let converted = span.ctxt().dollar_crate_name(); . if !converted.is_path_segment_keyword() { . f.write_str("::")?; . } . return fmt::Display::fmt(&converted, f); . } . } -- line 1654 ---------------------------------------- -- line 1656 ---------------------------------------- . } . } . . /// An newtype around `Ident` that calls [Ident::normalize_to_macro_rules] on . /// construction. . // FIXME(matthewj, petrochenkov) Use this more often, add a similar . // `ModernIdent` struct and use that as well. . #[derive(Copy, Clone, Eq, PartialEq, Hash)] 4,044 ( 0.00%) pub struct MacroRulesNormalizedIdent(Ident); . . impl MacroRulesNormalizedIdent { . pub fn new(ident: Ident) -> Self { 916 ( 0.00%) Self(ident.normalize_to_macro_rules()) . } . } . . impl fmt::Debug for MacroRulesNormalizedIdent { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Debug::fmt(&self.0, f) . } . } -- line 1676 ---------------------------------------- -- line 1686 ---------------------------------------- . /// Internally, a `Symbol` is implemented as an index, and all operations . /// (including hashing, equality, and ordering) operate on that index. The use . /// of `rustc_index::newtype_index!` means that `Option` only takes up 4 bytes, . /// because `rustc_index::newtype_index!` reserves the last 256 values for tagging purposes. . /// . /// Note that `Symbol` cannot directly be a `rustc_index::newtype_index!` because it . /// implements `fmt::Debug`, `Encodable`, and `Decodable` in special ways. . #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] 467,025 ( 0.01%) pub struct Symbol(SymbolIndex); . . rustc_index::newtype_index! { . struct SymbolIndex { .. } . } . . impl Symbol { . const fn new(n: u32) -> Self { . Symbol(SymbolIndex::from_u32(n)) 247,686 ( 0.01%) } . . /// Maps a string to its interned representation. 1,744,155 ( 0.04%) pub fn intern(string: &str) -> Self { . with_session_globals(|session_globals| session_globals.symbol_interner.intern(string)) 1,744,155 ( 0.04%) } . . /// Access the underlying string. This is a slowish operation because it . /// requires locking the symbol interner. . /// . /// Note that the lifetime of the return value is a lie. It's not the same . /// as `&self`, but actually tied to the lifetime of the underlying . /// interner. Interners are long-lived, and there are very few of them, and . /// this function is typically used for short-lived things, so in practice . /// it works out ok. 1,747,668 ( 0.04%) pub fn as_str(&self) -> &str { 582,556 ( 0.01%) with_session_globals(|session_globals| unsafe { . std::mem::transmute::<&str, &str>(session_globals.symbol_interner.get(*self)) . }) 2,330,224 ( 0.05%) } . . pub fn as_u32(self) -> u32 { . self.0.as_u32() . } . . pub fn is_empty(self) -> bool { . self == kw::Empty . } . . /// This method is supposed to be used in error messages, so it's expected to be . /// identical to printing the original identifier token written in source code . /// (`token_to_string`, `Ident::to_string`), except that symbols don't keep the rawness flag . /// or edition, so we have to guess the rawness using the global edition. 6 ( 0.00%) pub fn to_ident_string(self) -> String { . Ident::with_dummy_span(self).to_string() 6 ( 0.00%) } . } . . impl fmt::Debug for Symbol { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Debug::fmt(self.as_str(), f) . } . } . . impl fmt::Display for Symbol { 276,330 ( 0.01%) fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 840,816 ( 0.02%) fmt::Display::fmt(self.as_str(), f) . } . } . . impl Encodable for Symbol { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { 37,855 ( 0.00%) s.emit_str(self.as_str()) . } . } . . impl Decodable for Symbol { . #[inline] 22,292 ( 0.00%) fn decode(d: &mut D) -> Symbol { 76,274 ( 0.00%) Symbol::intern(&d.read_str()) . } . } . . impl HashStable for Symbol { . #[inline] 1,902 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { 30,466 ( 0.00%) self.as_str().hash_stable(hcx, hasher); 1,764 ( 0.00%) } . } . . impl ToStableHashKey for Symbol { . type KeyType = String; . #[inline] . fn to_stable_hash_key(&self, _: &CTX) -> String { . self.as_str().to_string() . } -- line 1778 ---------------------------------------- -- line 1785 ---------------------------------------- . // . // The `FxHashMap`+`Vec` pair could be replaced by `FxIndexSet`, but #75278 . // found that to regress performance up to 2% in some cases. This might be . // revisited after further improvements to `indexmap`. . // . // This type is private to prevent accidentally constructing more than one . // `Interner` on the same thread, which makes it easy to mixup `Symbol`s . // between `Interner`s. 2 ( 0.00%) #[derive(Default)] . struct InternerInner { . arena: DroplessArena, . names: FxHashMap<&'static str, Symbol>, . strings: Vec<&'static str>, . } . . impl Interner { . fn prefill(init: &[&'static str]) -> Self { 30 ( 0.00%) Interner(Lock::new(InternerInner { . strings: init.into(), . names: init.iter().copied().zip((0..).map(Symbol::new)).collect(), . ..Default::default() . })) . } . . #[inline] . fn intern(&self, string: &str) -> Symbol { . let mut inner = self.0.lock(); 363,448 ( 0.01%) if let Some(&name) = inner.names.get(string) { . return name; . } . 12,071 ( 0.00%) let name = Symbol::new(inner.strings.len() as u32); . . // SAFETY: we convert from `&str` to `&[u8]`, clone it into the arena, . // and immediately convert the clone back to `&[u8], all because there . // is no `inner.arena.alloc_str()` method. This is clearly safe. . let string: &str = . unsafe { str::from_utf8_unchecked(inner.arena.alloc_slice(string.as_bytes())) }; . . // SAFETY: we can extend the arena allocation to `'static` because we -- line 1824 ---------------------------------------- -- line 1831 ---------------------------------------- . // #91445 for details. . inner.names.insert(string, name); . name . } . . // Get the symbol as a string. `Symbol::as_str()` should be used in . // preference to this function. . fn get(&self, symbol: Symbol) -> &str { 1,747,668 ( 0.04%) self.0.lock().strings[symbol.0.as_usize()] . } . } . . // This module has a very short name because it's used a lot. . /// This module contains all the defined keyword `Symbol`s. . /// . /// Given that `kw` is imported, use them like `kw::keyword_name`. . /// For example `kw::Loop` or `kw::Break`. -- line 1847 ---------------------------------------- -- line 1863 ---------------------------------------- . . // Used from a macro in `librustc_feature/accepted.rs` . pub use super::kw::MacroRules as macro_rules; . . /// Get the symbol for an integer. . /// . /// The first few non-negative integers each have a static symbol and therefore . /// are fast. 552,427 ( 0.01%) pub fn integer + Copy + ToString>(n: N) -> Symbol { 552,325 ( 0.01%) if let Result::Ok(idx) = n.try_into() { 68 ( 0.00%) if idx < 10 { 495,372 ( 0.01%) return Symbol::new(super::SYMBOL_DIGITS_BASE + idx as u32); . } . } 14,277 ( 0.00%) Symbol::intern(&n.to_string()) 57,108 ( 0.00%) } . } . . impl Symbol { . fn is_special(self) -> bool { . self <= kw::Underscore . } . . fn is_used_keyword_always(self) -> bool { 462 ( 0.00%) self >= kw::As && self <= kw::While . } . . fn is_used_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool { 34,809 ( 0.00%) (self >= kw::Async && self <= kw::Dyn) && edition() >= Edition::Edition2018 . } . . fn is_unused_keyword_always(self) -> bool { 462 ( 0.00%) self >= kw::Abstract && self <= kw::Yield . } . . fn is_unused_keyword_conditional(self, edition: impl FnOnce() -> Edition) -> bool { 154 ( 0.00%) self == kw::Try && edition() >= Edition::Edition2018 . } . . pub fn is_reserved(self, edition: impl Copy + FnOnce() -> Edition) -> bool { 59,657 ( 0.00%) self.is_special() . || self.is_used_keyword_always() . || self.is_unused_keyword_always() . || self.is_used_keyword_conditional(edition) . || self.is_unused_keyword_conditional(edition) . } . . /// A keyword or reserved identifier that can be used as a path segment. . pub fn is_path_segment_keyword(self) -> bool { 147,735 ( 0.00%) self == kw::Super . || self == kw::SelfLower . || self == kw::SelfUpper . || self == kw::Crate . || self == kw::PathRoot . || self == kw::DollarCrate . } . . /// Returns `true` if the symbol is `true` or `false`. . pub fn is_bool_lit(self) -> bool { 1,622 ( 0.00%) self == kw::True || self == kw::False 1,622 ( 0.00%) } . . /// Returns `true` if this symbol can be a raw identifier. . pub fn can_be_raw(self) -> bool { 2,576 ( 0.00%) self != kw::Empty && self != kw::Underscore && !self.is_path_segment_keyword() 1 ( 0.00%) } . } . . impl Ident { . // Returns `true` for reserved identifiers used internally for elided lifetimes, . // unnamed method parameters, crate root module, error recovery etc. . pub fn is_special(self) -> bool { . self.name.is_special() 154 ( 0.00%) } . . /// Returns `true` if the token is a keyword used in the language. 154 ( 0.00%) pub fn is_used_keyword(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. 154 ( 0.00%) self.name.is_used_keyword_always() . || self.name.is_used_keyword_conditional(|| self.span.edition()) 308 ( 0.00%) } . . /// Returns `true` if the token is a keyword reserved for possible future use. 154 ( 0.00%) pub fn is_unused_keyword(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. 154 ( 0.00%) self.name.is_unused_keyword_always() . || self.name.is_unused_keyword_conditional(|| self.span.edition()) 308 ( 0.00%) } . . /// Returns `true` if the token is either a special identifier or a keyword. 10,652 ( 0.00%) pub fn is_reserved(self) -> bool { . // Note: `span.edition()` is relatively expensive, don't call it unless necessary. . self.name.is_reserved(|| self.span.edition()) 21,304 ( 0.00%) } . . /// A keyword or reserved identifier that can be used as a path segment. . pub fn is_path_segment_keyword(self) -> bool { . self.name.is_path_segment_keyword() 21,105 ( 0.00%) } . . /// We see this identifier in a normal identifier position, like variable name or a type. . /// How was it written originally? Did it use the raw form? Let's try to guess. 1,104 ( 0.00%) pub fn is_raw_guess(self) -> bool { . self.name.can_be_raw() && self.is_reserved() 2,208 ( 0.00%) } . } 650,201 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_middle/src/ty/consts/kind.rs -------------------------------------------------------------------------------- Ir -- line 7 ---------------------------------------- . use crate::ty::{self, TyCtxt, TypeFoldable}; . use rustc_errors::ErrorReported; . use rustc_hir::def_id::DefId; . use rustc_macros::HashStable; . use rustc_target::abi::Size; . . use super::ScalarInt; . /// An unevaluated, potentially generic, constant. 1,375 ( 0.00%) #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Lift)] . #[derive(Hash, HashStable)] . pub struct Unevaluated<'tcx, P = Option> { . pub def: ty::WithOptConstParam, 2,934 ( 0.00%) pub substs: SubstsRef<'tcx>, 2,475 ( 0.00%) pub promoted: P, . } . . impl<'tcx> Unevaluated<'tcx> { . #[inline] . pub fn shrink(self) -> Unevaluated<'tcx, ()> { . debug_assert_eq!(self.promoted, None); . Unevaluated { def: self.def, substs: self.substs, promoted: () } . } -- line 28 ---------------------------------------- -- line 38 ---------------------------------------- . impl<'tcx, P: Default> Unevaluated<'tcx, P> { . #[inline] . pub fn new(def: ty::WithOptConstParam, substs: SubstsRef<'tcx>) -> Unevaluated<'tcx, P> { . Unevaluated { def, substs, promoted: Default::default() } . } . } . . /// Represents a constant in Rust. 7,155,567 ( 0.15%) #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable)] 117,080 ( 0.00%) #[derive(Hash, HashStable)] . pub enum ConstKind<'tcx> { . /// A const generic parameter. 86 ( 0.00%) Param(ty::ParamConst), . . /// Infer the value of the const. . Infer(InferConst<'tcx>), . . /// Bound const variable, used only when preparing a trait query. . Bound(ty::DebruijnIndex, ty::BoundVar), . . /// A placeholder const - universally quantified higher-ranked const. . Placeholder(ty::PlaceholderConst<'tcx>), . . /// Used in the HIR by using `Unevaluated` everywhere and later normalizing to one of the other . /// variants when the code is monomorphic enough for that. . Unevaluated(Unevaluated<'tcx>), . . /// Used to hold computed value. 40,926 ( 0.00%) Value(ConstValue<'tcx>), . . /// A placeholder for a const which could not be computed; this is . /// propagated to avoid useless error messages. . Error(ty::DelaySpanBugEmitted), . } . . #[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))] . static_assert_size!(ConstKind<'_>, 40); . . impl<'tcx> ConstKind<'tcx> { . #[inline] . pub fn try_to_value(self) -> Option> { 4,983,008 ( 0.10%) if let ConstKind::Value(val) = self { Some(val) } else { None } . } . . #[inline] . pub fn try_to_scalar(self) -> Option> { . self.try_to_value()?.try_to_scalar() . } . . #[inline] . pub fn try_to_scalar_int(self) -> Option { . Some(self.try_to_value()?.try_to_scalar()?.assert_int()) . } . . #[inline] . pub fn try_to_bits(self, size: Size) -> Option { 496 ( 0.00%) self.try_to_scalar_int()?.to_bits(size).ok() . } . . #[inline] . pub fn try_to_bool(self) -> Option { . self.try_to_scalar_int()?.try_into().ok() . } . . #[inline] . pub fn try_to_machine_usize(self, tcx: TyCtxt<'tcx>) -> Option { 8,592 ( 0.00%) self.try_to_value()?.try_to_machine_usize(tcx) . } . } . . /// An inference variable for a const, for use in const generics. 773 ( 0.00%) #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, TyEncodable, TyDecodable, Hash)] . #[derive(HashStable)] . pub enum InferConst<'tcx> { . /// Infer the value of the const. . Var(ty::ConstVid<'tcx>), . /// A fresh const variable. See `infer::freshen` for more details. . Fresh(u32), . } . . impl<'tcx> ConstKind<'tcx> { . #[inline] . /// Tries to evaluate the constant if it is `Unevaluated`. If that doesn't succeed, return the . /// unevaluated constant. 27 ( 0.00%) pub fn eval(self, tcx: TyCtxt<'tcx>, param_env: ParamEnv<'tcx>) -> Self { . self.try_eval(tcx, param_env).and_then(Result::ok).map_or(self, ConstKind::Value) 24 ( 0.00%) } . . #[inline] . /// Tries to evaluate the constant if it is `Unevaluated`. If that isn't possible or necessary . /// return `None`. 14,416 ( 0.00%) pub(super) fn try_eval( . self, . tcx: TyCtxt<'tcx>, . param_env: ParamEnv<'tcx>, . ) -> Option, ErrorReported>> { 6,902 ( 0.00%) if let ConstKind::Unevaluated(unevaluated) = self { . use crate::mir::interpret::ErrorHandled; . . // HACK(eddyb) this erases lifetimes even though `const_eval_resolve` . // also does later, but we want to do it before checking for . // inference variables. . // Note that we erase regions *before* calling `with_reveal_all_normalized`, . // so that we don't try to invoke this query with . // any region variables. 736 ( 0.00%) let param_env_and = tcx . .erase_regions(param_env) . .with_reveal_all_normalized(tcx) . .and(tcx.erase_regions(unevaluated)); . . // HACK(eddyb) when the query key would contain inference variables, . // attempt using identity substs and `ParamEnv` instead, that will succeed . // when the expression doesn't depend on any parameters. . // FIXME(eddyb, skinny121) pass `InferCtxt` into here when it's available, so that . // we can call `infcx.const_eval_resolve` which handles inference variables. 184 ( 0.00%) let param_env_and = if param_env_and.needs_infer() { . tcx.param_env(unevaluated.def.did).and(ty::Unevaluated { . def: unevaluated.def, . substs: InternalSubsts::identity_for_item(tcx, unevaluated.def.did), . promoted: unevaluated.promoted, . }) . } else { . param_env_and . }; . . // FIXME(eddyb) maybe the `const_eval_*` methods should take . // `ty::ParamEnvAnd` instead of having them separate. . let (param_env, unevaluated) = param_env_and.into_parts(); . // try to resolve e.g. associated constants to their definition on an impl, and then . // evaluate the const. 3,496 ( 0.00%) match tcx.const_eval_resolve(param_env, unevaluated, None) { . // NOTE(eddyb) `val` contains no lifetimes/types/consts, . // and we use the original type, so nothing from `substs` . // (which may be identity substs, see above), . // can leak through `val` into the const we return. 920 ( 0.00%) Ok(val) => Some(Ok(val)), . Err(ErrorHandled::TooGeneric | ErrorHandled::Linted) => None, . Err(ErrorHandled::Reported(e)) => Some(Err(e)), . } . } else { . None . } 14,416 ( 0.00%) } . } 2,671,873 ( 0.05%) -------------------------------------------------------------------------------- -- 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 { 14,696,652 ( 0.30%) Vec { buf: RawVec::NEW, len: 0 } 126 ( 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 { 613,778 ( 0.01%) Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 } . } . . /// Creates a `Vec` directly from the raw components of another vector. . /// . /// # Safety . /// . /// This is highly unsafe, due to the number of invariants that aren't . /// checked: -- line 617 ---------------------------------------- -- line 677 ---------------------------------------- . /// // Put everything back together into a Vec . /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone()); . /// assert_eq!(rebuilt, [4, 5, 6]); . /// } . /// ``` . #[inline] . #[unstable(feature = "allocator_api", issue = "32838")] . pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self { 43,984 ( 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 { 1,859,651 ( 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) { 864,420 ( 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) { 8,090 ( 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. 17,073 ( 0.00%) if self.capacity() > self.len { 7,425 ( 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(); 5,494 ( 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")] 1,555,712 ( 0.03%) 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. 974,278 ( 0.02%) 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); 403,640 ( 0.01%) self.len = len; 4,091 ( 0.00%) ptr::drop_in_place(s); . } 1,866,854 ( 0.04%) } . . /// 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. 5,645,420 ( 0.12%) 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. 6,620,368 ( 0.14%) 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()); . 2,083,086 ( 0.04%) self.len = new_len; 3,552 ( 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 1305 ---------------------------------------- . assert_failed(index, len); . } . unsafe { . // We replace self[index] with the last element. Note that if the . // bounds check above succeeds there must be a last element (which . // can be self[index] itself). . let value = ptr::read(self.as_ptr().add(index)); . let base_ptr = self.as_mut_ptr(); 27 ( 0.00%) ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1); . self.set_len(len - 1); . value . } . } . . /// Inserts an element at position `index` within the vector, shifting all . /// elements after it to the right. . /// -- line 1321 ---------------------------------------- -- 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")] 4,914 ( 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); . } . 811 ( 0.00%) let len = self.len(); 2,894 ( 0.00%) if index > len { . assert_failed(index, len); . } . . // space for the new element 4,284 ( 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.) 6,099 ( 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); . } 4,284 ( 0.00%) self.set_len(len + 1); . } 4,212 ( 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); . } . 164 ( 0.00%) let len = self.len(); 618 ( 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. 608 ( 0.00%) ret = ptr::read(ptr); . . // Shift everything down to fill in that spot. 418 ( 0.00%) ptr::copy(ptr.offset(1), ptr, len - index - 1); . } 182 ( 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")] 122,310 ( 0.00%) pub fn retain(&mut self, mut f: F) . where . F: FnMut(&T) -> bool, . { 10,345 ( 0.00%) self.retain_mut(|elem| f(elem)); 118,136 ( 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, . { 18,733 ( 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) { 17,652 ( 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), 17,190 ( 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, . { 267,342 ( 0.01%) while g.processed_len != original_len { . // SAFETY: Unchecked element must be valid. . let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) }; 77,403 ( 0.00%) if !f(cur) { . // Advance early to avoid double drop if `drop_in_place` panicked. 28,190 ( 0.00%) g.processed_len += 1; 22,136 ( 0.00%) g.deleted_cnt += 1; . // SAFETY: We never touch this element again after dropped. 14,191 ( 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 { 2,487 ( 0.00%) let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt); . ptr::copy_nonoverlapping(cur, hole_slot, 1); . } . } 1,658 ( 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")] 4,963 ( 0.00%) pub fn dedup_by(&mut self, mut same_bucket: F) . where . F: FnMut(&mut T, &mut T) -> bool, . { 709 ( 0.00%) let len = self.len(); 2,874 ( 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 { 1,312 ( 0.00%) while gap.read < len { . let read_ptr = ptr.add(gap.read); . let prev_ptr = ptr.add(gap.write.wrapping_sub(1)); . 706 ( 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 */ 604 ( 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); . } 5,672 ( 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")] 755 ( 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. 11,355,954 ( 0.23%) if self.len == self.buf.capacity() { 362,692 ( 0.01%) self.buf.reserve_for_push(self.len); . } . unsafe { 160,656 ( 0.00%) let end = self.as_mut_ptr().add(self.len); . ptr::write(end, value); 17,331,938 ( 0.36%) self.len += 1; . } 604 ( 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 { 2,174,914 ( 0.04%) if self.len == 0 { 36 ( 0.00%) None . } else { . unsafe { 1,583,591 ( 0.03%) self.len -= 1; 106,536 ( 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")] 420 ( 0.00%) pub fn append(&mut self, other: &mut Self) { . unsafe { . self.append_elements(other.as_slice() as _); . other.set_len(0); . } 360 ( 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); 316,783 ( 0.01%) let len = self.len(); . unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) }; 2,141,791 ( 0.04%) 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. . // 24,186 ( 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). 552 ( 0.00%) let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start); 1,545 ( 0.00%) Drain { . tail_start: end, 370 ( 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) { 2,797,746 ( 0.06%) 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 { 1,432,234 ( 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); . } . 1,360 ( 0.00%) if at > self.len() { . assert_failed(at, self.len()); . } . 1,118 ( 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")] 31,279 ( 0.00%) pub fn resize_with(&mut self, new_len: usize, f: F) . where . F: FnMut() -> T, . { 4,289 ( 0.00%) let len = self.len(); 8,578 ( 0.00%) if new_len > len { 24,355 ( 0.00%) self.extend_with(new_len - len, ExtendFunc(f)); . } else { . self.truncate(new_len); . } 26,990 ( 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, 72 ( 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")] 1,860 ( 0.00%) pub fn resize(&mut self, new_len: usize, value: T) { 186 ( 0.00%) let len = self.len(); . 558 ( 0.00%) if new_len > len { 3,957 ( 0.00%) self.extend_with(new_len - len, ExtendElement(value)) . } else { . self.truncate(new_len); . } 930 ( 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 { 2,010 ( 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. 115,590 ( 0.00%) fn extend_with>(&mut self, n: usize, mut value: E) { . self.reserve(n); . . unsafe { 5,884 ( 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); . } . 162,135 ( 0.00%) if n > 0 { . // We can write the last element directly without cloning needlessly . ptr::write(ptr, value.last()); . local_len.increment_len(1); . } . . // len set by scope guard . } 91,765 ( 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) { 710 ( 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")] 29,640 ( 0.00%) pub fn from_elem(elem: T, n: usize) -> Vec { 155,173 ( 0.00%) ::from_elem(elem, n, Global) 34,745 ( 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] { 9,052,796 ( 0.19%) unsafe { slice::from_raw_parts(self.as_ptr(), self.len) } 97 ( 0.00%) } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl ops::DerefMut for Vec { . fn deref_mut(&mut self) -> &mut [T] { 1,417,158 ( 0.03%) unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) } . } . } . . #[cfg(not(no_global_oom_handling))] . trait SpecCloneFrom { . fn clone_from(this: &mut Self, other: &Self); . } . -- line 2447 ---------------------------------------- -- line 2468 ---------------------------------------- . this.extend_from_slice(other); . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Clone for Vec { . #[cfg(not(test))] 135,887 ( 0.00%) fn clone(&self) -> Self { . let alloc = self.allocator().clone(); 2 ( 0.00%) <[T]>::to_vec_in(&**self, alloc) 170,144 ( 0.00%) } . . // 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 { 135,852 ( 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 { 128 ( 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 { 2,148,901 ( 0.04%) >::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 { 1,703,924 ( 0.03%) 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(); 704,991 ( 0.01%) IntoIter { . buf: NonNull::new_unchecked(begin), . phantom: PhantomData, . cap, . alloc, . ptr: begin, . end, . } . } -- line 2589 ---------------------------------------- -- line 2591 ---------------------------------------- . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T, A: Allocator> IntoIterator for &'a Vec { . type Item = &'a T; . type IntoIter = slice::Iter<'a, T>; . . fn into_iter(self) -> slice::Iter<'a, T> { 259 ( 0.00%) self.iter() . } . } . . #[stable(feature = "rust1", since = "1.0.0")] . impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec { . type Item = &'a mut T; . type IntoIter = slice::IterMut<'a, T>; . . fn into_iter(self) -> slice::IterMut<'a, T> { 1,078 ( 0.00%) self.iter_mut() . } . } . . #[cfg(not(no_global_oom_handling))] . #[stable(feature = "rust1", since = "1.0.0")] . impl Extend for Vec { . #[inline] 1,016 ( 0.00%) fn extend>(&mut self, iter: I) { 576,064 ( 0.01%) >::spec_extend(self, iter.into_iter()) 1,016 ( 0.00%) } . . #[inline] . fn extend_one(&mut self, item: T) { 16 ( 0.00%) self.push(item); . } . . #[inline] . fn extend_reserve(&mut self, additional: usize) { . self.reserve(additional); . } . } . -- line 2631 ---------------------------------------- -- line 2636 ---------------------------------------- . fn extend_desugared>(&mut self, mut iterator: I) { . // This is the case for a general iterator. . // . // This function should be the moral equivalent of: . // . // for item in iterator { . // self.push(item); . // } 89,163 ( 0.00%) while let Some(element) = iterator.next() { 26,474 ( 0.00%) let len = self.len(); 209,471 ( 0.00%) if len == self.capacity() { 739 ( 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 167,304 ( 0.00%) self.set_len(len + 1); . } . } 1,493 ( 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, . { 3,458 ( 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, . { 1,482 ( 0.00%) let old_len = self.len(); . . // Guard against us getting leaked (leak amplification) . unsafe { . self.set_len(0); . } . 4,000 ( 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 { 7,004,250 ( 0.14%) 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 2,057,707 ( 0.04%) ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len)) . } . // RawVec handles deallocation 8,227,686 ( 0.17%) } . } . . #[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 ---------------------------------------- 4,090,583 ( 0.08%) -------------------------------------------------------------------------------- -- 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 { 4,100,148 ( 0.08%) Token { kind, len } . } . } . . /// Enum representing common lexeme types. . // perf note: Changing all `usize` to `u32` doesn't change performance. See #77629 91,390 ( 0.00%) #[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. 133 ( 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 152 ( 0.00%) } . . /// Parses the first token from the provided input string. 1,366,716 ( 0.03%) pub fn first_token(input: &str) -> Token { . debug_assert!(!input.is_empty()); 455,572 ( 0.01%) Cursor::new(input).advance_token() 1,822,288 ( 0.04%) } . . /// Creates an iterator that produces tokens from the input string. . pub fn tokenize(input: &str) -> impl Iterator + '_ { . let mut cursor = Cursor::new(input); . std::iter::from_fn(move || { . if cursor.is_eof() { . None . } else { -- line 235 ---------------------------------------- -- line 243 ---------------------------------------- . /// See [Rust language reference](https://doc.rust-lang.org/reference/whitespace.html) . /// for definitions of these classes. . pub fn is_whitespace(c: char) -> bool { . // This is Pattern_White_Space. . // . // Note that this set is stable (ie, it doesn't change with different . // Unicode versions), so it's ok to just hard-code the values. . 724,278 ( 0.01%) 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 269 ---------------------------------------- . | '\u{2028}' // LINE SEPARATOR . | '\u{2029}' // PARAGRAPH SEPARATOR . ) . } . . /// 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. 115 ( 0.00%) pub fn is_id_start(c: char) -> bool { . // This is XID_Start OR '_' (which formally is not a XID_Start). 278,136 ( 0.01%) c == '_' || unicode_xid::UnicodeXID::is_xid_start(c) 115 ( 0.00%) } . . /// 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) 128 ( 0.00%) } . . /// The passed string is lexically an identifier. 10 ( 0.00%) pub fn is_ident(string: &str) -> bool { . let mut chars = string.chars(); . if let Some(start) = chars.next() { . is_id_start(start) && chars.all(is_id_continue) . } else { . false . } 14 ( 0.00%) } . . impl Cursor<'_> { . /// Parses a token from the input string. 3,644,576 ( 0.07%) fn advance_token(&mut self) -> Token { . let first_char = self.bump().unwrap(); 1,397,338 ( 0.03%) let token_kind = match first_char { . // Slash, comment or block comment. 6,722 ( 0.00%) '/' => match self.first() { . '/' => self.line_comment(), . '*' => self.block_comment(), . _ => Slash, . }, . . // Whitespace sequence. . c if is_whitespace(c) => self.whitespace(), . . // Raw identifier, raw string literal or identifier. 944 ( 0.00%) 'r' => match (self.first(), self.second()) { . ('#', c1) if is_id_start(c1) => self.raw_ident(), . ('#', _) | ('"', _) => { 22 ( 0.00%) let (n_hashes, err) = self.raw_double_quoted_string(1); . let suffix_start = self.len_consumed(); 2 ( 0.00%) if err.is_none() { . self.eat_literal_suffix(); . } . let kind = RawStr { n_hashes, err }; 14 ( 0.00%) Literal { kind, suffix_start } . } . _ => self.ident_or_unknown_prefix(), . }, . . // Byte literal, byte string literal, raw byte string literal or identifier. 342 ( 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. 883,752 ( 0.02%) c @ '0'..='9' => { . let literal_kind = self.number(c); . let suffix_start = self.len_consumed(); . self.eat_literal_suffix(); 691,150 ( 0.01%) TokenKind::Literal { kind: literal_kind, suffix_start } . } . . // One-symbol tokens. 1,624 ( 0.00%) ';' => Semi, 280,186 ( 0.01%) ',' => Comma, 2,290 ( 0.00%) '.' => Dot, 3,524 ( 0.00%) '(' => OpenParen, 3,524 ( 0.00%) ')' => CloseParen, 1,520 ( 0.00%) '{' => OpenBrace, 1,520 ( 0.00%) '}' => CloseBrace, 1,686 ( 0.00%) '[' => OpenBracket, 1,686 ( 0.00%) ']' => CloseBracket, . '@' => At, 362 ( 0.00%) '#' => Pound, . '~' => Tilde, 24 ( 0.00%) '?' => Question, 5,964 ( 0.00%) ':' => Colon, 334 ( 0.00%) '$' => Dollar, 1,332 ( 0.00%) '=' => Eq, 674 ( 0.00%) '!' => Bang, 880 ( 0.00%) '<' => Lt, 1,440 ( 0.00%) '>' => Gt, 368 ( 0.00%) '-' => Minus, 2,064 ( 0.00%) '&' => And, 156 ( 0.00%) '|' => Or, 66 ( 0.00%) '+' => Plus, 76 ( 0.00%) '*' => Star, . '^' => Caret, . '%' => Percent, . . // Lifetime or character literal. 828 ( 0.00%) '\'' => self.lifetime_or_char(), . . // String literal. . '"' => { 1,284 ( 0.00%) let terminated = self.double_quoted_string(); . let suffix_start = self.len_consumed(); 856 ( 0.00%) if terminated { . self.eat_literal_suffix(); . } . let kind = Str { terminated }; 856 ( 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()) 4,100,148 ( 0.08%) } . . fn line_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '/'); . self.bump(); . 3,880 ( 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. 4,260 ( 0.00%) '/' if self.second() != '/' => Some(DocStyle::Outer), . _ => None, . }; . 53,666 ( 0.00%) self.eat_while(|c| c != '\n'); 5,040 ( 0.00%) LineComment { doc_style } . } . . fn block_comment(&mut self) -> TokenKind { . debug_assert!(self.prev() == '/' && self.first() == '*'); . self.bump(); . 4 ( 0.00%) let doc_style = match self.first() { . // `/*!` is an inner block doc comment. . '!' => Some(DocStyle::Inner), . // `/***` (more than 2 stars) is not considered a doc comment. . // `/**/` is not considered a doc comment. . '*' if !matches!(self.second(), '*' | '/') => Some(DocStyle::Outer), . _ => None, . }; . . let mut depth = 1usize; 302 ( 0.00%) while let Some(c) = self.bump() { . match c { . '/' if self.first() == '*' => { . self.bump(); . depth += 1; . } 2 ( 0.00%) '*' if self.first() == '/' => { . self.bump(); 2 ( 0.00%) depth -= 1; 2 ( 0.00%) if depth == 0 { . // This block comment is closed, so for a construction like "/* */ */" . // there will be a successfully parsed block comment "/* */" . // and " */" will be processed separately. . break; . } . } . _ => (), . } . } . 5 ( 0.00%) BlockComment { doc_style, terminated: depth == 0 } . } . . fn whitespace(&mut self) -> TokenKind { . debug_assert!(is_whitespace(self.prev())); . self.eat_while(is_whitespace); 150,166 ( 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 . } . 45,695 ( 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. 18,278 ( 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. 18,278 ( 0.00%) match self.first() { . '#' | '"' | '\'' => UnknownPrefix, 9,139 ( 0.00%) c if !c.is_ascii() && unic_emoji_char::is_emoji(c) => { . self.fake_ident_or_unknown_prefix() . } 9,139 ( 0.00%) _ => Ident, . } 36,556 ( 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; 276,460 ( 0.01%) if first_digit == '0' { . // Attempt to parse encoding base. 449,075 ( 0.01%) 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. 259,590 ( 0.01%) '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(); . }; . 310,200 ( 0.01%) 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()`) 24 ( 0.00%) '.' if self.second() != '.' && !is_id_start(self.second()) => { . // might have stuff after the ., and if it does, it needs to start . // with a number . self.bump(); . let mut empty_exponent = false; . if self.first().is_digit(10) { . self.eat_decimal_digits(); . match self.first() { . 'e' | 'E' => { -- line 575 ---------------------------------------- -- line 585 ---------------------------------------- . self.bump(); . let empty_exponent = !self.eat_float_exponent(); . Float { base, empty_exponent } . } . _ => Int { base, empty_int: false }, . } . } . 1,932 ( 0.00%) fn lifetime_or_char(&mut self) -> TokenKind { . debug_assert!(self.prev() == '\''); . 552 ( 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 ( 0.00%) if !can_be_a_lifetime { 75 ( 0.00%) let terminated = self.single_quoted_string(); . let suffix_start = self.len_consumed(); 50 ( 0.00%) if terminated { . self.eat_literal_suffix(); . } . let kind = Char { terminated }; 100 ( 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. . // First symbol can be a number (which isn't a valid identifier start), . // so skip it without any checks. . self.bump(); 502 ( 0.00%) self.eat_while(is_id_continue); . . // Check if after skipping literal contents we've met a closing . // single quote (which means that user attempted to create a . // string with single quotes). 502 ( 0.00%) if self.first() == '\'' { . self.bump(); . let kind = Char { terminated: true }; . Literal { kind, suffix_start: self.len_consumed() } . } else { 502 ( 0.00%) Lifetime { starts_with_number } . } 1,656 ( 0.00%) } . . fn single_quoted_string(&mut self) -> bool { . debug_assert!(self.prev() == '\''); . // Check if it's a one-symbol literal. 82 ( 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 { 99 ( 0.00%) 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 25 ( 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() { 25,682 ( 0.00%) match c { . '"' => { . return true; . } 464 ( 0.00%) '\\' if self.first() == '\\' || self.first() == '"' => { . // Bump again to skip escaped character. . self.bump(); . } . _ => (), . } . } . // End of file reached. . false 428 ( 0.00%) } . . /// Eats the double-quoted string and returns `n_hashes` and an error if encountered. 14 ( 0.00%) fn raw_double_quoted_string(&mut self, prefix_len: usize) -> (u16, Option) { . // Wrap the actual function to handle the error with too many hashes. . // This way, it eats the whole raw string. . let (n_hashes, err) = self.raw_string_unvalidated(prefix_len); . // Only up to 65535 `#`s are allowed in raw strings 2 ( 0.00%) match u16::try_from(n_hashes) { 14 ( 0.00%) Ok(num) => (num, err), . // We lie about the number of hashes here :P . Err(_) => (0, Some(RawStrError::TooManyDelimiters { found: n_hashes })), . } 16 ( 0.00%) } . . fn raw_string_unvalidated(&mut self, prefix_len: usize) -> (usize, Option) { . debug_assert!(self.prev() == 'r'); . let start_pos = self.len_consumed(); . let mut possible_terminator_offset = None; . let mut max_hashes = 0; . . // Count opening '#' symbols. . let mut eaten = 0; 8 ( 0.00%) while self.first() == '#' { 6 ( 0.00%) eaten += 1; . self.bump(); . } . let n_start_hashes = eaten; . . // Check that string is started. 8 ( 0.00%) match self.bump() { . Some('"') => (), . c => { . let c = c.unwrap_or(EOF_CHAR); . return (n_start_hashes, Some(RawStrError::InvalidStarter { bad_char: c })); . } . } . . // Skip the string contents and on each '#' character met, check if this is . // a raw string termination. . loop { 706 ( 0.00%) self.eat_while(|c| c != '"'); . 60 ( 0.00%) if self.is_eof() { . return ( . n_start_hashes, . Some(RawStrError::NoTerminator { . expected: n_start_hashes, . found: max_hashes, . possible_terminator_offset, . }), . ); -- line 749 ---------------------------------------- -- line 753 ---------------------------------------- . self.bump(); . . // Check that amount of closing '#' symbols . // is equal to the amount of opening ones. . // Note that this will not consume extra trailing `#` characters: . // `r###"abcde"####` is lexed as a `RawStr { n_hashes: 3 }` . // followed by a `#` token. . let mut n_end_hashes = 0; 248 ( 0.00%) while self.first() == '#' && n_end_hashes < n_start_hashes { 4 ( 0.00%) n_end_hashes += 1; . self.bump(); . } . 120 ( 0.00%) if n_end_hashes == n_start_hashes { . return (n_start_hashes, None); 116 ( 0.00%) } else if n_end_hashes > max_hashes { . // Keep track of possible terminators to give a hint about . // where there might be a missing terminator . possible_terminator_offset = . Some(self.len_consumed() - start_pos - n_end_hashes + prefix_len); . max_hashes = n_end_hashes; . } . } . } . . fn eat_decimal_digits(&mut self) -> bool { . let mut has_digits = false; . loop { 111,070 ( 0.00%) match self.first() { . '_' => { . self.bump(); . } 166,605 ( 0.00%) '0'..='9' => { . has_digits = true; . self.bump(); . } . _ => break, . } . } . has_digits 92,458 ( 0.00%) } . . fn eat_hexadecimal_digits(&mut self) -> bool { . let mut has_digits = false; . loop { 148,616 ( 0.00%) match self.first() { . '_' => { . self.bump(); . } 341,622 ( 0.01%) '0'..='9' | 'a'..='f' | 'A'..='F' => { . has_digits = true; . self.bump(); . } . _ => break, . } . } . has_digits 10,958 ( 0.00%) } . . /// Eats the float exponent. Returns true if at least one digit was met, . /// and returns false otherwise. . fn eat_float_exponent(&mut self) -> bool { . debug_assert!(self.prev() == 'e' || self.prev() == 'E'); . if self.first() == '-' || self.first() == '+' { . self.bump(); . } . self.eat_decimal_digits() . } . . // Eats the suffix of the literal, e.g. "_u8". . fn eat_literal_suffix(&mut self) { 277,370 ( 0.01%) self.eat_identifier(); . } . . // Eats the identifier. 416,055 ( 0.01%) fn eat_identifier(&mut self) { . if !is_id_start(self.first()) { . return; . } . self.bump(); . . self.eat_while(is_id_continue); 554,740 ( 0.01%) } . } 5,498,368 ( 0.11%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_data_structures/src/sip128.rs -------------------------------------------------------------------------------- Ir -- line 91 ---------------------------------------- . // maximum of number bytes needed to fill an 8-byte-sized element on which . // SipHash operates. Note that for variable-sized copies which are known to be . // less than 8 bytes, this function will perform more work than necessary unless . // the compiler is able to optimize the extra work away. . #[inline] . unsafe fn copy_nonoverlapping_small(src: *const u8, dst: *mut u8, count: usize) { . debug_assert!(count <= 8); . 127,539 ( 0.00%) if count == 8 { . ptr::copy_nonoverlapping(src, dst, 8); . return; . } . . let mut i = 0; 213,722 ( 0.00%) if i + 3 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 4); . i += 4; . } . 457,470 ( 0.01%) if i + 1 < count { . ptr::copy_nonoverlapping(src.add(i), dst.add(i), 2); 56,507 ( 0.00%) i += 2 . } . 213,722 ( 0.00%) if i < count { 124,011 ( 0.00%) *dst.add(i) = *src.add(i); . i += 1; . } . . debug_assert_eq!(i, count); . } . . // # Implementation . // -- line 124 ---------------------------------------- -- line 201 ---------------------------------------- . . hasher . } . . // A specialized write function for values with size <= 8. . #[inline] . fn short_write(&mut self, x: T) { . let size = mem::size_of::(); 1,938,711 ( 0.04%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . 13,112,977 ( 0.27%) if nbuf + size < BUFFER_SIZE { . unsafe { . // The memcpy call is optimized away because the size is known. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . ptr::copy_nonoverlapping(&x as *const _ as *const u8, dst, size); . } . 4,169,338 ( 0.09%) self.nbuf = nbuf + size; . . return; . } . 419,099 ( 0.01%) unsafe { self.short_write_process_buffer(x) } . } . . // A specialized write function for values with size <= 8 that should only . // be called when the write would cause the buffer to fill. . // . // SAFETY: the write of `x` into `self.buf` starting at byte offset . // `self.nbuf` must cause `self.buf` to become fully initialized (and not . // overflow) if it wasn't already. . #[inline(never)] 179,139 ( 0.00%) unsafe fn short_write_process_buffer(&mut self, x: T) { . let size = mem::size_of::(); 179,139 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(size <= 8); . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + size >= BUFFER_SIZE); . debug_assert!(nbuf + size < BUFFER_WITH_SPILL_SIZE); . . // Copy first part of input into end of buffer, possibly into spill . // element. The memcpy call is optimized away because the size is known. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . ptr::copy_nonoverlapping(&x as *const _ as *const u8, dst, size); . . // Process buffer. . for i in 0..BUFFER_CAPACITY { 1,791,390 ( 0.04%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 1,433,112 ( 0.03%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 1,612,251 ( 0.03%) self.state.v0 ^= elem; . } . . // Copy remaining input into start of buffer by copying size - 1 . // elements from spill (at most size - 1 bytes could have overflowed . // into the spill). The memcpy call is optimized away because the size . // is known. And the whole copy is optimized away for size == 1. . let src = self.buf.get_unchecked(BUFFER_SPILL_INDEX) as *const _ as *const u8; . ptr::copy_nonoverlapping(src, self.buf.as_mut_ptr() as *mut u8, size - 1); . . // This function should only be called when the write fills the buffer. . // Therefore, when size == 1, the new `self.nbuf` must be zero. The size . // is statically known, so the branch is optimized away. 881,795 ( 0.02%) self.nbuf = if size == 1 { 0 } else { nbuf + size - BUFFER_SIZE }; 716,556 ( 0.01%) self.processed += BUFFER_SIZE; 358,278 ( 0.01%) } . . // A write function for byte slices. . #[inline] . fn slice_write(&mut self, msg: &[u8]) { . let length = msg.len(); 146,911 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . 813,844 ( 0.02%) if nbuf + length < BUFFER_SIZE { . unsafe { . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . 45,290 ( 0.00%) if length <= 8 { . copy_nonoverlapping_small(msg.as_ptr(), dst, length); . } else { . // This memcpy is *not* optimized away. . ptr::copy_nonoverlapping(msg.as_ptr(), dst, length); . } . } . 207,055 ( 0.00%) self.nbuf = nbuf + length; . . return; . } . 152,391 ( 0.00%) unsafe { self.slice_write_process_buffer(msg) } . } . . // A write function for byte slices that should only be called when the . // write would cause the buffer to fill. . // . // SAFETY: `self.buf` must be initialized up to the byte offset `self.nbuf`, . // and `msg` must contain enough bytes to initialize the rest of the element . // containing the byte offset `self.nbuf`. . #[inline(never)] 238,920 ( 0.00%) unsafe fn slice_write_process_buffer(&mut self, msg: &[u8]) { . let length = msg.len(); 47,784 ( 0.00%) let nbuf = self.nbuf; . debug_assert!(nbuf < BUFFER_SIZE); . debug_assert!(nbuf + length >= BUFFER_SIZE); . . // Always copy first part of input into current element of buffer. . // This function should only be called when the write fills the buffer, . // so we know that there is enough input to fill the current element. 143,352 ( 0.00%) let valid_in_elem = nbuf % ELEM_SIZE; 47,784 ( 0.00%) let needed_in_elem = ELEM_SIZE - valid_in_elem; . . let src = msg.as_ptr(); . let dst = (self.buf.as_mut_ptr() as *mut u8).add(nbuf); . copy_nonoverlapping_small(src, dst, needed_in_elem); . . // Process buffer. . . // Using `nbuf / ELEM_SIZE + 1` rather than `(nbuf + needed_in_elem) / . // ELEM_SIZE` to show the compiler that this loop's upper bound is > 0. . // We know that is true, because last step ensured we have a full . // element in the buffer. 95,568 ( 0.00%) let last = nbuf / ELEM_SIZE + 1; . . for i in 0..last { 347,502 ( 0.01%) let elem = self.buf.get_unchecked(i).assume_init().to_le(); 395,286 ( 0.01%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 695,004 ( 0.01%) self.state.v0 ^= elem; . } . . // Process the remaining element-sized chunks of input. . let mut processed = needed_in_elem; 95,568 ( 0.00%) let input_left = length - processed; 139,449 ( 0.00%) let elems_left = input_left / ELEM_SIZE; . let extra_bytes_left = input_left % ELEM_SIZE; . . for _ in 0..elems_left { 46,799 ( 0.00%) let elem = (msg.as_ptr().add(processed) as *const u64).read_unaligned().to_le(); 46,799 ( 0.00%) self.state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut self.state); 46,799 ( 0.00%) self.state.v0 ^= elem; 93,598 ( 0.00%) processed += ELEM_SIZE; . } . . // Copy remaining input into start of buffer. . let src = msg.as_ptr().add(processed); . let dst = self.buf.as_mut_ptr() as *mut u8; . copy_nonoverlapping_small(src, dst, extra_bytes_left); . 47,784 ( 0.00%) self.nbuf = extra_bytes_left; 238,920 ( 0.00%) self.processed += nbuf + processed; 286,704 ( 0.01%) } . . #[inline] . pub fn finish128(mut self) -> (u64, u64) { . debug_assert!(self.nbuf < BUFFER_SIZE); . . // Process full elements in buffer. 17,283 ( 0.00%) let last = self.nbuf / ELEM_SIZE; . . // Since we're consuming self, avoid updating members for a potential . // performance gain. 23,044 ( 0.00%) let mut state = self.state; . . for i in 0..last { 15,542 ( 0.00%) let elem = unsafe { self.buf.get_unchecked(i).assume_init().to_le() }; 15,542 ( 0.00%) state.v3 ^= elem; . Sip24Rounds::c_rounds(&mut state); 15,542 ( 0.00%) state.v0 ^= elem; . } . . // Get remaining partial element. 11,522 ( 0.00%) let elem = if self.nbuf % ELEM_SIZE != 0 { . unsafe { . // Ensure element is initialized by writing zero bytes. At most . // `ELEM_SIZE - 1` are required given the above check. It's safe . // to write this many because we have the spill and we maintain . // `self.nbuf` such that this write will start before the spill. . let dst = (self.buf.as_mut_ptr() as *mut u8).add(self.nbuf); . ptr::write_bytes(dst, 0, ELEM_SIZE - 1); 4,926 ( 0.00%) self.buf.get_unchecked(last).assume_init().to_le() . } . } else { . 0 . }; . . // Finalize the hash. 16,448 ( 0.00%) let length = self.processed + self.nbuf; 11,520 ( 0.00%) let b: u64 = ((length as u64 & 0xff) << 56) | elem; . 5,760 ( 0.00%) state.v3 ^= b; . Sip24Rounds::c_rounds(&mut state); 5,760 ( 0.00%) state.v0 ^= b; . 5,760 ( 0.00%) state.v2 ^= 0xee; . Sip24Rounds::d_rounds(&mut state); 18,974 ( 0.00%) let _0 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . 7,452 ( 0.00%) state.v1 ^= 0xdd; . Sip24Rounds::d_rounds(&mut state); 7,452 ( 0.00%) let _1 = state.v0 ^ state.v1 ^ state.v2 ^ state.v3; . . (_0, _1) . } . } . . impl Hasher for SipHasher128 { . #[inline] . fn write_u8(&mut self, i: u8) { -- line 414 ---------------------------------------- -- line 471 ---------------------------------------- . } . . #[derive(Debug, Clone, Default)] . struct Sip24Rounds; . . impl Sip24Rounds { . #[inline] . fn c_rounds(state: &mut State) { 7,717,351 ( 0.16%) compress!(state); 8,974,783 ( 0.18%) compress!(state); . } . . #[inline] . fn d_rounds(state: &mut State) { 37,944 ( 0.00%) compress!(state); 37,944 ( 0.00%) compress!(state); 37,944 ( 0.00%) compress!(state); 32,185 ( 0.00%) compress!(state); . } . } 1,215,994 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/builtin.rs -------------------------------------------------------------------------------- Ir -- line 83 ---------------------------------------- . Warn, . "suggest using `loop { }` instead of `while true { }`" . } . . declare_lint_pass!(WhileTrue => [WHILE_TRUE]); . . /// Traverse through any amount of parenthesis and return the first non-parens expression. . fn pierce_parens(mut expr: &ast::Expr) -> &ast::Expr { 28 ( 0.00%) while let ast::ExprKind::Paren(sub) = &expr.kind { . expr = sub; . } . expr . } . . impl EarlyLintPass for WhileTrue { 870,618 ( 0.02%) fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { 290,206 ( 0.01%) if let ast::ExprKind::While(cond, _, label) = &e.kind { 14 ( 0.00%) if let ast::ExprKind::Lit(ref lit) = pierce_parens(cond).kind { . if let ast::LitKind::Bool(true) = lit.kind { . if !lit.span.from_expansion() { . let msg = "denote infinite loops with `loop { ... }`"; . let condition_span = e.span.with_hi(cond.span.hi()); . cx.struct_span_lint(WHILE_TRUE, condition_span, |lint| { . lint.build(msg) . .span_suggestion_short( . condition_span, -- line 108 ---------------------------------------- -- line 117 ---------------------------------------- . Applicability::MachineApplicable, . ) . .emit(); . }) . } . } . } . } 1,015,721 ( 0.02%) } . } . . declare_lint! { . /// The `box_pointers` lints use of the Box type. . /// . /// ### Example . /// . /// ```rust,compile_fail -- line 133 ---------------------------------------- -- line 147 ---------------------------------------- . BOX_POINTERS, . Allow, . "use of owned (Box type) heap memory" . } . . declare_lint_pass!(BoxPointers => [BOX_POINTERS]); . . impl BoxPointers { 1,603,184 ( 0.03%) fn check_heap_type(&self, cx: &LateContext<'_>, span: Span, ty: Ty<'_>) { 2,972,408 ( 0.06%) for leaf in ty.walk() { . if let GenericArgKind::Type(leaf_ty) = leaf.unpack() { 5,082 ( 0.00%) if leaf_ty.is_box() { 1,980 ( 0.00%) cx.struct_span_lint(BOX_POINTERS, span, |lint| { . lint.build(&format!("type uses owned (Box type) pointers: {}", ty)).emit() . }); . } . } . } 1,165,952 ( 0.02%) } . } . . impl<'tcx> LateLintPass<'tcx> for BoxPointers { 4,428 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 1,968 ( 0.00%) match it.kind { . hir::ItemKind::Fn(..) . | hir::ItemKind::TyAlias(..) . | hir::ItemKind::Enum(..) . | hir::ItemKind::Struct(..) . | hir::ItemKind::Union(..) => { 615 ( 0.00%) self.check_heap_type(cx, it.span, cx.tcx.type_of(it.def_id)) . } . _ => (), . } . . // If it's a struct, we also have to check the fields' types 1,599 ( 0.00%) match it.kind { . hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { 36 ( 0.00%) for struct_field in struct_def.fields() { 301 ( 0.00%) let def_id = cx.tcx.hir().local_def_id(struct_field.hir_id); 258 ( 0.00%) self.check_heap_type(cx, struct_field.span, cx.tcx.type_of(def_id)); . } . } . _ => (), . } 3,936 ( 0.00%) } . . fn check_expr(&mut self, cx: &LateContext<'_>, e: &hir::Expr<'_>) { 436,734 ( 0.01%) let ty = cx.typeck_results().node_type(e.hir_id); 582,312 ( 0.01%) self.check_heap_type(cx, e.span, ty); . } . } . . declare_lint! { . /// The `non_shorthand_field_patterns` lint detects using `Struct { x: x }` . /// instead of `Struct { x }` in a pattern. . /// . /// ### Example -- line 203 ---------------------------------------- -- line 230 ---------------------------------------- . NON_SHORTHAND_FIELD_PATTERNS, . Warn, . "using `Struct { x: x }` instead of `Struct { x }` in a pattern" . } . . declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]); . . impl<'tcx> LateLintPass<'tcx> for NonShorthandFieldPatterns { 9,429 ( 0.00%) fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) { 2,988 ( 0.00%) if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind { 490 ( 0.00%) let variant = cx . .typeck_results() . .pat_ty(pat) . .ty_adt_def() . .expect("struct pattern type is not an ADT") 588 ( 0.00%) .variant_of_res(cx.qpath_res(qpath, pat.hir_id)); . for fieldpat in field_pats { 342 ( 0.00%) if fieldpat.is_shorthand { . continue; . } 588 ( 0.00%) if fieldpat.span.from_expansion() { . // Don't lint if this is a macro expansion: macro authors . // shouldn't have to worry about this kind of style issue . // (Issue #49588) . continue; . } 10 ( 0.00%) if let PatKind::Binding(binding_annot, _, ident, None) = fieldpat.pat.kind { 7 ( 0.00%) if cx.tcx.find_field_index(ident, &variant) 6 ( 0.00%) == Some(cx.tcx.field_index(fieldpat.hir_id, cx.typeck_results())) . { . cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS, fieldpat.span, |lint| { . let mut err = lint . .build(&format!("the `{}:` in this pattern is redundant", ident)); . let binding = match binding_annot { . hir::BindingAnnotation::Unannotated => None, . hir::BindingAnnotation::Mutable => Some("mut"), . hir::BindingAnnotation::Ref => Some("ref"), -- line 266 ---------------------------------------- -- line 278 ---------------------------------------- . Applicability::MachineApplicable, . ); . err.emit(); . }); . } . } . } . } 10,776 ( 0.00%) } . } . . declare_lint! { . /// The `unsafe_code` lint catches usage of `unsafe` code. . /// . /// ### Example . /// . /// ```rust,compile_fail -- line 294 ---------------------------------------- -- line 316 ---------------------------------------- . impl UnsafeCode { . fn report_unsafe( . &self, . cx: &EarlyContext<'_>, . span: Span, . decorate: impl for<'a> FnOnce(LintDiagnosticBuilder<'a>), . ) { . // This comes from a macro that has `#[allow_internal_unsafe]`. 70 ( 0.00%) if span.allows_unsafe() { . return; . } . . cx.struct_span_lint(UNSAFE_CODE, span, decorate); . } . . fn report_overriden_symbol_name(&self, cx: &EarlyContext<'_>, span: Span, msg: &str) { . self.report_unsafe(cx, span, |lint| { -- line 332 ---------------------------------------- -- line 337 ---------------------------------------- . override them", . ) . .emit(); . }) . } . } . . impl EarlyLintPass for UnsafeCode { 5,157 ( 0.00%) fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { 244 ( 0.00%) if attr.has_name(sym::allow_internal_unsafe) { . self.report_unsafe(cx, attr.span, |lint| { . lint.build( . "`allow_internal_unsafe` allows defining \ . macros using unsafe without triggering \ . the `unsafe_code` lint at their call site", . ) . .emit() . }); . } 6,876 ( 0.00%) } . 435,309 ( 0.01%) fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) { 290,206 ( 0.01%) if let ast::ExprKind::Block(ref blk, _) = e.kind { . // Don't warn about generated blocks; that'll just pollute the output. 194 ( 0.00%) if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) { 13 ( 0.00%) self.report_unsafe(cx, blk.span, |lint| { . lint.build("usage of an `unsafe` block").emit() . }); . } . } 580,412 ( 0.01%) } . 2,676 ( 0.00%) fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) { 2,599 ( 0.00%) match it.kind { . ast::ItemKind::Trait(box ast::Trait { unsafety: ast::Unsafe::Yes(_), .. }) => self . .report_unsafe(cx, it.span, |lint| { . lint.build("declaration of an `unsafe` trait").emit() . }), . . ast::ItemKind::Impl(box ast::Impl { unsafety: ast::Unsafe::Yes(_), .. }) => self . .report_unsafe(cx, it.span, |lint| { . lint.build("implementation of an `unsafe` trait").emit() . }), . . ast::ItemKind::Fn(..) => { 700 ( 0.00%) if let Some(attr) = cx.sess().find_by_name(&it.attrs, sym::no_mangle) { . self.report_overriden_symbol_name( . cx, . attr.span, . "declaration of a `no_mangle` function", . ); . } 700 ( 0.00%) if let Some(attr) = cx.sess().find_by_name(&it.attrs, sym::export_name) { . self.report_overriden_symbol_name( . cx, . attr.span, . "declaration of a function with `export_name`", . ); . } . } . -- line 397 ---------------------------------------- -- line 409 ---------------------------------------- . attr.span, . "declaration of a static with `export_name`", . ); . } . } . . _ => {} . } 3,122 ( 0.00%) } . 1,182 ( 0.00%) fn check_impl_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) { 394 ( 0.00%) if let ast::AssocItemKind::Fn(..) = it.kind { 1,337 ( 0.00%) if let Some(attr) = cx.sess().find_by_name(&it.attrs, sym::no_mangle) { . self.report_overriden_symbol_name( . cx, . attr.span, . "declaration of a `no_mangle` method", . ); . } 1,337 ( 0.00%) if let Some(attr) = cx.sess().find_by_name(&it.attrs, sym::export_name) { . self.report_overriden_symbol_name( . cx, . attr.span, . "declaration of a method with `export_name`", . ); . } . } 1,379 ( 0.00%) } . . fn check_fn(&mut self, cx: &EarlyContext<'_>, fk: FnKind<'_>, span: Span, _: ast::NodeId) { 1,202 ( 0.00%) if let FnKind::Fn( . ctxt, . _, . ast::FnSig { header: ast::FnHeader { unsafety: ast::Unsafe::Yes(_), .. }, .. }, . _, . body, . ) = fk . { 32 ( 0.00%) let msg = match ctxt { . FnCtxt::Foreign => return, . FnCtxt::Free => "declaration of an `unsafe` function", . FnCtxt::Assoc(_) if body.is_none() => "declaration of an `unsafe` method", . FnCtxt::Assoc(_) => "implementation of an `unsafe` method", . }; . self.report_unsafe(cx, span, |lint| lint.build(msg).emit()); . } . } -- line 455 ---------------------------------------- -- line 487 ---------------------------------------- . . /// Private traits or trait items that leaked through. Don't check their methods. . private_traits: FxHashSet, . } . . impl_lint_pass!(MissingDoc => [MISSING_DOCS]); . . fn has_doc(attr: &ast::Attribute) -> bool { 420 ( 0.00%) if attr.is_doc_comment() { . return true; . } . . if !attr.has_name(sym::doc) { . return false; . } . . if attr.value_str().is_some() { -- line 503 ---------------------------------------- -- line 512 ---------------------------------------- . } . } . . false . } . . impl MissingDoc { . pub fn new() -> MissingDoc { 4 ( 0.00%) MissingDoc { doc_hidden_stack: vec![false], private_traits: FxHashSet::default() } . } . . fn doc_hidden(&self) -> bool { 149,611 ( 0.00%) *self.doc_hidden_stack.last().expect("empty doc_hidden_stack") . } . 5,499 ( 0.00%) fn check_missing_docs_attrs( . &self, . cx: &LateContext<'_>, . def_id: LocalDefId, . sp: Span, . article: &'static str, . desc: &'static str, . ) { . // If we're building a test harness, then warning about . // documentation is probably not really relevant right now. 846 ( 0.00%) if cx.sess().opts.test { . return; . } . . // `#[doc(hidden)]` disables missing_docs check. 423 ( 0.00%) if self.doc_hidden() { . return; . } . . // Only check publicly-visible items, using the result from the privacy pass. . // It's an option so the crate root can also use this function (it doesn't . // have a `NodeId`). 234 ( 0.00%) if def_id != CRATE_DEF_ID { 815 ( 0.00%) if !cx.access_levels.is_exported(def_id) { . return; . } . } . 467 ( 0.00%) let attrs = cx.tcx.get_attrs(def_id.to_def_id()); . let has_doc = attrs.iter().any(has_doc); . if !has_doc { 84 ( 0.00%) cx.struct_span_lint( . MISSING_DOCS, 48 ( 0.00%) cx.tcx.sess.source_map().guess_head_span(sp), . |lint| { . lint.build(&format!("missing documentation for {} {}", article, desc)).emit() . }, . ); . } 3,384 ( 0.00%) } . } . . impl<'tcx> LateLintPass<'tcx> for MissingDoc { 1,044,316 ( 0.02%) fn enter_lint_attrs(&mut self, _cx: &LateContext<'_>, attrs: &[ast::Attribute]) { 149,188 ( 0.00%) let doc_hidden = self.doc_hidden() . || attrs.iter().any(|attr| { 1,820 ( 0.00%) attr.has_name(sym::doc) 505 ( 0.00%) && match attr.meta_item_list() { . None => false, 707 ( 0.00%) Some(l) => attr::list_contains_name(&l, sym::hidden), . } . }); . self.doc_hidden_stack.push(doc_hidden); 1,193,504 ( 0.02%) } . . fn exit_lint_attrs(&mut self, _: &LateContext<'_>, _attrs: &[ast::Attribute]) { . self.doc_hidden_stack.pop().expect("empty doc_hidden_stack"); . } . 6 ( 0.00%) fn check_crate(&mut self, cx: &LateContext<'_>) { 10 ( 0.00%) self.check_missing_docs_attrs( . cx, . CRATE_DEF_ID, 1 ( 0.00%) cx.tcx.def_span(CRATE_DEF_ID), . "the", . "crate", . ); 4 ( 0.00%) } . 2,952 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 1,718 ( 0.00%) match it.kind { . hir::ItemKind::Trait(.., trait_item_refs) => { . // Issue #11592: traits are always considered exported, even when private. 4 ( 0.00%) if let hir::VisibilityKind::Inherited = it.vis.node { . self.private_traits.insert(it.hir_id()); . for trait_item_ref in trait_item_refs { . self.private_traits.insert(trait_item_ref.id.hir_id()); . } . return; . } . } 218 ( 0.00%) hir::ItemKind::Impl(hir::Impl { of_trait: Some(ref trait_ref), items, .. }) => { . // If the trait is private, add the impl items to `private_traits` so they don't get . // reported for missing docs. 327 ( 0.00%) let real_trait = trait_ref.path.res.def_id(); 109 ( 0.00%) let Some(def_id) = real_trait.as_local() else { return }; 4 ( 0.00%) let Some(Node::Item(item)) = cx.tcx.hir().find_by_def_id(def_id) else { return }; 2 ( 0.00%) if let hir::VisibilityKind::Inherited = item.vis.node { . for impl_item_ref in items { . self.private_traits.insert(impl_item_ref.id.hir_id()); . } . } . return; . } . . hir::ItemKind::TyAlias(..) -- line 622 ---------------------------------------- -- line 627 ---------------------------------------- . | hir::ItemKind::Struct(..) . | hir::ItemKind::Union(..) . | hir::ItemKind::Const(..) . | hir::ItemKind::Static(..) => {} . . _ => return, . }; . 2,160 ( 0.00%) let (article, desc) = cx.tcx.article_and_description(it.def_id.to_def_id()); . 1,440 ( 0.00%) self.check_missing_docs_attrs(cx, it.def_id, it.span, article, desc); 3,444 ( 0.00%) } . . fn check_trait_item(&mut self, cx: &LateContext<'_>, trait_item: &hir::TraitItem<'_>) { 5 ( 0.00%) if self.private_traits.contains(&trait_item.hir_id()) { . return; . } . 8 ( 0.00%) let (article, desc) = cx.tcx.article_and_description(trait_item.def_id.to_def_id()); . 6 ( 0.00%) self.check_missing_docs_attrs(cx, trait_item.def_id, trait_item.span, article, desc); . } . 1,970 ( 0.00%) fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) { . // If the method is an impl for a trait, don't doc. 1,182 ( 0.00%) if method_context(cx, impl_item.hir_id()) == MethodLateContext::TraitImpl { . return; . } . . // If the method is an impl for an item with docs_hidden, don't doc. 520 ( 0.00%) if method_context(cx, impl_item.hir_id()) == MethodLateContext::PlainImpl { 624 ( 0.00%) let parent = cx.tcx.hir().get_parent_item(impl_item.hir_id()); 104 ( 0.00%) let impl_ty = cx.tcx.type_of(parent); 520 ( 0.00%) let outerdef = match impl_ty.kind() { 416 ( 0.00%) ty::Adt(def, _) => Some(def.did), . ty::Foreign(def_id) => Some(*def_id), . _ => None, . }; . let is_hidden = match outerdef { 208 ( 0.00%) Some(id) => cx.tcx.is_doc_hidden(id), . None => false, . }; 208 ( 0.00%) if is_hidden { . return; . } . } . 832 ( 0.00%) let (article, desc) = cx.tcx.article_and_description(impl_item.def_id.to_def_id()); 624 ( 0.00%) self.check_missing_docs_attrs(cx, impl_item.def_id, impl_item.span, article, desc); 1,576 ( 0.00%) } . . fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'_>) { . let (article, desc) = cx.tcx.article_and_description(foreign_item.def_id.to_def_id()); . self.check_missing_docs_attrs(cx, foreign_item.def_id, foreign_item.span, article, desc); . } . . fn check_field_def(&mut self, cx: &LateContext<'_>, sf: &hir::FieldDef<'_>) { 248 ( 0.00%) if !sf.is_positional() { 330 ( 0.00%) let def_id = cx.tcx.hir().local_def_id(sf.hir_id); 605 ( 0.00%) self.check_missing_docs_attrs(cx, def_id, sf.span, "a", "struct field") . } . } . . fn check_variant(&mut self, cx: &LateContext<'_>, v: &hir::Variant<'_>) { 374 ( 0.00%) self.check_missing_docs_attrs(cx, cx.tcx.hir().local_def_id(v.id), v.span, "a", "variant"); . } . } . . declare_lint! { . /// The `missing_copy_implementations` lint detects potentially-forgotten . /// implementations of [`Copy`]. . /// . /// [`Copy`]: https://doc.rust-lang.org/std/marker/trait.Copy.html -- line 699 ---------------------------------------- -- line 724 ---------------------------------------- . pub MISSING_COPY_IMPLEMENTATIONS, . Allow, . "detects potentially-forgotten implementations of `Copy`" . } . . declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]); . . impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations { 4,428 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { 2,222 ( 0.00%) if !cx.access_levels.is_reachable(item.def_id) { . return; . } 1,724 ( 0.00%) let (def, ty) = match item.kind { . hir::ItemKind::Struct(_, ref ast_generics) => { 11 ( 0.00%) if !ast_generics.params.is_empty() { . return; . } . let def = cx.tcx.adt_def(item.def_id); . (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[]))) . } . hir::ItemKind::Union(_, ref ast_generics) => { . if !ast_generics.params.is_empty() { . return; . } . let def = cx.tcx.adt_def(item.def_id); . (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[]))) . } . hir::ItemKind::Enum(_, ref ast_generics) => { 8 ( 0.00%) if !ast_generics.params.is_empty() { . return; . } 6 ( 0.00%) let def = cx.tcx.adt_def(item.def_id); . (def, cx.tcx.mk_adt(def, cx.tcx.intern_substs(&[]))) . } . _ => return, . }; 30 ( 0.00%) if def.has_dtor(cx.tcx) { . return; . } . let param_env = ty::ParamEnv::empty(); 54 ( 0.00%) if ty.is_copy_modulo_regions(cx.tcx.at(item.span), param_env) { . return; . } 14 ( 0.00%) if can_type_implement_copy(cx.tcx, param_env, ty).is_ok() { 8 ( 0.00%) cx.struct_span_lint(MISSING_COPY_IMPLEMENTATIONS, item.span, |lint| { . lint.build( . "type could implement `Copy`; consider adding `impl \ . Copy`", . ) . .emit() . }) . } 3,936 ( 0.00%) } . } . . declare_lint! { . /// The `missing_debug_implementations` lint detects missing . /// implementations of [`fmt::Debug`]. . /// . /// [`fmt::Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html . /// -- line 784 ---------------------------------------- -- line 811 ---------------------------------------- . #[derive(Default)] . pub struct MissingDebugImplementations { . impling_types: Option, . } . . impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]); . . impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations { 3,444 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { 2,222 ( 0.00%) if !cx.access_levels.is_reachable(item.def_id) { . return; . } . 1,016 ( 0.00%) match item.kind { . hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) => {} . _ => return, . } . 133 ( 0.00%) let Some(debug) = cx.tcx.get_diagnostic_item(sym::Debug) else { . return . }; . 19 ( 0.00%) if self.impling_types.is_none() { . let mut impls = LocalDefIdSet::default(); 9,112 ( 0.00%) cx.tcx.for_each_impl(debug, |d| { 6,273 ( 0.00%) if let Some(ty_def) = cx.tcx.type_of(d).ty_adt_def() { 1,206 ( 0.00%) if let Some(def_id) = ty_def.did.as_local() { 21 ( 0.00%) impls.insert(def_id); . } . } 10,408 ( 0.00%) }); . 4 ( 0.00%) self.impling_types = Some(impls); . debug!("{:?}", self.impling_types); . } . 38 ( 0.00%) if !self.impling_types.as_ref().unwrap().contains(&item.def_id) { 6 ( 0.00%) cx.struct_span_lint(MISSING_DEBUG_IMPLEMENTATIONS, item.span, |lint| { . lint.build(&format!( . "type does not implement `{}`; consider adding `#[derive(Debug)]` \ . or a manual implementation", . cx.tcx.def_path_str(debug) . )) . .emit() . }); . } 2,460 ( 0.00%) } . } . . declare_lint! { . /// The `anonymous_parameters` lint detects anonymous parameters in trait . /// definitions. . /// . /// ### Example . /// -- line 865 ---------------------------------------- -- line 907 ---------------------------------------- . . declare_lint_pass!( . /// Checks for use of anonymous parameters (RFC 1685). . AnonymousParameters => [ANONYMOUS_PARAMETERS] . ); . . impl EarlyLintPass for AnonymousParameters { . fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) { 4 ( 0.00%) if cx.sess().edition() != Edition::Edition2015 { . // This is a hard error in future editions; avoid linting and erroring . return; . } 1 ( 0.00%) if let ast::AssocItemKind::Fn(box Fn { ref sig, .. }) = it.kind { . for arg in sig.decl.inputs.iter() { 14 ( 0.00%) if let ast::PatKind::Ident(_, ident, None) = arg.pat.kind { 2 ( 0.00%) if ident.name == kw::Empty { . cx.struct_span_lint(ANONYMOUS_PARAMETERS, arg.pat.span, |lint| { . let ty_snip = cx.sess().source_map().span_to_snippet(arg.ty.span); . . let (ty_snip, appl) = if let Ok(ref snip) = ty_snip { . (snip.as_str(), Applicability::MachineApplicable) . } else { . ("", Applicability::HasPlaceholders) . }; -- line 930 ---------------------------------------- -- line 956 ---------------------------------------- . // compute it for every attribute. . depr_attrs: Vec<&'static BuiltinAttribute>, . } . . impl_lint_pass!(DeprecatedAttr => []); . . impl DeprecatedAttr { . pub fn new() -> DeprecatedAttr { 1 ( 0.00%) DeprecatedAttr { depr_attrs: deprecated_attributes() } . } . } . . fn lint_deprecated_attr( . cx: &EarlyContext<'_>, . attr: &ast::Attribute, . msg: &str, . suggestion: Option<&str>, -- line 972 ---------------------------------------- -- line 979 ---------------------------------------- . String::new(), . Applicability::MachineApplicable, . ) . .emit(); . }) . } . . impl EarlyLintPass for DeprecatedAttr { 15,471 ( 0.00%) fn check_attribute(&mut self, cx: &EarlyContext<'_>, attr: &ast::Attribute) { 8,595 ( 0.00%) for BuiltinAttribute { name, gate, .. } in &self.depr_attrs { 7,364 ( 0.00%) if attr.ident().map(|ident| ident.name) == Some(*name) { . if let &AttributeGate::Gated( . Stability::Deprecated(link, suggestion), . name, . reason, . _, . ) = gate . { . let msg = . format!("use of deprecated attribute `{}`: {}. See {}", name, reason, link); . lint_deprecated_attr(cx, attr, &msg, suggestion); . } . return; . } . } 976 ( 0.00%) if attr.has_name(sym::no_start) || attr.has_name(sym::crate_id) { . let path_str = pprust::path_to_string(&attr.get_normal_item().path); . let msg = format!("use of deprecated attribute `{}`: no longer used.", path_str); . lint_deprecated_attr(cx, attr, &msg, None); . } 13,752 ( 0.00%) } . } . 1,748,052 ( 0.04%) fn warn_if_doc(cx: &EarlyContext<'_>, node_span: Span, node_kind: &str, attrs: &[ast::Attribute]) { . use rustc_ast::token::CommentKind; . . let mut attrs = attrs.iter().peekable(); . . // Accumulate a single span for sugared doc comments. . let mut sugared_span: Option = None; . . while let Some(attr) = attrs.next() { -- line 1020 ---------------------------------------- -- line 1044 ---------------------------------------- . AttrKind::DocComment(CommentKind::Block, _) => { . err.help("use `/* */` for a plain comment"); . } . } . err.emit(); . }); . } . } 1,165,368 ( 0.02%) } . . impl EarlyLintPass for UnusedDocComment { . fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) { 2,451 ( 0.00%) let kind = match stmt.kind { . ast::StmtKind::Local(..) => "statements", . // Disabled pending discussion in #78306 . ast::StmtKind::Item(..) => return, . // expressions will be reported by `check_expr`. . ast::StmtKind::Empty . | ast::StmtKind::Semi(_) . | ast::StmtKind::Expr(_) . | ast::StmtKind::MacCall(_) => return, . }; . 3,108 ( 0.00%) warn_if_doc(cx, stmt.span, kind, stmt.kind.attrs()); . } . 1,162 ( 0.00%) fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) { 1,162 ( 0.00%) let arm_span = arm.pat.span.with_hi(arm.body.span.hi()); 1,660 ( 0.00%) warn_if_doc(cx, arm_span, "match arms", &arm.attrs); . } . . fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) { 1,160,824 ( 0.02%) warn_if_doc(cx, expr.span, "expressions", &expr.attrs); . } . . fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) { 1,440 ( 0.00%) warn_if_doc(cx, param.ident.span, "generic parameters", ¶m.attrs); . } . } . . declare_lint! { . /// The `no_mangle_const_items` lint detects any `const` items with the . /// [`no_mangle` attribute]. . /// . /// [`no_mangle` attribute]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute -- line 1088 ---------------------------------------- -- line 1133 ---------------------------------------- . NO_MANGLE_GENERIC_ITEMS, . Warn, . "generic items must be mangled" . } . . declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]); . . impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems { 4,428 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 3,444 ( 0.00%) let attrs = cx.tcx.hir().attrs(it.hir_id()); . let check_no_mangle_on_generic_fn = |no_mangle_attr: &ast::Attribute, . impl_generics: Option<&hir::Generics<'_>>, . generics: &hir::Generics<'_>, . span| { . for param in . generics.params.iter().chain(impl_generics.map(|g| g.params).into_iter().flatten()) . { . match param.kind { -- line 1150 ---------------------------------------- -- line 1162 ---------------------------------------- . ) . .emit(); . }); . break; . } . } . } . }; 2,872 ( 0.00%) match it.kind { . hir::ItemKind::Fn(.., ref generics, _) => { 500 ( 0.00%) if let Some(no_mangle_attr) = cx.sess().find_by_name(attrs, sym::no_mangle) { . check_no_mangle_on_generic_fn(no_mangle_attr, None, generics, it.span); . } . } . hir::ItemKind::Const(..) => { 465 ( 0.00%) if cx.sess().contains_name(attrs, sym::no_mangle) { . // Const items do not refer to a particular location in memory, and therefore . // don't have anything to attach a symbol to . cx.struct_span_lint(NO_MANGLE_CONST_ITEMS, it.span, |lint| { . let msg = "const items should never be `#[no_mangle]`"; . let mut err = lint.build(msg); . . // account for "pub const" (#45562) . let start = cx -- line 1185 ---------------------------------------- -- line 1196 ---------------------------------------- . "try a static value", . "pub static".to_owned(), . Applicability::MachineApplicable, . ); . err.emit(); . }); . } . } 121 ( 0.00%) hir::ItemKind::Impl(hir::Impl { ref generics, items, .. }) => { . for it in items { 1,006 ( 0.00%) if let hir::AssocItemKind::Fn { .. } = it.kind { 1,146 ( 0.00%) if let Some(no_mangle_attr) = cx . .sess() 955 ( 0.00%) .find_by_name(cx.tcx.hir().attrs(it.id.hir_id()), sym::no_mangle) . { . check_no_mangle_on_generic_fn( . no_mangle_attr, . Some(generics), . cx.tcx.hir().get_generics(it.id.def_id).unwrap(), . it.span, . ); . } . } . } . } . _ => {} . } 3,936 ( 0.00%) } . } . . declare_lint! { . /// The `mutable_transmutes` lint catches transmuting from `&T` to `&mut . /// T` because it is [undefined behavior]. . /// . /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html . /// -- line 1231 ---------------------------------------- -- line 1248 ---------------------------------------- . MUTABLE_TRANSMUTES, . Deny, . "transmuting &T to &mut T is undefined behavior, even if the reference is unused" . } . . declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]); . . impl<'tcx> LateLintPass<'tcx> for MutableTransmutes { 1,019,046 ( 0.02%) fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) { . use rustc_target::spec::abi::Abi::RustIntrinsic; . if let Some((&ty::Ref(_, _, from_mt), &ty::Ref(_, _, to_mt))) = . get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (ty1.kind(), ty2.kind())) . { . if to_mt == hir::Mutability::Mut && from_mt == hir::Mutability::Not { . let msg = "transmuting &T to &mut T is undefined behavior, \ . even if the reference is unused, consider instead using an UnsafeCell"; . cx.struct_span_lint(MUTABLE_TRANSMUTES, expr.span, |lint| lint.build(msg).emit()); . } . } . . fn get_transmute_from_to<'tcx>( . cx: &LateContext<'tcx>, . expr: &hir::Expr<'_>, . ) -> Option<(Ty<'tcx>, Ty<'tcx>)> { 293,464 ( 0.01%) let def = if let hir::ExprKind::Path(ref qpath) = expr.kind { 9,232 ( 0.00%) cx.qpath_res(qpath, expr.hir_id) . } else { . return None; . }; 6,482 ( 0.00%) if let Res::Def(DefKind::Fn, did) = def { 40 ( 0.00%) if !def_id_is_transmute(cx, did) { . return None; . } . let sig = cx.typeck_results().node_type(expr.hir_id).fn_sig(cx.tcx); . let from = sig.inputs().skip_binder()[0]; . let to = sig.output().skip_binder(); . return Some((from, to)); . } . None . } . . fn def_id_is_transmute(cx: &LateContext<'_>, def_id: DefId) -> bool { 332 ( 0.00%) cx.tcx.fn_sig(def_id).abi() == RustIntrinsic 160 ( 0.00%) && cx.tcx.item_name(def_id) == sym::transmute . } 1,164,624 ( 0.02%) } . } . . declare_lint! { . /// The `unstable_features` is deprecated and should no longer be used. . UNSTABLE_FEATURES, . Allow, . "enabling unstable features (deprecated. do not use)" . } . . declare_lint_pass!( . /// Forbids using the `#[feature(...)]` attribute . UnstableFeatures => [UNSTABLE_FEATURES] . ); . . impl<'tcx> LateLintPass<'tcx> for UnstableFeatures { 12,131 ( 0.00%) fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &ast::Attribute) { 252 ( 0.00%) if attr.has_name(sym::feature) { . if let Some(items) = attr.meta_item_list() { . for item in items { . cx.struct_span_lint(UNSTABLE_FEATURES, item.span(), |lint| { . lint.build("unstable feature").emit() . }); . } . } . } 13,864 ( 0.00%) } . } . . declare_lint! { . /// The `unreachable_pub` lint triggers for `pub` items not reachable from . /// the crate root. . /// . /// ### Example . /// -- line 1327 ---------------------------------------- -- line 1352 ---------------------------------------- . } . . declare_lint_pass!( . /// Lint for items marked `pub` that aren't reachable from other crates. . UnreachablePub => [UNREACHABLE_PUB] . ); . . impl UnreachablePub { 6,008 ( 0.00%) fn perform_lint( . &self, . cx: &LateContext<'_>, . what: &str, . def_id: LocalDefId, . vis: &hir::Visibility<'_>, . span: Span, . exportable: bool, . ) { 751 ( 0.00%) let mut applicability = Applicability::MachineApplicable; 1,502 ( 0.00%) match vis.node { 1,104 ( 0.00%) hir::VisibilityKind::Public if !cx.access_levels.is_reachable(def_id) => { 216 ( 0.00%) if span.from_expansion() { . applicability = Applicability::MaybeIncorrect; . } 540 ( 0.00%) let def_span = cx.tcx.sess.source_map().guess_head_span(span); 1,296 ( 0.00%) cx.struct_span_lint(UNREACHABLE_PUB, def_span, |lint| { . let mut err = lint.build(&format!("unreachable `pub` {}", what)); . let replacement = if cx.tcx.features().crate_visibility_modifier { . "crate" . } else { . "pub(crate)" . } . .to_owned(); . -- line 1384 ---------------------------------------- -- line 1391 ---------------------------------------- . if exportable { . err.help("or consider exporting it for use by other crates"); . } . err.emit(); . }); . } . _ => {} . } 3,755 ( 0.00%) } . } . . impl<'tcx> LateLintPass<'tcx> for UnreachablePub { . fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { 3,936 ( 0.00%) self.perform_lint(cx, "item", item.def_id, &item.vis, item.span, true); . } . . fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'tcx>) { . self.perform_lint( . cx, . "item", . foreign_item.def_id, . &foreign_item.vis, . foreign_item.span, . true, . ); . } . . fn check_field_def(&mut self, cx: &LateContext<'_>, field: &hir::FieldDef<'_>) { 310 ( 0.00%) let def_id = cx.tcx.hir().local_def_id(field.hir_id); 496 ( 0.00%) self.perform_lint(cx, "field", def_id, &field.vis, field.span, false); . } . . fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) { 1,970 ( 0.00%) self.perform_lint(cx, "item", impl_item.def_id, &impl_item.vis, impl_item.span, false); . } . } . . declare_lint! { . /// The `type_alias_bounds` lint detects bounds in type aliases. . /// . /// ### Example . /// -- line 1432 ---------------------------------------- -- line 1493 ---------------------------------------- . . // Let's go for a walk! . let mut visitor = WalkAssocTypes { err }; . visitor.visit_ty(ty); . } . } . . impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds { 3,444 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) { 984 ( 0.00%) let hir::ItemKind::TyAlias(ty, type_alias_generics) = &item.kind else { . return . }; 3 ( 0.00%) if let hir::TyKind::OpaqueDef(..) = ty.kind { . // Bounds are respected for `type X = impl Trait` . return; . } 1 ( 0.00%) let mut suggested_changing_assoc_types = false; . // There must not be a where clause 1 ( 0.00%) if !type_alias_generics.where_clause.predicates.is_empty() { . cx.lint( . TYPE_ALIAS_BOUNDS, . |lint| { . let mut err = lint.build("where clauses are not enforced in type aliases"); . let spans: Vec<_> = type_alias_generics . .where_clause . .predicates . .iter() -- line 1519 ---------------------------------------- -- line 1530 ---------------------------------------- . TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err); . suggested_changing_assoc_types = true; . } . err.emit(); . }, . ); . } . // The parameters must not have bounds 1 ( 0.00%) for param in type_alias_generics.params.iter() { 2 ( 0.00%) let spans: Vec<_> = param.bounds.iter().map(|b| b.span()).collect(); . let suggestion = spans . .iter() . .map(|sp| { . let start = param.span.between(*sp); // Include the `:` in `T: Bound`. . (start.to(*sp), String::new()) . }) . .collect(); 1 ( 0.00%) if !spans.is_empty() { . cx.struct_span_lint(TYPE_ALIAS_BOUNDS, spans, |lint| { . let mut err = . lint.build("bounds on generic parameters are not enforced in type aliases"); . let msg = "the bound will not be checked when the type alias is used, \ . and should be removed"; . err.multipart_suggestion(&msg, suggestion, Applicability::MachineApplicable); . if !suggested_changing_assoc_types { . TypeAliasBounds::suggest_changing_assoc_types(ty, &mut err); . suggested_changing_assoc_types = true; . } . err.emit(); . }); . } . } 3,936 ( 0.00%) } . } . . declare_lint_pass!( . /// Lint constants that are erroneous. . /// Without this lint, we might not get any diagnostic if the constant is . /// unused within this crate, even though downstream crates can't use it . /// without producing an error. . UnusedBrokenConst => [] . ); . . impl<'tcx> LateLintPass<'tcx> for UnusedBrokenConst { . fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 2,274 ( 0.00%) match it.kind { 186 ( 0.00%) hir::ItemKind::Const(_, body_id) => { 372 ( 0.00%) let def_id = cx.tcx.hir().body_owner_def_id(body_id).to_def_id(); . // trigger the query once for all constants since that will already report the errors . // FIXME: Use ensure here 465 ( 0.00%) let _ = cx.tcx.const_eval_poly(def_id); . } . hir::ItemKind::Static(_, _, body_id) => { . let def_id = cx.tcx.hir().body_owner_def_id(body_id).to_def_id(); . // FIXME: Use ensure here . let _ = cx.tcx.eval_static_initializer(def_id); . } . _ => {} . } -- line 1588 ---------------------------------------- -- line 1626 ---------------------------------------- . . declare_lint_pass!( . /// Lint for trait and lifetime bounds that don't depend on type parameters . /// which either do nothing, or stop the item from being used. . TrivialConstraints => [TRIVIAL_BOUNDS] . ); . . impl<'tcx> LateLintPass<'tcx> for TrivialConstraints { 4,428 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) { . use rustc_middle::ty::fold::TypeFoldable; . use rustc_middle::ty::PredicateKind::*; . 1,968 ( 0.00%) if cx.tcx.features().trivial_bounds { . let predicates = cx.tcx.predicates_of(item.def_id); . for &(predicate, span) in predicates.predicates { . let predicate_kind_name = match predicate.kind().skip_binder() { . Trait(..) => "trait", . TypeOutlives(..) | . RegionOutlives(..) => "lifetime", . . // Ignore projections, as they can only be global -- line 1646 ---------------------------------------- -- line 1663 ---------------------------------------- . or lifetime parameters", . predicate_kind_name, predicate . )) . .emit() . }); . } . } . } 3,936 ( 0.00%) } . } . . declare_lint_pass!( . /// Does nothing as a lint pass, but registers some `Lint`s . /// which are used by other parts of the compiler. . SoftLints => [ . WHILE_TRUE, . BOX_POINTERS, -- line 1679 ---------------------------------------- -- line 1732 ---------------------------------------- . /// If `Some(_)`, suppress all subsequent pattern . /// warnings for better diagnostics. . node_id: Option, . } . . impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]); . . impl EarlyLintPass for EllipsisInclusiveRangePatterns { 9,100 ( 0.00%) fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) { 1,300 ( 0.00%) if self.node_id.is_some() { . // Don't recursively warn about patterns inside range endpoints. . return; . } . . use self::ast::{PatKind, RangeSyntax::DotDotDot}; . . /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span . /// corresponding to the ellipsis. . fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(Option<&Expr>, &Expr, Span)> { 2,600 ( 0.00%) match &pat.kind { . PatKind::Range( . a, . Some(b), . Spanned { span, node: RangeEnd::Included(DotDotDot) }, . ) => Some((a.as_deref(), b, *span)), . _ => None, . } . } . 3,900 ( 0.00%) let (parenthesise, endpoints) = match &pat.kind { . PatKind::Ref(subpat, _) => (true, matches_ellipsis_pat(&subpat)), . _ => (false, matches_ellipsis_pat(pat)), . }; . . if let Some((start, end, join)) = endpoints { . let msg = "`...` range patterns are deprecated"; . let suggestion = "use `..=` for an inclusive range"; . if parenthesise { -- line 1769 ---------------------------------------- -- line 1816 ---------------------------------------- . replace, . Applicability::MachineApplicable, . ) . .emit(); . }); . } . }; . } 10,400 ( 0.00%) } . . fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) { 3,900 ( 0.00%) if let Some(node_id) = self.node_id { . if pat.id == node_id { . self.node_id = None . } . } . } . } . . declare_lint! { -- line 1835 ---------------------------------------- -- line 1880 ---------------------------------------- . . impl UnnameableTestItems { . pub fn new() -> Self { . Self { boundary: None, items_nameable: true } . } . } . . impl<'tcx> LateLintPass<'tcx> for UnnameableTestItems { 2,460 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 984 ( 0.00%) if self.items_nameable { 982 ( 0.00%) if let hir::ItemKind::Mod(..) = it.kind { . } else { 473 ( 0.00%) self.items_nameable = false; 1,419 ( 0.00%) self.boundary = Some(it.def_id); . } . return; . } . 6 ( 0.00%) let attrs = cx.tcx.hir().attrs(it.hir_id()); 5 ( 0.00%) if let Some(attr) = cx.sess().find_by_name(attrs, sym::rustc_test_marker) { . cx.struct_span_lint(UNNAMEABLE_TEST_ITEMS, attr.span, |lint| { . lint.build("cannot test inner items").emit() . }); . } 2,952 ( 0.00%) } . . fn check_item_post(&mut self, _cx: &LateContext<'_>, it: &hir::Item<'_>) { 2,880 ( 0.00%) if !self.items_nameable && self.boundary == Some(it.def_id) { 473 ( 0.00%) self.items_nameable = true; . } . } . } . . declare_lint! { . /// The `keyword_idents` lint detects edition keywords being used as an . /// identifier. . /// -- line 1916 ---------------------------------------- -- line 1958 ---------------------------------------- . declare_lint_pass!( . /// Check for uses of edition keywords used as an identifier. . KeywordIdents => [KEYWORD_IDENTS] . ); . . struct UnderMacro(bool); . . impl KeywordIdents { 5,992 ( 0.00%) fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: TokenStream) { 55,841 ( 0.00%) for tt in tokens.into_trees() { 7,974 ( 0.00%) match tt { . // Only report non-raw idents. 13,708 ( 0.00%) TokenTree::Token(token) => { 17,764 ( 0.00%) if let Some((ident, false)) = token.ident() { 5,408 ( 0.00%) self.check_ident_token(cx, UnderMacro(true), ident); . } . } 1,120 ( 0.00%) TokenTree::Delimited(_, _, tts) => self.check_tokens(cx, tts), . } . } 5,992 ( 0.00%) } . 93,804 ( 0.00%) fn check_ident_token( . &mut self, . cx: &EarlyContext<'_>, . UnderMacro(under_macro): UnderMacro, . ident: Ident, . ) { 31,268 ( 0.00%) let next_edition = match cx.sess().edition() { . Edition::Edition2015 => { 54,719 ( 0.00%) match ident.name { . kw::Async | kw::Await | kw::Try => Edition::Edition2018, . . // rust-lang/rust#56327: Conservatively do not . // attempt to report occurrences of `dyn` within . // macro definitions or invocations, because `dyn` . // can legitimately occur as a contextual keyword . // in 2015 code denoting its 2018 meaning, and we . // do not want rustfix to inject bugs into working . // code by rewriting such occurrences. . // . // But if we see `dyn` outside of a macro, we know . // its precise role in the parsed AST and thus are . // assured this is truly an attempt to use it as . // an identifier. 15,634 ( 0.00%) kw::Dyn if !under_macro => Edition::Edition2018, . . _ => return, . } . } . . // There are no new keywords yet for the 2018 edition and beyond. . _ => return, . }; -- line 2011 ---------------------------------------- -- line 2020 ---------------------------------------- . .span_suggestion( . ident.span, . "you can use a raw identifier to stay compatible", . format!("r#{}", ident), . Applicability::MachineApplicable, . ) . .emit() . }); 54,719 ( 0.00%) } . } . . impl EarlyLintPass for KeywordIdents { . fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef, _id: ast::NodeId) { 20 ( 0.00%) self.check_tokens(cx, mac_def.body.inner_tokens()); . } . fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall) { 925 ( 0.00%) self.check_tokens(cx, mac.args.inner_tokens()); . } . fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: Ident) { 12,930 ( 0.00%) self.check_ident_token(cx, UnderMacro(false), ident); . } . } . 2 ( 0.00%) declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMENTS]); . . impl ExplicitOutlivesRequirements { . fn lifetimes_outliving_lifetime<'tcx>( . inferred_outlives: &'tcx [(ty::Predicate<'tcx>, Span)], . index: u32, . ) -> Vec> { . inferred_outlives . .iter() -- line 2051 ---------------------------------------- -- line 2179 ---------------------------------------- . } . } . merged . } . } . } . . impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements { 4,428 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) { . use rustc_middle::middle::resolve_lifetime::Region; . 1,968 ( 0.00%) let infer_static = cx.tcx.features().infer_static_outlives_requirements; 492 ( 0.00%) let def_id = item.def_id; 3,420 ( 0.00%) if let hir::ItemKind::Struct(_, ref hir_generics) 20 ( 0.00%) | hir::ItemKind::Enum(_, ref hir_generics) . | hir::ItemKind::Union(_, ref hir_generics) = item.kind . { 22 ( 0.00%) let inferred_outlives = cx.tcx.inferred_outlives_of(def_id); 43 ( 0.00%) if inferred_outlives.is_empty() { . return; . } . 1 ( 0.00%) let ty_generics = cx.tcx.generics_of(def_id); . 1 ( 0.00%) let mut bound_count = 0; . let mut lint_spans = Vec::new(); . . for param in hir_generics.params { 3 ( 0.00%) let has_lifetime_bounds = param . .bounds . .iter() . .any(|bound| matches!(bound, hir::GenericBound::Outlives(_))); . if !has_lifetime_bounds { . continue; . } . . let relevant_lifetimes = -- line 2215 ---------------------------------------- -- line 2229 ---------------------------------------- . param.span.shrink_to_hi(), . ¶m.bounds, . bound_spans, . )); . } . . let mut where_lint_spans = Vec::new(); . let mut dropped_predicate_count = 0; 1 ( 0.00%) let num_predicates = hir_generics.where_clause.predicates.len(); . for (i, where_predicate) in hir_generics.where_clause.predicates.iter().enumerate() { . let (relevant_lifetimes, bounds, span) = match where_predicate { . hir::WherePredicate::RegionPredicate(predicate) => { . if let Some(Region::EarlyBound(index, ..)) = . cx.tcx.named_region(predicate.lifetime.hir_id) . { . ( . Self::lifetimes_outliving_lifetime(inferred_outlives, index), -- line 2245 ---------------------------------------- -- line 2319 ---------------------------------------- . } else { . hir_generics.span.shrink_to_hi().to(where_span) . }; . lint_spans.push(full_where_span); . } else { . lint_spans.extend(where_lint_spans); . } . 1 ( 0.00%) if !lint_spans.is_empty() { . cx.struct_span_lint(EXPLICIT_OUTLIVES_REQUIREMENTS, lint_spans.clone(), |lint| { . lint.build("outlives requirements can be inferred") . .multipart_suggestion( . if bound_count == 1 { . "remove this bound" . } else { . "remove these bounds" . }, -- line 2335 ---------------------------------------- -- line 2338 ---------------------------------------- . .map(|span| (span, "".to_owned())) . .collect::>(), . Applicability::MachineApplicable, . ) . .emit(); . }); . } . } 3,936 ( 0.00%) } . } . . declare_lint! { . /// The `incomplete_features` lint detects unstable features enabled with . /// the [`feature` attribute] that may function improperly in some or all . /// cases. . /// . /// [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/ -- line 2354 ---------------------------------------- -- line 2448 ---------------------------------------- . pub INVALID_VALUE, . Warn, . "an invalid value is being created (such as a null reference)" . } . . declare_lint_pass!(InvalidValue => [INVALID_VALUE]); . . impl<'tcx> LateLintPass<'tcx> for InvalidValue { 1,019,046 ( 0.02%) fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) { . #[derive(Debug, Copy, Clone, PartialEq)] . enum InitKind { . Zeroed, . Uninit, . } . . /// Information about why a type cannot be initialized this way. . /// Contains an error message and optionally a span to point at. -- line 2464 ---------------------------------------- -- line 2478 ---------------------------------------- . } . Tup(tup) => tup.iter().all(is_zero), . _ => false, . } . } . . /// Determine if this expression is a "dangerous initialization". . fn is_dangerous_init(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option { 727,006 ( 0.01%) if let hir::ExprKind::Call(ref path_expr, ref args) = expr.kind { . // Find calls to `mem::{uninitialized,zeroed}` methods. 1,888 ( 0.00%) if let hir::ExprKind::Path(ref qpath) = path_expr.kind { 4,210 ( 0.00%) let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?; 3,624 ( 0.00%) match cx.tcx.get_diagnostic_name(def_id) { . Some(sym::mem_zeroed) => return Some(InitKind::Zeroed), . Some(sym::mem_uninitialized) => return Some(InitKind::Uninit), . Some(sym::transmute) if is_zero(&args[0]) => return Some(InitKind::Zeroed), . _ => {} . } . } . } else if let hir::ExprKind::MethodCall(_, ref args, _) = expr.kind { . // Find problematic calls to `MaybeUninit::assume_init`. 2,210 ( 0.00%) let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?; 2,652 ( 0.00%) if cx.tcx.is_diagnostic_item(sym::assume_init, def_id) { . // This is a call to *some* method named `assume_init`. . // See if the `self` parameter is one of the dangerous constructors. . if let hir::ExprKind::Call(ref path_expr, _) = args[0].kind { . if let hir::ExprKind::Path(ref qpath) = path_expr.kind { . let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?; . match cx.tcx.get_diagnostic_name(def_id) { . Some(sym::maybe_uninit_zeroed) => return Some(InitKind::Zeroed), . Some(sym::maybe_uninit_uninit) => return Some(InitKind::Uninit), -- line 2508 ---------------------------------------- -- line 2655 ---------------------------------------- . err.span_note(span, &msg); . } else { . err.note(&msg); . } . err.emit(); . }); . } . } 873,468 ( 0.02%) } . } . . declare_lint! { . /// The `clashing_extern_declarations` lint detects when an `extern fn` . /// has been declared with the same name but different types. . /// . /// ### Example . /// -- line 2671 ---------------------------------------- -- line 3078 ---------------------------------------- . pub DEREF_NULLPTR, . Warn, . "detects when an null pointer is dereferenced" . } . . declare_lint_pass!(DerefNullPtr => [DEREF_NULLPTR]); . . impl<'tcx> LateLintPass<'tcx> for DerefNullPtr { 436,734 ( 0.01%) fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) { . /// test if expression is a null ptr . fn is_null_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool { 1,536 ( 0.00%) match &expr.kind { . rustc_hir::ExprKind::Cast(ref expr, ref ty) => { . if let rustc_hir::TyKind::Ptr(_) = ty.kind { . return is_zero(expr) || is_null_ptr(cx, expr); . } . } . // check for call to `core::ptr::null` or `core::ptr::null_mut` . rustc_hir::ExprKind::Call(ref path, _) => { . if let rustc_hir::ExprKind::Path(ref qpath) = path.kind { -- line 3097 ---------------------------------------- -- line 3116 ---------------------------------------- . return a == 0; . } . } . _ => {} . } . false . } . 291,936 ( 0.01%) if let rustc_hir::ExprKind::Unary(rustc_hir::UnOp::Deref, expr_deref) = expr.kind { . if is_null_ptr(cx, expr_deref) { . cx.struct_span_lint(DEREF_NULLPTR, expr.span, |lint| { . let mut err = lint.build("dereferencing a null pointer"); . err.span_label(expr.span, "this code causes undefined behavior when executed"); . err.emit(); . }); . } . } 582,312 ( 0.01%) } . } . . declare_lint! { . /// The `named_asm_labels` lint detects the use of named labels in the . /// inline `asm!` macro. . /// . /// ### Example . /// -- line 3141 ---------------------------------------- -- line 3162 ---------------------------------------- . pub NAMED_ASM_LABELS, . Deny, . "named labels in inline assembly", . } . . declare_lint_pass!(NamedAsmLabels => [NAMED_ASM_LABELS]); . . impl<'tcx> LateLintPass<'tcx> for NamedAsmLabels { 1,019,046 ( 0.02%) fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) { 291,156 ( 0.01%) if let hir::Expr { . kind: hir::ExprKind::InlineAsm(hir::InlineAsm { template_strs, .. }), . .. . } = expr . { . for (template_sym, template_snippet, template_span) in template_strs.iter() { . let template_str = template_sym.as_str(); . let find_label_span = |needle: &str| -> Option { . if let Some(template_snippet) = template_snippet { -- line 3179 ---------------------------------------- -- line 3242 ---------------------------------------- . BuiltinLintDiagnostics::NamedAsmLabel( . "only local labels of the form `:` should be used in inline asm" . .to_string(), . ), . ); . } . } . } 1,164,624 ( 0.02%) } . } 27,974 ( 0.00%) -------------------------------------------------------------------------------- -- 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 { 149,052 ( 0.00%) pub id: hir::ItemLocalId, 3,413,886 ( 0.07%) 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(), . ), . } . } . } . 16,064,697 ( 0.33%) #[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 { 6,329 ( 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. 44,303 ( 0.00%) pub fn span(&self, tcx: TyCtxt<'_>, scope_tree: &ScopeTree) -> Span { 12,658 ( 0.00%) let hir_id = match self.hir_id(scope_tree) { . Some(hir_id) => hir_id, . None => return DUMMY_SP, . }; 25,316 ( 0.00%) let span = tcx.hir().span(hir_id); 25,316 ( 0.00%) if let ScopeData::Remainder(first_statement_index) = self.data { 2,688 ( 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) . 3,584 ( 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. 863 ( 0.00%) if span.lo() <= stmt_span.lo() && stmt_span.lo() <= span.hi() { 1,588 ( 0.00%) return span.with_lo(stmt_span.lo()); . } . } . } . span 56,961 ( 0.00%) } . } . . 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 { 904,176 ( 0.02%) pub fn record_scope_parent(&mut self, child: Scope, parent: Option<(Scope, ScopeDepth)>) { . debug!("{:?}.parent = {:?}", child, parent); . 301,392 ( 0.01%) if let Some(p) = parent { . let prev = self.parent_map.insert(child, p); 149,856 ( 0.00%) assert!(prev.is_none()); . } . . // Record the destruction scopes for later so we can query them. 301,392 ( 0.01%) if let ScopeData::Destruction = child.data { . self.destruction_scopes.insert(child.item_local_id(), child); . } 597,284 ( 0.01%) } . 293,100 ( 0.01%) pub fn opt_destruction_scope(&self, n: hir::ItemLocalId) -> Option { . self.destruction_scopes.get(&n).cloned() 293,100 ( 0.01%) } . . pub fn record_var_scope(&mut self, var: hir::ItemLocalId, lifetime: Scope) { . debug!("record_var_scope(sub={:?}, sup={:?})", var, lifetime); 874 ( 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); 2,668 ( 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` 1,752 ( 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)) 1,752 ( 0.00%) } . . /// Returns the scope when the temp created by `expr_id` will be cleaned up. 2,041,361 ( 0.04%) pub fn temporary_scope(&self, expr_id: hir::ItemLocalId) -> Option { . // Check for a designated rvalue scope. 4,020 ( 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. 290,283 ( 0.01%) let mut id = Scope { id: expr_id, data: ScopeData::Node }; . 9,742,320 ( 0.20%) while let Some(&(p, _)) = self.parent_map.get(&id) { 3,154,821 ( 0.06%) match p.data { . ScopeData::Destruction => { . debug!("temporary_scope({:?}) = {:?} [enclosing]", expr_id, id); . return Some(id); . } 1,142,946 ( 0.02%) _ => id = p, . } . } . . debug!("temporary_scope({:?}) = None", expr_id); . None 2,332,984 ( 0.05%) } . . /// 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 ---------------------------------------- 5,999,769 ( 0.12%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_privacy/src/lib.rs -------------------------------------------------------------------------------- Ir -- line 59 ---------------------------------------- . &mut self, . def_id: DefId, . kind: &str, . descr: &dyn fmt::Display, . ) -> ControlFlow; . . /// Not overridden, but used to actually visit types and traits. . fn skeleton(&mut self) -> DefIdVisitorSkeleton<'_, 'tcx, Self> { 1,525,091 ( 0.03%) DefIdVisitorSkeleton { . def_id_visitor: self, . visited_opaque_tys: Default::default(), . dummy: Default::default(), . } . } 1,089 ( 0.00%) fn visit(&mut self, ty_fragment: impl TypeFoldable<'tcx>) -> ControlFlow { . ty_fragment.visit_with(&mut self.skeleton()) 1,815 ( 0.00%) } 654 ( 0.00%) fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow { . self.skeleton().visit_trait(trait_ref) 654 ( 0.00%) } . fn visit_projection_ty( . &mut self, . projection: ty::ProjectionTy<'tcx>, . ) -> ControlFlow { 84 ( 0.00%) self.skeleton().visit_projection_ty(projection) . } . fn visit_predicates( . &mut self, . predicates: ty::GenericPredicates<'tcx>, . ) -> ControlFlow { 1,184 ( 0.00%) self.skeleton().visit_predicates(predicates) . } . } . . struct DefIdVisitorSkeleton<'v, 'tcx, V: ?Sized> { . def_id_visitor: &'v mut V, . visited_opaque_tys: FxHashSet, . dummy: PhantomData>, . } . . impl<'tcx, V> DefIdVisitorSkeleton<'_, 'tcx, V> . where . V: DefIdVisitor<'tcx> + ?Sized, . { . fn visit_trait(&mut self, trait_ref: TraitRef<'tcx>) -> ControlFlow { 109 ( 0.00%) let TraitRef { def_id, substs } = trait_ref; 13,835 ( 0.00%) self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref.print_only_trait_path())?; 109 ( 0.00%) if self.def_id_visitor.shallow() { ControlFlow::CONTINUE } else { substs.visit_with(self) } . } . 1,980 ( 0.00%) fn visit_projection_ty( . &mut self, . projection: ty::ProjectionTy<'tcx>, . ) -> ControlFlow { 1,584 ( 0.00%) let (trait_ref, assoc_substs) = 396 ( 0.00%) projection.trait_ref_and_own_substs(self.def_id_visitor.tcx()); . self.visit_trait(trait_ref)?; . if self.def_id_visitor.shallow() { . ControlFlow::CONTINUE . } else { . assoc_substs.iter().try_for_each(|subst| subst.visit_with(self)) . } 1,782 ( 0.00%) } . . fn visit_predicate(&mut self, predicate: ty::Predicate<'tcx>) -> ControlFlow { 549 ( 0.00%) match predicate.kind().skip_binder() { . ty::PredicateKind::Trait(ty::TraitPredicate { . trait_ref, . constness: _, . polarity: _, . }) => self.visit_trait(trait_ref), . ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => { 96 ( 0.00%) term.visit_with(self)?; 240 ( 0.00%) self.visit_projection_ty(projection_ty) . } . ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ty, _region)) => { . ty.visit_with(self) . } . ty::PredicateKind::RegionOutlives(..) => ControlFlow::CONTINUE, . ty::PredicateKind::ConstEvaluatable(uv) . if self.def_id_visitor.tcx().features().generic_const_exprs => . { -- line 140 ---------------------------------------- -- line 157 ---------------------------------------- . ACNode::Leaf(leaf) => self.visit_const(leaf), . ACNode::Cast(_, _, ty) => self.visit_ty(ty), . ACNode::Binop(..) | ACNode::UnaryOp(..) | ACNode::FunctionCall(_, _) => { . ControlFlow::CONTINUE . } . }) . } . 8,288 ( 0.00%) fn visit_predicates( . &mut self, . predicates: ty::GenericPredicates<'tcx>, . ) -> ControlFlow { . let ty::GenericPredicates { parent: _, predicates } = predicates; . predicates.iter().try_for_each(|&(predicate, _span)| self.visit_predicate(predicate)) 9,472 ( 0.00%) } . } . . impl<'tcx, V> TypeVisitor<'tcx> for DefIdVisitorSkeleton<'_, 'tcx, V> . where . V: DefIdVisitor<'tcx> + ?Sized, . { . type BreakTy = V::BreakTy; . 1,745,495 ( 0.04%) fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow { 193,949 ( 0.00%) let tcx = self.def_id_visitor.tcx(); . // InternalSubsts are not visited here because they are visited below in `super_visit_with`. 967,301 ( 0.02%) match *ty.kind() { 54,904 ( 0.00%) ty::Adt(&ty::AdtDef { did: def_id, .. }, ..) . | ty::Foreign(def_id) . | ty::FnDef(def_id, ..) . | ty::Closure(def_id, ..) . | ty::Generator(def_id, ..) => { 246,676 ( 0.01%) self.def_id_visitor.visit_def_id(def_id, "type", &ty)?; . if self.def_id_visitor.shallow() { . return ControlFlow::CONTINUE; . } . // Default type visitor doesn't visit signatures of fn types. . // Something like `fn() -> Priv {my_func}` is considered a private type even if . // `my_func` is public, so we need to visit signatures. 56,265 ( 0.00%) if let ty::FnDef(..) = ty.kind() { . tcx.fn_sig(def_id).visit_with(self)?; . } . // Inherent static methods don't have self type in substs. . // Something like `fn() {my_method}` type of the method . // `impl Pub { pub fn my_method() {} }` is considered a private type, . // so we need to visit the self type additionally. 86,946 ( 0.00%) if let Some(assoc_item) = tcx.opt_associated_item(def_id) { 4,564 ( 0.00%) if let ty::ImplContainer(impl_def_id) = assoc_item.container { 1,110 ( 0.00%) tcx.type_of(impl_def_id).visit_with(self)?; . } . } . } 258 ( 0.00%) ty::Projection(proj) => { . if self.def_id_visitor.skip_assoc_tys() { . // Visitors searching for minimal visibility/reachability want to . // conservatively approximate associated types like `::Alias` . // as visible/reachable even if both `Type` and `Trait` are private. . // Ideally, associated types should be substituted in the same way as . // free type aliases, but this isn't done yet. . return ControlFlow::CONTINUE; . } . // This will also visit substs if necessary, so we don't need to recurse. 1,278 ( 0.00%) return self.visit_projection_ty(proj); . } 113 ( 0.00%) ty::Dynamic(predicates, ..) => { . // All traits in the list are considered the "primary" part of the type . // and are visited by shallow visitors. 925 ( 0.00%) for predicate in predicates { 806 ( 0.00%) let trait_ref = match predicate.skip_binder() { 666 ( 0.00%) ty::ExistentialPredicate::Trait(trait_ref) => trait_ref, 230 ( 0.00%) ty::ExistentialPredicate::Projection(proj) => proj.trait_ref(tcx), . ty::ExistentialPredicate::AutoTrait(def_id) => { . ty::ExistentialTraitRef { def_id, substs: InternalSubsts::empty() } . } . }; 222 ( 0.00%) let ty::ExistentialTraitRef { def_id, substs: _ } = trait_ref; 1,506 ( 0.00%) self.def_id_visitor.visit_def_id(def_id, "trait", &trait_ref)?; . } . } . ty::Opaque(def_id, ..) => { . // Skip repeated `Opaque`s to avoid infinite recursion. . if self.visited_opaque_tys.insert(def_id) { . // The intent is to treat `impl Trait1 + Trait2` identically to . // `dyn Trait1 + Trait2`. Therefore we ignore def-id of the opaque type itself . // (it either has no visibility, or its visibility is insignificant, like -- line 241 ---------------------------------------- -- line 270 ---------------------------------------- . ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => { . bug!("unexpected type: {:?}", ty) . } . } . . if self.def_id_visitor.shallow() { . ControlFlow::CONTINUE . } else { 570,503 ( 0.01%) ty.super_visit_with(self) . } 1,730,241 ( 0.04%) } . . fn visit_const(&mut self, c: &'tcx Const<'tcx>) -> ControlFlow { 14,052 ( 0.00%) self.visit_ty(c.ty)?; 2,342 ( 0.00%) let tcx = self.def_id_visitor.tcx(); 16,394 ( 0.00%) if let Ok(Some(ct)) = AbstractConst::from_const(tcx, c) { . self.visit_abstract_const_expr(tcx, ct)?; . } . ControlFlow::CONTINUE . } . } . . fn min(vis1: ty::Visibility, vis2: ty::Visibility, tcx: TyCtxt<'_>) -> ty::Visibility { 494 ( 0.00%) if vis1.is_at_least(vis2, tcx) { vis2 } else { vis1 } . } . . //////////////////////////////////////////////////////////////////////////////// . /// Visitor used to determine if pub(restricted) is used anywhere in the crate. . /// . /// This is done so that `private_in_public` warnings can be turned into hard errors . /// in crates that have been updated to use pub(restricted). . //////////////////////////////////////////////////////////////////////////////// -- line 301 ---------------------------------------- -- line 303 ---------------------------------------- . tcx: TyCtxt<'tcx>, . has_pub_restricted: bool, . } . . impl<'tcx> Visitor<'tcx> for PubRestrictedVisitor<'tcx> { . type NestedFilter = nested_filter::All; . . fn nested_visit_map(&mut self) -> Self::Map { 1,091 ( 0.00%) self.tcx.hir() . } . fn visit_vis(&mut self, vis: &'tcx hir::Visibility<'tcx>) { 2,487 ( 0.00%) self.has_pub_restricted = self.has_pub_restricted || vis.node.is_pub_restricted(); . } . } . . //////////////////////////////////////////////////////////////////////////////// . /// Visitor used to determine impl visibility and reachability. . //////////////////////////////////////////////////////////////////////////////// . . struct FindMin<'a, 'tcx, VL: VisibilityLike> { -- line 322 ---------------------------------------- -- line 336 ---------------------------------------- . true . } . fn visit_def_id( . &mut self, . def_id: DefId, . _kind: &str, . _descr: &dyn fmt::Display, . ) -> ControlFlow { 3,623 ( 0.00%) self.min = VL::new_min(self, def_id); . ControlFlow::CONTINUE . } . } . . trait VisibilityLike: Sized { . const MAX: Self; . const SHALLOW: bool = false; . fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self; . . // Returns an over-approximation (`skip_assoc_tys` = true) of visibility due to . // associated types for which we can't determine visibility precisely. 2,541 ( 0.00%) fn of_impl(def_id: LocalDefId, tcx: TyCtxt<'_>, access_levels: &AccessLevels) -> Self { 1,210 ( 0.00%) let mut find = FindMin { tcx, access_levels, min: Self::MAX }; 363 ( 0.00%) find.visit(tcx.type_of(def_id)); 1,089 ( 0.00%) if let Some(trait_ref) = tcx.impl_trait_ref(def_id) { 109 ( 0.00%) find.visit_trait(trait_ref); . } 290 ( 0.00%) find.min 2,904 ( 0.00%) } . } . impl VisibilityLike for ty::Visibility { . const MAX: Self = ty::Visibility::Public; 2,471 ( 0.00%) fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self { 1,059 ( 0.00%) min(find.tcx.visibility(def_id), find.min, find.tcx) 3,530 ( 0.00%) } . } . impl VisibilityLike for Option { . const MAX: Self = Some(AccessLevel::Public); . // Type inference is very smart sometimes. . // It can make an impl reachable even some components of its type or trait are unreachable. . // E.g. methods of `impl ReachableTrait for ReachableTy { ... }` . // can be usable from other crates (#57264). So we skip substs when calculating reachability . // and consider an impl reachable if its "shallow" type and trait are reachable. . // . // The assumption we make here is that type-inference won't let you use an impl without knowing . // both "shallow" version of its self type and "shallow" version of its trait if it exists . // (which require reaching the `DefId`s in them). . const SHALLOW: bool = true; 1,374 ( 0.00%) fn new_min(find: &FindMin<'_, '_, Self>, def_id: DefId) -> Self { . cmp::min( 1,374 ( 0.00%) if let Some(def_id) = def_id.as_local() { 484 ( 0.00%) find.access_levels.map.get(&def_id).copied() . } else { . Self::MAX . }, 1,112 ( 0.00%) find.min, . ) 1,832 ( 0.00%) } . } . . //////////////////////////////////////////////////////////////////////////////// . /// The embargo visitor, used to determine the exports of the AST. . //////////////////////////////////////////////////////////////////////////////// . . struct EmbargoVisitor<'tcx> { . tcx: TyCtxt<'tcx>, -- line 400 ---------------------------------------- -- line 422 ---------------------------------------- . . struct ReachEverythingInTheInterfaceVisitor<'a, 'tcx> { . access_level: Option, . item_def_id: LocalDefId, . ev: &'a mut EmbargoVisitor<'tcx>, . } . . impl<'tcx> EmbargoVisitor<'tcx> { 7,656 ( 0.00%) fn get(&self, def_id: LocalDefId) -> Option { . self.access_levels.map.get(&def_id).copied() 7,656 ( 0.00%) } . . fn update_with_hir_id( . &mut self, . hir_id: hir::HirId, . level: Option, . ) -> Option { 594 ( 0.00%) let def_id = self.tcx.hir().local_def_id(hir_id); . self.update(def_id, level) . } . . /// Updates node level and returns the updated level. . fn update(&mut self, def_id: LocalDefId, level: Option) -> Option { 7,720 ( 0.00%) let old_level = self.get(def_id); . // Accessibility levels can only grow. . if level > old_level { . self.access_levels.map.insert(def_id, level.unwrap()); 263 ( 0.00%) self.changed = true; . level . } else { . old_level . } . } . . fn reach( . &mut self, -- line 457 ---------------------------------------- -- line 458 ---------------------------------------- . def_id: LocalDefId, . access_level: Option, . ) -> ReachEverythingInTheInterfaceVisitor<'_, 'tcx> { . ReachEverythingInTheInterfaceVisitor { . access_level: cmp::min(access_level, Some(AccessLevel::Reachable)), . item_def_id: def_id, . ev: self, . } 2,674 ( 0.00%) } . . // We have to make sure that the items that macros might reference . // are reachable, since they might be exported transitively. . fn update_reachability_from_macro(&mut self, local_def_id: LocalDefId, md: &MacroDef) { . // Non-opaque macros cannot make other items more accessible than they already are. . 8 ( 0.00%) let hir_id = self.tcx.hir().local_def_id_to_hir_id(local_def_id); 24 ( 0.00%) let attrs = self.tcx.hir().attrs(hir_id); 56 ( 0.00%) if attr::find_transparency(attrs, md.macro_rules).0 != Transparency::Opaque { . return; . } . . let item_def_id = local_def_id.to_def_id(); . let macro_module_def_id = . ty::DefIdTree::parent(self.tcx, item_def_id).unwrap().expect_local(); . if self.tcx.hir().opt_def_kind(macro_module_def_id) != Some(DefKind::Mod) { . // The macro's parent doesn't correspond to a `mod`, return early (#63164, #65252). -- line 483 ---------------------------------------- -- line 630 ---------------------------------------- . } . . impl<'tcx> Visitor<'tcx> for EmbargoVisitor<'tcx> { . type NestedFilter = nested_filter::All; . . /// We want to visit items in the context of their containing . /// module and so forth, so supply a crate for doing a deep walk. . fn nested_visit_map(&mut self) -> Self::Map { 2,182 ( 0.00%) self.tcx.hir() . } . 8,856 ( 0.00%) fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 1,968 ( 0.00%) let item_level = match item.kind { . hir::ItemKind::Impl { .. } => { . let impl_level = 1,452 ( 0.00%) Option::::of_impl(item.def_id, self.tcx, &self.access_levels); 242 ( 0.00%) self.update(item.def_id, impl_level) . } 2,968 ( 0.00%) _ => self.get(item.def_id), . }; . . // Update levels of nested things. 5,036 ( 0.00%) match item.kind { . hir::ItemKind::Enum(ref def, _) => { 20 ( 0.00%) for variant in def.variants { 132 ( 0.00%) let variant_level = self.update_with_hir_id(variant.id, item_level); 176 ( 0.00%) if let Some(ctor_hir_id) = variant.data.ctor_hir_id() { . self.update_with_hir_id(ctor_hir_id, item_level); . } 88 ( 0.00%) for field in variant.data.fields() { 100 ( 0.00%) self.update_with_hir_id(field.hir_id, variant_level); . } . } . } . hir::ItemKind::Impl(ref impl_) => { 726 ( 0.00%) for impl_item_ref in impl_.items { 1,678 ( 0.00%) if impl_.of_trait.is_some() 416 ( 0.00%) || self.tcx.visibility(impl_item_ref.id.def_id) == ty::Visibility::Public . { 644 ( 0.00%) self.update(impl_item_ref.id.def_id, item_level); . } . } . } 12 ( 0.00%) hir::ItemKind::Trait(.., trait_item_refs) => { . for trait_item_ref in trait_item_refs { 4 ( 0.00%) self.update(trait_item_ref.id.def_id, item_level); . } . } . hir::ItemKind::Struct(ref def, _) | hir::ItemKind::Union(ref def, _) => { 96 ( 0.00%) if let Some(ctor_hir_id) = def.ctor_hir_id() { . self.update_with_hir_id(ctor_hir_id, item_level); . } 48 ( 0.00%) for field in def.fields() { 344 ( 0.00%) if field.vis.node.is_pub() { 24 ( 0.00%) self.update_with_hir_id(field.hir_id, item_level); . } . } . } . hir::ItemKind::Macro(ref macro_def) => { 16 ( 0.00%) self.update_reachability_from_macro(item.def_id, macro_def); . } . hir::ItemKind::ForeignMod { items, .. } => { . for foreign_item in items { . if self.tcx.visibility(foreign_item.id.def_id) == ty::Visibility::Public { . self.update(foreign_item.id.def_id, item_level); . } . } . } -- line 697 ---------------------------------------- -- line 704 ---------------------------------------- . | hir::ItemKind::TyAlias(..) . | hir::ItemKind::Mod(..) . | hir::ItemKind::TraitAlias(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::ExternCrate(..) => {} . } . . // Mark all items in interfaces of reachable items as reachable. 4,920 ( 0.00%) match item.kind { . // The interface is empty. . hir::ItemKind::Macro(..) | hir::ItemKind::ExternCrate(..) => {} . // All nested items are checked by `visit_item`. . hir::ItemKind::Mod(..) => {} . // Handled in the access level of in rustc_resolve . hir::ItemKind::Use(..) => {} . // The interface is empty. . hir::ItemKind::GlobalAsm(..) => {} -- line 720 ---------------------------------------- -- line 732 ---------------------------------------- . self.reach(item.def_id, exist_level).generics().predicates().ty(); . } . } . // Visit everything. . hir::ItemKind::Const(..) . | hir::ItemKind::Static(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::TyAlias(..) => { 388 ( 0.00%) if item_level.is_some() { 372 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates().ty(); . } . } 8 ( 0.00%) hir::ItemKind::Trait(.., trait_item_refs) => { 4 ( 0.00%) if item_level.is_some() { 32 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates(); . . for trait_item_ref in trait_item_refs { 4 ( 0.00%) let mut reach = self.reach(trait_item_ref.id.def_id, item_level); 8 ( 0.00%) reach.generics().predicates(); . 2 ( 0.00%) if trait_item_ref.kind == AssocItemKind::Type . && !trait_item_ref.defaultness.has_value() . { . // No type to visit. . } else { 4 ( 0.00%) reach.ty(); . } . } . } . } . hir::ItemKind::TraitAlias(..) => { . if item_level.is_some() { . self.reach(item.def_id, item_level).generics().predicates(); . } . } . // Visit everything except for private impl items. . hir::ItemKind::Impl(ref impl_) => { 242 ( 0.00%) if item_level.is_some() { 2,320 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates().ty().trait_ref(); . 232 ( 0.00%) for impl_item_ref in impl_.items { 1,092 ( 0.00%) let impl_item_level = self.get(impl_item_ref.id.def_id); 1,432 ( 0.00%) if impl_item_level.is_some() { 2,940 ( 0.00%) self.reach(impl_item_ref.id.def_id, impl_item_level) . .generics() . .predicates() . .ty(); . } . } . } . } . . // Visit everything, but enum variants have their own levels. . hir::ItemKind::Enum(ref def, _) => { 20 ( 0.00%) if item_level.is_some() { 128 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates(); . } 20 ( 0.00%) for variant in def.variants { 396 ( 0.00%) let variant_level = self.get(self.tcx.hir().local_def_id(variant.id)); 44 ( 0.00%) if variant_level.is_some() { 72 ( 0.00%) for field in variant.data.fields() { 216 ( 0.00%) self.reach(self.tcx.hir().local_def_id(field.hir_id), variant_level) . .ty(); . } . // Corner case: if the variant is reachable, but its . // enum is not, make the enum reachable as well. 72 ( 0.00%) self.update(item.def_id, variant_level); . } . } . } . // Visit everything, but foreign items have their own levels. . hir::ItemKind::ForeignMod { items, .. } => { . for foreign_item in items { . let foreign_item_level = self.get(foreign_item.id.def_id); . if foreign_item_level.is_some() { -- line 806 ---------------------------------------- -- line 808 ---------------------------------------- . .generics() . .predicates() . .ty(); . } . } . } . // Visit everything except for private fields. . hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { 24 ( 0.00%) if item_level.is_some() { 176 ( 0.00%) self.reach(item.def_id, item_level).generics().predicates(); 44 ( 0.00%) for field in struct_def.fields() { 560 ( 0.00%) let def_id = self.tcx.hir().local_def_id(field.hir_id); 240 ( 0.00%) let field_level = self.get(def_id); 80 ( 0.00%) if field_level.is_some() { 30 ( 0.00%) self.reach(def_id, field_level).ty(); . } . } . } . } . } . . let orig_level = mem::replace(&mut self.prev_level, item_level); 2,952 ( 0.00%) intravisit::walk_item(self, item); 984 ( 0.00%) self.prev_level = orig_level; 7,872 ( 0.00%) } . . fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) { . // Blocks can have public items, for example impls, but they always . // start as completely private regardless of publicity of a function, . // constant, type, field, etc., in which this block resides. . let orig_level = mem::replace(&mut self.prev_level, None); . intravisit::walk_block(self, b); . self.prev_level = orig_level; . } . } . . impl ReachEverythingInTheInterfaceVisitor<'_, '_> { 5,292 ( 0.00%) fn generics(&mut self) -> &mut Self { 3,024 ( 0.00%) for param in &self.ev.tcx.generics_of(self.item_def_id).params { 2,468 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => {} 196 ( 0.00%) GenericParamDefKind::Type { has_default, .. } => { 196 ( 0.00%) if has_default { . self.visit(self.ev.tcx.type_of(param.def_id)); . } . } . GenericParamDefKind::Const { has_default, .. } => { . self.visit(self.ev.tcx.type_of(param.def_id)); . if has_default { . self.visit(self.ev.tcx.const_param_default(param.def_id)); . } . } . } . } . self 6,804 ( 0.00%) } . 3,780 ( 0.00%) fn predicates(&mut self) -> &mut Self { 2,268 ( 0.00%) self.visit_predicates(self.ev.tcx.predicates_of(self.item_def_id)); . self 4,536 ( 0.00%) } . 3,600 ( 0.00%) fn ty(&mut self) -> &mut Self { 2,184 ( 0.00%) self.visit(self.ev.tcx.type_of(self.item_def_id)); . self 4,320 ( 0.00%) } . . fn trait_ref(&mut self) -> &mut Self { 1,392 ( 0.00%) if let Some(trait_ref) = self.ev.tcx.impl_trait_ref(self.item_def_id) { . self.visit_trait(trait_ref); . } . self . } . } . . impl<'tcx> DefIdVisitor<'tcx> for ReachEverythingInTheInterfaceVisitor<'_, 'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 14,156 ( 0.00%) self.ev.tcx . } 15,680 ( 0.00%) fn visit_def_id( . &mut self, . def_id: DefId, . _kind: &str, . _descr: &dyn fmt::Display, . ) -> ControlFlow { 9,412 ( 0.00%) if let Some(def_id) = def_id.as_local() { 7,543 ( 0.00%) if let (ty::Visibility::Public, _) | (_, Some(AccessLevel::ReachableFromImplTrait)) = 1,914 ( 0.00%) (self.tcx().visibility(def_id.to_def_id()), self.access_level) . { . self.ev.update(def_id, self.access_level); . } . } . ControlFlow::CONTINUE 21,952 ( 0.00%) } . } . . ////////////////////////////////////////////////////////////////////////////////////// . /// Name privacy visitor, checks privacy and reports violations. . /// Most of name privacy checks are performed during the main resolution phase, . /// or later in type checking when field accesses and associated items are resolved. . /// This pass performs remaining checks for fields in struct expressions and patterns. . ////////////////////////////////////////////////////////////////////////////////////// -- line 909 ---------------------------------------- -- line 920 ---------------------------------------- . /// `Expr` or `Pat` nodes (they are guaranteed to be found only in bodies). . #[track_caller] . fn typeck_results(&self) -> &'tcx ty::TypeckResults<'tcx> { . self.maybe_typeck_results . .expect("`NamePrivacyVisitor::typeck_results` called outside of body") . } . . // Checks that a field in a struct constructor (expression or pattern) is accessible. 11,470 ( 0.00%) fn check_field( . &mut self, . use_ctxt: Span, // syntax context of the field name at the use site . span: Span, // span of the field pattern, e.g., `x: 0` . def: &'tcx ty::AdtDef, // definition of the struct or enum . field: &'tcx ty::FieldDef, . in_update_syntax: bool, . ) { 2,294 ( 0.00%) if def.is_enum() { . return; . } . . // definition of the field . let ident = Ident::new(kw::Empty, use_ctxt); 2,066 ( 0.00%) let hir_id = self.tcx.hir().local_def_id_to_hir_id(self.current_item); 7,231 ( 0.00%) let def_id = self.tcx.adjust_ident_and_get_scope(ident, def.did, hir_id).1; 1,033 ( 0.00%) if !field.vis.is_accessible_from(def_id, self.tcx) { . let label = if in_update_syntax { . format!("field `{}` is private", field.name) . } else { . "private field".to_string() . }; . . struct_span_err!( . self.tcx.sess, -- line 952 ---------------------------------------- -- line 955 ---------------------------------------- . "field `{}` of {} `{}` is private", . field.name, . def.variant_descr(), . self.tcx.def_path_str(def.did) . ) . .span_label(span, label) . .emit(); . } 9,176 ( 0.00%) } . } . . impl<'tcx> Visitor<'tcx> for NamePrivacyVisitor<'tcx> { . type NestedFilter = nested_filter::All; . . /// We want to visit items in the context of their containing . /// module and so forth, so supply a crate for doing a deep walk. . fn nested_visit_map(&mut self) -> Self::Map { 671 ( 0.00%) self.tcx.hir() . } . . fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) { . // Don't visit nested modules, since we run a separate visitor walk . // for each module in `privacy_access_levels` . } . . fn visit_nested_body(&mut self, body: hir::BodyId) { . let old_maybe_typeck_results = 2,139 ( 0.00%) self.maybe_typeck_results.replace(self.tcx.typeck_body(body)); 2,406 ( 0.00%) let body = self.tcx.hir().body(body); . self.visit_body(body); 403 ( 0.00%) self.maybe_typeck_results = old_maybe_typeck_results; . } . . fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 492 ( 0.00%) let orig_current_item = mem::replace(&mut self.current_item, item.def_id); 1,457 ( 0.00%) intravisit::walk_item(self, item); 492 ( 0.00%) self.current_item = orig_current_item; . } . 1,310,202 ( 0.03%) fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { 291,156 ( 0.01%) if let hir::ExprKind::Struct(qpath, fields, ref base) = expr.kind { 1,398 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, expr.hir_id); 699 ( 0.00%) let adt = self.typeck_results().expr_ty(expr).ty_adt_def().unwrap(); 2,097 ( 0.00%) let variant = adt.variant_of_res(res); 932 ( 0.00%) if let Some(base) = *base { . // If the expression uses FRU we need to make sure all the unmentioned fields . // are checked for privacy (RFC 736). Rather than computing the set of . // unmentioned fields, just check them all. . for (vf_index, variant_field) in variant.fields.iter().enumerate() { . let field = fields.iter().find(|f| { . self.tcx.field_index(f.hir_id, self.typeck_results()) == vf_index . }); . let (use_ctxt, span) = match field { . Some(field) => (field.ident.span, field.span), . None => (base.span, base.span), . }; . self.check_field(use_ctxt, span, adt, variant_field, true); . } . } else { . for field in fields { 976 ( 0.00%) let use_ctxt = field.ident.span; 6,045 ( 0.00%) let index = self.tcx.field_index(field.hir_id, self.typeck_results()); 10,736 ( 0.00%) self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); . } . } . } . 1,455,780 ( 0.03%) intravisit::walk_expr(self, expr); . } . 10,776 ( 0.00%) fn visit_pat(&mut self, pat: &'tcx hir::Pat<'tcx>) { 2,792 ( 0.00%) if let PatKind::Struct(ref qpath, fields, _) = pat.kind { 686 ( 0.00%) let res = self.typeck_results().qpath_res(qpath, pat.hir_id); 392 ( 0.00%) let adt = self.typeck_results().pat_ty(pat).ty_adt_def().unwrap(); 784 ( 0.00%) let variant = adt.variant_of_res(res); . for field in fields { 171 ( 0.00%) let use_ctxt = field.ident.span; 1,107 ( 0.00%) let index = self.tcx.field_index(field.hir_id, self.typeck_results()); 1,710 ( 0.00%) self.check_field(use_ctxt, field.span, adt, &variant.fields[index], false); . } . } . 12,123 ( 0.00%) intravisit::walk_pat(self, pat); . } . } . . //////////////////////////////////////////////////////////////////////////////////////////// . /// Type privacy visitor, checks types for privacy and reports violations. . /// Both explicitly written types and inferred types of expressions and patterns are checked. . /// Checks are performed on "semantic" types regardless of names and their hygiene. . //////////////////////////////////////////////////////////////////////////////////////////// -- line 1045 ---------------------------------------- -- line 1061 ---------------------------------------- . .expect("`TypePrivacyVisitor::typeck_results` called outside of body") . } . . fn item_is_accessible(&self, did: DefId) -> bool { . self.tcx.visibility(did).is_accessible_from(self.current_item.to_def_id(), self.tcx) . } . . // Take node-id of an expression or pattern and check its type for privacy. 1,030,932 ( 0.02%) fn check_expr_pat_type(&mut self, id: hir::HirId, span: Span) -> bool { 147,276 ( 0.00%) self.span = span; 147,276 ( 0.00%) let typeck_results = self.typeck_results(); . let result: ControlFlow<()> = try { 589,104 ( 0.01%) self.visit(typeck_results.node_type(id))?; 1,178,208 ( 0.02%) self.visit(typeck_results.node_substs(id))?; 1,325,484 ( 0.03%) if let Some(adjustments) = typeck_results.adjustments().get(id) { . adjustments.iter().try_for_each(|adjustment| self.visit(adjustment.target))?; . } . }; . result.is_break() 1,178,208 ( 0.02%) } . . fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool { 32,034 ( 0.00%) let is_error = !self.item_is_accessible(def_id); . if is_error { . self.tcx . .sess . .struct_span_err(self.span, &format!("{} `{}` is private", kind, descr)) . .span_label(self.span, &format!("private {}", kind)) . .emit(); . } . is_error -- line 1091 ---------------------------------------- -- line 1093 ---------------------------------------- . } . . impl<'tcx> Visitor<'tcx> for TypePrivacyVisitor<'tcx> { . type NestedFilter = nested_filter::All; . . /// We want to visit items in the context of their containing . /// module and so forth, so supply a crate for doing a deep walk. . fn nested_visit_map(&mut self) -> Self::Map { 671 ( 0.00%) self.tcx.hir() . } . . fn visit_mod(&mut self, _m: &'tcx hir::Mod<'tcx>, _s: Span, _n: hir::HirId) { . // Don't visit nested modules, since we run a separate visitor walk . // for each module in `privacy_access_levels` . } . 4,010 ( 0.00%) fn visit_nested_body(&mut self, body: hir::BodyId) { . let old_maybe_typeck_results = 1,203 ( 0.00%) self.maybe_typeck_results.replace(self.tcx.typeck_body(body)); 2,406 ( 0.00%) let body = self.tcx.hir().body(body); . self.visit_body(body); 401 ( 0.00%) self.maybe_typeck_results = old_maybe_typeck_results; 3,208 ( 0.00%) } . . fn visit_generic_arg(&mut self, generic_arg: &'tcx hir::GenericArg<'tcx>) { 3,614 ( 0.00%) match generic_arg { 1,392 ( 0.00%) hir::GenericArg::Type(t) => self.visit_ty(t), . hir::GenericArg::Infer(inf) => self.visit_infer(inf), . hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {} . } . } . 14,245 ( 0.00%) fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) { 4,070 ( 0.00%) self.span = hir_ty.span; 6,105 ( 0.00%) if let Some(typeck_results) = self.maybe_typeck_results { . // Types in bodies. 882 ( 0.00%) if self.visit(typeck_results.node_type(hir_ty.hir_id)).is_break() { . return; . } . } else { . // Types in signatures. . // FIXME: This is very ineffective. Ideally each HIR type should be converted . // into a semantic type only once and the result should be cached somehow. 5,223 ( 0.00%) if self.visit(rustc_typeck::hir_ty_to_ty(self.tcx, hir_ty)).is_break() { . return; . } . } . 6,105 ( 0.00%) intravisit::walk_ty(self, hir_ty); 12,210 ( 0.00%) } . . fn visit_infer(&mut self, inf: &'tcx hir::InferArg) { . self.span = inf.span; . if let Some(typeck_results) = self.maybe_typeck_results { . if let Some(ty) = typeck_results.node_type_opt(inf.hir_id) { . if self.visit(ty).is_break() { . return; . } -- line 1150 ---------------------------------------- -- line 1152 ---------------------------------------- . // We don't do anything for const infers here. . } . } else { . bug!("visit_infer without typeck_results"); . } . intravisit::walk_inf(self, inf); . } . 1,768 ( 0.00%) fn visit_trait_ref(&mut self, trait_ref: &'tcx hir::TraitRef<'tcx>) { 663 ( 0.00%) self.span = trait_ref.path.span; 221 ( 0.00%) if self.maybe_typeck_results.is_none() { . // Avoid calling `hir_trait_to_predicates` in bodies, it will ICE. . // The traits' privacy in bodies is already checked as a part of trait object types. 221 ( 0.00%) let bounds = rustc_typeck::hir_trait_to_predicates( 221 ( 0.00%) self.tcx, . trait_ref, . // NOTE: This isn't really right, but the actual type doesn't matter here. It's . // just required by `ty::TraitRef`. 663 ( 0.00%) self.tcx.types.never, . ); . 1,989 ( 0.00%) for (trait_predicate, _, _) in bounds.trait_bounds { 1,547 ( 0.00%) if self.visit_trait(trait_predicate.skip_binder()).is_break() { . return; . } . } . 1,473 ( 0.00%) for (poly_predicate, _) in bounds.projection_bounds { 126 ( 0.00%) let pred = poly_predicate.skip_binder(); . let poly_pred_term = self.visit(pred.term); 84 ( 0.00%) if poly_pred_term.is_break() . || self.visit_projection_ty(pred.projection_ty).is_break() . { . return; . } . } . } . . intravisit::walk_trait_ref(self, trait_ref); 1,768 ( 0.00%) } . . // Check types of expressions 1,310,202 ( 0.03%) fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { 1,310,202 ( 0.03%) if self.check_expr_pat_type(expr.hir_id, expr.span) { . // Do not check nested expressions if the error already happened. . return; . } 1,017,048 ( 0.02%) match expr.kind { 179 ( 0.00%) hir::ExprKind::Assign(_, rhs, _) | hir::ExprKind::Match(rhs, ..) => { . // Do not report duplicate errors for `x = y` and `match x { ... }`. 1,029 ( 0.00%) if self.check_expr_pat_type(rhs.hir_id, rhs.span) { . return; . } . } 442 ( 0.00%) hir::ExprKind::MethodCall(segment, ..) => { . // Method calls have to be checked specially. 884 ( 0.00%) self.span = segment.ident.span; 2,652 ( 0.00%) if let Some(def_id) = self.typeck_results().type_dependent_def_id(expr.hir_id) { 1,326 ( 0.00%) if self.visit(self.tcx.type_of(def_id)).is_break() { . return; . } . } else { . self.tcx . .sess . .delay_span_bug(expr.span, "no type-dependent def for method call"); . } . } . _ => {} . } . 436,734 ( 0.01%) intravisit::walk_expr(self, expr); 1,164,624 ( 0.02%) } . . // Prohibit access to associated items with insufficient nominal visibility. . // . // Additionally, until better reachability analysis for macros 2.0 is available, . // we prohibit access to private statics from other crates, this allows to give . // more code internal visibility at link time. (Access to private functions . // is already prohibited by type privacy for function types.) 43,480 ( 0.00%) fn visit_qpath(&mut self, qpath: &'tcx hir::QPath<'tcx>, id: hir::HirId, span: Span) { 8,696 ( 0.00%) let def = match qpath { 12,180 ( 0.00%) hir::QPath::Resolved(_, path) => match path.res { 12,060 ( 0.00%) Res::Def(kind, def_id) => Some((kind, def_id)), . _ => None, . }, 288 ( 0.00%) hir::QPath::TypeRelative(..) | hir::QPath::LangItem(..) => self . .maybe_typeck_results 2,538 ( 0.00%) .and_then(|typeck_results| typeck_results.type_dependent_def(id)), . }; . let def = def.filter(|(kind, _)| { 4,584 ( 0.00%) matches!( . kind, . DefKind::AssocFn | DefKind::AssocConst | DefKind::AssocTy | DefKind::Static . ) . }); . if let Some((kind, def_id)) = def { . let is_local_static = 1,328 ( 0.00%) if let DefKind::Static = kind { def_id.is_local() } else { false }; 720 ( 0.00%) if !self.item_is_accessible(def_id) && !is_local_static { . let sess = self.tcx.sess; . let sm = sess.source_map(); . let name = match qpath { . hir::QPath::Resolved(..) | hir::QPath::LangItem(..) => { . sm.span_to_snippet(qpath.span()).ok() . } . hir::QPath::TypeRelative(_, segment) => Some(segment.ident.to_string()), . }; -- line 1258 ---------------------------------------- -- line 1263 ---------------------------------------- . }; . sess.struct_span_err(span, &msg) . .span_label(span, &format!("private {}", kind)) . .emit(); . return; . } . } . 47,828 ( 0.00%) intravisit::walk_qpath(self, qpath, id, span); . } . . // Check types of patterns. . fn visit_pat(&mut self, pattern: &'tcx hir::Pat<'tcx>) { 8,676 ( 0.00%) if self.check_expr_pat_type(pattern.hir_id, pattern.span) { . // Do not check nested patterns if the error already happened. . return; . } . 4,632 ( 0.00%) intravisit::walk_pat(self, pattern); . } . 1,110 ( 0.00%) fn visit_local(&mut self, local: &'tcx hir::Local<'tcx>) { 666 ( 0.00%) if let Some(init) = local.init { 1,428 ( 0.00%) if self.check_expr_pat_type(init.hir_id, init.span) { . // Do not report duplicate errors for `let x = y`. . return; . } . } . . intravisit::walk_local(self, local); 816 ( 0.00%) } . . // Check types in item interfaces. . fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 492 ( 0.00%) let orig_current_item = mem::replace(&mut self.current_item, item.def_id); . let old_maybe_typeck_results = self.maybe_typeck_results.take(); 1,457 ( 0.00%) intravisit::walk_item(self, item); 492 ( 0.00%) self.maybe_typeck_results = old_maybe_typeck_results; 494 ( 0.00%) self.current_item = orig_current_item; . } . } . . impl<'tcx> DefIdVisitor<'tcx> for TypePrivacyVisitor<'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 374,440 ( 0.01%) self.tcx . } 240,255 ( 0.00%) fn visit_def_id( . &mut self, . def_id: DefId, . kind: &str, . descr: &dyn fmt::Display, . ) -> ControlFlow { . if self.check_def_id(def_id, kind, descr) { . ControlFlow::BREAK . } else { . ControlFlow::CONTINUE . } 144,153 ( 0.00%) } . } . . /////////////////////////////////////////////////////////////////////////////// . /// Obsolete visitors for checking for private items in public interfaces. . /// These visitors are supposed to be kept in frozen state and produce an . /// "old error node set". For backward compatibility the new visitor reports . /// warnings instead of hard errors when the erroneous node is not in this old set. . /////////////////////////////////////////////////////////////////////////////// -- line 1328 ---------------------------------------- -- line 1342 ---------------------------------------- . /// Whether we've recurred at all (i.e., if we're pointing at the . /// first type on which `visit_ty` was called). . at_outer_type: bool, . /// Whether that first type is a public path. . outer_type_is_public_path: bool, . } . . impl<'a, 'tcx> ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { 785 ( 0.00%) fn path_is_private_type(&self, path: &hir::Path<'_>) -> bool { 2,424 ( 0.00%) let did = match path.res { . Res::PrimTy(..) | Res::SelfTy(..) | Res::Err => return false, 2,994 ( 0.00%) res => res.def_id(), . }; . . // A path can only be private if: . // it's in this crate... 499 ( 0.00%) if let Some(did) = did.as_local() { . // .. and it corresponds to a private type in the AST (this returns . // `None` for type parameters). 1,603 ( 0.00%) match self.tcx.hir().find(self.tcx.hir().local_def_id_to_hir_id(did)) { 804 ( 0.00%) Some(Node::Item(item)) => !item.vis.node.is_pub(), . Some(_) | None => false, . } . } else { . false . } 1,570 ( 0.00%) } . . fn trait_is_public(&self, trait_id: LocalDefId) -> bool { . // FIXME: this would preferably be using `exported_items`, but all . // traits are exported currently (see `EmbargoVisitor.exported_trait`). . self.access_levels.is_public(trait_id) . } . . fn check_generic_bound(&mut self, bound: &hir::GenericBound<'_>) { 116 ( 0.00%) if let hir::GenericBound::Trait(ref trait_ref, _) = *bound { 64 ( 0.00%) if self.path_is_private_type(trait_ref.trait_ref.path) { . self.old_error_set.insert(trait_ref.trait_ref.hir_ref_id); . } . } . } . . fn item_is_public(&self, def_id: LocalDefId, vis: &hir::Visibility<'_>) -> bool { 567 ( 0.00%) self.access_levels.is_reachable(def_id) || vis.node.is_pub() . } . } . . impl<'a, 'b, 'tcx, 'v> Visitor<'v> for ObsoleteCheckTypeForPrivatenessVisitor<'a, 'b, 'tcx> { . fn visit_generic_arg(&mut self, generic_arg: &'v hir::GenericArg<'v>) { 606 ( 0.00%) match generic_arg { . hir::GenericArg::Type(t) => self.visit_ty(t), . hir::GenericArg::Infer(inf) => self.visit_ty(&inf.to_ty()), . hir::GenericArg::Lifetime(_) | hir::GenericArg::Const(_) => {} . } . } . . fn visit_ty(&mut self, ty: &hir::Ty<'_>) { 915 ( 0.00%) if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = ty.kind { 732 ( 0.00%) if self.inner.path_is_private_type(path) { . self.contains_private = true; . // Found what we're looking for, so let's stop working. . return; . } . } . if let hir::TyKind::Path(_) = ty.kind { 124 ( 0.00%) if self.at_outer_type { 120 ( 0.00%) self.outer_type_is_public_path = true; . } . } 302 ( 0.00%) self.at_outer_type = false; 364 ( 0.00%) intravisit::walk_ty(self, ty) 480 ( 0.00%) } . . // Don't want to recurse into `[, .. expr]`. . fn visit_expr(&mut self, _: &hir::Expr<'_>) {} . } . . impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { . type NestedFilter = nested_filter::All; . . /// We want to visit items in the context of their containing . /// module and so forth, so supply a crate for doing a deep walk. . fn nested_visit_map(&mut self) -> Self::Map { 740 ( 0.00%) self.tcx.hir() . } . 4,419 ( 0.00%) fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 1,964 ( 0.00%) match item.kind { . // Contents of a private mod can be re-exported, so we need . // to check internals. . hir::ItemKind::Mod(_) => {} . . // An `extern {}` doesn't introduce a new privacy . // namespace (the contents have their own privacies). . hir::ItemKind::ForeignMod { .. } => {} . 4 ( 0.00%) hir::ItemKind::Trait(.., bounds, _) => { 10 ( 0.00%) if !self.trait_is_public(item.def_id) { . return; . } . . for bound in bounds.iter() { . self.check_generic_bound(bound) . } . } . -- line 1447 ---------------------------------------- -- line 1454 ---------------------------------------- . // `impl [... for] Private` is never visible. . let self_contains_private; . // `impl [... for] Public<...>`, but not `impl [... for] . // Vec` or `(Public,)`, etc. . let self_is_public_path; . . // Check the properties of the `Self` type: . { 484 ( 0.00%) let mut visitor = ObsoleteCheckTypeForPrivatenessVisitor { . inner: self, . contains_private: false, . at_outer_type: true, . outer_type_is_public_path: false, . }; 121 ( 0.00%) visitor.visit_ty(impl_.self_ty); . self_contains_private = visitor.contains_private; . self_is_public_path = visitor.outer_type_is_public_path; . } . . // Miscellaneous info about the impl: . . // `true` iff this is `impl Private for ...`. . let not_private_trait = impl_.of_trait.as_ref().map_or( . true, // no trait counts as public trait . |tr| { 327 ( 0.00%) if let Some(def_id) = tr.path.res.def_id().as_local() { 3 ( 0.00%) self.trait_is_public(def_id) . } else { . true // external traits must be public . } . }, . ); . . // `true` iff this is a trait impl or at least one method is public. . // . // `impl Public { $( fn ...() {} )* }` is not visible. . // . // This is required over just using the methods' privacy . // directly because we might have `impl> ...`, . // and we shouldn't warn about the generics if all the methods . // are private (because `T` won't be visible externally). . let trait_or_some_public_method = impl_.of_trait.is_some() 12 ( 0.00%) || impl_.items.iter().any(|impl_item_ref| { 92 ( 0.00%) let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); 106 ( 0.00%) match impl_item.kind { . hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) => { . self.access_levels.is_reachable(impl_item_ref.id.def_id) . } . hir::ImplItemKind::TyAlias(_) => false, . } . }); . 238 ( 0.00%) if !self_contains_private && not_private_trait && trait_or_some_public_method { . intravisit::walk_generics(self, &impl_.generics); . 236 ( 0.00%) match impl_.of_trait { . None => { 10 ( 0.00%) for impl_item_ref in impl_.items { . // This is where we choose whether to walk down . // further into the impl to check its items. We . // should only walk into public items so that we . // don't erroneously report errors for private . // types in private items. 558 ( 0.00%) let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); 515 ( 0.00%) match impl_item.kind { . hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) 288 ( 0.00%) if self 93 ( 0.00%) .item_is_public(impl_item.def_id, &impl_item.vis) => . { . intravisit::walk_impl_item(self, impl_item) . } . hir::ImplItemKind::TyAlias(..) => { . intravisit::walk_impl_item(self, impl_item) . } . _ => {} . } -- line 1529 ---------------------------------------- -- line 1538 ---------------------------------------- . // . // Those in 1. can only occur if the trait is in . // this crate and will've been warned about on the . // trait definition (there's no need to warn twice . // so we don't check the methods). . // . // Those in 2. are warned via walk_generics and this . // call here. 324 ( 0.00%) intravisit::walk_path(self, tr.path); . . // Those in 3. are warned with this call. 108 ( 0.00%) for impl_item_ref in impl_.items { 460 ( 0.00%) let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); 757 ( 0.00%) if let hir::ImplItemKind::TyAlias(ty) = impl_item.kind { . self.visit_ty(ty); . } . } . } . } 9 ( 0.00%) } else if impl_.of_trait.is_none() && self_is_public_path { . // `impl Public { ... }`. Any public static . // methods will be visible as `Public::foo`. . let mut found_pub_static = false; 2 ( 0.00%) for impl_item_ref in impl_.items { 44 ( 0.00%) if self.access_levels.is_reachable(impl_item_ref.id.def_id) 22 ( 0.00%) || self.tcx.visibility(impl_item_ref.id.def_id) . == ty::Visibility::Public . { 45 ( 0.00%) let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); 116 ( 0.00%) match impl_item_ref.kind { . AssocItemKind::Const => { . found_pub_static = true; . intravisit::walk_impl_item(self, impl_item); . } . AssocItemKind::Fn { has_self: false } => { . found_pub_static = true; . intravisit::walk_impl_item(self, impl_item); . } . _ => {} . } . } . } 4 ( 0.00%) if found_pub_static { 3 ( 0.00%) intravisit::walk_generics(self, &impl_.generics) . } . } . return; . } . . // `type ... = ...;` can contain private types, because . // we're introducing a new name. . hir::ItemKind::TyAlias(..) => return, . . // Not at all public, so we don't care. 1,951 ( 0.00%) _ if !self.item_is_public(item.def_id, &item.vis) => { . return; . } . . _ => {} . } . . // We've carefully constructed it so that if we're here, then . // any `visit_ty`'s will be called on things that are in . // public signatures, i.e., things that we're interested in for . // this visitor. 2,490 ( 0.00%) intravisit::walk_item(self, item); 1,936 ( 0.00%) } . 1,424 ( 0.00%) fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { . for param in generics.params { 43 ( 0.00%) for bound in param.bounds { . self.check_generic_bound(bound); . } . } 178 ( 0.00%) for predicate in generics.where_clause.predicates { 42 ( 0.00%) match predicate { . hir::WherePredicate::BoundPredicate(bound_pred) => { 14 ( 0.00%) for bound in bound_pred.bounds.iter() { . self.check_generic_bound(bound) . } . } . hir::WherePredicate::RegionPredicate(_) => {} . hir::WherePredicate::EqPredicate(eq_pred) => { . self.visit_ty(eq_pred.rhs_ty); . } . } . } 1,424 ( 0.00%) } . . fn visit_foreign_item(&mut self, item: &'tcx hir::ForeignItem<'tcx>) { . if self.access_levels.is_reachable(item.def_id) { . intravisit::walk_foreign_item(self, item) . } . } . . fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) { 2,597 ( 0.00%) if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = t.kind { 1,844 ( 0.00%) if self.path_is_private_type(path) { . self.old_error_set.insert(t.hir_id); . } . } 3,785 ( 0.00%) intravisit::walk_ty(self, t) . } . 160 ( 0.00%) fn visit_variant( . &mut self, . v: &'tcx hir::Variant<'tcx>, . g: &'tcx hir::Generics<'tcx>, . item_id: hir::HirId, . ) { 198 ( 0.00%) if self.access_levels.is_reachable(self.tcx.hir().local_def_id(v.id)) { 18 ( 0.00%) self.in_variant = true; . intravisit::walk_variant(self, v, g, item_id); 18 ( 0.00%) self.in_variant = false; . } 140 ( 0.00%) } . 275 ( 0.00%) fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) { 324 ( 0.00%) if s.vis.node.is_pub() || self.in_variant { . intravisit::walk_field_def(self, s); . } 160 ( 0.00%) } . . // We don't need to introspect into these at all: an . // expression/block context can't possibly contain exported things. . // (Making them no-ops stops us from traversing the whole AST without . // having to be super careful about our `walk_...` calls above.) . fn visit_block(&mut self, _: &'tcx hir::Block<'tcx>) {} . fn visit_expr(&mut self, _: &'tcx hir::Expr<'tcx>) {} . } -- line 1667 ---------------------------------------- -- line 1679 ---------------------------------------- . /// The visitor checks that each component type is at least this visible. . required_visibility: ty::Visibility, . has_pub_restricted: bool, . has_old_errors: bool, . in_assoc_ty: bool, . } . . impl SearchInterfaceForPrivateItemsVisitor<'_> { 2,996 ( 0.00%) fn generics(&mut self) -> &mut Self { 1,284 ( 0.00%) for param in &self.tcx.generics_of(self.item_def_id).params { 563 ( 0.00%) match param.kind { . GenericParamDefKind::Lifetime => {} 64 ( 0.00%) GenericParamDefKind::Type { has_default, .. } => { 64 ( 0.00%) if has_default { . self.visit(self.tcx.type_of(param.def_id)); . } . } . // FIXME(generic_const_exprs): May want to look inside const here . GenericParamDefKind::Const { .. } => { . self.visit(self.tcx.type_of(param.def_id)); . } . } . } . self 3,424 ( 0.00%) } . 2,140 ( 0.00%) fn predicates(&mut self) -> &mut Self { . // N.B., we use `explicit_predicates_of` and not `predicates_of` . // because we don't want to report privacy errors due to where . // clauses that the compiler inferred. We only want to . // consider the ones that the user wrote. This is important . // for the inferred outlives rules; see . // `src/test/ui/rfc-2093-infer-outlives/privacy.rs`. 856 ( 0.00%) self.visit_predicates(self.tcx.explicit_predicates_of(self.item_def_id)); . self 2,568 ( 0.00%) } . . fn bounds(&mut self) -> &mut Self { . self.visit_predicates(ty::GenericPredicates { . parent: None, . predicates: self.tcx.explicit_item_bounds(self.item_def_id), . }); . self . } . 2,270 ( 0.00%) fn ty(&mut self) -> &mut Self { 908 ( 0.00%) self.visit(self.tcx.type_of(self.item_def_id)); . self 2,270 ( 0.00%) } . . fn check_def_id(&mut self, def_id: DefId, kind: &str, descr: &dyn fmt::Display) -> bool { 7,415 ( 0.00%) if self.leaks_private_dep(def_id) { . self.tcx.struct_span_lint_hir( . lint::builtin::EXPORTED_PRIVATE_DEPENDENCIES, . self.tcx.hir().local_def_id_to_hir_id(self.item_def_id), . self.tcx.def_span(self.item_def_id.to_def_id()), . |lint| { . lint.build(&format!( . "{} `{}` from private dependency '{}' in public \ . interface", -- line 1738 ---------------------------------------- -- line 1740 ---------------------------------------- . descr, . self.tcx.crate_name(def_id.krate) . )) . .emit() . }, . ); . } . 3,316 ( 0.00%) let hir_id = match def_id.as_local() { 894 ( 0.00%) Some(def_id) => self.tcx.hir().local_def_id_to_hir_id(def_id), . None => return false, . }; . . let vis = self.tcx.visibility(def_id); 1,648 ( 0.00%) if !vis.is_at_least(self.required_visibility, self.tcx) { . let vis_descr = match vis { . ty::Visibility::Public => "public", . ty::Visibility::Invisible => "private", . ty::Visibility::Restricted(vis_def_id) => { . if vis_def_id == self.tcx.parent_module(hir_id).to_def_id() { . "private" . } else if vis_def_id.is_top_level_module() { . "crate-private" -- line 1762 ---------------------------------------- -- line 1792 ---------------------------------------- . false . } . . /// An item is 'leaked' from a private dependency if all . /// of the following are true: . /// 1. It's contained within a public type . /// 2. It comes from a private crate . fn leaks_private_dep(&self, item_id: DefId) -> bool { 4,584 ( 0.00%) let ret = self.required_visibility.is_public() && self.tcx.is_private_dep(item_id.krate); . . tracing::debug!("leaks_private_dep(item_id={:?})={}", item_id, ret); . ret . } . } . . impl<'tcx> DefIdVisitor<'tcx> for SearchInterfaceForPrivateItemsVisitor<'tcx> { . fn tcx(&self) -> TyCtxt<'tcx> { 3,041 ( 0.00%) self.tcx . } 24,448 ( 0.00%) fn visit_def_id( . &mut self, . def_id: DefId, . kind: &str, . descr: &dyn fmt::Display, . ) -> ControlFlow { . if self.check_def_id(def_id, kind, descr) { . ControlFlow::BREAK . } else { . ControlFlow::CONTINUE . } 13,752 ( 0.00%) } . } . . struct PrivateItemsInPublicInterfacesVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . has_pub_restricted: bool, . old_error_set_ancestry: LocalDefIdSet, . } . . impl<'tcx> PrivateItemsInPublicInterfacesVisitor<'tcx> { . fn check( . &self, . def_id: LocalDefId, . required_visibility: ty::Visibility, . ) -> SearchInterfaceForPrivateItemsVisitor<'tcx> { 4,013 ( 0.00%) SearchInterfaceForPrivateItemsVisitor { 260 ( 0.00%) tcx: self.tcx, . item_def_id: def_id, . required_visibility, 552 ( 0.00%) has_pub_restricted: self.has_pub_restricted, . has_old_errors: self.old_error_set_ancestry.contains(&def_id), . in_assoc_ty: false, . } . } . 2,574 ( 0.00%) fn check_assoc_item( . &self, . def_id: LocalDefId, . assoc_item_kind: AssocItemKind, . defaultness: hir::Defaultness, . vis: ty::Visibility, . ) { . let mut check = self.check(def_id, vis); . 396 ( 0.00%) let (check_ty, is_assoc_ty) = match assoc_item_kind { . AssocItemKind::Const | AssocItemKind::Fn { .. } => (true, false), 12 ( 0.00%) AssocItemKind::Type => (defaultness.has_value(), true), . }; 396 ( 0.00%) check.in_assoc_ty = is_assoc_ty; 792 ( 0.00%) check.generics().predicates(); 12 ( 0.00%) if check_ty { 198 ( 0.00%) check.ty(); . } 1,584 ( 0.00%) } . } . . impl<'tcx> Visitor<'tcx> for PrivateItemsInPublicInterfacesVisitor<'tcx> { . type NestedFilter = nested_filter::OnlyBodies; . . fn nested_visit_map(&mut self) -> Self::Map { 205 ( 0.00%) self.tcx.hir() . } . 4,428 ( 0.00%) fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { 492 ( 0.00%) let tcx = self.tcx; 492 ( 0.00%) let item_visibility = tcx.visibility(item.def_id); . 2,460 ( 0.00%) match item.kind { . // Crates are always public. . hir::ItemKind::ExternCrate(..) => {} . // All nested items are checked by `visit_item`. . hir::ItemKind::Mod(..) => {} . // Checked in resolve. . hir::ItemKind::Use(..) => {} . // No subitems. . hir::ItemKind::Macro(..) | hir::ItemKind::GlobalAsm(..) => {} . // Subitems of these items have inherited publicity. . hir::ItemKind::Const(..) . | hir::ItemKind::Static(..) . | hir::ItemKind::Fn(..) . | hir::ItemKind::TyAlias(..) => { 1,164 ( 0.00%) self.check(item.def_id, item_visibility).generics().predicates().ty(); . } . hir::ItemKind::OpaqueTy(..) => { . // `ty()` for opaque types is the underlying type, . // it's not a part of interface, so we skip it. . self.check(item.def_id, item_visibility).generics().bounds(); . } 8 ( 0.00%) hir::ItemKind::Trait(.., trait_item_refs) => { 8 ( 0.00%) self.check(item.def_id, item_visibility).generics().predicates(); . . for trait_item_ref in trait_item_refs { 6 ( 0.00%) self.check_assoc_item( 1 ( 0.00%) trait_item_ref.id.def_id, . trait_item_ref.kind, . trait_item_ref.defaultness, . item_visibility, . ); . 7 ( 0.00%) if let AssocItemKind::Type = trait_item_ref.kind { . self.check(trait_item_ref.id.def_id, item_visibility).bounds(); . } . } . } . hir::ItemKind::TraitAlias(..) => { . self.check(item.def_id, item_visibility).generics().predicates(); . } . hir::ItemKind::Enum(ref def, _) => { 40 ( 0.00%) self.check(item.def_id, item_visibility).generics().predicates(); . 10 ( 0.00%) for variant in def.variants { 22 ( 0.00%) for field in variant.data.fields() { 228 ( 0.00%) self.check(self.tcx.hir().local_def_id(field.hir_id), item_visibility).ty(); . } . } . } . // Subitems of foreign modules have their own publicity. . hir::ItemKind::ForeignMod { items, .. } => { . for foreign_item in items { . let vis = tcx.visibility(foreign_item.id.def_id); . self.check(foreign_item.id.def_id, vis).generics().predicates().ty(); . } . } . // Subitems of structs and unions have their own publicity. . hir::ItemKind::Struct(ref struct_def, _) | hir::ItemKind::Union(ref struct_def, _) => { 48 ( 0.00%) self.check(item.def_id, item_visibility).generics().predicates(); . 36 ( 0.00%) for field in struct_def.fields() { 258 ( 0.00%) let def_id = tcx.hir().local_def_id(field.hir_id); . let field_visibility = tcx.visibility(def_id); 129 ( 0.00%) self.check(def_id, min(item_visibility, field_visibility, tcx)).ty(); . } . } . // An inherent impl is public when its type is public . // Subitems of inherent impls have their own publicity. . // A trait impl is public when both its type and its trait are public . // Subitems of trait impls have inherited publicity. . hir::ItemKind::Impl(ref impl_) => { 484 ( 0.00%) let impl_vis = ty::Visibility::of_impl(item.def_id, tcx, &Default::default()); . // check that private components do not appear in the generics or predicates of inherent impls . // this check is intentionally NOT performed for impls of traits, per #90586 242 ( 0.00%) if impl_.of_trait.is_none() { 60 ( 0.00%) self.check(item.def_id, impl_vis).generics().predicates(); . } 121 ( 0.00%) for impl_item_ref in impl_.items { 176 ( 0.00%) let impl_item_vis = if impl_.of_trait.is_none() { 104 ( 0.00%) min(tcx.visibility(impl_item_ref.id.def_id), impl_vis, tcx) . } else { . impl_vis . }; 1,078 ( 0.00%) self.check_assoc_item( 197 ( 0.00%) impl_item_ref.id.def_id, . impl_item_ref.kind, . impl_item_ref.defaultness, . impl_item_vis, . ); . } . } . } 3,936 ( 0.00%) } . } . . pub fn provide(providers: &mut Providers) { 8 ( 0.00%) *providers = Providers { . visibility, . privacy_access_levels, . check_private_in_public, . check_mod_privacy, . ..*providers . }; 1 ( 0.00%) } . 7,272 ( 0.00%) fn visibility(tcx: TyCtxt<'_>, def_id: DefId) -> ty::Visibility { 808 ( 0.00%) let def_id = def_id.expect_local(); . match tcx.resolutions(()).visibilities.get(&def_id) { 1,304 ( 0.00%) Some(vis) => *vis, . None => { . let hir_id = tcx.hir().local_def_id_to_hir_id(def_id); 1,766 ( 0.00%) match tcx.hir().get(hir_id) { . // Unique types created for closures participate in type privacy checking. . // They have visibilities inherited from the module they are defined in. . Node::Expr(hir::Expr { kind: hir::ExprKind::Closure(..), .. }) => { 102 ( 0.00%) ty::Visibility::Restricted(tcx.parent_module(hir_id).to_def_id()) . } . // - AST lowering may clone `use` items and the clones don't . // get their entries in the resolver's visibility table. . // - AST lowering also creates opaque type items with inherited visibilies. . // Visibility on them should have no effect, but to avoid the visibility . // query failing on some items, we provide it for opaque types as well. . Node::Item(hir::Item { 46 ( 0.00%) vis, . kind: hir::ItemKind::Use(..) | hir::ItemKind::OpaqueTy(..), . .. 276 ( 0.00%) }) => ty::Visibility::from_hir(vis, hir_id, tcx), . // Visibilities of trait impl items are inherited from their traits . // and are not filled in resolve. . Node::ImplItem(impl_item) => { 1,209 ( 0.00%) match tcx.hir().get_by_def_id(tcx.hir().get_parent_item(hir_id)) { . Node::Item(hir::Item { . kind: hir::ItemKind::Impl(hir::Impl { of_trait: Some(tr), .. }), . .. 93 ( 0.00%) }) => tr.path.res.opt_def_id().map_or_else( . || { . tcx.sess.delay_span_bug(tr.path.span, "trait without a def-id"); . ty::Visibility::Public . }, . |def_id| tcx.visibility(def_id), . ), . _ => span_bug!(impl_item.span, "the parent is not a trait impl"), . } -- line 2021 ---------------------------------------- -- line 2023 ---------------------------------------- . _ => span_bug!( . tcx.def_span(def_id), . "visibility table unexpectedly missing a def-id: {:?}", . def_id, . ), . } . } . } 6,464 ( 0.00%) } . 152 ( 0.00%) fn check_mod_privacy(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { . // Check privacy of names not checked in previous compilation stages. . let mut visitor = 76 ( 0.00%) NamePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id }; 171 ( 0.00%) let (module, span, hir_id) = tcx.hir().get_module(module_def_id); . . intravisit::walk_mod(&mut visitor, module, hir_id); . . // Check privacy of explicitly written types and traits as well as . // inferred types of expressions and patterns. . let mut visitor = 114 ( 0.00%) TypePrivacyVisitor { tcx, maybe_typeck_results: None, current_item: module_def_id, span }; . intravisit::walk_mod(&mut visitor, module, hir_id); 152 ( 0.00%) } . 7 ( 0.00%) fn privacy_access_levels(tcx: TyCtxt<'_>, (): ()) -> &AccessLevels { . // Build up a set of all exported items in the AST. This is a set of all . // items which are reachable from external crates based on visibility. 9 ( 0.00%) let mut visitor = EmbargoVisitor { . tcx, . access_levels: tcx.resolutions(()).access_levels.clone(), . macro_reachable: Default::default(), . prev_level: Some(AccessLevel::Public), . changed: false, . }; . . loop { . tcx.hir().walk_toplevel_module(&mut visitor); 4 ( 0.00%) if visitor.changed { 3 ( 0.00%) visitor.changed = false; . } else { . break; . } . } . 1 ( 0.00%) tcx.arena.alloc(visitor.access_levels) 9 ( 0.00%) } . 8 ( 0.00%) fn check_private_in_public(tcx: TyCtxt<'_>, (): ()) { . let access_levels = tcx.privacy_access_levels(()); . 9 ( 0.00%) let mut visitor = ObsoleteVisiblePrivateTypesVisitor { . tcx, . access_levels, . in_variant: false, . old_error_set: Default::default(), . }; . tcx.hir().walk_toplevel_module(&mut visitor); . . let has_pub_restricted = { 5 ( 0.00%) let mut pub_restricted_visitor = PubRestrictedVisitor { tcx, has_pub_restricted: false }; . tcx.hir().walk_toplevel_module(&mut pub_restricted_visitor); 1 ( 0.00%) pub_restricted_visitor.has_pub_restricted . }; . . let mut old_error_set_ancestry = HirIdSet::default(); 9 ( 0.00%) for mut id in visitor.old_error_set.iter().copied() { . loop { . if !old_error_set_ancestry.insert(id) { . break; . } . let parent = tcx.hir().get_parent_node(id); . if parent == id { . break; . } . id = parent; . } . } . . // Check for private types and traits in public interfaces. 8 ( 0.00%) let mut visitor = PrivateItemsInPublicInterfacesVisitor { . tcx, . has_pub_restricted, . // Only definition IDs are ever searched in `old_error_set_ancestry`, . // so we can filter away all non-definition IDs at this point. . old_error_set_ancestry: old_error_set_ancestry . .into_iter() . .filter_map(|hir_id| tcx.hir().opt_local_def_id(hir_id)) . .collect(), . }; 6 ( 0.00%) tcx.hir().visit_all_item_likes(&mut DeepVisitor::new(&mut visitor)); 8 ( 0.00%) } 926,805 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/.cargo/registry/src/github.com-1ecc6299db9ec823/hashbrown-0.12.0/src/raw/mod.rs -------------------------------------------------------------------------------- Ir -- line 111 ---------------------------------------- . const EMPTY: u8 = 0b1111_1111; . . /// Control byte value for a deleted bucket. . const DELETED: u8 = 0b1000_0000; . . /// Checks whether a control byte represents a full bucket (top bit is clear). . #[inline] . fn is_full(ctrl: u8) -> bool { 3,684,287 ( 0.08%) ctrl & 0x80 == 0 . } . . /// Checks whether a control byte represents a special value (top bit is set). . #[inline] . fn is_special(ctrl: u8) -> bool { . ctrl & 0x80 != 0 . } . . /// Checks whether a special control value is EMPTY (just check 1 bit). . #[inline] . fn special_is_empty(ctrl: u8) -> bool { . debug_assert!(is_special(ctrl)); 94,528 ( 0.00%) ctrl & 0x01 != 0 . } . . /// Primary hash function, used to select the initial bucket to probe from. . #[inline] . #[allow(clippy::cast_possible_truncation)] . fn h1(hash: u64) -> usize { . // On 32-bit platforms we simply ignore the higher hash bits. . hash as usize -- line 140 ---------------------------------------- -- line 143 ---------------------------------------- . /// Secondary hash function, saved in the low 7 bits of the control byte. . #[inline] . #[allow(clippy::cast_possible_truncation)] . fn h2(hash: u64) -> u8 { . // Grab the top 7 bits of the hash. While the hash is normally a full 64-bit . // value, some hash functions (such as FxHash) produce a usize result . // instead, which means that the top 32 bits are 0 on 32-bit platforms. . let hash_len = usize::min(mem::size_of::(), mem::size_of::()); 85,798,092 ( 1.76%) let top7 = hash >> (hash_len * 8 - 7); . (top7 & 0x7f) as u8 // truncation . } . . /// Probe sequence based on triangular numbers, which is guaranteed (since our . /// table size is a power of two) to visit every group of elements exactly once. . /// . /// A triangular probe has us jump by 1 more group every time. So first we . /// jump by 1 group (meaning we just continue our linear scan), then 2 groups -- line 159 ---------------------------------------- -- line 170 ---------------------------------------- . #[inline] . fn move_next(&mut self, bucket_mask: usize) { . // We should have found an empty bucket by now and ended the probe. . debug_assert!( . self.stride <= bucket_mask, . "Went past end of probe sequence" . ); . 233,116 ( 0.00%) self.stride += Group::WIDTH; 233,116 ( 0.00%) self.pos += self.stride; 191,911 ( 0.00%) self.pos &= bucket_mask; . } . } . . /// Returns the number of buckets needed to hold the given number of items, . /// taking the maximum load factor into account. . /// . /// Returns `None` if an overflow occurs. . // Workaround for emscripten bug emscripten-core/emscripten-fastcomp#258 . #[cfg_attr(target_os = "emscripten", inline(never))] . #[cfg_attr(not(target_os = "emscripten"), inline)] . fn capacity_to_buckets(cap: usize) -> Option { . debug_assert_ne!(cap, 0); . . // For small tables we require at least 1 empty bucket so that lookups are . // guaranteed to terminate if an element doesn't exist in the table. 112,654 ( 0.00%) if cap < 8 { . // We don't bother with a table size of 2 buckets since that can only . // hold a single element. Instead we skip directly to a 4 bucket table . // which can hold 3 elements. 223,600 ( 0.00%) return Some(if cap < 4 { 4 } else { 8 }); . } . . // Otherwise require 1/8 buckets to be empty (87.5% load) . // . // Be careful when modifying this, calculate_layout relies on the . // overflow check here. 69,642 ( 0.00%) let adjusted_cap = cap.checked_mul(8)? / 7; . . // Any overflows will have been caught by the checked_mul. Also, any . // rounding errors from the division above will be cleaned up by . // next_power_of_two (which can't overflow because of the previous division). . Some(adjusted_cap.next_power_of_two()) . } . . /// Returns the maximum effective capacity for the given bucket mask, taking . /// the maximum load factor into account. . #[inline] . fn bucket_mask_to_capacity(bucket_mask: usize) -> usize { 298,667 ( 0.01%) if bucket_mask < 8 { . // For tables with 1/2/4/8 buckets, we always reserve one empty slot. . // Keep in mind that the bucket mask is one less than the bucket count. . bucket_mask . } else { . // For larger tables we reserve 12.5% of the slots as empty. 92,220 ( 0.00%) ((bucket_mask + 1) / 8) * 7 . } . } . . /// Helper which allows the max calculation for ctrl_align to be statically computed for each T . /// while keeping the rest of `calculate_layout_for` independent of `T` . #[derive(Copy, Clone)] . struct TableLayout { . size: usize, -- line 233 ---------------------------------------- -- line 246 ---------------------------------------- . . #[inline] . fn calculate_layout_for(self, buckets: usize) -> Option<(Layout, usize)> { . debug_assert!(buckets.is_power_of_two()); . . let TableLayout { size, ctrl_align } = self; . // Manual layout calculation since Layout methods are not yet stable. . let ctrl_offset = 225,733 ( 0.00%) size.checked_mul(buckets)?.checked_add(ctrl_align - 1)? & !(ctrl_align - 1); 303,451 ( 0.01%) let len = ctrl_offset.checked_add(buckets + Group::WIDTH)?; . . Some(( . unsafe { Layout::from_size_align_unchecked(len, ctrl_align) }, . ctrl_offset, . )) . } . } . -- line 263 ---------------------------------------- -- line 337 ---------------------------------------- . } . } . #[cfg_attr(feature = "inline-more", inline)] . pub unsafe fn drop(&self) { . self.as_ptr().drop_in_place(); . } . #[inline] . pub unsafe fn read(&self) -> T { 3,042 ( 0.00%) self.as_ptr().read() . } . #[inline] . pub unsafe fn write(&self, val: T) { . self.as_ptr().write(val); . } . #[inline] . pub unsafe fn as_ref<'a>(&self) -> &'a T { . &*self.as_ptr() -- line 353 ---------------------------------------- -- line 422 ---------------------------------------- . /// Creates a new empty hash table without allocating any memory, using the . /// given allocator. . /// . /// In effect this returns a table with exactly 1 bucket. However we can . /// leave the data pointer dangling since that bucket is never written to . /// due to our load factor forcing us to always have at least 1 free bucket. . #[inline] . pub fn new_in(alloc: A) -> Self { 384 ( 0.00%) Self { . table: RawTableInner::new_in(alloc), . marker: PhantomData, . } . } . . /// Allocates a new hash table with the given number of buckets. . /// . /// The control bytes are left uninitialized. -- line 438 ---------------------------------------- -- line 440 ---------------------------------------- . unsafe fn new_uninitialized( . alloc: A, . buckets: usize, . fallibility: Fallibility, . ) -> Result { . debug_assert!(buckets.is_power_of_two()); . . Ok(Self { 225 ( 0.00%) table: RawTableInner::new_uninitialized( . alloc, . TableLayout::new::(), . buckets, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 456 ---------------------------------------- -- line 458 ---------------------------------------- . /// Attempts to allocate a new hash table with at least enough capacity . /// for inserting the given number of elements without reallocating. . fn fallible_with_capacity( . alloc: A, . capacity: usize, . fallibility: Fallibility, . ) -> Result { . Ok(Self { 7,840 ( 0.00%) table: RawTableInner::fallible_with_capacity( . alloc, . TableLayout::new::(), . capacity, . fallibility, . )?, . marker: PhantomData, . }) . } -- line 474 ---------------------------------------- -- line 527 ---------------------------------------- . debug_assert_ne!(self.table.bucket_mask, 0); . debug_assert!(index < self.buckets()); . Bucket::from_base_index(self.data_end(), index) . } . . /// Erases an element from the table without dropping it. . #[cfg_attr(feature = "inline-more", inline)] . #[deprecated(since = "0.8.1", note = "use erase or remove instead")] 17,021 ( 0.00%) pub unsafe fn erase_no_drop(&mut self, item: &Bucket) { 17,021 ( 0.00%) let index = self.bucket_index(item); . self.table.erase(index); 34,042 ( 0.00%) } . . /// Erases an element from the table, dropping it in place. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::needless_pass_by_value)] . #[allow(deprecated)] . pub unsafe fn erase(&mut self, item: Bucket) { . // Erase the element from the table first since drop might panic. 6,154 ( 0.00%) self.erase_no_drop(&item); . item.drop(); . } . . /// Finds and erases an element from the table, dropping it in place. . /// Returns true if an element was found. . #[cfg(feature = "raw")] . #[cfg_attr(feature = "inline-more", inline)] . pub fn erase_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> bool { -- line 554 ---------------------------------------- -- line 563 ---------------------------------------- . } . } . . /// Removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] . #[allow(clippy::needless_pass_by_value)] . #[allow(deprecated)] . pub unsafe fn remove(&mut self, item: Bucket) -> T { 27,888 ( 0.00%) self.erase_no_drop(&item); 92 ( 0.00%) item.read() . } . . /// Finds and removes an element from the table, returning it. . #[cfg_attr(feature = "inline-more", inline)] 1,773,488 ( 0.04%) pub fn remove_entry(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option { . // Avoid `Option::map` because it bloats LLVM IR. 2,382 ( 0.00%) match self.find(hash, eq) { 6,826 ( 0.00%) Some(bucket) => Some(unsafe { self.remove(bucket) }), 949,033 ( 0.02%) None => None, . } 2,816,919 ( 0.06%) } . . /// Marks all table buckets as empty without dropping their contents. . #[cfg_attr(feature = "inline-more", inline)] . pub fn clear_no_drop(&mut self) { . self.table.clear_no_drop(); . } . . /// Removes all elements from the table without freeing the backing memory. . #[cfg_attr(feature = "inline-more", inline)] . pub fn clear(&mut self) { . // Ensure that the table is reset even if one of the drops panic . let mut self_ = guard(self, |self_| self_.clear_no_drop()); . unsafe { 1 ( 0.00%) self_.drop_elements(); . } . } . 7 ( 0.00%) unsafe fn drop_elements(&mut self) { 10,440 ( 0.00%) if mem::needs_drop::() && !self.is_empty() { . for item in self.iter() { . item.drop(); . } . } 8 ( 0.00%) } . . /// Shrinks the table to fit `max(self.len(), min_size)` elements. . #[cfg_attr(feature = "inline-more", inline)] . pub fn shrink_to(&mut self, min_size: usize, hasher: impl Fn(&T) -> u64) { . // Calculate the minimal number of elements that we need to reserve . // space for. . let min_size = usize::max(self.table.items, min_size); . if min_size == 0 { -- line 615 ---------------------------------------- -- line 642 ---------------------------------------- . } . } . } . . /// Ensures that at least `additional` items can be inserted into the table . /// without reallocation. . #[cfg_attr(feature = "inline-more", inline)] . pub fn reserve(&mut self, additional: usize, hasher: impl Fn(&T) -> u64) { 259,842 ( 0.01%) if additional > self.table.growth_left { . // Avoid `Result::unwrap_or_else` because it bloats LLVM IR. 189,572 ( 0.00%) if self . .reserve_rehash(additional, hasher, Fallibility::Infallible) . .is_err() . { . unsafe { hint::unreachable_unchecked() } . } . } . } . -- line 660 ---------------------------------------- -- line 671 ---------------------------------------- . } else { . Ok(()) . } . } . . /// Out-of-line slow path for `reserve` and `try_reserve`. . #[cold] . #[inline(never)] 449,968 ( 0.01%) fn reserve_rehash( . &mut self, . additional: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, . ) -> Result<(), TryReserveError> { . unsafe { . self.table.reserve_rehash_inner( . additional, -- line 687 ---------------------------------------- -- line 690 ---------------------------------------- . TableLayout::new::(), . if mem::needs_drop::() { . Some(mem::transmute(ptr::drop_in_place:: as unsafe fn(*mut T))) . } else { . None . }, . ) . } 287,944 ( 0.01%) } . . /// Allocates a new table of a different size and moves the contents of the . /// current table into it. . fn resize( . &mut self, . capacity: usize, . hasher: impl Fn(&T) -> u64, . fallibility: Fallibility, -- line 706 ---------------------------------------- -- line 714 ---------------------------------------- . ) . } . } . . /// Inserts a new element into the table, and returns its raw bucket. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 4,165,054 ( 0.09%) pub fn insert(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> Bucket { . unsafe { . let mut index = self.table.find_insert_slot(hash); . . // We can avoid growing the table once we have reached our load . // factor if we are replacing a tombstone. This works since the . // number of EMPTY slots does not change in this case. 5,850 ( 0.00%) let old_ctrl = *self.table.ctrl(index); 3,614,951 ( 0.07%) if unlikely(self.table.growth_left == 0 && special_is_empty(old_ctrl)) { . self.reserve(1, hasher); . index = self.table.find_insert_slot(hash); . } . . self.table.record_item_insert_at(index, old_ctrl, hash); . . let bucket = self.bucket(index); 2 ( 0.00%) bucket.write(value); . bucket . } 3,100,392 ( 0.06%) } . . /// Attempts to insert a new element without growing the table and return its raw bucket. . /// . /// Returns an `Err` containing the given element if inserting it would require growing the . /// table. . /// . /// This does not check if the given element already exists in the table. . #[cfg(feature = "raw")] -- line 749 ---------------------------------------- -- line 760 ---------------------------------------- . } . } . } . . /// Inserts a new element into the table, and returns a mutable reference to it. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] 604,096 ( 0.01%) pub fn insert_entry(&mut self, hash: u64, value: T, hasher: impl Fn(&T) -> u64) -> &mut T { 174 ( 0.00%) unsafe { self.insert(hash, value, hasher).as_mut() } 453,072 ( 0.01%) } . . /// Inserts a new element into the table, without growing the table. . /// . /// There must be enough space in the table to insert the new element. . /// . /// This does not check if the given element already exists in the table. . #[cfg_attr(feature = "inline-more", inline)] . #[cfg(any(feature = "raw", feature = "rustc-internal-api"))] 1,162 ( 0.00%) pub unsafe fn insert_no_grow(&mut self, hash: u64, value: T) -> Bucket { 265,106 ( 0.01%) let (index, old_ctrl) = self.table.prepare_insert_slot(hash); 8,134 ( 0.00%) let bucket = self.table.bucket(index); . . // If we are replacing a DELETED entry then we don't need to update . // the load counter. 558,101 ( 0.01%) self.table.growth_left -= special_is_empty(old_ctrl) as usize; . . bucket.write(value); 441,507 ( 0.01%) self.table.items += 1; . bucket 2,208 ( 0.00%) } . . /// Temporary removes a bucket, applying the given function to the removed . /// element and optionally put back the returned value in the same bucket. . /// . /// Returns `true` if the bucket still contains an element . /// . /// This does not check if the given bucket is actually occupied. . #[cfg_attr(feature = "inline-more", inline)] -- line 798 ---------------------------------------- -- line 813 ---------------------------------------- . true . } else { . false . } . } . . /// Searches for an element in the table. . #[inline] 2,568 ( 0.00%) pub fn find(&self, hash: u64, mut eq: impl FnMut(&T) -> bool) -> Option> { 689,658 ( 0.01%) let result = self.table.find_inner(hash, &mut |index| unsafe { 423,605 ( 0.01%) eq(self.bucket(index).as_ref()) 546,025 ( 0.01%) }); . . // Avoid `Option::map` because it bloats LLVM IR. . match result { 136,420 ( 0.00%) Some(index) => Some(unsafe { self.bucket(index) }), . None => None, . } 2,568 ( 0.00%) } . . /// Gets a reference to an element in the table. . #[inline] . pub fn get(&self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&T> { . // Avoid `Option::map` because it bloats LLVM IR. 283,080 ( 0.01%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_ref() }), . None => None, . } . } . . /// Gets a mutable reference to an element in the table. . #[inline] . pub fn get_mut(&mut self, hash: u64, eq: impl FnMut(&T) -> bool) -> Option<&mut T> { . // Avoid `Option::map` because it bloats LLVM IR. 2,566 ( 0.00%) match self.find(hash, eq) { . Some(bucket) => Some(unsafe { bucket.as_mut() }), . None => None, . } . } . . /// Attempts to get mutable references to `N` entries in the table at once. . /// . /// Returns an array of length `N` with the results of each query. -- line 855 ---------------------------------------- -- line 920 ---------------------------------------- . #[inline] . pub fn len(&self) -> usize { . self.table.items . } . . /// Returns `true` if the table contains no elements. . #[inline] . pub fn is_empty(&self) -> bool { 4,953,833 ( 0.10%) self.len() == 0 . } . . /// Returns the number of buckets in the table. . #[inline] . pub fn buckets(&self) -> usize { . self.table.bucket_mask + 1 . } . . /// Returns an iterator over every element in the table. It is up to . /// the caller to ensure that the `RawTable` outlives the `RawIter`. . /// Because we cannot make the `next` method unsafe on the `RawIter` . /// struct, we have to make the `iter` method unsafe. . #[inline] . pub unsafe fn iter(&self) -> RawIter { 6 ( 0.00%) let data = Bucket::from_base_index(self.data_end(), 0); . RawIter { . iter: RawIterRange::new(self.table.ctrl.as_ptr(), data, self.table.buckets()), 920,823 ( 0.02%) items: self.table.items, . } . } . . /// Returns an iterator over occupied buckets that could match a given hash. . /// . /// `RawTable` only stores 7 bits of the hash value, so this iterator may . /// return items that have a hash value different than the one provided. You . /// should always validate the returned values before using them. -- line 954 ---------------------------------------- -- line 995 ---------------------------------------- . /// Iteration starts at the provided iterator's current location. . /// . /// It is up to the caller to ensure that the iterator is valid for this . /// `RawTable` and covers all items that remain in the table. . pub unsafe fn into_iter_from(self, iter: RawIter) -> RawIntoIter { . debug_assert_eq!(iter.len(), self.len()); . . let alloc = self.table.alloc.clone(); 7,664 ( 0.00%) let allocation = self.into_allocation(); 5,748 ( 0.00%) RawIntoIter { 9,580 ( 0.00%) iter, . allocation, . marker: PhantomData, . alloc, . } . } . . /// Converts the table into a raw allocation. The contents of the table . /// should be dropped using a `RawIter` before freeing the allocation. . #[cfg_attr(feature = "inline-more", inline)] . pub(crate) fn into_allocation(self) -> Option<(NonNull, Layout)> { 3,144 ( 0.00%) let alloc = if self.table.is_empty_singleton() { . None . } else { . // Avoid `Option::unwrap_or_else` because it bloats LLVM IR. . let (layout, ctrl_offset) = match calculate_layout::(self.table.buckets()) { . Some(lco) => lco, . None => unsafe { hint::unreachable_unchecked() }, . }; . Some(( 522 ( 0.00%) unsafe { NonNull::new_unchecked(self.table.ctrl.as_ptr().sub(ctrl_offset)) }, . layout, . )) . }; . mem::forget(self); . alloc . } . } . -- line 1033 ---------------------------------------- -- line 1042 ---------------------------------------- . T: Sync, . A: Sync, . { . } . . impl RawTableInner { . #[inline] . const fn new_in(alloc: A) -> Self { 5,662,766 ( 0.12%) 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)] 405,488 ( 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()); . } . 94,376 ( 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)); 223,746 ( 0.00%) Ok(Self { . ctrl, 93,663 ( 0.00%) bucket_mask: buckets - 1, . items: 0, . growth_left: bucket_mask_to_capacity(buckets - 1), . alloc, . }) 295,186 ( 0.01%) } . . #[inline] 18,728 ( 0.00%) fn fallible_with_capacity( . alloc: A, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result { 4,970 ( 0.00%) if capacity == 0 { 4,808 ( 0.00%) Ok(Self::new_in(alloc)) . } else { . unsafe { . let buckets = . capacity_to_buckets(capacity).ok_or_else(|| fallibility.capacity_overflow())?; . 184,086 ( 0.00%) let result = Self::new_uninitialized(alloc, table_layout, buckets, fallibility)?; . result.ctrl(0).write_bytes(EMPTY, result.num_ctrl_bytes()); . 8,681 ( 0.00%) Ok(result) . } . } 18,728 ( 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] 93,453 ( 0.00%) unsafe fn prepare_insert_slot(&self, hash: u64) -> (usize, u8) { . let index = self.find_insert_slot(hash); 93,453 ( 0.00%) let old_ctrl = *self.ctrl(index); . self.set_ctrl_h2(index, hash); . (index, old_ctrl) 186,906 ( 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)); 2,292,280 ( 0.05%) if let Some(bit) = group.match_empty_or_deleted().lowest_set_bit() { 6,762,050 ( 0.14%) 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). 3,156,885 ( 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); . 56,560 ( 0.00%) loop { . let group = unsafe { Group::load(self.ctrl(probe_seq.pos)) }; . 11,136,733 ( 0.23%) for bit in group.match_byte(h2_hash) { 21,627,374 ( 0.44%) let index = (probe_seq.pos + bit) & self.bucket_mask; . 12,518,398 ( 0.26%) if likely(eq(index)) { . return Some(index); . } . } . 3,512,401 ( 0.07%) 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(); 9,729,992 ( 0.20%) 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 { 56,759,593 ( 1.16%) 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) { 4,515,925 ( 0.09%) self.growth_left -= special_is_empty(old_ctrl) as usize; . self.set_ctrl_h2(index, hash); 3,612,740 ( 0.07%) 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] | . // --------------------------------------------- 6,641,886 ( 0.14%) let index2 = ((index.wrapping_sub(Group::WIDTH)) & self.bucket_mask) + Group::WIDTH; . 2,213,962 ( 0.05%) *self.ctrl(index) = ctrl; 2,214,811 ( 0.05%) *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 { 1,512,410 ( 0.03%) self.bucket_mask + 1 . } . . #[inline] . fn num_ctrl_bytes(&self) -> usize { 233,343 ( 0.00%) self.bucket_mask + 1 + Group::WIDTH . } . . #[inline] . fn is_empty_singleton(&self) -> bool { 8,896,788 ( 0.18%) self.bucket_mask == 0 . } . . #[allow(clippy::mut_mut)] . #[inline] . unsafe fn prepare_resize( . &self, . table_layout: TableLayout, . capacity: usize, . fallibility: Fallibility, . ) -> Result, TryReserveError> { . debug_assert!(self.items <= capacity); . . // Allocate and initialize the new table. 1,287 ( 0.00%) let mut new_table = RawTableInner::fallible_with_capacity( . self.alloc.clone(), . table_layout, . capacity, . fallibility, . )?; 120,303 ( 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_| { 55,308 ( 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. 110,621 ( 0.00%) let new_items = match self.items.checked_add(additional) { . Some(new_items) => new_items, . None => return Err(fallibility.capacity_overflow()), . }; 110,616 ( 0.00%) let full_capacity = bucket_mask_to_capacity(self.bucket_mask); 231,044 ( 0.00%) if new_items <= full_capacity / 2 { . // Rehash in-place without re-allocating if we have plenty of spare . // capacity that is locked up due to DELETED entries. . self.rehash_in_place(hasher, layout.size, drop); . Ok(()) . } else { . // Otherwise, conservatively resize to at least the next size up . // to avoid churning deletes into frequent rehashes. . self.resize_inner( 55,308 ( 0.00%) usize::max(new_items, full_capacity + 1), . hasher, . fallibility, . layout, . ) . } . } . . /// Allocates a new table of a different size and moves the contents of the -- line 1418 ---------------------------------------- -- line 1424 ---------------------------------------- . #[inline(always)] . unsafe fn resize_inner( . &mut self, . capacity: usize, . hasher: &dyn Fn(&mut Self, usize) -> u64, . fallibility: Fallibility, . layout: TableLayout, . ) -> Result<(), TryReserveError> { 3,130 ( 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() { 1,430,587 ( 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); . 55,308 ( 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( 33,294 ( 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) { 10,520 ( 0.00%) if !self.is_empty_singleton() { . unsafe { . self.ctrl(0).write_bytes(EMPTY, self.num_ctrl_bytes()); . } . } 14,255 ( 0.00%) self.items = 0; 10,520 ( 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))); 86,679 ( 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. 346,716 ( 0.01%) let ctrl = if empty_before.leading_zeros() + empty_after.trailing_zeros() >= Group::WIDTH { . DELETED . } else { 432,705 ( 0.01%) self.growth_left += 1; . EMPTY . }; . self.set_ctrl(index, ctrl); 346,716 ( 0.01%) self.items -= 1; . } . } . . impl Clone for RawTable { 1,040 ( 0.00%) fn clone(&self) -> Self { 183 ( 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) . } . } 1,170 ( 0.00%) } . . fn clone_from(&mut self, source: &Self) { . if source.table.is_empty_singleton() { . *self = Self::new_in(self.table.alloc.clone()); . } else { . unsafe { . // First, drop all our elements without clearing the control bytes. . self.drop_elements(); -- line 1640 ---------------------------------------- -- line 1687 ---------------------------------------- . .table . .ctrl(0) . .copy_to_nonoverlapping(self.table.ctrl(0), self.table.num_ctrl_bytes()); . source . .data_start() . .copy_to_nonoverlapping(self.data_start(), self.table.buckets()); . . self.table.items = source.table.items; 90 ( 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)] 7,237,960 ( 0.15%) fn drop(&mut self) { 4,156,052 ( 0.09%) if !self.table.is_empty_singleton() { . unsafe { . self.drop_elements(); . self.free_buckets(); . } . } 8,239,364 ( 0.17%) } . } . #[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)] 7,664 ( 0.00%) fn into_iter(self) -> RawIntoIter { . unsafe { . let iter = self.iter(); . self.into_iter_from(iter) . } 9,580 ( 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 { 876,324 ( 0.02%) if let Some(index) = self.current_group.lowest_set_bit() { 165,830 ( 0.00%) self.current_group = self.current_group.remove_lowest_bit(); 294,002 ( 0.01%) return Some(self.data.next_n(index)); . } . 1,056,025 ( 0.02%) 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). 18,222 ( 0.00%) self.current_group = Group::load_aligned(self.next_ctrl).match_full(); 32,410 ( 0.00%) self.data = self.data.next_n(Group::WIDTH); 21,388 ( 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) { 1,406 ( 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)] 169,861 ( 0.00%) fn next(&mut self) -> Option> { 352,318 ( 0.01%) if let Some(b) = self.iter.next() { 905,372 ( 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 . } 339,722 ( 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)] 3,212 ( 0.00%) fn drop(&mut self) { . unsafe { . // Drop all remaining elements . self.iter.drop_elements(); . . // Free the table 14,449 ( 0.00%) if let Some((ptr, layout)) = self.allocation { . self.alloc.deallocate(ptr, layout); . } . } 1,030 ( 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)] 524 ( 0.00%) fn next(&mut self) -> Option { 183 ( 0.00%) unsafe { Some(self.iter.next()?.read()) } 1,048 ( 0.00%) } . . #[inline] . fn size_hint(&self) -> (usize, Option) { 4 ( 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)] 352 ( 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. 44 ( 0.00%) self.orig_table . .as_ptr() . .copy_from_nonoverlapping(&*self.table, 1); . } 352 ( 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 ---------------------------------------- 30,443,327 ( 0.62%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/types.rs -------------------------------------------------------------------------------- Ir -- line 166 ---------------------------------------- . } . } . overwritten . } . . // For `isize` & `usize`, be conservative with the warnings, so that the . // warnings are consistent between 32- and 64-bit platforms. . fn int_ty_range(int_ty: ty::IntTy) -> (i128, i128) { 15 ( 0.00%) match int_ty { . ty::IntTy::Isize => (i64::MIN.into(), i64::MAX.into()), . ty::IntTy::I8 => (i8::MIN.into(), i8::MAX.into()), . ty::IntTy::I16 => (i16::MIN.into(), i16::MAX.into()), . ty::IntTy::I32 => (i32::MIN.into(), i32::MAX.into()), . ty::IntTy::I64 => (i64::MIN.into(), i64::MAX.into()), . ty::IntTy::I128 => (i128::MIN, i128::MAX), . } . } . . fn uint_ty_range(uint_ty: ty::UintTy) -> (u128, u128) { 828,534 ( 0.02%) let max = match uint_ty { . ty::UintTy::Usize => u64::MAX.into(), . ty::UintTy::U8 => u8::MAX.into(), . ty::UintTy::U16 => u16::MAX.into(), . ty::UintTy::U32 => u32::MAX.into(), . ty::UintTy::U64 => u64::MAX.into(), . ty::UintTy::U128 => u128::MAX, . }; . (0, max) -- line 193 ---------------------------------------- -- line 317 ---------------------------------------- . fn lint_int_literal<'tcx>( . cx: &LateContext<'tcx>, . type_limits: &TypeLimits, . e: &'tcx hir::Expr<'tcx>, . lit: &hir::Lit, . t: ty::IntTy, . v: u128, . ) { 15 ( 0.00%) let int_type = t.normalize(cx.sess().target.pointer_width); 6 ( 0.00%) let (min, max) = int_ty_range(int_type); 6 ( 0.00%) let max = max as u128; 9 ( 0.00%) let negative = type_limits.negated_expr_id == Some(e.hir_id); . . // Detect literal value out of range [min, max] inclusive . // avoiding use of -min to prevent overflow/panic 12 ( 0.00%) if (negative && v > max + 1) || (!negative && v > max) { . if let Some(repr_str) = get_bin_hex_repr(cx, lit) { . report_bin_hex_error( . cx, . e, . attr::IntType::SignedInt(ty::ast_int_ty(t)), . repr_str, . v, . negative, -- line 340 ---------------------------------------- -- line 377 ---------------------------------------- . } . . fn lint_uint_literal<'tcx>( . cx: &LateContext<'tcx>, . e: &'tcx hir::Expr<'tcx>, . lit: &hir::Lit, . t: ty::UintTy, . ) { 414,267 ( 0.01%) let uint_type = t.normalize(cx.sess().target.pointer_width); 552,356 ( 0.01%) let (min, max) = uint_ty_range(uint_type); 690,445 ( 0.01%) let lit_val: u128 = match lit.node { . // _v is u8, within range by definition . ast::LitKind::Byte(_v) => return, 552,356 ( 0.01%) ast::LitKind::Int(v, _) => v, . _ => bug!(), . }; 552,356 ( 0.01%) if lit_val < min || lit_val > max { . let parent_id = cx.tcx.hir().get_parent_node(e.hir_id); . if let Node::Expr(par_e) = cx.tcx.hir().get(parent_id) { . match par_e.kind { . hir::ExprKind::Cast(..) => { . if let ty::Char = cx.typeck_results().expr_ty(par_e).kind() { . cx.struct_span_lint(OVERFLOWING_LITERALS, par_e.span, |lint| { . lint.build("only `u8` can be cast into `char`") . .span_suggestion( -- line 401 ---------------------------------------- -- line 448 ---------------------------------------- . } . . fn lint_literal<'tcx>( . cx: &LateContext<'tcx>, . type_limits: &TypeLimits, . e: &'tcx hir::Expr<'tcx>, . lit: &hir::Lit, . ) { 1,385,390 ( 0.03%) match *cx.typeck_results().node_type(e.hir_id).kind() { . ty::Int(t) => { 15 ( 0.00%) match lit.node { 21 ( 0.00%) ast::LitKind::Int(v, ast::LitIntType::Signed(_) | ast::LitIntType::Unsuffixed) => { . lint_int_literal(cx, type_limits, e, lit, t, v) . } . _ => bug!(), . }; . } 276,178 ( 0.01%) ty::Uint(t) => lint_uint_literal(cx, e, lit, t), . ty::Float(t) => { . let is_infinite = match lit.node { . ast::LitKind::Float(v, _) => match t { . ty::FloatTy::F32 => v.as_str().parse().map(f32::is_infinite), . ty::FloatTy::F64 => v.as_str().parse().map(f64::is_infinite), . }, . _ => bug!(), . }; -- line 473 ---------------------------------------- -- line 487 ---------------------------------------- . }); . } . } . _ => {} . } . } . . impl<'tcx> LateLintPass<'tcx> for TypeLimits { 1,310,202 ( 0.03%) fn check_expr(&mut self, cx: &LateContext<'tcx>, e: &'tcx hir::Expr<'tcx>) { 1,018,314 ( 0.02%) match e.kind { . hir::ExprKind::Unary(hir::UnOp::Neg, ref expr) => { . // propagate negation, if the negation itself isn't negated . if self.negated_expr_id != Some(e.hir_id) { . self.negated_expr_id = Some(expr.hir_id); . } . } 183 ( 0.00%) hir::ExprKind::Binary(binop, ref l, ref r) => { 417 ( 0.00%) if is_comparison(binop) && !check_limits(cx, binop, &l, &r) { . cx.struct_span_lint(UNUSED_COMPARISONS, e.span, |lint| { . lint.build("comparison is useless due to type limits").emit() . }); . } . } 276,928 ( 0.01%) hir::ExprKind::Lit(ref lit) => lint_literal(cx, self, e, lit), . _ => {} . }; . . fn is_valid(binop: hir::BinOp, v: T, min: T, max: T) -> bool { 27 ( 0.00%) match binop.node { . hir::BinOpKind::Lt => v > min && v <= max, . hir::BinOpKind::Le => v >= min && v < max, . hir::BinOpKind::Gt => v >= min && v < max, . hir::BinOpKind::Ge => v > min && v <= max, . hir::BinOpKind::Eq | hir::BinOpKind::Ne => v >= min && v <= max, . _ => bug!(), . } . } -- line 523 ---------------------------------------- -- line 536 ---------------------------------------- . } . . fn check_limits( . cx: &LateContext<'_>, . binop: hir::BinOp, . l: &hir::Expr<'_>, . r: &hir::Expr<'_>, . ) -> bool { 555 ( 0.00%) let (lit, expr, swap) = match (&l.kind, &r.kind) { . (&hir::ExprKind::Lit(_), _) => (l, r, true), . (_, &hir::ExprKind::Lit(_)) => (r, l, false), . _ => return true, . }; . // Normalize the binop so that the literal is always on the RHS in . // the comparison . let norm_binop = if swap { rev_binop(binop) } else { binop }; 74 ( 0.00%) match *cx.typeck_results().node_type(expr.hir_id).kind() { 10 ( 0.00%) ty::Int(int_ty) => { . let (min, max) = int_ty_range(int_ty); . let lit_val: i128 = match lit.kind { 10 ( 0.00%) hir::ExprKind::Lit(ref li) => match li.node { . ast::LitKind::Int( . v, . ast::LitIntType::Signed(_) | ast::LitIntType::Unsuffixed, . ) => v as i128, . _ => return true, . }, . _ => bug!(), . }; . is_valid(norm_binop, lit_val, min, max) . } 42 ( 0.00%) ty::Uint(uint_ty) => { . let (min, max): (u128, u128) = uint_ty_range(uint_ty); . let lit_val: u128 = match lit.kind { 14 ( 0.00%) hir::ExprKind::Lit(ref li) => match li.node { . ast::LitKind::Int(v, _) => v, . _ => return true, . }, . _ => bug!(), . }; . is_valid(norm_binop, lit_val, min, max) . } . _ => true, . } . } . . fn is_comparison(binop: hir::BinOp) -> bool { 366 ( 0.00%) matches!( 183 ( 0.00%) binop.node, . hir::BinOpKind::Eq . | hir::BinOpKind::Lt . | hir::BinOpKind::Le . | hir::BinOpKind::Ne . | hir::BinOpKind::Ge . | hir::BinOpKind::Gt . ) . } 1,164,624 ( 0.02%) } . } . . declare_lint! { . /// The `improper_ctypes` lint detects incorrect use of types in foreign . /// modules. . /// . /// ### Example . /// -- line 601 ---------------------------------------- -- line 1268 ---------------------------------------- . . fn check_foreign_static(&mut self, id: hir::HirId, span: Span) { . let def_id = self.cx.tcx.hir().local_def_id(id); . let ty = self.cx.tcx.type_of(def_id); . self.check_type_for_ffi_and_report_errors(span, ty, true, false); . } . . fn is_internal_abi(&self, abi: SpecAbi) -> bool { 582 ( 0.00%) matches!( . abi, . SpecAbi::Rust | SpecAbi::RustCall | SpecAbi::RustIntrinsic | SpecAbi::PlatformIntrinsic . ) . } . } . . impl<'tcx> LateLintPass<'tcx> for ImproperCTypesDeclarations { . fn check_foreign_item(&mut self, cx: &LateContext<'_>, it: &hir::ForeignItem<'_>) { -- line 1284 ---------------------------------------- -- line 1306 ---------------------------------------- . kind: hir::intravisit::FnKind<'tcx>, . decl: &'tcx hir::FnDecl<'_>, . _: &'tcx hir::Body<'_>, . _: Span, . hir_id: hir::HirId, . ) { . use hir::intravisit::FnKind; . 1,255 ( 0.00%) let abi = match kind { . FnKind::ItemFn(_, _, header, ..) => header.abi, 191 ( 0.00%) FnKind::Method(_, sig, ..) => sig.header.abi, . _ => return, . }; . 582 ( 0.00%) let mut vis = ImproperCTypesVisitor { cx, mode: CItemKind::Definition }; . if !vis.is_internal_abi(abi) { . vis.check_foreign_fn(hir_id, decl); . } . } . } . . declare_lint_pass!(VariantSizeDifferences => [VARIANT_SIZE_DIFFERENCES]); . . impl<'tcx> LateLintPass<'tcx> for VariantSizeDifferences { 3,444 ( 0.00%) fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) { 984 ( 0.00%) if let hir::ItemKind::Enum(ref enum_definition, _) = it.kind { 20 ( 0.00%) let t = cx.tcx.type_of(it.def_id); 10 ( 0.00%) let ty = cx.tcx.erase_regions(t); 61 ( 0.00%) let layout = match cx.layout_of(ty) { 7 ( 0.00%) Ok(layout) => layout, . Err( . ty::layout::LayoutError::Unknown(_) . | ty::layout::LayoutError::SizeOverflow(_) . | ty::layout::LayoutError::NormalizationFailure(_, _), . ) => return, . }; 28 ( 0.00%) let Variants::Multiple { . tag_encoding: TagEncoding::Direct, tag, ref variants, .. . } = &layout.variants else { . return . }; . 7 ( 0.00%) let tag_size = tag.value.size(&cx.tcx).bytes(); . . debug!( . "enum `{}` is {} bytes large with layout:\n{:#?}", . t, . layout.size.bytes(), . layout . ); . 21 ( 0.00%) let (largest, slargest, largest_index) = iter::zip(enum_definition.variants, variants) . .map(|(variant, variant_layout)| { . // Subtract the size of the enum tag. . let bytes = variant_layout.size.bytes().saturating_sub(tag_size); . . debug!("- variant `{}` is {} bytes large", variant.ident, bytes); . bytes . }) . .enumerate() . .fold((0, 0, 0), |(l, s, li), (idx, size)| { 119 ( 0.00%) if size > l { . (size, l, idx) . } else if size > s { . (l, size, li) . } else { . (l, s, li) . } . }); . . // We only warn if the largest variant is at least thrice as large as . // the second-largest. 49 ( 0.00%) if largest > slargest * 3 && slargest > 0 { . cx.struct_span_lint( . VARIANT_SIZE_DIFFERENCES, . enum_definition.variants[largest_index].span, . |lint| { . lint.build(&format!( . "enum variant is more than three times \ . larger ({} bytes) than the next largest", . largest . )) . .emit() . }, . ); . } . } 3,936 ( 0.00%) } . } . . declare_lint! { . /// The `invalid_atomic_ordering` lint detects passing an `Ordering` . /// to an atomic operation that does not support that ordering. . /// . /// ### Example . /// -- line 1401 ---------------------------------------- -- line 1437 ---------------------------------------- . INVALID_ATOMIC_ORDERING, . Deny, . "usage of invalid atomic ordering in atomic operations and memory fences" . } . . declare_lint_pass!(InvalidAtomicOrdering => [INVALID_ATOMIC_ORDERING]); . . impl InvalidAtomicOrdering { 2,329,248 ( 0.05%) fn inherent_atomic_method_call<'hir>( . cx: &LateContext<'_>, . expr: &Expr<'hir>, . recognized_names: &[Symbol], // used for fast path calculation . ) -> Option<(Symbol, &'hir [Expr<'hir>])> { . const ATOMIC_TYPES: &[Symbol] = &[ . sym::AtomicBool, . sym::AtomicPtr, . sym::AtomicUsize, -- line 1453 ---------------------------------------- -- line 1459 ---------------------------------------- . sym::AtomicIsize, . sym::AtomicI8, . sym::AtomicI16, . sym::AtomicI32, . sym::AtomicI64, . sym::AtomicI128, . ]; . if_chain! { 582,312 ( 0.01%) if let ExprKind::MethodCall(ref method_path, args, _) = &expr.kind; 1,768 ( 0.00%) if recognized_names.contains(&method_path.ident.name); . if let Some(m_def_id) = cx.typeck_results().type_dependent_def_id(expr.hir_id); . if let Some(impl_did) = cx.tcx.impl_of_method(m_def_id); . if let Some(adt) = cx.tcx.type_of(impl_did).ty_adt_def(); . // skip extension traits, only lint functions from the standard library . if cx.tcx.trait_id_of_impl(impl_did).is_none(); . . if let Some(parent) = cx.tcx.parent(adt.did); . if cx.tcx.is_diagnostic_item(sym::atomic_mod, parent); . if ATOMIC_TYPES.contains(&cx.tcx.item_name(adt.did)); . then { . return Some((method_path.ident.name, args)); . } . } 291,156 ( 0.01%) None 2,329,248 ( 0.05%) } . . fn matches_ordering(cx: &LateContext<'_>, did: DefId, orderings: &[Symbol]) -> bool { . let tcx = cx.tcx; . let atomic_ordering = tcx.get_diagnostic_item(sym::Ordering); . orderings.iter().any(|ordering| { . tcx.item_name(did) == *ordering && { . let parent = tcx.parent(did); . parent == atomic_ordering -- line 1491 ---------------------------------------- -- line 1502 ---------------------------------------- . None . } . } . . fn check_atomic_load_store(cx: &LateContext<'_>, expr: &Expr<'_>) { . use rustc_hir::def::{DefKind, Res}; . use rustc_hir::QPath; . if_chain! { 1,019,046 ( 0.02%) if let Some((method, args)) = Self::inherent_atomic_method_call(cx, expr, &[sym::load, sym::store]); . if let Some((ordering_arg, invalid_ordering)) = match method { . sym::load => Some((&args[1], sym::Release)), . sym::store => Some((&args[2], sym::Acquire)), . _ => None, . }; . . if let ExprKind::Path(QPath::Resolved(_, path)) = ordering_arg.kind; . if let Res::Def(DefKind::Ctor(..), ctor_id) = path.res; -- line 1518 ---------------------------------------- -- line 1531 ---------------------------------------- . } . }); . } . } . } . . fn check_memory_fence(cx: &LateContext<'_>, expr: &Expr<'_>) { . if_chain! { 291,156 ( 0.01%) if let ExprKind::Call(ref func, ref args) = expr.kind; 1,888 ( 0.00%) if let ExprKind::Path(ref func_qpath) = func.kind; 4,210 ( 0.00%) if let Some(def_id) = cx.qpath_res(func_qpath, func.hir_id).opt_def_id(); 2,718 ( 0.00%) if matches!(cx.tcx.get_diagnostic_name(def_id), Some(sym::fence | sym::compiler_fence)); . if let ExprKind::Path(ref ordering_qpath) = &args[0].kind; . if let Some(ordering_def_id) = cx.qpath_res(ordering_qpath, args[0].hir_id).opt_def_id(); . if Self::matches_ordering(cx, ordering_def_id, &[sym::Relaxed]); . then { . cx.struct_span_lint(INVALID_ATOMIC_ORDERING, args[0].span, |diag| { . diag.build("memory fences cannot have `Relaxed` ordering") . .help("consider using ordering modes `Acquire`, `Release`, `AcqRel` or `SeqCst`") . .emit(); . }); . } . } . } . . fn check_atomic_compare_exchange(cx: &LateContext<'_>, expr: &Expr<'_>) { . if_chain! { 1,310,202 ( 0.03%) if let Some((method, args)) = Self::inherent_atomic_method_call(cx, expr, &[sym::fetch_update, sym::compare_exchange, sym::compare_exchange_weak]); . if let Some((success_order_arg, failure_order_arg)) = match method { . sym::fetch_update => Some((&args[1], &args[2])), . sym::compare_exchange | sym::compare_exchange_weak => Some((&args[3], &args[4])), . _ => None, . }; . . if let Some(fail_ordering_def_id) = Self::opt_ordering_defid(cx, failure_order_arg); . then { -- line 1566 ---------------------------------------- -- line 1613 ---------------------------------------- . } . } . } . } . } . } . . impl<'tcx> LateLintPass<'tcx> for InvalidAtomicOrdering { 1,310,202 ( 0.03%) fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx Expr<'_>) { . Self::check_atomic_load_store(cx, expr); . Self::check_memory_fence(cx, expr); . Self::check_atomic_compare_exchange(cx, expr); 1,164,624 ( 0.02%) } . } 157,912 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_query_system/src/query/caches.rs -------------------------------------------------------------------------------- Ir -- line 94 ---------------------------------------- . &self, . state: &'s QueryCacheStore, . key: &K, . on_hit: OnHit, . ) -> Result . where . OnHit: FnOnce(&V, DepNodeIndex) -> R, . { 9,351 ( 0.00%) let (lookup, lock) = state.get_lookup(key); . let result = lock.raw_entry().from_key_hashed_nocheck(lookup.key_hash, key); . 6,267,824 ( 0.13%) if let Some((_, value)) = result { 3,128,807 ( 0.06%) let hit_result = on_hit(&value.0, value.1); 2,600,881 ( 0.05%) Ok(hit_result) . } else { 35,517 ( 0.00%) Err(lookup) . } . } . . #[inline] . fn complete( . &self, . lock_sharded_storage: &mut Self::Sharded, . key: K, . value: V, . index: DepNodeIndex, . ) -> Self::Stored { 65,267 ( 0.00%) lock_sharded_storage.insert(key, (value.clone(), index)); 2,468 ( 0.00%) value . } . . fn iter( . &self, . shards: &Sharded, . f: &mut dyn FnMut(&Self::Key, &Self::Value, DepNodeIndex), . ) { . let shards = shards.lock_shards(); -- line 130 ---------------------------------------- -- line 178 ---------------------------------------- . &self, . state: &'s QueryCacheStore, . key: &K, . on_hit: OnHit, . ) -> Result . where . OnHit: FnOnce(&&'tcx V, DepNodeIndex) -> R, . { 2,754 ( 0.00%) let (lookup, lock) = state.get_lookup(key); . let result = lock.raw_entry().from_key_hashed_nocheck(lookup.key_hash, key); . 185,487 ( 0.00%) if let Some((_, value)) = result { 256,214 ( 0.01%) let hit_result = on_hit(&&value.0, value.1); 34,228 ( 0.00%) Ok(hit_result) . } else { 2,430 ( 0.00%) Err(lookup) . } . } . . #[inline] . fn complete( . &self, . lock_sharded_storage: &mut Self::Sharded, . key: K, . value: V, . index: DepNodeIndex, . ) -> Self::Stored { 37,858 ( 0.00%) let value = self.arena.alloc((value, index)); . let value = unsafe { &*(value as *const _) }; . lock_sharded_storage.insert(key, value); . &value.0 . } . . fn iter( . &self, . shards: &Sharded, -- line 213 ---------------------------------------- 3,586,830 ( 0.07%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_passes/src/check_attr.rs -------------------------------------------------------------------------------- Ir -- line 23 ---------------------------------------- . use rustc_span::symbol::{sym, Symbol}; . use rustc_span::{MultiSpan, Span, DUMMY_SP}; . use std::collections::hash_map::Entry; . . pub(crate) fn target_from_impl_item<'tcx>( . tcx: TyCtxt<'tcx>, . impl_item: &hir::ImplItem<'_>, . ) -> Target { 1,970 ( 0.00%) match impl_item.kind { . hir::ImplItemKind::Const(..) => Target::AssocConst, . hir::ImplItemKind::Fn(..) => { 1,910 ( 0.00%) let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id()); 1,528 ( 0.00%) let containing_item = tcx.hir().expect_item(parent_hir_id); 764 ( 0.00%) let containing_impl_is_for_trait = match &containing_item.kind { . hir::ItemKind::Impl(impl_) => impl_.of_trait.is_some(), . _ => bug!("parent of an ImplItem must be an Impl"), . }; 1,146 ( 0.00%) if containing_impl_is_for_trait { . Target::Method(MethodKind::Trait { body: true }) . } else { . Target::Method(MethodKind::Inherent) . } . } . hir::ImplItemKind::TyAlias(..) => Target::AssocTy, . } . } -- line 48 ---------------------------------------- -- line 54 ---------------------------------------- . } . . struct CheckAttrVisitor<'tcx> { . tcx: TyCtxt<'tcx>, . } . . impl CheckAttrVisitor<'_> { . /// Checks any attribute. 1,474,040 ( 0.03%) fn check_attributes( . &self, . hir_id: HirId, . span: &Span, . target: Target, . item: Option>, . ) { . let mut doc_aliases = FxHashMap::default(); . let mut is_valid = true; 147,404 ( 0.00%) let mut specified_inline = None; . let mut seen = FxHashMap::default(); 1,179,232 ( 0.02%) let attrs = self.tcx.hir().attrs(hir_id); . for attr in attrs { 22,141 ( 0.00%) let attr_is_valid = match attr.name_or_empty() { . sym::inline => self.check_inline(hir_id, attr, span, target), . sym::non_exhaustive => self.check_non_exhaustive(hir_id, attr, span, target), . sym::marker => self.check_marker(hir_id, attr, span, target), . sym::target_feature => self.check_target_feature(hir_id, attr, span, target), . sym::track_caller => { . self.check_track_caller(hir_id, &attr.span, attrs, span, target) . } . sym::doc => self.check_doc_attrs( -- line 83 ---------------------------------------- -- line 116 ---------------------------------------- . sym::rustc_pass_by_value => self.check_pass_by_value(&attr, span, target), . sym::rustc_const_unstable . | sym::rustc_const_stable . | sym::unstable . | sym::stable . | sym::rustc_promotable => self.check_stability_promotable(&attr, span, target), . _ => true, . }; 5,181 ( 0.00%) is_valid &= attr_is_valid; . . // lint-only checks 19,895 ( 0.00%) match attr.name_or_empty() { . sym::cold => self.check_cold(hir_id, attr, span, target), . sym::link => self.check_link(hir_id, attr, span, target), . sym::link_name => self.check_link_name(hir_id, attr, span, target), . sym::link_section => self.check_link_section(hir_id, attr, span, target), . sym::no_mangle => self.check_no_mangle(hir_id, attr, span, target), . sym::deprecated | sym::rustc_deprecated => { . self.check_deprecated(hir_id, attr, span, target) . } 2 ( 0.00%) sym::macro_use | sym::macro_escape => self.check_macro_use(hir_id, attr, target), . sym::path => self.check_generic_attr(hir_id, attr, target, &[Target::Mod]), . sym::plugin_registrar => self.check_plugin_registrar(hir_id, attr, target), . sym::macro_export => self.check_macro_export(hir_id, attr, target), . sym::ignore | sym::should_panic | sym::proc_macro_derive => { . self.check_generic_attr(hir_id, attr, target, &[Target::Fn]) . } . sym::automatically_derived => { 560 ( 0.00%) self.check_generic_attr(hir_id, attr, target, &[Target::Impl]) . } . sym::no_implicit_prelude => { . self.check_generic_attr(hir_id, attr, target, &[Target::Mod]) . } . _ => {} . } . 1,727 ( 0.00%) let builtin = attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)); . 3,507 ( 0.00%) if hir_id != CRATE_HIR_ID { 753 ( 0.00%) if let Some(BuiltinAttribute { type_: AttributeType::CrateLevel, .. }) = 1,673 ( 0.00%) attr.ident().and_then(|ident| BUILTIN_ATTRIBUTE_MAP.get(&ident.name)) . { . self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { . let msg = match attr.style { . ast::AttrStyle::Outer => { . "crate-level attribute should be an inner attribute: add an exclamation \ . mark: `#![foo]`" . } . ast::AttrStyle::Inner => "crate-level attribute should be in the root module", . }; . lint.build(msg).emit() . }); . } . } . 3,958 ( 0.00%) if let Some(BuiltinAttribute { duplicates, .. }) = builtin { 756 ( 0.00%) check_duplicates(self.tcx, attr, hir_id, *duplicates, &mut seen); . } . . // Warn on useless empty attributes. 15,392 ( 0.00%) if matches!( 1,727 ( 0.00%) attr.name_or_empty(), . sym::macro_use . | sym::allow . | sym::warn . | sym::deny . | sym::forbid . | sym::feature . | sym::repr . | sym::target_feature 225 ( 0.00%) ) && attr.meta_item_list().map_or(false, |list| list.is_empty()) . { . self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { . lint.build("unused attribute") . .span_suggestion( . attr.span, . "remove this attribute", . String::new(), . Applicability::MachineApplicable, -- line 194 ---------------------------------------- -- line 197 ---------------------------------------- . "attribute `{}` with an empty list has no effect", . attr.name_or_empty() . )) . .emit(); . }); . } . } . 738 ( 0.00%) if !is_valid { . return; . } . 294,808 ( 0.01%) if matches!(target, Target::Closure | Target::Fn | Target::Method(_) | Target::ForeignFn) { 1,854 ( 0.00%) self.tcx.ensure().codegen_fn_attrs(self.tcx.hir().local_def_id(hir_id)); . } . . self.check_repr(attrs, span, target, item, hir_id); . self.check_used(attrs, target); 1,179,232 ( 0.02%) } . . fn inline_attr_str_error_with_macro_def(&self, hir_id: HirId, attr: &Attribute, sym: &str) { . self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { . lint.build(&format!( . "`#[{}]` is ignored on struct fields, match arms and macro defs", . sym, . )) . .warn( -- line 223 ---------------------------------------- -- line 246 ---------------------------------------- . for more information", . ) . .emit(); . }); . } . . /// Checks if an `#[inline]` is applied to a function or a closure. Returns `true` if valid. . fn check_inline(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool { 475 ( 0.00%) match target { . Target::Fn . | Target::Closure . | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true, . Target::Method(MethodKind::Trait { body: false }) | Target::ForeignFn => { . self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { . lint.build("`#[inline]` is ignored on function prototypes").emit() . }); . true -- line 262 ---------------------------------------- -- line 295 ---------------------------------------- . ) . .span_label(*span, "not a function or closure") . .emit(); . false . } . } . } . 728 ( 0.00%) fn check_generic_attr( . &self, . hir_id: HirId, . attr: &Attribute, . target: Target, . allowed_targets: &[Target], . ) { . if !allowed_targets.iter().any(|t| t == &target) { . let name = attr.name_or_empty(); -- line 311 ---------------------------------------- -- line 324 ---------------------------------------- . b.push_str(&(allowed_target.to_string() + "s")); . b . }); . self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { . lint.build(&format!("`#[{name}]` only has an effect on {}", supported_names)) . .emit(); . }); . } 392 ( 0.00%) } . . /// Checks if `#[naked]` is applied to a function definition. . fn check_naked(&self, hir_id: HirId, attr: &Attribute, span: &Span, target: Target) -> bool { . match target { . Target::Fn . | Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => true, . // FIXME(#80564): We permit struct fields, match arms and macro defs to have an . // `#[allow_internal_unstable]` attribute with just a lint, because we previously -- line 340 ---------------------------------------- -- line 818 ---------------------------------------- . . /// Checks that an attribute is used at the crate level. Returns `true` if valid. . fn check_attr_crate_level( . &self, . attr: &Attribute, . meta: &NestedMetaItem, . hir_id: HirId, . ) -> bool { 2 ( 0.00%) if hir_id != CRATE_HIR_ID { . self.tcx.struct_span_lint_hir( . INVALID_DOC_ATTRIBUTES, . hir_id, . meta.span(), . |lint| { . let mut err = lint.build( . "this attribute can only be applied at the crate level", . ); -- line 834 ---------------------------------------- -- line 906 ---------------------------------------- . attr: &Attribute, . hir_id: HirId, . target: Target, . specified_inline: &mut Option<(bool, Span)>, . aliases: &mut FxHashMap, . ) -> bool { . let mut is_valid = true; . 168 ( 0.00%) if let Some(list) = attr.meta().and_then(|mi| mi.meta_item_list().map(|l| l.to_vec())) { . for meta in &list { 48 ( 0.00%) if let Some(i_meta) = meta.meta_item() { 72 ( 0.00%) match i_meta.name_or_empty() { . sym::alias . if !self.check_attr_not_crate_level(&meta, hir_id, "alias") . || !self.check_doc_alias(&meta, hir_id, target, aliases) => . { . is_valid = false . } . . sym::keyword -- line 925 ---------------------------------------- -- line 1059 ---------------------------------------- . }, . ); . is_valid = false; . } . } . } . . is_valid 36 ( 0.00%) } . . /// Warns against some misuses of `#[pass_by_value]` . fn check_pass_by_value(&self, attr: &Attribute, span: &Span, target: Target) -> bool { . match target { . Target::Struct | Target::Enum | Target::TyAlias => true, . _ => { . self.tcx . .sess -- line 1075 ---------------------------------------- -- line 1672 ---------------------------------------- . hint_spans, . E0692, . "transparent {} cannot have other repr hints", . target . ) . .emit(); . } . // Warn on repr(u8, u16), repr(C, simd), and c-like-enum-repr(C, u8) 1,179,232 ( 0.02%) if (int_reprs > 1) . || (is_simd && is_c) 589,616 ( 0.01%) || (int_reprs == 1 . && is_c . && item.map_or(false, |item| { . if let ItemLike::Item(item) = item { . return is_c_like_enum(item); . } . return false; . })) . { -- line 1690 ---------------------------------------- -- line 1698 ---------------------------------------- . .emit(); . }, . ); . } . } . . fn check_used(&self, attrs: &[Attribute], target: Target) { . for attr in attrs { 252 ( 0.00%) if attr.has_name(sym::used) && target != Target::Static { . self.tcx . .sess . .span_err(attr.span, "attribute must be applied to a `static` variable"); . } . } . } . . /// Outputs an error for `#[allow_internal_unstable]` which can only be applied to macros. -- line 1714 ---------------------------------------- -- line 1823 ---------------------------------------- . .emit(); . false . } . _ => true, . } . } . . fn check_deprecated(&self, hir_id: HirId, attr: &Attribute, _span: &Span, target: Target) { 2 ( 0.00%) match target { . Target::Closure | Target::Expression | Target::Statement | Target::Arm => { . self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { . lint.build("attribute is ignored here").emit(); . }); . } . _ => {} . } . } . . fn check_macro_use(&self, hir_id: HirId, attr: &Attribute, target: Target) { 2 ( 0.00%) let name = attr.name_or_empty(); 2 ( 0.00%) match target { . Target::ExternCrate | Target::Mod => {} . _ => { . self.tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, attr.span, |lint| { . lint.build(&format!( . "`#[{name}]` only has an effect on `extern crate` and modules" . )) . .emit(); . }); -- line 1851 ---------------------------------------- -- line 1869 ---------------------------------------- . } . } . } . . impl<'tcx> Visitor<'tcx> for CheckAttrVisitor<'tcx> { . type NestedFilter = nested_filter::OnlyBodies; . . fn nested_visit_map(&mut self) -> Self::Map { 401 ( 0.00%) self.tcx.hir() . } . 4,428 ( 0.00%) fn visit_item(&mut self, item: &'tcx Item<'tcx>) { . // Historically we've run more checks on non-exported than exported macros, . // so this lets us continue to run them while maintaining backwards compatibility. . // In the long run, the checks should be harmonized. 984 ( 0.00%) if let ItemKind::Macro(ref macro_def) = item.kind { 4 ( 0.00%) let def_id = item.def_id.to_def_id(); 40 ( 0.00%) if macro_def.macro_rules && !self.tcx.has_attr(def_id, sym::macro_export) { . check_non_exported_macro_for_invalid_attrs(self.tcx, item); . } . } . 984 ( 0.00%) let target = Target::from_item(item); 4,920 ( 0.00%) self.check_attributes(item.hir_id(), &item.span, target, Some(ItemLike::Item(item))); 1,476 ( 0.00%) intravisit::walk_item(self, item) 3,936 ( 0.00%) } . . fn visit_generic_param(&mut self, generic_param: &'tcx hir::GenericParam<'tcx>) { 360 ( 0.00%) let target = Target::from_generic_param(generic_param); 1,620 ( 0.00%) self.check_attributes(generic_param.hir_id, &generic_param.span, target, None); 540 ( 0.00%) intravisit::walk_generic_param(self, generic_param) . } . . fn visit_trait_item(&mut self, trait_item: &'tcx TraitItem<'tcx>) { 2 ( 0.00%) let target = Target::from_trait_item(trait_item); 8 ( 0.00%) self.check_attributes(trait_item.hir_id(), &trait_item.span, target, None); 3 ( 0.00%) intravisit::walk_trait_item(self, trait_item) . } . . fn visit_field_def(&mut self, struct_field: &'tcx hir::FieldDef<'tcx>) { 496 ( 0.00%) self.check_attributes(struct_field.hir_id, &struct_field.span, Target::Field, None); . intravisit::walk_field_def(self, struct_field); . } . . fn visit_arm(&mut self, arm: &'tcx hir::Arm<'tcx>) { 1,656 ( 0.00%) self.check_attributes(arm.hir_id, &arm.span, Target::Arm, None); 621 ( 0.00%) intravisit::walk_arm(self, arm); . } . . fn visit_foreign_item(&mut self, f_item: &'tcx ForeignItem<'tcx>) { . let target = Target::from_foreign_item(f_item); . self.check_attributes( . f_item.hir_id(), . &f_item.span, . target, . Some(ItemLike::ForeignItem(f_item)), . ); . intravisit::walk_foreign_item(self, f_item) . } . 1,182 ( 0.00%) fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { . let target = target_from_impl_item(self.tcx, impl_item); 1,576 ( 0.00%) self.check_attributes(impl_item.hir_id(), &impl_item.span, target, None); 591 ( 0.00%) intravisit::walk_impl_item(self, impl_item) 985 ( 0.00%) } . . fn visit_stmt(&mut self, stmt: &'tcx hir::Stmt<'tcx>) { . // When checking statements ignore expressions, they will be checked later. 2,025 ( 0.00%) if let hir::StmtKind::Local(ref l) = stmt.kind { 1,776 ( 0.00%) self.check_attributes(l.hir_id, &stmt.span, Target::Statement, None); . } . intravisit::walk_stmt(self, stmt) . } . . fn visit_expr(&mut self, expr: &'tcx hir::Expr<'tcx>) { 143,394 ( 0.00%) let target = match expr.kind { . hir::ExprKind::Closure(..) => Target::Closure, . _ => Target::Expression, . }; . 1,151,244 ( 0.02%) self.check_attributes(expr.hir_id, &expr.span, target, None); 435,231 ( 0.01%) intravisit::walk_expr(self, expr) . } . . fn visit_variant( . &mut self, . variant: &'tcx hir::Variant<'tcx>, . generics: &'tcx hir::Generics<'tcx>, . item_id: HirId, . ) { 154 ( 0.00%) self.check_attributes(variant.id, &variant.span, Target::Variant, None); . intravisit::walk_variant(self, variant, generics, item_id) . } . . fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { 3,094 ( 0.00%) self.check_attributes(param.hir_id, ¶m.span, Target::Param, None); . . intravisit::walk_param(self, param); . } . } . . fn is_c_like_enum(item: &Item<'_>) -> bool { . if let ItemKind::Enum(ref def, _) = item.kind { . for variant in def.variants { -- line 1972 ---------------------------------------- -- line 1999 ---------------------------------------- . sym::test_case, . sym::global_allocator, . sym::bench, . ]; . . for attr in attrs { . // This function should only be called with crate attributes . // which are inner attributes always but lets check to make sure 54 ( 0.00%) if attr.style == AttrStyle::Inner { . for attr_to_check in ATTRS_TO_CHECK { 11 ( 0.00%) if attr.has_name(*attr_to_check) { . let mut err = tcx.sess.struct_span_err( . attr.span, . &format!( . "`{}` attribute cannot be used at crate level", . attr_to_check.to_ident_string() . ), . ); . // Only emit an error with a suggestion if we can create a -- line 2017 ---------------------------------------- -- line 2028 ---------------------------------------- . err.emit() . } . } . } . } . } . . fn check_non_exported_macro_for_invalid_attrs(tcx: TyCtxt<'_>, item: &Item<'_>) { 5 ( 0.00%) let attrs = tcx.hir().attrs(item.hir_id()); . . for attr in attrs { . if attr.has_name(sym::inline) { . struct_span_err!( . tcx.sess, . attr.span, . E0518, . "attribute should be applied to function or closure", . ) . .span_label(attr.span, "not a function or closure") . .emit(); . } . } . } . 171 ( 0.00%) fn check_mod_attrs(tcx: TyCtxt<'_>, module_def_id: LocalDefId) { 19 ( 0.00%) let check_attr_visitor = &mut CheckAttrVisitor { tcx }; 114 ( 0.00%) tcx.hir().visit_item_likes_in_module(module_def_id, &mut check_attr_visitor.as_deep_visitor()); 19 ( 0.00%) if module_def_id.is_top_level_module() { 7 ( 0.00%) check_attr_visitor.check_attributes(CRATE_HIR_ID, &DUMMY_SP, Target::Mod, None); 4 ( 0.00%) check_invalid_crate_level_attr(tcx, tcx.hir().krate_attrs()); . } 152 ( 0.00%) } . . pub(crate) fn provide(providers: &mut Providers) { 2 ( 0.00%) *providers = Providers { check_mod_attrs, ..*providers }; . } . . fn check_duplicates( . tcx: TyCtxt<'_>, . attr: &Attribute, . hir_id: HirId, . duplicates: AttributeDuplicates, . seen: &mut FxHashMap, . ) { . use AttributeDuplicates::*; 1,263 ( 0.00%) if matches!(duplicates, WarnFollowingWordOnly) && !attr.is_word() { . return; . } . match duplicates { . DuplicatesOk => {} . WarnFollowing | FutureWarnFollowing | WarnFollowingWordOnly | FutureWarnPreceding => { 165 ( 0.00%) match seen.entry(attr.name_or_empty()) { . Entry::Occupied(mut entry) => { . let (this, other) = if matches!(duplicates, FutureWarnPreceding) { . let to_remove = entry.insert(attr.span); . (to_remove, attr.span) . } else { . (attr.span, *entry.get()) . }; . tcx.struct_span_lint_hir(UNUSED_ATTRIBUTES, hir_id, this, |lint| { -- line 2087 ---------------------------------------- -- line 2098 ---------------------------------------- . being phased out; it will become a hard error in \ . a future release!", . ); . } . db.emit(); . }); . } . Entry::Vacant(entry) => { 165 ( 0.00%) entry.insert(attr.span); . } . } . } . ErrorFollowing | ErrorPreceding => match seen.entry(attr.name_or_empty()) { . Entry::Occupied(mut entry) => { . let (this, other) = if matches!(duplicates, ErrorPreceding) { . let to_remove = entry.insert(attr.span); . (to_remove, attr.span) -- line 2114 ---------------------------------------- 1,052,843 ( 0.02%) -------------------------------------------------------------------------------- -- 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}; . 423,818 ( 0.01%) 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); . } . } . } . }; . } . 7,772 ( 0.00%) #[derive(Clone)] . pub struct Parser<'a> { 266 ( 0.00%) pub sess: &'a ParseSess, . /// The current token. 190 ( 0.00%) pub token: Token, . /// The spacing for the current token 128 ( 0.00%) pub token_spacing: Spacing, . /// The previous token. 285 ( 0.00%) pub prev_token: Token, 161 ( 0.00%) pub capture_cfg: bool, 355 ( 0.00%) restrictions: Restrictions, 256 ( 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, 256 ( 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. 256 ( 0.00%) unmatched_angle_bracket_count: u32, 384 ( 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. 128 ( 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` 128 ( 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, . } . 555 ( 0.00%) #[derive(Clone)] . struct CaptureState { 512 ( 0.00%) capturing: Capturing, 128 ( 0.00%) replace_ranges: Vec, . inner_attr_ranges: FxHashMap, . } . . impl<'a> Drop for Parser<'a> { . fn drop(&mut self) { 1,192 ( 0.00%) emit_unclosed_delims(&mut self.unclosed_delims, &self.sess); . } . } . 52,920 ( 0.00%) #[derive(Clone)] . struct TokenCursor { . frame: TokenCursorFrame, 12,295 ( 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. 3,824 ( 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, . } . 23,780 ( 0.00%) #[derive(Clone)] . struct TokenCursorFrame { 6,565 ( 0.00%) delim: token::DelimToken, . span: DelimSpan, . open_delim: bool, 13,130 ( 0.00%) tree_cursor: tokenstream::Cursor, . close_delim: bool, . } . . impl TokenCursorFrame { . fn new(span: DelimSpan, delim: DelimToken, tts: TokenStream) -> Self { 1,155 ( 0.00%) TokenCursorFrame { . delim, . span, . open_delim: false, 4,759 ( 0.00%) tree_cursor: tts.into_trees(), . close_delim: false, . } . } . } . . impl TokenCursor { 3,751,596 ( 0.08%) fn next(&mut self) -> (Token, Spacing) { . loop { 1,593,008 ( 0.03%) let (tree, spacing) = if !self.frame.open_delim { 4,297 ( 0.00%) self.frame.open_delim = true; 21,485 ( 0.00%) TokenTree::open_tt(self.frame.span, self.frame.delim).into() 3,741,173 ( 0.08%) } else if let Some(tree) = self.frame.tree_cursor.next_with_spacing() { . tree 17,306 ( 0.00%) } else if !self.frame.close_delim { 4,179 ( 0.00%) self.frame.close_delim = true; 20,895 ( 0.00%) TokenTree::close_tt(self.frame.span, self.frame.delim).into() 8,358 ( 0.00%) } else if let Some(frame) = self.stack.pop() { 54,327 ( 0.00%) self.frame = frame; . continue; . } else { 5,310 ( 0.00%) (TokenTree::Token(Token::new(token::Eof, DUMMY_SP)), Spacing::Alone) . }; . 633,860 ( 0.01%) match tree { . TokenTree::Token(token) => { 2,501,064 ( 0.05%) return (token, spacing); . } . TokenTree::Delimited(sp, delim, tts) => { . let frame = TokenCursorFrame::new(sp, delim, tts); . self.stack.push(mem::replace(&mut self.frame, frame)); . } . } . } 2,501,064 ( 0.05%) } . 31,030 ( 0.00%) fn next_desugared(&mut self) -> (Token, Spacing) { 9,309 ( 0.00%) let (data, attr_style, sp) = match self.next() { . (Token { kind: token::DocComment(_, attr_style, data), span }, _) => { . (data, attr_style, span) . } 15,515 ( 0.00%) tok => return tok, . }; . . // Searches for the occurrences of `"#*` and returns the minimum number of `#`s . // required to wrap the text. . let mut num_of_hashes = 0; . let mut count = 0; . for ch in data.as_str().chars() { . count = match ch { -- line 298 ---------------------------------------- -- line 332 ---------------------------------------- . .iter() . .cloned() . .collect::() . }, . ), . )); . . self.next() 27,927 ( 0.00%) } . } . 13,420 ( 0.00%) #[derive(Debug, Clone, PartialEq)] . enum TokenType { 10,736 ( 0.00%) Token(TokenKind), . Keyword(Symbol), . Operator, . Lifetime, . Ident, . Path, . Type, . Const, . } -- line 353 ---------------------------------------- -- line 378 ---------------------------------------- . /// The separator token. . sep: Option, . /// `true` if a trailing separator is allowed. . trailing_sep_allowed: bool, . } . . impl SeqSep { . fn trailing_allowed(t: TokenKind) -> SeqSep { 69 ( 0.00%) SeqSep { sep: Some(t), trailing_sep_allowed: true } . } . . fn none() -> SeqSep { . SeqSep { sep: None, trailing_sep_allowed: false } . } . } . . pub enum FollowedByType { . Yes, . No, . } . . fn token_descr_opt(token: &Token) -> Option<&'static str> { 308 ( 0.00%) Some(match token.kind { 616 ( 0.00%) _ if token.is_special_ident() => "reserved identifier", 616 ( 0.00%) _ if token.is_used_keyword() => "keyword", 616 ( 0.00%) _ if token.is_unused_keyword() => "reserved keyword", . token::DocComment(..) => "doc comment", . _ => return None, . }) . } . 1,078 ( 0.00%) pub(super) fn token_descr(token: &Token) -> String { 308 ( 0.00%) let token_str = pprust::token_to_string(token); . match token_descr_opt(token) { . Some(prefix) => format!("{} `{}`", prefix, token_str), 1,078 ( 0.00%) _ => format!("`{}`", token_str), . } 770 ( 0.00%) } . . impl<'a> Parser<'a> { 3,234 ( 0.00%) pub fn new( . sess: &'a ParseSess, . tokens: TokenStream, . desugar_doc_comments: bool, . subparser_name: Option<&'static str>, . ) -> Self { 231 ( 0.00%) let mut start_frame = TokenCursorFrame::new(DelimSpan::dummy(), token::NoDelim, tokens); 462 ( 0.00%) start_frame.open_delim = true; . start_frame.close_delim = true; . 7,161 ( 0.00%) let mut parser = Parser { . sess, 231 ( 0.00%) token: Token::dummy(), . token_spacing: Spacing::Alone, 231 ( 0.00%) prev_token: Token::dummy(), . capture_cfg: false, . restrictions: Restrictions::empty(), . expected_tokens: Vec::new(), . token_cursor: TokenCursor { 1,386 ( 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. 462 ( 0.00%) parser.bump(); . . parser 2,079 ( 0.00%) } . . fn next_tok(&mut self, fallback_span: Span) -> (Token, Spacing) { . loop { 1,864,098 ( 0.04%) let (mut next, spacing) = if self.desugar_doc_comments { 12,412 ( 0.00%) self.token_cursor.next_desugared() . } else { 922,740 ( 0.02%) self.token_cursor.next() . }; 1,242,732 ( 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 310,683 ( 0.01%) self.token_cursor.break_last_token = false; 1,242,732 ( 0.03%) if next.span.is_dummy() { . // Tweak the location for better diagnostics, but keep syntactic context intact. 1,012 ( 0.00%) next.span = fallback_span.with_ctxt(next.span.ctxt()); . } 944,586 ( 0.02%) if matches!( 621,366 ( 0.01%) next.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 1,242,732 ( 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`. 1,263,537 ( 0.03%) pub fn expect(&mut self, t: &TokenKind) -> PResult<'a, bool /* recovered */> { 140,393 ( 0.00%) if self.expected_tokens.is_empty() { 2,016 ( 0.00%) if self.token == *t { 1,680 ( 0.00%) self.bump(); . Ok(false) . } else { . self.unexpected_try_recover(t) . } . } else { 1,680,684 ( 0.03%) self.expect_one_of(slice::from_ref(t), &[]) . } 2,105,895 ( 0.04%) } . . /// 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. 1,694,484 ( 0.03%) pub fn expect_one_of( . &mut self, . edible: &[TokenKind], . inedible: &[TokenKind], . ) -> PResult<'a, bool /* recovered */> { 282,414 ( 0.01%) if edible.contains(&self.token.kind) { 422,232 ( 0.01%) self.bump(); . Ok(false) . } else if inedible.contains(&self.token.kind) { . // leave it in the input . Ok(false) . } else if self.last_unexpected_token_span == Some(self.token.span) { . FatalError.raise(); . } else { . self.expected_one_of_not_found(edible, inedible) . } 2,118,105 ( 0.04%) } . . // Public for rustfmt usage. . pub fn parse_ident(&mut self) -> PResult<'a, Ident> { 23,849 ( 0.00%) self.parse_ident_common(true) . } . . fn ident_or_err(&mut self) -> PResult<'a, (Ident, /* is_raw */ bool)> { 19,980 ( 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(), . }) . } . 46,060 ( 0.00%) fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, Ident> { 6,580 ( 0.00%) let (ident, is_raw) = self.ident_or_err()?; 39,480 ( 0.00%) if !is_raw && ident.is_reserved() { . let mut err = self.expected_ident_found(); . if recover { . err.emit(); . } else { . return Err(err); . } . } 26,320 ( 0.00%) self.bump(); . Ok(ident) 65,800 ( 0.00%) } . . /// Checks if the next token is `tok`, and returns `true` if so. . /// . /// This method will automatically add `tok` to `expected_tokens` if `tok` is not . /// encountered. 5,409,586 ( 0.11%) fn check(&mut self, tok: &TokenKind) -> bool { 2,323,504 ( 0.05%) let is_present = self.token == *tok; 1,551,220 ( 0.03%) if !is_present { 3,805,727 ( 0.08%) self.expected_tokens.push(TokenType::Token(tok.clone())); . } . is_present 5,409,586 ( 0.11%) } . . /// Consumes a token 'tok' if it exists. Returns whether the given token was present. 232 ( 0.00%) pub fn eat(&mut self, tok: &TokenKind) -> bool { 945,959 ( 0.02%) let is_present = self.check(tok); 630,005 ( 0.01%) if is_present { 17,744 ( 0.00%) self.bump() . } . is_present 290 ( 0.00%) } . . /// If the next token is the given keyword, returns `true` without eating it. . /// An expectation is also added for diagnostics purposes. 15,830 ( 0.00%) fn check_keyword(&mut self, kw: Symbol) -> bool { 5,146 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw)); 125,327 ( 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. 34,130 ( 0.00%) pub fn eat_keyword(&mut self, kw: Symbol) -> bool { 27,388 ( 0.00%) if self.check_keyword(kw) { 3,505 ( 0.00%) self.bump(); . true . } else { . false . } 34,130 ( 0.00%) } . . fn eat_keyword_noexpect(&mut self, kw: Symbol) -> bool { 5,342 ( 0.00%) if self.token.is_keyword(kw) { 1,127 ( 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. 420 ( 0.00%) fn expect_keyword(&mut self, kw: Symbol) -> PResult<'a, ()> { . if !self.eat_keyword(kw) { self.unexpected() } else { Ok(()) } 336 ( 0.00%) } . . /// Is the given keyword `kw` followed by a non-reserved identifier? 23,664 ( 0.00%) fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool { 11,832 ( 0.00%) self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident()) 26,622 ( 0.00%) } . 31,338 ( 0.00%) fn check_or_expected(&mut self, ok: bool, typ: TokenType) -> bool { 11,908 ( 0.00%) if ok { . true . } else { 6,044 ( 0.00%) self.expected_tokens.push(typ); . false . } 31,338 ( 0.00%) } . . fn check_ident(&mut self) -> bool { 6,301 ( 0.00%) self.check_or_expected(self.token.is_ident(), TokenType::Ident) . } . 11,016 ( 0.00%) fn check_path(&mut self) -> bool { 24,460 ( 0.00%) self.check_or_expected(self.token.is_path_start(), TokenType::Path) 13,770 ( 0.00%) } . . fn check_type(&mut self) -> bool { 2,664 ( 0.00%) self.check_or_expected(self.token.can_begin_type(), TokenType::Type) . } . . fn check_const_arg(&mut self) -> bool { 2,424 ( 0.00%) self.check_or_expected(self.token.can_begin_const_arg(), TokenType::Const) . } . 6,228 ( 0.00%) fn check_inline_const(&self, dist: usize) -> bool { 3,460 ( 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, . }) 6,228 ( 0.00%) } . . /// Checks to see if the next token is either `+` or `+=`. . /// Otherwise returns `false`. . fn check_plus(&mut self) -> bool { 3,704 ( 0.00%) self.check_or_expected( 1,852 ( 0.00%) self.token.is_like_plus(), 1,852 ( 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. 56,772 ( 0.00%) fn break_and_eat(&mut self, expected: TokenKind) -> bool { 33,117 ( 0.00%) if self.token.kind == expected { 3,398 ( 0.00%) self.bump(); . return true; . } 15,160 ( 0.00%) match self.token.kind.break_two_token_op() { 1,009 ( 0.00%) Some((first, second)) if first == expected => { 256 ( 0.00%) let first_span = self.sess.source_map().start_point(self.token.span); 320 ( 0.00%) let second_span = self.token.span.with_lo(first_span.hi()); 576 ( 0.00%) 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 . // is not needed (we'll capture the entire 'glued' token), . // and `next_tok` will set this field to `None` 64 ( 0.00%) self.token_cursor.break_last_token = true; . // Use the spacing of the glued token as the spacing . // of the unglued second token. 896 ( 0.00%) self.bump_with((Token::new(second, second_span), self.token_spacing)); . true . } . _ => { 8,904 ( 0.00%) self.expected_tokens.push(TokenType::Token(expected)); . false . } . } 54,638 ( 0.00%) } . . /// Eats `+` possibly breaking tokens like `+=` in process. . fn eat_plus(&mut self) -> bool { 332 ( 0.00%) self.break_and_eat(token::BinOp(token::Plus)) . } . . /// Eats `&` possibly breaking tokens like `&&` in process. . /// Signals an error if `&` is not eaten. . fn expect_and(&mut self) -> PResult<'a, ()> { 5,340 ( 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, ()> { 138 ( 0.00%) if self.break_and_eat(token::BinOp(token::Or)) { Ok(()) } else { self.unexpected() } . } . . /// Eats `<` possibly breaking tokens like `<<` in process. 2,398 ( 0.00%) fn eat_lt(&mut self) -> bool { 10,666 ( 0.00%) let ate = self.break_and_eat(token::Lt); 6,973 ( 0.00%) if ate { . // See doc comment for `unmatched_angle_bracket_count`. 1,684 ( 0.00%) self.unmatched_angle_bracket_count += 1; 1,779 ( 0.00%) self.max_angle_bracket_count += 1; . debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count); . } . ate 2,398 ( 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, ()> { 2,526 ( 0.00%) if self.break_and_eat(token::Gt) { . // See doc comment for `unmatched_angle_bracket_count`. 1,263 ( 0.00%) if self.unmatched_angle_bracket_count > 0 { 842 ( 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 { 836,574 ( 0.02%) TokenExpectType::Expect => self.check(k), 369 ( 0.00%) TokenExpectType::NoExpect => self.token == **k, . }) . } . . fn parse_seq_to_before_tokens( . &mut self, . kets: &[&TokenKind], . sep: SeqSep, . expect: TokenExpectType, -- line 759 ---------------------------------------- -- line 761 ---------------------------------------- . ) -> PResult<'a, (Vec, bool /* trailing */, bool /* recovered */)> { . let mut first = true; . let mut recovered = false; . let mut trailing = false; . let mut v = vec![]; . let unclosed_delims = !self.unclosed_delims.is_empty(); . . while !self.expect_any_with_type(kets, expect) { 698,517 ( 0.01%) if let token::CloseDelim(..) | token::Eof = self.token.kind { . break; . } 283,247 ( 0.01%) if let Some(ref t) = sep.sep { 421,367 ( 0.01%) if first { . first = false; . } else { 1,104,036 ( 0.02%) 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; . } . } . } . } . } . } 279,048 ( 0.01%) if sep.trailing_sep_allowed && self.expect_any_with_type(kets, expect) { . trailing = true; . break; . } . 140,048 ( 0.00%) let t = f(self)?; 1,646 ( 0.00%) v.push(t); . } . 7,356 ( 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)> { 7,452 ( 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. 8,160 ( 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 */)> { 4,473 ( 0.00%) let (val, trailing, recovered) = self.parse_seq_to_before_end(ket, sep, f)?; 2,791 ( 0.00%) if !recovered { . self.eat(ket); . } 10,098 ( 0.00%) Ok((val, trailing)) 6,528 ( 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)> { 3,015 ( 0.00%) self.expect(bra)?; 6,528 ( 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( 1,248 ( 0.00%) &token::OpenDelim(delim), 1,691 ( 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. 4,039,711 ( 0.08%) fn bump_with(&mut self, (next_token, next_spacing): (Token, Spacing)) { . // Bumping after EOF is a bad sign, usually an infinite loop. 1,864,482 ( 0.04%) if self.prev_token.kind == TokenKind::Eof { . let msg = "attempted to bump the parser past EOF (may be stuck in a loop)"; . self.span_bug(self.token.span, msg); . } . . // Update the current and previous tokens. 1,242,988 ( 0.03%) self.prev_token = mem::replace(&mut self.token, next_token); 310,747 ( 0.01%) self.token_spacing = next_spacing; . . // Diagnostics. 310,747 ( 0.01%) self.expected_tokens.clear(); . } . . /// Advance the parser by one token. 2,485,464 ( 0.05%) pub fn bump(&mut self) { 1,242,732 ( 0.03%) let next_token = self.next_tok(self.token.span); 1,864,098 ( 0.04%) self.bump_with(next_token); 2,485,464 ( 0.05%) } . . /// Look-ahead `dist` tokens of `self.token` and get access to that token there. . /// When `dist == 0` then the current token is looked at. 392 ( 0.00%) pub fn look_ahead(&self, dist: usize, looker: impl FnOnce(&Token) -> R) -> R { 2,566 ( 0.00%) if dist == 0 { 1,016 ( 0.00%) return looker(&self.token); . } . 148,468 ( 0.00%) let frame = &self.token_cursor.frame; 149,761 ( 0.00%) if frame.delim != DelimToken::NoDelim { . let all_normal = (0..dist).all(|i| { 443,968 ( 0.01%) let token = frame.tree_cursor.look_ahead(i); 591,774 ( 0.01%) !matches!(token, Some(TokenTree::Delimited(_, DelimToken::NoDelim, _))) . }); . if all_normal { 739,687 ( 0.02%) return match frame.tree_cursor.look_ahead(dist - 1) { 293,539 ( 0.01%) Some(tree) => match tree { 146,402 ( 0.00%) TokenTree::Token(token) => looker(token), . TokenTree::Delimited(dspan, delim, _) => { 3,105 ( 0.00%) looker(&Token::new(token::OpenDelim(*delim), dspan.open)) . } . }, 8,126 ( 0.00%) None => looker(&Token::new(token::CloseDelim(frame.delim), frame.span.close)), . }; . } . } . . let mut cursor = self.token_cursor.clone(); . let mut i = 0; 1,912 ( 0.00%) let mut token = Token::dummy(); 2,450 ( 0.00%) while i < dist { 14,654 ( 0.00%) token = cursor.next().0; 6,332 ( 0.00%) if matches!( 3,900 ( 0.00%) token.kind, . token::OpenDelim(token::NoDelim) | token::CloseDelim(token::NoDelim) . ) { . continue; . } 1,225 ( 0.00%) i += 1; . } 227 ( 0.00%) return looker(&token); 441 ( 0.00%) } . . /// Returns whether any of the given keywords are `dist` tokens ahead of the current one. 10,323 ( 0.00%) fn is_keyword_ahead(&self, dist: usize, kws: &[Symbol]) -> bool { 3,024 ( 0.00%) self.look_ahead(dist, |t| kws.iter().any(|&kw| t.is_keyword(kw))) 10,323 ( 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. 754 ( 0.00%) fn parse_unsafety(&mut self) -> Unsafe { . if self.eat_keyword(kw::Unsafe) { 20 ( 0.00%) Unsafe::Yes(self.prev_token.uninterpolated_span()) . } else { . Unsafe::No . } 3,016 ( 0.00%) } . . /// Parses constness: `const` or nothing. 6,200 ( 0.00%) fn parse_constness(&mut self) -> Const { . // Avoid const blocks to be parsed as const items 1,926 ( 0.00%) if self.look_ahead(1, |t| t != &token::OpenDelim(DelimToken::Brace)) . && self.eat_keyword(kw::Const) . { 465 ( 0.00%) Const::Yes(self.prev_token.uninterpolated_span()) . } else { . Const::No . } 10,850 ( 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 1108 ---------------------------------------- . id: DUMMY_NODE_ID, . value: self.mk_expr(blk.span, ExprKind::Block(blk, None), AttrVec::new()), . }; . 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). 16 ( 0.00%) fn parse_mutability(&mut self) -> Mutability { . if self.eat_keyword(kw::Mut) { Mutability::Mut } else { Mutability::Not } 1,788 ( 0.00%) } . . /// Possibly parses mutability (`const` or `mut`). 36 ( 0.00%) fn parse_const_or_mut(&mut self) -> Option { . if self.eat_keyword(kw::Mut) { . Some(Mutability::Mut) . } else if self.eat_keyword(kw::Const) { . Some(Mutability::Not) . } else { . None . } 36 ( 0.00%) } . . fn parse_field_name(&mut self) -> PResult<'a, Ident> { 1,254 ( 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 { 1,881 ( 0.00%) self.parse_ident_common(true) . } . } . . fn parse_mac_args(&mut self) -> PResult<'a, P> { 505 ( 0.00%) self.parse_mac_args_common(true).map(P) . } . . fn parse_attr_args(&mut self) -> PResult<'a, MacArgs> { 540 ( 0.00%) self.parse_mac_args_common(false) . } . 3,582 ( 0.00%) fn parse_mac_args_common(&mut self, delimited_only: bool) -> PResult<'a, MacArgs> { 3,184 ( 0.00%) Ok( 2,574 ( 0.00%) if self.check(&token::OpenDelim(DelimToken::Paren)) 468 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Bracket)) 408 ( 0.00%) || self.check(&token::OpenDelim(DelimToken::Brace)) . { 1,096 ( 0.00%) match self.parse_token_tree() { 1,370 ( 0.00%) TokenTree::Delimited(dspan, delim, tokens) => . // We've confirmed above that there is a delimiter so unwrapping is OK. . { 548 ( 0.00%) MacArgs::Delimited(dspan, MacDelimiter::from_token(delim).unwrap(), tokens) . } . _ => unreachable!(), . } 248 ( 0.00%) } else if !delimited_only { . if self.eat(&token::Eq) { . let eq_span = self.prev_token.span; . . // Collect tokens because they are used during lowering to HIR. . let expr = self.parse_expr_force_collect()?; . let span = expr.span; . . let token_kind = token::Interpolated(Lrc::new(token::NtExpr(expr))); -- line 1172 ---------------------------------------- -- line 1173 ---------------------------------------- . MacArgs::Eq(eq_span, Token::new(token_kind, span)) . } else { . MacArgs::Empty . } . } else { . return self.unexpected(); . }, . ) 2,786 ( 0.00%) } . . fn parse_or_use_outer_attributes( . &mut self, . already_parsed_attrs: Option, . ) -> PResult<'a, AttrWrapper> { 424,588 ( 0.01%) if let Some(attrs) = already_parsed_attrs { . Ok(attrs) . } else { 282,300 ( 0.01%) self.parse_outer_attributes() . } . } . . /// Parses a single token tree from the input. 5,144 ( 0.00%) pub(crate) fn parse_token_tree(&mut self) -> TokenTree { 2,993 ( 0.00%) match self.token.kind { . token::OpenDelim(..) => { . let depth = self.token_cursor.stack.len(); . . // We keep advancing the token cursor until we hit . // the matching `CloseDelim` token. 21,602 ( 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. 15,624 ( 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; 754 ( 0.00%) let stream = frame.tree_cursor.stream.clone(); 754 ( 0.00%) let span = frame.span; 377 ( 0.00%) let delim = frame.delim; . // Consume close delimiter 754 ( 0.00%) self.bump(); 1,885 ( 0.00%) TokenTree::Delimited(span, delim, stream) . } . token::CloseDelim(_) | token::Eof => unreachable!(), . _ => { 532 ( 0.00%) self.bump(); 1,330 ( 0.00%) TokenTree::Token(self.prev_token.clone()) . } . } 4,501 ( 0.00%) } . . /// Parses a stream of tokens into a list of `TokenTree`s, up to EOF. . pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec> { . let mut tts = Vec::new(); . while self.token != token::Eof { . tts.push(self.parse_token_tree()); . } . Ok(tts) . } . 8 ( 0.00%) pub fn parse_tokens(&mut self) -> TokenStream { . let mut result = Vec::new(); . loop { 12 ( 0.00%) match self.token.kind { . token::Eof | token::CloseDelim(..) => break, 3 ( 0.00%) _ => result.push(self.parse_token_tree().into()), . } . } 6 ( 0.00%) TokenStream::new(result) 8 ( 0.00%) } . . /// 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 { 141,358 ( 0.00%) let old = self.restrictions; 142,140 ( 0.00%) self.restrictions = res; . let res = f(self); 141,963 ( 0.00%) self.restrictions = old; . res . } . 11,672 ( 0.00%) fn is_crate_vis(&self) -> bool { 7,295 ( 0.00%) self.token.is_keyword(kw::Crate) && self.look_ahead(1, |t| t != &token::ModSep) 13,131 ( 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. 9,180 ( 0.00%) pub fn parse_visibility(&mut self, fbt: FollowedByType) -> PResult<'a, Visibility> { 1,836 ( 0.00%) maybe_whole!(self, NtVis, |x| x); . 918 ( 0.00%) self.expected_tokens.push(TokenType::Keyword(kw::Crate)); 3,672 ( 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". 597 ( 0.00%) return Ok(Visibility { 1,791 ( 0.00%) span: self.token.span.shrink_to_lo(), . kind: VisibilityKind::Inherited, . tokens: None, . }); . } 321 ( 0.00%) let lo = self.prev_token.span; . 1,605 ( 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. 171 ( 0.00%) if self.is_keyword_ahead(1, &[kw::Crate]) && self.look_ahead(2, |t| t != &token::ModSep) . // account for `pub(crate::foo)` . { . // Parse `pub(crate)`. 57 ( 0.00%) self.bump(); // `(` 38 ( 0.00%) self.bump(); // `crate` 57 ( 0.00%) self.expect(&token::CloseDelim(token::Paren))?; // `)` 19 ( 0.00%) let vis = VisibilityKind::Crate(CrateSugar::PubCrate); . return Ok(Visibility { 57 ( 0.00%) span: lo.to(self.prev_token.span), . kind: vis, . tokens: None, . }); . } else if self.is_keyword_ahead(1, &[kw::In]) { . // Parse `pub(in path)`. . self.bump(); // `(` . self.bump(); // `in` . let path = self.parse_path(PathStyle::Mod)?; // `path` -- line 1317 ---------------------------------------- -- line 1338 ---------------------------------------- . } else if let FollowedByType::No = fbt { . // Provide this diagnostic if a type cannot follow; . // in particular, if this is not a tuple struct. . self.recover_incorrect_vis_restriction()?; . // Emit diagnostic, but continue with public visibility. . } . } . 906 ( 0.00%) Ok(Visibility { span: lo, kind: VisibilityKind::Public, tokens: None }) 8,262 ( 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 { 297 ( 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, . } . } . 140 ( 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, 14 ( 0.00%) |this, _attrs| Ok((f(this)?, TrailingToken::None)), . ) 140 ( 0.00%) } . . /// `::{` or `::*` 37,880 ( 0.00%) fn is_import_coupler(&mut self) -> bool { 18,940 ( 0.00%) self.check(&token::ModSep) . && self.look_ahead(1, |t| { 11,935 ( 0.00%) *t == token::OpenDelim(token::Brace) || *t == token::BinOp(token::Star) . }) 37,404 ( 0.00%) } . . pub fn clear_expected_tokens(&mut self) { . self.expected_tokens.clear(); . } . } . . crate fn make_unclosed_delims_error( . unmatched: UnmatchedBrace, -- line 1430 ---------------------------------------- -- line 1450 ---------------------------------------- . err.span_label(sp, "closing delimiter possibly meant for this"); . } . if let Some(sp) = unmatched.unclosed_span { . err.span_label(sp, "unclosed delimiter"); . } . Some(err) . } . 2,872 ( 0.00%) pub fn emit_unclosed_delims(unclosed_delims: &mut Vec, sess: &ParseSess) { 1,436 ( 0.00%) *sess.reached_eof.borrow_mut() |= . unclosed_delims.iter().any(|unmatched_delim| unmatched_delim.found_delim.is_none()); 1,436 ( 0.00%) for unmatched in unclosed_delims.drain(..) { . if let Some(mut e) = make_unclosed_delims_error(unmatched, sess) { . e.emit(); . } . } 2,872 ( 0.00%) } . . /// A helper struct used when building an `AttrAnnotatedTokenStream` from . /// a `LazyTokenStream`. Both delimiter and non-delimited tokens . /// are stored as `FlatToken::Token`. A vector of `FlatToken`s . /// is then 'parsed' to build up an `AttrAnnotatedTokenStream` with nested . /// `AttrAnnotatedTokenTree::Delimited` tokens . #[derive(Debug, Clone)] . pub enum FlatToken { -- line 1474 ---------------------------------------- 1,858,357 ( 0.04%) -------------------------------------------------------------------------------- -- 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 { 4,894,106 ( 0.10%) if value < 0x80 { . unsafe { 1,843,253 ( 0.04%) *out.get_unchecked_mut(i).as_mut_ptr() = value as u8; . } . 3,004,124 ( 0.06%) i += 1; . break; . } else { . unsafe { 2,103,156 ( 0.04%) *out.get_unchecked_mut(i).as_mut_ptr() = ((value & 0x7f) | 0x80) as u8; . } . 924,234 ( 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. 1,847,852 ( 0.04%) let byte = slice[*position]; 923,926 ( 0.02%) *position += 1; 923,926 ( 0.02%) if (byte & 0x80) == 0 { . return byte as $int_ty; . } 1,078 ( 0.00%) let mut result = (byte & 0x7F) as $int_ty; . let mut shift = 7; . loop { 587,667 ( 0.01%) let byte = slice[*position]; 384,910 ( 0.01%) *position += 1; 391,778 ( 0.01%) if (byte & 0x80) == 0 { 311,174 ( 0.01%) result |= (byte as $int_ty) << shift; . return result; . } else { . result |= ((byte & 0x7F) as $int_ty) << shift; . } . shift += 7; . } . } . }; -- line 80 ---------------------------------------- 1,142,482 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/late.rs -------------------------------------------------------------------------------- Ir -- line 29 ---------------------------------------- . . use std::any::Any; . use std::cell::Cell; . use std::slice; . use tracing::debug; . . /// Extract the `LintStore` from the query context. . /// This function exists because we've erased `LintStore` as `dyn Any` in the context. 2 ( 0.00%) crate fn unerased_lint_store(tcx: TyCtxt<'_>) -> &LintStore { 41 ( 0.00%) let store: &dyn Any = &*tcx.lint_store; . store.downcast_ref().unwrap() 6 ( 0.00%) } . . macro_rules! lint_callback { ($cx:expr, $f:ident, $($args:expr),*) => ({ . $cx.pass.$f(&$cx.context, $($args),*); . }) } . . struct LateContextAndPass<'tcx, T: LateLintPass<'tcx>> { . context: LateContext<'tcx>, . pass: T, -- line 48 ---------------------------------------- -- line 51 ---------------------------------------- . impl<'tcx, T: LateLintPass<'tcx>> LateContextAndPass<'tcx, T> { . /// Merge the lints specified by any lint attributes into the . /// current lint context, call the provided function, then reset the . /// lints in effect to their previous state. . fn with_lint_attrs(&mut self, id: hir::HirId, f: F) . where . F: FnOnce(&mut Self), . { 2,202,554 ( 0.05%) let attrs = self.context.tcx.hir().attrs(id); 42,065 ( 0.00%) let prev = self.context.last_node_with_lint_attrs; 1,012,826 ( 0.02%) self.context.last_node_with_lint_attrs = id; . self.enter_attrs(attrs); . f(self); . self.exit_attrs(attrs); 1,151,049 ( 0.02%) self.context.last_node_with_lint_attrs = prev; . } . . fn with_param_env(&mut self, id: hir::HirId, f: F) . where . F: FnOnce(&mut Self), . { 1,380 ( 0.00%) let old_param_env = self.context.param_env; 1,872 ( 0.00%) self.context.param_env = 4,830 ( 0.00%) self.context.tcx.param_env(self.context.tcx.hir().local_def_id(id)); . f(self); 2,070 ( 0.00%) self.context.param_env = old_param_env; . } . . fn process_mod(&mut self, m: &'tcx hir::Mod<'tcx>, s: Span, n: hir::HirId) { 152 ( 0.00%) lint_callback!(self, check_mod, m, s, n); . hir_visit::walk_mod(self, m, n); 259 ( 0.00%) lint_callback!(self, check_mod_post, m, s, n); . } . . fn enter_attrs(&mut self, attrs: &'tcx [ast::Attribute]) { . debug!("late context: enter_attrs({:?})", attrs); 748,590 ( 0.02%) lint_callback!(self, enter_lint_attrs, attrs); . } . . fn exit_attrs(&mut self, attrs: &'tcx [ast::Attribute]) { . debug!("late context: exit_attrs({:?})", attrs); 1,030,079 ( 0.02%) lint_callback!(self, exit_lint_attrs, attrs); . } . } . . impl<'tcx, T: LateLintPass<'tcx>> hir_visit::Visitor<'tcx> for LateContextAndPass<'tcx, T> { . type NestedFilter = nested_filter::All; . . /// Because lints are scoped lexically, we want to walk nested . /// items in the context of the outer item, so enable . /// deep-walking. . fn nested_visit_map(&mut self) -> Self::Map { . self.context.tcx.hir() . } . 5,937 ( 0.00%) fn visit_nested_body(&mut self, body_id: hir::BodyId) { . let old_enclosing_body = self.context.enclosing_body.replace(body_id); 785 ( 0.00%) let old_cached_typeck_results = self.context.cached_typeck_results.get(); . . // HACK(eddyb) avoid trashing `cached_typeck_results` when we're . // nested in `visit_fn`, which may have already resulted in them . // being queried. 2,127 ( 0.00%) if old_enclosing_body != Some(body_id) { . self.context.cached_typeck_results.set(None); . } . 5,871 ( 0.00%) let body = self.context.tcx.hir().body(body_id); . self.visit_body(body); 1,861 ( 0.00%) self.context.enclosing_body = old_enclosing_body; . . // See HACK comment above. 2,076 ( 0.00%) if old_enclosing_body != Some(body_id) { . self.context.cached_typeck_results.set(old_cached_typeck_results); . } 5,536 ( 0.00%) } . 3,807 ( 0.00%) fn visit_param(&mut self, param: &'tcx hir::Param<'tcx>) { 1,768 ( 0.00%) self.with_lint_attrs(param.hir_id, |cx| { 1,768 ( 0.00%) lint_callback!(cx, check_param, param); . hir_visit::walk_param(cx, param); . }); 3,384 ( 0.00%) } . . fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) { 2,005 ( 0.00%) lint_callback!(self, check_body, body); 1,533 ( 0.00%) hir_visit::walk_body(self, body); 2,005 ( 0.00%) lint_callback!(self, check_body_post, body); . } . . fn visit_item(&mut self, it: &'tcx hir::Item<'tcx>) { . let generics = self.context.generics.take(); 2,952 ( 0.00%) self.context.generics = it.kind.generics(); . let old_cached_typeck_results = self.context.cached_typeck_results.take(); . let old_enclosing_body = self.context.enclosing_body.take(); 984 ( 0.00%) self.with_lint_attrs(it.hir_id(), |cx| { 2,952 ( 0.00%) cx.with_param_env(it.hir_id(), |cx| { 3,936 ( 0.00%) lint_callback!(cx, check_item, it); 3,444 ( 0.00%) hir_visit::walk_item(cx, it); 1,968 ( 0.00%) lint_callback!(cx, check_item_post, it); . }); . }); 2,460 ( 0.00%) self.context.enclosing_body = old_enclosing_body; . self.context.cached_typeck_results.set(old_cached_typeck_results); 984 ( 0.00%) self.context.generics = generics; . } . . fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) { . self.with_lint_attrs(it.hir_id(), |cx| { . cx.with_param_env(it.hir_id(), |cx| { . lint_callback!(cx, check_foreign_item, it); . hir_visit::walk_foreign_item(cx, it); . lint_callback!(cx, check_foreign_item_post, it); . }); . }) . } . . fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) { 5,882 ( 0.00%) lint_callback!(self, check_pat, p); 8,440 ( 0.00%) hir_visit::walk_pat(self, p); . } . 1,428 ( 0.00%) fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) { 578,326 ( 0.01%) self.with_lint_attrs(e.hir_id, |cx| { 1,152,767 ( 0.02%) lint_callback!(cx, check_expr, e); 867,966 ( 0.02%) hir_visit::walk_expr(cx, e); 575,679 ( 0.01%) lint_callback!(cx, check_expr_post, e); . }) 1,260 ( 0.00%) } . . fn visit_stmt(&mut self, s: &'tcx hir::Stmt<'tcx>) { . // See `EarlyContextAndPass::visit_stmt` for an explanation . // of why we call `walk_stmt` outside of `with_lint_attrs` 1,752 ( 0.00%) self.with_lint_attrs(s.hir_id, |cx| { 1,752 ( 0.00%) lint_callback!(cx, check_stmt, s); . }); 3,504 ( 0.00%) hir_visit::walk_stmt(self, s); . } . 3,201 ( 0.00%) fn visit_fn( . &mut self, . fk: hir_visit::FnKind<'tcx>, . decl: &'tcx hir::FnDecl<'tcx>, . body_id: hir::BodyId, . span: Span, . id: hir::HirId, . ) { . // Wrap in typeck results here, not just in visit_nested_body, . // in order for `check_fn` to be able to use them. . let old_enclosing_body = self.context.enclosing_body.replace(body_id); . let old_cached_typeck_results = self.context.cached_typeck_results.take(); 4,586 ( 0.00%) let body = self.context.tcx.hir().body(body_id); 7,773 ( 0.00%) lint_callback!(self, check_fn, fk, decl, body, span, id); 5,056 ( 0.00%) hir_visit::walk_fn(self, fk, decl, body_id, span, id); 5,842 ( 0.00%) lint_callback!(self, check_fn_post, fk, decl, body, span, id); 1,283 ( 0.00%) self.context.enclosing_body = old_enclosing_body; . self.context.cached_typeck_results.set(old_cached_typeck_results); 2,328 ( 0.00%) } . . fn visit_variant_data( . &mut self, . s: &'tcx hir::VariantData<'tcx>, . _: Symbol, . _: &'tcx hir::Generics<'tcx>, . _: hir::HirId, . _: Span, . ) { 148 ( 0.00%) lint_callback!(self, check_struct_def, s); . hir_visit::walk_struct_def(self, s); 220 ( 0.00%) lint_callback!(self, check_struct_def_post, s); . } . 1,116 ( 0.00%) fn visit_field_def(&mut self, s: &'tcx hir::FieldDef<'tcx>) { 248 ( 0.00%) self.with_lint_attrs(s.hir_id, |cx| { 248 ( 0.00%) lint_callback!(cx, check_field_def, s); . hir_visit::walk_field_def(cx, s); . }) 992 ( 0.00%) } . . fn visit_variant( . &mut self, . v: &'tcx hir::Variant<'tcx>, . g: &'tcx hir::Generics<'tcx>, . item_id: hir::HirId, . ) { 88 ( 0.00%) self.with_lint_attrs(v.id, |cx| { 88 ( 0.00%) lint_callback!(cx, check_variant, v); 286 ( 0.00%) hir_visit::walk_variant(cx, v, g, item_id); 88 ( 0.00%) lint_callback!(cx, check_variant_post, v); . }) . } . . fn visit_ty(&mut self, t: &'tcx hir::Ty<'tcx>) { 7,213 ( 0.00%) lint_callback!(self, check_ty, t); 11,370 ( 0.00%) hir_visit::walk_ty(self, t); . } . . fn visit_infer(&mut self, inf: &'tcx hir::InferArg) { . lint_callback!(self, check_infer, inf); . hir_visit::walk_inf(self, inf); . } . . fn visit_name(&mut self, sp: Span, name: Symbol) { 35,984 ( 0.00%) lint_callback!(self, check_name, sp, name); . } . . fn visit_mod(&mut self, m: &'tcx hir::Mod<'tcx>, s: Span, n: hir::HirId) { 74 ( 0.00%) if !self.context.only_module { . self.process_mod(m, s, n); . } . } . . fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) { 888 ( 0.00%) self.with_lint_attrs(l.hir_id, |cx| { 888 ( 0.00%) lint_callback!(cx, check_local, l); 1,332 ( 0.00%) hir_visit::walk_local(cx, l); . }) . } . . fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) { . lint_callback!(self, check_block, b); . hir_visit::walk_block(self, b); . lint_callback!(self, check_block_post, b); . } . . fn visit_arm(&mut self, a: &'tcx hir::Arm<'tcx>) { 828 ( 0.00%) lint_callback!(self, check_arm, a); 1,656 ( 0.00%) hir_visit::walk_arm(self, a); . } . . fn visit_generic_param(&mut self, p: &'tcx hir::GenericParam<'tcx>) { 720 ( 0.00%) lint_callback!(self, check_generic_param, p); 1,441 ( 0.00%) hir_visit::walk_generic_param(self, p); . } . . fn visit_generics(&mut self, g: &'tcx hir::Generics<'tcx>) { 2,185 ( 0.00%) lint_callback!(self, check_generics, g); 1,202 ( 0.00%) hir_visit::walk_generics(self, g); . } . . fn visit_where_predicate(&mut self, p: &'tcx hir::WherePredicate<'tcx>) { 80 ( 0.00%) lint_callback!(self, check_where_predicate, p); 140 ( 0.00%) hir_visit::walk_where_predicate(self, p); . } . . fn visit_poly_trait_ref( . &mut self, . t: &'tcx hir::PolyTraitRef<'tcx>, . m: hir::TraitBoundModifier, . ) { 672 ( 0.00%) lint_callback!(self, check_poly_trait_ref, t, m); . hir_visit::walk_poly_trait_ref(self, t, m); . } . . fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { . let generics = self.context.generics.take(); 2 ( 0.00%) self.context.generics = Some(&trait_item.generics); 2 ( 0.00%) self.with_lint_attrs(trait_item.hir_id(), |cx| { 6 ( 0.00%) cx.with_param_env(trait_item.hir_id(), |cx| { 5 ( 0.00%) lint_callback!(cx, check_trait_item, trait_item); 7 ( 0.00%) hir_visit::walk_trait_item(cx, trait_item); 5 ( 0.00%) lint_callback!(cx, check_trait_item_post, trait_item); . }); . }); 2 ( 0.00%) self.context.generics = generics; . } . . fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem<'tcx>) { . let generics = self.context.generics.take(); 788 ( 0.00%) self.context.generics = Some(&impl_item.generics); 394 ( 0.00%) self.with_lint_attrs(impl_item.hir_id(), |cx| { 1,182 ( 0.00%) cx.with_param_env(impl_item.hir_id(), |cx| { 985 ( 0.00%) lint_callback!(cx, check_impl_item, impl_item); 1,379 ( 0.00%) hir_visit::walk_impl_item(cx, impl_item); 985 ( 0.00%) lint_callback!(cx, check_impl_item_post, impl_item); . }); . }); 394 ( 0.00%) self.context.generics = generics; . } . . fn visit_lifetime(&mut self, lt: &'tcx hir::Lifetime) { 2,640 ( 0.00%) lint_callback!(self, check_lifetime, lt); . hir_visit::walk_lifetime(self, lt); . } . 4,284 ( 0.00%) fn visit_path(&mut self, p: &'tcx hir::Path<'tcx>, id: hir::HirId) { 30,058 ( 0.00%) lint_callback!(self, check_path, p, id); . hir_visit::walk_path(self, p); 3,808 ( 0.00%) } . . fn visit_attribute(&mut self, hir_id: hir::HirId, attr: &'tcx ast::Attribute) { . self.with_lint_attrs(hir_id, |cx| { 6,932 ( 0.00%) lint_callback!(cx, check_attribute, attr); . }) . } . } . . struct LateLintPassObjects<'a> { . lints: &'a mut [LateLintPassObject], . } . -- line 350 ---------------------------------------- -- line 389 ---------------------------------------- . param_env: ty::ParamEnv::empty(), . access_levels, . lint_store: unerased_lint_store(tcx), . last_node_with_lint_attrs: tcx.hir().local_def_id_to_hir_id(module_def_id), . generics: None, . only_module: true, . }; . 342 ( 0.00%) let mut cx = LateContextAndPass { context, pass }; . 209 ( 0.00%) let (module, span, hir_id) = tcx.hir().get_module(module_def_id); . cx.process_mod(module, span, hir_id); . . // Visit the crate attributes 57 ( 0.00%) if hir_id == hir::CRATE_HIR_ID { 5 ( 0.00%) for attr in tcx.hir().attrs(hir::CRATE_HIR_ID).iter() { . cx.visit_attribute(hir_id, attr) . } . } . } . 133 ( 0.00%) pub fn late_lint_mod<'tcx, T: LateLintPass<'tcx>>( . tcx: TyCtxt<'tcx>, . module_def_id: LocalDefId, . builtin_lints: T, . ) { 57 ( 0.00%) if tcx.sess.opts.debugging_opts.no_interleave_lints { . // These passes runs in late_lint_crate with -Z no_interleave_lints . return; . } . . late_lint_mod_pass(tcx, module_def_id, builtin_lints); . . let mut passes: Vec<_> = . unerased_lint_store(tcx).late_module_passes.iter().map(|pass| (pass)()).collect(); . 19 ( 0.00%) if !passes.is_empty() { . late_lint_mod_pass(tcx, module_def_id, LateLintPassObjects { lints: &mut passes[..] }); . } 152 ( 0.00%) } . . fn late_lint_pass_crate<'tcx, T: LateLintPass<'tcx>>(tcx: TyCtxt<'tcx>, pass: T) { . let access_levels = &tcx.privacy_access_levels(()); . . let context = LateContext { . tcx, . enclosing_body: None, . cached_typeck_results: Cell::new(None), . param_env: ty::ParamEnv::empty(), . access_levels, 2 ( 0.00%) lint_store: unerased_lint_store(tcx), . last_node_with_lint_attrs: hir::CRATE_HIR_ID, . generics: None, . only_module: false, . }; . 16 ( 0.00%) let mut cx = LateContextAndPass { context, pass }; . . // Visit the whole crate. . cx.with_lint_attrs(hir::CRATE_HIR_ID, |cx| { . // since the root module isn't visited as an item (because it isn't an . // item), warn for it here. 2 ( 0.00%) lint_callback!(cx, check_crate,); 1 ( 0.00%) tcx.hir().walk_toplevel_module(cx); 1 ( 0.00%) tcx.hir().walk_attributes(cx); 2 ( 0.00%) lint_callback!(cx, check_crate_post,); . }) . } . 10 ( 0.00%) fn late_lint_crate<'tcx, T: LateLintPass<'tcx>>(tcx: TyCtxt<'tcx>, builtin_lints: T) { 1 ( 0.00%) let mut passes = unerased_lint_store(tcx).late_passes.iter().map(|p| (p)()).collect::>(); . 6 ( 0.00%) if !tcx.sess.opts.debugging_opts.no_interleave_lints { 1 ( 0.00%) if !passes.is_empty() { . late_lint_pass_crate(tcx, LateLintPassObjects { lints: &mut passes[..] }); . } . 4 ( 0.00%) late_lint_pass_crate(tcx, builtin_lints); . } else { . for pass in &mut passes { . tcx.sess.prof.extra_verbose_generic_activity("run_late_lint", pass.name()).run(|| { . late_lint_pass_crate(tcx, LateLintPassObjects { lints: slice::from_mut(pass) }); . }); . } . . let mut passes: Vec<_> = -- line 474 ---------------------------------------- -- line 477 ---------------------------------------- . for pass in &mut passes { . tcx.sess.prof.extra_verbose_generic_activity("run_late_module_lint", pass.name()).run( . || { . late_lint_pass_crate(tcx, LateLintPassObjects { lints: slice::from_mut(pass) }); . }, . ); . } . } 9 ( 0.00%) } . . /// Performs lint checking on a crate. . pub fn check_crate<'tcx, T: LateLintPass<'tcx>>( . tcx: TyCtxt<'tcx>, . builtin_lints: impl FnOnce() -> T + Send, . ) { . join( . || { 5 ( 0.00%) tcx.sess.time("crate_lints", || { . // Run whole crate non-incremental lints 4 ( 0.00%) late_lint_crate(tcx, builtin_lints()); . }); . }, . || { 5 ( 0.00%) tcx.sess.time("module_lints", || { . // Run per-module lints 1 ( 0.00%) tcx.hir().par_for_each_module(|module| tcx.ensure().lint_mod(module)); . }); . }, . ); . } 2,251 ( 0.00%) -------------------------------------------------------------------------------- -- 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) { 361 ( 0.00%) let mut tt_reader = TokenTreesReader { . string_reader: self, 19 ( 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(), . }; 19 ( 0.00%) let res = tt_reader.parse_all_token_trees(); 114 ( 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`. 152 ( 0.00%) fn parse_all_token_trees(&mut self) -> PResult<'a, TokenStream> { . let mut buf = TokenStreamBuilder::default(); . . self.bump(); 8,414 ( 0.00%) while self.token != token::Eof { 33,504 ( 0.00%) buf.push(self.parse_token_tree()?); . } . . Ok(buf.into_token_stream()) 171 ( 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 { 602,032 ( 0.01%) if let token::CloseDelim(..) = self.token.kind { . return buf.into_token_stream(); . } . 1,488,255 ( 0.03%) match self.parse_token_tree() { 2,678,859 ( 0.05%) Ok(tree) => buf.push(tree), . Err(mut e) => { . e.emit(); . return buf.into_token_stream(); . } . } . } . } . 2,716,551 ( 0.06%) fn parse_token_tree(&mut self) -> PResult<'a, TreeAndSpacing> { 603,678 ( 0.01%) let sm = self.string_reader.sess.source_map(); . 2,703,091 ( 0.06%) match self.token.kind { . token::Eof => { . let msg = "this file contains an unclosed delimiter"; . let mut err = . self.string_reader.sess.span_diagnostic.struct_span_err(self.token.span, msg); . for &(_, sp) in &self.open_braces { . err.span_label(sp, "unclosed delimiter"); . self.unmatched_braces.push(UnmatchedBrace { . expected_delim: token::DelimToken::Brace, -- line 91 ---------------------------------------- -- line 113 ---------------------------------------- . err.span_label( . *close_sp, . "...as it matches this but it has different indentation", . ); . } . } . Err(err) . } 3,365 ( 0.00%) token::OpenDelim(delim) => { . // The span for beginning of the delimited section 3,365 ( 0.00%) let pre_span = self.token.span; . . // Parse the open delimiter. 23,555 ( 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. 3,365 ( 0.00%) let tts = self.parse_token_trees_until_close_delim(); . . // Expand to cover the entire delimited token tree 16,825 ( 0.00%) let delim_span = DelimSpan::from_pair(pre_span, self.token.span); . 6,730 ( 0.00%) match self.token.kind { . // Correct delimiter. 6,730 ( 0.00%) token::CloseDelim(d) if d == delim => { . let (open_brace, open_brace_span) = self.open_braces.pop().unwrap(); 6,730 ( 0.00%) let close_brace_span = self.token.span; . 10,095 ( 0.00%) if tts.is_empty() { 1,995 ( 0.00%) let empty_block_span = open_brace_span.to(close_brace_span); 2,660 ( 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 13,460 ( 0.00%) if let (DelimToken::Brace, DelimToken::Brace) = (open_brace, delim) { . self.matching_block_spans.push((open_brace_span, close_brace_span)); . } . 3,365 ( 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. . } . _ => {} . } . 23,555 ( 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) . } . _ => { 1,492,370 ( 0.03%) let tt = TokenTree::Token(self.token.take()); . let mut spacing = self.bump(); 596,948 ( 0.01%) if !self.token.is_op() { . spacing = Alone; . } 1,790,844 ( 0.04%) Ok((tt, spacing)) . } . } 2,414,712 ( 0.05%) } . . fn bump(&mut self) -> Spacing { 2,730,125 ( 0.06%) let (spacing, token) = self.string_reader.next_token(); 1,509,366 ( 0.03%) self.token = token; . spacing . } . } . 3,365 ( 0.00%) #[derive(Default)] . struct TokenStreamBuilder { . buf: Vec, . } . . impl TokenStreamBuilder { 3,923,907 ( 0.08%) fn push(&mut self, (tree, joint): TreeAndSpacing) { 2,370,985 ( 0.05%) if let Some((TokenTree::Token(prev_token), Joint)) = self.buf.last() { 289,504 ( 0.01%) if let TokenTree::Token(token) = &tree { 440,052 ( 0.01%) if let Some(glued) = prev_token.glue(token) { . self.buf.pop(); 17,388 ( 0.00%) self.buf.push((TokenTree::Token(glued), joint)); . return; . } . } . } 1,501,950 ( 0.03%) self.buf.push((tree, joint)) 2,414,712 ( 0.05%) } . . fn into_token_stream(self) -> TokenStream { 33,821 ( 0.00%) TokenStream::new(self.buf) . } . } 638,048 ( 0.01%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_passes/src/region.rs -------------------------------------------------------------------------------- Ir -- line 71 ---------------------------------------- . } . . /// Records the lifetime of a local variable as `cx.var_parent` . fn record_var_lifetime( . visitor: &mut RegionResolutionVisitor<'_>, . var_id: hir::ItemLocalId, . _sp: Span, . ) { 2,622 ( 0.00%) match visitor.cx.var_parent { . None => { . // this can happen in extern fn declarations like . // . // extern fn isalnum(c: c_int) -> c_int . } 3,496 ( 0.00%) Some((parent_scope, _)) => visitor.scope_tree.record_var_scope(var_id, parent_scope), . } . } . . fn resolve_block<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, blk: &'tcx hir::Block<'tcx>) { . debug!("resolve_block(blk.hir_id={:?})", blk.hir_id); . 3,744 ( 0.00%) let prev_cx = visitor.cx; . . // We treat the tail expression in the block (if any) somewhat . // differently from the statements. The issue has to do with . // temporary lifetimes. Consider the following: . // . // quux({ . // let inner = ... (&bar()) ...; . // -- line 100 ---------------------------------------- -- line 111 ---------------------------------------- . // tail expression for the block are assigned lifetimes so that . // they will be cleaned up as part of the terminating scope . // *surrounding* the block expression. Here, the terminating . // scope for the block expression is the `quux(..)` call; so . // those temporaries will only be cleaned up *after* both . // `other_argument()` has run and also the call to `quux(..)` . // itself has returned. . 1,872 ( 0.00%) visitor.enter_node_scope_with_dtor(blk.hir_id.local_id); 3,120 ( 0.00%) visitor.cx.var_parent = visitor.cx.parent; . . { . // This block should be kept approximately in sync with . // `intravisit::walk_block`. (We manually walk the block, rather . // than call `walk_block`, in order to maintain precise . // index information.) . 624 ( 0.00%) for (i, statement) in blk.stmts.iter().enumerate() { 876 ( 0.00%) match statement.kind { . hir::StmtKind::Local(..) | hir::StmtKind::Item(..) => { . // Each declaration introduces a subscope for bindings . // introduced by the declaration; this subscope covers a . // suffix of the block. Each subscope in a block has the . // previous subscope in the block as a parent, except for . // the first such subscope, which has the block itself as a . // parent. . visitor.enter_scope(Scope { . id: blk.hir_id.local_id, . data: ScopeData::Remainder(FirstStatementIndex::new(i)), . }); 1,115 ( 0.00%) visitor.cx.var_parent = visitor.cx.parent; . } . hir::StmtKind::Expr(..) | hir::StmtKind::Semi(..) => {} . } . visitor.visit_stmt(statement) . } 1,674 ( 0.00%) walk_list!(visitor, visit_expr, &blk.expr); . } . 3,120 ( 0.00%) visitor.cx = prev_cx; . } . . fn resolve_arm<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, arm: &'tcx hir::Arm<'tcx>) { 828 ( 0.00%) let prev_cx = visitor.cx; . 207 ( 0.00%) visitor.enter_scope(Scope { id: arm.hir_id.local_id, data: ScopeData::Node }); 828 ( 0.00%) visitor.cx.var_parent = visitor.cx.parent; . 414 ( 0.00%) visitor.terminating_scopes.insert(arm.body.hir_id.local_id); . 621 ( 0.00%) if let Some(hir::Guard::If(ref expr)) = arm.guard { . visitor.terminating_scopes.insert(expr.hir_id.local_id); . } . . intravisit::walk_arm(visitor, arm); . 828 ( 0.00%) visitor.cx = prev_cx; . } . . fn resolve_pat<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, pat: &'tcx hir::Pat<'tcx>) { 1,347 ( 0.00%) visitor.record_child_scope(Scope { id: pat.hir_id.local_id, data: ScopeData::Node }); . . // If this is a binding then record the lifetime of that binding. 2,694 ( 0.00%) if let PatKind::Binding(..) = pat.kind { . record_var_lifetime(visitor, pat.hir_id.local_id, pat.span); . } . . debug!("resolve_pat - pre-increment {} pat = {:?}", visitor.expr_and_pat_count, pat); . 4,041 ( 0.00%) intravisit::walk_pat(visitor, pat); . 5,388 ( 0.00%) visitor.expr_and_pat_count += 1; . . debug!("resolve_pat - post-increment {} pat = {:?}", visitor.expr_and_pat_count, pat); . } . . fn resolve_stmt<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, stmt: &'tcx hir::Stmt<'tcx>) { 876 ( 0.00%) let stmt_id = stmt.hir_id.local_id; . debug!("resolve_stmt(stmt.id={:?})", stmt_id); . . // Every statement will clean up the temporaries created during . // execution of that statement. Therefore each statement has an . // associated destruction scope that represents the scope of the . // statement plus its destructors, and thus the scope for which . // regions referenced by the destructors need to survive. . visitor.terminating_scopes.insert(stmt_id); . 1,752 ( 0.00%) let prev_parent = visitor.cx.parent; 1,314 ( 0.00%) visitor.enter_node_scope_with_dtor(stmt_id); . . intravisit::walk_stmt(visitor, stmt); . 1,752 ( 0.00%) visitor.cx.parent = prev_parent; . } . . fn resolve_expr<'tcx>(visitor: &mut RegionResolutionVisitor<'tcx>, expr: &'tcx hir::Expr<'tcx>) { . debug!("resolve_expr - pre-increment {} expr = {:?}", visitor.expr_and_pat_count, expr); . 582,312 ( 0.01%) let prev_cx = visitor.cx; 291,156 ( 0.01%) visitor.enter_node_scope_with_dtor(expr.hir_id.local_id); . . { . let terminating_scopes = &mut visitor.terminating_scopes; . let mut terminating = |id: hir::ItemLocalId| { . terminating_scopes.insert(id); . }; 583,384 ( 0.01%) match expr.kind { . // Conditional or repeating scopes are always terminating . // scopes, meaning that temporaries cannot outlive them. . // This ensures fixed size stacks. . hir::ExprKind::Binary( . source_map::Spanned { node: hir::BinOpKind::And, .. }, . _, . ref r, . ) -- line 225 ---------------------------------------- -- line 229 ---------------------------------------- . ref r, . ) => { . // For shortcircuiting operators, mark the RHS as a terminating . // scope since it only executes conditionally. . terminating(r.hir_id.local_id); . } . . hir::ExprKind::If(_, ref then, Some(ref otherwise)) => { 126 ( 0.00%) terminating(then.hir_id.local_id); . terminating(otherwise.hir_id.local_id); . } . . hir::ExprKind::If(_, ref then, None) => { 39 ( 0.00%) terminating(then.hir_id.local_id); . } . . hir::ExprKind::Loop(ref body, _, _, _) => { 57 ( 0.00%) terminating(body.hir_id.local_id); . } . . hir::ExprKind::DropTemps(ref expr) => { . // `DropTemps(expr)` does not denote a conditional scope. . // Rather, we want to achieve the same behavior as `{ let _t = expr; _t }`. 196 ( 0.00%) terminating(expr.hir_id.local_id); . } . . hir::ExprKind::AssignOp(..) . | hir::ExprKind::Index(..) . | hir::ExprKind::Unary(..) . | hir::ExprKind::Call(..) . | hir::ExprKind::MethodCall(..) => { . // FIXME(https://github.com/rust-lang/rfcs/issues/811) Nested method calls -- line 260 ---------------------------------------- -- line 276 ---------------------------------------- . // . // record_superlifetime(new_cx, expr.callee_id); . } . . _ => {} . } . } . 20 ( 0.00%) let prev_pessimistic = visitor.pessimistic_yield; . . // Ordinarily, we can rely on the visit order of HIR intravisit . // to correspond to the actual execution order of statements. . // However, there's a weird corner case with compound assignment . // operators (e.g. `a += b`). The evaluation order depends on whether . // or not the operator is overloaded (e.g. whether or not a trait . // like AddAssign is implemented). . -- line 292 ---------------------------------------- -- line 328 ---------------------------------------- . // about what types could possibly live across yield points, . // but we will never fail to detect that a type does actually . // live across a yield point. The latter part is critical - . // we're already overly conservative about what types will live . // across yield points, as the generated MIR will determine . // when things are actually live. However, for typecheck to work . // properly, we can't miss any types. . 873,672 ( 0.02%) match expr.kind { . // Manually recurse over closures and inline consts, because they are the only . // case of nested bodies that share the parent environment. 34 ( 0.00%) hir::ExprKind::Closure(.., body, _, _) . | hir::ExprKind::ConstBlock(hir::AnonConst { body, .. }) => { 68 ( 0.00%) let body = visitor.tcx.hir().body(body); 51 ( 0.00%) visitor.visit_body(body); . } . hir::ExprKind::AssignOp(_, ref left_expr, ref right_expr) => { . debug!( . "resolve_expr - enabling pessimistic_yield, was previously {}", . prev_pessimistic . ); . 20 ( 0.00%) let start_point = visitor.fixup_scopes.len(); 20 ( 0.00%) visitor.pessimistic_yield = true; . . // If the actual execution order turns out to be right-to-left, . // then we're fine. However, if the actual execution order is left-to-right, . // then we'll assign too low a count to any `yield` expressions . // we encounter in 'right_expression' - they should really occur after all of the . // expressions in 'left_expression'. 100 ( 0.00%) visitor.visit_expr(&right_expr); 20 ( 0.00%) visitor.pessimistic_yield = prev_pessimistic; . . debug!("resolve_expr - restoring pessimistic_yield to {}", prev_pessimistic); 80 ( 0.00%) visitor.visit_expr(&left_expr); . debug!("resolve_expr - fixing up counts to {}", visitor.expr_and_pat_count); . . // Remove and process any scopes pushed by the visitor . let target_scopes = visitor.fixup_scopes.drain(start_point..); . 100 ( 0.00%) for scope in target_scopes { . let mut yield_data = . visitor.scope_tree.yield_in_scope.get_mut(&scope).unwrap().last_mut().unwrap(); . let count = yield_data.expr_and_pat_count; . let span = yield_data.span; . . // expr_and_pat_count never decreases. Since we recorded counts in yield_in_scope . // before walking the left-hand side, it should be impossible for the recorded . // count to be greater than the left-hand side count. -- line 376 ---------------------------------------- -- line 388 ---------------------------------------- . scope, count, new_count, span . ); . . yield_data.expr_and_pat_count = new_count; . } . } . . hir::ExprKind::If(ref cond, ref then, Some(ref otherwise)) => { 252 ( 0.00%) let expr_cx = visitor.cx; 126 ( 0.00%) visitor.enter_scope(Scope { id: then.hir_id.local_id, data: ScopeData::IfThen }); 315 ( 0.00%) visitor.cx.var_parent = visitor.cx.parent; 252 ( 0.00%) visitor.visit_expr(cond); 189 ( 0.00%) visitor.visit_expr(then); 252 ( 0.00%) visitor.cx = expr_cx; 189 ( 0.00%) visitor.visit_expr(otherwise); . } . . hir::ExprKind::If(ref cond, ref then, None) => { 156 ( 0.00%) let expr_cx = visitor.cx; 78 ( 0.00%) visitor.enter_scope(Scope { id: then.hir_id.local_id, data: ScopeData::IfThen }); 195 ( 0.00%) visitor.cx.var_parent = visitor.cx.parent; 156 ( 0.00%) visitor.visit_expr(cond); 117 ( 0.00%) visitor.visit_expr(then); 156 ( 0.00%) visitor.cx = expr_cx; . } . 436,317 ( 0.01%) _ => intravisit::walk_expr(visitor, expr), . } . 582,312 ( 0.01%) visitor.expr_and_pat_count += 1; . . debug!("resolve_expr post-increment {}, expr = {:?}", visitor.expr_and_pat_count, expr); . 291,156 ( 0.01%) if let hir::ExprKind::Yield(_, source) = &expr.kind { . // Mark this expr's scope and all parent scopes as containing `yield`. . let mut scope = Scope { id: expr.hir_id.local_id, data: ScopeData::Node }; . loop { . let span = match expr.kind { . hir::ExprKind::Yield(expr, hir::YieldSource::Await { .. }) => { . expr.span.shrink_to_hi().to(expr.span) . } . _ => expr.span, -- line 429 ---------------------------------------- -- line 449 ---------------------------------------- . ScopeData::CallSite => break, . _ => scope = superscope, . }, . None => break, . } . } . } . 727,890 ( 0.01%) visitor.cx = prev_cx; . } . . fn resolve_local<'tcx>( . visitor: &mut RegionResolutionVisitor<'tcx>, . pat: Option<&'tcx hir::Pat<'tcx>>, . init: Option<&'tcx hir::Expr<'tcx>>, . ) { . debug!("resolve_local(pat={:?}, init={:?})", pat, init); . 93 ( 0.00%) let blk_scope = visitor.cx.var_parent.map(|(p, _)| p); . . // As an exception to the normal rules governing temporary . // lifetimes, initializers in a let have a temporary lifetime . // of the enclosing block. This means that e.g., a program . // like the following is legal: . // . // let ref x = HashMap::new(); . // -- line 475 ---------------------------------------- -- line 517 ---------------------------------------- . // rvalue). For example: . // . // let ref x = [&a(), &b()]; . // . // Here, the expression `[...]` has an extended lifetime due to rule . // A, but the inner rvalues `a()` and `b()` have an extended lifetime . // due to rule C. . 444 ( 0.00%) if let Some(expr) = init { 1,503 ( 0.00%) record_rvalue_scope_if_borrow_expr(visitor, &expr, blk_scope); . . if let Some(pat) = pat { 816 ( 0.00%) if is_binding_pat(pat) { . record_rvalue_scope(visitor, &expr, blk_scope); . } . } . } . . // Make sure we visit the initializer first, so expr_and_pat_count remains correct . if let Some(expr) = init { 1,095 ( 0.00%) visitor.visit_expr(expr); . } . if let Some(pat) = pat { 2,220 ( 0.00%) visitor.visit_pat(pat); . } . . /// Returns `true` if `pat` match the `P&` non-terminal. . /// . /// ```text . /// P& = ref X . /// | StructName { ..., P&, ... } . /// | VariantName(..., P&, ...) . /// | [ ..., P&, ... ] . /// | ( ..., P&, ... ) . /// | ... "|" P& "|" ... . /// | box P& . /// ``` 824 ( 0.00%) fn is_binding_pat(pat: &hir::Pat<'_>) -> bool { . // Note that the code below looks for *explicit* refs only, that is, it won't . // know about *implicit* refs as introduced in #42640. . // . // This is not a problem. For example, consider . // . // let (ref x, ref y) = (Foo { .. }, Bar { .. }); . // . // Due to the explicit refs on the left hand side, the below code would signal -- line 562 ---------------------------------------- -- line 570 ---------------------------------------- . // . // in place of . // . // let Foo { ref x, .. } = Foo { ... }; . // . // In the former case (the implicit ref version), the temporary is created by the . // & expression, and its lifetime would be extended to the end of the block (due . // to a different rule, not the below code). 948 ( 0.00%) match pat.kind { . PatKind::Binding(hir::BindingAnnotation::Ref, ..) . | PatKind::Binding(hir::BindingAnnotation::RefMut, ..) => true, . . PatKind::Struct(_, ref field_pats, _) => { . field_pats.iter().any(|fp| is_binding_pat(&fp.pat)) . } . . PatKind::Slice(ref pats1, ref pats2, ref pats3) => { . pats1.iter().any(|p| is_binding_pat(&p)) . || pats2.iter().any(|p| is_binding_pat(&p)) . || pats3.iter().any(|p| is_binding_pat(&p)) . } . . PatKind::Or(ref subpats) . | PatKind::TupleStruct(_, ref subpats, _) 6 ( 0.00%) | PatKind::Tuple(ref subpats, _) => subpats.iter().any(|p| is_binding_pat(&p)), . . PatKind::Box(ref subpat) => is_binding_pat(&subpat), . . PatKind::Ref(_, _) . | PatKind::Binding( . hir::BindingAnnotation::Unannotated | hir::BindingAnnotation::Mutable, . .., . ) . | PatKind::Wild . | PatKind::Path(_) . | PatKind::Lit(_) . | PatKind::Range(_, _, _) => false, . } 824 ( 0.00%) } . . /// If `expr` matches the `E&` grammar, then records an extended rvalue scope as appropriate: . /// . /// ```text . /// E& = & ET . /// | StructName { ..., f: E&, ... } . /// | [ ..., E&, ... ] . /// | ( ..., E&, ... ) . /// | {...; E&} . /// | box E& . /// | E& as ... . /// | ( E& ) . /// ``` 1,676,604 ( 0.03%) fn record_rvalue_scope_if_borrow_expr<'tcx>( . visitor: &mut RegionResolutionVisitor<'tcx>, . expr: &hir::Expr<'_>, . blk_id: Option, . ) { 558,904 ( 0.01%) match expr.kind { . hir::ExprKind::AddrOf(_, _, ref subexpr) => { 6,600 ( 0.00%) record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id); . record_rvalue_scope(visitor, &subexpr, blk_id); . } 91 ( 0.00%) hir::ExprKind::Struct(_, fields, _) => { . for field in fields { 2,730 ( 0.00%) record_rvalue_scope_if_borrow_expr(visitor, &field.expr, blk_id); . } . } . hir::ExprKind::Array(subexprs) | hir::ExprKind::Tup(subexprs) => { . for subexpr in subexprs { 691,070 ( 0.01%) record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id); . } . } . hir::ExprKind::Cast(ref subexpr, _) => { . record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id) . } . hir::ExprKind::Block(ref block, _) => { 36 ( 0.00%) if let Some(ref subexpr) = block.expr { . record_rvalue_scope_if_borrow_expr(visitor, &subexpr, blk_id); . } . } . _ => {} . } 1,117,736 ( 0.02%) } . . /// Applied to an expression `expr` if `expr` -- or something owned or partially owned by . /// `expr` -- is going to be indirectly referenced by a variable in a let statement. In that . /// case, the "temporary lifetime" or `expr` is extended to be the block enclosing the `let` . /// statement. . /// . /// More formally, if `expr` matches the grammar `ET`, record the rvalue scope of the matching . /// `` as `blk_id`: -- line 660 ---------------------------------------- -- line 675 ---------------------------------------- . ) { . let mut expr = expr; . loop { . // Note: give all the expressions matching `ET` with the . // extended temporary lifetime, not just the innermost rvalue, . // because in codegen if we must compile e.g., `*rvalue()` . // into a temporary, we request the temporary scope of the . // outer expression. 3,335 ( 0.00%) visitor.scope_tree.record_rvalue_scope(expr.hir_id.local_id, blk_scope); . 2,668 ( 0.00%) match expr.kind { . hir::ExprKind::AddrOf(_, _, ref subexpr) . | hir::ExprKind::Unary(hir::UnOp::Deref, ref subexpr) 4 ( 0.00%) | hir::ExprKind::Field(ref subexpr, _) . | hir::ExprKind::Index(ref subexpr, _) => { 11 ( 0.00%) expr = &subexpr; . } . _ => { . return; . } . } . } . } . } . . impl<'tcx> RegionResolutionVisitor<'tcx> { . /// Records the current parent (if any) as the parent of `child_scope`. . /// Returns the depth of `child_scope`. . fn record_child_scope(&mut self, child_scope: Scope) -> ScopeDepth { 301,437 ( 0.01%) let parent = self.cx.parent; 1,056,942 ( 0.02%) self.scope_tree.record_scope_parent(child_scope, parent); . // If `child_scope` has no parent, it must be the root node, and so has . // a depth of 1. Otherwise, its depth is one more than its parent's. 297,930 ( 0.01%) parent.map_or(1, |(_p, d)| d + 1) . } . . /// Records the current parent (if any) as the parent of `child_scope`, . /// and sets `child_scope` as the new current parent. . fn enter_scope(&mut self, child_scope: Scope) { . let child_depth = self.record_child_scope(child_scope); 448,448 ( 0.01%) self.cx.parent = Some((child_scope, child_depth)); . } . 1,026,480 ( 0.02%) fn enter_node_scope_with_dtor(&mut self, id: hir::ItemLocalId) { . // If node was previously marked as a terminating scope during the . // recursive visit of its parent node in the AST, then we need to . // account for the destruction scope representing the scope of . // the destructors that run immediately after it completes. 293,280 ( 0.01%) if self.terminating_scopes.contains(&id) { 1,375 ( 0.00%) self.enter_scope(Scope { id, data: ScopeData::Destruction }); . } 146,640 ( 0.00%) self.enter_scope(Scope { id, data: ScopeData::Node }); 879,840 ( 0.02%) } . } . . impl<'tcx> Visitor<'tcx> for RegionResolutionVisitor<'tcx> { 5,616 ( 0.00%) fn visit_block(&mut self, b: &'tcx Block<'tcx>) { . resolve_block(self, b); 4,992 ( 0.00%) } . 3,609 ( 0.00%) fn visit_body(&mut self, body: &'tcx hir::Body<'tcx>) { 1,203 ( 0.00%) let body_id = body.id(); 3,208 ( 0.00%) let owner_id = self.tcx.hir().body_owner(body_id); . . debug!( . "visit_body(id={:?}, span={:?}, body.id={:?}, cx.parent={:?})", . owner_id, . self.tcx.sess.source_map().span_to_diagnostic_string(body.value.span), . body_id, . self.cx.parent . ); . . // Save all state that is specific to the outer function . // body. These will be restored once down below, once we've . // visited the body. . let outer_ec = mem::replace(&mut self.expr_and_pat_count, 0); 1,604 ( 0.00%) let outer_cx = self.cx; 401 ( 0.00%) let outer_ts = mem::take(&mut self.terminating_scopes); . // The 'pessimistic yield' flag is set to true when we are . // processing a `+=` statement and have to make pessimistic . // control flow assumptions. This doesn't apply to nested . // bodies within the `+=` statements. See #69307. . let outer_pessimistic_yield = mem::replace(&mut self.pessimistic_yield, false); 802 ( 0.00%) self.terminating_scopes.insert(body.value.hir_id.local_id); . 401 ( 0.00%) self.enter_scope(Scope { id: body.value.hir_id.local_id, data: ScopeData::CallSite }); 401 ( 0.00%) self.enter_scope(Scope { id: body.value.hir_id.local_id, data: ScopeData::Arguments }); . . // The arguments and `self` are parented to the fn. 802 ( 0.00%) self.cx.var_parent = self.cx.parent.take(); 2,807 ( 0.00%) for param in body.params { 2,210 ( 0.00%) self.visit_pat(¶m.pat); . } . . // The body of the every fn is a root scope. 1,604 ( 0.00%) self.cx.parent = self.cx.var_parent; 4,411 ( 0.00%) if self.tcx.hir().body_owner_kind(owner_id).is_fn_or_closure() { 1,232 ( 0.00%) self.visit_expr(&body.value) . } else { . // Only functions have an outer terminating (drop) scope, while . // temporaries in constant initializers may be 'static, but only . // according to rvalue lifetime semantics, using the same . // syntactical rules used for let initializers. . // . // e.g., in `let x = &f();`, the temporary holding the result from . // the `f()` call lives for the entirety of the surrounding block. -- line 780 ---------------------------------------- -- line 784 ---------------------------------------- . // ever get lifted) that the value *could* have a destructor, but . // it'd get leaked instead of the destructor running during the . // evaluation of `X` (if at all allowed by CTFE). . // . // However, `const Y: ... = g(&f());`, like `let y = g(&f());`, . // would *not* let the `f()` temporary escape into an outer scope . // (i.e., `'static`), which means that after `g` returns, it drops, . // and all the associated destruction scope rules apply. 93 ( 0.00%) self.cx.var_parent = None; . resolve_local(self, None, Some(&body.value)); . } . 401 ( 0.00%) if body.generator_kind.is_some() { . self.scope_tree.body_expr_count.insert(body_id, self.expr_and_pat_count); . } . . // Restore context we had at the start. 401 ( 0.00%) self.expr_and_pat_count = outer_ec; 1,604 ( 0.00%) self.cx = outer_cx; 2,005 ( 0.00%) self.terminating_scopes = outer_ts; 401 ( 0.00%) self.pessimistic_yield = outer_pessimistic_yield; 3,208 ( 0.00%) } . 1,863 ( 0.00%) fn visit_arm(&mut self, a: &'tcx Arm<'tcx>) { . resolve_arm(self, a); 1,656 ( 0.00%) } 12,123 ( 0.00%) fn visit_pat(&mut self, p: &'tcx Pat<'tcx>) { . resolve_pat(self, p); 10,776 ( 0.00%) } . fn visit_stmt(&mut self, s: &'tcx Stmt<'tcx>) { . resolve_stmt(self, s); . } 1,310,202 ( 0.03%) fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) { . resolve_expr(self, ex); 1,164,624 ( 0.02%) } 1,776 ( 0.00%) fn visit_local(&mut self, l: &'tcx Local<'tcx>) { 444 ( 0.00%) resolve_local(self, Some(&l.pat), l.init); . } . } . 5,530 ( 0.00%) fn region_scope_tree(tcx: TyCtxt<'_>, def_id: DefId) -> &ScopeTree { 1,659 ( 0.00%) let typeck_root_def_id = tcx.typeck_root_def_id(def_id); 1,659 ( 0.00%) if typeck_root_def_id != def_id { . return tcx.region_scope_tree(typeck_root_def_id); . } . . let id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); 2,680 ( 0.00%) let scope_tree = if let Some(body_id) = tcx.hir().maybe_body_owned_by(id) { 7,296 ( 0.00%) let mut visitor = RegionResolutionVisitor { . tcx, . scope_tree: ScopeTree::default(), . expr_and_pat_count: 0, . cx: Context { parent: None, var_parent: None }, . terminating_scopes: Default::default(), . pessimistic_yield: false, . fixup_scopes: vec![], . }; . 1,536 ( 0.00%) let body = tcx.hir().body(body_id); 1,152 ( 0.00%) visitor.scope_tree.root_body = Some(body.value.hir_id); 768 ( 0.00%) visitor.visit_body(body); 11,520 ( 0.00%) visitor.scope_tree . } else { . ScopeTree::default() . }; . 536 ( 0.00%) tcx.arena.alloc(scope_tree) 4,977 ( 0.00%) } . . pub fn provide(providers: &mut Providers) { 2 ( 0.00%) *providers = Providers { region_scope_tree, ..*providers }; . } 2,132,842 ( 0.04%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_lint/src/passes.rs -------------------------------------------------------------------------------- Ir -- line 107 ---------------------------------------- . ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({ . $($self.$passes.$name $params;)* . }) . } . . #[macro_export] . macro_rules! expand_combined_late_lint_pass_methods { . ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => ( 1,917,853 ( 0.04%) $(fn $name(&mut self, context: &LateContext<'tcx>, $($param: $arg),*) { 7,763,998 ( 0.16%) expand_combined_late_lint_pass_method!($passes, self, $name, (context, $($param),*)); 484,364 ( 0.01%) })* . ) . } . . #[macro_export] . macro_rules! declare_combined_late_lint_pass { . ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], [$hir:tt], $methods:tt) => ( . #[allow(non_snake_case)] . $v struct $name { . $($passes: $passes,)* . } . . impl $name { 4 ( 0.00%) $v fn new() -> Self { 14 ( 0.00%) Self { . $($passes: $constructor,)* . } 5 ( 0.00%) } . 6 ( 0.00%) $v fn get_lints() -> LintArray { . let mut lints = Vec::new(); 1 ( 0.00%) $(lints.extend_from_slice(&$passes::get_lints());)* . lints 7 ( 0.00%) } . } . . impl<'tcx> LateLintPass<'tcx> for $name { . expand_combined_late_lint_pass_methods!([$($passes),*], $methods); . } . . #[allow(rustc::lint_pass_impl_without_macro)] . impl LintPass for $name { -- line 148 ---------------------------------------- -- line 234 ---------------------------------------- . ([$($passes:ident),*], $self: ident, $name: ident, $params:tt) => ({ . $($self.$passes.$name $params;)* . }) . } . . #[macro_export] . macro_rules! expand_combined_early_lint_pass_methods { . ($passes:tt, [$($(#[$attr:meta])* fn $name:ident($($param:ident: $arg:ty),*);)*]) => ( 923,162 ( 0.02%) $(fn $name(&mut self, context: &EarlyContext<'_>, $($param: $arg),*) { 2,508,651 ( 0.05%) expand_combined_early_lint_pass_method!($passes, self, $name, (context, $($param),*)); 1,065,507 ( 0.02%) })* . ) . } . . #[macro_export] . macro_rules! declare_combined_early_lint_pass { . ([$v:vis $name:ident, [$($passes:ident: $constructor:expr,)*]], $methods:tt) => ( . #[allow(non_snake_case)] . $v struct $name { . $($passes: $passes,)* . } . . impl $name { 4 ( 0.00%) $v fn new() -> Self { 5 ( 0.00%) Self { . $($passes: $constructor,)* . } 23 ( 0.00%) } . 12 ( 0.00%) $v fn get_lints() -> LintArray { . let mut lints = Vec::new(); 1 ( 0.00%) $(lints.extend_from_slice(&$passes::get_lints());)* . lints 14 ( 0.00%) } . } . . impl EarlyLintPass for $name { . expand_combined_early_lint_pass_methods!([$($passes),*], $methods); . } . . #[allow(rustc::lint_pass_impl_without_macro)] . impl LintPass for $name { -- line 275 ---------------------------------------- 310 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/expr/as_operand.rs -------------------------------------------------------------------------------- Ir -- line 15 ---------------------------------------- . /// please do *not* return it from functions to avoid bad . /// miscompiles. . crate fn as_local_operand( . &mut self, . block: BasicBlock, . expr: &Expr<'tcx>, . ) -> BlockAnd> { . let local_scope = self.local_scope(); 8,418 ( 0.00%) self.as_operand(block, Some(local_scope), expr, None) . } . . /// Returns an operand suitable for use until the end of the current scope expression and . /// suitable also to be passed as function arguments. . /// . /// The operand returned from this function will *not be valid* after an ExprKind::Scope is . /// passed, so please do *not* return it from functions to avoid bad miscompiles. Returns an . /// operand suitable for use as a call argument. This is almost always equivalent to -- line 31 ---------------------------------------- -- line 72 ---------------------------------------- . /// . /// See #68034 for more details. . crate fn as_local_call_operand( . &mut self, . block: BasicBlock, . expr: &Expr<'tcx>, . ) -> BlockAnd> { . let local_scope = self.local_scope(); 7,620 ( 0.00%) self.as_call_operand(block, Some(local_scope), expr) . } . . /// Compile `expr` into a value that can be used as an operand. . /// If `expr` is a place like `x`, this will introduce a . /// temporary `tmp = x`, so that we capture the value of `x` at . /// this time. . /// . /// If we end up needing to create a temporary, then we will use -- line 88 ---------------------------------------- -- line 89 ---------------------------------------- . /// `local_info` as its `LocalInfo`, unless `as_temporary` . /// has already assigned it a non-`None` `LocalInfo`. . /// Normally, you should use `None` for `local_info` . /// . /// The operand is known to be live until the end of `scope`. . /// . /// Like `as_local_call_operand`, except that the argument will . /// not be valid once `scope` ends. 2,834,790 ( 0.06%) crate fn as_operand( . &mut self, . mut block: BasicBlock, . scope: Option, . expr: &Expr<'tcx>, . local_info: Option>>, . ) -> BlockAnd> { . debug!("as_operand(block={:?}, expr={:?} local_info={:?})", block, expr, local_info); . let this = self; . 1,832,222 ( 0.04%) if let ExprKind::Scope { region_scope, lint_level, value } = expr.kind { 280,510 ( 0.01%) let source_info = this.source_info(expr.span); . let region_scope = (region_scope, source_info); . return this.in_scope(region_scope, lint_level, |this| { 1,823,315 ( 0.04%) this.as_operand(block, scope, &this.thir[value], local_info) . }); . } . . let category = Category::of(&expr.kind).unwrap(); . debug!("as_operand: category={:?} for={:?}", category, expr.kind); . match category { . Category::Constant => { 418,857 ( 0.01%) let constant = this.as_constant(expr); . block.and(Operand::Constant(Box::new(constant))) . } . Category::Place | Category::Rvalue(..) => { . let operand = unpack!(block = this.as_temp(block, scope, expr, Mutability::Mut)); 7,210 ( 0.00%) if this.local_decls[operand].local_info.is_none() { 7,210 ( 0.00%) this.local_decls[operand].local_info = local_info; . } 3,605 ( 0.00%) block.and(Operand::Move(Place::from(operand))) . } . } 2,554,916 ( 0.05%) } . 39,052 ( 0.00%) crate fn as_call_operand( . &mut self, . mut block: BasicBlock, . scope: Option, . expr: &Expr<'tcx>, . ) -> BlockAnd> { . debug!("as_call_operand(block={:?}, expr={:?})", block, expr); . let this = self; . 19,372 ( 0.00%) if let ExprKind::Scope { region_scope, lint_level, value } = expr.kind { 2,960 ( 0.00%) let source_info = this.source_info(expr.span); . let region_scope = (region_scope, source_info); . return this.in_scope(region_scope, lint_level, |this| { 16,280 ( 0.00%) this.as_call_operand(block, scope, &this.thir[value]) . }); . } . 1,524 ( 0.00%) let tcx = this.tcx; . 6,096 ( 0.00%) if tcx.features().unsized_fn_params { . let ty = expr.ty; . let span = expr.span; . let param_env = this.param_env; . . if !ty.is_sized(tcx.at(span), param_env) { . // !sized means !copy, so this is an unsized move . assert!(!ty.is_copy_modulo_regions(tcx.at(span), param_env)); . -- line 159 ---------------------------------------- -- line 171 ---------------------------------------- . projection: tcx.intern_place_elems(&[PlaceElem::Deref]), . }; . . return block.and(Operand::Move(place)); . } . } . } . 13,716 ( 0.00%) this.as_operand(block, scope, expr, None) 24,032 ( 0.00%) } . } 1,703,104 ( 0.03%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_typeck/src/mem_categorization.rs -------------------------------------------------------------------------------- Ir -- line 67 ---------------------------------------- . . crate trait HirNode { . fn hir_id(&self) -> hir::HirId; . fn span(&self) -> Span; . } . . impl HirNode for hir::Expr<'_> { . fn hir_id(&self) -> hir::HirId { 836 ( 0.00%) self.hir_id . } . fn span(&self) -> Span { . self.span . } . } . . impl HirNode for hir::Pat<'_> { . fn hir_id(&self) -> hir::HirId { -- line 83 ---------------------------------------- -- line 96 ---------------------------------------- . body_owner: LocalDefId, . upvars: Option<&'tcx FxIndexMap>, . } . . crate type McResult = Result; . . impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> { . /// Creates a `MemCategorizationContext`. 1,373,715 ( 0.03%) crate fn new( . infcx: &'a InferCtxt<'a, 'tcx>, . param_env: ty::ParamEnv<'tcx>, . body_owner: LocalDefId, . typeck_results: &'a ty::TypeckResults<'tcx>, . ) -> MemCategorizationContext<'a, 'tcx> { 763,175 ( 0.02%) MemCategorizationContext { . typeck_results, . infcx, . param_env, . body_owner, 152,635 ( 0.00%) upvars: infcx.tcx.upvars_mentioned(body_owner), . } 1,373,715 ( 0.03%) } . . crate fn tcx(&self) -> TyCtxt<'tcx> { 493 ( 0.00%) self.infcx.tcx . } . . crate fn type_is_copy_modulo_regions(&self, ty: Ty<'tcx>, span: Span) -> bool { 760 ( 0.00%) self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) . } . . fn resolve_vars_if_possible(&self, value: T) -> T . where . T: TypeFoldable<'tcx>, . { . self.infcx.resolve_vars_if_possible(value) . } . . fn is_tainted_by_errors(&self) -> bool { . self.infcx.is_tainted_by_errors() . } . 3,300 ( 0.00%) fn resolve_type_vars_or_error( . &self, . id: hir::HirId, . ty: Option>, . ) -> McResult> { 297,078 ( 0.01%) match ty { . Some(ty) => { . let ty = self.resolve_vars_if_possible(ty); 298,178 ( 0.01%) if ty.references_error() || ty.is_ty_var() { . debug!("resolve_type_vars_or_error: error from {:?}", ty); . Err(()) . } else { . Ok(ty) . } . } . // FIXME . None if self.is_tainted_by_errors() => Err(()), -- line 154 ---------------------------------------- -- line 155 ---------------------------------------- . None => { . bug!( . "no type for node {}: {} in mem_categorization", . id, . self.tcx().hir().node_to_string(id) . ); . } . } 2,750 ( 0.00%) } . . crate fn node_ty(&self, hir_id: hir::HirId) -> McResult> { 3,960 ( 0.00%) self.resolve_type_vars_or_error(hir_id, self.typeck_results.node_type_opt(hir_id)) . } . . fn expr_ty(&self, expr: &hir::Expr<'_>) -> McResult> { 1,332,506 ( 0.03%) self.resolve_type_vars_or_error(expr.hir_id, self.typeck_results.expr_ty_opt(expr)) . } . . crate fn expr_ty_adjusted(&self, expr: &hir::Expr<'_>) -> McResult> { 605 ( 0.00%) self.resolve_type_vars_or_error(expr.hir_id, self.typeck_results.expr_ty_adjusted_opt(expr)) . } . . /// Returns the type of value that this pattern matches against. . /// Some non-obvious cases: . /// . /// - a `ref x` binding matches against a value of type `T` and gives . /// `x` the type `&T`; we return `T`. . /// - a pattern with implicit derefs (thanks to default binding . /// modes #42640) may look like `Some(x)` but in fact have . /// implicit deref patterns attached (e.g., it is really . /// `&Some(x)`). In that case, we return the "outermost" type . /// (e.g., `&Option). 3,072 ( 0.00%) crate fn pat_ty_adjusted(&self, pat: &hir::Pat<'_>) -> McResult> { . // Check for implicit `&` types wrapping the pattern; note . // that these are never attached to binding patterns, so . // actually this is somewhat "disjoint" from the code below . // that aims to account for `ref x`. 4,992 ( 0.00%) if let Some(vec) = self.typeck_results.pat_adjustments().get(pat.hir_id) { . if let Some(first_ty) = vec.first() { . debug!("pat_ty(pat={:?}) found adjusted ty `{:?}`", pat, first_ty); . return Ok(first_ty); . } . } . . self.pat_ty_unadjusted(pat) 3,072 ( 0.00%) } . . /// Like `pat_ty`, but ignores implicit `&` patterns. . fn pat_ty_unadjusted(&self, pat: &hir::Pat<'_>) -> McResult> { 768 ( 0.00%) let base_ty = self.node_ty(pat.hir_id)?; . debug!("pat_ty(pat={:?}) base_ty={:?}", pat, base_ty); . . // This code detects whether we are looking at a `ref x`, . // and if so, figures out what the type *being borrowed* is. 768 ( 0.00%) let ret_ty = match pat.kind { . PatKind::Binding(..) => { 2,160 ( 0.00%) let bm = *self . .typeck_results . .pat_binding_modes() . .get(pat.hir_id) . .expect("missing binding mode"); . 540 ( 0.00%) if let ty::BindByReference(_) = bm { . // a bind-by-ref means that the base_ty will be the type of the ident itself, . // but what we want here is the type of the underlying value being borrowed. . // So peel off one-level, turning the &T into T. 850 ( 0.00%) match base_ty.builtin_deref(false) { . Some(t) => t.ty, . None => { . debug!("By-ref binding of non-derefable type {:?}", base_ty); . return Err(()); . } . } . } else { . base_ty -- line 229 ---------------------------------------- -- line 231 ---------------------------------------- . } . _ => base_ty, . }; . debug!("pat_ty(pat={:?}) ret_ty={:?}", pat, ret_ty); . . Ok(ret_ty) . } . 5,950 ( 0.00%) crate fn cat_expr(&self, expr: &hir::Expr<'_>) -> McResult> { . // This recursion helper avoids going through *too many* . // adjustments, since *only* non-overloaded deref recurses. . fn helper<'a, 'tcx>( . mc: &MemCategorizationContext<'a, 'tcx>, . expr: &hir::Expr<'_>, . adjustments: &[adjustment::Adjustment<'tcx>], . ) -> McResult> { 4,628 ( 0.00%) match adjustments.split_last() { 5,331 ( 0.00%) None => mc.cat_expr_unadjusted(expr), . Some((adjustment, previous)) => { 3,722 ( 0.00%) mc.cat_expr_adjusted_with(expr, || helper(mc, expr, previous), adjustment) . } . } . } . 6,914 ( 0.00%) helper(self, expr, self.typeck_results.expr_adjustments(expr)) 5,100 ( 0.00%) } . 49,324 ( 0.00%) crate fn cat_expr_adjusted( . &self, . expr: &hir::Expr<'_>, . previous: PlaceWithHirId<'tcx>, . adjustment: &adjustment::Adjustment<'tcx>, . ) -> McResult> { 35,872 ( 0.00%) self.cat_expr_adjusted_with(expr, || Ok(previous), adjustment) 40,356 ( 0.00%) } . 4,125 ( 0.00%) fn cat_expr_adjusted_with( . &self, . expr: &hir::Expr<'_>, . previous: F, . adjustment: &adjustment::Adjustment<'tcx>, . ) -> McResult> . where . F: FnOnce() -> McResult>, . { . debug!("cat_expr_adjusted_with({:?}): {:?}", adjustment, expr); 9,343 ( 0.00%) let target = self.resolve_vars_if_possible(adjustment.target); 9,718 ( 0.00%) match adjustment.kind { 2,144 ( 0.00%) adjustment::Adjust::Deref(overloaded) => { . // Equivalent to *expr or something similar. 6,096 ( 0.00%) let base = if let Some(deref) = overloaded { . let ref_ty = self . .tcx() 50 ( 0.00%) .mk_ref(deref.region, ty::TypeAndMut { ty: target, mutbl: deref.mutbl }); 50 ( 0.00%) self.cat_rvalue(expr.hir_id, expr.span, ref_ty) . } else { 19,174 ( 0.00%) previous()? . }; 40,686 ( 0.00%) self.cat_deref(expr, base) . } . . adjustment::Adjust::NeverToAny . | adjustment::Adjust::Pointer(_) . | adjustment::Adjust::Borrow(_) => { . // Result is an rvalue. 29,865 ( 0.00%) Ok(self.cat_rvalue(expr.hir_id, expr.span, target)) . } . } 4,433 ( 0.00%) } . 1,331,901 ( 0.03%) crate fn cat_expr_unadjusted(&self, expr: &hir::Expr<'_>) -> McResult> { . debug!("cat_expr: id={} expr={:?}", expr.hir_id, expr); . . let expr_ty = self.expr_ty(expr)?; 740,829 ( 0.02%) match expr.kind { . hir::ExprKind::Unary(hir::UnOp::Deref, ref e_base) => { 2,180 ( 0.00%) if self.typeck_results.is_method_call(expr) { . self.cat_overloaded_place(expr, e_base) . } else { 1,728 ( 0.00%) let base = self.cat_expr(e_base)?; 4,752 ( 0.00%) self.cat_deref(expr, base) . } . } . . hir::ExprKind::Field(ref base, _) => { 2,090 ( 0.00%) let base = self.cat_expr(base)?; . debug!("cat_expr(cat_field): id={} expr={:?} base={:?}", expr.hir_id, expr, base); . 2,090 ( 0.00%) let field_idx = self . .typeck_results . .field_indices() 1,254 ( 0.00%) .get(expr.hir_id) . .cloned() . .expect("Field index not found"); . 836 ( 0.00%) Ok(self.cat_projection( . expr, 3,344 ( 0.00%) base, . expr_ty, . ProjectionKind::Field(field_idx as u32, VariantIdx::new(0)), . )) . } . . hir::ExprKind::Index(ref base, _) => { 255 ( 0.00%) if self.typeck_results.is_method_call(expr) { . // If this is an index implemented by a method call, then it . // will include an implicit deref of the result. . // The call to index() returns a `&T` value, which . // is an rvalue. That is what we will be . // dereferencing. . self.cat_overloaded_place(expr, base) . } else { . let base = self.cat_expr(base)?; . Ok(self.cat_projection(expr, base, expr_ty, ProjectionKind::Index)) . } . } . 3,295 ( 0.00%) hir::ExprKind::Path(ref qpath) => { 16,475 ( 0.00%) let res = self.typeck_results.qpath_res(qpath, expr.hir_id); 46,130 ( 0.00%) self.cat_res(expr.hir_id, expr.span, expr_ty, res) . } . . hir::ExprKind::Type(ref e, _) => self.cat_expr(e), . . hir::ExprKind::AddrOf(..) . | hir::ExprKind::Call(..) . | hir::ExprKind::Assign(..) . | hir::ExprKind::AssignOp(..) -- line 358 ---------------------------------------- -- line 374 ---------------------------------------- . | hir::ExprKind::Lit(..) . | hir::ExprKind::ConstBlock(..) . | hir::ExprKind::Break(..) . | hir::ExprKind::Continue(..) . | hir::ExprKind::Struct(..) . | hir::ExprKind::Repeat(..) . | hir::ExprKind::InlineAsm(..) . | hir::ExprKind::Box(..) 1,006,523 ( 0.02%) | hir::ExprKind::Err => Ok(self.cat_rvalue(expr.hir_id, expr.span, expr_ty)), . } 1,331,901 ( 0.03%) } . 36,553 ( 0.00%) crate fn cat_res( . &self, . hir_id: hir::HirId, . span: Span, . expr_ty: Ty<'tcx>, . res: Res, . ) -> McResult> { . debug!("cat_res: id={:?} expr={:?} def={:?}", hir_id, expr_ty, res); . 22,389 ( 0.00%) match res { . Res::Def( . DefKind::Ctor(..) . | DefKind::Const . | DefKind::ConstParam . | DefKind::AssocConst . | DefKind::Fn . | DefKind::AssocFn, . _, . ) . | Res::SelfCtor(..) => Ok(self.cat_rvalue(hir_id, span, expr_ty)), . . Res::Def(DefKind::Static, _) => { . Ok(PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::StaticItem, Vec::new())) . } . 9,804 ( 0.00%) Res::Local(var_id) => { 2,503 ( 0.00%) if self.upvars.map_or(false, |upvars| upvars.contains_key(&var_id)) { . self.cat_upvar(hir_id, var_id) . } else { 24,230 ( 0.00%) Ok(PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::Local(var_id), Vec::new())) . } . } . . def => span_bug!(span, "unexpected definition in memory categorization: {:?}", def), . } 26,584 ( 0.00%) } . . /// Categorize an upvar. . /// . /// Note: the actual upvar access contains invisible derefs of closure . /// environment and upvar reference as appropriate. Only regionck cares . /// about these dereferences, so we let it compute them as needed. . fn cat_upvar(&self, hir_id: hir::HirId, var_id: hir::HirId) -> McResult> { 28 ( 0.00%) let closure_expr_def_id = self.body_owner; . . let upvar_id = ty::UpvarId { . var_path: ty::UpvarPath { hir_id: var_id }, . closure_expr_id: closure_expr_def_id, . }; 56 ( 0.00%) let var_ty = self.node_ty(var_id)?; . 392 ( 0.00%) let ret = PlaceWithHirId::new(hir_id, var_ty, PlaceBase::Upvar(upvar_id), Vec::new()); . . debug!("cat_upvar ret={:?}", ret); . Ok(ret) . } . . crate fn cat_rvalue( . &self, . hir_id: hir::HirId, . span: Span, . expr_ty: Ty<'tcx>, . ) -> PlaceWithHirId<'tcx> { . debug!("cat_rvalue hir_id={:?}, expr_ty={:?}, span={:?}", hir_id, expr_ty, span); 888,038 ( 0.02%) let ret = PlaceWithHirId::new(hir_id, expr_ty, PlaceBase::Rvalue, Vec::new()); . debug!("cat_rvalue ret={:?}", ret); . ret . } . 4,598 ( 0.00%) crate fn cat_projection( . &self, . node: &N, . base_place: PlaceWithHirId<'tcx>, . ty: Ty<'tcx>, . kind: ProjectionKind, . ) -> PlaceWithHirId<'tcx> { 2,767 ( 0.00%) let mut projections = base_place.place.projections; 441 ( 0.00%) projections.push(Projection { kind, ty }); 4,477 ( 0.00%) let ret = PlaceWithHirId::new( . node.hir_id(), 418 ( 0.00%) base_place.place.base_ty, 836 ( 0.00%) base_place.place.base, 2,944 ( 0.00%) projections, . ); . debug!("cat_field ret {:?}", ret); . ret 3,344 ( 0.00%) } . 605 ( 0.00%) fn cat_overloaded_place( . &self, . expr: &hir::Expr<'_>, . base: &hir::Expr<'_>, . ) -> McResult> { . debug!("cat_overloaded_place(expr={:?}, base={:?})", expr, base); . . // Reconstruct the output assuming it's a reference with the . // same region and mutability as the receiver. This holds for . // `Deref(Mut)::Deref(_mut)` and `Index(Mut)::index(_mut)`. 110 ( 0.00%) let place_ty = self.expr_ty(expr)?; 110 ( 0.00%) let base_ty = self.expr_ty_adjusted(base)?; . 165 ( 0.00%) let (region, mutbl) = match *base_ty.kind() { 110 ( 0.00%) ty::Ref(region, _, mutbl) => (region, mutbl), . _ => span_bug!(expr.span, "cat_overloaded_place: base is not a reference"), . }; . let ref_ty = self.tcx().mk_ref(region, ty::TypeAndMut { ty: place_ty, mutbl }); . 110 ( 0.00%) let base = self.cat_rvalue(expr.hir_id, expr.span, ref_ty); 770 ( 0.00%) self.cat_deref(expr, base) 440 ( 0.00%) } . 27,090 ( 0.00%) fn cat_deref( . &self, . node: &impl HirNode, . base_place: PlaceWithHirId<'tcx>, . ) -> McResult> { . debug!("cat_deref: base_place={:?}", base_place); . 5,418 ( 0.00%) let base_curr_ty = base_place.place.ty(); 13,545 ( 0.00%) let deref_ty = match base_curr_ty.builtin_deref(true) { . Some(mt) => mt.ty, . None => { . debug!("explicit deref of non-derefable type: {:?}", base_curr_ty); . return Err(()); . } . }; 10,836 ( 0.00%) let mut projections = base_place.place.projections; . projections.push(Projection { kind: ProjectionKind::Deref, ty: deref_ty }); . 13,545 ( 0.00%) let ret = PlaceWithHirId::new( . node.hir_id(), 2,709 ( 0.00%) base_place.place.base_ty, 5,418 ( 0.00%) base_place.place.base, 10,836 ( 0.00%) projections, . ); . debug!("cat_deref ret {:?}", ret); 21,672 ( 0.00%) Ok(ret) 18,963 ( 0.00%) } . . crate fn cat_pattern( . &self, . place: PlaceWithHirId<'tcx>, . pat: &hir::Pat<'_>, . mut op: F, . ) -> McResult<()> . where . F: FnMut(&PlaceWithHirId<'tcx>, &hir::Pat<'_>), . { 11,537 ( 0.00%) self.cat_pattern_(place, pat, &mut op) . } . . /// Returns the variant index for an ADT used within a Struct or TupleStruct pattern . /// Here `pat_hir_id` is the HirId of the pattern itself. 1,992 ( 0.00%) fn variant_index_for_adt( . &self, . qpath: &hir::QPath<'_>, . pat_hir_id: hir::HirId, . span: Span, . ) -> McResult { 1,162 ( 0.00%) let res = self.typeck_results.qpath_res(qpath, pat_hir_id); 664 ( 0.00%) let ty = self.typeck_results.node_type(pat_hir_id); 332 ( 0.00%) let adt_def = match ty.kind() { . ty::Adt(adt_def, _) => adt_def, . _ => { . self.tcx() . .sess . .delay_span_bug(span, "struct or tuple struct pattern not applied to an ADT"); . return Err(()); . } . }; . 1,294 ( 0.00%) match res { 405 ( 0.00%) Res::Def(DefKind::Variant, variant_id) => Ok(adt_def.variant_index_with_id(variant_id)), 132 ( 0.00%) Res::Def(DefKind::Ctor(CtorOf::Variant, ..), variant_ctor_id) => { 198 ( 0.00%) Ok(adt_def.variant_index_with_ctor_id(variant_ctor_id)) . } . Res::Def(DefKind::Ctor(CtorOf::Struct, ..), _) . | Res::Def(DefKind::Struct | DefKind::Union | DefKind::TyAlias | DefKind::AssocTy, _) . | Res::SelfCtor(..) . | Res::SelfTy(..) => { . // Structs and Unions have only have one variant. . Ok(VariantIdx::new(0)) . } . _ => bug!("expected ADT path, found={:?}", res), . } 1,328 ( 0.00%) } . . /// Returns the total number of fields in an ADT variant used within a pattern. . /// Here `pat_hir_id` is the HirId of the pattern itself. . fn total_fields_in_adt_variant( . &self, . pat_hir_id: hir::HirId, . variant_index: VariantIdx, . span: Span, . ) -> McResult { 132 ( 0.00%) let ty = self.typeck_results.node_type(pat_hir_id); 132 ( 0.00%) match ty.kind() { 198 ( 0.00%) ty::Adt(adt_def, _) => Ok(adt_def.variants[variant_index].fields.len()), . _ => { . self.tcx() . .sess . .delay_span_bug(span, "struct or tuple struct pattern not applied to an ADT"); . Err(()) . } . } . } . . /// Returns the total number of fields in a tuple used within a Tuple pattern. . /// Here `pat_hir_id` is the HirId of the pattern itself. . fn total_fields_in_tuple(&self, pat_hir_id: hir::HirId, span: Span) -> McResult { 300 ( 0.00%) let ty = self.typeck_results.node_type(pat_hir_id); 150 ( 0.00%) match ty.kind() { 75 ( 0.00%) ty::Tuple(substs) => Ok(substs.len()), . _ => { . self.tcx().sess.delay_span_bug(span, "tuple pattern not applied to a tuple"); . Err(()) . } . } . } . . // FIXME(#19596) This is a workaround, but there should be a better way to do this 14,685 ( 0.00%) fn cat_pattern_( . &self, . mut place_with_id: PlaceWithHirId<'tcx>, . pat: &hir::Pat<'_>, . op: &mut F, . ) -> McResult<()> . where . F: FnMut(&PlaceWithHirId<'tcx>, &hir::Pat<'_>), . { -- line 615 ---------------------------------------- -- line 649 ---------------------------------------- . // Some(x, ) => { ... }, . // _ => { ... }, . // } . // ``` . // . // Then we see that to get the same result, we must start with . // `deref { deref { place_foo }}` instead of `place_foo` since the pattern is now `Some(x,)` . // and not `&&Some(x,)`, even though its assigned type is that of `&&Some(x,)`. 10,680 ( 0.00%) for _ in 0..self.typeck_results.pat_adjustments().get(pat.hir_id).map_or(0, |v| v.len()) { . debug!("cat_pattern: applying adjustment to place_with_id={:?}", place_with_id); . place_with_id = self.cat_deref(pat, place_with_id)?; . } 17,355 ( 0.00%) let place_with_id = place_with_id; // lose mutability . debug!("cat_pattern: applied adjustment derefs to get place_with_id={:?}", place_with_id); . . // Invoke the callback, but only now, after the `place_with_id` has adjusted. . // . // To see that this makes sense, consider `match &Some(3) { Some(x) => { ... }}`. In that . // case, the initial `place_with_id` will be that for `&Some(3)` and the pattern is `Some(x)`. We . // don't want to call `op` with these incompatible values. As written, what happens instead . // is that `op` is called with the adjusted place (that for `*&Some(3)`) and the pattern . // `Some(x)` (which matches). Recursing once more, `*&Some(3)` and the pattern `Some(x)` . // result in the place `Downcast(*&Some(3)).0` associated to `x` and invoke `op` with . // that (where the `ref` on `x` is implied). . op(&place_with_id, pat); . 9,342 ( 0.00%) match pat.kind { 375 ( 0.00%) PatKind::Tuple(subpats, dots_pos) => { . // (p1, ..., pN) 300 ( 0.00%) let total_fields = self.total_fields_in_tuple(pat.hir_id, pat.span)?; . . for (i, subpat) in subpats.iter().enumerate_and_adjust(total_fields, dots_pos) { 560 ( 0.00%) let subpat_ty = self.pat_ty_adjusted(subpat)?; . let projection_kind = ProjectionKind::Field(i as u32, VariantIdx::new(0)); . let sub_place = 224 ( 0.00%) self.cat_projection(pat, place_with_id.clone(), subpat_ty, projection_kind); 1,680 ( 0.00%) self.cat_pattern_(sub_place, subpat, op)?; . } . } . 396 ( 0.00%) PatKind::TupleStruct(ref qpath, subpats, dots_pos) => { . // S(p1, ..., pN) 660 ( 0.00%) let variant_index = self.variant_index_for_adt(qpath, pat.hir_id, pat.span)?; . let total_fields = 264 ( 0.00%) self.total_fields_in_adt_variant(pat.hir_id, variant_index, pat.span)?; . . for (i, subpat) in subpats.iter().enumerate_and_adjust(total_fields, dots_pos) { 380 ( 0.00%) let subpat_ty = self.pat_ty_adjusted(subpat)?; . let projection_kind = ProjectionKind::Field(i as u32, variant_index); . let sub_place = 152 ( 0.00%) self.cat_projection(pat, place_with_id.clone(), subpat_ty, projection_kind); 1,140 ( 0.00%) self.cat_pattern_(sub_place, subpat, op)?; . } . } . 300 ( 0.00%) PatKind::Struct(ref qpath, field_pats, _) => { . // S { f1: p1, ..., fN: pN } . 999 ( 0.00%) let variant_index = self.variant_index_for_adt(qpath, pat.hir_id, pat.span)?; . . for fp in field_pats { 1,062 ( 0.00%) let field_ty = self.pat_ty_adjusted(fp.pat)?; 1,062 ( 0.00%) let field_index = self . .typeck_results . .field_indices() 354 ( 0.00%) .get(fp.hir_id) . .cloned() . .expect("no index for a field"); . 354 ( 0.00%) let field_place = self.cat_projection( . pat, . place_with_id.clone(), . field_ty, . ProjectionKind::Field(field_index as u32, variant_index), . ); 2,655 ( 0.00%) self.cat_pattern_(field_place, fp.pat, op)?; . } . } . 6 ( 0.00%) PatKind::Or(pats) => { 18 ( 0.00%) for pat in pats { 84 ( 0.00%) self.cat_pattern_(place_with_id.clone(), pat, op)?; . } . } . . PatKind::Binding(.., Some(ref subpat)) => { . self.cat_pattern_(place_with_id, subpat, op)?; . } . . PatKind::Box(ref subpat) | PatKind::Ref(ref subpat, _) => { . // box p1, &p1, &mut p1. we can ignore the mutability of . // PatKind::Ref since that information is already contained . // in the type. 1,170 ( 0.00%) let subplace = self.cat_deref(pat, place_with_id)?; 936 ( 0.00%) self.cat_pattern_(subplace, subpat, op)?; . } . . PatKind::Slice(before, ref slice, after) => { . let element_ty = match place_with_id.place.ty().builtin_index() { . Some(ty) => ty, . None => { . debug!("explicit index of non-indexable type {:?}", place_with_id); . return Err(()); -- line 751 ---------------------------------------- -- line 780 ---------------------------------------- . | PatKind::Lit(..) . | PatKind::Range(..) . | PatKind::Wild => { . // always ok . } . } . . Ok(()) 10,680 ( 0.00%) } . } 1,071,446 ( 0.02%) -------------------------------------------------------------------------------- -- 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 { 1,402,476 ( 0.03%) let index = self.offset + self.data.len(); 4,484,600 ( 0.09%) self.data.push_back(value); . index . } . . pub fn clear(&mut self) { 95 ( 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() . } . 3,506,190 ( 0.07%) pub fn pop_first(&mut self) -> Option { . let first = self.data.pop_front()?; 2,804,952 ( 0.06%) self.offset += 1; 4,207,428 ( 0.09%) Some(first) 4,908,666 ( 0.10%) } . . pub fn last(&self) -> Option<&T> { . self.data.back() . } . . pub fn last_mut(&mut self) -> Option<&mut T> { . self.data.back_mut() . } -- line 63 ---------------------------------------- 3,506,190 ( 0.07%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_mir_build/src/build/expr/as_constant.rs -------------------------------------------------------------------------------- Ir -- line 3 ---------------------------------------- . use crate::build::Builder; . use rustc_middle::mir::*; . use rustc_middle::thir::*; . use rustc_middle::ty::CanonicalUserTypeAnnotation; . . impl<'a, 'tcx> Builder<'a, 'tcx> { . /// Compile `expr`, yielding a compile-time constant. Assumes that . /// `expr` is a valid compile-time constant! 977,333 ( 0.02%) crate fn as_constant(&mut self, expr: &Expr<'tcx>) -> Constant<'tcx> { . let this = self; 698,095 ( 0.01%) let Expr { ty, temp_lifetime: _, span, ref kind } = *expr; 418,857 ( 0.01%) match *kind { . ExprKind::Scope { region_scope: _, lint_level: _, value } => { . this.as_constant(&this.thir[value]) . } 418,857 ( 0.01%) ExprKind::Literal { literal, user_ty, const_id: _ } => { 977,333 ( 0.02%) let user_ty = user_ty.map(|user_ty| { . this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation { . span, . user_ty, . inferred_ty: ty, . }) . }); 139,816 ( 0.00%) assert_eq!(literal.ty, ty); 698,095 ( 0.01%) Constant { span, user_ty, literal: literal.into() } . } . ExprKind::StaticRef { literal, .. } => { . Constant { span, user_ty: None, literal: literal.into() } . } . ExprKind::ConstBlock { value } => { . Constant { span: span, user_ty: None, literal: value.into() } . } . _ => span_bug!(span, "expression is not a valid constant {:?}", kind), . } 1,256,571 ( 0.03%) } . } 837,714 ( 0.02%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/compiler/rustc_ast/src/ptr.rs -------------------------------------------------------------------------------- Ir -- line 31 ---------------------------------------- . use rustc_data_structures::stable_hasher::{HashStable, StableHasher}; . /// An owned smart pointer. . pub struct P { . ptr: Box, . } . . /// Construct a `P` from a `T` value. . #[allow(non_snake_case)] 168 ( 0.00%) pub fn P(value: T) -> P { . P { ptr: Box::new(value) } 169 ( 0.00%) } . . impl P { . /// Move out of the pointer. . /// Intended for chaining transformations not covered by `map`. . pub fn and_then(self, f: F) -> U . where . F: FnOnce(T) -> U, . { . f(*self.ptr) . } . . /// Equivalent to `and_then(|x| x)`. . pub fn into_inner(self) -> T { 2,212 ( 0.00%) *self.ptr . } . . /// Produce a new `P` from `self` without reallocating. 1,128,152 ( 0.02%) pub fn map(mut self, f: F) -> P . where . F: FnOnce(T) -> T, . { 2,538,342 ( 0.05%) let x = f(*self.ptr); 987,568 ( 0.02%) *self.ptr = x; . . self 1,269,171 ( 0.03%) } . . /// Optionally produce a new `P` from `self` without reallocating. . pub fn filter_map(mut self, f: F) -> Option> . where . F: FnOnce(T) -> Option, . { . *self.ptr = f(*self.ptr)?; . Some(self) . } . } . . impl Deref for P { . type Target = T; . . fn deref(&self) -> &T { 1,832,073 ( 0.04%) &self.ptr . } . } . . impl DerefMut for P { . fn deref_mut(&mut self) -> &mut T { 9,134 ( 0.00%) &mut self.ptr . } . } . . impl Clone for P { 18,588 ( 0.00%) fn clone(&self) -> P { 1,167 ( 0.00%) P((**self).clone()) 21,626 ( 0.00%) } . } . . impl Debug for P { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . Debug::fmt(&self.ptr, f) . } . } . -- line 104 ---------------------------------------- -- line 111 ---------------------------------------- . impl fmt::Pointer for P { . fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { . fmt::Pointer::fmt(&self.ptr, f) . } . } . . impl> Decodable for P { . fn decode(d: &mut D) -> P { 36 ( 0.00%) P(Decodable::decode(d)) . } . } . . impl> Encodable for P { . fn encode(&self, s: &mut S) -> Result<(), S::Error> { 4 ( 0.00%) (**self).encode(s) . } . } . . impl P<[T]> { . pub const fn new() -> P<[T]> { . // HACK(eddyb) bypass the lack of a `const fn` to create an empty `Box<[T]>` . // (as trait methods, `default` in this case, can't be `const fn` yet). . P { -- line 133 ---------------------------------------- -- line 208 ---------------------------------------- . P::from_vec(Decodable::decode(d)) . } . } . . impl HashStable for P . where . T: ?Sized + HashStable, . { 56 ( 0.00%) fn hash_stable(&self, hcx: &mut CTX, hasher: &mut StableHasher) { . (**self).hash_stable(hcx, hasher); . } . } 1,395 ( 0.00%) -------------------------------------------------------------------------------- -- Auto-annotated source: /usr/home/liquid/rust/worktree-benchmarking/library/core/src/num/mod.rs -------------------------------------------------------------------------------- Ir -- line 279 ---------------------------------------- . /// assert!(ascii.is_ascii()); . /// assert!(!non_ascii.is_ascii()); . /// ``` . #[must_use] . #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] . #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.43.0")] . #[inline] . pub const fn is_ascii(&self) -> bool { 1,619 ( 0.00%) *self & 128 == 0 . } . . /// Makes a copy of the value in its ASCII upper case equivalent. . /// . /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z', . /// but non-ASCII letters are unchanged. . /// . /// To uppercase the value in-place, use [`make_ascii_uppercase`]. -- line 295 ---------------------------------------- -- line 304 ---------------------------------------- . /// . /// [`make_ascii_uppercase`]: Self::make_ascii_uppercase . #[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"] . #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] . #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")] . #[inline] . pub const fn to_ascii_uppercase(&self) -> u8 { . // Unset the fifth bit if this is a lowercase letter 4,144 ( 0.00%) *self & !((self.is_ascii_lowercase() as u8) * ASCII_CASE_MASK) . } . . /// Makes a copy of the value in its ASCII lower case equivalent. . /// . /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z', . /// but non-ASCII letters are unchanged. . /// . /// To lowercase the value in-place, use [`make_ascii_lowercase`]. -- line 320 ---------------------------------------- -- line 329 ---------------------------------------- . /// . /// [`make_ascii_lowercase`]: Self::make_ascii_lowercase . #[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"] . #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] . #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")] . #[inline] . pub const fn to_ascii_lowercase(&self) -> u8 { . // Set the fifth bit if this is an uppercase letter 3,326 ( 0.00%) *self | (self.is_ascii_uppercase() as u8 * ASCII_CASE_MASK) . } . . /// Assumes self is ascii . #[inline] . pub(crate) const fn ascii_change_case_unchecked(&self) -> u8 { . *self ^ ASCII_CASE_MASK . } . -- line 345 ---------------------------------------- -- line 404 ---------------------------------------- . /// . /// assert_eq!(b'a', byte); . /// ``` . /// . /// [`to_ascii_lowercase`]: Self::to_ascii_lowercase . #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")] . #[inline] . pub fn make_ascii_lowercase(&mut self) { 2,656 ( 0.00%) *self = self.to_ascii_lowercase(); . } . . /// Checks if the value is an ASCII alphabetic character: . /// . /// - U+0041 'A' ..= U+005A 'Z', or . /// - U+0061 'a' ..= U+007A 'z'. . /// . /// # Examples -- line 420 ---------------------------------------- -- line 474 ---------------------------------------- . /// assert!(!lf.is_ascii_uppercase()); . /// assert!(!esc.is_ascii_uppercase()); . /// ``` . #[must_use] . #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] . #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")] . #[inline] . pub const fn is_ascii_uppercase(&self) -> bool { 4,601 ( 0.00%) matches!(*self, b'A'..=b'Z') . } . . /// Checks if the value is an ASCII lowercase character: . /// U+0061 'a' ..= U+007A 'z'. . /// . /// # Examples . /// . /// ``` -- line 490 ---------------------------------------- -- line 508 ---------------------------------------- . /// assert!(!lf.is_ascii_lowercase()); . /// assert!(!esc.is_ascii_lowercase()); . /// ``` . #[must_use] . #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")] . #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")] . #[inline] . pub const fn is_ascii_lowercase(&self) -> bool { 2,368 ( 0.00%) matches!(*self, b'a'..=b'z') . } . . /// Checks if the value is an ASCII alphanumeric character: . /// . /// - U+0041 'A' ..= U+005A 'Z', or . /// - U+0061 'a' ..= U+007A 'z', or . /// - U+0030 '0' ..= U+0039 '9'. . /// -- line 524 ---------------------------------------- -- line 949 ---------------------------------------- . fn checked_add(&self, other: u32) -> Option; . } . . macro_rules! from_str_radix_int_impl { . ($($t:ty)*) => {$( . #[stable(feature = "rust1", since = "1.0.0")] . impl FromStr for $t { . type Err = ParseIntError; 2 ( 0.00%) fn from_str(src: &str) -> Result { . from_str_radix(src, 10) 102 ( 0.00%) } . } . )*} . } . from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 } . . macro_rules! doit { . ($($t:ty)*) => ($(impl FromStrRadixHelper for $t { . #[inline] -- line 967 ---------------------------------------- -- line 975 ---------------------------------------- . Self::checked_mul(*self, other as Self) . } . #[inline] . fn checked_sub(&self, other: u32) -> Option { . Self::checked_sub(*self, other as Self) . } . #[inline] . fn checked_add(&self, other: u32) -> Option { 210,755 ( 0.00%) Self::checked_add(*self, other as Self) . } . })*) . } . doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize } . 828,258 ( 0.02%) fn from_str_radix(src: &str, radix: u32) -> Result { . use self::IntErrorKind::*; . use self::ParseIntError as PIE; . . assert!( . (2..=36).contains(&radix), . "from_str_radix_int: must lie in the range `[2, 36]` - found {}", . radix . ); . 138,095 ( 0.00%) if src.is_empty() { . return Err(PIE { kind: Empty }); . } . . let is_signed_ty = T::from_u32(0) > T::min_value(); . . // all valid digits are ascii, so we will just iterate over the utf8 bytes . // and cast them to chars. .to_digit() will safely return None for anything . // other than a valid ascii digit for the given radix, including the first-byte . // of multi-byte sequences . let src = src.as_bytes(); . 690,475 ( 0.01%) let (is_positive, digits) = match src[0] { . b'+' | b'-' if src[1..].is_empty() => { . return Err(PIE { kind: InvalidDigit }); . } . b'+' => (true, &src[1..]), . b'-' if is_signed_ty => (false, &src[1..]), . _ => (true, src), . }; . . let mut result = T::from_u32(0); . if is_positive { . // The number is positive 210,757 ( 0.00%) for &c in digits { 176,015 ( 0.00%) let x = match (c as char).to_digit(radix) { . Some(x) => x, . None => return Err(PIE { kind: InvalidDigit }), . }; 352,625 ( 0.01%) result = match result.checked_mul(radix) { . Some(result) => result, . None => return Err(PIE { kind: PosOverflow }), . }; 352,685 ( 0.01%) result = match result.checked_add(x) { . Some(result) => result, . None => return Err(PIE { kind: PosOverflow }), . }; . } . } else { . // The number is negative . for &c in digits { . let x = match (c as char).to_digit(radix) { -- line 1040 ---------------------------------------- -- line 1046 ---------------------------------------- . None => return Err(PIE { kind: NegOverflow }), . }; . result = match result.checked_sub(x) { . Some(result) => result, . None => return Err(PIE { kind: NegOverflow }), . }; . } . } 552,172 ( 0.01%) Ok(result) 966,513 ( 0.02%) } 973,984 ( 0.02%) -------------------------------------------------------------------------------- The following files chosen for auto-annotation could not be found: -------------------------------------------------------------------------------- ./elf/dl-lookup.c ./malloc/malloc.c ./string/../sysdeps/x86_64/multiarch/memmove-vec-unaligned-erms.S -------------------------------------------------------------------------------- Ir -------------------------------------------------------------------------------- 2,955,004,887 (60.62%) events annotated