From 5885baa812853a496425df6031fd84ecb680909d Mon Sep 17 00:00:00 2001 From: Kurashina Hinata Date: Sat, 26 Sep 2026 19:20:32 +0900 Subject: [PATCH 01/18] Don't suggest replacing foreign format specifiers in `concat!` output When a format string is not a literal in the source, e.g. when it is produced by `concat!`, the offsets of printf- and shell-style specifiers are relative to the expanded string rather than to the source. `check_foreign!` still used them to place a machine-applicable suggestion, which could rewrite unrelated source text such as turning `concat!` into `c{}cat!`, or ICE when the span landed inside a multibyte character. When the format string is not a source literal, explain the translation in a note instead, e.g. "`%d` should be written as `{}`", and don't emit the suggestion. For specifiers that cannot be translated, point the note at the whole format string argument instead of a span computed from those offsets; the output is the same as before. The output for format strings written as literals is unchanged. --- compiler/rustc_builtin_macros/src/format.rs | 31 +++++-- .../format-args-concat-foreign-specifier.rs | 32 ++++++++ ...ormat-args-concat-foreign-specifier.stderr | 82 +++++++++++++++++++ 3 files changed, 138 insertions(+), 7 deletions(-) create mode 100644 tests/ui/fmt/format-args-concat-foreign-specifier.rs create mode 100644 tests/ui/fmt/format-args-concat-foreign-specifier.stderr diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index e23c057f8a651..cd0bfd581a3f0 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -630,6 +630,7 @@ fn make_format_args( foreign_fmt_str, uncooked_fmt_str.1.as_str(), fmt_span, + is_source_literal, ); } @@ -736,6 +737,7 @@ fn report_missing_placeholders( fmt_str: &str, uncooked_fmt_str: &str, fmt_span: Span, + is_source_literal: bool, ) { let mut diag = if let &[(span, named)] = &unused[..] { ecx.dcx().create_err(diagnostics::FormatUnusedArg { span, named }) @@ -805,8 +807,8 @@ fn report_missing_placeholders( _ => continue, }; - let pos = sub.position(); - if !explained.insert(sub.to_string()) { + let sub_str = sub.to_string(); + if !explained.insert(sub_str.clone()) { continue; } @@ -815,14 +817,29 @@ fn report_missing_placeholders( show_doc_note = true; } - let sp = fmt_span.from_inner(pos); + if is_source_literal { + let sp = fmt_span.from_inner(sub.position()); - if success { - suggestions.push((sp, trn)); + if success { + suggestions.push((sp, trn)); + } else { + diag.span_note( + sp, + format!("format specifiers use curly braces, and {}", trn), + ); + } + } else if success { + // The offsets of `sub` are relative to the expanded format string, so + // they cannot be mapped back to the source. Explain the translation in + // text instead of suggesting a replacement at a bogus location. + diag.note(format!( + "format specifiers use curly braces: `{sub_str}` should be written as \ + `{trn}`" + )); } else { diag.span_note( - sp, - format!("format specifiers use curly braces, and {}", trn), + fmt_span, + format!("format specifiers use curly braces, and {trn}"), ); } } diff --git a/tests/ui/fmt/format-args-concat-foreign-specifier.rs b/tests/ui/fmt/format-args-concat-foreign-specifier.rs new file mode 100644 index 0000000000000..6f00964deae6f --- /dev/null +++ b/tests/ui/fmt/format-args-concat-foreign-specifier.rs @@ -0,0 +1,32 @@ +// When the format string comes from `concat!`, the offsets of printf- and shell-style specifiers +// are relative to the expanded string, not to the source. Before the fix, `check_foreign!` used +// them to place a machine-applicable suggestion at a bogus location in the `concat!` invocation, +// and rendering it caused an ICE if that location was inside a multibyte character. After the +// fix, the translation is explained in a note instead of a suggestion. + +fn main() { + // Used to ICE: the specifier's span lands inside `é` (2 bytes) or `𐏿` (4 bytes). + format_args!(concat!("é", "aaaaa%d"), 1); + //~^ ERROR argument never used + format_args!(concat!("𐏿", "aaa%d"), 1); + //~^ ERROR argument never used + format_args!(concat!("é", "aaaaa$1"), 1); + //~^ ERROR argument never used + format_args!(concat!("𐏿", "aaa$1"), 1); + //~^ ERROR argument never used + + // Used to suggest rewriting `concat!` itself, e.g. into `c{}cat!`. + format_args!(concat!("%d", ""), 1); + //~^ ERROR argument never used + format_args!(concat!("$1", ""), 1); + //~^ ERROR argument never used + + // Several specifiers each get their own note. + format_args!(concat!("%d %s", ""), 1, 2); + //~^ ERROR multiple unused formatting arguments + + // A specifier that cannot be translated keeps getting a note pointing at the whole `concat!` + // invocation, as before. + format_args!(concat!("%5.3d", ""), 1); + //~^ ERROR argument never used +} diff --git a/tests/ui/fmt/format-args-concat-foreign-specifier.stderr b/tests/ui/fmt/format-args-concat-foreign-specifier.stderr new file mode 100644 index 0000000000000..37fbd53200da2 --- /dev/null +++ b/tests/ui/fmt/format-args-concat-foreign-specifier.stderr @@ -0,0 +1,82 @@ +error: argument never used + --> $DIR/format-args-concat-foreign-specifier.rs:9:43 + | +LL | format_args!(concat!("é", "aaaaa%d"), 1); + | ^ argument never used + | + = note: format specifiers use curly braces: `%d` should be written as `{}` + = note: printf formatting is not supported; see the documentation for `std::fmt` + +error: argument never used + --> $DIR/format-args-concat-foreign-specifier.rs:11:41 + | +LL | format_args!(concat!("𐏿", "aaa%d"), 1); + | ^ argument never used + | + = note: format specifiers use curly braces: `%d` should be written as `{}` + = note: printf formatting is not supported; see the documentation for `std::fmt` + +error: argument never used + --> $DIR/format-args-concat-foreign-specifier.rs:13:43 + | +LL | format_args!(concat!("é", "aaaaa$1"), 1); + | ^ argument never used + | + = note: format specifiers use curly braces: `$1` should be written as `{1}` + = note: shell formatting is not supported; see the documentation for `std::fmt` + +error: argument never used + --> $DIR/format-args-concat-foreign-specifier.rs:15:41 + | +LL | format_args!(concat!("𐏿", "aaa$1"), 1); + | ^ argument never used + | + = note: format specifiers use curly braces: `$1` should be written as `{1}` + = note: shell formatting is not supported; see the documentation for `std::fmt` + +error: argument never used + --> $DIR/format-args-concat-foreign-specifier.rs:19:37 + | +LL | format_args!(concat!("%d", ""), 1); + | ^ argument never used + | + = note: format specifiers use curly braces: `%d` should be written as `{}` + = note: printf formatting is not supported; see the documentation for `std::fmt` + +error: argument never used + --> $DIR/format-args-concat-foreign-specifier.rs:21:37 + | +LL | format_args!(concat!("$1", ""), 1); + | ^ argument never used + | + = note: format specifiers use curly braces: `$1` should be written as `{1}` + = note: shell formatting is not supported; see the documentation for `std::fmt` + +error: multiple unused formatting arguments + --> $DIR/format-args-concat-foreign-specifier.rs:25:40 + | +LL | format_args!(concat!("%d %s", ""), 1, 2); + | -------------------- ^ ^ argument never used + | | | + | | argument never used + | multiple missing formatting specifiers + | + = note: format specifiers use curly braces: `%d` should be written as `{}` + = note: format specifiers use curly braces: `%s` should be written as `{}` + = note: printf formatting is not supported; see the documentation for `std::fmt` + +error: argument never used + --> $DIR/format-args-concat-foreign-specifier.rs:30:40 + | +LL | format_args!(concat!("%5.3d", ""), 1); + | ^ argument never used + | +note: format specifiers use curly braces, and width and precision cannot both be specified for integer conversions + --> $DIR/format-args-concat-foreign-specifier.rs:30:18 + | +LL | format_args!(concat!("%5.3d", ""), 1); + | ^^^^^^^^^^^^^^^^^^^^ + = note: printf formatting is not supported; see the documentation for `std::fmt` + +error: aborting due to 8 previous errors + From e99838b28059447d48f79cfde1003cd629e2c36b Mon Sep 17 00:00:00 2001 From: Bee Date: Mon, 5 Oct 2026 20:26:30 +0100 Subject: [PATCH 02/18] Fix the floating point clobbers of RISC-V `clobber_abi` --- compiler/rustc_target/src/asm/mod.rs | 23 ++++++++++++++++++----- tests/codegen-llvm/asm/riscv-clobbers.rs | 6 +++--- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/compiler/rustc_target/src/asm/mod.rs b/compiler/rustc_target/src/asm/mod.rs index 6f9751e807490..9893d3911e88f 100644 --- a/compiler/rustc_target/src/asm/mod.rs +++ b/compiler/rustc_target/src/asm/mod.rs @@ -1268,13 +1268,24 @@ impl InlineAsmClobberAbi { x10, x11, x12, x13, x14, x15, x16, x17, // t3-t6 x28, x29, x30, x31, + + // Only ABI_FLEN bits of the callee-saved floating point registers are + // preserved. As LLVM doesn't have partial clobbers, this means we have to + // clobber the callee-saved floating point registers as well as the temporary + // registers. // ft0-ft7 f0, f1, f2, f3, f4, f5, f6, f7, + // fs0-fs1 (callee-saved) + f8, f9, // fa0-fa7 f10, f11, f12, f13, f14, f15, f16, f17, + // fs2-fs11 (callee-saved) + f18, f19, f20, f21, f22, f23, f24, f25, + f26, f27, // ft8-ft11 f28, f29, f30, f31, + // v0-v31 v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, @@ -1293,12 +1304,14 @@ impl InlineAsmClobberAbi { x5, x6, x7, // a0-a5 x10, x11, x12, x13, x14, x15, - // ft0-ft7 + + // f0-f31 f0, f1, f2, f3, f4, f5, f6, f7, - // fa0-fa7 - f10, f11, f12, f13, f14, f15, f16, f17, - // ft8-ft11 - f28, f29, f30, f31, + f8, f9, f10, f11, f12, f13, f14, f15, + f16, f17, f18, f19, f20, f21, f22, f23, + f24, f25, f26, f27, f28, f29, f30, f31, + + // v0-v31 v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, diff --git a/tests/codegen-llvm/asm/riscv-clobbers.rs b/tests/codegen-llvm/asm/riscv-clobbers.rs index 51b9b25aec486..fb2bbebd8883a 100644 --- a/tests/codegen-llvm/asm/riscv-clobbers.rs +++ b/tests/codegen-llvm/asm/riscv-clobbers.rs @@ -31,9 +31,9 @@ pub unsafe fn no_clobber() { } // CHECK-LABEL: @clobber_abi -// rv32i: asm sideeffect "", "={x1},={x5},={x6},={x7},={x10},={x11},={x12},={x13},={x14},={x15},={x16},={x17},={x28},={x29},={x30},={x31},~{f0},~{f1},~{f2},~{f3},~{f4},~{f5},~{f6},~{f7},~{f10},~{f11},~{f12},~{f13},~{f14},~{f15},~{f16},~{f17},~{f28},~{f29},~{f30},~{f31},~{v0},~{v1},~{v2},~{v3},~{v4},~{v5},~{v6},~{v7},~{v8},~{v9},~{v10},~{v11},~{v12},~{v13},~{v14},~{v15},~{v16},~{v17},~{v18},~{v19},~{v20},~{v21},~{v22},~{v23},~{v24},~{v25},~{v26},~{v27},~{v28},~{v29},~{v30},~{v31}"() -// rv64i: asm sideeffect "", "={x1},={x5},={x6},={x7},={x10},={x11},={x12},={x13},={x14},={x15},={x16},={x17},={x28},={x29},={x30},={x31},~{f0},~{f1},~{f2},~{f3},~{f4},~{f5},~{f6},~{f7},~{f10},~{f11},~{f12},~{f13},~{f14},~{f15},~{f16},~{f17},~{f28},~{f29},~{f30},~{f31},~{v0},~{v1},~{v2},~{v3},~{v4},~{v5},~{v6},~{v7},~{v8},~{v9},~{v10},~{v11},~{v12},~{v13},~{v14},~{v15},~{v16},~{v17},~{v18},~{v19},~{v20},~{v21},~{v22},~{v23},~{v24},~{v25},~{v26},~{v27},~{v28},~{v29},~{v30},~{v31}"() -// rv32e: asm sideeffect "", "={x1},={x5},={x6},={x7},={x10},={x11},={x12},={x13},={x14},={x15},~{f0},~{f1},~{f2},~{f3},~{f4},~{f5},~{f6},~{f7},~{f10},~{f11},~{f12},~{f13},~{f14},~{f15},~{f16},~{f17},~{f28},~{f29},~{f30},~{f31},~{v0},~{v1},~{v2},~{v3},~{v4},~{v5},~{v6},~{v7},~{v8},~{v9},~{v10},~{v11},~{v12},~{v13},~{v14},~{v15},~{v16},~{v17},~{v18},~{v19},~{v20},~{v21},~{v22},~{v23},~{v24},~{v25},~{v26},~{v27},~{v28},~{v29},~{v30},~{v31}"() +// rv32i: asm sideeffect "", "={x1},={x5},={x6},={x7},={x10},={x11},={x12},={x13},={x14},={x15},={x16},={x17},={x28},={x29},={x30},={x31},~{f0},~{f1},~{f2},~{f3},~{f4},~{f5},~{f6},~{f7},~{f8},~{f9},~{f10},~{f11},~{f12},~{f13},~{f14},~{f15},~{f16},~{f17},~{f18},~{f19},~{f20},~{f21},~{f22},~{f23},~{f24},~{f25},~{f26},~{f27},~{f28},~{f29},~{f30},~{f31},~{v0},~{v1},~{v2},~{v3},~{v4},~{v5},~{v6},~{v7},~{v8},~{v9},~{v10},~{v11},~{v12},~{v13},~{v14},~{v15},~{v16},~{v17},~{v18},~{v19},~{v20},~{v21},~{v22},~{v23},~{v24},~{v25},~{v26},~{v27},~{v28},~{v29},~{v30},~{v31}"() +// rv64i: asm sideeffect "", "={x1},={x5},={x6},={x7},={x10},={x11},={x12},={x13},={x14},={x15},={x16},={x17},={x28},={x29},={x30},={x31},~{f0},~{f1},~{f2},~{f3},~{f4},~{f5},~{f6},~{f7},~{f8},~{f9},~{f10},~{f11},~{f12},~{f13},~{f14},~{f15},~{f16},~{f17},~{f18},~{f19},~{f20},~{f21},~{f22},~{f23},~{f24},~{f25},~{f26},~{f27},~{f28},~{f29},~{f30},~{f31},~{v0},~{v1},~{v2},~{v3},~{v4},~{v5},~{v6},~{v7},~{v8},~{v9},~{v10},~{v11},~{v12},~{v13},~{v14},~{v15},~{v16},~{v17},~{v18},~{v19},~{v20},~{v21},~{v22},~{v23},~{v24},~{v25},~{v26},~{v27},~{v28},~{v29},~{v30},~{v31}"() +// rv32e: asm sideeffect "", "={x1},={x5},={x6},={x7},={x10},={x11},={x12},={x13},={x14},={x15},~{f0},~{f1},~{f2},~{f3},~{f4},~{f5},~{f6},~{f7},~{f8},~{f9},~{f10},~{f11},~{f12},~{f13},~{f14},~{f15},~{f16},~{f17},~{f18},~{f19},~{f20},~{f21},~{f22},~{f23},~{f24},~{f25},~{f26},~{f27},~{f28},~{f29},~{f30},~{f31},~{v0},~{v1},~{v2},~{v3},~{v4},~{v5},~{v6},~{v7},~{v8},~{v9},~{v10},~{v11},~{v12},~{v13},~{v14},~{v15},~{v16},~{v17},~{v18},~{v19},~{v20},~{v21},~{v22},~{v23},~{v24},~{v25},~{v26},~{v27},~{v28},~{v29},~{v30},~{v31}"() #[no_mangle] pub unsafe fn clobber_abi() { asm!("", clobber_abi("C"), options(nostack, nomem, preserves_flags)); From 15b7f9224373a95713adab3fc16a1f668d9654c2 Mon Sep 17 00:00:00 2001 From: mejrs <59372212+mejrs@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:35:26 +0200 Subject: [PATCH 03/18] omit unconditionally invoking crate level limits query These are always checked in attribute parsing --- compiler/rustc_interface/src/passes.rs | 7 ------- 1 file changed, 7 deletions(-) diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 5ea1cb20990b5..670547dae9d6b 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -1130,13 +1130,6 @@ fn run_required_analyses(tcx: TyCtxt<'_>) { tcx.ensure_ok().check_mod_unstable_api_usage(module); }); }, - &mut || { - // We force these queries to run, - // since they might not otherwise get called. - // This marks the corresponding crate-level attributes - // as used, and ensures that their values are valid. - tcx.ensure_ok().limits(()); - }, ]); }); From d3a4f96a6257be859b707e007b0434993d9c69de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Sun, 25 Oct 2026 18:06:58 +0000 Subject: [PATCH 04/18] Point at prior token on `let` when expression is expected ``` error: expected expression, found `let` statement --> issue-87291.rs:2:5 | 2 | - let a = opt1.map(|_| { | - ^^^ | | | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions ``` --- compiler/rustc_parse/src/parser/expr.rs | 7 ++ tests/ui/missing/missing-let.rs | 2 +- tests/ui/missing/missing-let.stderr | 3 + .../avoid-invalid-mir.stderr | 4 +- .../disallowed-positions.e2021.stderr | 92 ++++++++++++++----- .../disallowed-positions.e2024.stderr | 92 ++++++++++++++----- .../disallowed-positions.nothing.stderr | 92 ++++++++++++++----- ...e-does-not-interact-with-let-chains.stderr | 4 +- .../invalid-let-in-a-valid-let-context.stderr | 12 ++- 9 files changed, 233 insertions(+), 75 deletions(-) diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 5ad0aae9a916a..411018f248369 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -2609,6 +2609,13 @@ impl<'a> Parser<'a> { if self.prev_token == token::Or { // This was part of a closure, the that part of the parser recover. return Err(self.dcx().create_err(err)); + } else if AssocOp::from_token(&self.prev_token).is_some() + || self.prev_token == token::Bang + { + // This was something like `- let`, we want to point at that. + let mut err = self.dcx().create_err(err); + err.span_label(self.prev_token.span, "expected an expression after this"); + Recovered::Yes(err.emit_err()) } else { Recovered::Yes(self.dcx().emit_err(err)) } diff --git a/tests/ui/missing/missing-let.rs b/tests/ui/missing/missing-let.rs index 595de640470b6..ab5fbdd6e8502 100644 --- a/tests/ui/missing/missing-let.rs +++ b/tests/ui/missing/missing-let.rs @@ -7,7 +7,7 @@ fn main() { //~| NOTE: only supported directly in conditions of `if` and `while` expressions {} - if Some(_) = y && + if Some(_) = y && //~ NOTE: expected an expression after this //~^ NOTE expected `let` expression, found assignment //~| ERROR let-chain with missing `let` let Some(_) = z diff --git a/tests/ui/missing/missing-let.stderr b/tests/ui/missing/missing-let.stderr index 0a6e76b154f78..577109ae98ee1 100644 --- a/tests/ui/missing/missing-let.stderr +++ b/tests/ui/missing/missing-let.stderr @@ -17,6 +17,9 @@ LL | && Some(x) == x error: expected expression, found `let` statement --> $DIR/missing-let.rs:13:9 | +LL | if Some(_) = y && + | -- expected an expression after this +... LL | let Some(_) = z | ^^^ | diff --git a/tests/ui/rfcs/rfc-2497-if-let-chains/avoid-invalid-mir.stderr b/tests/ui/rfcs/rfc-2497-if-let-chains/avoid-invalid-mir.stderr index 606f808f09369..3a85860b43389 100644 --- a/tests/ui/rfcs/rfc-2497-if-let-chains/avoid-invalid-mir.stderr +++ b/tests/ui/rfcs/rfc-2497-if-let-chains/avoid-invalid-mir.stderr @@ -2,7 +2,9 @@ error: expected expression, found `let` statement --> $DIR/avoid-invalid-mir.rs:5:6 | LL | !let y = 42; - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions diff --git a/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.e2021.stderr b/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.e2021.stderr index 40a32880f4071..974ca914ba926 100644 --- a/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.e2021.stderr +++ b/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.e2021.stderr @@ -330,7 +330,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:130:12 | LL | if x = let 0 = 0 {} - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -394,7 +396,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:161:19 | LL | if let true = let true = true {} - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -450,7 +454,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:184:12 | LL | if (|| let 0 = 0) {} - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -536,7 +542,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:221:15 | LL | while x = let 0 = 0 {} - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -600,7 +608,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:252:22 | LL | while let true = let true = true {} - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -656,7 +666,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:275:15 | LL | while (|| let 0 = 0) {} - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -672,7 +684,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:295:6 | LL | &let 0 = 0; - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -680,7 +694,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:298:6 | LL | !let 0 = 0; - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -688,7 +704,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:300:6 | LL | *let 0 = 0; - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -696,7 +714,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:302:6 | LL | -let 0 = 0; - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -704,7 +724,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:304:13 | LL | let _ = let _ = 3; - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -720,7 +742,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:315:13 | LL | true || let 0 = 0; - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -728,7 +752,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:317:14 | LL | (true || let 0 = 0); - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -736,7 +762,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:319:22 | LL | true && (true || let 0 = 0); - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -744,7 +772,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:323:9 | LL | x = let 0 = 0; - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -792,7 +822,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:337:17 | LL | (let true = let true = true); - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -800,7 +832,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:343:25 | LL | let x = true && let y = 1; - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -816,7 +850,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:354:6 | LL | &let 0 = 0 - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -824,7 +860,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:365:17 | LL | true && let 1 = 1 - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -832,7 +870,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:370:17 | LL | true && let 1 = 1 - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -840,7 +880,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:375:17 | LL | true && let 1 = 1 - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -848,7 +890,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:386:17 | LL | true && let 1 = 1 - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -1014,7 +1058,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:439:22 | LL | let x = (true && let y = 1); - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions diff --git a/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.e2024.stderr b/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.e2024.stderr index 21167cf63d176..1b707338fa454 100644 --- a/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.e2024.stderr +++ b/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.e2024.stderr @@ -306,7 +306,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:130:12 | LL | if x = let 0 = 0 {} - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -370,7 +372,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:161:19 | LL | if let true = let true = true {} - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -426,7 +430,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:184:12 | LL | if (|| let 0 = 0) {} - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -512,7 +518,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:221:15 | LL | while x = let 0 = 0 {} - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -576,7 +584,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:252:22 | LL | while let true = let true = true {} - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -632,7 +642,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:275:15 | LL | while (|| let 0 = 0) {} - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -648,7 +660,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:295:6 | LL | &let 0 = 0; - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -656,7 +670,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:298:6 | LL | !let 0 = 0; - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -664,7 +680,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:300:6 | LL | *let 0 = 0; - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -672,7 +690,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:302:6 | LL | -let 0 = 0; - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -680,7 +700,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:304:13 | LL | let _ = let _ = 3; - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -696,7 +718,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:315:13 | LL | true || let 0 = 0; - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -704,7 +728,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:317:14 | LL | (true || let 0 = 0); - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -712,7 +738,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:319:22 | LL | true && (true || let 0 = 0); - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -720,7 +748,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:323:9 | LL | x = let 0 = 0; - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -768,7 +798,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:337:17 | LL | (let true = let true = true); - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -776,7 +808,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:343:25 | LL | let x = true && let y = 1; - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -792,7 +826,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:354:6 | LL | &let 0 = 0 - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -800,7 +836,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:365:17 | LL | true && let 1 = 1 - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -808,7 +846,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:370:17 | LL | true && let 1 = 1 - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -816,7 +856,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:375:17 | LL | true && let 1 = 1 - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -824,7 +866,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:386:17 | LL | true && let 1 = 1 - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -960,7 +1004,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:439:22 | LL | let x = (true && let y = 1); - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions diff --git a/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.nothing.stderr b/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.nothing.stderr index f69c18ff0d906..10b3f800c618b 100644 --- a/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.nothing.stderr +++ b/tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.nothing.stderr @@ -306,7 +306,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:130:12 | LL | if x = let 0 = 0 {} - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -370,7 +372,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:161:19 | LL | if let true = let true = true {} - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -426,7 +430,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:184:12 | LL | if (|| let 0 = 0) {} - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -512,7 +518,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:221:15 | LL | while x = let 0 = 0 {} - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -576,7 +584,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:252:22 | LL | while let true = let true = true {} - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -632,7 +642,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:275:15 | LL | while (|| let 0 = 0) {} - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -648,7 +660,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:295:6 | LL | &let 0 = 0; - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -656,7 +670,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:298:6 | LL | !let 0 = 0; - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -664,7 +680,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:300:6 | LL | *let 0 = 0; - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -672,7 +690,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:302:6 | LL | -let 0 = 0; - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -680,7 +700,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:304:13 | LL | let _ = let _ = 3; - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -696,7 +718,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:315:13 | LL | true || let 0 = 0; - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -704,7 +728,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:317:14 | LL | (true || let 0 = 0); - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -712,7 +738,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:319:22 | LL | true && (true || let 0 = 0); - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -720,7 +748,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:323:9 | LL | x = let 0 = 0; - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -768,7 +798,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:337:17 | LL | (let true = let true = true); - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -776,7 +808,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:343:25 | LL | let x = true && let y = 1; - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -792,7 +826,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:354:6 | LL | &let 0 = 0 - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -800,7 +836,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:365:17 | LL | true && let 1 = 1 - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -808,7 +846,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:370:17 | LL | true && let 1 = 1 - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -816,7 +856,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:375:17 | LL | true && let 1 = 1 - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -824,7 +866,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:386:17 | LL | true && let 1 = 1 - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -960,7 +1004,9 @@ error: expected expression, found `let` statement --> $DIR/disallowed-positions.rs:439:22 | LL | let x = (true && let y = 1); - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions diff --git a/tests/ui/rfcs/rfc-2497-if-let-chains/ensure-that-let-else-does-not-interact-with-let-chains.stderr b/tests/ui/rfcs/rfc-2497-if-let-chains/ensure-that-let-else-does-not-interact-with-let-chains.stderr index 0442f1218b183..c03af5a9cd4f5 100644 --- a/tests/ui/rfcs/rfc-2497-if-let-chains/ensure-that-let-else-does-not-interact-with-let-chains.stderr +++ b/tests/ui/rfcs/rfc-2497-if-let-chains/ensure-that-let-else-does-not-interact-with-let-chains.stderr @@ -13,7 +13,9 @@ error: expected expression, found `let` statement --> $DIR/ensure-that-let-else-does-not-interact-with-let-chains.rs:15:26 | LL | let Some(n) = opt && let another = n else { - | ^^^ + | -- ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions diff --git a/tests/ui/rfcs/rfc-2497-if-let-chains/invalid-let-in-a-valid-let-context.stderr b/tests/ui/rfcs/rfc-2497-if-let-chains/invalid-let-in-a-valid-let-context.stderr index f3726166eba71..a170af2ddb4ce 100644 --- a/tests/ui/rfcs/rfc-2497-if-let-chains/invalid-let-in-a-valid-let-context.stderr +++ b/tests/ui/rfcs/rfc-2497-if-let-chains/invalid-let-in-a-valid-let-context.stderr @@ -2,7 +2,9 @@ error: expected expression, found `let` statement --> $DIR/invalid-let-in-a-valid-let-context.rs:8:19 | LL | let _ = &&let Some(x) = Some(42); - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -18,7 +20,9 @@ error: expected expression, found `let` statement --> $DIR/invalid-let-in-a-valid-let-context.rs:13:57 | LL | if let Some(elem) = _opt && [1, 2, 3][let _ = &&let Some(x) = Some(42)] = 1 { - | ^^^ + | -^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions @@ -66,7 +70,9 @@ error: expected expression, found `let` statement --> $DIR/invalid-let-in-a-valid-let-context.rs:42:21 | LL | let x = let y = 1; - | ^^^ + | - ^^^ + | | + | expected an expression after this | = note: only supported directly in conditions of `if` and `while` expressions From 79bcc9d8a8e90fa7372c8e38ba62e5f809095aa6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Tue, 27 Oct 2026 14:50:39 +0100 Subject: [PATCH 05/18] Remove GenericArgRef fixup cranelift --- compiler/rustc_borrowck/src/borrow_set.rs | 8 +- .../src/diagnostics/conflict_errors.rs | 4 +- .../src/diagnostics/mutability_errors.rs | 59 +++-- .../src/diagnostics/region_name.rs | 8 +- compiler/rustc_borrowck/src/lib.rs | 2 +- .../src/polonius/liveness_constraints.rs | 6 +- .../opaque_types/member_constraints.rs | 4 +- .../src/region_infer/opaque_types/mod.rs | 8 +- compiler/rustc_borrowck/src/renumber.rs | 4 +- compiler/rustc_borrowck/src/root_cx.rs | 2 +- .../src/type_check/constraint_conversion.rs | 2 +- .../src/type_check/liveness/mod.rs | 4 +- compiler/rustc_borrowck/src/type_check/mod.rs | 15 +- .../src/type_check/relate_tys.rs | 10 +- .../rustc_borrowck/src/universal_regions.rs | 32 +-- .../src/intrinsics/mod.rs | 4 +- .../src/intrinsics/simd.rs | 2 +- compiler/rustc_codegen_llvm/src/context.rs | 2 +- .../src/debuginfo/metadata/type_map.rs | 2 +- .../rustc_codegen_llvm/src/debuginfo/mod.rs | 6 +- compiler/rustc_codegen_llvm/src/intrinsic.rs | 4 +- .../src/back/symbol_export.rs | 35 ++- .../src/debuginfo/type_names.rs | 8 +- compiler/rustc_codegen_ssa/src/mono_item.rs | 2 +- .../src/check_consts/check.rs | 2 +- .../rustc_const_eval/src/check_consts/ops.rs | 10 +- .../src/const_eval/machine.rs | 8 +- .../src/const_eval/type_info.rs | 6 +- .../src/const_eval/type_info/adt.rs | 2 +- .../rustc_const_eval/src/interpret/call.rs | 8 +- .../src/interpret/eval_context.rs | 4 +- .../src/interpret/intrinsics.rs | 2 +- .../src/interpret/intrinsics/atomic.rs | 2 +- .../src/interpret/intrinsics/simd.rs | 2 +- .../rustc_const_eval/src/util/type_name.rs | 10 +- .../src/check/always_applicable.rs | 18 +- .../rustc_hir_analysis/src/check/check.rs | 21 +- .../src/check/compare_impl_item.rs | 2 +- .../rustc_hir_analysis/src/check/intrinsic.rs | 2 +- compiler/rustc_hir_analysis/src/check/mod.rs | 6 +- .../src/coherence/builtin.rs | 4 +- .../src/coherence/builtin/coerce_shared.rs | 16 +- compiler/rustc_hir_analysis/src/collect.rs | 6 +- .../src/collect/item_bounds.rs | 2 +- compiler/rustc_hir_analysis/src/delegation.rs | 67 +++--- .../src/hir_ty_lowering/errors.rs | 3 +- .../src/hir_ty_lowering/generics.rs | 4 +- .../src/hir_ty_lowering/mod.rs | 39 ++-- .../src/impl_wf_check/min_specialization.rs | 16 +- .../src/outlives/implicit_infer.rs | 10 +- .../src/variance/constraints.rs | 6 +- .../rustc_hir_analysis/src/variance/mod.rs | 10 +- compiler/rustc_hir_typeck/src/_match.rs | 2 +- compiler/rustc_hir_typeck/src/callee.rs | 6 +- compiler/rustc_hir_typeck/src/cast.rs | 2 +- compiler/rustc_hir_typeck/src/closure.rs | 8 +- compiler/rustc_hir_typeck/src/demand.rs | 2 +- compiler/rustc_hir_typeck/src/expr.rs | 32 +-- .../rustc_hir_typeck/src/expr_use_visitor.rs | 2 +- compiler/rustc_hir_typeck/src/fallback.rs | 2 +- .../rustc_hir_typeck/src/fn_ctxt/_impl.rs | 24 +-- .../src/fn_ctxt/adjust_fulfillment_errors.rs | 18 +- .../rustc_hir_typeck/src/fn_ctxt/checks.rs | 10 +- compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs | 4 +- .../src/fn_ctxt/suggestions.rs | 4 +- .../rustc_hir_typeck/src/method/confirm.rs | 16 +- compiler/rustc_hir_typeck/src/method/mod.rs | 4 +- compiler/rustc_hir_typeck/src/method/probe.rs | 8 +- .../rustc_hir_typeck/src/method/suggest.rs | 12 +- compiler/rustc_hir_typeck/src/pat.rs | 10 +- compiler/rustc_hir_typeck/src/upvar.rs | 2 +- .../src/infer/canonical/instantiate.rs | 4 +- compiler/rustc_infer/src/infer/context.rs | 2 +- compiler/rustc_infer/src/infer/mod.rs | 8 +- .../rustc_infer/src/infer/opaque_types/mod.rs | 2 +- .../src/infer/outlives/obligations.rs | 4 +- .../src/infer/outlives/test_type_match.rs | 6 +- .../src/infer/relate/generalize.rs | 6 +- .../rustc_infer/src/infer/relate/lattice.rs | 6 +- .../src/infer/relate/type_relating.rs | 6 +- compiler/rustc_lint/src/builtin.rs | 14 +- compiler/rustc_lint/src/context.rs | 10 +- .../rustc_lint/src/disallowed_pass_by_ref.rs | 2 +- .../src/for_loops_over_fallibles.rs | 2 +- compiler/rustc_lint/src/foreign_modules.rs | 2 +- .../rustc_lint/src/impl_trait_overcaptures.rs | 6 +- compiler/rustc_lint/src/internal.rs | 6 +- compiler/rustc_lint/src/reference_casting.rs | 2 +- compiler/rustc_lint/src/runtime_symbols.rs | 2 +- compiler/rustc_lint/src/types.rs | 8 +- .../rustc_lint/src/types/improper_ctypes.rs | 10 +- compiler/rustc_middle/src/infer/canonical.rs | 4 +- .../src/middle/exported_symbols.rs | 4 +- compiler/rustc_middle/src/mir/consts.rs | 6 +- compiler/rustc_middle/src/mir/mod.rs | 4 +- compiler/rustc_middle/src/mir/statement.rs | 8 +- compiler/rustc_middle/src/mir/syntax.rs | 10 +- compiler/rustc_middle/src/mir/visit.rs | 4 +- compiler/rustc_middle/src/mono.rs | 2 +- compiler/rustc_middle/src/queries.rs | 24 +-- compiler/rustc_middle/src/query/erase.rs | 2 + compiler/rustc_middle/src/query/keys.rs | 8 +- compiler/rustc_middle/src/thir.rs | 12 +- compiler/rustc_middle/src/traits/mod.rs | 4 +- compiler/rustc_middle/src/ty/adt.rs | 6 +- compiler/rustc_middle/src/ty/codec.rs | 4 +- compiler/rustc_middle/src/ty/consts/kind.rs | 15 +- compiler/rustc_middle/src/ty/context.rs | 40 ++-- .../src/ty/context/impl_interner.rs | 31 +-- compiler/rustc_middle/src/ty/generic_args.rs | 204 +++++++++++++----- compiler/rustc_middle/src/ty/generics.rs | 23 +- .../ty/inhabitedness/inhabited_predicate.rs | 4 +- .../rustc_middle/src/ty/inhabitedness/mod.rs | 4 +- compiler/rustc_middle/src/ty/instance.rs | 30 +-- compiler/rustc_middle/src/ty/layout.rs | 4 +- compiler/rustc_middle/src/ty/mod.rs | 14 +- .../src/ty/normalize_erasing_regions.rs | 6 +- compiler/rustc_middle/src/ty/opaque_types.rs | 4 +- compiler/rustc_middle/src/ty/print/mod.rs | 37 ++-- compiler/rustc_middle/src/ty/print/pretty.rs | 59 ++--- compiler/rustc_middle/src/ty/relate.rs | 8 +- .../src/ty/significant_drop_order.rs | 4 +- .../rustc_middle/src/ty/structural_impls.rs | 5 +- compiler/rustc_middle/src/ty/sty.rs | 66 +++--- .../rustc_middle/src/ty/typeck_results.rs | 14 +- compiler/rustc_middle/src/ty/typetree.rs | 2 +- compiler/rustc_middle/src/ty/util.rs | 8 +- .../src/builder/custom/parse/instruction.rs | 2 +- compiler/rustc_mir_build/src/builder/mod.rs | 6 +- compiler/rustc_mir_build/src/thir/cx/expr.rs | 20 +- .../src/thir/pattern/check_match.rs | 2 +- .../src/thir/pattern/const_to_pat.rs | 2 +- .../rustc_mir_build/src/thir/pattern/mod.rs | 2 +- .../rustc_mir_dataflow/src/value_analysis.rs | 2 +- .../src/check_alignment.rs | 8 +- .../src/check_call_recursion.rs | 19 +- .../rustc_mir_transform/src/check_null.rs | 8 +- .../rustc_mir_transform/src/coroutine/mod.rs | 4 +- .../src/dataflow_const_prop.rs | 2 +- .../rustc_mir_transform/src/elaborate_drop.rs | 18 +- .../src/function_item_references.rs | 10 +- compiler/rustc_mir_transform/src/gvn.rs | 4 +- compiler/rustc_mir_transform/src/inline.rs | 2 +- .../rustc_mir_transform/src/inline/cycle.rs | 4 +- .../rustc_mir_transform/src/instsimplify.rs | 8 +- compiler/rustc_mir_transform/src/liveness.rs | 2 +- .../src/post_analysis_normalize.rs | 2 +- .../src/remove_uninit_drops.rs | 8 +- compiler/rustc_mir_transform/src/shim.rs | 2 +- .../src/shim/async_destructor_ctor.rs | 2 +- compiler/rustc_mir_transform/src/validate.rs | 2 +- .../rustc_passes/src/canonical_symbols.rs | 4 +- compiler/rustc_pattern_analysis/src/rustc.rs | 4 +- .../src/unstable/convert/internal.rs | 2 +- .../src/unstable/internal_cx/helpers.rs | 6 +- .../src/unstable/internal_cx/mod.rs | 8 +- compiler/rustc_public/src/unstable/mod.rs | 2 +- .../rustc_public_bridge/src/context/impls.rs | 26 +-- .../src/cfi/typeid/itanium_cxx_abi/encode.rs | 8 +- .../cfi/typeid/itanium_cxx_abi/transform.rs | 4 +- compiler/rustc_symbol_mangling/src/export.rs | 2 +- compiler/rustc_symbol_mangling/src/legacy.rs | 14 +- compiler/rustc_symbol_mangling/src/v0.rs | 45 ++-- .../src/error_reporting/infer/mod.rs | 26 +-- .../error_reporting/infer/need_type_info.rs | 37 ++-- .../nice_region_error/placeholder_error.rs | 6 +- .../error_reporting/infer/note_and_explain.rs | 2 +- .../src/error_reporting/infer/suggest.rs | 4 +- .../src/error_reporting/traits/call_kind.rs | 6 +- .../traits/fulfillment_errors.rs | 6 +- .../src/error_reporting/traits/suggestions.rs | 15 +- .../rustc_trait_selection/src/opaque_types.rs | 4 +- .../src/solve/delegate.rs | 2 +- .../src/solve/inspect/analyse.rs | 2 +- .../src/traits/auto_trait.rs | 2 +- .../src/traits/coherence.rs | 2 +- .../src/traits/dyn_compatibility.rs | 4 +- .../src/traits/fulfill.rs | 4 +- .../rustc_trait_selection/src/traits/misc.rs | 2 +- .../rustc_trait_selection/src/traits/mod.rs | 10 +- .../src/traits/outlives_for_liveness.rs | 2 +- .../src/traits/project.rs | 8 +- .../src/traits/select/_match.rs | 6 +- .../src/traits/select/candidate_assembly.rs | 2 +- .../src/traits/select/confirmation.rs | 4 +- .../src/traits/select/mod.rs | 16 +- .../src/traits/specialize/mod.rs | 14 +- .../rustc_trait_selection/src/traits/wf.rs | 10 +- compiler/rustc_transmute/src/layout/tree.rs | 2 +- compiler/rustc_ty_utils/src/instance.rs | 6 +- compiler/rustc_ty_utils/src/layout.rs | 2 +- compiler/rustc_ty_utils/src/needs_drop.rs | 6 +- compiler/rustc_ty_utils/src/opaque_types.rs | 8 +- compiler/rustc_ty_walk/src/lib.rs | 6 +- compiler/rustc_type_ir/src/binder.rs | 22 +- compiler/rustc_type_ir/src/inherent.rs | 6 +- compiler/rustc_type_ir/src/interner.rs | 10 +- .../rustc_type_ir/src/region_constraint.rs | 3 +- compiler/rustc_type_ir/src/term_kind.rs | 12 +- compiler/rustc_type_ir/src/ty_kind.rs | 12 +- compiler/rustc_type_ir/src/ty_kind/closure.rs | 43 ++-- 201 files changed, 1127 insertions(+), 954 deletions(-) diff --git a/compiler/rustc_borrowck/src/borrow_set.rs b/compiler/rustc_borrowck/src/borrow_set.rs index 8161871e37cc8..3c5e939cd93b7 100644 --- a/compiler/rustc_borrowck/src/borrow_set.rs +++ b/compiler/rustc_borrowck/src/borrow_set.rs @@ -296,10 +296,10 @@ impl<'a, 'tcx> GatherBorrows<'a, 'tcx> { kind: mir::BorrowKind, location: Location, target_adt: ty::AdtDef<'tcx>, - target_args: &'tcx ty::List>, + target_args: ty::GenericArgs<'tcx>, target_place: mir::Place<'tcx>, source_adt: ty::AdtDef<'tcx>, - source_args: &'tcx ty::List>, + source_args: ty::GenericArgs<'tcx>, source_place: mir::Place<'tcx>, ) { let mut did_reborrow = false; @@ -384,10 +384,10 @@ impl<'a, 'tcx> GatherBorrows<'a, 'tcx> { kind, location, *target_field_adt, - target_field_args, + *target_field_args, target_field_place, *source_field_adt, - source_field_args, + *source_field_args, source_field_place, ); } diff --git a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs index fe10ab9fe2466..e759fd6618276 100644 --- a/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs @@ -1295,7 +1295,7 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> { // In practice unless there are more than one field with the same type, we'll be // suggesting a single field at a type, because we don't aggregate multiple borrow // checker errors involving the functional record update syntax into a single one. - let field_ty = field.ty(self.infcx.tcx, args).skip_norm_wip(); + let field_ty = field.ty(self.infcx.tcx, *args).skip_norm_wip(); let ident = field.ident(self.infcx.tcx); if field_ty == ty && fields.iter().all(|field| field.ident.name != ident.name) { // Suggest adding field and cloning it. @@ -1371,7 +1371,7 @@ impl<'diag, 'tcx> MirBorrowckCtxt<'_, 'diag, 'tcx> { && let Some(local_did) = def.did().as_local() && def.variants().iter().all(|variant| { variant.fields.iter().all(|field| { - self.implements_clone(field.ty(self.infcx.tcx, args).skip_norm_wip()) + self.implements_clone(field.ty(self.infcx.tcx, *args).skip_norm_wip()) }) }) { diff --git a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs index 1182cdb5c2c6e..30d6ecc017b42 100644 --- a/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs @@ -1225,7 +1225,7 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { err.span_label(closure_span, "in this closure"); let closure_arg_has_fn_trait_bound = - |callee_def_id, input_index, generic_args: ty::GenericArgsRef<'tcx>| { + |callee_def_id, input_index, generic_args: ty::GenericArgs<'tcx>| { let sig = tcx.fn_sig(callee_def_id).instantiate(tcx, generic_args).skip_binder(); let Some(input_ty): Option> = sig.inputs().get(input_index).copied() else { @@ -1247,40 +1247,39 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { // If the HIR node is a function or method call, get the DefId // of the callee function or method, the span, and argument info for the call expr. - let get_call_details = - || -> Option<(DefId, Span, usize, usize, ty::GenericArgsRef<'tcx>)> { - let hir::Node::Expr(hir::Expr { hir_id, kind, .. }) = node else { - return None; - }; + let get_call_details = || -> Option<(DefId, Span, usize, usize, ty::GenericArgs<'tcx>)> { + let hir::Node::Expr(hir::Expr { hir_id, kind, .. }) = node else { + return None; + }; - let typeck_results = tcx.typeck(def_id); + let typeck_results = tcx.typeck(def_id); - match kind { - hir::ExprKind::Call(expr, args) => { - if let Some(ty::FnDef(def_id, generic_args)) = - typeck_results.node_type_opt(expr.hir_id).as_ref().map(|ty| ty.kind()) - { - let arg_pos = args.iter().position(|arg| arg.hir_id == closure_id)?; - Some(( - *def_id, - expr.span, - arg_pos, - arg_pos, - generic_args.no_bound_vars().unwrap(), - )) - } else { - None - } - } - hir::ExprKind::MethodCall(_, _, args, span) => { + match kind { + hir::ExprKind::Call(expr, args) => { + if let Some(ty::FnDef(def_id, generic_args)) = + typeck_results.node_type_opt(expr.hir_id).as_ref().map(|ty| ty.kind()) + { let arg_pos = args.iter().position(|arg| arg.hir_id == closure_id)?; - let def_id = typeck_results.type_dependent_def_id(*hir_id)?; - let generic_args = typeck_results.node_args_opt(*hir_id)?; - Some((def_id, *span, arg_pos, arg_pos + 1, generic_args)) + Some(( + *def_id, + expr.span, + arg_pos, + arg_pos, + generic_args.no_bound_vars().unwrap(), + )) + } else { + None } - _ => None, } - }; + hir::ExprKind::MethodCall(_, _, args, span) => { + let arg_pos = args.iter().position(|arg| arg.hir_id == closure_id)?; + let def_id = typeck_results.type_dependent_def_id(*hir_id)?; + let generic_args = typeck_results.node_args_opt(*hir_id)?; + Some((def_id, *span, arg_pos, arg_pos + 1, generic_args)) + } + _ => None, + } + }; // If we can detect the expression to be a function or method call where the closure was // an argument, we point at the function or method definition argument... diff --git a/compiler/rustc_borrowck/src/diagnostics/region_name.rs b/compiler/rustc_borrowck/src/diagnostics/region_name.rs index 99203fe0ebf18..eb896526173b1 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_name.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_name.rs @@ -6,7 +6,7 @@ use rustc_errors::Diag; use rustc_hir as hir; use rustc_hir::def::{DefKind, Res}; use rustc_middle::ty::print::RegionHighlightMode; -use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, RegionVid, Ty, Unnormalized}; +use rustc_middle::ty::{self, GenericArgKind, GenericArgs, RegionVid, Ty, Unnormalized}; use rustc_span::{DUMMY_SP, Span, Symbol, bug, kw, span_bug, sym}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use tracing::{debug, instrument}; @@ -669,7 +669,7 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { _ => { if let Some(last_segment) = path.segments.last() && let Some(highlight) = self.match_adt_and_segment( - args, + *args, needle_fr, last_segment, search_stack, @@ -713,7 +713,7 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { /// types+hir to search through). fn match_adt_and_segment<'hir>( &self, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, needle_fr: RegionVid, last_segment: &'hir hir::PathSegment<'hir>, search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>, @@ -736,7 +736,7 @@ impl<'tcx> MirBorrowckCtxt<'_, '_, 'tcx> { /// `search_stack` the types+hir to search through. fn try_match_adt_and_generic_args<'hir>( &self, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, needle_fr: RegionVid, hir_args: &'hir hir::GenericArgs<'hir>, search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty<'hir>)>, diff --git a/compiler/rustc_borrowck/src/lib.rs b/compiler/rustc_borrowck/src/lib.rs index 7e1ba1fad72c4..d09f4a0a6d09f 100644 --- a/compiler/rustc_borrowck/src/lib.rs +++ b/compiler/rustc_borrowck/src/lib.rs @@ -154,7 +154,7 @@ struct PropagatedBorrowCheckResults<'tcx> { used_mut_upvars: SmallVec<[FieldIdx; 8]>, } -type DeferredClosureRequirements<'tcx> = Vec<(LocalDefId, ty::GenericArgsRef<'tcx>, Locations)>; +type DeferredClosureRequirements<'tcx> = Vec<(LocalDefId, ty::GenericArgs<'tcx>, Locations)>; /// After we borrow check a closure, we are left with various /// requirements that we have inferred between the free regions that diff --git a/compiler/rustc_borrowck/src/polonius/liveness_constraints.rs b/compiler/rustc_borrowck/src/polonius/liveness_constraints.rs index 4981fc5f6e421..ee24b60206ad9 100644 --- a/compiler/rustc_borrowck/src/polonius/liveness_constraints.rs +++ b/compiler/rustc_borrowck/src/polonius/liveness_constraints.rs @@ -92,9 +92,9 @@ impl<'tcx> TypeRelation> for VarianceExtractor<'_, 'tcx> { a_ty: Ty<'tcx>, _: Ty<'tcx>, def_id: DefId, - a_args: ty::GenericArgsRef<'tcx>, - b_args: ty::GenericArgsRef<'tcx>, - _: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>, + a_args: ty::GenericArgs<'tcx>, + b_args: ty::GenericArgs<'tcx>, + _: impl FnOnce(ty::GenericArgs<'tcx>) -> Ty<'tcx>, ) -> RelateResult<'tcx, Ty<'tcx>> { let variances = self.cx().variances_of(def_id); relate_args_with_variances(self, variances, a_args, b_args)?; diff --git a/compiler/rustc_borrowck/src/region_infer/opaque_types/member_constraints.rs b/compiler/rustc_borrowck/src/region_infer/opaque_types/member_constraints.rs index e79ba00610cc1..9a211c50316bc 100644 --- a/compiler/rustc_borrowck/src/region_infer/opaque_types/member_constraints.rs +++ b/compiler/rustc_borrowck/src/region_infer/opaque_types/member_constraints.rs @@ -1,7 +1,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir::def_id::DefId; use rustc_middle::ty::{ - self, Flags, GenericArgsRef, Region, RegionVid, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, + self, Flags, GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, }; use rustc_span::bug; @@ -147,7 +147,7 @@ impl<'tcx> CollectMemberConstraintsVisitor<'_, '_, 'tcx> { fn cx(&self) -> TyCtxt<'tcx> { self.rcx.infcx.tcx } - fn visit_closure_args(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) { + fn visit_closure_args(&mut self, def_id: DefId, args: GenericArgs<'tcx>) { let generics = self.cx().generics_of(def_id); for arg in args.iter().skip(generics.parent_count) { arg.visit_with(self); diff --git a/compiler/rustc_borrowck/src/region_infer/opaque_types/mod.rs b/compiler/rustc_borrowck/src/region_infer/opaque_types/mod.rs index 7892e6ed72f96..baeee36dffe44 100644 --- a/compiler/rustc_borrowck/src/region_infer/opaque_types/mod.rs +++ b/compiler/rustc_borrowck/src/region_infer/opaque_types/mod.rs @@ -11,8 +11,8 @@ use rustc_macros::extension; use rustc_middle::mir::{Body, ConstraintCategory}; use rustc_middle::ty::{ self, DefiningScopeKind, DefinitionSiteHiddenType, FallibleTypeFolder, Flags, GenericArg, - GenericArgsRef, OpaqueTypeKey, ProvisionalHiddenType, Region, RegionVid, Ty, TyCtxt, - TypeFoldable, TypeSuperFoldable, TypeVisitableExt, Unnormalized, fold_regions, + GenericArgs, OpaqueTypeKey, ProvisionalHiddenType, Region, RegionVid, Ty, TyCtxt, TypeFoldable, + TypeSuperFoldable, TypeVisitableExt, Unnormalized, fold_regions, }; use rustc_mir_dataflow::points::DenseLocationMap; use rustc_span::Span; @@ -439,8 +439,8 @@ impl<'a, 'tcx> ToArgRegionsFolder<'a, 'tcx> { fn fold_closure_args( &mut self, def_id: DefId, - args: GenericArgsRef<'tcx>, - ) -> Result, RegionVid> { + args: GenericArgs<'tcx>, + ) -> Result, RegionVid> { let generics = self.cx().generics_of(def_id); self.cx().mk_args_from_iter(args.iter().enumerate().map(|(index, arg)| { if index < generics.parent_count { diff --git a/compiler/rustc_borrowck/src/renumber.rs b/compiler/rustc_borrowck/src/renumber.rs index d6dbc7dd831fb..0f24b0d5a4a5d 100644 --- a/compiler/rustc_borrowck/src/renumber.rs +++ b/compiler/rustc_borrowck/src/renumber.rs @@ -2,7 +2,7 @@ use rustc_index::IndexSlice; use rustc_infer::infer::NllRegionVariableOrigin; use rustc_middle::mir::visit::{MutVisitor, TyContext}; use rustc_middle::mir::{Body, ConstOperand, Location, Promoted}; -use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, TypeFoldable, fold_regions}; +use rustc_middle::ty::{self, GenericArgs, Ty, TyCtxt, TypeFoldable, fold_regions}; use rustc_span::Symbol; use tracing::{debug, instrument}; @@ -90,7 +90,7 @@ impl<'a, 'tcx> MutVisitor<'tcx> for RegionRenumberer<'a, 'tcx> { } #[instrument(skip(self), level = "debug")] - fn visit_args(&mut self, args: &mut GenericArgsRef<'tcx>, location: Location) { + fn visit_args(&mut self, args: &mut GenericArgs<'tcx>, location: Location) { *args = self.renumber_regions(*args, || RegionCtxt::Location(location)); debug!(?args); diff --git a/compiler/rustc_borrowck/src/root_cx.rs b/compiler/rustc_borrowck/src/root_cx.rs index 1cd39f5089617..9e090700070ff 100644 --- a/compiler/rustc_borrowck/src/root_cx.rs +++ b/compiler/rustc_borrowck/src/root_cx.rs @@ -248,7 +248,7 @@ impl<'diag, 'tcx> BorrowCheckRootCtxt<'diag, 'tcx> { input: &mut CollectRegionConstraintsResult<'tcx>, closure_requirements: &Option>, closure_def_id: LocalDefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, locations: Locations, ) { if let Some(closure_requirements) = closure_requirements { diff --git a/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs b/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs index 9790cece59196..bb81acef05a1f 100644 --- a/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs +++ b/compiler/rustc_borrowck/src/type_check/constraint_conversion.rs @@ -86,7 +86,7 @@ impl<'a, 'tcx> ConstraintConversion<'a, 'tcx> { &mut self, closure_requirements: &ClosureRegionRequirements<'tcx>, closure_def_id: LocalDefId, - closure_args: ty::GenericArgsRef<'tcx>, + closure_args: ty::GenericArgs<'tcx>, ) { // Extract the values of the free regions in `closure_args` // into a vector. These are the regions that we will be diff --git a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs index 735fd68a2b1d2..b9d5e69760a61 100644 --- a/compiler/rustc_borrowck/src/type_check/liveness/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/liveness/mod.rs @@ -4,7 +4,7 @@ use rustc_index::interval::IntervalSet; use rustc_middle::mir::visit::{TyContext, Visitor}; use rustc_middle::mir::{Body, Local, Location, SourceInfo}; use rustc_middle::ty::relate::Relate; -use rustc_middle::ty::{GenericArgsRef, Region, RegionVid, Ty, TyCtxt, TypeVisitable}; +use rustc_middle::ty::{GenericArgs, Region, RegionVid, Ty, TyCtxt, TypeVisitable}; use rustc_mir_dataflow::move_paths::MoveData; use rustc_mir_dataflow::points::{DenseLocationMap, PointIndex}; use rustc_span::span_bug; @@ -220,7 +220,7 @@ struct LiveVariablesVisitor<'a, 'tcx> { impl<'a, 'tcx> Visitor<'tcx> for LiveVariablesVisitor<'a, 'tcx> { /// We sometimes have `args` within an rvalue, or within a /// call. Make them live at the location where they appear. - fn visit_args(&mut self, args: &GenericArgsRef<'tcx>, location: Location) { + fn visit_args(&mut self, args: &GenericArgs<'tcx>, location: Location) { self.record_regions_live_at(*args, location); self.super_args(args); } diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index 2a103ff70eb6c..900b417f8626f 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -25,7 +25,7 @@ use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::cast::CastTy; use rustc_middle::ty::{ - self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, GenericArgsRef, Ty, TyCtxt, + self, CanonicalUserTypeAnnotation, CanonicalUserTypeAnnotations, GenericArgs, Ty, TyCtxt, TypeVisitableExt, UserArgs, UserTypeAnnotationIndex, fold_regions, }; use rustc_mir_dataflow::move_paths::MoveData; @@ -2509,7 +2509,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { let src_ty = src_place.ty(self.body, tcx).ty; let ty::Adt(dst_adt, dst_args) = dst_ty.kind() else { bug!() }; - let [dst_arg, ..] = ***dst_args else { bug!() }; + let [dst_arg, ..] = *dst_args.as_slice() else { bug!() }; let ty::GenericArgKind::Lifetime(dst_region) = dst_arg.kind() else { bug!() }; constraints.liveness_constraints.add_location(dst_region.as_var(), location); @@ -2596,8 +2596,8 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { }; // These field types can still contain projections from the source or target type // and normalize them before handing them to `NllTypeRelating` - let dst_ty = self.normalize(dst_field.ty(tcx, dst_args), location.to_locations()); - let src_ty = self.normalize(src_field.ty(tcx, src_args), location.to_locations()); + let dst_ty = self.normalize(dst_field.ty(tcx, *dst_args), location.to_locations()); + let src_ty = self.normalize(src_field.ty(tcx, *src_args), location.to_locations()); if let ( ty::Ref(src_region, _, Mutability::Mut), @@ -2709,7 +2709,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { &mut self, tcx: TyCtxt<'tcx>, def_id: LocalDefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, location: Location, ) -> ty::InstantiatedClauses<'tcx> { let root_def_id = self.infcx.root_def_id; @@ -2728,16 +2728,15 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { // FIXME(async_closures): It may be useful to add a debug assert here // to actually call `type_of` and check the `parent_args` are the same // length as the `typeck_root_args`. - &args[..typeck_root_args.len()] + tcx.mk_args(&args.as_slice()[..typeck_root_args.len()]) } DefKind::AnonConst if tcx.anon_const_kind(def_id) == ty::AnonConstKind::NonTypeSystemInline => { - args.as_inline_const().parent_args() + tcx.mk_args(args.as_inline_const().parent_args()) } other => bug!("unexpected item {:?}", other), }; - let parent_args = tcx.mk_args(parent_args); assert_eq!(typeck_root_args.len(), parent_args.len()); if let Err(_) = self.eq_args( diff --git a/compiler/rustc_borrowck/src/type_check/relate_tys.rs b/compiler/rustc_borrowck/src/type_check/relate_tys.rs index bc4fc17a3a5d5..4b5ad21dac9e8 100644 --- a/compiler/rustc_borrowck/src/type_check/relate_tys.rs +++ b/compiler/rustc_borrowck/src/type_check/relate_tys.rs @@ -45,8 +45,8 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { /// Add sufficient constraints to ensure `a == b`. See also [Self::relate_types]. pub(super) fn eq_args( &mut self, - a: ty::GenericArgsRef<'tcx>, - b: ty::GenericArgsRef<'tcx>, + a: ty::GenericArgs<'tcx>, + b: ty::GenericArgs<'tcx>, locations: Locations, category: ConstraintCategory<'tcx>, ) -> Result<(), NoSolution> { @@ -338,9 +338,9 @@ impl<'b, 'tcx> TypeRelation> for NllTypeRelating<'_, 'b, 'tcx> { a_ty: Ty<'tcx>, b_ty: Ty<'tcx>, def_id: DefId, - a_args: ty::GenericArgsRef<'tcx>, - b_args: ty::GenericArgsRef<'tcx>, - _: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>, + a_args: ty::GenericArgs<'tcx>, + b_args: ty::GenericArgs<'tcx>, + _: impl FnOnce(ty::GenericArgs<'tcx>) -> Ty<'tcx>, ) -> RelateResult<'tcx, Ty<'tcx>> { if self.ambient_variance == ty::Invariant { // Avoid fetching the variance if we are in an invariant context, diff --git a/compiler/rustc_borrowck/src/universal_regions.rs b/compiler/rustc_borrowck/src/universal_regions.rs index 7a666726cecc3..6b43a6707a2df 100644 --- a/compiler/rustc_borrowck/src/universal_regions.rs +++ b/compiler/rustc_borrowck/src/universal_regions.rs @@ -26,8 +26,8 @@ use rustc_macros::extension; use rustc_middle::mir::RETURN_PLACE; use rustc_middle::ty::print::with_no_trimmed_paths; use rustc_middle::ty::{ - self, BoundVariableKind, GenericArgs, GenericArgsRef, InlineConstArgs, InlineConstArgsParts, - List, RegionVid, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, fold_regions, + self, BoundVariableKind, GenericArgs, InlineConstArgs, InlineConstArgsParts, List, RegionVid, + Ty, TyCtxt, TypeFoldable, TypeVisitableExt, fold_regions, }; use rustc_span::{ErrorGuaranteed, bug, kw, span_bug, sym}; use tracing::{debug, instrument}; @@ -99,32 +99,32 @@ pub(crate) struct UniversalRegions<'tcx> { pub(crate) enum DefiningTy<'tcx> { /// The MIR is a closure. The signature is found via /// `ClosureArgs::closure_sig_ty`. - Closure(DefId, GenericArgsRef<'tcx>), + Closure(DefId, GenericArgs<'tcx>), /// The MIR is a coroutine. The signature is that coroutines take /// no parameters and return the result of /// `ClosureArgs::coroutine_return_ty`. - Coroutine(DefId, GenericArgsRef<'tcx>), + Coroutine(DefId, GenericArgs<'tcx>), /// The MIR is a special kind of closure that returns coroutines. /// /// See the documentation on `CoroutineClosureSignature` for details /// on how to construct the callable signature of the coroutine from /// its args. - CoroutineClosure(DefId, GenericArgsRef<'tcx>), + CoroutineClosure(DefId, GenericArgs<'tcx>), /// The MIR is a fn item with the given `DefId` and args. The signature /// of the function can be bound then with the `fn_sig` query. - FnDef(DefId, GenericArgsRef<'tcx>), + FnDef(DefId, GenericArgs<'tcx>), /// The MIR represents some form of constant. The signature then /// is that it has no inputs and a single return value, which is /// the value of the constant. - Const(DefId, GenericArgsRef<'tcx>), + Const(DefId, GenericArgs<'tcx>), /// The MIR represents an inline const. The signature has no inputs and a /// single return value found via `InlineConstArgs::ty`. - InlineConst(DefId, GenericArgsRef<'tcx>), + InlineConst(DefId, GenericArgs<'tcx>), // Fake body for a global asm. Not particularly useful or interesting, // but we need it so we can properly store the typeck results of the asm @@ -179,7 +179,11 @@ impl<'tcx> DefiningTy<'tcx> { let ty = body.local_decls[RETURN_PLACE].ty; let typeck_root_def_id = tcx.typeck_root_def_id(body_def_id.to_def_id()); let parent_args = GenericArgs::identity_for_item(tcx, typeck_root_def_id); - let args = InlineConstArgs::new(tcx, InlineConstArgsParts { parent_args, ty }).args; + let args = InlineConstArgs::new( + tcx, + InlineConstArgsParts { parent_args: parent_args.as_slice(), ty }, + ) + .args; DefiningTy::InlineConst(body_def_id.to_def_id(), args) } @@ -424,7 +428,7 @@ impl<'tcx> DefiningTy<'tcx> { /// Returns the args of the `DefiningTy`. These are equivalent to the identity /// substs of the body, but replaced with region vids. - pub(crate) fn args(&self) -> ty::GenericArgsRef<'tcx> { + pub(crate) fn args(&self) -> ty::GenericArgs<'tcx> { match *self { DefiningTy::Closure(_, args) | DefiningTy::Coroutine(_, args) @@ -432,7 +436,7 @@ impl<'tcx> DefiningTy<'tcx> { | DefiningTy::FnDef(_, args) | DefiningTy::Const(_, args) | DefiningTy::InlineConst(_, args) => args, - DefiningTy::GlobalAsm(_) => ty::List::empty(), + DefiningTy::GlobalAsm(_) => ty::GenericArgs::empty(), } } } @@ -524,7 +528,7 @@ impl<'tcx> UniversalRegions<'tcx> { /// `V[1]: V[2]`. pub(crate) fn closure_mapping( tcx: TyCtxt<'tcx>, - closure_args: GenericArgsRef<'tcx>, + closure_args: GenericArgs<'tcx>, expected_num_vars: usize, closure_def_id: LocalDefId, ) -> IndexVec> { @@ -618,7 +622,7 @@ impl<'tcx> UniversalRegions<'tcx> { match self.defining_ty { DefiningTy::Closure(def_id, args) => { let v = with_no_trimmed_paths!( - args[tcx.generics_of(def_id).parent_count..] + args.as_slice()[tcx.generics_of(def_id).parent_count..] .iter() .map(|arg| arg.to_string()) .collect::>() @@ -643,7 +647,7 @@ impl<'tcx> UniversalRegions<'tcx> { } DefiningTy::Coroutine(def_id, args) => { let v = with_no_trimmed_paths!( - args[tcx.generics_of(def_id).parent_count..] + args.as_slice()[tcx.generics_of(def_id).parent_count..] .iter() .map(|arg| arg.to_string()) .collect::>() diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs index d0ea2e0ffb2c9..61e165ef272a5 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/mod.rs @@ -21,7 +21,7 @@ use cranelift_codegen::ir::{ AtomicRmwOp, BlockArg, ExceptionTableData, ExceptionTableItem, ExceptionTag, }; use rustc_middle::ty; -use rustc_middle::ty::GenericArgsRef; +use rustc_middle::ty::GenericArgs; use rustc_middle::ty::layout::{HasTypingEnv as _, ValidityRequirement}; use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths}; use rustc_span::{Spanned, Symbol, sym}; @@ -387,7 +387,7 @@ fn codegen_regular_intrinsic_call<'tcx>( fx: &mut FunctionCx<'_, '_, 'tcx>, instance: Instance<'tcx>, intrinsic: Symbol, - generic_args: GenericArgsRef<'tcx>, + generic_args: GenericArgs<'tcx>, args: &[Spanned>], ret: CPlace<'tcx>, destination: Option, diff --git a/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs b/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs index 270ea4e88a999..c773413f31074 100644 --- a/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs +++ b/compiler/rustc_codegen_cranelift/src/intrinsics/simd.rs @@ -21,7 +21,7 @@ fn report_simd_type_validation_error( pub(super) fn codegen_simd_intrinsic_call<'tcx>( fx: &mut FunctionCx<'_, '_, 'tcx>, intrinsic: Symbol, - generic_args: GenericArgsRef<'tcx>, + generic_args: GenericArgs<'tcx>, args: &[Spanned>], ret: CPlace<'tcx>, target: BasicBlock, diff --git a/compiler/rustc_codegen_llvm/src/context.rs b/compiler/rustc_codegen_llvm/src/context.rs index 8ef5ce26e1c2d..ead1c8670713c 100644 --- a/compiler/rustc_codegen_llvm/src/context.rs +++ b/compiler/rustc_codegen_llvm/src/context.rs @@ -1021,7 +1021,7 @@ impl<'ll, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'ll, 'tcx> { tcx, self.typing_env(), def_id, - ty::List::empty(), + ty::GenericArgs::empty(), DUMMY_SP, ), tcx.sess.pointer_authentication_functions(), diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs index 3687bc4e2faab..c9039bf46e416 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/metadata/type_map.rs @@ -314,7 +314,7 @@ pub(super) fn build_type_with_children<'ll, 'tcx>( // FIXME: indicate that this is an expanding recursive type in stub metadata? return DINodeCreationResult::new(stub_info.metadata, false); } else { - debug_context(cx).adt_stack.borrow_mut().push((def_id, args)); + debug_context(cx).adt_stack.borrow_mut().push((def_id, *args)); _adt_stack_pop_guard = Some(AdtStackPopGuard { cx }); } } diff --git a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs index eb923316cc649..337d477bc74ea 100644 --- a/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs +++ b/compiler/rustc_codegen_llvm/src/debuginfo/mod.rs @@ -15,7 +15,7 @@ use rustc_codegen_ssa::traits::*; use rustc_data_structures::unord::UnordMap; use rustc_hir::def_id::{DefId, DefIdMap}; use rustc_middle::ty::layout::{HasTypingEnv, LayoutOf}; -use rustc_middle::ty::{self, GenericArgsRef, Instance, Ty, TypeVisitableExt, Unnormalized}; +use rustc_middle::ty::{self, GenericArgs, Instance, Ty, TypeVisitableExt, Unnormalized}; use rustc_session::Session; use rustc_session::config::{self, DebugInfo}; use rustc_span::{ @@ -55,7 +55,7 @@ pub(crate) struct CodegenUnitDebugContext<'ll, 'tcx> { created_files: RefCell, &'ll DIFile>>, type_map: metadata::TypeMap<'ll, 'tcx>, - adt_stack: RefCell)>>, + adt_stack: RefCell)>>, namespace_map: RefCell>, recursion_marker_type: OnceCell<&'ll DIType>, } @@ -287,7 +287,7 @@ impl<'ll, 'tcx> DebugInfoBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> { fn get_template_parameters<'ll, 'tcx>( cx: &CodegenCx<'ll, 'tcx>, generics: &ty::Generics, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> &'ll DIArray { if args.terms().next().is_none() { return create_DIArray(DIB(cx), &[]); diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 212e2886fe019..081a9a87fd324 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -22,7 +22,7 @@ use rustc_middle::mir::interpret::{AllocId, Allocation, ErrorHandled, GlobalAllo use rustc_middle::mir::{self, BinOp}; use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, LayoutOf}; use rustc_middle::ty::offload_meta::OffloadMetadata; -use rustc_middle::ty::{self, GenericArgsRef, Instance, SimdAlign, Ty, TyCtxt}; +use rustc_middle::ty::{self, GenericArgs, Instance, SimdAlign, Ty, TyCtxt}; use rustc_session::diagnostics::feature_err; use rustc_span::{ErrorGuaranteed, Span, Symbol, bug, span_bug, sym}; use rustc_structures::CrateType; @@ -2032,7 +2032,7 @@ fn get_args_from_tuple<'ll, 'tcx>( fn generic_simd_intrinsic<'ll, 'tcx>( bx: &mut Builder<'_, 'll, 'tcx>, name: Symbol, - fn_args: GenericArgsRef<'tcx>, + fn_args: GenericArgs<'tcx>, args: &[OperandRef<'tcx, &'ll Value>], ret_ty: Ty<'tcx>, llret_ty: &'ll Type, diff --git a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs index d4a040d3a44df..e2acf1fdcf69b 100644 --- a/compiler/rustc_codegen_ssa/src/back/symbol_export.rs +++ b/compiler/rustc_codegen_ssa/src/back/symbol_export.rs @@ -15,7 +15,7 @@ use rustc_middle::middle::exported_symbols::{ }; use rustc_middle::query::LocalCrate; use rustc_middle::ty::{ - self, GenericArgKind, GenericArgsRef, Instance, ShimKind, SymbolName, Ty, TyCtxt, + self, GenericArgKind, GenericArgs, Instance, ShimKind, SymbolName, Ty, TyCtxt, }; use rustc_middle::util::Providers; use rustc_span::{Span, bug}; @@ -359,16 +359,15 @@ fn exported_generic_symbols_provider_local<'tcx>( is_local }; - let is_instantiable_downstream = - |did: Option, generic_args: GenericArgsRef<'tcx>| { - generic_args - .types() - .chain(did.into_iter().map(move |did| tcx.type_of(did).skip_binder())) - .all(move |arg| { - arg.walk() - .all(|ty| ty.as_type().is_none_or(|ty| !is_local_to_current_crate(ty))) - }) - }; + let is_instantiable_downstream = |did: Option, generic_args: GenericArgs<'tcx>| { + generic_args + .types() + .chain(did.into_iter().map(move |did| tcx.type_of(did).skip_binder())) + .all(move |arg| { + arg.walk() + .all(|ty| ty.as_type().is_none_or(|ty| !is_local_to_current_crate(ty))) + }) + }; let is_offload_instance = |mono_item: &MonoItem<'tcx>| { if let MonoItem::Fn(instance) = mono_item { @@ -413,7 +412,7 @@ fn exported_generic_symbols_provider_local<'tcx>( let should_export = if item_is_offload { has_generics } else { - has_generics && is_instantiable_downstream(Some(def), &args) + has_generics && is_instantiable_downstream(Some(def), args) }; if should_export { @@ -442,8 +441,8 @@ fn exported_generic_symbols_provider_local<'tcx>( // Drop glue did is always going to be non-local outside of libcore, thus we don't need to check it's locality (which includes invoking `type_of` query). let should_export = match ty.kind() { - ty::Adt(_, args) => is_instantiable_downstream(None, args), - ty::Closure(_, args) => is_instantiable_downstream(None, args), + ty::Adt(_, args) => is_instantiable_downstream(None, *args), + ty::Closure(_, args) => is_instantiable_downstream(None, *args), _ => true, }; @@ -505,7 +504,7 @@ fn exported_generic_symbols_provider_local<'tcx>( fn upstream_monomorphizations_provider( tcx: TyCtxt<'_>, (): (), -) -> DefIdMap, CrateNum>> { +) -> DefIdMap, CrateNum>> { let cnums = tcx.crates(()); let mut instances: DefIdMap> = Default::default(); @@ -570,14 +569,14 @@ fn upstream_monomorphizations_provider( fn upstream_monomorphizations_for_provider( tcx: TyCtxt<'_>, def_id: DefId, -) -> Option<&UnordMap, CrateNum>> { +) -> Option<&UnordMap, CrateNum>> { assert!(!def_id.is_local()); tcx.upstream_monomorphizations(()).get(&def_id) } fn upstream_drop_glue_for_provider<'tcx>( tcx: TyCtxt<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Option { let def_id = tcx.lang_items().drop_glue_fn()?; tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned() @@ -585,7 +584,7 @@ fn upstream_drop_glue_for_provider<'tcx>( fn upstream_async_drop_glue_for_provider<'tcx>( tcx: TyCtxt<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Option { let def_id = tcx.lang_items().async_drop_in_place_fn()?; tcx.upstream_monomorphizations_for(def_id)?.get(&args).cloned() diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index 810253956b186..1034a0f417120 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -22,7 +22,7 @@ use rustc_hir::definitions::{DefPathData, DefPathDataName, DisambiguatedDefPathD use rustc_hir::{CoroutineDesugaring, CoroutineKind, CoroutineSource, Mutability}; use rustc_middle::ty::layout::{IntegerExt, TyAndLayout}; use rustc_middle::ty::{ - self, ExistentialProjection, GenericArgKind, GenericArgsRef, Ty, TyCtxt, Unnormalized, + self, ExistentialProjection, GenericArgKind, GenericArgs, Ty, TyCtxt, Unnormalized, }; use rustc_span::bug; use smallvec::SmallVec; @@ -647,7 +647,7 @@ fn push_unqualified_item_name( }; } -pub fn push_generic_args<'tcx>(tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>, output: &mut String) { +pub fn push_generic_args<'tcx>(tcx: TyCtxt<'tcx>, args: GenericArgs<'tcx>, output: &mut String) { let _prof = tcx.prof.generic_activity("compute_debuginfo_type_name"); let mut visited = FxHashSet::default(); push_generic_args_internal(tcx, args, output, &mut visited); @@ -655,7 +655,7 @@ pub fn push_generic_args<'tcx>(tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>, ou fn push_generic_args_internal<'tcx>( tcx: TyCtxt<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, output: &mut String, visited: &mut FxHashSet>, ) -> bool { @@ -749,7 +749,7 @@ fn push_debuginfo_const_name<'tcx>(tcx: TyCtxt<'tcx>, ct: ty::Const<'tcx>, outpu fn push_closure_or_coroutine_name<'tcx>( tcx: TyCtxt<'tcx>, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, qualified: bool, output: &mut String, visited: &mut FxHashSet>, diff --git a/compiler/rustc_codegen_ssa/src/mono_item.rs b/compiler/rustc_codegen_ssa/src/mono_item.rs index 5150b8da8ff4d..59440530e84f7 100644 --- a/compiler/rustc_codegen_ssa/src/mono_item.rs +++ b/compiler/rustc_codegen_ssa/src/mono_item.rs @@ -89,7 +89,7 @@ impl<'a, 'tcx: 'a> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> { fn to_raw_string(&self) -> String { match *self { MonoItem::Fn(instance) => { - format!("Fn({:?}, {})", instance.def, instance.args.as_ptr().addr()) + format!("Fn({:?}, {})", instance.def, instance.args.as_slice().as_ptr().addr()) } MonoItem::Static(id) => format!("Static({id:?})"), MonoItem::GlobalAsm(id) => format!("GlobalAsm({id:?})"), diff --git a/compiler/rustc_const_eval/src/check_consts/check.rs b/compiler/rustc_const_eval/src/check_consts/check.rs index 192bb8556a75d..11f1b2a7a8210 100644 --- a/compiler/rustc_const_eval/src/check_consts/check.rs +++ b/compiler/rustc_const_eval/src/check_consts/check.rs @@ -339,7 +339,7 @@ impl<'mir, 'tcx> Checker<'mir, 'tcx> { fn revalidate_conditional_constness( &mut self, callee: DefId, - callee_args: ty::GenericArgsRef<'tcx>, + callee_args: ty::GenericArgs<'tcx>, call_span: Span, ) -> Option { let tcx = self.tcx; diff --git a/compiler/rustc_const_eval/src/check_consts/ops.rs b/compiler/rustc_const_eval/src/check_consts/ops.rs index ace12201abf02..3a1c083fa835f 100644 --- a/compiler/rustc_const_eval/src/check_consts/ops.rs +++ b/compiler/rustc_const_eval/src/check_consts/ops.rs @@ -11,8 +11,8 @@ use rustc_infer::traits::{ImplSource, Obligation, ObligationCause}; use rustc_middle::mir::CallSource; use rustc_middle::ty::print::{PrintTraitRefExt as _, with_no_trimmed_paths}; use rustc_middle::ty::{ - self, AssocContainer, Closure, FnDef, FnPtr, GenericArgKind, GenericArgsRef, Param, TraitRef, - Ty, suggest_constraining_type_param, + self, AssocContainer, Closure, FnDef, FnPtr, GenericArgKind, GenericArgs, Param, TraitRef, Ty, + suggest_constraining_type_param, }; use rustc_session::diagnostics::add_feature_diagnostics; use rustc_span::{BytePos, Pos, Span, Symbol, span_bug, sym}; @@ -100,7 +100,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallCVariadic { #[derive(Debug)] pub(crate) struct ConditionallyConstCall<'tcx> { pub callee: DefId, - pub args: GenericArgsRef<'tcx>, + pub args: GenericArgs<'tcx>, pub span: Span, pub call_source: CallSource, } @@ -140,7 +140,7 @@ impl<'tcx> NonConstOp<'tcx> for ConditionallyConstCall<'tcx> { #[derive(Debug, Clone, Copy)] pub(crate) struct FnCallNonConst<'tcx> { pub callee: DefId, - pub args: GenericArgsRef<'tcx>, + pub args: GenericArgs<'tcx>, pub span: Span, pub call_source: CallSource, } @@ -218,7 +218,7 @@ impl<'tcx> NonConstOp<'tcx> for FnCallNonConst<'tcx> { fn build_error_for_const_call<'tcx>( ccx: &ConstCx<'_, 'tcx>, callee: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, span: Span, call_source: CallSource, non_or_conditionally: &'static str, diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index cb9432f9832e5..39831f28118b0 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -821,7 +821,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { let (ty, variant, field) = if let ty::Adt(def, args) = frt_ty.kind() && let Some(FieldInfo { base, variant_idx, field_idx, .. }) = - def.field_representing_type_info(ecx.tcx.tcx, args) + def.field_representing_type_info(ecx.tcx.tcx, *args) { (base, variant_idx, field_idx) } else { @@ -841,7 +841,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { let field_name = if let ty::Adt(def, args) = frt_ty.kind() && let Some(FieldInfo { name, .. }) = - def.field_representing_type_info(ecx.tcx.tcx, args) + def.field_representing_type_info(ecx.tcx.tcx, *args) { name } else { @@ -862,7 +862,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { let (ty, variant, field) = if let ty::Adt(def, args) = frt_ty.kind() && let Some(FieldInfo { base, variant_idx, field_idx, .. }) = - def.field_representing_type_info(ecx.tcx.tcx, args) + def.field_representing_type_info(ecx.tcx.tcx, *args) { (base, variant_idx, field_idx) } else { @@ -882,7 +882,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { let field_ty = if let ty::Adt(def, args) = frt_ty.kind() && let Some(FieldInfo { ty, .. }) = - def.field_representing_type_info(ecx.tcx.tcx, args) + def.field_representing_type_info(ecx.tcx.tcx, *args) { ecx.tcx.erase_and_anonymize_regions(ty) } else { diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index 0df2e9b5fd0ae..fc32787fa8703 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -233,7 +233,7 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { place: &impl Writeable<'tcx, CtfeProvenance>, ty: Ty<'tcx>, ) -> InterpResult<'tcx> { - let generics: ty::Binder<'_, ty::GenericArgsRef<'_>> = match *ty.kind() { + let generics: ty::Binder<'_, ty::GenericArgs<'_>> = match *ty.kind() { ty::Bool | ty::Char | ty::Int(..) @@ -256,10 +256,10 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { | ty::Placeholder(..) | ty::Infer(..) | ty::Error(..) - | ty::Slice(..) => ty::Binder::dummy(ty::GenericArgsRef::default()), + | ty::Slice(..) => ty::Binder::dummy(ty::GenericArgs::default()), ty::Adt(_, args) => ty::Binder::dummy(args), ty::FnDef(_, binder) => binder, - ty::UnsafeBinder(binder) => binder.rebind(ty::GenericArgsRef::default()), + ty::UnsafeBinder(binder) => binder.rebind(ty::GenericArgs::default()), ty::Closure(_, args) => ty::Binder::dummy(args), ty::CoroutineClosure(_, args) => ty::Binder::dummy(args), ty::Coroutine(_, args) => ty::Binder::dummy(args), diff --git a/compiler/rustc_const_eval/src/const_eval/type_info/adt.rs b/compiler/rustc_const_eval/src/const_eval/type_info/adt.rs index 4ff1b37e953d4..ec24dda8b46d3 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info/adt.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info/adt.rs @@ -36,7 +36,7 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { pub(super) fn write_generics( &mut self, place: &impl Writeable<'tcx, CtfeProvenance>, - generics: &'tcx GenericArgs<'tcx>, + generics: GenericArgs<'tcx>, ) -> InterpResult<'tcx> { self.allocate_fill_and_write_slice_ptr(place, generics.len() as u64, |this, i, place| { match generics[i as usize].kind() { diff --git a/compiler/rustc_const_eval/src/interpret/call.rs b/compiler/rustc_const_eval/src/interpret/call.rs index 27239ce58a9ea..9943dd524c896 100644 --- a/compiler/rustc_const_eval/src/interpret/call.rs +++ b/compiler/rustc_const_eval/src/interpret/call.rs @@ -176,7 +176,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { let all_fields_1zst = |variant: &VariantDef| -> InterpResult<'tcx, _> { for field in &variant.fields { - let ty = field.ty(*self.tcx, args).skip_norm_wip(); + let ty = field.ty(*self.tcx, *args).skip_norm_wip(); let layout = self.layout_of(ty)?; if !layout.is_1zst() { return interp_ok(false); @@ -202,7 +202,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { return interp_ok(layout); } let inner = - relevant_variant.fields[FieldIdx::from_u32(0)].ty(*self.tcx, args).skip_norm_wip(); + relevant_variant.fields[FieldIdx::from_u32(0)].ty(*self.tcx, *args).skip_norm_wip(); let inner = self.layout_of(inner)?; // Check if the inner type is one of the NPO-guaranteed ones. @@ -283,8 +283,8 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { let normalized_field_ty = |field: &FieldDef, args| { self.tcx.normalize_erasing_regions(self.typing_env, field.ty(*self.tcx, args)) }; - let caller_ty = normalized_field_ty(caller_field, caller_args); - let callee_ty = normalized_field_ty(callee_field, callee_args); + let caller_ty = normalized_field_ty(caller_field, *caller_args); + let callee_ty = normalized_field_ty(callee_field, *callee_args); self.identical_c_types(caller_ty, callee_ty) }) } diff --git a/compiler/rustc_const_eval/src/interpret/eval_context.rs b/compiler/rustc_const_eval/src/interpret/eval_context.rs index 4307019c6cf27..a3cac4525d988 100644 --- a/compiler/rustc_const_eval/src/interpret/eval_context.rs +++ b/compiler/rustc_const_eval/src/interpret/eval_context.rs @@ -14,7 +14,7 @@ use rustc_middle::ty::layout::{ LayoutOfHelpers, TyAndLayout, }; use rustc_middle::ty::{ - self, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, TypingEnv, Variance, + self, GenericArgs, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, TypingEnv, Variance, }; use rustc_span::{Span, span_bug}; use rustc_structures::Limit; @@ -360,7 +360,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { pub(super) fn resolve( &self, def: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> InterpResult<'tcx, ty::Instance<'tcx>> { let _trace = enter_trace_span!(M, resolve::try_resolve, def = ?def); trace!("resolve: {:?}, {:#?}", def, args); diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index 5ad977168a835..a86a00d260105 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -1323,7 +1323,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { }; for (i, field) in adt.non_enum_variant().fields.iter().enumerate() { - if field.ty(*self.tcx, substs).skip_norm_wip().is_raw_ptr() { + if field.ty(*self.tcx, *substs).skip_norm_wip().is_raw_ptr() { return self.project_field(&va_list_inner, FieldIdx::from_usize(i)); } } diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics/atomic.rs b/compiler/rustc_const_eval/src/interpret/intrinsics/atomic.rs index 30fbbcca8f6da..d5c19dff867e0 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics/atomic.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics/atomic.rs @@ -14,7 +14,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { pub fn eval_atomic_intrinsic( &mut self, intrinsic_name: Symbol, - generic_args: ty::GenericArgsRef<'tcx>, + generic_args: ty::GenericArgs<'tcx>, args: &[OpTy<'tcx, M::Provenance>], dest: &PlaceTy<'tcx, M::Provenance>, ret: Option, diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs b/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs index a31d1ec4e920d..3a743ce71f637 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs @@ -21,7 +21,7 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { pub fn eval_simd_intrinsic( &mut self, intrinsic_name: Symbol, - generic_args: ty::GenericArgsRef<'tcx>, + generic_args: ty::GenericArgs<'tcx>, args: &[OpTy<'tcx, M::Provenance>], dest: &PlaceTy<'tcx, M::Provenance>, ret: Option, diff --git a/compiler/rustc_const_eval/src/util/type_name.rs b/compiler/rustc_const_eval/src/util/type_name.rs index d0cd1f57479c0..ec56b053144c4 100644 --- a/compiler/rustc_const_eval/src/util/type_name.rs +++ b/compiler/rustc_const_eval/src/util/type_name.rs @@ -4,7 +4,7 @@ use rustc_data_structures::intern::Interned; use rustc_hir::def_id::{CrateNum, DefId}; use rustc_hir::definitions::DisambiguatedDefPathData; use rustc_middle::ty::print::{PrettyPrinter, PrintError, Printer}; -use rustc_middle::ty::{self, GenericArg, Ty, TyCtxt}; +use rustc_middle::ty::{self, Ty, TyCtxt}; use rustc_span::bug; struct TypeNamePrinter<'tcx> { @@ -61,7 +61,7 @@ impl<'tcx> Printer<'tcx> for TypeNamePrinter<'tcx> { | ty::Closure(def_id, args) | ty::CoroutineClosure(def_id, args) | ty::Coroutine(def_id, args) => self.print_def_path(def_id, args), - ty::Foreign(def_id) => self.print_def_path(def_id, &[]), + ty::Foreign(def_id) => self.print_def_path(def_id, ty::GenericArgs::empty()), ty::FnDef(def_id, args) => self.print_def_path(def_id, args.no_bound_vars().unwrap()), ty::Alias(_, ty::AliasTy { kind: ty::Free { .. }, .. }) => { @@ -132,11 +132,11 @@ impl<'tcx> Printer<'tcx> for TypeNamePrinter<'tcx> { fn print_path_with_generic_args( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - args: &[GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { print_prefix(self)?; if !args.is_empty() { - self.generic_delimiters(|cx| cx.comma_sep(args.iter().copied())) + self.generic_delimiters(|cx| cx.comma_sep(args.iter())) } else { Ok(()) } @@ -145,7 +145,7 @@ impl<'tcx> Printer<'tcx> for TypeNamePrinter<'tcx> { fn print_coroutine_with_kind( &mut self, def_id: DefId, - parent_args: &'tcx [GenericArg<'tcx>], + parent_args: ty::GenericArgs<'tcx>, kind: Ty<'tcx>, ) -> Result<(), PrintError> { self.print_def_path(def_id, parent_args)?; diff --git a/compiler/rustc_hir_analysis/src/check/always_applicable.rs b/compiler/rustc_hir_analysis/src/check/always_applicable.rs index a7e02cee4ea75..a7c44176e5fae 100644 --- a/compiler/rustc_hir_analysis/src/check/always_applicable.rs +++ b/compiler/rustc_hir_analysis/src/check/always_applicable.rs @@ -11,7 +11,7 @@ use rustc_errors::{ErrorGuaranteed, struct_span_code_err}; use rustc_infer::infer::{RegionResolutionError, TyCtxtInferExt}; use rustc_infer::traits::{ObligationCause, ObligationCauseCode}; use rustc_middle::ty::util::CheckRegions; -use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, TypingMode}; +use rustc_middle::ty::{self, GenericArgs, Ty, TyCtxt, TypeVisitableExt, TypingMode}; use rustc_span::{span_bug, sym}; use rustc_trait_selection::regions::InferCtxtRegionExt; use rustc_trait_selection::traits::{self, ObligationCtxt}; @@ -59,7 +59,7 @@ pub(crate) fn check_drop_impl( tcx, drop_impl_did, adt_def.did(), - adt_to_impl_args, + *adt_to_impl_args, )?; ensure_all_fields_are_const_destruct(tcx, drop_impl_did, adt_def.did())?; @@ -68,7 +68,7 @@ pub(crate) fn check_drop_impl( tcx, drop_impl_did, adt_def.did(), - adt_to_impl_args, + *adt_to_impl_args, )?; check_drop_xor_pin_drop(tcx, adt_def.did(), drop_impl_did)?; @@ -107,14 +107,14 @@ pub(crate) fn check_negative_auto_trait_impl<'tcx>( tcx, impl_def_id, adt_def.did(), - adt_to_impl_args, + *adt_to_impl_args, )?; ensure_impl_predicates_are_implied_by_item_defn( tcx, impl_def_id, adt_def.did(), - adt_to_impl_args, + *adt_to_impl_args, ) } _ => { @@ -138,9 +138,11 @@ fn ensure_impl_params_and_item_params_correspond<'tcx>( tcx: TyCtxt<'tcx>, impl_def_id: LocalDefId, adt_def_id: DefId, - adt_to_impl_args: GenericArgsRef<'tcx>, + adt_to_impl_args: ty::GenericArgs<'tcx>, ) -> Result<(), ErrorGuaranteed> { - let Err(arg) = tcx.uses_unique_generic_params(adt_to_impl_args, CheckRegions::OnlyParam) else { + let Err(arg) = + tcx.uses_unique_generic_params(adt_to_impl_args.as_slice(), CheckRegions::OnlyParam) + else { return Ok(()); }; @@ -252,7 +254,7 @@ fn ensure_impl_predicates_are_implied_by_item_defn<'tcx>( tcx: TyCtxt<'tcx>, impl_def_id: LocalDefId, adt_def_id: DefId, - adt_to_impl_args: GenericArgsRef<'tcx>, + adt_to_impl_args: GenericArgs<'tcx>, ) -> Result<(), ErrorGuaranteed> { let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis()); let ocx = ObligationCtxt::new_with_diagnostics(&infcx); diff --git a/compiler/rustc_hir_analysis/src/check/check.rs b/compiler/rustc_hir_analysis/src/check/check.rs index 4f753f02ed9fd..f3ed94c25114f 100644 --- a/compiler/rustc_hir_analysis/src/check/check.rs +++ b/compiler/rustc_hir_analysis/src/check/check.rs @@ -263,7 +263,7 @@ fn check_opaque_for_cycles<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, ) -> Result<(), ErrorGuaranteed> { - let args = GenericArgs::identity_for_item(tcx, def_id); + let args = ty::GenericArgs::identity_for_item(tcx, def_id); // First, try to look at any opaque expansion cycles, considering coroutine fields // (even though these aren't necessarily true errors). @@ -321,7 +321,7 @@ fn check_opaque_meets_bounds<'tcx>( let args = match origin { hir::OpaqueTyOrigin::FnReturn { parent, .. } | hir::OpaqueTyOrigin::AsyncFn { parent, .. } - | hir::OpaqueTyOrigin::TyAlias { parent, .. } => GenericArgs::identity_for_item( + | hir::OpaqueTyOrigin::TyAlias { parent, .. } => ty::GenericArgs::identity_for_item( tcx, parent, ) .extend_to(tcx, def_id.to_def_id(), |param, _| { @@ -732,7 +732,7 @@ fn check_opaque_precise_captures<'tcx>(tcx: TyCtxt<'tcx>, opaque_def_id: LocalDe fn is_enum_of_nonnullable_ptr<'tcx>( tcx: TyCtxt<'tcx>, adt_def: AdtDef<'tcx>, - args: GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> bool { if adt_def.repr().inhibit_enum_layout_opt() { return false; @@ -873,7 +873,7 @@ pub(crate) fn check_item_type(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), for &assoc_item in assoc_items.in_definition_order() { match assoc_item.kind { ty::AssocKind::Type { .. } if assoc_item.defaultness(tcx).has_value() => { - let trait_args = GenericArgs::identity_for_item(tcx, def_id); + let trait_args = ty::GenericArgs::identity_for_item(tcx, def_id); let _: Result<_, rustc_errors::ErrorGuaranteed> = check_type_bounds( tcx, assoc_item, @@ -1491,7 +1491,7 @@ fn check_simd(tcx: TyCtxt<'_>, sp: Span, def_id: LocalDefId) { } let array_field = &fields[FieldIdx::ZERO]; - let array_ty = array_field.ty(tcx, args).skip_norm_wip(); + let array_ty = array_field.ty(tcx, *args).skip_norm_wip(); let ty::Array(element_ty, len_const) = array_ty.kind() else { struct_span_code_err!( tcx.dcx(), @@ -1598,7 +1598,7 @@ fn check_scalable_vector(tcx: TyCtxt<'_>, span: Span, def_id: LocalDefId, scalab match scalable { ScalableElt::ElementCount(..) => { - let element_ty = &fields[FieldIdx::ZERO].ty(tcx, args).skip_norm_wip(); + let element_ty = &fields[FieldIdx::ZERO].ty(tcx, *args).skip_norm_wip(); // Check that `element_ty` only uses types valid in the lanes of a scalable vector // register: scalar types which directly match a "machine" type - integers, floats and @@ -1620,7 +1620,7 @@ fn check_scalable_vector(tcx: TyCtxt<'_>, span: Span, def_id: LocalDefId, scalab ScalableElt::Container => { let mut prev_field_ty = None; for field in fields.iter() { - let element_ty = field.ty(tcx, args).skip_norm_wip(); + let element_ty = field.ty(tcx, *args).skip_norm_wip(); if let ty::Adt(def, _) = element_ty.kind() && def.repr().scalable() { @@ -1761,7 +1761,7 @@ fn check_packed_inner( stack.push(def_id); for field in &def.non_enum_variant().fields { - if let ty::Adt(def, _) = field.ty(tcx, args).skip_norm_wip().kind() + if let ty::Adt(def, _) = field.ty(tcx, *args).skip_norm_wip().kind() && !stack.contains(&def.did()) && let Some(mut defs) = check_packed_inner(tcx, def.did(), stack) { @@ -1850,7 +1850,7 @@ fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) { return ControlFlow::Break(NonTrivialReason::ReprC { ty }); } def.all_fields() - .map(|field| field.ty(tcx, args).skip_norm_wip()) + .map(|field| field.ty(tcx, *args).skip_norm_wip()) .try_for_each(|t| is_trivial(tcx, typing_env, t)) } _ => ControlFlow::Continue(()), @@ -1861,7 +1861,8 @@ fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>) { .fields .iter() .filter_map(|field| { - let ty = field.ty(tcx, GenericArgs::identity_for_item(tcx, field.did)).skip_norm_wip(); + let ty = + field.ty(tcx, ty::GenericArgs::identity_for_item(tcx, field.did)).skip_norm_wip(); let layout = tcx.layout_of(typing_env.as_query_input(ty)); // We are currently checking the type this field came from, so it must be local let span = tcx.hir_span_if_local(field.did).unwrap(); diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs index 8a7ad70f8ebb1..c757c80280efa 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item.rs @@ -795,7 +795,7 @@ pub(super) fn collect_return_position_impl_trait_in_trait_tys<'tcx>( struct ImplTraitInTraitCollector<'a, 'tcx, E> { ocx: &'a ObligationCtxt<'a, 'tcx, E>, - types: FxIndexMap, ty::GenericArgsRef<'tcx>)>, + types: FxIndexMap, ty::GenericArgs<'tcx>)>, span: Span, param_env: ty::ParamEnv<'tcx>, impl_m_id: LocalDefId, diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index 0aa3e97568729..85b666372074a 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -301,7 +301,7 @@ pub(crate) fn check_intrinsic_type( sym::type_id_function_ptr => { let fn_ptr = tcx.require_lang_item(LangItem::FnPtr, span); let fn_ptr_adt_ref = tcx.adt_def(fn_ptr); - let fn_ptr_ty = Ty::new_adt(tcx, fn_ptr_adt_ref, ty::List::empty()); + let fn_ptr_ty = Ty::new_adt(tcx, fn_ptr_adt_ref, ty::GenericArgs::empty()); let option = tcx.require_lang_item(LangItem::Option, span); let option_adt_ref = tcx.adt_def(option); diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index 0a57a177be985..bf0d64d78d395 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -88,9 +88,7 @@ use rustc_middle::middle::stability::EvalResult; use rustc_middle::query::Providers; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::print::with_types_for_signature; -use rustc_middle::ty::{ - self, GenericArgs, GenericArgsRef, OutlivesClause, Region, Ty, TyCtxt, TypingMode, -}; +use rustc_middle::ty::{self, GenericArgs, OutlivesClause, Region, Ty, TyCtxt, TypingMode}; use rustc_session::diagnostics::feature_err; use rustc_span::def_id::CRATE_DEF_ID; use rustc_span::{BytePos, DUMMY_SP, Ident, Span, Symbol, bug, kw, span_bug}; @@ -585,7 +583,7 @@ fn suggestion_signature<'tcx>( assoc: ty::AssocItem, impl_trait_ref: ty::TraitRef<'tcx>, ) -> String { - let args = ty::GenericArgs::identity_for_item(tcx, assoc.def_id).rebase_onto( + let args = GenericArgs::identity_for_item(tcx, assoc.def_id).rebase_onto( tcx, assoc.container_id(tcx), impl_trait_ref.with_replaced_self_ty(tcx, tcx.types.self_param).args, diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin.rs b/compiler/rustc_hir_analysis/src/coherence/builtin.rs index e7f20766bc8eb..341880ec7ec0b 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin.rs @@ -496,7 +496,7 @@ pub(crate) fn reborrow_info<'tcx>( } }; - let lifetimes_count = generic_lifetime_params_count(args); + let lifetimes_count = generic_lifetime_params_count(args.as_slice()); let data_fields = collect_reborrow_data_fields(tcx, def, args); if lifetimes_count != 1 { @@ -576,7 +576,7 @@ struct ReborrowDataField<'tcx> { fn collect_reborrow_data_fields<'tcx>( tcx: TyCtxt<'tcx>, def: ty::AdtDef<'tcx>, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Vec> { def.non_enum_variant() .fields diff --git a/compiler/rustc_hir_analysis/src/coherence/builtin/coerce_shared.rs b/compiler/rustc_hir_analysis/src/coherence/builtin/coerce_shared.rs index 4d685ec3c6810..46bd5086a9dc8 100644 --- a/compiler/rustc_hir_analysis/src/coherence/builtin/coerce_shared.rs +++ b/compiler/rustc_hir_analysis/src/coherence/builtin/coerce_shared.rs @@ -341,7 +341,7 @@ enum CoerceSharedFieldPairError<'tcx> { MissingSourceField { target: ReborrowDataField<'tcx> }, } -fn single_region_arg<'tcx>(args: ty::GenericArgsRef<'tcx>) -> Option> { +fn single_region_arg<'tcx>(args: ty::GenericArgs<'tcx>) -> Option> { let mut lifetimes = args.iter().filter_map(|arg| arg.as_region()); let lifetime = lifetimes.next()?; lifetimes.next().is_none().then_some(lifetime) @@ -353,9 +353,9 @@ fn single_region_arg<'tcx>(args: ty::GenericArgsRef<'tcx>) -> Option( tcx: TyCtxt<'tcx>, source_def: ty::AdtDef<'tcx>, - source_args: ty::GenericArgsRef<'tcx>, + source_args: ty::GenericArgs<'tcx>, target_def: ty::AdtDef<'tcx>, - target_args: ty::GenericArgsRef<'tcx>, + target_args: ty::GenericArgs<'tcx>, ) -> Result, CoerceSharedFieldPairError<'tcx>> { let source_variant = source_def.non_enum_variant(); let target_variant = target_def.non_enum_variant(); @@ -424,9 +424,9 @@ fn validate_coerce_shared_fields<'tcx>( span: Span, diagnostic_context: CoerceSharedDiagnosticContext, source_def: ty::AdtDef<'tcx>, - source_args: ty::GenericArgsRef<'tcx>, + source_args: ty::GenericArgs<'tcx>, target_def: ty::AdtDef<'tcx>, - target_args: ty::GenericArgsRef<'tcx>, + target_args: ty::GenericArgs<'tcx>, ) -> Result<(), ErrorGuaranteed> { let tcx = infcx.tcx; let fields = match collect_coerce_shared_field_pairs( @@ -509,9 +509,9 @@ fn validate_coerce_shared_fields_are_memcpy_compatible<'tcx>( span: Span, diagnostic_context: CoerceSharedDiagnosticContext, source_def: ty::AdtDef<'tcx>, - source_args: ty::GenericArgsRef<'tcx>, + source_args: ty::GenericArgs<'tcx>, target_def: ty::AdtDef<'tcx>, - target_args: ty::GenericArgsRef<'tcx>, + target_args: ty::GenericArgs<'tcx>, ) -> Result<(), ErrorGuaranteed> { let tcx = infcx.tcx; let source_non_zst_fields = @@ -578,7 +578,7 @@ fn non_zst_reborrow_data_fields<'tcx>( infcx: &InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, def: ty::AdtDef<'tcx>, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Vec> { let tcx = infcx.tcx; collect_reborrow_data_fields(tcx, def, args) diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 0a42a2e94a551..43065f8203f59 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -630,7 +630,7 @@ impl<'tcx> HirTyLowerer<'tcx> for ItemCtxt<'tcx> { item_def_id: DefId, item_segment: &rustc_hir::PathSegment<'_>, poly_trait_ref: ty::PolyTraitRef<'tcx>, - ) -> Result<(DefId, ty::GenericArgsRef<'tcx>), ErrorGuaranteed> { + ) -> Result<(DefId, ty::GenericArgs<'tcx>), ErrorGuaranteed> { if let Some(trait_ref) = poly_trait_ref.no_bound_vars() { let item_args = self.lowerer().lower_generic_args_of_assoc_item( span, @@ -1449,7 +1449,7 @@ pub fn suggest_impl_trait<'tcx>( ) -> Option { let format_as_assoc: fn(_, _, _, _, _) -> _ = |tcx: TyCtxt<'tcx>, - _: ty::GenericArgsRef<'tcx>, + _: ty::GenericArgs<'tcx>, trait_def_id: DefId, assoc_item_def_id: DefId, item_ty: Ty<'tcx>| { @@ -1459,7 +1459,7 @@ pub fn suggest_impl_trait<'tcx>( }; let format_as_parenthesized: fn(_, _, _, _, _) -> _ = |tcx: TyCtxt<'tcx>, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, trait_def_id: DefId, _: DefId, item_ty: Ty<'tcx>| { diff --git a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs index 99a710f207c4e..5ed5745310f16 100644 --- a/compiler/rustc_hir_analysis/src/collect/item_bounds.rs +++ b/compiler/rustc_hir_analysis/src/collect/item_bounds.rs @@ -153,7 +153,7 @@ fn remap_gat_vars_and_recurse_into_nested_projections<'tcx>( { // We have found the GAT in question... // Return the vars, since we may need to remap them. - break &alias_ty.args[item_trait_ref.args.len()..]; + break tcx.mk_args(&alias_ty.args.as_slice()[item_trait_ref.args.len()..]); } else { // Only collect *self* type bounds if the filter is for self. match filter { diff --git a/compiler/rustc_hir_analysis/src/delegation.rs b/compiler/rustc_hir_analysis/src/delegation.rs index 56aa2334d939a..b736376167198 100644 --- a/compiler/rustc_hir_analysis/src/delegation.rs +++ b/compiler/rustc_hir_analysis/src/delegation.rs @@ -408,19 +408,21 @@ fn create_generic_args<'tcx>( tcx: TyCtxt<'tcx>, sig_id: DefId, def_id: LocalDefId, - mut parent_args: &[ty::GenericArg<'tcx>], - mut child_args: &[ty::GenericArg<'tcx>], -) -> (Vec>, &'tcx [ty::GenericArg<'tcx>]) { + mut parent_args: ty::GenericArgs<'tcx>, + mut child_args: ty::GenericArgs<'tcx>, +) -> (Vec>, ty::GenericArgs<'tcx>) { let delegation_generics = tcx.generics_of(def_id); let delegation_args = ty::GenericArgs::identity_for_item(tcx, def_id); let real_args_count = delegation_args.len() - delegation_generics.own_synthetic_params_count(); - let synth_args = &delegation_args[real_args_count..]; + let synth_args = &delegation_args.as_slice()[real_args_count..]; - let mut delegation_parent_args = - &delegation_args[delegation_generics.has_self as usize..delegation_generics.parent_count]; + let mut delegation_parent_args = tcx.mk_args( + &delegation_args.as_slice() + [delegation_generics.has_self as usize..delegation_generics.parent_count], + ); - let delegation_args = &delegation_args[delegation_generics.parent_count..]; + let delegation_args = &delegation_args.as_slice()[delegation_generics.parent_count..]; let kinds @ (_, parent_kind) = fn_kinds(tcx, def_id, sig_id); if matches!(kinds, (FnKind::AssocTraitImpl, FnKind::AssocTrait)) { @@ -432,10 +434,11 @@ fn create_generic_args<'tcx>( parent_args = tcx.impl_trait_header(parent).trait_ref.instantiate_identity().skip_norm_wip().args; - child_args = - &delegation_args[delegation_args.len() - delegation_generics.own_params.len()..]; + child_args = tcx.mk_args( + &delegation_args[delegation_args.len() - delegation_generics.own_params.len()..], + ); - delegation_parent_args = &[]; + delegation_parent_args = ty::GenericArgs::empty(); } let self_type = get_delegation_self_ty(tcx, def_id).map(ty::GenericArg::from); @@ -445,7 +448,7 @@ fn create_generic_args<'tcx>( FnKind::AssocInherentImpl => parent_args, // Remove `Self` from parent args (it is always at the `0th` index) as it is // added manually. - FnKind::AssocTrait => &parent_args[1..], + FnKind::AssocTrait => tcx.mk_args(&parent_args.as_slice()[1..]), _ => unreachable!("if parent args are non-empty then the parent must exist"), } } @@ -467,14 +470,14 @@ fn create_generic_args<'tcx>( let after_lifetimes_self = after_lifetimes_self.as_ref().into_iter(); let args = zero_self - .chain(delegation_parent_args) + .copied() + .chain(delegation_parent_args.iter()) .chain(parent_args.iter().filter(|a| a.as_region().is_some())) .chain(child_args.iter().filter(|a| a.as_region().is_some())) - .chain(after_lifetimes_self) + .chain(after_lifetimes_self.copied()) .chain(parent_args.iter().filter(|a| a.as_region().is_none())) .chain(child_args.iter().filter(|a| a.as_region().is_none())) - .chain(synth_args) - .copied() + .chain(synth_args.iter().copied()) .collect::>(); (args, delegation_parent_args) @@ -640,8 +643,8 @@ fn create_folder_and_args<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, sig_id: DefId, - parent_args: &'tcx [ty::GenericArg<'tcx>], - child_args: &'tcx [ty::GenericArg<'tcx>], + parent_args: ty::GenericArgs<'tcx>, + child_args: ty::GenericArgs<'tcx>, ) -> (ParamIndexRemapper<'tcx>, Vec>) { let (args, delegation_parent_args) = create_generic_args(tcx, sig_id, def_id, parent_args, child_args); @@ -737,7 +740,7 @@ fn adjust_sig_in_inherent_impl_cases<'tcx>( tcx: TyCtxt<'tcx>, sig_id: DefId, def_id: LocalDefId, - parent_args: &[ty::GenericArg<'tcx>], + parent_args: ty::GenericArgs<'tcx>, sig: &mut [Ty<'tcx>], ) { if !tcx.is_method(sig_id) { @@ -754,7 +757,7 @@ fn adjust_sig_in_inherent_impl_cases<'tcx>( }; for i in 0..sig.len() { - let to_replace = Ty::new_adt(tcx, *def, tcx.mk_args(parent_args)); + let to_replace = Ty::new_adt(tcx, *def, parent_args); let replacement = match def_kind { FnKind::Free => unreachable!(), @@ -789,7 +792,7 @@ fn adjust_sig_in_inherent_impl_cases<'tcx>( pub(crate) fn delegation_user_specified_args<'tcx>( tcx: TyCtxt<'tcx>, def_id: LocalDefId, -) -> (&'tcx [ty::GenericArg<'tcx>], &'tcx [ty::GenericArg<'tcx>]) { +) -> (ty::GenericArgs<'tcx>, ty::GenericArgs<'tcx>) { let info = tcx.hir_delegation_info(def_id); let get_segment = |hir_id| -> Option<(&'tcx PathSegment<'tcx>, DefId)> { @@ -812,10 +815,12 @@ pub(crate) fn delegation_user_specified_args<'tcx>( let self_ty = (tcx.def_kind(def_id) == DefKind::Trait) .then(|| Ty::new_param(tcx, 0, kw::SelfUpper)); - lowerer - .lower_generic_args_of_path(segment.ident.span, def_id, &[], segment, self_ty) - .0 - .as_slice() + tcx.mk_args( + lowerer + .lower_generic_args_of_path(segment.ident.span, def_id, &[], segment, self_ty) + .0 + .as_slice(), + ) }); let child_args = info.child_seg_id_for_sig.and_then(get_segment).map(|(segment, def_id)| { @@ -824,19 +829,25 @@ pub(crate) fn delegation_user_specified_args<'tcx>( let parent_args = if matches!(tcx.def_kind(parent), DefKind::Impl { of_trait: false } | DefKind::Trait) { - ty::GenericArgs::identity_for_item(tcx, parent).as_slice() + ty::GenericArgs::identity_for_item(tcx, parent) } else if let Some(parent_args) = parent_args { parent_args } else { - &[] + ty::GenericArgs::empty() }; let args = lowerer - .lower_generic_args_of_path(segment.ident.span, def_id, parent_args, segment, None) + .lower_generic_args_of_path( + segment.ident.span, + def_id, + parent_args.as_slice(), + segment, + None, + ) .0; let synth_params_count = tcx.generics_of(def_id).own_synthetic_params_count(); - &args[parent_args.len()..args.len() - synth_params_count] + tcx.mk_args(&args.as_slice()[parent_args.len()..args.len() - synth_params_count]) }); (parent_args.unwrap_or_default(), child_args.unwrap_or_default()) diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs index e1e84f8079bac..83f924b9e374c 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/errors.rs @@ -265,7 +265,8 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { return self.dcx().emit_err(err); } - let trait_args = &ty::GenericArgs::identity_for_item(tcx, best_trait)[1..]; + let trait_args = ty::GenericArgs::identity_for_item(tcx, best_trait); + let trait_args = &trait_args.as_slice()[1..]; let mut trait_ref = trait_name.clone(); let applicability = if let [arg, args @ ..] = trait_args { use std::fmt::Write; diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs index e7bb779b233de..1147425d138ab 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/generics.rs @@ -9,7 +9,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::{self as hir, GenericArg}; use rustc_lint_defs::builtin::LATE_BOUND_LIFETIME_ARGUMENTS; use rustc_middle::ty::{ - self, GenericArgsRef, GenericParamDef, GenericParamDefKind, IsSuggestable, Ty, + self, GenericArgs, GenericParamDef, GenericParamDefKind, IsSuggestable, Ty, }; use rustc_span::kw; use rustc_trait_selection::traits; @@ -195,7 +195,7 @@ pub fn lower_generic_args<'tcx: 'a, 'a>( self_ty: Option>, arg_count: &GenericArgCountResult, ctx: &mut impl GenericArgsLowerer<'a, 'tcx>, -) -> GenericArgsRef<'tcx> { +) -> GenericArgs<'tcx> { let tcx = cx.tcx(); // Collect the segments of the path; we need to instantiate arguments // for parameters throughout the entire path (wherever there are diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index 65db947b4cf50..e2803fb990256 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -43,9 +43,9 @@ use rustc_lint_defs::builtin::AMBIGUOUS_ASSOCIATED_ITEMS; use rustc_macros::{TypeFoldable, TypeVisitable}; use rustc_middle::middle::stability::AllowUnstable; use rustc_middle::ty::{ - self, Const, FnSigKind, GenericArgKind, GenericArgsRef, GenericParamDefKind, LitToConstInput, - Ty, TyCtxt, TypeSuperFoldable, TypeVisitableExt, TypingMode, Unnormalized, Upcast, - const_lit_matches_ty, fold_regions, + self, Const, FnSigKind, GenericArgKind, GenericParamDefKind, LitToConstInput, Ty, TyCtxt, + TypeSuperFoldable, TypeVisitableExt, TypingMode, Unnormalized, Upcast, const_lit_matches_ty, + fold_regions, }; use rustc_session::diagnostics::feature_err; use rustc_span::def_id::{LocalModId, ModId}; @@ -207,7 +207,7 @@ pub trait HirTyLowerer<'tcx> { item_def_id: DefId, item_segment: &hir::PathSegment<'_>, poly_trait_ref: ty::PolyTraitRef<'tcx>, - ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed>; + ) -> Result<(DefId, ty::GenericArgs<'tcx>), ErrorGuaranteed>; fn lower_fn_sig( &self, @@ -309,7 +309,7 @@ pub enum PermitVariants { enum TypeRelativePath<'tcx> { AssocItem(ty::AliasTerm<'tcx>), Variant { adt: Ty<'tcx>, variant_did: DefId }, - Ctor { ctor_def_id: DefId, args: GenericArgsRef<'tcx> }, + Ctor { ctor_def_id: DefId, args: ty::GenericArgs<'tcx> }, } /// New-typed boolean indicating whether explicit late-bound lifetimes @@ -632,7 +632,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { span: Span, def_id: DefId, item_segment: &hir::PathSegment<'_>, - ) -> GenericArgsRef<'tcx> { + ) -> ty::GenericArgs<'tcx> { let (args, _) = self.lower_generic_args_of_path(span, def_id, &[], item_segment, None); if let Some(c) = item_segment.args().constraints.first() { prohibit_assoc_item_constraint(self, c, Some((def_id, item_segment, span))); @@ -659,7 +659,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// 2. The path in question is the path to the trait `std::ops::Index`, /// which will have been resolved to a `def_id` /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type - /// parameters are returned in the `GenericArgsRef` + /// parameters are returned in the `GenericArgs` /// 4. Associated item constraints like `Output = u32` are contained in `generic_args.constraints`. /// /// Note that the type listing given here is *exactly* what the user provided. @@ -672,7 +672,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { /// /// We have the parent args are the args for the parent trait: /// `[Vec, u8]` and `generic_args` are the arguments for the associated - /// type itself: `['a]`. The returned `GenericArgsRef` concatenates these two + /// type itself: `['a]`. The returned `GenericArgs` concatenates these two /// lists: `[Vec, u8, 'a]`. #[instrument(level = "debug", skip(self, span), ret)] pub(crate) fn lower_generic_args_of_path( @@ -682,7 +682,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { parent_args: &[ty::GenericArg<'tcx>], segment: &hir::PathSegment<'_>, self_ty: Option>, - ) -> (GenericArgsRef<'tcx>, GenericArgCountResult) { + ) -> (ty::GenericArgs<'tcx>, GenericArgCountResult) { // If the type is parameterized by this region, then replace this // region with the current anon region binding (in other words, // whatever & would get replaced with). @@ -903,10 +903,15 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { span: Span, item_def_id: DefId, item_segment: &hir::PathSegment<'_>, - parent_args: GenericArgsRef<'tcx>, - ) -> GenericArgsRef<'tcx> { - let (args, _) = - self.lower_generic_args_of_path(span, item_def_id, parent_args, item_segment, None); + parent_args: ty::GenericArgs<'tcx>, + ) -> ty::GenericArgs<'tcx> { + let (args, _) = self.lower_generic_args_of_path( + span, + item_def_id, + parent_args.as_slice(), + item_segment, + None, + ); if let Some(c) = item_segment.args().constraints.first() { prohibit_assoc_item_constraint(self, c, Some((item_def_id, item_segment, span))); } @@ -1022,7 +1027,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { let constraints = segment.args().constraints; - if transient && (!generic_args[1..].is_empty() || !constraints.is_empty()) { + if transient && (!generic_args.as_slice()[1..].is_empty() || !constraints.is_empty()) { // Since the bound won't be present in the middle::ty IR as established above, any // arguments or constraints won't be checked for well-formedness in later passes. // @@ -1544,7 +1549,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { }, ); let ty::Adt(_, enum_args) = self_ty.kind() else { unreachable!() }; - return Ok(TypeRelativePath::Ctor { ctor_def_id, args: enum_args }); + return Ok(TypeRelativePath::Ctor { ctor_def_id, args: *enum_args }); } if let PermitVariants::Yes = mode.permit_variants() { tcx.check_stability(variant_def.def_id, Some(qpath_hir_id), span, None); @@ -1965,7 +1970,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { trait_segment: Option<&hir::PathSegment<'_>>, item_segment: &hir::PathSegment<'_>, assoc_tag: ty::AssocTag, - ) -> Result<(DefId, GenericArgsRef<'tcx>), ErrorGuaranteed> { + ) -> Result<(DefId, ty::GenericArgs<'tcx>), ErrorGuaranteed> { let tcx = self.tcx(); let trait_def_id = tcx.parent(item_def_id); @@ -3857,7 +3862,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { &self, ctor_def_id: DefId, ctor_of: CtorOf, - args: GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Const<'tcx> { let tcx = self.tcx(); let parent_did = tcx.parent(ctor_def_id); diff --git a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs index fdc6357bb9bbe..d5084e41d6e4f 100644 --- a/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs +++ b/compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs @@ -71,9 +71,7 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::specialization_graph::Node; use rustc_infer::traits::{ObligationCause, TraitErrors}; use rustc_middle::ty::trait_def::TraitSpecializationKind; -use rustc_middle::ty::{ - self, GenericArg, GenericArgs, GenericArgsRef, TyCtxt, TypeVisitableExt, TypingMode, -}; +use rustc_middle::ty::{self, GenericArg, GenericArgs, TyCtxt, TypeVisitableExt, TypingMode}; use rustc_span::{ErrorGuaranteed, Span}; use rustc_trait_selection::error_reporting::InferCtxtErrorExt; use rustc_trait_selection::traits::{self, ObligationCtxt, translate_args_with_cause, wf}; @@ -125,7 +123,7 @@ fn check_always_applicable( debug!(?impl2_def_id, ?impl2_args); let parent_args = if impl2_node.is_from_trait() { - impl2_args.to_vec() + impl2_args.as_slice().to_vec() } else { unconstrained_parent_impl_args(tcx, impl2_def_id, impl2_args) }; @@ -167,7 +165,7 @@ fn get_impl_args( tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node: Node, -) -> Result<(GenericArgsRef<'_>, GenericArgsRef<'_>), ErrorGuaranteed> { +) -> Result<(GenericArgs<'_>, GenericArgs<'_>), ErrorGuaranteed> { let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis()); let ocx = ObligationCtxt::new_with_diagnostics(infcx); let param_env = tcx.param_env(impl1_def_id); @@ -210,7 +208,7 @@ fn get_impl_args( fn unconstrained_parent_impl_args<'tcx>( tcx: TyCtxt<'tcx>, impl_def_id: DefId, - impl_args: GenericArgsRef<'tcx>, + impl_args: GenericArgs<'tcx>, ) -> Vec> { let impl_generic_clauses = tcx.clauses_of(impl_def_id); let mut unconstrained_parameters = FxHashSet::default(); @@ -270,7 +268,7 @@ fn unconstrained_parent_impl_args<'tcx>( /// `[Vec]`. This means we allow this impl. fn check_duplicate_params<'tcx>( tcx: TyCtxt<'tcx>, - impl1_args: GenericArgsRef<'tcx>, + impl1_args: GenericArgs<'tcx>, parent_args: Vec>, span: Span, ) -> Result<(), ErrorGuaranteed> { @@ -319,9 +317,9 @@ fn check_static_lifetimes<'tcx>( fn check_predicates<'tcx>( tcx: TyCtxt<'tcx>, impl1_def_id: LocalDefId, - impl1_args: GenericArgsRef<'tcx>, + impl1_args: GenericArgs<'tcx>, impl2_node: Node, - impl2_args: GenericArgsRef<'tcx>, + impl2_args: GenericArgs<'tcx>, span: Span, ) -> Result<(), ErrorGuaranteed> { let impl1_clauses: Vec<(ty::Clause<'_>, _)> = traits::elaborate( diff --git a/compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs b/compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs index ca7e246a9e05b..766b65215258a 100644 --- a/compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs +++ b/compiler/rustc_hir_analysis/src/outlives/implicit_infer.rs @@ -147,7 +147,7 @@ fn insert_required_clauses_to_be_wf<'tcx>( check_explicit_clauses( tcx, def.did(), - args, + args.as_slice(), required_clauses, explicit_map, IgnoreClausesReferencingSelf::No, @@ -168,7 +168,7 @@ fn insert_required_clauses_to_be_wf<'tcx>( check_explicit_clauses( tcx, def_id, - args, + args.as_slice(), required_clauses, explicit_map, IgnoreClausesReferencingSelf::No, @@ -196,7 +196,7 @@ fn insert_required_clauses_to_be_wf<'tcx>( check_explicit_clauses( tcx, trait_ref.def_id(), - args, + args.as_slice(), required_clauses, explicit_map, IgnoreClausesReferencingSelf::Yes, @@ -212,7 +212,7 @@ fn insert_required_clauses_to_be_wf<'tcx>( check_explicit_clauses( tcx, tcx.parent(def_id), - args, + args.as_slice(), required_clauses, explicit_map, IgnoreClausesReferencingSelf::No, @@ -301,7 +301,7 @@ enum IgnoreClausesReferencingSelf { fn check_inferred_clauses<'tcx>( tcx: TyCtxt<'tcx>, def_id: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, global_inferred_outlives: &FxIndexMap>>, required_clauses: &mut RequiredClauses<'tcx>, ) { diff --git a/compiler/rustc_hir_analysis/src/variance/constraints.rs b/compiler/rustc_hir_analysis/src/variance/constraints.rs index cfab2ed340910..114b7a5cf453d 100644 --- a/compiler/rustc_hir_analysis/src/variance/constraints.rs +++ b/compiler/rustc_hir_analysis/src/variance/constraints.rs @@ -6,7 +6,7 @@ use hir::def_id::{DefId, LocalDefId}; use rustc_hir as hir; use rustc_hir::def::DefKind; -use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, Ty, TyCtxt}; +use rustc_middle::ty::{self, GenericArgKind, GenericArgs, Ty, TyCtxt}; use rustc_span::{bug, span_bug}; use tracing::{debug, instrument}; @@ -182,7 +182,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { fn add_constraints_from_invariant_args( &mut self, current: &CurrentItem, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, variance: VarianceTermPtr<'a>, ) { // Trait are always invariant so we can take advantage of that. @@ -350,7 +350,7 @@ impl<'a, 'tcx> ConstraintContext<'a, 'tcx> { &mut self, current: &CurrentItem, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, variance: VarianceTermPtr<'a>, ) { debug!( diff --git a/compiler/rustc_hir_analysis/src/variance/mod.rs b/compiler/rustc_hir_analysis/src/variance/mod.rs index dd5b602241d23..47cad50c8f25b 100644 --- a/compiler/rustc_hir_analysis/src/variance/mod.rs +++ b/compiler/rustc_hir_analysis/src/variance/mod.rs @@ -9,7 +9,7 @@ use rustc_hir as hir; use rustc_hir::def::DefKind; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::ty::{ - self, CrateVariancesMap, GenericArgsRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, + self, CrateVariancesMap, GenericArgs, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, Unnormalized, }; use rustc_span::span_bug; @@ -114,7 +114,7 @@ fn variance_of_opaque( impl<'tcx> OpaqueTypeLifetimeCollector<'tcx> { #[instrument(level = "trace", skip(self), ret)] - fn visit_opaque(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) { + fn visit_opaque(&mut self, def_id: DefId, args: GenericArgs<'tcx>) { if def_id != self.root_def_id && self.tcx.is_descendant_of(def_id, self.root_def_id) { let child_variances = self.tcx.variances_of(def_id); for (a, v) in args.iter().zip_eq(child_variances) { @@ -140,7 +140,7 @@ fn variance_of_opaque( fn visit_ty(&mut self, t: Ty<'tcx>) { match t.kind() { ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => { - self.visit_opaque(*def_id, args); + self.visit_opaque(*def_id, *args); } _ => t.super_visit_with(self), } @@ -202,7 +202,7 @@ fn variance_of_opaque( trait_ref: ty::TraitRef { def_id: _, args, .. }, constness: _, }) => { - for arg in &args[1..] { + for arg in &args.as_slice()[1..] { arg.visit_with(&mut collector); } } @@ -210,7 +210,7 @@ fn variance_of_opaque( projection_term: ty::AliasTerm { args, .. }, term, }) => { - for arg in &args[1..] { + for arg in &args.as_slice()[1..] { arg.visit_with(&mut collector); } term.visit_with(&mut collector); diff --git a/compiler/rustc_hir_typeck/src/_match.rs b/compiler/rustc_hir_typeck/src/_match.rs index a1ff036574fdc..9eed99e23a35e 100644 --- a/compiler/rustc_hir_typeck/src/_match.rs +++ b/compiler/rustc_hir_typeck/src/_match.rs @@ -550,7 +550,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { else { return None; }; - if &args[0..self.tcx.generics_of(parent_def_id).count()] + if &args.as_slice()[0..self.tcx.generics_of(parent_def_id).count()] != ty::GenericArgs::identity_for_item(self.tcx, parent_def_id).as_slice() { return None; diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index f1cb5269e50c6..316dd72ed2652 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -16,7 +16,7 @@ use rustc_infer::traits::{Obligation, ObligationCause, ObligationCauseCode, Well use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AllowTwoPhase, AutoBorrow, AutoBorrowMutability, }; -use rustc_middle::ty::{self, FnSig, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, Unnormalized}; +use rustc_middle::ty::{self, FnSig, GenericArgs, Ty, TyCtxt, TypeVisitableExt, Unnormalized}; use rustc_span::def_id::LocalDefId; use rustc_span::{Ident, Span, bug, sym}; use rustc_target::spec::{AbiMap, AbiMapping}; @@ -665,7 +665,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expected: Expectation<'tcx>, tuple_arguments_flag: TupleArgumentsFlag, fn_id: SplatLoweringInfo<'tcx>, - callee_generic_args: Option>, + callee_generic_args: Option>, ) { let mut formal_inputs = Cow::Borrowed(fn_sig.inputs()); if let (SplatLoweringInfo::FnDef(def_id), Some(args)) = (fn_id, callee_generic_args) { @@ -1127,7 +1127,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { call_hir_id: Option, span: Span, callee_did: DefId, - callee_args: GenericArgsRef<'tcx>, + callee_args: GenericArgs<'tcx>, ) { let const_context = self.tcx.hir_body_const_context(self.body_def_id); diff --git a/compiler/rustc_hir_typeck/src/cast.rs b/compiler/rustc_hir_typeck/src/cast.rs index 14cb73e28c871..18bd66f791e37 100644 --- a/compiler/rustc_hir_typeck/src/cast.rs +++ b/compiler/rustc_hir_typeck/src/cast.rs @@ -562,7 +562,7 @@ impl<'a, 'tcx> CastCheck<'tcx> { .must_apply_modulo_regions() { let to_ty = if let ty::Adt(def, args) = self.cast_ty.kind() { - fcx.tcx.value_path_str_with_args(def.did(), args) + fcx.tcx.value_path_str_with_args(def.did(), *args) } else { self.cast_ty.to_string() }; diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index 7423d7d94d7f0..07ce529f9174d 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -101,7 +101,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let closure_args = ty::ClosureArgs::new( tcx, ty::ClosureArgsParts { - parent_args, + parent_args: parent_args.as_slice(), closure_kind_ty, closure_sig_as_fn_ptr_ty: Ty::new_fn_ptr(tcx, sig), tupled_upvars_ty, @@ -167,7 +167,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let coroutine_args = ty::CoroutineArgs::new( tcx, ty::CoroutineArgsParts { - parent_args, + parent_args: parent_args.as_slice(), kind_ty, resume_ty, yield_ty, @@ -212,7 +212,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let closure_args = ty::CoroutineClosureArgs::new( tcx, ty::CoroutineClosureArgsParts { - parent_args, + parent_args: parent_args.as_slice(), closure_kind_ty, signature_parts_ty: Ty::new_fn_ptr( tcx, @@ -253,7 +253,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { closure_args.coroutine_closure_sig().map_bound(|sig| { sig.to_coroutine( tcx, - parent_args, + parent_args.as_slice(), coroutine_kind_ty, tcx.coroutine_for_closure(expr_def_id), coroutine_upvars_ty, diff --git a/compiler/rustc_hir_typeck/src/demand.rs b/compiler/rustc_hir_typeck/src/demand.rs index 78335f036ffb7..662f5ee2afc80 100644 --- a/compiler/rustc_hir_typeck/src/demand.rs +++ b/compiler/rustc_hir_typeck/src/demand.rs @@ -1237,7 +1237,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { err.span_suggestion_verbose( *span, "use the type name directly", - self.tcx.value_path_str_with_args(e_def.did(), e_args), + self.tcx.value_path_str_with_args(e_def.did(), *e_args), Applicability::MaybeIncorrect, ); } diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index 6059ede2ecdc6..d56e8c2cf73e1 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -31,7 +31,7 @@ use rustc_infer::traits::WellFormedLoc; use rustc_infer::traits::query::NoSolution; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase}; use rustc_middle::ty::error::{ExpectedFound, TypeError}; -use rustc_middle::ty::{self, AdtKind, GenericArgsRef, Ty, TypeVisitableExt, Unnormalized}; +use rustc_middle::ty::{self, AdtKind, GenericArgs, Ty, TypeVisitableExt, Unnormalized}; use rustc_session::diagnostics::feature_err; use rustc_span::edit_distance::find_best_match_for_name; use rustc_span::hygiene::DesugaringKind; @@ -1560,7 +1560,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { false, TupleArgumentsFlag::DontTupleArguments, SplatLoweringInfo::Error(guar), - Some(GenericArgsRef::default()), + Some(GenericArgs::default()), ); err_ty @@ -1970,7 +1970,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { tcx.check_stability(v_field.did, Some(field.hir_id), field.span, None); } - Ok(self.field_ty(field.span, v_field, args)) + Ok(self.field_ty(field.span, v_field, *args)) } else { error_happened = true; let guar = if let Some(prev_span) = seen_fields.get(&ident) { @@ -2012,7 +2012,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { if let Err(diag) = diag { if idx == hir_fields.len() - 1 { if remaining_fields.is_empty() { - self.suggest_fru_from_range_and_emit(field, variant, args, diag); + self.suggest_fru_from_range_and_emit(field, variant, *args, diag); } else { diag.stash(field.span, StashKey::MaybeFruTypo); } @@ -2118,12 +2118,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty::Adt(adt, args) if adt.is_struct() => variant .fields .iter() - .map(|f| self.normalize(span, f.ty(self.tcx, args))) + .map(|f| self.normalize(span, f.ty(self.tcx, *args))) .collect(), ty::Adt(adt, args) if adt.is_enum() => variant .fields .iter() - .map(|f| self.normalize(span, f.ty(self.tcx, args))) + .map(|f| self.normalize(span, f.ty(self.tcx, *args))) .collect(), _ => { self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct { span }); @@ -2158,7 +2158,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let ident = self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id); if let Some(_) = remaining_fields.remove(&ident) { - let target_ty = self.field_ty(base_expr.span, f, args); + let target_ty = self.field_ty(base_expr.span, f, *args); let cause = self.misc(base_expr.span); if let Err(diag) = self.demand_suptype_diag(cause.span, target_ty, fru_ty) @@ -2221,7 +2221,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ty::Adt(adt, args) if adt.is_struct() => variant .fields .iter() - .map(|f| self.normalize(expr.span, f.ty(self.tcx, args))) + .map(|f| self.normalize(expr.span, f.ty(self.tcx, *args))) .collect(), _ => { self.dcx().emit_err(FunctionalRecordUpdateOnNonStruct { @@ -2278,7 +2278,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { remaining_fields, variant, hir_fields, - args, + *args, ); } } @@ -2318,7 +2318,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { remaining_fields: UnordMap, variant: &'tcx ty::VariantDef, hir_fields: &'tcx [hir::ExprField<'tcx>], - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) { let len = remaining_fields.len(); @@ -2395,7 +2395,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, last_expr_field: &hir::ExprField<'tcx>, variant: &ty::VariantDef, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, mut err: Diag<'_>, ) { if is_range_literal(last_expr_field.expr) @@ -2819,7 +2819,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { self.register_predicates(autoderef.into_obligations()); self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None); - return self.field_ty(expr.span, field, args); + return self.field_ty(expr.span, field, *args); } // The field is not accessible, fall through to error reporting. @@ -3265,7 +3265,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); let ty_str = match base_ty.peel_refs().kind() { - ty::Adt(def, args) => self.tcx.def_path_str_with_args(def.did(), args), + ty::Adt(def, args) => self.tcx.def_path_str_with_args(def.did(), *args), _ => base_ty.peel_refs().to_string(), }; err.multipart_suggestion( @@ -3404,7 +3404,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .map(|field_def| { ( field_def.ident(self.tcx).normalize_to_macros_2_0(), - field_def.ty(self.tcx, args).skip_norm_wip(), + field_def.ty(self.tcx, *args).skip_norm_wip(), ) }) .collect::>(), @@ -3888,7 +3888,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { break; }; - let field_ty = self.field_ty(expr.span, field, args); + let field_ty = self.field_ty(expr.span, field, *args); // Enums are anyway always sized. But just to safeguard against future // language extensions, let's double-check. @@ -3927,7 +3927,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .iter_enumerated() .find(|(_, f)| f.ident(self.tcx).normalize_to_macros_2_0() == ident) { - let field_ty = self.field_ty(expr.span, field, args); + let field_ty = self.field_ty(expr.span, field, *args); if self.tcx.features().offset_of_slice() { self.require_type_has_static_alignment(field_ty, expr.span); diff --git a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs index 0c49ec002671d..3bcd96711e655 100644 --- a/compiler/rustc_hir_typeck/src/expr_use_visitor.rs +++ b/compiler/rustc_hir_typeck/src/expr_use_visitor.rs @@ -689,7 +689,7 @@ impl<'tcx, Cx: TypeInformationCtxt<'tcx>, D: Delegate<'tcx>> ExprUseVisitor<'tcx let field_place = self.cat_projection( with_expr.hir_id, with_place.clone(), - with_field.ty(self.cx.tcx(), args).skip_norm_wip(), + with_field.ty(self.cx.tcx(), *args).skip_norm_wip(), ProjectionKind::Field(f_index, FIRST_VARIANT), ); self.consume_or_copy(&field_place, field_place.hir_id); diff --git a/compiler/rustc_hir_typeck/src/fallback.rs b/compiler/rustc_hir_typeck/src/fallback.rs index 8dd38d2eaa407..09c5e36f42847 100644 --- a/compiler/rustc_hir_typeck/src/fallback.rs +++ b/compiler/rustc_hir_typeck/src/fallback.rs @@ -370,7 +370,7 @@ impl<'tcx> AnnotateUnitFallbackVisitor<'_, 'tcx> { if arg_segment.args.is_none() && let Some(all_args) = self.fcx.typeck_results.borrow().node_args_opt(id) && let generics = self.fcx.tcx.generics_of(def_id) - && let args = all_args[generics.parent_count..].iter().zip(&generics.own_params) + && let args = all_args.as_slice()[generics.parent_count..].iter().zip(&generics.own_params) // We can't turbofish consts :( && args.clone().all(|(_, param)| matches!(param.kind, ty::GenericParamDefKind::Type { .. } | ty::GenericParamDefKind::Lifetime)) { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs index 13aa54d7be7bf..a0be92752b4d8 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs @@ -28,9 +28,9 @@ use rustc_middle::ty::adjustment::{ Adjust, Adjustment, AutoBorrow, AutoBorrowMutability, DerefAdjustKind, }; use rustc_middle::ty::{ - self, AdtKind, CanonicalUserType, GenericArgsRef, GenericParamDefKind, IsIdentity, - SizedTraitKind, SplattedDef, Ty, TyCtxt, TypeFoldable, TypeVisitable, TypeVisitableExt, - Unnormalized, UserArgs, UserSelfTy, + self, AdtKind, CanonicalUserType, GenericArgs, GenericParamDefKind, IsIdentity, SizedTraitKind, + SplattedDef, Ty, TyCtxt, TypeFoldable, TypeVisitable, TypeVisitableExt, Unnormalized, UserArgs, + UserSelfTy, }; use rustc_span::def_id::LocalDefId; use rustc_span::hygiene::DesugaringKind; @@ -237,7 +237,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, hir_id: HirId, fn_id: SplatLoweringInfo<'tcx>, - callee_generic_args: Option>, + callee_generic_args: Option>, first_tupled_arg_index: u16, tupled_args_count: u16, ) { @@ -285,7 +285,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } } - fn write_args(&self, node_id: HirId, args: GenericArgsRef<'tcx>) { + fn write_args(&self, node_id: HirId, args: GenericArgs<'tcx>) { if !args.is_empty() { debug!("write_args({:?}, {:?}) in fcx {}", node_id, args, self.tag()); @@ -305,7 +305,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, hir_id: HirId, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, user_self_ty: Option>, ) { debug!("fcx {}", self.tag()); @@ -596,8 +596,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { pub(super) fn user_args_for_adt(ty: LoweredTy<'tcx>) -> UserArgs<'tcx> { match (ty.raw.kind(), ty.normalized.kind()) { - (ty::Adt(_, args), _) => UserArgs { args, user_self_ty: None }, - (_, ty::Adt(adt, args)) => UserArgs { + (&ty::Adt(_, args), _) => UserArgs { args, user_self_ty: None }, + (_, &ty::Adt(ref adt, args)) => UserArgs { args, user_self_ty: Some(UserSelfTy { impl_def_id: adt.did(), self_ty: ty.raw }), }, @@ -684,7 +684,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } /// Registers obligations that all `args` are well-formed. - pub(crate) fn add_wf_bounds(&self, args: GenericArgsRef<'tcx>, span: Span, hir_id: HirId) { + pub(crate) fn add_wf_bounds(&self, args: GenericArgs<'tcx>, span: Span, hir_id: HirId) { for term in args.iter().filter_map(ty::GenericArg::as_term) { self.register_wf_obligation( term, @@ -701,7 +701,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, span: Span, field: &'tcx ty::FieldDef, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Ty<'tcx> { self.normalize(span, field.ty(self.tcx, args)) } @@ -1523,7 +1523,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, span: Span, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, hir_id: HirId, ) { self.add_required_obligations_with_code(span, def_id, args, |idx, span| { @@ -1536,7 +1536,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &self, span: Span, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, code: impl Fn(usize, Span) -> ObligationCauseCode<'tcx>, ) { let param_env = self.param_env; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs index ea0aa9db46a9c..45b0b6b43d37c 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/adjust_fulfillment_errors.rs @@ -83,12 +83,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (predicate_args, predicate_self_type_to_point_at) = match uninstantiated_clause.kind().skip_binder() { ty::ClauseKind::Trait(pred) => { - (pred.trait_ref.args.to_vec(), Some(pred.self_ty().into())) + (pred.trait_ref.args.as_slice().to_vec(), Some(pred.self_ty().into())) } ty::ClauseKind::HostEffect(clause) => { - (clause.trait_ref.args.to_vec(), Some(clause.self_ty().into())) + (clause.trait_ref.args.as_slice().to_vec(), Some(clause.self_ty().into())) + } + ty::ClauseKind::Projection(pred) => { + (pred.projection_term.args.as_slice().to_vec(), None) } - ty::ClauseKind::Projection(pred) => (pred.projection_term.args.to_vec(), None), ty::ClauseKind::ConstArgHasType(arg, ty) => (vec![ty.into(), arg.into()], None), ty::ClauseKind::ConstEvaluatable(e) => (vec![e.into()], None), _ => return false, @@ -542,10 +544,8 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { param_to_point_at: ty::GenericArg<'tcx>, segment: &hir::PathSegment<'tcx>, ) -> bool { - let own_args = self - .tcx - .generics_of(def_id) - .own_args(ty::GenericArgs::identity_for_item(self.tcx, def_id)); + let args = ty::GenericArgs::identity_for_item(self.tcx, def_id); + let own_args = self.tcx.generics_of(def_id).own_args(args.as_slice()); let Some(mut index) = own_args.iter().position(|arg| *arg == param_to_point_at) else { return false; }; @@ -589,7 +589,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { && let Some(arg) = ty::GenericArgs::identity_for_item(self.0.tcx, self.1).get(index as usize) { - ControlFlow::Break(*arg) + ControlFlow::Break(arg) } else { ty.super_visit_with(self) } @@ -1130,7 +1130,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .variant_with_id(variant_def_id) .fields .iter() - .map(|field| field.ty(self.tcx, in_ty_adt_generic_args).skip_norm_wip()) + .map(|field| field.ty(self.tcx, *in_ty_adt_generic_args).skip_norm_wip()) .enumerate() .filter(|(_index, field_type)| find_param_in_ty((*field_type).into(), param)), ) else { diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs index 69ffd02466589..ae3e833bf81e1 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs @@ -209,7 +209,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Lowering info if a splatted function is being called. fn_id: SplatLoweringInfo<'tcx>, // The generics of the function being called. Only used for splatting - callee_generic_args: Option>, + callee_generic_args: Option>, ) { let tcx = self.tcx; @@ -597,7 +597,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Lowering info if a splatted function is being called. fn_id: SplatLoweringInfo<'tcx>, // The generics of the function being called. Only used for splatting - callee_generic_args: Option>, + callee_generic_args: Option>, ) -> TupledArgCheckOutcome<'tcx> { let (first_tupled_arg_index, is_self_splatted) = tuple_arguments.tupled_arg_index(); let Some(first_tupled_arg_index) = first_tupled_arg_index else { @@ -3719,9 +3719,9 @@ fn only_keep_structural_changes<'tcx>( formal_ty: Ty<'tcx>, _expected_ty: Ty<'tcx>, _def_id: DefId, - formal_args: ty::GenericArgsRef<'tcx>, - expected_args: ty::GenericArgsRef<'tcx>, - mk: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>, + formal_args: ty::GenericArgs<'tcx>, + expected_args: ty::GenericArgs<'tcx>, + mk: impl FnOnce(ty::GenericArgs<'tcx>) -> Ty<'tcx>, ) -> RelateResult<'tcx, Ty<'tcx>> { let new_args = relate::relate_args_invariantly(self, formal_args, expected_args)?; diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs index b2b49dc06b7a6..7db3c4a4d6eea 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/mod.rs @@ -387,7 +387,7 @@ impl<'tcx> HirTyLowerer<'tcx> for FnCtxt<'_, 'tcx> { item_def_id: DefId, item_segment: &rustc_hir::PathSegment<'_>, poly_trait_ref: ty::PolyTraitRef<'tcx>, - ) -> Result<(DefId, ty::GenericArgsRef<'tcx>), ErrorGuaranteed> { + ) -> Result<(DefId, ty::GenericArgs<'tcx>), ErrorGuaranteed> { let trait_ref = self.instantiate_binder_with_fresh_vars( span, // FIXME(mgca): `item_def_id` can be an AssocConst; rename this variant. @@ -434,7 +434,7 @@ impl<'tcx> HirTyLowerer<'tcx> for FnCtxt<'_, 'tcx> { ty::AliasTy { kind: ty::Projection { def_id } | ty::Free { def_id }, args, .. }, ) = ty.kind() { - self.add_required_obligations_for_hir(span, *def_id, args, hir_id); + self.add_required_obligations_for_hir(span, *def_id, *args, hir_id); } self.normalize(span, Unnormalized::new_wip(ty)) diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 397fb560e86f4..95bcdeb2bd030 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -2717,7 +2717,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // suggestions would be often wrong. So suppress the suggestion. See #145294. if let (ty::Adt(exp_adt, _), ty::Adt(act_adt, _)) = (expected.kind(), expr_ty.kind()) && exp_adt.did() == act_adt.did() - && sole_field.ty(self.tcx, args).skip_norm_wip().is_ty_var() { + && sole_field.ty(self.tcx, *args).skip_norm_wip().is_ty_var() { return None; } @@ -2734,7 +2734,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let note_about_variant_field_privacy = (field_is_local && !field_is_accessible) .then(|| " (its field is private, but it's local to this crate and its privacy can be changed)".to_string()); - let sole_field_ty = sole_field.ty(self.tcx, args).skip_norm_wip(); + let sole_field_ty = sole_field.ty(self.tcx, *args).skip_norm_wip(); if self.may_coerce(expr_ty, sole_field_ty) { let variant_path = with_types_for_suggestion!(with_no_trimmed_paths!( self.tcx.def_path_str(variant.def_id) diff --git a/compiler/rustc_hir_typeck/src/method/confirm.rs b/compiler/rustc_hir_typeck/src/method/confirm.rs index 2926f9b61eeca..86f3e4dd4f1e9 100644 --- a/compiler/rustc_hir_typeck/src/method/confirm.rs +++ b/compiler/rustc_hir_typeck/src/method/confirm.rs @@ -23,8 +23,8 @@ use rustc_middle::ty::adjustment::{ PointerCoercion, }; use rustc_middle::ty::{ - self, AssocContainer, GenericArgs, GenericArgsRef, GenericParamDefKind, Ty, TyCtxt, - TypeFoldable, TypeVisitableExt, Unnormalized, UserArgs, + self, AssocContainer, GenericArgs, GenericParamDefKind, Ty, TyCtxt, TypeFoldable, + TypeVisitableExt, Unnormalized, UserArgs, }; use rustc_span::{DUMMY_SP, Span, bug, span_bug}; use rustc_trait_selection::traits; @@ -301,7 +301,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { &mut self, self_ty: Ty<'tcx>, pick: &probe::Pick<'tcx>, - ) -> GenericArgsRef<'tcx> { + ) -> GenericArgs<'tcx> { match pick.kind { probe::InherentImplPick => { let impl_def_id = pick.item.container_id(self.tcx); @@ -419,8 +419,8 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { &mut self, pick: &probe::Pick<'tcx>, seg: &hir::PathSegment<'tcx>, - parent_args: GenericArgsRef<'tcx>, - ) -> GenericArgsRef<'tcx> { + parent_args: GenericArgs<'tcx>, + ) -> GenericArgs<'tcx> { // Determine the values for the generic parameters of the method. // If they were not explicitly supplied, just construct fresh // variables. @@ -519,7 +519,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { let args = lower_generic_args( self.fcx, pick.item.def_id, - parent_args, + parent_args.as_slice(), false, None, &arg_count_correct, @@ -614,7 +614,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { fn instantiate_method_sig( &mut self, pick: &probe::Pick<'tcx>, - all_args: GenericArgsRef<'tcx>, + all_args: GenericArgs<'tcx>, ) -> (ty::FnSig<'tcx>, ty::InstantiatedClauses<'tcx>) { debug!("instantiate_method_sig(pick={:?}, all_args={:?})", pick, all_args); @@ -638,7 +638,7 @@ impl<'a, 'tcx> ConfirmContext<'a, 'tcx> { fn add_obligations( &mut self, sig: ty::FnSig<'tcx>, - all_args: GenericArgsRef<'tcx>, + all_args: GenericArgs<'tcx>, method_clauses: ty::InstantiatedClauses<'tcx>, def_id: DefId, ) { diff --git a/compiler/rustc_hir_typeck/src/method/mod.rs b/compiler/rustc_hir_typeck/src/method/mod.rs index 690275faa31b9..bebf7a9e9380b 100644 --- a/compiler/rustc_hir_typeck/src/method/mod.rs +++ b/compiler/rustc_hir_typeck/src/method/mod.rs @@ -15,7 +15,7 @@ use rustc_infer::infer::{BoundRegionConversionTime, InferOk}; use rustc_infer::traits::PredicateObligations; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::{ - self, GenericArgs, GenericArgsRef, GenericParamDefKind, Ty, TypeVisitableExt, Unnormalized, + self, GenericArgs, GenericParamDefKind, Ty, TypeVisitableExt, Unnormalized, }; use rustc_span::{ErrorGuaranteed, Ident, Span, Symbol, bug, span_bug}; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt; @@ -31,7 +31,7 @@ use crate::method::probe::UnsatisfiedPredicates; pub(crate) struct MethodCallee<'tcx> { /// Impl method ID, for inherent methods, or trait method ID, otherwise. pub def_id: DefId, - pub args: GenericArgsRef<'tcx>, + pub args: GenericArgs<'tcx>, /// Instantiated method signature, i.e., it has been /// instantiated, normalized, and has had late-bound diff --git a/compiler/rustc_hir_typeck/src/method/probe.rs b/compiler/rustc_hir_typeck/src/method/probe.rs index fee295aa0e149..4dc94d013eb55 100644 --- a/compiler/rustc_hir_typeck/src/method/probe.rs +++ b/compiler/rustc_hir_typeck/src/method/probe.rs @@ -22,8 +22,8 @@ use rustc_middle::middle::stability; use rustc_middle::ty::elaborate::supertrait_def_ids; use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams, simplify_type}; use rustc_middle::ty::{ - self, AssocContainer, AssocItem, GenericArgs, GenericArgsRef, GenericParamDefKind, ParamEnvAnd, - Ty, TyCtxt, TypeVisitableExt, Unnormalized, Upcast, + self, AssocContainer, AssocItem, GenericArgs, GenericParamDefKind, ParamEnvAnd, Ty, TyCtxt, + TypeVisitableExt, Unnormalized, Upcast, }; use rustc_span::def_id::{DefId, LocalDefId}; use rustc_span::edit_distance::{ @@ -2592,7 +2592,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { &self, item: ty::AssocItem, impl_ty: Ty<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> (Ty<'tcx>, Option>) { if item.is_fn() && self.mode == Mode::MethodCall { let sig = self.xform_method_sig(item.def_id, args); @@ -2603,7 +2603,7 @@ impl<'a, 'tcx> ProbeContext<'a, 'tcx> { } #[instrument(level = "debug", skip(self))] - fn xform_method_sig(&self, method: DefId, args: GenericArgsRef<'tcx>) -> ty::FnSig<'tcx> { + fn xform_method_sig(&self, method: DefId, args: GenericArgs<'tcx>) -> ty::FnSig<'tcx> { let fn_sig = self.tcx.fn_sig(method); debug!(?fn_sig); diff --git a/compiler/rustc_hir_typeck/src/method/suggest.rs b/compiler/rustc_hir_typeck/src/method/suggest.rs index 2d332ae9d6cf8..d4487bfaea67c 100644 --- a/compiler/rustc_hir_typeck/src/method/suggest.rs +++ b/compiler/rustc_hir_typeck/src/method/suggest.rs @@ -2398,7 +2398,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .rebase_onto( self.tcx, inherent_method.container_id(self.tcx), - adt_args, + *adt_args, ); let fn_sig = self .tcx @@ -2836,7 +2836,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let variant = &def.non_enum_variant(); tcx.find_field_index(item_name, variant).map(|index| { let field = &variant.fields[index]; - let field_ty = field.ty(tcx, args).skip_norm_wip(); + let field_ty = field.ty(tcx, *args).skip_norm_wip(); (field, field_ty) }) } @@ -3294,7 +3294,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let [field] = &variant.fields.raw[..] else { return None; }; - let field_ty = field.ty(tcx, args).skip_norm_wip(); + let field_ty = field.ty(tcx, *args).skip_norm_wip(); // Skip `_`, since that'll just lead to ambiguity. if self.deeply_resolve_ignoring_regions(field_ty).is_ty_var() { @@ -3329,7 +3329,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match &matching_variants[..] { [(_, field, pick)] => { - let self_ty = field.ty(tcx, args).skip_norm_wip(); + let self_ty = field.ty(tcx, *args).skip_norm_wip(); err.span_note( tcx.def_span(pick.item.def_id), format!("the method `{item_name}` exists on the type `{self_ty}`"), @@ -3373,7 +3373,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Target wrapper types - types that wrap or pretend to wrap another type, // perhaps this inner type is meant to be called? ty::AdtKind::Struct | ty::AdtKind::Union => { - let [first] = ***args else { + let [first] = *args.as_slice() else { return; }; let ty::GenericArgKind::Type(ty) = first.kind() else { @@ -3858,7 +3858,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { /// Print out the type for use in value namespace. fn ty_to_value_string(&self, ty: Ty<'tcx>) -> String { match ty.kind() { - ty::Adt(def, args) => self.tcx.value_path_str_with_args(def.did(), args), + ty::Adt(def, args) => self.tcx.value_path_str_with_args(def.did(), *args), _ => self.ty_to_string(ty), } } diff --git a/compiler/rustc_hir_typeck/src/pat.rs b/compiler/rustc_hir_typeck/src/pat.rs index ff06a59e7fd6e..0ebb418c7f2ac 100644 --- a/compiler/rustc_hir_typeck/src/pat.rs +++ b/compiler/rustc_hir_typeck/src/pat.rs @@ -1862,7 +1862,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }; for (i, subpat) in subpats.iter().enumerate_and_adjust(variant.fields.len(), ddpos) { let field = &variant.fields[FieldIdx::from_usize(i)]; - let field_ty = self.field_ty(subpat.span, field, args); + let field_ty = self.field_ty(subpat.span, field, *args); self.check_pat(subpat, field_ty, pat_info); self.tcx.check_stability( @@ -1956,7 +1956,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // the tuple struct pattern. Otherwise the args could get out of range on e.g., // `let P() = U;` where `P != U` with `struct Box(T);`. (ty::Adt(_, args), [field], Ok(())) => { - let field_ty = self.field_ty(pat_span, field, args); + let field_ty = self.field_ty(pat_span, field, *args); match field_ty.kind() { ty::Tuple(fields) => fields.len() == subpats.len(), _ => false, @@ -2129,7 +2129,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .map(|(i, f)| { self.write_field_index(field.hir_id, *i); self.tcx.check_stability(f.did, Some(field.hir_id), span, None); - self.field_ty(span, f, args) + self.field_ty(span, f, *args) }) .unwrap_or_else(|| { inexistent_fields.push(field); @@ -2159,7 +2159,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { &mut unmentioned_fields, pat, variant, - args, + *args, )) } else { None @@ -2315,7 +2315,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { unmentioned_fields: &mut Vec<(&'tcx ty::FieldDef, Ident)>, pat: &'tcx Pat<'tcx>, variant: &ty::VariantDef, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Diag<'a> { let tcx = self.tcx; let (field_names, t, plural) = match inexistent_fields { diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index fbe20c849de9c..3c59017c78d85 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -1824,7 +1824,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }) .collect(); - let after_field_ty = field.ty(self.tcx, args).skip_norm_wip(); + let after_field_ty = field.ty(self.tcx, *args).skip_norm_wip(); self.has_significant_drop_outside_of_captures( closure_def_id, closure_span, diff --git a/compiler/rustc_infer/src/infer/canonical/instantiate.rs b/compiler/rustc_infer/src/infer/canonical/instantiate.rs index 2bc7e269efc9d..3d7a1ed133de3 100644 --- a/compiler/rustc_infer/src/infer/canonical/instantiate.rs +++ b/compiler/rustc_infer/src/infer/canonical/instantiate.rs @@ -76,7 +76,7 @@ struct CanonicalInstantiator<'tcx> { tcx: TyCtxt<'tcx>, // The values that the bound vars are are being instantiated with. - var_values: ty::GenericArgsRef<'tcx>, + var_values: ty::GenericArgs<'tcx>, // Because we use `ty::BoundVarIndexKind::Canonical`, we can cache // based only on the entire ty, not worrying about a `DebruijnIndex` @@ -149,7 +149,7 @@ impl<'tcx> TypeFolder> for CanonicalInstantiator<'tcx> { .lock() .entry(c) .or_insert_with(|| highest_var_in_clauses(c)); - let c_args = &self.var_values[..=index]; + let c_args = &self.var_values.as_tcx_slice()[..=index]; if let Some(c) = self.tcx.caches.clauses_cache.lock().get(&(c, c_args)) { c diff --git a/compiler/rustc_infer/src/infer/context.rs b/compiler/rustc_infer/src/infer/context.rs index 38dab6ec4875d..f5fadd2ab8229 100644 --- a/compiler/rustc_infer/src/infer/context.rs +++ b/compiler/rustc_infer/src/infer/context.rs @@ -163,7 +163,7 @@ impl<'tcx> rustc_type_ir::InferCtxtLike for InferCtxt<'tcx> { self.next_const_var(DUMMY_SP) } - fn fresh_args_for_item(&self, def_id: DefId) -> ty::GenericArgsRef<'tcx> { + fn fresh_args_for_item(&self, def_id: DefId) -> ty::GenericArgs<'tcx> { self.fresh_args_for_item(DUMMY_SP, def_id) } diff --git a/compiler/rustc_infer/src/infer/mod.rs b/compiler/rustc_infer/src/infer/mod.rs index 09020656226e5..00178404e8132 100644 --- a/compiler/rustc_infer/src/infer/mod.rs +++ b/compiler/rustc_infer/src/infer/mod.rs @@ -29,9 +29,9 @@ use rustc_middle::traits::solve::Goal; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::{ self, BoundVarReplacerDelegate, ConstVid, FloatVid, GenericArg, GenericArgKind, GenericArgs, - GenericArgsRef, GenericParamDefKind, InferConst, OpaqueTypeKey, ProvisionalHiddenType, - PseudoCanonicalInput, Term, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable, - TypeVisitable, TypeVisitableExt, TypingEnv, TypingMode, fold_regions, + GenericParamDefKind, InferConst, OpaqueTypeKey, ProvisionalHiddenType, PseudoCanonicalInput, + Term, Ty, TyCtxt, TyVid, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitable, + TypeVisitableExt, TypingEnv, TypingMode, fold_regions, }; use rustc_span::{DUMMY_SP, Span, Symbol, bug}; use rustc_type_ir::{CanonicalizerState, MayBeErased}; @@ -1076,7 +1076,7 @@ impl<'tcx> InferCtxt<'tcx> { /// Given a set of generics defined on a type or impl, returns the generic parameters mapping /// each type/region parameter to a fresh inference variable. - pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgsRef<'tcx> { + pub fn fresh_args_for_item(&self, span: Span, def_id: DefId) -> GenericArgs<'tcx> { GenericArgs::for_item(self.tcx, def_id, |param, _| self.var_for_def(span, param)) } diff --git a/compiler/rustc_infer/src/infer/opaque_types/mod.rs b/compiler/rustc_infer/src/infer/opaque_types/mod.rs index 6a922f75dbe9b..e7e394fa0efb4 100644 --- a/compiler/rustc_infer/src/infer/opaque_types/mod.rs +++ b/compiler/rustc_infer/src/infer/opaque_types/mod.rs @@ -296,7 +296,7 @@ impl<'tcx> InferCtxt<'tcx> { pub fn add_item_bounds_for_hidden_type( &self, def_id: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, param_env: ty::ParamEnv<'tcx>, hidden_ty: Ty<'tcx>, goals: &mut Vec>>, diff --git a/compiler/rustc_infer/src/infer/outlives/obligations.rs b/compiler/rustc_infer/src/infer/outlives/obligations.rs index 53226265cc9d7..19631c9d986cb 100644 --- a/compiler/rustc_infer/src/infer/outlives/obligations.rs +++ b/compiler/rustc_infer/src/infer/outlives/obligations.rs @@ -64,7 +64,7 @@ use rustc_data_structures::undo_log::UndoLogs; use rustc_middle::mir::ConstraintCategory; use rustc_middle::ty::outlives::{Component, push_outlives_components}; use rustc_middle::ty::{ - self, GenericArgKind, GenericArgsRef, PolyTypeOutlivesClause, Region, RegionVid, Ty, TyCtxt, + self, GenericArgKind, GenericArgs, PolyTypeOutlivesClause, Region, RegionVid, Ty, TyCtxt, TypeVisitableExt, Upcast, }; use rustc_span::bug; @@ -671,7 +671,7 @@ where #[instrument(level = "debug", skip(self))] fn args_must_outlive( &mut self, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, origin: infer::SubregionOrigin<'tcx>, region: ty::Region<'tcx>, opt_variances: Option<&[ty::Variance]>, diff --git a/compiler/rustc_infer/src/infer/outlives/test_type_match.rs b/compiler/rustc_infer/src/infer/outlives/test_type_match.rs index de42736ce2b06..310aec470e233 100644 --- a/compiler/rustc_infer/src/infer/outlives/test_type_match.rs +++ b/compiler/rustc_infer/src/infer/outlives/test_type_match.rs @@ -147,9 +147,9 @@ impl<'tcx> TypeRelation> for MatchAgainstHigherRankedOutlives<'tcx> a_ty: Ty<'tcx>, _: Ty<'tcx>, def_id: DefId, - a_args: ty::GenericArgsRef<'tcx>, - b_args: ty::GenericArgsRef<'tcx>, - _: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>, + a_args: ty::GenericArgs<'tcx>, + b_args: ty::GenericArgs<'tcx>, + _: impl FnOnce(ty::GenericArgs<'tcx>) -> Ty<'tcx>, ) -> RelateResult<'tcx, Ty<'tcx>> { let variances = self.cx().variances_of(def_id); relate_args_with_variances(self, variances, a_args, b_args)?; diff --git a/compiler/rustc_infer/src/infer/relate/generalize.rs b/compiler/rustc_infer/src/infer/relate/generalize.rs index a81ec3d527a6e..d885c4be1e511 100644 --- a/compiler/rustc_infer/src/infer/relate/generalize.rs +++ b/compiler/rustc_infer/src/infer/relate/generalize.rs @@ -454,9 +454,9 @@ impl<'tcx> TypeRelation> for Generalizer<'_, 'tcx> { a_ty: Ty<'tcx>, _: Ty<'tcx>, def_id: DefId, - a_args: ty::GenericArgsRef<'tcx>, - b_args: ty::GenericArgsRef<'tcx>, - mk: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>, + a_args: ty::GenericArgs<'tcx>, + b_args: ty::GenericArgs<'tcx>, + mk: impl FnOnce(ty::GenericArgs<'tcx>) -> Ty<'tcx>, ) -> RelateResult<'tcx, Ty<'tcx>> { let args = if self.ambient_variance == ty::Invariant { // Avoid fetching the variance if we are in an invariant diff --git a/compiler/rustc_infer/src/infer/relate/lattice.rs b/compiler/rustc_infer/src/infer/relate/lattice.rs index 875631eef1f65..27bebbf239c1c 100644 --- a/compiler/rustc_infer/src/infer/relate/lattice.rs +++ b/compiler/rustc_infer/src/infer/relate/lattice.rs @@ -80,9 +80,9 @@ impl<'tcx> TypeRelation> for LatticeOp<'_, 'tcx> { a_ty: Ty<'tcx>, b_ty: Ty<'tcx>, def_id: DefId, - a_args: ty::GenericArgsRef<'tcx>, - b_args: ty::GenericArgsRef<'tcx>, - mk: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>, + a_args: ty::GenericArgs<'tcx>, + b_args: ty::GenericArgs<'tcx>, + mk: impl FnOnce(ty::GenericArgs<'tcx>) -> Ty<'tcx>, ) -> RelateResult<'tcx, Ty<'tcx>> { let variances = self.cx().variances_of(def_id); combine_ty_args(self.infcx, self, a_ty, b_ty, variances, a_args, b_args, |args| mk(args)) diff --git a/compiler/rustc_infer/src/infer/relate/type_relating.rs b/compiler/rustc_infer/src/infer/relate/type_relating.rs index 7c8e263db5582..6bc65d362eed1 100644 --- a/compiler/rustc_infer/src/infer/relate/type_relating.rs +++ b/compiler/rustc_infer/src/infer/relate/type_relating.rs @@ -83,9 +83,9 @@ impl<'tcx> TypeRelation> for TypeRelating<'_, 'tcx> { a_ty: Ty<'tcx>, b_ty: Ty<'tcx>, def_id: DefId, - a_args: ty::GenericArgsRef<'tcx>, - b_args: ty::GenericArgsRef<'tcx>, - _: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>, + a_args: ty::GenericArgs<'tcx>, + b_args: ty::GenericArgs<'tcx>, + _: impl FnOnce(ty::GenericArgs<'tcx>) -> Ty<'tcx>, ) -> RelateResult<'tcx, Ty<'tcx>> { if self.ambient_variance == ty::Invariant { // Avoid fetching the variance if we are in an invariant diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index d19d6a0da98ac..dc054ef0f30f1 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -466,21 +466,21 @@ impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations { return; } let def = cx.tcx.adt_def(item.owner_id); - (def, Ty::new_adt(cx.tcx, def, ty::List::empty())) + (def, Ty::new_adt(cx.tcx, def, ty::GenericArgs::empty())) } hir::ItemKind::Union(_, generics, _) => { if !generics.params.is_empty() { return; } let def = cx.tcx.adt_def(item.owner_id); - (def, Ty::new_adt(cx.tcx, def, ty::List::empty())) + (def, Ty::new_adt(cx.tcx, def, ty::GenericArgs::empty())) } hir::ItemKind::Enum(_, generics, _) => { if !generics.params.is_empty() { return; } let def = cx.tcx.adt_def(item.owner_id); - (def, Ty::new_adt(cx.tcx, def, ty::List::empty())) + (def, Ty::new_adt(cx.tcx, def, ty::GenericArgs::empty())) } _ => return, }; @@ -2394,7 +2394,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { cx: &LateContext<'tcx>, ty: Ty<'tcx>, variant: &VariantDef, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, descr: &str, init: InitKind, ) -> Option { @@ -2493,7 +2493,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { cx, ty, adt_def.non_enum_variant(), - args, + *args, "struct field", init, ); @@ -2503,7 +2503,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { let mut potential_variants = adt_def.variants().iter().filter_map(|variant| { let definitely_inhabited = match variant .inhabited_predicate(cx.tcx) - .instantiate(cx.tcx, args) + .instantiate(cx.tcx, *args) .apply_any_module(cx.tcx, cx.typing_env()) { // Entirely skip uninhabited variants. @@ -2528,7 +2528,7 @@ impl<'tcx> LateLintPass<'tcx> for InvalidValue { cx, ty, first_variant.0, - args, + *args, "field of the only potentially inhabited enum variant", init, ); diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 9678ed65d2891..d2a02d6529927 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -26,9 +26,7 @@ use rustc_middle::lint::{LevelSpec, StableLevelSpec, UnstableLevelSpec}; use rustc_middle::middle::privacy::EffectiveVisibilities; use rustc_middle::ty::layout::{LayoutError, LayoutOfHelpers, TyAndLayout}; use rustc_middle::ty::print::{PrintError, PrintTraitRefExt as _, Printer, with_no_trimmed_paths}; -use rustc_middle::ty::{ - self, GenericArg, RegisteredTools, Ty, TyCtxt, TypingEnv, TypingMode, Unnormalized, -}; +use rustc_middle::ty::{self, RegisteredTools, Ty, TyCtxt, TypingEnv, TypingMode, Unnormalized}; use rustc_session::{DynLintStore, Session}; use rustc_span::edit_distance::find_best_match_for_names; use rustc_span::{Ident, Span, Symbol, bug, sym}; @@ -738,7 +736,7 @@ impl<'tcx> LateContext<'tcx> { if trait_ref.is_none() && let ty::Adt(def, args) = self_ty.kind() { - return self.print_def_path(def.did(), args); + return self.print_def_path(def.did(), *args); } // This shouldn't ever be needed, but just in case: @@ -798,14 +796,14 @@ impl<'tcx> LateContext<'tcx> { fn print_path_with_generic_args( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - _args: &[GenericArg<'tcx>], + _args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { print_prefix(self) } } let mut p = LintPathPrinter { tcx: self.tcx, path: vec![] }; - p.print_def_path(def_id, &[]).unwrap(); + p.print_def_path(def_id, ty::GenericArgs::empty()).unwrap(); p.path } diff --git a/compiler/rustc_lint/src/disallowed_pass_by_ref.rs b/compiler/rustc_lint/src/disallowed_pass_by_ref.rs index 71d81e4512ca2..a373436d4298f 100644 --- a/compiler/rustc_lint/src/disallowed_pass_by_ref.rs +++ b/compiler/rustc_lint/src/disallowed_pass_by_ref.rs @@ -53,7 +53,7 @@ fn path_for_rustc_pass_by_value(cx: &LateContext<'_>, ty: &hir::Ty<'_>) -> Optio cx.tcx.type_of(did).instantiate_identity().skip_norm_wip().kind() { if find_attr!(cx.tcx, adt.did(), RustcPassByValue) { - return Some(cx.tcx.def_path_str_with_args(adt.did(), args)); + return Some(cx.tcx.def_path_str_with_args(adt.did(), *args)); } } } diff --git a/compiler/rustc_lint/src/for_loops_over_fallibles.rs b/compiler/rustc_lint/src/for_loops_over_fallibles.rs index bb0f2a2793ab8..94f57f44bea50 100644 --- a/compiler/rustc_lint/src/for_loops_over_fallibles.rs +++ b/compiler/rustc_lint/src/for_loops_over_fallibles.rs @@ -150,7 +150,7 @@ fn extract_iterator_next_call<'tcx>( fn suggest_question_mark<'tcx>( cx: &LateContext<'tcx>, adt: ty::AdtDef<'tcx>, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, span: Span, ) -> bool { let Some(body_id) = cx.enclosing_body else { return false }; diff --git a/compiler/rustc_lint/src/foreign_modules.rs b/compiler/rustc_lint/src/foreign_modules.rs index e6092a1497a0f..14faf032799b6 100644 --- a/compiler/rustc_lint/src/foreign_modules.rs +++ b/compiler/rustc_lint/src/foreign_modules.rs @@ -104,7 +104,7 @@ impl ClashingExternDeclarations { /// for the item, return its HirId without updating the set. fn insert(&mut self, tcx: TyCtxt<'_>, fi: hir::ForeignItemId) -> Option { let did = fi.owner_id.to_def_id(); - let instance = Instance::new_raw(did, ty::List::identity_for_item(tcx, did)); + let instance = Instance::new_raw(did, ty::GenericArgs::identity_for_item(tcx, did)); let name = Symbol::intern(tcx.symbol_name(instance).name); if let Some(&existing_id) = self.seen_decls.get(&name) { // Avoid updating the map with the new entry when we do find a collision. We want to diff --git a/compiler/rustc_lint/src/impl_trait_overcaptures.rs b/compiler/rustc_lint/src/impl_trait_overcaptures.rs index 9d7d0a0df475f..1850596f082aa 100644 --- a/compiler/rustc_lint/src/impl_trait_overcaptures.rs +++ b/compiler/rustc_lint/src/impl_trait_overcaptures.rs @@ -542,9 +542,9 @@ impl<'tcx> TypeRelation> for FunctionalVariances<'tcx> { a_ty: Ty<'tcx>, _: Ty<'tcx>, def_id: DefId, - a_args: ty::GenericArgsRef<'tcx>, - b_args: ty::GenericArgsRef<'tcx>, - _: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>, + a_args: ty::GenericArgs<'tcx>, + b_args: ty::GenericArgs<'tcx>, + _: impl FnOnce(ty::GenericArgs<'tcx>) -> Ty<'tcx>, ) -> RelateResult<'tcx, Ty<'tcx>> { let variances = self.cx().variances_of(def_id); relate_args_with_variances(self, variances, a_args, b_args)?; diff --git a/compiler/rustc_lint/src/internal.rs b/compiler/rustc_lint/src/internal.rs index 03622e253c90a..05dbaa848c194 100644 --- a/compiler/rustc_lint/src/internal.rs +++ b/compiler/rustc_lint/src/internal.rs @@ -10,7 +10,7 @@ use rustc_hir::def_id::DefId; use rustc_hir::{Expr, ExprKind, HirId}; use rustc_infer::infer::TyCtxtInferExt as _; use rustc_lint_defs::{declare_lint_pass, declare_tool_lint}; -use rustc_middle::ty::{self, ClausePolarity, GenericArgsRef}; +use rustc_middle::ty::{self, ClausePolarity, GenericArgs}; use rustc_span::hygiene::{ExpnKind, MacroKind}; use rustc_span::{DUMMY_SP, Span, sym}; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; @@ -126,7 +126,7 @@ impl<'tcx> LateLintPass<'tcx> for QueryStability { fn has_unstable_into_iter_predicate<'tcx>( cx: &LateContext<'tcx>, callee_def_id: DefId, - generic_args: GenericArgsRef<'tcx>, + generic_args: GenericArgs<'tcx>, ) -> bool { let Some(into_iterator_def_id) = cx.tcx.get_diagnostic_item(sym::IntoIterator) else { return false; @@ -173,7 +173,7 @@ fn has_unstable_into_iter_predicate<'tcx>( fn get_callee_span_generic_args_and_args<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, -) -> Option<(DefId, Span, GenericArgsRef<'tcx>, Option<&'tcx Expr<'tcx>>, &'tcx [Expr<'tcx>])> { +) -> Option<(DefId, Span, GenericArgs<'tcx>, Option<&'tcx Expr<'tcx>>, &'tcx [Expr<'tcx>])> { if let ExprKind::Call(callee, args) = expr.kind && let callee_ty = cx.typeck_results().expr_ty(callee) && let ty::FnDef(callee_def_id, generic_args) = callee_ty.kind() diff --git a/compiler/rustc_lint/src/reference_casting.rs b/compiler/rustc_lint/src/reference_casting.rs index d61dfb5b03932..97f33806d3023 100644 --- a/compiler/rustc_lint/src/reference_casting.rs +++ b/compiler/rustc_lint/src/reference_casting.rs @@ -276,7 +276,7 @@ fn is_ty_fully_unsafe_celled<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool } variant.fields.iter().all(|field| { - let field_ty = field.ty(cx.tcx, args).skip_norm_wip(); + let field_ty = field.ty(cx.tcx, *args).skip_norm_wip(); inner(cx, field_ty, depth + 1) }) } diff --git a/compiler/rustc_lint/src/runtime_symbols.rs b/compiler/rustc_lint/src/runtime_symbols.rs index f0e186c34ca0f..a49a69ceb8d26 100644 --- a/compiler/rustc_lint/src/runtime_symbols.rs +++ b/compiler/rustc_lint/src/runtime_symbols.rs @@ -117,7 +117,7 @@ impl<'tcx> LateLintPass<'tcx> for RuntimeSymbols { let did = item.owner_id.def_id; let instance = Instance::new_raw( did.to_def_id(), - ty::List::identity_for_item(cx.tcx, did), + ty::GenericArgs::identity_for_item(cx.tcx, did), ); let symbol_name = cx.tcx.symbol_name(instance); diff --git a/compiler/rustc_lint/src/types.rs b/compiler/rustc_lint/src/types.rs index 08c0e8d6f2557..b66e06a93a074 100644 --- a/compiler/rustc_lint/src/types.rs +++ b/compiler/rustc_lint/src/types.rs @@ -833,7 +833,7 @@ fn ty_is_known_nonnull<'tcx>( } def.variants().iter().filter_map(|variant| transparent_newtype_field(tcx, variant)).any( - |field| ty_is_known_nonnull(tcx, typing_env, field.ty(tcx, args).skip_norm_wip()), + |field| ty_is_known_nonnull(tcx, typing_env, field.ty(tcx, *args).skip_norm_wip()), ) } ty::Pat(base, pat) => { @@ -955,10 +955,10 @@ pub(crate) fn repr_nullable_ptr<'tcx>( ty::Adt(ty_def, args) => { let field_ty = match &ty_def.variants().raw[..] { [var_one, var_two] => match (&var_one.fields.raw[..], &var_two.fields.raw[..]) { - ([], [field]) | ([field], []) => field.ty(tcx, args).skip_norm_wip(), + ([], [field]) | ([field], []) => field.ty(tcx, *args).skip_norm_wip(), ([field1], [field2]) => { - let ty1 = field1.ty(tcx, args).skip_norm_wip(); - let ty2 = field2.ty(tcx, args).skip_norm_wip(); + let ty1 = field1.ty(tcx, *args).skip_norm_wip(); + let ty2 = field2.ty(tcx, *args).skip_norm_wip(); if is_niche_optimization_candidate(tcx, typing_env, ty1) { ty2 diff --git a/compiler/rustc_lint/src/types/improper_ctypes.rs b/compiler/rustc_lint/src/types/improper_ctypes.rs index 94a17ec1aef4f..646824c00d5b5 100644 --- a/compiler/rustc_lint/src/types/improper_ctypes.rs +++ b/compiler/rustc_lint/src/types/improper_ctypes.rs @@ -12,7 +12,7 @@ use rustc_hir::intravisit::Visitor; use rustc_hir::{self as hir, AmbigArg}; use rustc_lint_defs::{declare_lint, impl_lint_pass}; use rustc_middle::ty::{ - self, Adt, AdtDef, AdtKind, GenericArgsRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, + self, Adt, AdtDef, AdtKind, GenericArgs, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, Unnormalized, }; use rustc_span::def_id::LocalDefId; @@ -573,7 +573,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { // (mid-retcon-commit-chain comment:) // this is the original fallback behavior, which is wrong if let ty::Adt(def, args) = ty.kind() { - self.visit_struct_or_union(state, ty, *def, args) + self.visit_struct_or_union(state, ty, *def, *args) } else if cfg!(debug_assertions) { bug!("ImproperCTypes: this retcon commit was badly written") } else { @@ -617,7 +617,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { ty: Ty<'tcx>, def: AdtDef<'tcx>, variant: &ty::VariantDef, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> FfiResult<'tcx> { use FfiResult::*; @@ -672,7 +672,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { state: VisitorState, ty: Ty<'tcx>, def: AdtDef<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> FfiResult<'tcx> { debug_assert!(matches!(def.adt_kind(), AdtKind::Struct | AdtKind::Union)); use FfiResult::*; @@ -734,7 +734,7 @@ impl<'a, 'tcx> ImproperCTypesVisitor<'a, 'tcx> { state: VisitorState, ty: Ty<'tcx>, def: AdtDef<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> FfiResult<'tcx> { debug_assert!(matches!(def.adt_kind(), AdtKind::Enum)); use FfiResult::*; diff --git a/compiler/rustc_middle/src/infer/canonical.rs b/compiler/rustc_middle/src/infer/canonical.rs index 291a7b8e59f4f..40db4383d6659 100644 --- a/compiler/rustc_middle/src/infer/canonical.rs +++ b/compiler/rustc_middle/src/infer/canonical.rs @@ -30,7 +30,7 @@ pub use rustc_type_ir as ir; use smallvec::SmallVec; use crate::mir::ConstraintCategory; -use crate::ty::{self, GenericArg, GenericArgsRef, List, Ty, TyCtxt, TypeFlags, TypeVisitableExt}; +use crate::ty::{self, GenericArg, GenericArgs, List, Ty, TyCtxt, TypeFlags, TypeVisitableExt}; pub type CanonicalQueryInput<'tcx, V> = ir::CanonicalQueryInput, V>; pub type Canonical<'tcx, V> = ir::Canonical, V>; @@ -69,7 +69,7 @@ impl<'tcx> Default for OriginalQueryValues<'tcx> { /// `instantiate_query_result` to access the data in this result. #[derive(Clone, Debug, StableHash, TypeFoldable, TypeVisitable)] pub struct QueryResponse<'tcx, R> { - pub var_values: GenericArgsRef<'tcx>, + pub var_values: GenericArgs<'tcx>, pub region_constraints: QueryRegionConstraints<'tcx>, pub certainty: Certainty, pub opaque_types: Vec<(ty::OpaqueTypeKey<'tcx>, Ty<'tcx>)>, diff --git a/compiler/rustc_middle/src/middle/exported_symbols.rs b/compiler/rustc_middle/src/middle/exported_symbols.rs index e23ad3c832ef7..3186b6c0b8e0f 100644 --- a/compiler/rustc_middle/src/middle/exported_symbols.rs +++ b/compiler/rustc_middle/src/middle/exported_symbols.rs @@ -1,7 +1,7 @@ use rustc_hir::def_id::{DefId, LOCAL_CRATE}; use rustc_macros::{Decodable, Encodable, StableHash, TyDecodable, TyEncodable}; -use crate::ty::{self, GenericArgsRef, Ty, TyCtxt}; +use crate::ty::{self, GenericArgs, Ty, TyCtxt}; /// The SymbolExportLevel of a symbols specifies from which kinds of crates /// the symbol will be exported. `C` symbols will be exported from any @@ -48,7 +48,7 @@ pub struct SymbolExportInfo { #[derive(Eq, PartialEq, Debug, Copy, Clone, TyEncodable, TyDecodable, StableHash)] pub enum ExportedSymbol<'tcx> { NonGeneric(DefId), - Generic(DefId, GenericArgsRef<'tcx>), + Generic(DefId, GenericArgs<'tcx>), DropGlue(Ty<'tcx>), AsyncDropGlueCtorShim(Ty<'tcx>), AsyncDropGlue(DefId, Ty<'tcx>), diff --git a/compiler/rustc_middle/src/mir/consts.rs b/compiler/rustc_middle/src/mir/consts.rs index 95fbe87a4519a..37623cc2da369 100644 --- a/compiler/rustc_middle/src/mir/consts.rs +++ b/compiler/rustc_middle/src/mir/consts.rs @@ -11,7 +11,7 @@ use super::interpret::ReportedErrorInfo; use crate::mir::interpret::{AllocId, AllocRange, ErrorHandled, GlobalAlloc, Scalar, alloc_range}; use crate::mir::{Promoted, pretty_print_const_value}; use crate::ty::print::{pretty_print_const, with_no_trimmed_paths}; -use crate::ty::{self, ConstKind, GenericArgsRef, ScalarInt, Ty, TyCtxt}; +use crate::ty::{self, ConstKind, GenericArgs, ScalarInt, Ty, TyCtxt}; /////////////////////////////////////////////////////////////////////////// /// Evaluated Constants @@ -465,7 +465,7 @@ impl<'tcx> Const<'tcx> { #[derive(Hash, StableHash, TypeFoldable, TypeVisitable, Lift)] pub struct UnevaluatedConst<'tcx> { pub def: DefId, - pub args: GenericArgsRef<'tcx>, + pub args: GenericArgs<'tcx>, pub promoted: Option, } @@ -493,7 +493,7 @@ impl<'tcx> UnevaluatedConst<'tcx> { impl<'tcx> UnevaluatedConst<'tcx> { #[inline] - pub fn new(def: DefId, args: GenericArgsRef<'tcx>) -> UnevaluatedConst<'tcx> { + pub fn new(def: DefId, args: GenericArgs<'tcx>) -> UnevaluatedConst<'tcx> { UnevaluatedConst { def, args, promoted: Default::default() } } diff --git a/compiler/rustc_middle/src/mir/mod.rs b/compiler/rustc_middle/src/mir/mod.rs index ebcc2da09551e..f12f6cdd5901b 100644 --- a/compiler/rustc_middle/src/mir/mod.rs +++ b/compiler/rustc_middle/src/mir/mod.rs @@ -32,7 +32,7 @@ use crate::mir::interpret::{AllocRange, Scalar}; use crate::ty::codec::{TyDecoder, TyEncoder}; use crate::ty::print::{FmtPrinter, Printer, pretty_print_const, with_no_trimmed_paths}; use crate::ty::{ - self, GenericArg, GenericArgsRef, Instance, InstanceKind, List, ShimKind, Ty, TyCtxt, + self, GenericArg, GenericArgs, Instance, InstanceKind, List, ShimKind, Ty, TyCtxt, TypeVisitableExt, TypingEnv, UserTypeAnnotationIndex, }; @@ -1695,7 +1695,7 @@ pub fn find_self_call<'tcx>( body: &Body<'tcx>, local: Local, block: BasicBlock, -) -> Option<(DefId, GenericArgsRef<'tcx>)> { +) -> Option<(DefId, GenericArgs<'tcx>)> { debug!("find_self_call(local={:?}): terminator={:?}", local, body[block].terminator); if let Some(Terminator { kind: TerminatorKind::Call { func, args, .. }, .. }) = &body[block].terminator diff --git a/compiler/rustc_middle/src/mir/statement.rs b/compiler/rustc_middle/src/mir/statement.rs index 22366f70fbe4e..a53f51fc9512a 100644 --- a/compiler/rustc_middle/src/mir/statement.rs +++ b/compiler/rustc_middle/src/mir/statement.rs @@ -145,7 +145,7 @@ impl<'tcx> PlaceTy<'tcx> { } else { match self_ty.kind() { ty::Adt(adt_def, args) if !adt_def.is_enum() => { - adt_def.non_enum_variant().fields[f].ty(tcx, args) + adt_def.non_enum_variant().fields[f].ty(tcx, *args) } ty::Closure(_, args) => Unnormalized::dummy( args.as_closure() @@ -448,7 +448,7 @@ impl<'tcx> Place<'tcx> { let ty = self.ty(local_decls, tcx).ty; let ty::Adt(adt, args) = ty.kind() else { panic!("projecting to field of non-ADT {ty}") }; let field = &adt.non_enum_variant().fields[idx]; - let field_ty = field.ty(tcx, args).skip_norm_wip(); + let field_ty = field.ty(tcx, *args).skip_norm_wip(); self.project_deeper(&[ProjectionElem::Field(idx, field_ty)], tcx) } @@ -638,7 +638,7 @@ impl<'tcx> Operand<'tcx> { pub fn unevaluated_constant( tcx: TyCtxt<'tcx>, def_id: DefId, - args: &[GenericArg<'tcx>], + args: GenericArgs<'tcx>, span: Span, ) -> Self { let const_ = Const::from_unevaluated(tcx, def_id).instantiate(tcx, args).skip_norm_wip(); @@ -711,7 +711,7 @@ impl<'tcx> Operand<'tcx> { /// /// While this is unlikely in general, it's the normal case of what you'll /// find as the `func` in a [`TerminatorKind::Call`]. - pub fn const_fn_def(&self) -> Option<(DefId, GenericArgsRef<'tcx>)> { + pub fn const_fn_def(&self) -> Option<(DefId, GenericArgs<'tcx>)> { let const_ty = self.constant()?.const_.ty(); if let ty::FnDef(def_id, args) = *const_ty.kind() { Some((def_id, args.no_bound_vars().unwrap())) diff --git a/compiler/rustc_middle/src/mir/syntax.rs b/compiler/rustc_middle/src/mir/syntax.rs index b0462a8c2bd28..51c86daf82294 100644 --- a/compiler/rustc_middle/src/mir/syntax.rs +++ b/compiler/rustc_middle/src/mir/syntax.rs @@ -20,7 +20,7 @@ use thin_vec::ThinVec; use super::{BasicBlock, Const, Local, UserTypeProjection}; use crate::mir::coverage::CoverageKind; use crate::ty::adjustment::PointerCoercion; -use crate::ty::{self, GenericArgsRef, List, Region, Ty, UserTypeAnnotationIndex}; +use crate::ty::{self, GenericArgs, List, Region, Ty, UserTypeAnnotationIndex}; /// Represents the "flavors" of MIR. /// @@ -1559,11 +1559,11 @@ pub enum AggregateKind<'tcx> { /// active field number and is present only for union expressions /// -- e.g., for a union expression `SomeUnion { c: .. }`, the /// active field index would identity the field `c` - Adt(DefId, VariantIdx, GenericArgsRef<'tcx>, Option, Option), + Adt(DefId, VariantIdx, GenericArgs<'tcx>, Option, Option), - Closure(DefId, GenericArgsRef<'tcx>), - Coroutine(DefId, GenericArgsRef<'tcx>), - CoroutineClosure(DefId, GenericArgsRef<'tcx>), + Closure(DefId, GenericArgs<'tcx>), + Coroutine(DefId, GenericArgs<'tcx>), + CoroutineClosure(DefId, GenericArgs<'tcx>), /// Construct a raw pointer from the data pointer and metadata. /// diff --git a/compiler/rustc_middle/src/mir/visit.rs b/compiler/rustc_middle/src/mir/visit.rs index 2bbe41bdad09f..2fc07d1c43cd3 100644 --- a/compiler/rustc_middle/src/mir/visit.rs +++ b/compiler/rustc_middle/src/mir/visit.rs @@ -246,7 +246,7 @@ macro_rules! make_mir_visitor { fn visit_args( &mut self, - args: & $($mutability)? GenericArgsRef<'tcx>, + args: & $($mutability)? GenericArgs<'tcx>, _: Location, ) { self.super_args(args); @@ -986,7 +986,7 @@ macro_rules! make_mir_visitor { fn super_region(&mut self, _region: $(& $mutability)? ty::Region<'tcx>) {} - fn super_args(&mut self, _args: & $($mutability)? GenericArgsRef<'tcx>) {} + fn super_args(&mut self, _args: & $($mutability)? GenericArgs<'tcx>) {} // Convenience methods diff --git a/compiler/rustc_middle/src/mono.rs b/compiler/rustc_middle/src/mono.rs index cf567fa1c8999..afefe410d3043 100644 --- a/compiler/rustc_middle/src/mono.rs +++ b/compiler/rustc_middle/src/mono.rs @@ -278,7 +278,7 @@ impl<'tcx> MonoItem<'tcx> { MonoItem::GlobalAsm(..) => return true, }; - !tcx.instantiate_and_check_impossible_clauses((def_id, &args)) + !tcx.instantiate_and_check_impossible_clauses((def_id, args)) } pub fn local_span(&self, tcx: TyCtxt<'tcx>) -> Option { diff --git a/compiler/rustc_middle/src/queries.rs b/compiler/rustc_middle/src/queries.rs index 56889f84f38d6..2f69ff2122e39 100644 --- a/compiler/rustc_middle/src/queries.rs +++ b/compiler/rustc_middle/src/queries.rs @@ -117,7 +117,7 @@ use crate::ty::layout::ValidityRequirement; use crate::ty::print::PrintTraitRefExt; use crate::ty::util::AlwaysRequiresDrop; use crate::ty::{ - self, CrateInherentImpls, GenericArg, GenericArgsRef, LitToConstInput, PseudoCanonicalInput, + self, CrateInherentImpls, GenericArg, GenericArgs, LitToConstInput, PseudoCanonicalInput, RequiredDepth, SizedTraitKind, Ty, TyCtxt, TyCtxtFeed, }; use crate::{mir, thir}; @@ -1325,7 +1325,7 @@ rustc_queries! { } /// Obtain all the calls into other local functions - query mir_inliner_callees(key: ty::InstanceKind<'tcx>) -> &'tcx [(DefId, GenericArgsRef<'tcx>)] { + query mir_inliner_callees(key: ty::InstanceKind<'tcx>) -> &'tcx [(DefId, GenericArgs<'tcx>)] { desc { "computing all local function calls in `{}`", tcx.def_path_str(key.def_id()), @@ -1966,7 +1966,7 @@ rustc_queries! { /// crate. Instead use the narrower `upstream_monomorphizations_for`, /// `upstream_drop_glue_for`, `upstream_async_drop_glue_for`, or, /// even better, `Instance::upstream_monomorphization()`. - query upstream_monomorphizations(_: ()) -> &'tcx DefIdMap, CrateNum>> { + query upstream_monomorphizations(_: ()) -> &'tcx DefIdMap, CrateNum>> { arena_cache desc { "collecting available upstream monomorphizations" } } @@ -1979,7 +1979,7 @@ rustc_queries! { /// You likely want to call `Instance::upstream_monomorphization()` /// instead of invoking this query directly. query upstream_monomorphizations_for(def_id: DefId) - -> Option<&'tcx UnordMap, CrateNum>> + -> Option<&'tcx UnordMap, CrateNum>> { desc { "collecting available upstream monomorphizations for `{}`", @@ -2003,7 +2003,7 @@ rustc_queries! { /// NOTE: This query could easily be extended to also support other /// common functions that have are large set of monomorphizations /// (like `Clone::clone` for example). - query upstream_drop_glue_for(args: GenericArgsRef<'tcx>) -> Option { + query upstream_drop_glue_for(args: GenericArgs<'tcx>) -> Option { desc { "available upstream drop-glue for `{:?}`", args } } @@ -2023,7 +2023,7 @@ rustc_queries! { /// NOTE: This query could easily be extended to also support other /// common functions that have are large set of monomorphizations /// (like `Clone::clone` for example). - query upstream_async_drop_glue_for(args: GenericArgsRef<'tcx>) -> Option { + query upstream_async_drop_glue_for(args: GenericArgs<'tcx>) -> Option { desc { "available upstream async-drop-glue for `{:?}`", args } } @@ -2110,7 +2110,7 @@ rustc_queries! { desc { "inheriting delegation signature" } } - query delegation_user_specified_args(def_id: LocalDefId) -> (&'tcx [GenericArg<'tcx>], &'tcx [GenericArg<'tcx>]) { + query delegation_user_specified_args(def_id: LocalDefId) -> (ty::GenericArgs<'tcx>, ty::GenericArgs<'tcx>) { desc { "getting delegation user-specified args" } } @@ -2225,7 +2225,7 @@ rustc_queries! { } /// Do not call this query directly: invoke `Ty::is_opsem_inhabited` instead. - query is_opsem_inhabited_adt_cached(env: ty::PseudoCanonicalInput<'tcx, (ty::AdtDef<'tcx>, ty::GenericArgsRef<'tcx>)>) -> bool { + query is_opsem_inhabited_adt_cached(env: ty::PseudoCanonicalInput<'tcx, (ty::AdtDef<'tcx>, ty::GenericArgs<'tcx>)>) -> bool { desc { "computing whether `{:?}` is inhabited on the opsem level", env.value } } @@ -2647,7 +2647,7 @@ rustc_queries! { desc { "normalizing `{:?}`", goal.canonical.value.value.value.skip_normalization() } } - query instantiate_and_check_impossible_clauses(key: (DefId, GenericArgsRef<'tcx>)) -> bool { + query instantiate_and_check_impossible_clauses(key: (DefId, GenericArgs<'tcx>)) -> bool { desc { "checking impossible instantiated clauses: `{}`", tcx.def_path_str(key.0) @@ -2702,16 +2702,16 @@ rustc_queries! { } /// Attempt to resolve the given `DefId` to an `Instance`, for the - /// given generics args (`GenericArgsRef`), returning one of: + /// given generics args (`GenericArgs`), returning one of: /// * `Ok(Some(instance))` on success - /// * `Ok(None)` when the `GenericArgsRef` are still too generic, + /// * `Ok(None)` when the `GenericArgs` are still too generic, /// and therefore don't allow finding the final `Instance` /// * `Err(ErrorGuaranteed)` when the `Instance` resolution process /// couldn't complete due to errors elsewhere - this is distinct /// from `Ok(None)` to avoid misleading diagnostics when an error /// has already been/will be emitted, for the original cause. query resolve_instance_raw( - key: ty::PseudoCanonicalInput<'tcx, (DefId, GenericArgsRef<'tcx>)> + key: ty::PseudoCanonicalInput<'tcx, (DefId, GenericArgs<'tcx>)> ) -> Result>, ErrorGuaranteed> { desc { "resolving instance `{}`", ty::Instance::new_raw(key.value.0, key.value.1) } } diff --git a/compiler/rustc_middle/src/query/erase.rs b/compiler/rustc_middle/src/query/erase.rs index b0281a70eeb73..cee5bf6dccb80 100644 --- a/compiler/rustc_middle/src/query/erase.rs +++ b/compiler/rustc_middle/src/query/erase.rs @@ -178,6 +178,7 @@ impl_erasable_for_types_with_no_type_params! { &'_ str, (&'_ ty::CrateInherentImpls, Result<(), ErrorGuaranteed>), (), + (rustc_middle::ty::GenericArgs<'_>, rustc_middle::ty::GenericArgs<'_>), (traits::solve::QueryResult<'_>, &'_ traits::solve::inspect::Probe>, ty::RequiredDepth), Option<&'_ OsStr>, Option<&'_ [rustc_hir::PreciseCapturingArgKind]>, @@ -250,6 +251,7 @@ impl_erasable_for_types_with_no_type_params! { rustc_middle::ty::ClosureTypeInfo<'_>, rustc_middle::ty::Const<'_>, rustc_middle::ty::ConstConditions<'_>, + rustc_middle::ty::GenericArgs<'_>, rustc_middle::ty::GenericClauses<'_>, rustc_middle::ty::ImplTraitHeader<'_>, rustc_middle::ty::ParamEnv<'_>, diff --git a/compiler/rustc_middle/src/query/keys.rs b/compiler/rustc_middle/src/query/keys.rs index 2bfe80f444090..c3d8ffbf4de3b 100644 --- a/compiler/rustc_middle/src/query/keys.rs +++ b/compiler/rustc_middle/src/query/keys.rs @@ -18,7 +18,7 @@ use crate::mono::CollectionMode; use crate::query::{DefIdCache, DefaultCache, SingleCache, VecCache}; use crate::ty::fast_reject::SimplifiedType; use crate::ty::layout::ValidityRequirement; -use crate::ty::{self, GenericArg, GenericArgsRef, Ty, TyCtxt}; +use crate::ty::{self, GenericArg, GenericArgs, Ty, TyCtxt}; use crate::{mir, traits}; /// Placeholder for `CrateNum`'s "local" counterpart @@ -248,13 +248,13 @@ impl QueryKey for (DefId, ty::SizedTraitKind) { } } -impl<'tcx> QueryKey for GenericArgsRef<'tcx> { +impl<'tcx> QueryKey for GenericArgs<'tcx> { fn default_span(&self, _: TyCtxt<'_>) -> Span { DUMMY_SP } } -impl<'tcx> QueryKey for (DefId, GenericArgsRef<'tcx>) { +impl<'tcx> QueryKey for (DefId, GenericArgs<'tcx>) { fn default_span(&self, tcx: TyCtxt<'_>) -> Span { self.0.default_span(tcx) } @@ -308,7 +308,7 @@ impl<'tcx, T: QueryKey> QueryKey for ty::PseudoCanonicalInput<'tcx, T> { } } -impl<'tcx> QueryKey for (ty::AdtDef<'tcx>, ty::GenericArgsRef<'tcx>) { +impl<'tcx> QueryKey for (ty::AdtDef<'tcx>, ty::GenericArgs<'tcx>) { fn default_span(&self, tcx: TyCtxt<'_>) -> Span { tcx.def_span(self.0.did()) } diff --git a/compiler/rustc_middle/src/thir.rs b/compiler/rustc_middle/src/thir.rs index 1205c5813a679..9e8c28452299a 100644 --- a/compiler/rustc_middle/src/thir.rs +++ b/compiler/rustc_middle/src/thir.rs @@ -35,8 +35,8 @@ use crate::thir::visit::for_each_immediate_subpat; use crate::ty::adjustment::PointerCoercion; use crate::ty::layout::IntegerExt; use crate::ty::{ - self, AdtDef, CanonicalUserType, CanonicalUserTypeAnnotation, FnSig, GenericArgsRef, Ty, - TyCtxt, UpvarArgs, + self, AdtDef, CanonicalUserType, CanonicalUserTypeAnnotation, FnSig, GenericArgs, Ty, TyCtxt, + UpvarArgs, }; pub mod visit; @@ -147,7 +147,7 @@ pub struct AdtExpr<'tcx> { pub adt_def: AdtDef<'tcx>, /// The variant of the ADT. pub variant_index: VariantIdx, - pub args: GenericArgsRef<'tcx>, + pub args: GenericArgs<'tcx>, /// Optional user-given args: for something like `let x = /// Bar:: { ... }`. @@ -466,7 +466,7 @@ pub enum ExprKind<'tcx> { /// An inline `const` block, e.g. `const {}`. ConstBlock { did: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, }, /// An array literal constructed from one repeated element, e.g. `[1; 5]`. Repeat { @@ -529,7 +529,7 @@ pub enum ExprKind<'tcx> { /// Associated constants and named constants NamedConst { def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, user_ty: UserTy<'tcx>, }, ConstParam { @@ -795,7 +795,7 @@ pub enum PatKind<'tcx> { /// multiple variants. Variant { adt_def: AdtDef<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, variant_index: VariantIdx, subpatterns: Vec>, }, diff --git a/compiler/rustc_middle/src/traits/mod.rs b/compiler/rustc_middle/src/traits/mod.rs index 7c4c2d5aed157..6d07a4a5269f3 100644 --- a/compiler/rustc_middle/src/traits/mod.rs +++ b/compiler/rustc_middle/src/traits/mod.rs @@ -29,7 +29,7 @@ pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, Selecti use crate::mir::ConstraintCategory; pub use crate::traits::solve::BuiltinImplSource; use crate::ty::abstract_const::NotConstEvaluatable; -use crate::ty::{self, AdtKind, GenericArgsRef, Ty}; +use crate::ty::{self, AdtKind, GenericArgs, Ty}; /// The reason why we incurred this obligation; used for error reporting. /// @@ -754,7 +754,7 @@ impl<'tcx, N> ImplSource<'tcx, N> { #[derive(TypeFoldable, TypeVisitable)] pub struct ImplSourceUserDefinedData<'tcx, N> { pub impl_def_id: DefId, - pub args: GenericArgsRef<'tcx>, + pub args: GenericArgs<'tcx>, pub nested: ThinVec, } diff --git a/compiler/rustc_middle/src/ty/adt.rs b/compiler/rustc_middle/src/ty/adt.rs index d0c4f08ae57fb..e93059f5216c2 100644 --- a/compiler/rustc_middle/src/ty/adt.rs +++ b/compiler/rustc_middle/src/ty/adt.rs @@ -228,7 +228,7 @@ impl<'tcx> AdtDef<'tcx> { pub fn field_representing_type_info( self, tcx: TyCtxt<'tcx>, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Option>> { if !self.is_field_representing_type() { return None; @@ -246,7 +246,7 @@ impl<'tcx> AdtDef<'tcx> { ty::Adt(base_def, base_args) => { let variant = base_def.variant(variant_idx); let field = &variant.fields[field_idx]; - let ty = field.ty(tcx, base_args).skip_norm_wip(); + let ty = field.ty(tcx, *base_args).skip_norm_wip(); (ty, base_def.is_enum().then_some(variant.name), field.name) } ty::Tuple(tys) => { @@ -300,7 +300,7 @@ impl<'tcx> rustc_type_ir::inherent::AdtDef> for AdtDef<'tcx> { fn field_representing_type_info( self, tcx: TyCtxt<'tcx>, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Option>> { self.field_representing_type_info(tcx, args) } diff --git a/compiler/rustc_middle/src/ty/codec.rs b/compiler/rustc_middle/src/ty/codec.rs index 81462e214b20f..a8d78ca01bcaa 100644 --- a/compiler/rustc_middle/src/ty/codec.rs +++ b/compiler/rustc_middle/src/ty/codec.rs @@ -18,7 +18,7 @@ pub use self::ref_decodable::RefDecodable; use crate::infer::canonical::{CanonicalVarKind, CanonicalVarKinds}; use crate::mir; use crate::mir::interpret::{AllocId, ConstAllocation, CtfeProvenance}; -use crate::ty::{self, AdtDef, GenericArgsRef, Ty, TyCtxt}; +use crate::ty::{self, AdtDef, GenericArgs, Ty, TyCtxt}; mod ref_decodable; @@ -230,7 +230,7 @@ impl<'tcx, D: TyDecoder<'tcx>> Decodable for ty::Clause<'tcx> { } } -impl<'tcx, D: TyDecoder<'tcx>> Decodable for GenericArgsRef<'tcx> { +impl<'tcx, D: TyDecoder<'tcx>> Decodable for GenericArgs<'tcx> { fn decode(decoder: &mut D) -> Self { let len = decoder.read_usize(); let tcx = decoder.interner(); diff --git a/compiler/rustc_middle/src/ty/consts/kind.rs b/compiler/rustc_middle/src/ty/consts/kind.rs index b089871b671a0..0728db816ee35 100644 --- a/compiler/rustc_middle/src/ty/consts/kind.rs +++ b/compiler/rustc_middle/src/ty/consts/kind.rs @@ -20,11 +20,11 @@ pub enum ExprKind { #[derive(StableHash, TyEncodable, TyDecodable, TypeVisitable, TypeFoldable)] pub struct Expr<'tcx> { pub kind: ExprKind, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, } impl<'tcx> rustc_type_ir::inherent::ExprConst> for Expr<'tcx> { - fn args(self) -> ty::GenericArgsRef<'tcx> { + fn args(self) -> ty::GenericArgs<'tcx> { self.args } } @@ -90,14 +90,15 @@ impl<'tcx> Expr<'tcx> { Self { kind: ExprKind::FunctionCall, args } } - pub fn call_args(self) -> (Ty<'tcx>, Const<'tcx>, impl Iterator>) { + pub fn call_args(self) -> (Ty<'tcx>, Const<'tcx>, Vec>) { assert_matches!(self.kind, ExprKind::FunctionCall); - match self.args().as_slice() { + let args = self.args(); + match args.as_slice() { [func_ty, func, rest @ ..] => ( func_ty.expect_ty(), func.expect_const(), - rest.iter().map(|arg| arg.expect_const()), + rest.iter().map(|arg| arg.expect_const()).collect(), ), _ => bug!("Invalid args for `Call` expr {self:?}"), } @@ -128,11 +129,11 @@ impl<'tcx> Expr<'tcx> { } } - pub fn new(kind: ExprKind, args: ty::GenericArgsRef<'tcx>) -> Self { + pub fn new(kind: ExprKind, args: ty::GenericArgs<'tcx>) -> Self { Self { kind, args } } - pub fn args(self) -> ty::GenericArgsRef<'tcx> { + pub fn args(self) -> ty::GenericArgs<'tcx> { self.args } } diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 2e71a7c72603d..179d3056294ee 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -74,10 +74,10 @@ use crate::traits::solve::{ use crate::ty::predicate::ExistentialPredicateStableCmpExt as _; use crate::ty::{ self, AdtDef, AdtDefData, AdtKind, Binder, Clause, ClausePolarity, Clauses, Const, ConstKind, - FnSigKind, GenericArg, GenericArgs, GenericArgsRef, GenericParamDefKind, List, - ListWithCachedTypeInfo, ParamConst, Pattern, PatternKind, PolyExistentialPredicate, PolyFnSig, - Predicate, PredicateKind, Region, RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, - TyVid, ValTree, ValTreeKind, Visibility, + FnSigKind, GenericArg, GenericArgsUnsized, GenericParamDefKind, List, ListWithCachedTypeInfo, + ParamConst, Pattern, PatternKind, PolyExistentialPredicate, PolyFnSig, Predicate, + PredicateKind, Region, RegionKind, ReprOptions, TraitObjectVisitor, Ty, TyKind, TyVid, ValTree, + ValTreeKind, Visibility, }; impl<'tcx> rustc_type_ir::inherent::DefId> for DefId { @@ -145,7 +145,7 @@ pub struct CtxtInterners<'tcx> { // they're accessed quite often. type_: InternedSet<'tcx, WithCachedTypeInfo>>, const_lists: InternedSet<'tcx, List>>, - args: InternedSet<'tcx, GenericArgs<'tcx>>, + args: InternedSet<'tcx, GenericArgsUnsized<'tcx>>, type_lists: InternedSet<'tcx, List>>, canonical_var_kinds: InternedSet<'tcx, List>>, region: InternedSet<'tcx, RegionKind<'tcx>>, @@ -2080,7 +2080,7 @@ macro_rules! slice_interners { // should be used when possible, because it's faster. slice_interners!( const_lists: pub mk_const_list(Const<'tcx>), - args: pub mk_args(GenericArg<'tcx>), + args: pub mk_args_raw(GenericArg<'tcx>), type_lists: pub mk_type_list(Ty<'tcx>), canonical_var_kinds: pub mk_canonical_var_kinds(CanonicalVarKind<'tcx>), poly_existential_predicates: intern_poly_existential_predicates(PolyExistentialPredicate<'tcx>), @@ -2189,16 +2189,16 @@ impl<'tcx> TyCtxt<'tcx> { /// consts always have `impl`-form args, and will return an invalid result if the `def_id` comes /// from a [`ty::AliasConstKind::InherentSelf`] (see the doc on that for what "impl form args" /// means). - pub fn check_args_compatible(self, def_id: DefId, args: &'tcx [ty::GenericArg<'tcx>]) -> bool { + pub fn check_args_compatible(self, def_id: DefId, args: ty::GenericArgs<'tcx>) -> bool { let is_inherent_assoc_ty = matches!(self.def_kind(def_id), DefKind::AssocTy) && matches!(self.def_kind(self.parent(def_id)), DefKind::Impl { of_trait: false }); - self.check_args_compatible_inner(def_id, args, is_inherent_assoc_ty) + self.check_args_compatible_inner(def_id, args.as_slice(), is_inherent_assoc_ty) } pub fn check_alias_term_args_compatible( self, kind: ty::AliasTermKind<'tcx>, - args: &'tcx [ty::GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> bool { let (def_id, is_self_args) = match kind { ty::AliasTermKind::ProjectionTy { def_id } @@ -2211,13 +2211,13 @@ impl<'tcx> TyCtxt<'tcx> { ty::AliasTermKind::InherentTy { def_id } | ty::AliasTermKind::InherentConstSelf { def_id } => (def_id, true), }; - self.check_args_compatible_inner(def_id, args, is_self_args) + self.check_args_compatible_inner(def_id, args.as_slice(), is_self_args) } fn check_args_compatible_inner( self, def_id: DefId, - args: &'tcx [ty::GenericArg<'tcx>], + args: &[ty::GenericArg<'tcx>], is_self_args: bool, ) -> bool { let generics = self.generics_of(def_id); @@ -2268,7 +2268,7 @@ impl<'tcx> TyCtxt<'tcx> { /// If you have a [`ty::Alias`], you should use /// [`Self::debug_assert_alias_term_args_compatible`] instead. See note on /// [`Self::check_args_compatible`]. - pub fn debug_assert_args_compatible(self, def_id: DefId, args: &'tcx [ty::GenericArg<'tcx>]) { + pub fn debug_assert_args_compatible(self, def_id: DefId, args: ty::GenericArgs<'tcx>) { if cfg!(debug_assertions) && !self.check_args_compatible(def_id, args) { let is_inherent_assoc_ty = matches!(self.def_kind(def_id), DefKind::AssocTy) && matches!(self.def_kind(self.parent(def_id)), DefKind::Impl { of_trait: false }); @@ -2279,7 +2279,7 @@ impl<'tcx> TyCtxt<'tcx> { pub fn debug_assert_alias_term_args_compatible( self, kind: ty::AliasTermKind<'tcx>, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) { if cfg!(debug_assertions) { self.debug_assert_alias_term_kind_matches_def_kind(kind); @@ -2349,7 +2349,7 @@ impl<'tcx> TyCtxt<'tcx> { fn emit_bug_args_compatible( self, def_id: DefId, - args: &'tcx [ty::GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, is_self_args: bool, ) -> ! { if is_self_args { @@ -2361,7 +2361,7 @@ impl<'tcx> TyCtxt<'tcx> { self.mk_args_from_iter( [self.types.self_param.into()].into_iter().chain( self.generics_of(def_id) - .own_args(ty::GenericArgs::identity_for_item(self, def_id)) + .own_args(ty::GenericArgs::identity_for_item(self, def_id).as_slice()) .iter() .copied() ) @@ -2382,7 +2382,7 @@ impl<'tcx> TyCtxt<'tcx> { self, def_id: DefId, args: impl IntoIterator>>, - ) -> GenericArgsRef<'tcx> { + ) -> ty::GenericArgs<'tcx> { let args = self.mk_args_from_iter(args.into_iter().map(Into::into)); self.debug_assert_args_compatible(def_id, args); args @@ -2604,10 +2604,14 @@ impl<'tcx> TyCtxt<'tcx> { T::collect_and_apply(iter, |xs| self.mk_type_list(xs)) } + pub fn mk_args(self, args: &[GenericArg<'tcx>]) -> ty::GenericArgs<'tcx> { + ty::GenericArgs::from_args(self.mk_args_raw(args)) + } + pub fn mk_args_from_iter(self, iter: I) -> T::Output where I: Iterator, - T: CollectAndApply, ty::GenericArgsRef<'tcx>>, + T: CollectAndApply, ty::GenericArgs<'tcx>>, { T::collect_and_apply(iter, |xs| self.mk_args(xs)) } @@ -2640,7 +2644,7 @@ impl<'tcx> TyCtxt<'tcx> { self, self_ty: Ty<'tcx>, rest: impl IntoIterator>, - ) -> GenericArgsRef<'tcx> { + ) -> ty::GenericArgs<'tcx> { self.mk_args_from_iter(iter::once(self_ty.into()).chain(rest)) } diff --git a/compiler/rustc_middle/src/ty/context/impl_interner.rs b/compiler/rustc_middle/src/ty/context/impl_interner.rs index e849f3076a9f3..7f1501e45913e 100644 --- a/compiler/rustc_middle/src/ty/context/impl_interner.rs +++ b/compiler/rustc_middle/src/ty/context/impl_interner.rs @@ -61,9 +61,12 @@ impl<'tcx> Interner for TyCtxt<'tcx> { type InherentAssocTermId = DefId; type Span = Span; - type GenericArgs = ty::GenericArgsRef<'tcx>; + type GenericArgs = ty::GenericArgs<'tcx>; - type GenericArgsSlice = &'tcx [ty::GenericArg<'tcx>]; + type GenericArgsSlice<'a> + = &'a [ty::GenericArg<'tcx>] + where + Self: 'a; type GenericArg = ty::GenericArg<'tcx>; type Term = ty::Term<'tcx>; type BoundVarKinds = &'tcx List>; @@ -220,26 +223,26 @@ impl<'tcx> Interner for TyCtxt<'tcx> { self.adt_def(adt_def_id) } - fn trait_ref_and_own_args_for_alias( + fn trait_ref_and_own_args_for_alias<'a>( self, def_id: DefId, - args: ty::GenericArgsRef<'tcx>, - ) -> (ty::TraitRef<'tcx>, &'tcx [ty::GenericArg<'tcx>]) { + args: &'a ty::GenericArgs<'tcx>, + ) -> (ty::TraitRef<'tcx>, &'a [ty::GenericArg<'tcx>]) { debug_assert_matches!(self.def_kind(def_id), DefKind::AssocTy | DefKind::AssocConst); let trait_def_id = self.parent(def_id); debug_assert_matches!(self.def_kind(trait_def_id), DefKind::Trait); - let trait_ref = ty::TraitRef::from_assoc(self, trait_def_id, args); - (trait_ref, &args[trait_ref.args.len()..]) + let trait_ref = ty::TraitRef::from_assoc(self, trait_def_id, *args); + (trait_ref, &args.as_slice()[trait_ref.args.len()..]) } - fn mk_args(self, args: &[Self::GenericArg]) -> ty::GenericArgsRef<'tcx> { + fn mk_args(self, args: &[Self::GenericArg]) -> ty::GenericArgs<'tcx> { self.mk_args(args) } fn mk_args_from_iter(self, args: I) -> T::Output where I: Iterator, - T: CollectAndApply>, + T: CollectAndApply>, { self.mk_args_from_iter(args) } @@ -247,19 +250,19 @@ impl<'tcx> Interner for TyCtxt<'tcx> { fn check_alias_term_args_compatible( self, kind: ty::AliasTermKind<'tcx>, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> bool { self.check_alias_term_args_compatible(kind, args) } - fn debug_assert_args_compatible(self, def_id: DefId, args: ty::GenericArgsRef<'tcx>) { + fn debug_assert_args_compatible(self, def_id: DefId, args: ty::GenericArgs<'tcx>) { self.debug_assert_args_compatible(def_id, args); } fn debug_assert_alias_term_args_compatible( self, kind: ty::AliasTermKind<'tcx>, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) { self.debug_assert_alias_term_args_compatible(kind, args); } @@ -278,7 +281,9 @@ impl<'tcx> Interner for TyCtxt<'tcx> { self.debug_assert_args_compatible( def_id, self.mk_args_from_iter( - [self.types.trait_object_dummy_self.into()].into_iter().chain(args.iter()), + [self.types.trait_object_dummy_self.into()] + .into_iter() + .chain(args.as_slice().iter().copied()), ), ); } diff --git a/compiler/rustc_middle/src/ty/generic_args.rs b/compiler/rustc_middle/src/ty/generic_args.rs index 23d716113674e..4d2d8f704f9e5 100644 --- a/compiler/rustc_middle/src/ty/generic_args.rs +++ b/compiler/rustc_middle/src/ty/generic_args.rs @@ -1,8 +1,10 @@ // Generic arguments. use core::intrinsics; +use std::fmt::Debug; use std::marker::PhantomData; use std::num::NonZero; +use std::ops::Index; use std::ptr::NonNull; use rustc_data_structures::intern::Interned; @@ -41,32 +43,32 @@ pub struct GenericArg<'tcx> { impl<'tcx> rustc_type_ir::inherent::GenericArg> for GenericArg<'tcx> {} -impl<'tcx> rustc_type_ir::inherent::GenericArgs> for ty::GenericArgsRef<'tcx> { +impl<'tcx> rustc_type_ir::inherent::GenericArgs> for ty::GenericArgs<'tcx> { fn rebase_onto( self, tcx: TyCtxt<'tcx>, source_ancestor: DefId, - target_args: GenericArgsRef<'tcx>, - ) -> GenericArgsRef<'tcx> { - self.rebase_onto(tcx, source_ancestor, target_args) + target_args: GenericArgs<'tcx>, + ) -> GenericArgs<'tcx> { + GenericArgs::rebase_onto(&self, tcx, source_ancestor, target_args) } #[track_caller] fn type_at(self, i: usize) -> Ty<'tcx> { - self.type_at(i) + GenericArgs::type_at(&self, i) } #[track_caller] fn region_at(self, i: usize) -> ty::Region<'tcx> { - self.region_at(i) + GenericArgs::region_at(&self, i) } #[track_caller] fn const_at(self, i: usize) -> ty::Const<'tcx> { - self.const_at(i) + GenericArgs::const_at(&self, i) } - fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> ty::GenericArgsRef<'tcx> { + fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> ty::GenericArgs<'tcx> { GenericArgs::identity_for_item(tcx, def_id) } @@ -74,13 +76,13 @@ impl<'tcx> rustc_type_ir::inherent::GenericArgs> for ty::GenericArg tcx: TyCtxt<'tcx>, def_id: DefId, original_args: &[ty::GenericArg<'tcx>], - ) -> ty::GenericArgsRef<'tcx> { + ) -> ty::GenericArgs<'tcx> { ty::GenericArgs::extend_with_error(tcx, def_id, original_args) } - fn split_closure_args(self) -> ty::ClosureArgsParts> { - match self[..] { - [ref parent_args @ .., closure_kind_ty, closure_sig_as_fn_ptr_ty, tupled_upvars_ty] => { + fn split_closure_args<'a>(&'a self) -> ty::ClosureArgsParts<'a, TyCtxt<'tcx>> { + match self.as_slice() { + [parent_args @ .., closure_kind_ty, closure_sig_as_fn_ptr_ty, tupled_upvars_ty] => { ty::ClosureArgsParts { parent_args, closure_kind_ty: closure_kind_ty.expect_ty(), @@ -92,10 +94,12 @@ impl<'tcx> rustc_type_ir::inherent::GenericArgs> for ty::GenericArg } } - fn split_coroutine_closure_args(self) -> ty::CoroutineClosureArgsParts> { - match self[..] { + fn split_coroutine_closure_args<'a>( + &'a self, + ) -> ty::CoroutineClosureArgsParts<'a, TyCtxt<'tcx>> { + match self.as_slice() { [ - ref parent_args @ .., + parent_args @ .., closure_kind_ty, signature_parts_ty, tupled_upvars_ty, @@ -111,9 +115,9 @@ impl<'tcx> rustc_type_ir::inherent::GenericArgs> for ty::GenericArg } } - fn split_coroutine_args(self) -> ty::CoroutineArgsParts> { - match self[..] { - [ref parent_args @ .., kind_ty, resume_ty, yield_ty, return_ty, tupled_upvars_ty] => { + fn split_coroutine_args<'a>(&'a self) -> ty::CoroutineArgsParts<'a, TyCtxt<'tcx>> { + match self.as_slice() { + [parent_args @ .., kind_ty, resume_ty, yield_ty, return_ty, tupled_upvars_ty] => { ty::CoroutineArgsParts { parent_args, kind_ty: kind_ty.expect_ty(), @@ -374,19 +378,116 @@ impl<'tcx, D: TyDecoder<'tcx>> Decodable for GenericArg<'tcx> { } } +pub type GenericArgsUnsized<'tcx> = List>; + /// List of generic arguments that are gonna be used to replace generic parameters. -pub type GenericArgs<'tcx> = List>; +#[derive(Copy, Clone, PartialEq, Eq, Hash)] +#[derive(TyEncodable, StableHash, TypeVisitable, Lift)] +pub struct GenericArgs<'tcx>(&'tcx GenericArgsUnsized<'tcx>); + +impl<'tcx> Index for GenericArgs<'tcx> { + type Output = GenericArg<'tcx>; + + fn index(&self, index: usize) -> &Self::Output { + &self.as_slice()[index] + } +} + +impl<'tcx> Debug for GenericArgs<'tcx> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_list().entries(self.iter()).finish() + } +} + +impl<'tcx> Default for GenericArgs<'tcx> { + fn default() -> Self { + Self::empty() + } +} -pub type GenericArgsRef<'tcx> = &'tcx GenericArgs<'tcx>; +impl<'tcx> AsRef<[GenericArg<'tcx>]> for GenericArgs<'tcx> { + fn as_ref(&self) -> &[GenericArg<'tcx>] { + self.as_slice() + } +} + +impl<'tcx> rustc_type_ir::inherent::SliceLike for GenericArgs<'tcx> { + type Item = GenericArg<'tcx>; + type IntoIter = ::IntoIter; + + fn iter(self) -> Self::IntoIter { + self.iter() + } + + fn as_slice(&self) -> &[Self::Item] { + self.as_slice() + } +} + +impl<'tcx> IntoIterator for GenericArgs<'tcx> { + type Item = GenericArg<'tcx>; + type IntoIter = std::iter::Copied>>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} impl<'tcx> GenericArgs<'tcx> { + #[inline] + pub fn empty() -> Self { + Self::from_args(List::empty()) + } + + #[inline] + pub fn iter(self) -> ::IntoIter { + self.into_iter() + } + + #[inline] + pub fn get(self, idx: usize) -> Option> { + self.as_slice().get(idx).copied() + } + + #[inline] + pub fn first(self) -> Option> { + self.as_slice().first().copied() + } + + #[inline] + pub fn as_slice(&self) -> &[GenericArg<'tcx>] { + self.0.as_slice() + } + + #[inline] + pub fn is_empty(&self) -> bool { + self.as_slice().is_empty() + } + + #[inline] + pub fn len(&self) -> usize { + self.as_slice().len() + } + + // FIXME: we cannot easily provide this anymore in the future if we store 1 element inline. + // Use as little as possible. + #[inline] + pub fn as_tcx_slice(&self) -> &'tcx [GenericArg<'tcx>] { + self.0.as_slice() + } + + #[inline] + pub fn from_args(args: &'tcx GenericArgsUnsized<'tcx>) -> Self { + Self(args) + } + /// Converts generic args to a type list. /// /// # Panics /// /// If any of the generic arguments are not types. pub fn into_type_list(&self, tcx: TyCtxt<'tcx>) -> &'tcx List> { - tcx.mk_type_list_from_iter(self.iter().map(|arg| match arg.kind() { + tcx.mk_type_list_from_iter(self.as_slice().iter().map(|arg| match arg.kind() { GenericArgKind::Type(ty) => ty, _ => bug!("`into_type_list` called on generic arg with non-types"), })) @@ -396,7 +497,7 @@ impl<'tcx> GenericArgs<'tcx> { /// Closure args have a particular structure controlled by the /// compiler that encodes information like the signature and closure kind; /// see `ty::ClosureArgs` struct for more comments. - pub fn as_closure(&'tcx self) -> ClosureArgs> { + pub fn as_closure(self) -> ClosureArgs> { ClosureArgs { args: self } } @@ -404,7 +505,7 @@ impl<'tcx> GenericArgs<'tcx> { /// Coroutine-closure args have a particular structure controlled by the /// compiler that encodes information like the signature and closure kind; /// see `ty::CoroutineClosureArgs` struct for more comments. - pub fn as_coroutine_closure(&'tcx self) -> CoroutineClosureArgs> { + pub fn as_coroutine_closure(self) -> CoroutineClosureArgs> { CoroutineClosureArgs { args: self } } @@ -412,7 +513,7 @@ impl<'tcx> GenericArgs<'tcx> { /// Coroutine args have a particular structure controlled by the /// compiler that encodes information like the signature and coroutine kind; /// see `ty::CoroutineArgs` struct for more comments. - pub fn as_coroutine(&'tcx self) -> CoroutineArgs> { + pub fn as_coroutine(self) -> CoroutineArgs> { CoroutineArgs { args: self } } @@ -420,12 +521,12 @@ impl<'tcx> GenericArgs<'tcx> { /// Inline const args have a particular structure controlled by the /// compiler that encodes information like the inferred type; /// see `ty::InlineConstArgs` struct for more comments. - pub fn as_inline_const(&'tcx self) -> InlineConstArgs<'tcx> { + pub fn as_inline_const(self) -> InlineConstArgs<'tcx> { InlineConstArgs { args: self } } /// Creates a [`GenericArgs`] that maps each generic parameter to itself. - pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: impl Into) -> GenericArgsRef<'tcx> { + pub fn identity_for_item(tcx: TyCtxt<'tcx>, def_id: impl Into) -> GenericArgs<'tcx> { Self::for_item(tcx, def_id.into(), |param, _| tcx.mk_param_from_def(param)) } @@ -434,7 +535,7 @@ impl<'tcx> GenericArgs<'tcx> { /// The closures get to observe the [`GenericArgs`] as they're /// being built, which can be used to correctly /// replace defaults of generic parameters. - pub fn for_item(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> GenericArgsRef<'tcx> + pub fn for_item(tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F) -> GenericArgs<'tcx> where F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, { @@ -450,12 +551,15 @@ impl<'tcx> GenericArgs<'tcx> { tcx: TyCtxt<'tcx>, def_id: DefId, mut mk_kind: F, - ) -> GenericArgsRef<'tcx> + ) -> GenericArgs<'tcx> where F: FnMut(&ty::GenericParamDef, &[GenericArg<'tcx>]) -> GenericArg<'tcx>, { Self::for_item(tcx, def_id, |param, args| { - self.get(param.index as usize).cloned().unwrap_or_else(|| mk_kind(param, args)) + self.as_slice() + .get(param.index as usize) + .copied() + .unwrap_or_else(|| mk_kind(param, args)) }) } @@ -495,7 +599,7 @@ impl<'tcx> GenericArgs<'tcx> { tcx: TyCtxt<'tcx>, def_id: DefId, original_args: &[GenericArg<'tcx>], - ) -> GenericArgsRef<'tcx> { + ) -> GenericArgs<'tcx> { ty::GenericArgs::for_item(tcx, def_id, |def, _| { if let Some(arg) = original_args.get(def.index as usize) { *arg @@ -589,8 +693,8 @@ impl<'tcx> GenericArgs<'tcx> { &self, tcx: TyCtxt<'tcx>, source_ancestor: DefId, - target_args: GenericArgsRef<'tcx>, - ) -> GenericArgsRef<'tcx> { + target_args: GenericArgs<'tcx>, + ) -> GenericArgs<'tcx> { let defs = tcx.generics_of(source_ancestor); tcx.mk_args_from_iter(target_args.iter().chain(self.iter().skip(defs.count()))) } @@ -598,8 +702,8 @@ impl<'tcx> GenericArgs<'tcx> { /// Truncates this list of generic args to have at most the number of args in `generics`. /// /// You might be looking for [`TraitRef::from_assoc`](super::TraitRef::from_assoc). - pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> GenericArgsRef<'tcx> { - tcx.mk_args(&self[..generics.count()]) + pub fn truncate_to(&self, tcx: TyCtxt<'tcx>, generics: &ty::Generics) -> GenericArgs<'tcx> { + tcx.mk_args(&self.as_slice()[..generics.count()]) } pub fn print_as_list(&self) -> String { @@ -608,26 +712,27 @@ impl<'tcx> GenericArgs<'tcx> { } } -impl<'tcx> TypeFoldable> for GenericArgsRef<'tcx> { +impl<'tcx> TypeFoldable> for GenericArgs<'tcx> { fn try_fold_with>>( self, folder: &mut F, ) -> Result { + let args = self.as_slice(); // This code is hot enough that it's worth specializing for the most // common length lists, to avoid the overhead of `SmallVec` creation. // The match arms are in order of frequency. The 1, 2, and 0 cases are // typically hit in 90--99.99% of cases. When folding doesn't change // the args, it's faster to reuse the existing args rather than // calling `mk_args`. - match self.len() { + match args.len() { 1 => { - let param0 = self[0].try_fold_with(folder)?; - if param0 == self[0] { Ok(self) } else { Ok(folder.cx().mk_args(&[param0])) } + let param0 = args[0].try_fold_with(folder)?; + if param0 == args[0] { Ok(self) } else { Ok(folder.cx().mk_args(&[param0])) } } 2 => { - let param0 = self[0].try_fold_with(folder)?; - let param1 = self[1].try_fold_with(folder)?; - if param0 == self[0] && param1 == self[1] { + let param0 = args[0].try_fold_with(folder)?; + let param1 = args[1].try_fold_with(folder)?; + if param0 == args[0] && param1 == args[1] { Ok(self) } else { Ok(folder.cx().mk_args(&[param0, param1])) @@ -639,16 +744,17 @@ impl<'tcx> TypeFoldable> for GenericArgsRef<'tcx> { } fn fold_with>>(self, folder: &mut F) -> Self { + let args = self.as_slice(); // See justification for this behavior in `try_fold_with`. - match self.len() { + match args.len() { 1 => { - let param0 = self[0].fold_with(folder); - if param0 == self[0] { self } else { folder.cx().mk_args(&[param0]) } + let param0 = args[0].fold_with(folder); + if param0 == args[0] { self } else { folder.cx().mk_args(&[param0]) } } 2 => { - let param0 = self[0].fold_with(folder); - let param1 = self[1].fold_with(folder); - if param0 == self[0] && param1 == self[1] { + let param0 = args[0].fold_with(folder); + let param1 = args[1].fold_with(folder); + if param0 == args[0] && param1 == args[1] { self } else { folder.cx().mk_args(&[param0, param1]) @@ -665,7 +771,7 @@ impl<'tcx> TypeFoldable> for &'tcx ty::List> { self, folder: &mut F, ) -> Result { - // This code is fairly hot, though not as hot as `GenericArgsRef`. + // This code is fairly hot, though not as hot as `GenericArgs`. // // When compiling stage 2, I get the following results: // @@ -725,7 +831,7 @@ impl<'tcx, T: TypeVisitable>> TypeVisitable> for &'tcx #[derive(StableHash, TypeFoldable, TypeVisitable, Lift)] pub struct UserArgs<'tcx> { /// The args for the item as given by the user. - pub args: GenericArgsRef<'tcx>, + pub args: GenericArgs<'tcx>, /// The self type, in the case of a `::Item` path (when applied /// to an inherent impl). See `UserSelfTy` below. diff --git a/compiler/rustc_middle/src/ty/generics.rs b/compiler/rustc_middle/src/ty/generics.rs index edddd7043077c..83989e470e483 100644 --- a/compiler/rustc_middle/src/ty/generics.rs +++ b/compiler/rustc_middle/src/ty/generics.rs @@ -9,7 +9,7 @@ use rustc_type_ir::{TypeSuperVisitable as _, TypeVisitable, TypeVisitor}; use tracing::instrument; use super::{Clause, InstantiatedClauses, ParamConst, ParamTy, Ty, TyCtxt, Unnormalized}; -use crate::ty::{self, ClauseKind, EarlyBinder, GenericArgsRef, Region, RegionKind, TyKind}; +use crate::ty::{self, ClauseKind, EarlyBinder, GenericArgs, Region, RegionKind, TyKind}; #[derive(Clone, Debug, TyEncodable, TyDecodable, StableHash)] pub enum GenericParamDefKind { @@ -362,10 +362,7 @@ impl<'tcx> Generics { /// Returns the args corresponding to the generic parameters of this item, excluding `Self`. /// /// **This should only be used for diagnostics purposes.** - pub fn own_args( - &'tcx self, - args: &'tcx [ty::GenericArg<'tcx>], - ) -> &'tcx [ty::GenericArg<'tcx>] { + pub fn own_args<'a>(&self, args: &'a [ty::GenericArg<'tcx>]) -> &'a [ty::GenericArg<'tcx>] { let own = &args[self.parent_count..][..self.own_params.len()]; if self.has_own_self() { &own[1..] } else { own } } @@ -377,7 +374,7 @@ impl<'tcx> Generics { pub fn check_concrete_type_after_default( &'tcx self, tcx: TyCtxt<'tcx>, - args: &'tcx [ty::GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> bool { let mut default_param_seen = false; for param in self.own_params.iter() { @@ -419,7 +416,7 @@ impl<'tcx> GenericClauses<'tcx> { pub fn instantiate( self, tcx: TyCtxt<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> InstantiatedClauses<'tcx> { let mut instantiated = InstantiatedClauses::empty(); self.instantiate_into(tcx, &mut instantiated, args); @@ -429,7 +426,7 @@ impl<'tcx> GenericClauses<'tcx> { pub fn instantiate_own( self, tcx: TyCtxt<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> impl Iterator>, Span)> + DoubleEndedIterator + ExactSizeIterator @@ -457,7 +454,7 @@ impl<'tcx> GenericClauses<'tcx> { self, tcx: TyCtxt<'tcx>, instantiated: &mut InstantiatedClauses<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) { if let Some(def_id) = self.parent { tcx.clauses_of(def_id).instantiate_into(tcx, instantiated, args); @@ -536,7 +533,7 @@ impl<'tcx> GenericClauses<'tcx> { // considering we apply the fully-generic-for-reflection rules to any impls for // that trait, too. if matches!(trait_predicate.self_ty().kind(), ty::Param(_)) - && trait_predicate.trait_ref.args[1..] + && trait_predicate.trait_ref.args.as_slice()[1..] .iter() .all(|arg| arg.visit_with(&mut ParamChecker).is_continue()) { @@ -571,7 +568,7 @@ impl<'tcx> ConstConditions<'tcx> { pub fn instantiate( self, tcx: TyCtxt<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Vec<(Unnormalized<'tcx, ty::PolyTraitRef<'tcx>>, Span)> { let mut instantiated = vec![]; self.instantiate_into(tcx, &mut instantiated, args); @@ -581,7 +578,7 @@ impl<'tcx> ConstConditions<'tcx> { pub fn instantiate_own( self, tcx: TyCtxt<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> impl Iterator>, Span)> + DoubleEndedIterator + ExactSizeIterator @@ -609,7 +606,7 @@ impl<'tcx> ConstConditions<'tcx> { self, tcx: TyCtxt<'tcx>, instantiated: &mut Vec<(Unnormalized<'tcx, ty::PolyTraitRef<'tcx>>, Span)>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) { if let Some(def_id) = self.parent { tcx.const_conditions(def_id).instantiate_into(tcx, instantiated, args); diff --git a/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs b/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs index 6b0234c971830..d392e05b57ab9 100644 --- a/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs +++ b/compiler/rustc_middle/src/ty/inhabitedness/inhabited_predicate.rs @@ -233,7 +233,7 @@ impl<'tcx> InhabitedPredicate<'tcx> { } /// Replaces generic types with its corresponding predicate - pub fn instantiate(self, tcx: TyCtxt<'tcx>, args: ty::GenericArgsRef<'tcx>) -> Self { + pub fn instantiate(self, tcx: TyCtxt<'tcx>, args: ty::GenericArgs<'tcx>) -> Self { self.instantiate_opt(tcx, args).unwrap_or(self) } @@ -242,7 +242,7 @@ impl<'tcx> InhabitedPredicate<'tcx> { /// allocating a recursive copy of everything when the result is unchanged. /// /// Only used to implement `instantiate` itself. - fn instantiate_opt(self, tcx: TyCtxt<'tcx>, args: ty::GenericArgsRef<'tcx>) -> Option { + fn instantiate_opt(self, tcx: TyCtxt<'tcx>, args: ty::GenericArgs<'tcx>) -> Option { match self { Self::ConstIsZero(c) => { let c = ty::EarlyBinder::bind(tcx, c).instantiate(tcx, args).skip_norm_wip(); diff --git a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs index 180a62eaf15a5..409c597863e65 100644 --- a/compiler/rustc_middle/src/ty/inhabitedness/mod.rs +++ b/compiler/rustc_middle/src/ty/inhabitedness/mod.rs @@ -348,7 +348,7 @@ impl<'tcx> OpsemInhabitedCtx<'tcx> { fn is_inhabited_adt_ty( &mut self, adt_def: ty::AdtDef<'tcx>, - adt_args: ty::GenericArgsRef<'tcx>, + adt_args: ty::GenericArgs<'tcx>, ) -> bool { let Self { tcx, typing_env, .. } = *self; @@ -392,7 +392,7 @@ impl<'tcx> OpsemInhabitedCtx<'tcx> { fn is_opsem_inhabited_adt_cached<'tcx>( tcx: TyCtxt<'tcx>, - env: ty::PseudoCanonicalInput<'tcx, (ty::AdtDef<'tcx>, ty::GenericArgsRef<'tcx>)>, + env: ty::PseudoCanonicalInput<'tcx, (ty::AdtDef<'tcx>, ty::GenericArgs<'tcx>)>, ) -> bool { let ((def, args), typing_env) = (env.value, env.typing_env); OpsemInhabitedCtx { tcx, typing_env, seen: Some(FxHashSet::default()), stop_at_ref: false } diff --git a/compiler/rustc_middle/src/ty/instance.rs b/compiler/rustc_middle/src/ty/instance.rs index 1a00293f8ffc6..a90de4c3baba6 100644 --- a/compiler/rustc_middle/src/ty/instance.rs +++ b/compiler/rustc_middle/src/ty/instance.rs @@ -16,8 +16,8 @@ use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags; use crate::ty::normalize_erasing_regions::NormalizationError; use crate::ty::print::{FmtPrinter, Print}; use crate::ty::{ - self, AssocContainer, EarlyBinder, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, - TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, + self, AssocContainer, EarlyBinder, GenericArgs, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable, + TypeVisitable, TypeVisitableExt, TypeVisitor, }; /// An `InstanceKind` along with the args that are needed to substitute the instance. @@ -32,7 +32,7 @@ use crate::ty::{ #[derive(StableHash, Lift, TypeFoldable, TypeVisitable)] pub struct Instance<'tcx> { pub def: InstanceKind<'tcx>, - pub args: GenericArgsRef<'tcx>, + pub args: GenericArgs<'tcx>, } /// Describes why a `ReifyShim` was created. This is needed to distinguish a ReifyShim created to @@ -481,7 +481,7 @@ fn resolve_async_drop_poll<'tcx>(mut cor_ty: Ty<'tcx>) -> Instance<'tcx> { first_cor, cor_ty, )), - args: proxy_args, + args: *proxy_args, }; } } else { @@ -495,12 +495,12 @@ fn resolve_async_drop_poll<'tcx>(mut cor_ty: Ty<'tcx>) -> Instance<'tcx> { first_cor, cor_ty, )), - args: proxy_args, + args: *proxy_args, }; } else { return Instance { def: ty::InstanceKind::Shim(ShimKind::AsyncDropGlue(poll_def_id, cor_ty)), - args: child_args, + args: *child_args, }; } } @@ -516,7 +516,7 @@ impl<'tcx> Instance<'tcx> { /// this function should probably use [`Instance::expect_resolve`], or if run /// in a polymorphic environment or within a lint (that may encounter ambiguity) /// [`Instance::try_resolve`] instead. - pub fn new_raw(def_id: DefId, args: GenericArgsRef<'tcx>) -> Instance<'tcx> { + pub fn new_raw(def_id: DefId, args: GenericArgs<'tcx>) -> Instance<'tcx> { assert!( !args.has_escaping_bound_vars(), "args of instance {def_id:?} has escaping bound vars: {args:?}" @@ -573,7 +573,7 @@ impl<'tcx> Instance<'tcx> { tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Result>, ErrorGuaranteed> { assert_matches!( tcx.def_kind(def_id), @@ -614,7 +614,7 @@ impl<'tcx> Instance<'tcx> { tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, span: Span, ) -> Instance<'tcx> { // We compute the span lazily, to avoid unnecessary query calls. @@ -656,7 +656,7 @@ impl<'tcx> Instance<'tcx> { tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Option> { debug!("resolve(def_id={:?}, args={:?})", def_id, args); // Use either `resolve_closure` or `resolve_for_vtable` @@ -705,7 +705,7 @@ impl<'tcx> Instance<'tcx> { tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, span: Span, ) -> Instance<'tcx> { debug!("resolve_for_vtable(def_id={:?}, args={:?})", def_id, args); @@ -785,7 +785,7 @@ impl<'tcx> Instance<'tcx> { pub fn resolve_closure( tcx: TyCtxt<'tcx>, def_id: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, requested_kind: ty::ClosureKind, ) -> Instance<'tcx> { let actual_kind = args.as_closure().kind(); @@ -833,7 +833,7 @@ impl<'tcx> Instance<'tcx> { pub fn fn_once_adapter_instance( tcx: TyCtxt<'tcx>, closure_did: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Instance<'tcx> { let fn_once = tcx.require_lang_item(LangItem::FnOnce, DUMMY_SP); let call_once = tcx @@ -864,7 +864,7 @@ impl<'tcx> Instance<'tcx> { tcx: TyCtxt<'tcx>, trait_item_id: DefId, trait_id: DefId, - rcvr_args: ty::GenericArgsRef<'tcx>, + rcvr_args: ty::GenericArgs<'tcx>, ) -> Option> { let ty::Coroutine(coroutine_def_id, args) = *rcvr_args.type_at(0).kind() else { return None; @@ -936,7 +936,7 @@ impl<'tcx> Instance<'tcx> { /// This function returns `Some(args)` in the former case and `None` otherwise -- i.e., if /// this function returns `None`, then the MIR body does not require instantiation during /// codegen. - fn args_for_mir_body(&self) -> Option> { + fn args_for_mir_body(&self) -> Option> { self.def.has_polymorphic_mir_body().then_some(self.args) } diff --git a/compiler/rustc_middle/src/ty/layout.rs b/compiler/rustc_middle/src/ty/layout.rs index 998fcf77f7b1f..770bed217cdd6 100644 --- a/compiler/rustc_middle/src/ty/layout.rs +++ b/compiler/rustc_middle/src/ty/layout.rs @@ -140,7 +140,7 @@ impl abi::Float { F16B => Ty::new_adt( tcx, tcx.adt_def(tcx.require_lang_item(LangItem::F16B, DUMMY_SP)), - ty::List::empty(), + ty::GenericArgs::empty(), ), F32 => tcx.types.f32, F64 => tcx.types.f64, @@ -148,7 +148,7 @@ impl abi::Float { PpcF128 => Ty::new_adt( tcx, tcx.adt_def(tcx.require_lang_item(LangItem::PpcF128, DUMMY_SP)), - ty::List::empty(), + ty::GenericArgs::empty(), ), } } diff --git a/compiler/rustc_middle/src/ty/mod.rs b/compiler/rustc_middle/src/ty/mod.rs index e6321fadd0701..9194e768f3c41 100644 --- a/compiler/rustc_middle/src/ty/mod.rs +++ b/compiler/rustc_middle/src/ty/mod.rs @@ -923,7 +923,7 @@ impl<'tcx> ProvisionalHiddenType<'tcx> { // This zip may have several times the same lifetime in `args` paired with a different // lifetime from `id_args`. Simply `collect`ing the iterator is the correct behaviour: // it will pick the last one, which is the one we introduced in the impl-trait desugaring. - let map = args.iter().zip(id_args).collect(); + let map = args.iter().zip(id_args.iter()).collect(); debug!("map = {:#?}", map); // Convert the type from the function into a type valid outside by mapping generic @@ -1580,11 +1580,7 @@ impl Hash for FieldDef { impl<'tcx> FieldDef { /// Returns the type of this field. The `args` are typically obtained via /// the second field of [`TyKind::Adt`]. - pub fn ty( - &self, - tcx: TyCtxt<'tcx>, - args: GenericArgsRef<'tcx>, - ) -> Unnormalized<'tcx, Ty<'tcx>> { + pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgs<'tcx>) -> Unnormalized<'tcx, Ty<'tcx>> { tcx.type_of(self.did).instantiate(tcx, args) } @@ -1954,7 +1950,7 @@ impl<'tcx> TyCtxt<'tcx> { fn ordinary_coroutine_layout( self, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> { let coroutine_kind_ty = args.as_coroutine().kind_ty(); let mir = self.optimized_mir(def_id); @@ -1995,7 +1991,7 @@ impl<'tcx> TyCtxt<'tcx> { fn async_drop_coroutine_layout( self, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> { let ty = || Ty::new_coroutine(self, def_id, args); if args[0].has_placeholders() || args[0].has_non_region_param() { @@ -2012,7 +2008,7 @@ impl<'tcx> TyCtxt<'tcx> { pub fn coroutine_layout( self, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Result<&'tcx CoroutineLayout<'tcx>, &'tcx LayoutError<'tcx>> { if self.is_async_drop_in_place_coroutine(def_id) { // layout of `async_drop_in_place::{closure}` in case, diff --git a/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs b/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs index c7837eeec307b..ebd9b1099b6cb 100644 --- a/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs +++ b/compiler/rustc_middle/src/ty/normalize_erasing_regions.rs @@ -13,7 +13,7 @@ use tracing::{debug, instrument}; use crate::traits::query::NoSolution; use crate::ty::{ - self, EarlyBinder, FallibleTypeFolder, GenericArgsRef, Ty, TyCtxt, TypeFoldable, TypeFolder, + self, EarlyBinder, FallibleTypeFolder, GenericArgs, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeVisitableExt, Unnormalized, }; @@ -161,7 +161,7 @@ impl<'tcx> TyCtxt<'tcx> { #[instrument(level = "debug", skip(self))] pub fn instantiate_and_normalize_erasing_regions( self, - param_args: GenericArgsRef<'tcx>, + param_args: GenericArgs<'tcx>, typing_env: ty::TypingEnv<'tcx>, value: EarlyBinder<'tcx, T>, ) -> T @@ -179,7 +179,7 @@ impl<'tcx> TyCtxt<'tcx> { #[instrument(level = "debug", skip(self))] pub fn try_instantiate_and_normalize_erasing_regions( self, - param_args: GenericArgsRef<'tcx>, + param_args: GenericArgs<'tcx>, typing_env: ty::TypingEnv<'tcx>, value: EarlyBinder<'tcx, T>, ) -> Result> diff --git a/compiler/rustc_middle/src/ty/opaque_types.rs b/compiler/rustc_middle/src/ty/opaque_types.rs index 7333d17e259e0..1edcbdd9e14fc 100644 --- a/compiler/rustc_middle/src/ty/opaque_types.rs +++ b/compiler/rustc_middle/src/ty/opaque_types.rs @@ -49,8 +49,8 @@ impl<'tcx> ReverseMapper<'tcx> { fn fold_closure_args( &mut self, def_id: DefId, - args: ty::GenericArgsRef<'tcx>, - ) -> ty::GenericArgsRef<'tcx> { + args: ty::GenericArgs<'tcx>, + ) -> ty::GenericArgs<'tcx> { // I am a horrible monster and I pray for death. When // we encounter a closure here, it is always a closure // from within the function that we are currently diff --git a/compiler/rustc_middle/src/ty/print/mod.rs b/compiler/rustc_middle/src/ty/print/mod.rs index 451a75e52d2d9..afb0bc1705f91 100644 --- a/compiler/rustc_middle/src/ty/print/mod.rs +++ b/compiler/rustc_middle/src/ty/print/mod.rs @@ -32,7 +32,7 @@ pub trait Printer<'tcx>: Sized { fn print_def_path( &mut self, def_id: DefId, - args: &'tcx [GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { self.default_print_def_path(def_id, args) } @@ -41,7 +41,7 @@ pub trait Printer<'tcx>: Sized { fn print_impl_path( &mut self, impl_def_id: DefId, - args: &'tcx [GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { let tcx = self.tcx(); let self_ty = tcx.type_of(impl_def_id); @@ -115,7 +115,7 @@ pub trait Printer<'tcx>: Sized { fn print_path_with_generic_args( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - args: &[GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError>; /// Appends a representation of a qualified path segment, e.g. `>`. @@ -129,10 +129,13 @@ pub trait Printer<'tcx>: Sized { fn print_coroutine_with_kind( &mut self, def_id: DefId, - parent_args: &'tcx [GenericArg<'tcx>], + parent_args: ty::GenericArgs<'tcx>, kind: Ty<'tcx>, ) -> Result<(), PrintError> { - self.print_path_with_generic_args(|p| p.print_def_path(def_id, parent_args), &[kind.into()]) + self.print_path_with_generic_args( + |p| p.print_def_path(def_id, parent_args), + self.tcx().mk_args(&[kind.into()]), + ) } fn reset_path(&mut self) -> Result<(), PrintError> { @@ -148,7 +151,7 @@ pub trait Printer<'tcx>: Sized { fn default_print_def_path( &mut self, def_id: DefId, - args: &'tcx [GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { let key = self.tcx().def_key(def_id); debug!(?key); @@ -164,11 +167,11 @@ pub trait Printer<'tcx>: Sized { _ => { let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id }; - let mut parent_args = args; + let mut parent_args = args.as_slice(); let mut trait_qualify_parent = false; if !args.is_empty() { let generics = self.tcx().generics_of(def_id); - parent_args = &args[..generics.parent_count.min(args.len())]; + parent_args = &args.as_slice()[..generics.parent_count.min(args.len())]; match key.disambiguated_data.data { DefPathData::Closure => { @@ -182,7 +185,7 @@ pub trait Printer<'tcx>: Sized { { return self.print_coroutine_with_kind( def_id, - parent_args, + self.tcx().mk_args(parent_args), args[parent_args.len()].expect_ty(), ); } else { @@ -202,10 +205,12 @@ pub trait Printer<'tcx>: Sized { // on top of the same path, but without its own generics. _ => { if !generics.is_own_empty() && args.len() >= generics.count() { - let args = generics.own_args_no_defaults(self.tcx(), args); + let args = + generics.own_args_no_defaults(self.tcx(), args.as_slice()); + let parent_args = self.tcx().mk_args(parent_args); return self.print_path_with_generic_args( |p| p.print_def_path(def_id, parent_args), - args, + self.tcx().mk_args(args), ); } } @@ -222,17 +227,15 @@ pub trait Printer<'tcx>: Sized { let omit_parent = matches!(key.disambiguated_data.data, DefPathData::TypeNs(..)) && self.should_omit_parent_def_path(parent_def_id); + let parent_args = self.tcx().mk_args(parent_args); self.print_path_with_simple( |p: &mut Self| { if omit_parent { p.reset_path()?; Ok(()) } else if trait_qualify_parent { - let trait_ref = ty::TraitRef::new( - p.tcx(), - parent_def_id, - parent_args.iter().copied(), - ); + let trait_ref = + ty::TraitRef::new(p.tcx(), parent_def_id, parent_args.iter()); p.print_path_with_qualified(trait_ref.self_ty(), Some(trait_ref)) } else { p.print_def_path(parent_def_id, parent_args) @@ -277,7 +280,7 @@ pub trait Printer<'tcx>: Sized { // trait-type, then fallback to a format that identifies // the module more clearly. self.print_path_with_impl( - |p| p.print_def_path(parent_def_id, &[]), + |p| p.print_def_path(parent_def_id, ty::GenericArgs::empty()), self_ty, impl_trait_ref, ) diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index e6e29fe7eac70..555d4978f0899 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -264,7 +264,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { fn pretty_print_value_path( &mut self, def_id: DefId, - args: &'tcx [GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { self.print_def_path(def_id, args) } @@ -531,7 +531,9 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { // in cases where the `extern crate foo` has non-trivial // parents, e.g. it's nested in `impl foo::Trait for Bar` // (see also issues #55779 and #87932). - with_no_visible_paths!(self.print_def_path(def_id, &[])?); + with_no_visible_paths!( + self.print_def_path(def_id, ty::GenericArgs::empty())? + ); return Ok(true); } @@ -725,7 +727,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { fn pretty_print_closure_inner( &mut self, did: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { if self.should_truncate() { write!(self, "@...") @@ -866,7 +868,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { write!(self, ")")?; } } - ty::Foreign(def_id) => self.print_def_path(def_id, &[])?, + ty::Foreign(def_id) => self.print_def_path(def_id, ty::GenericArgs::empty())?, ty::Alias( _, ref data @ ty::AliasTy { @@ -916,7 +918,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } _ => { if with_reduced_queries() { - self.print_def_path(def_id, &[])?; + self.print_def_path(def_id, ty::GenericArgs::empty())?; return Ok(()); } else { return self.pretty_print_opaque_impl_type(def_id, args); @@ -1041,7 +1043,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { fn pretty_print_opaque_impl_type( &mut self, def_id: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { let tcx = self.tcx(); @@ -1183,7 +1185,8 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { trait_pred.trait_ref.print_only_trait_name().print(p)?; let generics = tcx.generics_of(trait_pred.def_id()); - let own_args = generics.own_args_no_defaults(tcx, trait_pred.trait_ref.args); + let own_args = + generics.own_args_no_defaults(tcx, trait_pred.trait_ref.args.as_slice()); if !own_args.is_empty() || !assoc_items.is_empty() { let mut first = true; @@ -1322,14 +1325,14 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { &def_key.disambiguated_data, ) }, - &alias_term.args[1..], + self.tcx().mk_args(&alias_term.args.as_slice()[1..]), ) } fn pretty_print_rpitit( &mut self, def_id: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { let fn_args = if self.tcx().features().return_type_notation() && let Some(ty::ImplTraitInTraitData::Trait { fn_def_id, .. }) = @@ -1346,7 +1349,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { .all(|param| matches!(param.kind, ty::GenericParamDefKind::Lifetime)) { let num_args = generics.count(); - Some((fn_def_id, &args[..num_args])) + Some((fn_def_id, self.tcx().mk_args(&args.as_slice()[..num_args]))) } else { None }; @@ -1387,7 +1390,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { if let Some(bound_principal) = predicates.principal() { self.wrap_binder(&bound_principal, WrapBinderMode::ForAll, |principal, p| { - p.print_def_path(principal.def_id, &[])?; + p.print_def_path(principal.def_id, ty::GenericArgs::empty())?; let mut resugared = false; @@ -1418,7 +1421,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { let args = p .tcx() .generics_of(principal_with_self.def_id) - .own_args_no_defaults(p.tcx(), principal_with_self.args); + .own_args_no_defaults(p.tcx(), principal_with_self.args.as_slice()); let bound_principal_with_self = bound_principal .with_self_ty(p.tcx(), p.tcx().types.trait_object_dummy_self); @@ -1495,7 +1498,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { } first = false; - self.print_def_path(def_id, &[])?; + self.print_def_path(def_id, ty::GenericArgs::empty())?; } Ok(()) @@ -1689,7 +1692,7 @@ pub trait PrettyPrinter<'tcx>: Printer<'tcx> + fmt::Write { write!(self, "(")?; self.pretty_print_const(fn_def, print_ty)?; write!(self, ")(")?; - self.comma_sep(fn_args)?; + self.comma_sep(fn_args.into_iter())?; write!(self, ")")?; } ty::ExprKind::Cast(kind) => { @@ -2192,14 +2195,14 @@ impl<'t> TyCtxt<'t> { /// suitable for user output. pub fn def_path_str(self, def_id: impl IntoQueryKey) -> String { let def_id = def_id.into_query_key(); - self.def_path_str_with_args(def_id, &[]) + self.def_path_str_with_args(def_id, ty::GenericArgs::empty()) } /// For this one we determine the appropriate namespace for the `def_id`. pub fn def_path_str_with_args( self, def_id: impl IntoQueryKey, - args: &'t [GenericArg<'t>], + args: ty::GenericArgs<'t>, ) -> String { let def_id = def_id.into_query_key(); let ns = guess_def_namespace(self, def_id); @@ -2212,7 +2215,7 @@ impl<'t> TyCtxt<'t> { pub fn value_path_str_with_args( self, def_id: impl IntoQueryKey, - args: &'t [GenericArg<'t>], + args: ty::GenericArgs<'t>, ) -> String { let def_id = def_id.into_query_key(); let ns = Namespace::ValueNS; @@ -2250,7 +2253,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { fn print_def_path( &mut self, def_id: DefId, - args: &'tcx [GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { if args.is_empty() { match self.try_print_trimmed_def_path(def_id)? { @@ -2281,7 +2284,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { let parent_def_id = DefId { index: key.parent.unwrap(), ..def_id }; let span = self.tcx.def_span(def_id); - self.print_def_path(parent_def_id, &[])?; + self.print_def_path(parent_def_id, ty::GenericArgs::empty())?; // HACK(eddyb) copy of `print_path_with_simple` to avoid // constructing a `DisambiguatedDefPathData`. @@ -2495,7 +2498,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { fn print_path_with_generic_args( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - args: &[GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { print_prefix(self)?; @@ -2503,7 +2506,7 @@ impl<'tcx> Printer<'tcx> for FmtPrinter<'_, 'tcx> { if self.in_value { write!(self, "::")?; } - self.generic_delimiters(|p| p.comma_sep(args.iter().copied())) + self.generic_delimiters(|p| p.comma_sep(args.iter())) } else { Ok(()) } @@ -2526,7 +2529,7 @@ impl<'tcx> PrettyPrinter<'tcx> for FmtPrinter<'_, 'tcx> { fn pretty_print_value_path( &mut self, def_id: DefId, - args: &'tcx [GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { let was_in_value = std::mem::replace(&mut self.in_value, true); self.print_def_path(def_id, args)?; @@ -3274,7 +3277,7 @@ define_print! { ty::PredicateKind::Coerce(predicate) => predicate.print(p)?, ty::PredicateKind::DynCompatible(trait_def_id) => { write!(p, "the trait `")?; - p.print_def_path(trait_def_id, &[])?; + p.print_def_path(trait_def_id, ty::GenericArgs::empty())?; write!(p, "` is dyn-compatible")?; } ty::PredicateKind::ConstEquate(c1, c2) => { @@ -3293,7 +3296,7 @@ define_print! { match *self { ty::ExistentialPredicate::Trait(x) => x.print(p)?, ty::ExistentialPredicate::Projection(x) => x.print(p)?, - ty::ExistentialPredicate::AutoTrait(def_id) => p.print_def_path(def_id, &[])?, + ty::ExistentialPredicate::AutoTrait(def_id) => p.print_def_path(def_id, ty::GenericArgs::empty())?, } } @@ -3308,8 +3311,8 @@ define_print! { let name = p.tcx().associated_item(self.def_id).name(); // The args don't contain the self ty (as it has been erased) but the corresp. // generics do as the trait always has a self ty param. We need to offset. - let args = &self.args[p.tcx().generics_of(self.def_id).parent_count - 1..]; - p.print_path_with_generic_args(|p| write!(p, "{name}"), args)?; + let args = &self.args.as_slice()[p.tcx().generics_of(self.def_id).parent_count - 1..]; + p.print_path_with_generic_args(|p| write!(p, "{name}"), p.tcx().mk_args(args))?; write!(p, " = ")?; self.term.print(p)?; } @@ -3386,7 +3389,7 @@ define_print_and_forward_display! { } TraitRefPrintOnlyTraitName<'tcx> { - p.print_def_path(self.0.def_id, &[])?; + p.print_def_path(self.0.def_id, ty::GenericArgs::empty())?; } TraitClausePrintModifiersAndPath<'tcx> { @@ -3448,7 +3451,7 @@ define_print_and_forward_display! { write!(p, " at for ", key.disambiguated_data.as_sym(false))?; self_ty.print(p)?; write!(p, ">")?; diff --git a/compiler/rustc_middle/src/ty/relate.rs b/compiler/rustc_middle/src/ty/relate.rs index 477e5133cc358..2e37c47ffdc30 100644 --- a/compiler/rustc_middle/src/ty/relate.rs +++ b/compiler/rustc_middle/src/ty/relate.rs @@ -88,12 +88,12 @@ impl<'tcx> Relate> for &'tcx ty::List Relate> for ty::GenericArgsRef<'tcx> { +impl<'tcx> Relate> for ty::GenericArgs<'tcx> { fn relate>>( relation: &mut R, - a: ty::GenericArgsRef<'tcx>, - b: ty::GenericArgsRef<'tcx>, - ) -> RelateResult<'tcx, ty::GenericArgsRef<'tcx>> { + a: ty::GenericArgs<'tcx>, + b: ty::GenericArgs<'tcx>, + ) -> RelateResult<'tcx, ty::GenericArgs<'tcx>> { relate_args_invariantly(relation, a, b) } } diff --git a/compiler/rustc_middle/src/ty/significant_drop_order.rs b/compiler/rustc_middle/src/ty/significant_drop_order.rs index c5b50163fbbb1..d700c362cfa8d 100644 --- a/compiler/rustc_middle/src/ty/significant_drop_order.rs +++ b/compiler/rustc_middle/src/ty/significant_drop_order.rs @@ -46,7 +46,7 @@ fn true_significant_drop_ty<'tcx>( // These are important types from Rust ecosystem ["tracing", "instrument", "Instrumented"] | ["bytes", "Bytes"] => Some(smallvec![]), ["hashbrown", "raw", "RawTable" | "RawIntoIter"] => { - if let [ty, ..] = &***args + if let [ty, ..] = args.as_slice() && let Some(ty) = ty.as_type() { Some(smallvec![ty]) @@ -55,7 +55,7 @@ fn true_significant_drop_ty<'tcx>( } } ["hashbrown", "raw", "RawDrain"] => { - if let [_, ty, ..] = &***args + if let [_, ty, ..] = args.as_slice() && let Some(ty) = ty.as_type() { Some(smallvec![ty]) diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 300c70e04ede6..810d6908829d6 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -24,7 +24,7 @@ impl fmt::Debug for ty::TraitDef { ty::tls::with(|tcx| { with_no_trimmed_paths!({ let s = FmtPrinter::print_string(tcx, Namespace::TypeNS, |p| { - p.print_def_path(self.def_id, &[]) + p.print_def_path(self.def_id, ty::GenericArgs::empty()) })?; f.write_str(&s) }) @@ -37,7 +37,7 @@ impl<'tcx> fmt::Debug for ty::AdtDef<'tcx> { ty::tls::with(|tcx| { with_no_trimmed_paths!({ let s = FmtPrinter::print_string(tcx, Namespace::TypeNS, |p| { - p.print_def_path(self.did(), &[]) + p.print_def_path(self.did(), ty::GenericArgs::empty()) })?; f.write_str(&s) }) @@ -122,7 +122,6 @@ impl<'tcx> fmt::Debug for ty::consts::Expr<'tcx> { } ty::ExprKind::FunctionCall => { let (func_ty, func, args) = self.call_args(); - let args = args.collect::>(); write!(f, "({:?}: {:?})(", func, func_ty)?; for arg in args.iter().rev().skip(1).rev() { write!(f, "{:?}, ", arg)?; diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 09a18c858db17..b7719ec0598de 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -28,8 +28,8 @@ use crate::infer::canonical::Canonical; use crate::traits::ObligationCause; use crate::ty::InferTy::*; use crate::ty::{ - self, AdtDef, Const, Discr, GenericArg, GenericArgs, GenericArgsRef, List, ParamEnv, Region, - Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy, ValTree, + self, AdtDef, Const, Discr, GenericArg, GenericArgs, List, ParamEnv, Region, Ty, TyCtxt, + TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy, ValTree, }; // Re-export and re-parameterize some `I = TyCtxt<'tcx>` types here @@ -177,9 +177,9 @@ impl<'tcx> ty::CoroutineArgs> { #[derive(Debug, Copy, Clone, StableHash, TypeFoldable, TypeVisitable)] pub enum UpvarArgs<'tcx> { - Closure(GenericArgsRef<'tcx>), - Coroutine(GenericArgsRef<'tcx>), - CoroutineClosure(GenericArgsRef<'tcx>), + Closure(GenericArgs<'tcx>), + Coroutine(GenericArgs<'tcx>), + CoroutineClosure(GenericArgs<'tcx>), } impl<'tcx> UpvarArgs<'tcx> { @@ -224,12 +224,12 @@ impl<'tcx> UpvarArgs<'tcx> { pub struct InlineConstArgs<'tcx> { /// Generic parameters from the enclosing item, /// concatenated with the inferred type of the constant. - pub args: GenericArgsRef<'tcx>, + pub args: GenericArgs<'tcx>, } /// Struct returned by `split()`. -pub struct InlineConstArgsParts<'tcx, T> { - pub parent_args: &'tcx [GenericArg<'tcx>], +pub struct InlineConstArgsParts<'tcx, 'a, T> { + pub parent_args: &'a [GenericArg<'tcx>], pub ty: T, } @@ -237,7 +237,7 @@ impl<'tcx> InlineConstArgs<'tcx> { /// Construct `InlineConstArgs` from `InlineConstArgsParts`. pub fn new( tcx: TyCtxt<'tcx>, - parts: InlineConstArgsParts<'tcx, Ty<'tcx>>, + parts: InlineConstArgsParts<'tcx, '_, Ty<'tcx>>, ) -> InlineConstArgs<'tcx> { InlineConstArgs { args: tcx.mk_args_from_iter( @@ -248,15 +248,15 @@ impl<'tcx> InlineConstArgs<'tcx> { /// Divides the inline const args into their respective components. /// The ordering assumed here must match that used by `InlineConstArgs::new` above. - fn split(self) -> InlineConstArgsParts<'tcx, GenericArg<'tcx>> { - match self.args[..] { - [ref parent_args @ .., ty] => InlineConstArgsParts { parent_args, ty }, + fn split(&self) -> InlineConstArgsParts<'tcx, '_, GenericArg<'tcx>> { + match self.args.as_slice() { + [parent_args @ .., ty] => InlineConstArgsParts { parent_args, ty: *ty }, _ => bug!("inline const args missing synthetics"), } } /// Returns the generic parameters of the inline const's parent. - pub fn parent_args(self) -> &'tcx [GenericArg<'tcx>] { + pub fn parent_args(&self) -> &[GenericArg<'tcx>] { self.split().parent_args } @@ -523,7 +523,7 @@ impl<'tcx> Ty<'tcx> { tcx: TyCtxt<'tcx>, is_rigid: ty::IsRigid, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Ty<'tcx> { Ty::new_alias(tcx, is_rigid, AliasTy::new_from_args(tcx, ty::Opaque { def_id }, args)) } @@ -634,7 +634,7 @@ impl<'tcx> Ty<'tcx> { } #[inline] - pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> { + pub fn new_adt(tcx: TyCtxt<'tcx>, def: AdtDef<'tcx>, args: GenericArgs<'tcx>) -> Ty<'tcx> { tcx.debug_assert_args_compatible(def.did(), args); if cfg!(debug_assertions) { match tcx.def_kind(def.did()) { @@ -778,7 +778,7 @@ impl<'tcx> Ty<'tcx> { tcx: TyCtxt<'tcx>, is_rigid: ty::IsRigid, item_def_id: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Ty<'tcx> { Ty::new_alias( tcx, @@ -805,7 +805,7 @@ impl<'tcx> Ty<'tcx> { pub fn new_closure( tcx: TyCtxt<'tcx>, def_id: DefId, - closure_args: GenericArgsRef<'tcx>, + closure_args: GenericArgs<'tcx>, ) -> Ty<'tcx> { tcx.debug_assert_args_compatible(def_id, closure_args); Ty::new(tcx, Closure(def_id, closure_args)) @@ -815,7 +815,7 @@ impl<'tcx> Ty<'tcx> { pub fn new_coroutine_closure( tcx: TyCtxt<'tcx>, def_id: DefId, - closure_args: GenericArgsRef<'tcx>, + closure_args: GenericArgs<'tcx>, ) -> Ty<'tcx> { tcx.debug_assert_args_compatible(def_id, closure_args); Ty::new(tcx, CoroutineClosure(def_id, closure_args)) @@ -825,7 +825,7 @@ impl<'tcx> Ty<'tcx> { pub fn new_coroutine( tcx: TyCtxt<'tcx>, def_id: DefId, - coroutine_args: GenericArgsRef<'tcx>, + coroutine_args: GenericArgs<'tcx>, ) -> Ty<'tcx> { tcx.debug_assert_args_compatible(def_id, coroutine_args); Ty::new(tcx, Coroutine(def_id, coroutine_args)) @@ -835,7 +835,7 @@ impl<'tcx> Ty<'tcx> { pub fn new_coroutine_witness( tcx: TyCtxt<'tcx>, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Ty<'tcx> { if cfg!(debug_assertions) { tcx.debug_assert_args_compatible(tcx.typeck_root_def_id(def_id), args); @@ -846,7 +846,7 @@ impl<'tcx> Ty<'tcx> { pub fn new_coroutine_witness_for_coroutine( tcx: TyCtxt<'tcx>, def_id: DefId, - coroutine_args: GenericArgsRef<'tcx>, + coroutine_args: GenericArgs<'tcx>, ) -> Ty<'tcx> { tcx.debug_assert_args_compatible(def_id, coroutine_args); // HACK: Coroutine witness types are lifetime erased, so they @@ -989,7 +989,7 @@ impl<'tcx> rustc_type_ir::inherent::Ty> for Ty<'tcx> { fn new_adt( interner: TyCtxt<'tcx>, adt_def: ty::AdtDef<'tcx>, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Self { Ty::new_adt(interner, adt_def, args) } @@ -1006,30 +1006,26 @@ impl<'tcx> rustc_type_ir::inherent::Ty> for Ty<'tcx> { Ty::new_dynamic(interner, preds, region) } - fn new_coroutine( - interner: TyCtxt<'tcx>, - def_id: DefId, - args: ty::GenericArgsRef<'tcx>, - ) -> Self { + fn new_coroutine(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgs<'tcx>) -> Self { Ty::new_coroutine(interner, def_id, args) } fn new_coroutine_closure( interner: TyCtxt<'tcx>, def_id: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Self { Ty::new_coroutine_closure(interner, def_id, args) } - fn new_closure(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgsRef<'tcx>) -> Self { + fn new_closure(interner: TyCtxt<'tcx>, def_id: DefId, args: ty::GenericArgs<'tcx>) -> Self { Ty::new_closure(interner, def_id, args) } fn new_coroutine_witness( interner: TyCtxt<'tcx>, def_id: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Self { Ty::new_coroutine_witness(interner, def_id, args) } @@ -1037,7 +1033,7 @@ impl<'tcx> rustc_type_ir::inherent::Ty> for Ty<'tcx> { fn new_coroutine_witness_for_coroutine( interner: TyCtxt<'tcx>, def_id: DefId, - coroutine_args: ty::GenericArgsRef<'tcx>, + coroutine_args: ty::GenericArgs<'tcx>, ) -> Self { Ty::new_coroutine_witness_for_coroutine(interner, def_id, coroutine_args) } @@ -1097,7 +1093,7 @@ impl<'tcx> rustc_type_ir::inherent::Ty> for Ty<'tcx> { fn new_fn_def( interner: TyCtxt<'tcx>, def_id: DefId, - args: ty::Binder<'tcx, ty::GenericArgsRef<'tcx>>, + args: ty::Binder<'tcx, ty::GenericArgs<'tcx>>, ) -> Self { Ty::new_fn_def(interner, def_id, args) } @@ -1307,7 +1303,7 @@ impl<'tcx> Ty<'tcx> { ScalableElt::Container => ( NumScalableVectors::from_field_count(def.non_enum_variant().fields.len())?, def.non_enum_variant().fields[FieldIdx::ZERO] - .ty(tcx, args) + .ty(tcx, *args) .skip_norm_wip() .ty_adt_def()?, ), @@ -1317,7 +1313,7 @@ impl<'tcx> Ty<'tcx> { }; let variant = vec_def.non_enum_variant(); assert_eq!(variant.fields.len(), 1); - let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args); + let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, *args); Some((element_count, field_ty.skip_norm_wip(), num_vectors)) } @@ -1328,7 +1324,7 @@ impl<'tcx> Ty<'tcx> { assert!(def.repr().simd(), "`simd_size_and_type` called on non-SIMD type"); let variant = def.non_enum_variant(); assert_eq!(variant.fields.len(), 1); - let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, args); + let field_ty = variant.fields[FieldIdx::ZERO].ty(tcx, *args); let Array(f0_elem_ty, f0_len) = field_ty.skip_norm_wip().kind() else { bug!("Simd type has non-array field type {field_ty:?}") }; diff --git a/compiler/rustc_middle/src/ty/typeck_results.rs b/compiler/rustc_middle/src/ty/typeck_results.rs index 509ff98741731..dcb3f1010d299 100644 --- a/compiler/rustc_middle/src/ty/typeck_results.rs +++ b/compiler/rustc_middle/src/ty/typeck_results.rs @@ -23,8 +23,8 @@ use crate::mir::FakeReadCause; use crate::thir::DerefPatBorrowMode; use crate::traits::ObligationCause; use crate::ty::{ - self, BoundVar, CanonicalPolyFnSig, ClosureSizeProfileData, GenericArgKind, GenericArgs, - GenericArgsRef, Ty, UserArgs, tls, + self, BoundVar, CanonicalPolyFnSig, ClosureSizeProfileData, GenericArgKind, GenericArgs, Ty, + UserArgs, tls, }; #[derive(TyEncodable, TyDecodable, Debug, StableHash)] @@ -54,7 +54,7 @@ pub struct TypeckResults<'tcx> { /// of this node. This only applies to nodes that refer to entities /// parameterized by type parameters, such as generic fns, types, or /// other items. - node_args: ItemLocalMap>, + node_args: ItemLocalMap>, /// This will either store the canonicalized types provided by the user /// or the generic parameters that the user explicitly gave (if any) attached @@ -357,16 +357,16 @@ impl<'tcx> TypeckResults<'tcx> { self.node_types.get(&id.local_id).cloned() } - pub fn node_args_mut(&mut self) -> LocalTableInContextMut<'_, GenericArgsRef<'tcx>> { + pub fn node_args_mut(&mut self) -> LocalTableInContextMut<'_, GenericArgs<'tcx>> { LocalTableInContextMut { hir_owner: self.hir_owner, data: &mut self.node_args } } - pub fn node_args(&self, id: HirId) -> GenericArgsRef<'tcx> { + pub fn node_args(&self, id: HirId) -> GenericArgs<'tcx> { validate_hir_id_for_typeck_results(self.hir_owner, id); self.node_args.get(&id.local_id).cloned().unwrap_or_else(|| GenericArgs::empty()) } - pub fn node_args_opt(&self, id: HirId) -> Option> { + pub fn node_args_opt(&self, id: HirId) -> Option> { validate_hir_id_for_typeck_results(self.hir_owner, id); self.node_args.get(&id.local_id).cloned() } @@ -880,7 +880,7 @@ impl<'tcx> IsIdentity for CanonicalUserType<'tcx> { return false; } - iter::zip(user_args.args, BoundVar::ZERO..).all(|(arg, cvar)| { + iter::zip(user_args.args.as_slice(), BoundVar::ZERO..).all(|(arg, cvar)| { match arg.kind() { GenericArgKind::Type(ty) => match ty.kind() { ty::Bound(debruijn, b) => { diff --git a/compiler/rustc_middle/src/ty/typetree.rs b/compiler/rustc_middle/src/ty/typetree.rs index c2479e0c62bca..a75c7f718a39b 100644 --- a/compiler/rustc_middle/src/ty/typetree.rs +++ b/compiler/rustc_middle/src/ty/typetree.rs @@ -176,7 +176,7 @@ fn typetree_from_ty_impl_inner<'tcx>( let mut types = Vec::new(); for (field_idx, field_def) in adt_def.all_fields().enumerate() { - let field_ty = field_def.ty(tcx, args); + let field_ty = field_def.ty(tcx, *args); let field_tree = typetree_from_ty_impl_inner( tcx, field_ty.skip_norm_wip(), diff --git a/compiler/rustc_middle/src/ty/util.rs b/compiler/rustc_middle/src/ty/util.rs index 83589adb1691b..12228ae721734 100644 --- a/compiler/rustc_middle/src/ty/util.rs +++ b/compiler/rustc_middle/src/ty/util.rs @@ -28,7 +28,7 @@ use crate::query::Providers; use crate::traits::ObligationCause; use crate::ty::layout::{FloatExt, IntegerExt}; use crate::ty::{ - self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgsRef, Ty, TyCtxt, TypeFoldable, + self, Asyncness, FallibleTypeFolder, GenericArgKind, GenericArgs, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, Unnormalized, }; @@ -772,7 +772,7 @@ impl<'tcx> TyCtxt<'tcx> { pub fn try_expand_impl_trait_type( self, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Result, Ty<'tcx>> { let mut visitor = OpaqueTypeExpander { seen_opaque_tys: FxHashSet::default(), @@ -982,7 +982,7 @@ struct OpaqueTypeExpander<'tcx> { seen_opaque_tys: FxHashSet, // Cache of all expansions we've seen so far. This is a critical // optimization for some large types produced by async fn trees. - expanded_cache: FxHashMap<(DefId, GenericArgsRef<'tcx>), Ty<'tcx>>, + expanded_cache: FxHashMap<(DefId, GenericArgs<'tcx>), Ty<'tcx>>, primary_def_id: Option, found_recursion: bool, found_any_recursion: bool, @@ -994,7 +994,7 @@ struct OpaqueTypeExpander<'tcx> { } impl<'tcx> OpaqueTypeExpander<'tcx> { - fn expand_opaque_ty(&mut self, def_id: DefId, args: GenericArgsRef<'tcx>) -> Option> { + fn expand_opaque_ty(&mut self, def_id: DefId, args: GenericArgs<'tcx>) -> Option> { if self.found_any_recursion { return None; } diff --git a/compiler/rustc_mir_build/src/builder/custom/parse/instruction.rs b/compiler/rustc_mir_build/src/builder/custom/parse/instruction.rs index 3241e2b17ece5..c759614798ab2 100644 --- a/compiler/rustc_mir_build/src/builder/custom/parse/instruction.rs +++ b/compiler/rustc_mir_build/src/builder/custom/parse/instruction.rs @@ -376,7 +376,7 @@ impl<'a, 'tcx> ParseCtxt<'a, 'tcx> { let active_field_index = is_union.then(|| fields[0].name); Ok(Rvalue::Aggregate( - Box::new(AggregateKind::Adt(adt_def.did(), *variant_index, args, None, active_field_index)), + Box::new(AggregateKind::Adt(adt_def.did(), *variant_index, *args, None, active_field_index)), fields.iter().map(|f| self.parse_operand(f.expr)).collect::>()? )) }, diff --git a/compiler/rustc_mir_build/src/builder/mod.rs b/compiler/rustc_mir_build/src/builder/mod.rs index 7e6c9f9ac6565..0c532b61aa059 100644 --- a/compiler/rustc_mir_build/src/builder/mod.rs +++ b/compiler/rustc_mir_build/src/builder/mod.rs @@ -887,9 +887,9 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { } let upvar_args = match closure_ty.kind() { - ty::Closure(_, args) => ty::UpvarArgs::Closure(args), - ty::Coroutine(_, args) => ty::UpvarArgs::Coroutine(args), - ty::CoroutineClosure(_, args) => ty::UpvarArgs::CoroutineClosure(args), + ty::Closure(_, args) => ty::UpvarArgs::Closure(*args), + ty::Coroutine(_, args) => ty::UpvarArgs::Coroutine(*args), + ty::CoroutineClosure(_, args) => ty::UpvarArgs::CoroutineClosure(*args), _ => return, }; diff --git a/compiler/rustc_mir_build/src/thir/cx/expr.rs b/compiler/rustc_mir_build/src/thir/cx/expr.rs index 3730446af2c82..5aa86e9140929 100644 --- a/compiler/rustc_mir_build/src/thir/cx/expr.rs +++ b/compiler/rustc_mir_build/src/thir/cx/expr.rs @@ -735,7 +735,7 @@ impl<'tcx> ThirBuildCx<'tcx> { ExprKind::Adt(Box::new(AdtExpr { adt_def: *adt, variant_index: FIRST_VARIANT, - args, + args: *args, user_ty, fields: self.field_refs(fields), base: match base { @@ -778,7 +778,7 @@ impl<'tcx> ThirBuildCx<'tcx> { ExprKind::Adt(Box::new(AdtExpr { adt_def: *adt, variant_index: index, - args, + args: *args, user_ty, fields: self.field_refs(fields), base: match base { @@ -904,9 +904,11 @@ impl<'tcx> ThirBuildCx<'tcx> { let parent_args = tcx.erase_and_anonymize_regions( GenericArgs::identity_for_item(tcx, typeck_root_def_id), ); - let args = - InlineConstArgs::new(tcx, InlineConstArgsParts { parent_args, ty }) - .args; + let args = InlineConstArgs::new( + tcx, + InlineConstArgsParts { parent_args: parent_args.as_slice(), ty }, + ) + .args; let uneval = mir::UnevaluatedConst::new(did.to_def_id(), args); let value = mir::Const::Unevaluated(uneval, ty); @@ -986,7 +988,11 @@ impl<'tcx> ThirBuildCx<'tcx> { tcx, typeck_root_def_id, )); - let args = InlineConstArgs::new(tcx, InlineConstArgsParts { parent_args, ty }).args; + let args = InlineConstArgs::new( + tcx, + InlineConstArgsParts { parent_args: parent_args.as_slice(), ty }, + ) + .args; ExprKind::ConstBlock { did: did.to_def_id(), args } } @@ -1514,7 +1520,7 @@ impl<'tcx> ThirBuildCx<'tcx> { ty::Adt(adt_def, args) => ExprKind::Adt(Box::new(AdtExpr { adt_def: *adt_def, variant_index: adt_def.variant_index_with_ctor_id(def_id), - args, + args: *args, user_ty, fields: Box::new([]), base: AdtExprBase::None, diff --git a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs index 72c2ffbe957e7..bbbc939d6acd3 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/check_match.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/check_match.rs @@ -729,7 +729,7 @@ impl<'p, 'tcx> MatchVisitor<'p, 'tcx> { let variant_inhabited = adt .variant(*variant_index) .inhabited_predicate(self.tcx) - .instantiate(self.tcx, args); + .instantiate(self.tcx, *args); variant_inhabited.apply(self.tcx, cx.typing_env, cx.module) && !variant_inhabited.apply_ignore_module(self.tcx, cx.typing_env) } else { diff --git a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs index 4b97f13f35fef..bd0e142bd3bd6 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/const_to_pat.rs @@ -378,7 +378,7 @@ impl<'tcx> ConstToPat<'tcx> { let variant_index = VariantIdx::from_u32(variant_index.to_leaf().to_u32()); PatKind::Variant { adt_def: *adt_def, - args, + args: *args, variant_index, subpatterns: self .lower_field_values_to_fieldpats(fields.iter().map(|ct| ct.to_value())), diff --git a/compiler/rustc_mir_build/src/thir/pattern/mod.rs b/compiler/rustc_mir_build/src/thir/pattern/mod.rs index 5b7a4d626aae3..62441c833aa48 100644 --- a/compiler/rustc_mir_build/src/thir/pattern/mod.rs +++ b/compiler/rustc_mir_build/src/thir/pattern/mod.rs @@ -543,7 +543,7 @@ impl<'tcx, 'ptcx> PatCtxt<'tcx, 'ptcx> { if adt_def.is_enum() { let args = match ty.kind() { ty::FnDef(_, args) => args.no_bound_vars().unwrap(), - ty::Adt(_, args) => args, + ty::Adt(_, args) => *args, ty::Error(e) => { // Avoid ICE (#50585) return Box::new(Pat { diff --git a/compiler/rustc_mir_dataflow/src/value_analysis.rs b/compiler/rustc_mir_dataflow/src/value_analysis.rs index 128a137a7bb92..c9da55e748260 100644 --- a/compiler/rustc_mir_dataflow/src/value_analysis.rs +++ b/compiler/rustc_mir_dataflow/src/value_analysis.rs @@ -1011,7 +1011,7 @@ pub fn iter_fields<'tcx>( for (v_index, v_def) in def.variants().iter_enumerated() { let variant = if def.is_struct() { None } else { Some(v_index) }; for (f_index, f_def) in v_def.fields.iter().enumerate() { - let field_ty = f_def.ty(tcx, args); + let field_ty = f_def.ty(tcx, *args); let field_ty = tcx.try_normalize_erasing_regions(typing_env, field_ty).unwrap_or_else( |_| tcx.erase_and_anonymize_regions(field_ty.skip_norm_wip()), diff --git a/compiler/rustc_mir_transform/src/check_alignment.rs b/compiler/rustc_mir_transform/src/check_alignment.rs index 326936acb82cf..0c1662c66ef66 100644 --- a/compiler/rustc_mir_transform/src/check_alignment.rs +++ b/compiler/rustc_mir_transform/src/check_alignment.rs @@ -58,8 +58,12 @@ fn insert_alignment_check<'tcx>( // Get the alignment of the pointee let align_def_id = tcx.require_lang_item(LangItem::AlignOf, source_info.span); - let alignment = - Operand::unevaluated_constant(tcx, align_def_id, &[pointee_ty.into()], source_info.span); + let alignment = Operand::unevaluated_constant( + tcx, + align_def_id, + tcx.mk_args(&[pointee_ty.into()]), + source_info.span, + ); // Subtract 1 from the alignment to get the alignment mask let alignment_mask = diff --git a/compiler/rustc_mir_transform/src/check_call_recursion.rs b/compiler/rustc_mir_transform/src/check_call_recursion.rs index aa5649ed9eb2d..4e0d673ea99fc 100644 --- a/compiler/rustc_mir_transform/src/check_call_recursion.rs +++ b/compiler/rustc_mir_transform/src/check_call_recursion.rs @@ -21,15 +21,15 @@ impl<'tcx> MirLint<'tcx> for CheckCallRecursion { if let DefKind::Fn | DefKind::AssocFn = tcx.def_kind(def_id) { // If this is trait/impl method, extract the trait's args. - let trait_args = match tcx.trait_of_assoc(def_id.to_def_id()) { + match tcx.trait_of_assoc(def_id.to_def_id()) { Some(trait_def_id) => { let trait_args_count = tcx.generics_of(trait_def_id).count(); - &GenericArgs::identity_for_item(tcx, def_id)[..trait_args_count] + let args = GenericArgs::identity_for_item(tcx, def_id); + let trait_args = &args.as_slice()[..trait_args_count]; + check_recursion(tcx, body, CallRecursion { trait_args }) } - _ => &[], + _ => check_recursion(tcx, body, CallRecursion { trait_args: &[] }), }; - - check_recursion(tcx, body, CallRecursion { trait_args }) } } } @@ -111,8 +111,8 @@ struct Search<'mir, 'tcx, C: TerminatorClassifier<'tcx>> { reachable_recursive_calls: Vec, } -struct CallRecursion<'tcx> { - trait_args: &'tcx [GenericArg<'tcx>], +struct CallRecursion<'tcx, 'a> { + trait_args: &'a [GenericArg<'tcx>], } struct RecursiveDrop<'tcx> { @@ -120,7 +120,7 @@ struct RecursiveDrop<'tcx> { drop_for: Ty<'tcx>, } -impl<'tcx> TerminatorClassifier<'tcx> for CallRecursion<'tcx> { +impl<'tcx> TerminatorClassifier<'tcx> for CallRecursion<'tcx, '_> { /// Returns `true` if `func` refers to the function we are searching in. fn is_recursive_terminator( &self, @@ -163,7 +163,8 @@ impl<'tcx> TerminatorClassifier<'tcx> for CallRecursion<'tcx> { // calling into an entirely different method (for example, a call from the default // method in the trait to `>::method`, where `A` and/or `B` are // specific types). - return callee == caller && &call_args[..self.trait_args.len()] == self.trait_args; + return callee == caller + && &call_args.as_slice()[..self.trait_args.len()] == self.trait_args; } false diff --git a/compiler/rustc_mir_transform/src/check_null.rs b/compiler/rustc_mir_transform/src/check_null.rs index 37443fed005d7..9cdd8964db4eb 100644 --- a/compiler/rustc_mir_transform/src/check_null.rs +++ b/compiler/rustc_mir_transform/src/check_null.rs @@ -69,8 +69,12 @@ fn insert_null_check<'tcx>( // Other usages of null pointers only are UB if the pointee is not a ZST. _ => { let size_of = tcx.require_lang_item(LangItem::SizeOf, source_info.span); - let size_of = - Operand::unevaluated_constant(tcx, size_of, &[pointee_ty.into()], source_info.span); + let size_of = Operand::unevaluated_constant( + tcx, + size_of, + tcx.mk_args(&[pointee_ty.into()]), + source_info.span, + ); let pointee_should_be_checked = local_decls.push(LocalDecl::with_source_info(tcx.types.bool, source_info)).into(); diff --git a/compiler/rustc_mir_transform/src/coroutine/mod.rs b/compiler/rustc_mir_transform/src/coroutine/mod.rs index 1162399b539b4..726baefa182c4 100644 --- a/compiler/rustc_mir_transform/src/coroutine/mod.rs +++ b/compiler/rustc_mir_transform/src/coroutine/mod.rs @@ -70,7 +70,7 @@ use rustc_index::{Idx, IndexVec, indexvec}; use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor}; use rustc_middle::mir::*; use rustc_middle::ty::{ - self, CoroutineArgs, CoroutineArgsExt, GenericArgsRef, InstanceKind, ShimKind, Ty, TyCtxt, + self, CoroutineArgs, CoroutineArgsExt, GenericArgs, InstanceKind, ShimKind, Ty, TyCtxt, }; use rustc_mir_dataflow::impls::always_storage_live_locals; use rustc_span::def_id::DefId; @@ -541,7 +541,7 @@ impl<'tcx> MutVisitor<'tcx> for TransformVisitor<'tcx> { fn make_aggregate_adt<'tcx>( def_id: DefId, variant_idx: VariantIdx, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, operands: IndexVec>, ) -> Rvalue<'tcx> { Rvalue::Aggregate(Box::new(AggregateKind::Adt(def_id, variant_idx, args, None, None)), operands) diff --git a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs index e52a9a847b119..ab7391b65bd79 100644 --- a/compiler/rustc_mir_transform/src/dataflow_const_prop.rs +++ b/compiler/rustc_mir_transform/src/dataflow_const_prop.rs @@ -844,7 +844,7 @@ fn try_write_constant<'tcx>( }; for (i, field) in variant_def.fields.iter_enumerated() { - let ty = field.ty(*ecx.tcx, args).skip_norm_wip(); + let ty = field.ty(*ecx.tcx, *args).skip_norm_wip(); let Some(field) = map.apply(variant_place, TrackElem::Field(i)) else { throw_machine_stop_str!("missing field in ADT") }; diff --git a/compiler/rustc_mir_transform/src/elaborate_drop.rs b/compiler/rustc_mir_transform/src/elaborate_drop.rs index 6f4a98b1765e8..7d05589b6169a 100644 --- a/compiler/rustc_mir_transform/src/elaborate_drop.rs +++ b/compiler/rustc_mir_transform/src/elaborate_drop.rs @@ -8,7 +8,7 @@ use rustc_index::Idx; use rustc_middle::mir::*; use rustc_middle::ty::adjustment::PointerCoercion; use rustc_middle::ty::util::{Discr, IntTypeExt}; -use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt}; +use rustc_middle::ty::{self, GenericArgs, Ty, TyCtxt}; use rustc_mir_dataflow::DropFlagState; use rustc_span::{DUMMY_SP, bug, dummy_spanned, span_bug}; use tracing::{debug, instrument}; @@ -756,7 +756,7 @@ where base_place: Place<'tcx>, variant_path: D::Path, variant: &'tcx ty::VariantDef, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Vec<(Place<'tcx>, Option)> { variant .fields @@ -976,7 +976,7 @@ where fn open_drop_for_box_contents( &mut self, adt: ty::AdtDef<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, succ: BasicBlock, unwind: Unwind, dropline: Option, @@ -1010,11 +1010,7 @@ where } #[instrument(level = "debug", ret)] - fn open_drop_for_adt( - &mut self, - adt: ty::AdtDef<'tcx>, - args: GenericArgsRef<'tcx>, - ) -> BasicBlock { + fn open_drop_for_adt(&mut self, adt: ty::AdtDef<'tcx>, args: GenericArgs<'tcx>) -> BasicBlock { if adt.variants().is_empty() { return self.new_block(self.unwind, TerminatorKind::Unreachable); } @@ -1058,7 +1054,7 @@ where fn open_drop_for_adt_contents( &mut self, adt: ty::AdtDef<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> (BasicBlock, Unwind, Option) { let (succ, unwind, dropline) = self.drop_ladder_bottom(); if !adt.is_enum() { @@ -1073,7 +1069,7 @@ where fn open_drop_for_multivariant( &mut self, adt: ty::AdtDef<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, succ: BasicBlock, unwind: Unwind, dropline: Option, @@ -1504,7 +1500,7 @@ where // See librustc_body/transform/coroutine.rs for more details. ty::Coroutine(_, args) => self.open_drop_for_tuple(args.as_coroutine().upvar_tys()), ty::Tuple(fields) => self.open_drop_for_tuple(fields), - ty::Adt(def, args) => self.open_drop_for_adt(*def, args), + ty::Adt(def, args) => self.open_drop_for_adt(*def, *args), ty::Dynamic(..) => self.complete_drop(self.succ, self.unwind), ty::Array(ety, size) => { let size = size.try_to_target_usize(self.tcx()); diff --git a/compiler/rustc_mir_transform/src/function_item_references.rs b/compiler/rustc_mir_transform/src/function_item_references.rs index 9bad35731c108..89615b74907b3 100644 --- a/compiler/rustc_mir_transform/src/function_item_references.rs +++ b/compiler/rustc_mir_transform/src/function_item_references.rs @@ -4,7 +4,7 @@ use rustc_hir::def_id::DefId; use rustc_lint_defs::builtin::FUNCTION_ITEM_REFERENCES; use rustc_middle::mir::visit::Visitor; use rustc_middle::mir::*; -use rustc_middle::ty::{self, EarlyBinder, GenericArgsRef, Ty, TyCtxt}; +use rustc_middle::ty::{self, EarlyBinder, GenericArgs, Ty, TyCtxt}; use rustc_span::{Span, Spanned, sym}; use crate::diagnostics; @@ -71,7 +71,7 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { fn check_bound_args( &self, def_id: DefId, - args_ref: GenericArgsRef<'tcx>, + args_ref: GenericArgs<'tcx>, args: &[Spanned>], source_info: SourceInfo, ) { @@ -122,8 +122,8 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { } /// If a type is a reference or raw pointer to the anonymous type of a function definition, - /// returns that function's `DefId` and `GenericArgsRef`. - fn is_fn_ref(ty: Ty<'tcx>) -> Option<(DefId, GenericArgsRef<'tcx>)> { + /// returns that function's `DefId` and `GenericArgs`. + fn is_fn_ref(ty: Ty<'tcx>) -> Option<(DefId, GenericArgs<'tcx>)> { let referent_ty = match ty.kind() { ty::Ref(_, referent_ty, _) => Some(referent_ty), ty::RawPtr(referent_ty, _) => Some(referent_ty), @@ -147,7 +147,7 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { fn emit_lint( &self, fn_id: DefId, - fn_args: GenericArgsRef<'tcx>, + fn_args: GenericArgs<'tcx>, source_info: SourceInfo, span: Span, ) { diff --git a/compiler/rustc_mir_transform/src/gvn.rs b/compiler/rustc_mir_transform/src/gvn.rs index 07215976ef9f3..6519c2770c1fb 100644 --- a/compiler/rustc_mir_transform/src/gvn.rs +++ b/compiler/rustc_mir_transform/src/gvn.rs @@ -1735,7 +1735,7 @@ impl<'body, 'a, 'tcx> VnState<'body, 'a, 'tcx> { || adt_def.all_fields().any(|field| { ty_may_have_ref_inner( tcx, - field.ty(tcx, args).skip_normalization(), + field.ty(tcx, *args).skip_normalization(), depth, ) }) @@ -1849,7 +1849,7 @@ impl<'body, 'a, 'tcx> VnState<'body, 'a, 'tcx> { && adt.repr().transparent() && let [single_field] = adt.non_enum_variant().fields.raw.as_slice() { - Some((FieldIdx::ZERO, single_field.ty(self.tcx, args).skip_norm_wip())) + Some((FieldIdx::ZERO, single_field.ty(self.tcx, *args).skip_norm_wip())) } else { None } diff --git a/compiler/rustc_mir_transform/src/inline.rs b/compiler/rustc_mir_transform/src/inline.rs index 367e16daa8232..501d2c38df170 100644 --- a/compiler/rustc_mir_transform/src/inline.rs +++ b/compiler/rustc_mir_transform/src/inline.rs @@ -1355,7 +1355,7 @@ fn try_instance_mir<'tcx>( { let fields = def.all_fields(); for field in fields { - let field_ty = field.ty(tcx, args); + let field_ty = field.ty(tcx, *args); if field_ty.has_param() && field_ty.has_aliases() { return Err("cannot build drop shim for polymorphic type"); } diff --git a/compiler/rustc_mir_transform/src/inline/cycle.rs b/compiler/rustc_mir_transform/src/inline/cycle.rs index c7115035e4121..ed3fcb1bbc679 100644 --- a/compiler/rustc_mir_transform/src/inline/cycle.rs +++ b/compiler/rustc_mir_transform/src/inline/cycle.rs @@ -2,7 +2,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; use rustc_data_structures::unord::UnordSet; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_middle::mir::TerminatorKind; -use rustc_middle::ty::{self, GenericArgsRef, InstanceKind, ShimKind, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{self, GenericArgs, InstanceKind, ShimKind, TyCtxt, TypeVisitableExt}; use rustc_span::sym; use rustc_structures::Limit; use tracing::{instrument, trace}; @@ -192,7 +192,7 @@ pub(crate) fn mir_callgraph_cyclic<'tcx>( pub(crate) fn mir_inliner_callees<'tcx>( tcx: TyCtxt<'tcx>, instance: ty::InstanceKind<'tcx>, -) -> &'tcx [(DefId, GenericArgsRef<'tcx>)] { +) -> &'tcx [(DefId, GenericArgs<'tcx>)] { let steal; let guard; let body = match (instance, instance.def_id().as_local()) { diff --git a/compiler/rustc_mir_transform/src/instsimplify.rs b/compiler/rustc_mir_transform/src/instsimplify.rs index f1a31db86c6dc..0ac5e5ef72ad5 100644 --- a/compiler/rustc_mir_transform/src/instsimplify.rs +++ b/compiler/rustc_mir_transform/src/instsimplify.rs @@ -7,7 +7,7 @@ use rustc_index::IndexVec; use rustc_middle::mir::visit::MutVisitor; use rustc_middle::mir::*; use rustc_middle::ty::layout::{IntegerExt, ValidityRequirement}; -use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, layout}; +use rustc_middle::ty::{self, GenericArgs, Ty, TyCtxt, layout}; use rustc_span::{Symbol, bug, sym}; use crate::PassPolicy; @@ -303,7 +303,7 @@ impl<'tcx> InstSimplifyContext<'_, 'tcx> { let const_op = Operand::unevaluated_constant( self.tcx, const_def_id, - &[ty.into()], + self.tcx.mk_args(&[ty.into()]), source_info.span, ); statements.push(Statement::new( @@ -407,7 +407,7 @@ impl<'tcx> InstSimplifyContext<'_, 'tcx> { return; }; // The intrinsics we are interested in have one generic parameter - let [arg, ..] = args[..] else { return }; + let [arg, ..] = *args.as_slice() else { return }; let known_is_valid = intrinsic_assert_panics(self.tcx, self.typing_env, arg, intrinsic_name); @@ -440,7 +440,7 @@ fn intrinsic_assert_panics<'tcx>( fn resolve_rust_intrinsic<'tcx>( tcx: TyCtxt<'tcx>, func_ty: Ty<'tcx>, -) -> Option<(Symbol, GenericArgsRef<'tcx>)> { +) -> Option<(Symbol, GenericArgs<'tcx>)> { let ty::FnDef(def_id, args) = *func_ty.kind() else { return None }; let intrinsic = tcx.intrinsic(def_id)?; Some((intrinsic.name, args.no_bound_vars().unwrap())) diff --git a/compiler/rustc_mir_transform/src/liveness.rs b/compiler/rustc_mir_transform/src/liveness.rs index 77b8cfa3b86c2..d2eac09a3ffcd 100644 --- a/compiler/rustc_mir_transform/src/liveness.rs +++ b/compiler/rustc_mir_transform/src/liveness.rs @@ -97,7 +97,7 @@ pub(crate) fn check_liveness<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Den let (capture_kind, args) = match self_ty.kind() { ty::Closure(_, args) => { - (CaptureKind::Closure(args.as_closure().kind()), ty::UpvarArgs::Closure(args)) + (CaptureKind::Closure(args.as_closure().kind()), ty::UpvarArgs::Closure(*args)) } &ty::Coroutine(_, args) => (CaptureKind::Coroutine, ty::UpvarArgs::Coroutine(args)), &ty::CoroutineClosure(_, args) => { diff --git a/compiler/rustc_mir_transform/src/post_analysis_normalize.rs b/compiler/rustc_mir_transform/src/post_analysis_normalize.rs index 78f97c2eb1448..cc5e5bb9b63df 100644 --- a/compiler/rustc_mir_transform/src/post_analysis_normalize.rs +++ b/compiler/rustc_mir_transform/src/post_analysis_normalize.rs @@ -89,7 +89,7 @@ impl<'tcx> MutVisitor<'tcx> for PostAnalysisNormalizeVisitor<'tcx> { } #[inline] - fn visit_args(&mut self, args: &mut ty::GenericArgsRef<'tcx>, _: Location) { + fn visit_args(&mut self, args: &mut ty::GenericArgs<'tcx>, _: Location) { if let Ok(a) = self.tcx.try_normalize_erasing_regions( self.typing_env, ty::set_aliases_to_non_rigid(self.tcx, *args), diff --git a/compiler/rustc_mir_transform/src/remove_uninit_drops.rs b/compiler/rustc_mir_transform/src/remove_uninit_drops.rs index 74cac4c8481f0..8442c65fcf0ff 100644 --- a/compiler/rustc_mir_transform/src/remove_uninit_drops.rs +++ b/compiler/rustc_mir_transform/src/remove_uninit_drops.rs @@ -1,7 +1,7 @@ use rustc_abi::FieldIdx; use rustc_index::bit_set::MixedBitSet; use rustc_middle::mir::{Body, TerminatorKind}; -use rustc_middle::ty::{self, GenericArgsRef, Ty, TyCtxt, VariantDef}; +use rustc_middle::ty::{self, GenericArgs, Ty, TyCtxt, VariantDef}; use rustc_mir_dataflow::impls::MaybeInitializedPlaces; use rustc_mir_dataflow::move_paths::{LookupResult, MoveData, MovePathIndex}; use rustc_mir_dataflow::{Analysis, MaybeReachable, move_path_children_matching}; @@ -118,7 +118,7 @@ fn is_needs_drop_and_init<'tcx>( let downcast = move_path_children_matching(move_data, mpi, |x| x.is_downcast_to(vid)); let Some(dc_mpi) = downcast else { - return variant_needs_drop(tcx, typing_env, args, variant); + return variant_needs_drop(tcx, typing_env, *args, variant); }; dc_mpi @@ -131,7 +131,7 @@ fn is_needs_drop_and_init<'tcx>( .iter() .enumerate() .map(|(f, field)| { - (FieldIdx::from_usize(f), field.ty(tcx, args).skip_norm_wip(), mpi) + (FieldIdx::from_usize(f), field.ty(tcx, *args).skip_norm_wip(), mpi) }) .any(field_needs_drop_and_init) }) @@ -150,7 +150,7 @@ fn is_needs_drop_and_init<'tcx>( fn variant_needs_drop<'tcx>( tcx: TyCtxt<'tcx>, typing_env: ty::TypingEnv<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, variant: &VariantDef, ) -> bool { variant.fields.iter().any(|field| { diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index f1d85166653ff..f117950a0eb8a 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -1028,7 +1028,7 @@ pub(super) fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> { // return; debug!("build_ctor: variant_index={:?}", variant_index); - let kind = AggregateKind::Adt(adt_def.did(), variant_index, args, None, None); + let kind = AggregateKind::Adt(adt_def.did(), variant_index, *args, None, None); let variant = adt_def.variant(variant_index); let statement = Statement::new( source_info, diff --git a/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs b/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs index 7530716e8cf39..d020d536fc693 100644 --- a/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs +++ b/compiler/rustc_mir_transform/src/shim/async_destructor_ctor.rs @@ -68,7 +68,7 @@ pub(super) fn build_async_drop_shim<'tcx>( let needs_sync_drop = !needs_async_drop && drop_ty.needs_drop(tcx, typing_env); let resume_adt = tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, DUMMY_SP)); - let resume_ty = Ty::new_adt(tcx, resume_adt, ty::List::empty()); + let resume_ty = Ty::new_adt(tcx, resume_adt, ty::GenericArgs::empty()); let fn_sig = ty::Binder::dummy(tcx.mk_fn_sig_safe_rust_abi([ty, resume_ty], tcx.types.unit)); let sig = tcx.instantiate_bound_regions_with_erased(fn_sig); diff --git a/compiler/rustc_mir_transform/src/validate.rs b/compiler/rustc_mir_transform/src/validate.rs index 7056b1b1619fb..7238dbfbb4da1 100644 --- a/compiler/rustc_mir_transform/src/validate.rs +++ b/compiler/rustc_mir_transform/src/validate.rs @@ -736,7 +736,7 @@ impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> { fail_out_of_bounds(self, location); return; }; - check_equal(self, location, field.ty(self.tcx, args).skip_norm_wip()); + check_equal(self, location, field.ty(self.tcx, *args).skip_norm_wip()); } ty::Closure(_, args) => { let args = args.as_closure(); diff --git a/compiler/rustc_passes/src/canonical_symbols.rs b/compiler/rustc_passes/src/canonical_symbols.rs index afecab452bf3d..4e70755ef6c18 100644 --- a/compiler/rustc_passes/src/canonical_symbols.rs +++ b/compiler/rustc_passes/src/canonical_symbols.rs @@ -1,7 +1,7 @@ use rustc_attr_ir::{CanonicalSymbols, find_attr}; use rustc_hir::ForeignItemId; use rustc_middle::query::{LocalCrate, Providers}; -use rustc_middle::ty::{Instance, List, TyCtxt}; +use rustc_middle::ty::{GenericArgs, Instance, TyCtxt}; use rustc_span::def_id::{DefId, LOCAL_CRATE}; use rustc_span::{Symbol, sym}; @@ -15,7 +15,7 @@ fn observe_item<'tcx>( let attrs = tcx.hir_attrs(fid.owner_id.into()); if find_attr!(attrs, RustcCanonicalSymbol) { let did = fid.owner_id.def_id; - let instance = Instance::new_raw(did.to_def_id(), List::identity_for_item(tcx, did)); + let instance = Instance::new_raw(did.to_def_id(), GenericArgs::identity_for_item(tcx, did)); let symbol_name = tcx.symbol_name(instance); let symbol_name = Symbol::intern(symbol_name.name); diff --git a/compiler/rustc_pattern_analysis/src/rustc.rs b/compiler/rustc_pattern_analysis/src/rustc.rs index 5e6b682626210..ea46150ed7ca2 100644 --- a/compiler/rustc_pattern_analysis/src/rustc.rs +++ b/compiler/rustc_pattern_analysis/src/rustc.rs @@ -192,7 +192,7 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { ) -> impl Iterator)> { let ty::Adt(_, args) = ty.kind() else { bug!() }; variant.fields.iter().map(move |field| { - let ty = field.ty(self.tcx, args); + let ty = field.ty(self.tcx, *args); // `field.ty()` doesn't normalize after instantiating. let ty = self.tcx.try_normalize_erasing_regions(self.typing_env, ty).unwrap_or_else(|e| { @@ -380,7 +380,7 @@ impl<'p, 'tcx: 'p> RustcPatCtxt<'p, 'tcx> { // Visibly uninhabited variants. let is_inhabited = v .inhabited_predicate(cx.tcx) - .instantiate(cx.tcx, args) + .instantiate(cx.tcx, *args) .apply_revealing_opaque(cx.tcx, cx.typing_env, cx.module, &|key| { cx.reveal_opaque_key(key) }); diff --git a/compiler/rustc_public/src/unstable/convert/internal.rs b/compiler/rustc_public/src/unstable/convert/internal.rs index e8a089fd86f60..8fb176bbeca72 100644 --- a/compiler/rustc_public/src/unstable/convert/internal.rs +++ b/compiler/rustc_public/src/unstable/convert/internal.rs @@ -56,7 +56,7 @@ impl RustcInternal for DefId { } impl RustcInternal for GenericArgs { - type T<'tcx> = rustc_ty::GenericArgsRef<'tcx>; + type T<'tcx> = rustc_ty::GenericArgs<'tcx>; fn internal<'tcx>( &self, tables: &mut Tables<'_, BridgeTys>, diff --git a/compiler/rustc_public/src/unstable/internal_cx/helpers.rs b/compiler/rustc_public/src/unstable/internal_cx/helpers.rs index da635c04d7442..04602ee8e18b5 100644 --- a/compiler/rustc_public/src/unstable/internal_cx/helpers.rs +++ b/compiler/rustc_public/src/unstable/internal_cx/helpers.rs @@ -9,7 +9,7 @@ pub(crate) trait ExistentialProjectionHelpers<'tcx> { fn new_from_args( &self, def_id: rustc_span::def_id::DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, term: ty::Term<'tcx>, ) -> ty::ExistentialProjection<'tcx>; } @@ -18,7 +18,7 @@ pub(crate) trait ExistentialTraitRefHelpers<'tcx> { fn new_from_args( &self, trait_def_id: rustc_span::def_id::DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> ty::ExistentialTraitRef<'tcx>; } @@ -26,6 +26,6 @@ pub(crate) trait TraitRefHelpers<'tcx> { fn new_from_args( &self, trait_def_id: rustc_span::def_id::DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> ty::TraitRef<'tcx>; } diff --git a/compiler/rustc_public/src/unstable/internal_cx/mod.rs b/compiler/rustc_public/src/unstable/internal_cx/mod.rs index f178ced7224c1..ea152818f7470 100644 --- a/compiler/rustc_public/src/unstable/internal_cx/mod.rs +++ b/compiler/rustc_public/src/unstable/internal_cx/mod.rs @@ -12,7 +12,7 @@ impl<'tcx, T: InternalCx<'tcx>> ExistentialProjectionHelpers<'tcx> for T { fn new_from_args( &self, def_id: rustc_span::def_id::DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, term: ty::Term<'tcx>, ) -> ty::ExistentialProjection<'tcx> { ty::ExistentialProjection::new_from_args(self.tcx(), def_id, args, term) @@ -23,7 +23,7 @@ impl<'tcx, T: InternalCx<'tcx>> ExistentialTraitRefHelpers<'tcx> for T { fn new_from_args( &self, trait_def_id: rustc_span::def_id::DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> ty::ExistentialTraitRef<'tcx> { ty::ExistentialTraitRef::new_from_args(self.tcx(), trait_def_id, args) } @@ -33,7 +33,7 @@ impl<'tcx, T: InternalCx<'tcx>> TraitRefHelpers<'tcx> for T { fn new_from_args( &self, trait_def_id: rustc_span::def_id::DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> ty::TraitRef<'tcx> { ty::TraitRef::new_from_args(self.tcx(), trait_def_id, args) } @@ -51,7 +51,7 @@ impl<'tcx> InternalCx<'tcx> for TyCtxt<'tcx> { fn mk_args_from_iter(self, iter: I) -> T::Output where I: Iterator, - T: ty::CollectAndApply, ty::GenericArgsRef<'tcx>>, + T: ty::CollectAndApply, ty::GenericArgs<'tcx>>, { TyCtxt::mk_args_from_iter(self, iter) } diff --git a/compiler/rustc_public/src/unstable/mod.rs b/compiler/rustc_public/src/unstable/mod.rs index c8eba987134f9..05e98eb4cba69 100644 --- a/compiler/rustc_public/src/unstable/mod.rs +++ b/compiler/rustc_public/src/unstable/mod.rs @@ -31,7 +31,7 @@ pub trait InternalCx<'tcx>: Copy + Clone { fn mk_args_from_iter(self, iter: I) -> T::Output where I: Iterator, - T: ty::CollectAndApply, ty::GenericArgsRef<'tcx>>; + T: ty::CollectAndApply, ty::GenericArgs<'tcx>>; fn mk_pat(self, v: ty::PatternKind<'tcx>) -> ty::Pattern<'tcx>; diff --git a/compiler/rustc_public_bridge/src/context/impls.rs b/compiler/rustc_public_bridge/src/context/impls.rs index cf36e9819b6a6..179707b08fb81 100644 --- a/compiler/rustc_public_bridge/src/context/impls.rs +++ b/compiler/rustc_public_bridge/src/context/impls.rs @@ -18,9 +18,9 @@ use rustc_middle::ty::print::{ use rustc_middle::ty::util::Discr; use rustc_middle::ty::{ AdtDef, AdtKind, AssocItem, Binder, ClosureKind, CoroutineArgsExt, EarlyBinder, - ExistentialTraitRef, FnSig, GenericArgsRef, Instance, InstanceKind, IntrinsicDef, List, - PolyFnSig, ScalarInt, TraitDef, TraitRef, Ty, TyCtxt, TyKind, TypeVisitableExt, UintTy, - ValTree, VariantDef, VtblEntry, + ExistentialTraitRef, FnSig, GenericArgs, Instance, InstanceKind, IntrinsicDef, List, PolyFnSig, + ScalarInt, TraitDef, TraitRef, Ty, TyCtxt, TyKind, TypeVisitableExt, UintTy, ValTree, + VariantDef, VtblEntry, }; use rustc_middle::{mir, ty}; use rustc_span::def_id::{CrateNum, DefId, LOCAL_CRATE}; @@ -389,11 +389,7 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { } /// Retrieve the function signature for the given generic arguments. - pub fn fn_sig( - &self, - def_id: DefId, - args_ref: GenericArgsRef<'tcx>, - ) -> Binder<'tcx, FnSig<'tcx>> { + pub fn fn_sig(&self, def_id: DefId, args_ref: GenericArgs<'tcx>) -> Binder<'tcx, FnSig<'tcx>> { let sig = self.tcx.fn_sig(def_id).instantiate(self.tcx, args_ref).skip_norm_wip(); sig } @@ -420,7 +416,7 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { } /// Retrieve the closure signature for the given generic arguments. - pub fn closure_sig(&self, args_ref: GenericArgsRef<'tcx>) -> Binder<'tcx, FnSig<'tcx>> { + pub fn closure_sig(&self, args_ref: GenericArgs<'tcx>) -> Binder<'tcx, FnSig<'tcx>> { args_ref.as_closure().sig() } @@ -442,7 +438,7 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { pub fn coroutine_discr_for_variant( &self, coroutine: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, variant: rustc_abi::VariantIdx, ) -> Discr<'tcx> { args.as_coroutine().discriminant_for_variant(coroutine, self.tcx, variant) @@ -571,7 +567,7 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { } /// Returns the type of given definition instantiated with the given arguments. - pub fn def_ty_with_args(&self, item: DefId, args_ref: GenericArgsRef<'tcx>) -> Ty<'tcx> { + pub fn def_ty_with_args(&self, item: DefId, args_ref: GenericArgs<'tcx>) -> Ty<'tcx> { let def_ty = self.tcx.type_of(item); self.tcx.instantiate_and_normalize_erasing_regions(args_ref, self.typing_env(), def_ty) } @@ -613,7 +609,7 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { } /// Get the instantiation types. - pub fn instance_args(&self, instance: ty::Instance<'tcx>) -> GenericArgsRef<'tcx> { + pub fn instance_args(&self, instance: ty::Instance<'tcx>) -> GenericArgs<'tcx> { instance.args } @@ -676,7 +672,7 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { pub fn resolve_instance( &self, def_id: DefId, - args_ref: GenericArgsRef<'tcx>, + args_ref: GenericArgs<'tcx>, ) -> Option> { match Instance::try_resolve(self.tcx, self.typing_env(), def_id, args_ref) { Ok(Some(instance)) => Some(instance), @@ -694,7 +690,7 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { pub fn resolve_for_fn_ptr( &self, def_id: DefId, - args_ref: GenericArgsRef<'tcx>, + args_ref: GenericArgs<'tcx>, ) -> Option> { Instance::resolve_for_fn_ptr(self.tcx, self.typing_env(), def_id, args_ref) } @@ -703,7 +699,7 @@ impl<'tcx, B: Bridge> CompilerCtxt<'tcx, B> { pub fn resolve_closure( &self, def_id: DefId, - args_ref: GenericArgsRef<'tcx>, + args_ref: GenericArgs<'tcx>, closure_kind: ClosureKind, ) -> Option> { Some(Instance::resolve_closure(self.tcx, def_id, args_ref, closure_kind)) diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs index e0f68b37b0a7f..30275f9f7244e 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/encode.rs @@ -14,7 +14,7 @@ use rustc_data_structures::fx::FxHashMap; use rustc_hir as hir; use rustc_middle::ty::layout::IntegerExt; use rustc_middle::ty::{ - self, Const, ExistentialPredicate, FloatTy, FnSig, GenericArg, GenericArgKind, GenericArgsRef, + self, Const, ExistentialPredicate, FloatTy, FnSig, GenericArg, GenericArgKind, GenericArgs, IntTy, List, Region, RegionKind, TermKind, Ty, TyCtxt, TypeFoldable, UintTy, }; use rustc_span::bug; @@ -67,7 +67,7 @@ fn compress<'tcx>( /// types that are not used at the FFI boundary. fn encode_args<'tcx>( tcx: TyCtxt<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, for_def: DefId, has_erased_self: bool, dict: &mut FxHashMap, usize>, @@ -593,7 +593,7 @@ pub(crate) fn encode_ty<'tcx>( // , as vendor extended type. let name = encode_ty_name(tcx, def_id); let _ = write!(s, "u{}{}", name.len(), name); - s.push_str(&encode_args(tcx, args, def_id, false, dict, options)); + s.push_str(&encode_args(tcx, *args, def_id, false, dict, options)); compress(dict, DictKey::Ty(ty, TyQ::None), &mut s); } typeid.push_str(&s); @@ -621,7 +621,7 @@ pub(crate) fn encode_ty<'tcx>( let mut s = String::new(); let name = encode_ty_name(tcx, *def_id); let _ = write!(s, "u{}{}", name.len(), name); - s.push_str(&encode_args(tcx, args, *def_id, false, dict, options)); + s.push_str(&encode_args(tcx, *args, *def_id, false, dict, options)); compress(dict, DictKey::Ty(ty, TyQ::None), &mut s); typeid.push_str(&s); } diff --git a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs index ba89f40b60254..e0c8dbd6a3d16 100644 --- a/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs +++ b/compiler/rustc_sanitizers/src/cfi/typeid/itanium_cxx_abi/transform.rs @@ -157,7 +157,7 @@ impl<'tcx> TypeFolder> for TransformTy<'tcx> { if let Some(field) = field { let ty0 = self.tcx.normalize_erasing_regions( ty::TypingEnv::fully_monomorphized(), - field.ty(self.tcx, args), + field.ty(self.tcx, *args), ); // Generalize any repr(transparent) user-defined type that is either a // pointer or reference, and either references itself or any other type that @@ -415,7 +415,7 @@ fn transform_drop_glue<'tcx>(tcx: TyCtxt<'tcx>, mut instance: Instance<'tcx>) -> let predicate = ty::ExistentialPredicate::Trait(ty::ExistentialTraitRef::new_from_args( tcx, trait_id, - ty::List::empty(), + ty::GenericArgs::empty(), )); let predicates = tcx.mk_poly_existential_predicates(&[ty::Binder::dummy(predicate)]); let self_ty = Ty::new_dynamic(tcx, predicates, tcx.lifetimes.re_erased); diff --git a/compiler/rustc_symbol_mangling/src/export.rs b/compiler/rustc_symbol_mangling/src/export.rs index 9f9c30abe2c1b..65caeb4f63d97 100644 --- a/compiler/rustc_symbol_mangling/src/export.rs +++ b/compiler/rustc_symbol_mangling/src/export.rs @@ -96,7 +96,7 @@ impl<'tcx> AbiStableHash<'tcx> for Ty<'tcx> { field_ty.abi_stable_hash(tcx, hasher); } } - args.abi_stable_hash(tcx, hasher); + args.as_slice().abi_stable_hash(tcx, hasher); } ty::Tuple(args) if args.len() == 0 => {} diff --git a/compiler/rustc_symbol_mangling/src/legacy.rs b/compiler/rustc_symbol_mangling/src/legacy.rs index b95082d9dbe71..afc0c7be687c6 100644 --- a/compiler/rustc_symbol_mangling/src/legacy.rs +++ b/compiler/rustc_symbol_mangling/src/legacy.rs @@ -65,6 +65,7 @@ pub(super) fn mangle<'tcx>( let hash = get_symbol_hash(tcx, instance, instance_ty, instantiating_crate); let mut p = LegacySymbolMangler { tcx, path: SymbolPath::new(), keep_within_component: false }; + p.print_def_path( def_id, if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, _)) @@ -72,7 +73,7 @@ pub(super) fn mangle<'tcx>( | ty::InstanceKind::Shim(ty::ShimKind::FutureDropPoll(_, _, _)) = instance.def { // Add the name of the dropped type to the symbol name - &*instance.args + instance.args } else if let ty::InstanceKind::Shim(ty::ShimKind::AsyncDropGlue(_, ty)) = instance.def { let ty::Coroutine(_, cor_args) = ty.kind() else { bug!(); @@ -80,7 +81,7 @@ pub(super) fn mangle<'tcx>( let drop_ty = cor_args.first().unwrap().expect_ty(); tcx.mk_args(&[GenericArg::from(drop_ty)]) } else { - &[] + ty::GenericArgs::empty() }, ) .unwrap(); @@ -399,12 +400,11 @@ impl<'tcx> Printer<'tcx> for LegacySymbolMangler<'tcx> { fn print_path_with_generic_args( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - args: &[GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { print_prefix(self)?; - let args = - args.iter().cloned().filter(|arg| !matches!(arg.kind(), GenericArgKind::Lifetime(_))); + let args = args.iter().filter(|arg| !matches!(arg.kind(), GenericArgKind::Lifetime(_))); if args.clone().next().is_some() { self.generic_delimiters(|cx| cx.comma_sep(args)) } else { @@ -415,7 +415,7 @@ impl<'tcx> Printer<'tcx> for LegacySymbolMangler<'tcx> { fn print_impl_path( &mut self, impl_def_id: DefId, - args: &'tcx [GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { let self_ty = self.tcx.type_of(impl_def_id); let impl_trait_ref = self.tcx.impl_opt_trait_ref(impl_def_id); @@ -434,7 +434,7 @@ impl<'tcx> Printer<'tcx> for LegacySymbolMangler<'tcx> { // NOTE: We don't support mangling partially substituted but still polymorphic // instances, like `impl Tr for ()` where `A` is substituted w/ `(T,)`. let (typing_env, mut self_ty, mut impl_trait_ref) = if generics.count() > args.len() - || &args[..generics.count()] + || &args.as_slice()[..generics.count()] == self .tcx .erase_and_anonymize_regions(ty::GenericArgs::identity_for_item( diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index 7bab29c658e66..6157085d9546d 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -78,14 +78,14 @@ pub(super) fn mangle<'tcx>( bug!(); }; let drop_ty = cor_args.first().unwrap().expect_ty(); - p.print_def_path(def_id, tcx.mk_args(&[GenericArg::from(drop_ty)])).unwrap() + p.print_def_path(def_id, p.tcx().mk_args(&[GenericArg::from(drop_ty)])).unwrap() } else if let Some(shim_kind) = shim_kind { p.path_append_ns(|p| p.print_def_path(def_id, args), 'S', 0, shim_kind).unwrap() } else { p.print_def_path(def_id, args).unwrap() }; if let Some(instantiating_crate) = instantiating_crate { - p.print_def_path(instantiating_crate.as_def_id(), &[]).unwrap(); + p.print_def_path(instantiating_crate.as_def_id(), ty::GenericArgs::empty()).unwrap(); } std::mem::take(&mut p.out) } @@ -106,13 +106,24 @@ pub fn mangle_cgu<'tcx>(tcx: TyCtxt<'tcx>, krate: CrateNum, cgu_name: Either { // If we have a CGU index, we can easily encode this with the shim mechanism. - p.path_append_ns(|p| p.print_def_path(krate.as_def_id(), &[]), 'S', cgu_index, "cgu") - .unwrap(); + p.path_append_ns( + |p| p.print_def_path(krate.as_def_id(), ty::GenericArgs::empty()), + 'S', + cgu_index, + "cgu", + ) + .unwrap(); } Either::Right(name) => { // In incremental compilation we just have a name and no index. Encode this as a str-typed generic argument to cgu shim for now. p.out.push('I'); - p.path_append_ns(|p| p.print_def_path(krate.as_def_id(), &[]), 'S', 0, "cgu").unwrap(); + p.path_append_ns( + |p| p.print_def_path(krate.as_def_id(), ty::GenericArgs::empty()), + 'S', + 0, + "cgu", + ) + .unwrap(); p.push("KRe"); for byte in name.as_bytes() { @@ -199,7 +210,7 @@ pub(super) fn mangle_typeid_for_trait_ref<'tcx>( binders: vec![], out: String::new(), }; - p.print_def_path(trait_ref.def_id, &[]).unwrap(); + p.print_def_path(trait_ref.def_id, ty::GenericArgs::empty()).unwrap(); std::mem::take(&mut p.out) } @@ -226,7 +237,7 @@ struct V0SymbolMangler<'tcx> { /// The length of the prefix in `out` (e.g. 2 for `_R`). start_offset: usize, /// The values are start positions in `out`, in bytes. - paths: FxHashMap<(DefId, &'tcx [GenericArg<'tcx>]), usize>, + paths: FxHashMap<(DefId, ty::GenericArgs<'tcx>), usize>, types: FxHashMap, usize>, consts: FxHashMap, usize>, } @@ -342,7 +353,7 @@ impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> { fn print_def_path( &mut self, def_id: DefId, - args: &'tcx [GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { if let Some(&i) = self.paths.get(&(def_id, args)) { return self.print_backref(i); @@ -362,7 +373,7 @@ impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> { fn print_impl_path( &mut self, impl_def_id: DefId, - args: &'tcx [GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { let key = self.tcx.def_key(impl_def_id); let parent_def_id = DefId { index: key.parent.unwrap(), ..impl_def_id }; @@ -384,7 +395,7 @@ impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> { // NOTE: We don't support mangling partially substituted but still polymorphic // instances, like `impl Tr for ()` where `A` is substituted w/ `(T,)`. let (typing_env, mut self_ty, mut impl_trait_ref) = if generics.count() > args.len() - || &args[..generics.count()] + || &args.as_slice()[..generics.count()] == self .tcx .erase_and_anonymize_regions(ty::GenericArgs::identity_for_item( @@ -439,7 +450,7 @@ impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> { self.print_path_with_generic_args( |this| { this.path_append_ns( - |p| p.print_def_path(parent_def_id, &[]), + |p| p.print_def_path(parent_def_id, ty::GenericArgs::empty()), 'I', key.disambiguated_data.disambiguator as u64, "", @@ -456,7 +467,7 @@ impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> { } }; self.push_disambiguator(disambiguator); - self.print_def_path(parent_def_id, &[])?; + self.print_def_path(parent_def_id, ty::GenericArgs::empty())?; } self_ty.print(self)?; @@ -607,7 +618,7 @@ impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> { } ty::Foreign(def_id) => { - self.print_def_path(def_id, &[])?; + self.print_def_path(def_id, ty::GenericArgs::empty())?; } ty::FnPtr(sig_tys, hdr) => { @@ -729,7 +740,7 @@ impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> { }?; } ty::ExistentialPredicate::AutoTrait(def_id) => { - p.print_def_path(*def_id, &[])?; + p.print_def_path(*def_id, ty::GenericArgs::empty())?; } } } @@ -877,7 +888,7 @@ impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> { let variant_def = &def.variant(variant_idx); self.push("V"); - self.print_def_path(variant_def.def_id, args)?; + self.print_def_path(variant_def.def_id, *args)?; match variant_def.ctor_kind() { Some(CtorKind::Const) => { @@ -999,14 +1010,14 @@ impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> { fn print_path_with_generic_args( &mut self, print_prefix: impl FnOnce(&mut Self) -> Result<(), PrintError>, - args: &[GenericArg<'tcx>], + args: ty::GenericArgs<'tcx>, ) -> Result<(), PrintError> { // Don't print any regions if they're all erased. let print_regions = args.iter().any(|arg| match arg.kind() { GenericArgKind::Lifetime(r) => !r.is_erased(), _ => false, }); - let args = args.iter().cloned().filter(|arg| match arg.kind() { + let args = args.iter().filter(|arg| match arg.kind() { GenericArgKind::Lifetime(_) => print_regions, _ => true, }); diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs index eada6d2457e75..c0097dc5a60c0 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs @@ -713,7 +713,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { t1_out: &mut DiagStyledString, t2_out: &mut DiagStyledString, path: String, - args: &'tcx [ty::GenericArg<'tcx>], + args: &[ty::GenericArg<'tcx>], other_path: String, other_ty: Ty<'tcx>, ) -> bool { @@ -752,9 +752,9 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn cmp_fn_sig( &self, sig1: ty::PolyFnSig<'tcx>, - fn_def1: Option<(DefId, Option<&'tcx [ty::GenericArg<'tcx>]>)>, + fn_def1: Option<(DefId, Option>)>, sig2: ty::PolyFnSig<'tcx>, - fn_def2: Option<(DefId, Option<&'tcx [ty::GenericArg<'tcx>]>)>, + fn_def2: Option<(DefId, Option>)>, ) -> (DiagStyledString, DiagStyledString) { let sig1 = self.normalize_fn_sig(Unnormalized::new_wip(sig1)); let sig2 = self.normalize_fn_sig(Unnormalized::new_wip(sig2)); @@ -1174,7 +1174,9 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // process starts here match (t1.kind(), t2.kind()) { - (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => { + (&ty::Adt(def1, sub1_args), &ty::Adt(def2, sub2_args)) => { + let sub1 = sub1_args.as_slice(); + let sub2 = sub2_args.as_slice(); let did1 = def1.did(); let did2 = def2.did(); @@ -1182,8 +1184,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let generics2 = self.tcx.generics_of(did2); let non_default_after_default = generics1 - .check_concrete_type_after_default(self.tcx, sub1) - || generics2.check_concrete_type_after_default(self.tcx, sub2); + .check_concrete_type_after_default(self.tcx, sub1_args) + || generics2.check_concrete_type_after_default(self.tcx, sub2_args); let sub_no_defaults_1 = if non_default_after_default { generics1.own_args(sub1) } else { @@ -1407,8 +1409,8 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { }} } // We skip the type of `Self`: - let args1 = &trait_ref1.args[1..]; - let args2 = &trait_ref2.args[1..]; + let args1 = &trait_ref1.args.as_slice()[1..]; + let args2 = &trait_ref2.args.as_slice()[1..]; self.compare_generics(&mut values, args1, args2); } else { values @@ -2187,7 +2189,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { fn format_on_type_error_notes( &self, directive: &Directive, - args: &ty::GenericArgsRef<'tcx>, + args: &ty::GenericArgs<'tcx>, item_def: ty::AdtDef<'tcx>, expected_ty: Ty<'tcx>, found_ty: Ty<'tcx>, @@ -2484,9 +2486,9 @@ impl<'tcx> TypeRelation> for SameTypeModuloInfer<'_, 'tcx> { a_ty: Ty<'tcx>, _: Ty<'tcx>, _: DefId, - a_args: ty::GenericArgsRef<'tcx>, - b_args: ty::GenericArgsRef<'tcx>, - _: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>, + a_args: ty::GenericArgs<'tcx>, + b_args: ty::GenericArgs<'tcx>, + _: impl FnOnce(ty::GenericArgs<'tcx>) -> Ty<'tcx>, ) -> RelateResult<'tcx, Ty<'tcx>> { relate::relate_args_invariantly(self, a_args, b_args)?; Ok(a_ty) diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs index e4cf2a40bd3fc..07859f505e8f3 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/need_type_info.rs @@ -14,9 +14,9 @@ use rustc_middle::hir::nested_filter; use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, DerefAdjustKind}; use rustc_middle::ty::print::{FmtPrinter, PrettyPrinter, Print, Printer}; use rustc_middle::ty::{ - self, GenericArg, GenericArgKind, GenericArgsRef, GenericParamDefKind, InferConst, - IsSuggestable, Term, TermKind, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, - TypeVisitableExt, TypeckResults, + self, GenericArg, GenericArgKind, GenericArgs, GenericParamDefKind, InferConst, IsSuggestable, + Term, TermKind, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeVisitableExt, + TypeckResults, }; use rustc_next_trait_solver::solve::TyOrConstInferVar; use rustc_span::{BytePos, DUMMY_SP, Ident, Span, bug, sym}; @@ -647,7 +647,7 @@ enum InferSourceKind<'tcx> { argument_index: usize, generics_def_id: DefId, def_id: DefId, - generic_args: &'tcx [GenericArg<'tcx>], + generic_args: GenericArgs<'tcx>, have_turbofish: bool, hir_id: HirId, }, @@ -656,7 +656,7 @@ enum InferSourceKind<'tcx> { /// If the method has other arguments, this is ", " and the start of the first argument, /// while for methods without arguments this is ")" and the end of the method call. successor: (&'static str, BytePos), - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, def_id: DefId, }, ClosureReturn { @@ -804,7 +804,7 @@ impl<'tcx> InferSourceKind<'tcx> { } } else { let mut p = fmt_printer(infcx, Namespace::TypeNS); - p.comma_sep(generic_args.iter().copied().map(|arg| { + p.comma_sep(generic_args.iter().map(|arg| { if arg.is_suggestable(tcx, true) { used_fallback = true; return arg; @@ -903,7 +903,7 @@ impl<'tcx> InferSourceKind<'tcx> { #[derive(Debug)] struct InsertableGenericArgs<'tcx> { insert_span: Span, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, generics_def_id: DefId, def_id: DefId, have_turbofish: bool, @@ -975,7 +975,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { 5 + self .tcx .generics_of(def.did()) - .own_args_no_defaults(self.tcx, args) + .own_args_no_defaults(self.tcx, args.as_slice()) .iter() .map(|&arg| self.arg_cost(arg)) .sum::() @@ -1000,7 +1000,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { DefKind::Variant | DefKind::Ctor(CtorOf::Variant, _) => 15, _ => 10, }; - variant_cost + generic_args.iter().map(|&arg| ctx.arg_cost(arg)).sum::() + variant_cost + generic_args.iter().map(|arg| ctx.arg_cost(arg)).sum::() } InferSourceKind::FullyQualifiedMethodCall { args, .. } => { 20 + args.iter().map(|arg| ctx.arg_cost(arg)).sum::() @@ -1038,7 +1038,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { } } - fn node_args_opt(&self, hir_id: HirId) -> Option> { + fn node_args_opt(&self, hir_id: HirId) -> Option> { let args = self.typeck_results.node_args_opt(hir_id); self.tecx.deeply_resolve_ignoring_regions(args) } @@ -1154,7 +1154,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { if let Some(ty) = self.opt_node_type(expr.hir_id) && let ty::Adt(_, args) = ty.kind() { - return Box::new(self.resolved_path_inferred_arg_iter(path, args)); + return Box::new(self.resolved_path_inferred_arg_iter(path, *args)); } } hir::ExprKind::MethodCall(segment, ..) => { @@ -1191,7 +1191,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { fn resolved_path_inferred_arg_iter( &self, path: &'tcx hir::Path<'tcx>, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> impl Iterator> + 'tcx { let tcx = self.tecx.tcx; let have_turbofish = path.segments.iter().any(|segment| { @@ -1246,7 +1246,7 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { fn path_inferred_arg_iter( &self, hir_id: HirId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, qpath: &'tcx hir::QPath<'tcx>, ) -> Box> + 'a> { let tcx = self.tecx.tcx; @@ -1304,7 +1304,8 @@ impl<'a, 'tcx> FindInferSourceVisitor<'a, 'tcx> { } } else { return Box::new( - self.resolved_path_inferred_arg_iter(path, args).chain(segment), + self.resolved_path_inferred_arg_iter(path, *args) + .chain(segment), ); } } @@ -1434,13 +1435,15 @@ impl<'a, 'tcx> Visitor<'tcx> for FindInferSourceVisitor<'a, 'tcx> { } = args; let generics = tcx.generics_of(generics_def_id); if let Some(argument_index) = generics - .own_args(args) + .own_args(args.as_slice()) .iter() .position(|&arg| self.generic_arg_contains_target(arg)) { let args = self.tecx.deeply_resolve_ignoring_regions(args); - let generic_args = - &generics.own_args_no_defaults(tcx, args)[generics.own_counts().lifetimes..]; + let generic_args = tcx.mk_args( + &generics.own_args_no_defaults(tcx, args.as_slice()) + [generics.own_counts().lifetimes..], + ); let span = match expr.kind { ExprKind::MethodCall(segment, ..) if have_turbofish diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs index fecf41c84a0e2..93309c916d71c 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/nice_region_error/placeholder_error.rs @@ -7,7 +7,7 @@ use rustc_hir::def::{DefKind, Namespace}; use rustc_hir::def_id::{CRATE_DEF_ID, DefId}; use rustc_middle::ty::error::ExpectedFound; use rustc_middle::ty::print::{FmtPrinter, Print, PrintTraitRefExt as _, RegionHighlightMode}; -use rustc_middle::ty::{self, GenericArgsRef, IsSuggestable, RePlaceholder, Region, TyCtxt}; +use rustc_middle::ty::{self, GenericArgs, IsSuggestable, RePlaceholder, Region, TyCtxt}; use rustc_span::{Span, bug}; use rustc_structures::Limit; use tracing::{debug, instrument}; @@ -250,8 +250,8 @@ impl<'tcx> NiceRegionError<'_, 'tcx> { sub_placeholder: Option>, sup_placeholder: Option>, trait_def_id: DefId, - expected_args: GenericArgsRef<'tcx>, - actual_args: GenericArgsRef<'tcx>, + expected_args: GenericArgs<'tcx>, + actual_args: GenericArgs<'tcx>, ) -> Diag<'tcx> { let span = cause.span; diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs index f6264ff0129e3..83bb2079d2ea5 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs @@ -1050,7 +1050,7 @@ fn foo(&self) -> Self::T { String::new() } pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String { FmtPrinter::print_string(self.tcx, hir::def::Namespace::TypeNS, |p| { - p.print_path_with_generic_args(|_| Ok(()), args) + p.print_path_with_generic_args(|_| Ok(()), self.tcx.mk_args(args)) }) .expect("could not write to `String`.") } diff --git a/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs b/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs index 4ccc7ab986f1e..32ac72708c339 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/infer/suggest.rs @@ -104,7 +104,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { }) .filter_map(|variant| { let sole_field = &variant.single_field(); - let sole_field_ty = sole_field.ty(self.tcx, args).skip_norm_wip(); + let sole_field_ty = sole_field.ty(self.tcx, *args).skip_norm_wip(); if self.same_type_modulo_infer(sole_field_ty, exp_found.found) { let variant_path = with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id)); @@ -350,7 +350,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { .fields .iter() .filter(|field| field.vis.is_accessible_from(field.did, self.tcx)) - .map(|field| (field.name, field.ty(self.tcx, expected_args).skip_norm_wip())) + .map(|field| (field.name, field.ty(self.tcx, *expected_args).skip_norm_wip())) .find(|(_, ty)| self.same_type_modulo_infer(*ty, exp_found.found)) && let ObligationCauseCode::Pattern { span: Some(span), .. } = *cause.code() && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/call_kind.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/call_kind.rs index 4142febc7844f..9fd34ff74f1a5 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/call_kind.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/call_kind.rs @@ -6,7 +6,7 @@ use rustc_attr_ir::lang_items::{self, LangItem}; use rustc_hir::def::DefKind; use rustc_hir::def_id::DefId; use rustc_middle::ty::{ - self, AssocContainer, GenericArgsRef, Instance, Ty, TyCtxt, TypingEnv, Unnormalized, + self, AssocContainer, GenericArgs, Instance, Ty, TyCtxt, TypingEnv, Unnormalized, }; use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, sym}; use tracing::debug; @@ -65,7 +65,7 @@ pub enum CallKind<'tcx> { self_arg: Option, desugaring: Option<(CallDesugaringKind, Ty<'tcx>)>, method_did: DefId, - method_args: GenericArgsRef<'tcx>, + method_args: GenericArgs<'tcx>, }, /// A call to `Fn(..)::call(..)`, desugared from `my_closure(a, b, c)` FnCall { fn_trait_id: DefId, self_ty: Ty<'tcx> }, @@ -85,7 +85,7 @@ pub fn call_kind<'tcx>( tcx: TyCtxt<'tcx>, typing_env: TypingEnv<'tcx>, method_did: DefId, - method_args: GenericArgsRef<'tcx>, + method_args: GenericArgs<'tcx>, fn_call_span: Span, from_hir_call: bool, self_arg: Option, diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs index ca68ee77d67b3..fdd3ca3d8c9cc 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs @@ -2357,9 +2357,9 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { let traits = self.cmp_traits( obligation_trait_ref.def_id(), - &obligation_trait_ref.trait_ref.args[1..], + &obligation_trait_ref.trait_ref.args.as_slice()[1..], impl_trait_ref.def_id, - &impl_trait_ref.args[1..], + &impl_trait_ref.args.as_slice()[1..], ); let traits_content = (traits.0.content(), traits.1.content()); let types = self.cmp(obligation_trait_ref.self_ty(), impl_trait_ref.self_ty()); @@ -3235,7 +3235,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { return true; } if let ty::Adt(def, args) = self_ty.kind() - && let [arg] = &args[..] + && let [arg] = &args.as_slice() && let ty::GenericArgKind::Type(ty) = arg.kind() && let ty::Adt(inner_def, _) = ty.kind() && inner_def == def diff --git a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs index a97effe2eb0fd..e71da3f59543f 100644 --- a/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs +++ b/compiler/rustc_trait_selection/src/error_reporting/traits/suggestions.rs @@ -362,7 +362,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { .unwrap_or_else(|| self.tcx.def_span(field_def.did)); if field_def.vis.is_accessible_from(def_scope, self.tcx) { - let accessible_field_ty = field_def.ty(self.tcx, args).skip_norm_wip(); + let accessible_field_ty = field_def.ty(self.tcx, *args).skip_norm_wip(); if let Some((private_base_ty, private_field_ty, private_field_span)) = private_candidate && !self.can_eq(param_env, private_field_ty, accessible_field_ty) @@ -454,7 +454,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { private_candidate.get_or_insert(( deref_base_ty, - field_def.ty(self.tcx, args).skip_norm_wip(), + field_def.ty(self.tcx, *args).skip_norm_wip(), field_span, )); } @@ -609,7 +609,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { // this that we do in `suggest_restriction` and pull the // `impl Trait` into a new generic if it shows up somewhere // else in the predicate. - if !trait_pred.skip_binder().trait_ref.args[1..] + if !trait_pred.skip_binder().trait_ref.args.as_slice()[1..] .iter() .all(|g| g.is_suggestable(self.tcx, false)) { @@ -868,8 +868,11 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { self.tcx, inner.trait_ref.def_id, self.tcx.mk_args( - &[&[l_ty.into(), r_ty.into()], &inner.trait_ref.args[2..]] - .concat(), + &[ + &[l_ty.into(), r_ty.into()], + &inner.trait_ref.args.as_slice()[2..], + ] + .concat(), ), ), ..inner @@ -5150,7 +5153,7 @@ impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> { is_derivable_trait && // Ensure all fields impl the trait. adt.all_fields().all(|field| { - let field_ty = ty::GenericArg::from(field.ty(self.tcx, args).skip_norm_wip()); + let field_ty = ty::GenericArg::from(field.ty(self.tcx, *args).skip_norm_wip()); let trait_args = match diagnostic_name { sym::PartialEq | sym::PartialOrd => { Some(field_ty) diff --git a/compiler/rustc_trait_selection/src/opaque_types.rs b/compiler/rustc_trait_selection/src/opaque_types.rs index 4370935ead285..d1c51819c2066 100644 --- a/compiler/rustc_trait_selection/src/opaque_types.rs +++ b/compiler/rustc_trait_selection/src/opaque_types.rs @@ -137,7 +137,7 @@ struct LazyOpaqueTyEnv<'tcx> { /// `type Opaque<'a: 'static, 'b: 'c, 'c: 'b> = impl Sized;` /// Identity args: `['a, 'b, 'c]` /// Canonical args: `['static, 'b, 'b]` - canonical_args: std::cell::OnceCell>, + canonical_args: std::cell::OnceCell>, } impl<'tcx> LazyOpaqueTyEnv<'tcx> { @@ -158,7 +158,7 @@ impl<'tcx> LazyOpaqueTyEnv<'tcx> { self.get_canonical_args()[param_index].error_reported() } - fn get_canonical_args(&self) -> ty::GenericArgsRef<'tcx> { + fn get_canonical_args(&self) -> GenericArgs<'tcx> { if let Some(&canonical_args) = self.canonical_args.get() { return canonical_args; } diff --git a/compiler/rustc_trait_selection/src/solve/delegate.rs b/compiler/rustc_trait_selection/src/solve/delegate.rs index d1064ba03948d..e7cd39d34d590 100644 --- a/compiler/rustc_trait_selection/src/solve/delegate.rs +++ b/compiler/rustc_trait_selection/src/solve/delegate.rs @@ -430,7 +430,7 @@ impl<'tcx> rustc_next_trait_solver::delegate::SolverDelegate for SolverDelegate< fn add_item_bounds_for_hidden_type( &self, def_id: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, param_env: ty::ParamEnv<'tcx>, hidden_ty: Ty<'tcx>, goals: &mut Vec>>, diff --git a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs index 63b65cca16c55..1a7f6a1109622 100644 --- a/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs +++ b/compiler/rustc_trait_selection/src/solve/inspect/analyse.rs @@ -141,7 +141,7 @@ impl<'a, 'tcx> InspectCandidate<'a, 'tcx> { skip_all, fields(goal = ?self.goal.goal, steps = ?self.steps) )] - pub fn instantiate_impl_args(&self, span: Span) -> ty::GenericArgsRef<'tcx> { + pub fn instantiate_impl_args(&self, span: Span) -> ty::GenericArgs<'tcx> { let infcx = self.goal.infcx; let mut orig_values = self.goal.orig_values.clone(); diff --git a/compiler/rustc_trait_selection/src/traits/auto_trait.rs b/compiler/rustc_trait_selection/src/traits/auto_trait.rs index 3b60bc53141d5..402241a7253e0 100644 --- a/compiler/rustc_trait_selection/src/traits/auto_trait.rs +++ b/compiler/rustc_trait_selection/src/traits/auto_trait.rs @@ -622,7 +622,7 @@ impl<'tcx> AutoTraitFinder<'tcx> { finished_map } - fn is_param_no_infer(&self, args: GenericArgsRef<'tcx>) -> bool { + fn is_param_no_infer(&self, args: GenericArgs<'tcx>) -> bool { self.is_of_param(args.type_at(0)) && !args.terms().any(|t| t.has_infer_types()) } diff --git a/compiler/rustc_trait_selection/src/traits/coherence.rs b/compiler/rustc_trait_selection/src/traits/coherence.rs index ed79ab1700fd6..ac4b42d393d53 100644 --- a/compiler/rustc_trait_selection/src/traits/coherence.rs +++ b/compiler/rustc_trait_selection/src/traits/coherence.rs @@ -41,7 +41,7 @@ use crate::traits::{ /// bounds / where-clauses). #[derive(Clone, Debug, TypeFoldable, TypeVisitable)] pub struct ImplHeader<'tcx> { - pub impl_args: ty::GenericArgsRef<'tcx>, + pub impl_args: ty::GenericArgs<'tcx>, pub self_ty: Ty<'tcx>, pub trait_ref: Option>, pub predicates: Vec>, diff --git a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs index f5d7a51ce8a28..56172df8ea45e 100644 --- a/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs +++ b/compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs @@ -223,7 +223,7 @@ fn predicate_references_self<'tcx>( match predicate.kind().skip_binder() { ty::ClauseKind::Trait(ref data) => { // In the case of a trait predicate, we can skip the "self" type. - data.trait_ref.args[1..] + data.trait_ref.args.as_slice()[1..] .iter() .any(|&arg| { contains_illegal_self_type_reference( @@ -251,7 +251,7 @@ fn predicate_references_self<'tcx>( // // This is ALT2 in issue #56288, see that for discussion of the // possible alternatives. - data.projection_term.args[1..] + data.projection_term.args.as_slice()[1..] .iter() .any(|&arg| { contains_illegal_self_type_reference( diff --git a/compiler/rustc_trait_selection/src/traits/fulfill.rs b/compiler/rustc_trait_selection/src/traits/fulfill.rs index cf77d061d2baa..3a1ad2ee5feab 100644 --- a/compiler/rustc_trait_selection/src/traits/fulfill.rs +++ b/compiler/rustc_trait_selection/src/traits/fulfill.rs @@ -13,7 +13,7 @@ use rustc_infer::traits::{ use rustc_middle::ty::abstract_const::NotConstEvaluatable; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::{ - self, Binder, Const, DelayedSet, GenericArgsRef, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, + self, Binder, Const, DelayedSet, GenericArgs, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, may_use_unstable_feature, }; use rustc_next_trait_solver::solve::TyOrConstInferVar; @@ -1033,7 +1033,7 @@ impl<'a, 'tcx> FulfillProcessor<'a, 'tcx> { /// Returns the set of inference variables contained in `args`. fn args_infer_vars<'tcx>( selcx: &SelectionContext<'_, 'tcx>, - args: ty::Binder<'tcx, GenericArgsRef<'tcx>>, + args: ty::Binder<'tcx, GenericArgs<'tcx>>, ) -> impl Iterator { selcx .infcx diff --git a/compiler/rustc_trait_selection/src/traits/misc.rs b/compiler/rustc_trait_selection/src/traits/misc.rs index 69fc873c4aae9..76ed6a8d491c0 100644 --- a/compiler/rustc_trait_selection/src/traits/misc.rs +++ b/compiler/rustc_trait_selection/src/traits/misc.rs @@ -206,7 +206,7 @@ pub fn all_fields_implement_trait<'tcx>( param_env: ty::ParamEnv<'tcx>, self_type: Ty<'tcx>, adt: AdtDef<'tcx>, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, parent_cause: ObligationCause<'tcx>, lang_item: LangItem, ) -> Result<(), Vec<(&'tcx ty::FieldDef, Ty<'tcx>, InfringingFieldsReason<'tcx>)>> { diff --git a/compiler/rustc_trait_selection/src/traits/mod.rs b/compiler/rustc_trait_selection/src/traits/mod.rs index 370a8d0c115c0..7076ec99c141c 100644 --- a/compiler/rustc_trait_selection/src/traits/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/mod.rs @@ -32,8 +32,8 @@ use rustc_macros::TypeVisitable; use rustc_middle::query::Providers; use rustc_middle::ty::error::{ExpectedFound, TypeError}; use rustc_middle::ty::{ - self, BottomUpFolder, Clause, GenericArgs, GenericArgsRef, Ty, TyCtxt, TypeFoldable, - TypeFolder, TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypingMode, + self, BottomUpFolder, Clause, GenericArgs, Ty, TyCtxt, TypeFoldable, TypeFolder, + TypeSuperFoldable, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypingMode, Unnormalized, Upcast, }; use rustc_span::Span; @@ -798,8 +798,8 @@ pub fn try_evaluate_const<'tcx, E: Debug>( /// args when they're not actually needed to evaluate a constant. fn replace_param_and_infer_args_with_placeholder<'tcx>( tcx: TyCtxt<'tcx>, - args: GenericArgsRef<'tcx>, -) -> GenericArgsRef<'tcx> { + args: GenericArgs<'tcx>, +) -> GenericArgs<'tcx> { struct ReplaceParamAndInferWithPlaceholder<'tcx> { tcx: TyCtxt<'tcx>, idx: ty::BoundVar, @@ -874,7 +874,7 @@ pub fn impossible_clauses<'tcx>(tcx: TyCtxt<'tcx>, clauses: Vec fn instantiate_and_check_impossible_clauses<'tcx>( tcx: TyCtxt<'tcx>, - key: (DefId, GenericArgsRef<'tcx>), + key: (DefId, GenericArgs<'tcx>), ) -> bool { debug!("instantiate_and_check_impossible_clauses(key={:?})", key); diff --git a/compiler/rustc_trait_selection/src/traits/outlives_for_liveness.rs b/compiler/rustc_trait_selection/src/traits/outlives_for_liveness.rs index 4cc3ac1a55320..b9770aecb357d 100644 --- a/compiler/rustc_trait_selection/src/traits/outlives_for_liveness.rs +++ b/compiler/rustc_trait_selection/src/traits/outlives_for_liveness.rs @@ -250,7 +250,7 @@ pub(crate) fn args_known_to_outlive_opaque_params<'tcx>( for (parent_outlived_region, opaque_outlived_arg_idx) in parent_outlives_regions.iter() { let mut opaque_outlives_args = DenseBitSet::new_empty(self_identity_args.len()); for (parent_outlived_arg_idx, parent_outlives_arg) in - self_identity_args[..generics.parent_count].iter().enumerate() + self_identity_args.as_slice()[..generics.parent_count].iter().enumerate() { let type_outlives = match parent_outlives_arg.kind() { // Consts don't have any non-static regions diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 5d7be99f7907a..c6a37d8d8147a 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -488,7 +488,7 @@ fn push_const_arg_has_type_obligation<'tcx>( param_env: ty::ParamEnv<'tcx>, term: Term<'tcx>, def_id: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) { if let Some(ct) = term.as_const() { let expected_ty = tcx.type_of(def_id).instantiate(tcx, args).skip_norm_wip(); @@ -607,7 +607,7 @@ pub fn compute_inherent_assoc_term_args<'a, 'b, 'tcx>( cause: ObligationCause<'tcx>, depth: usize, obligations: &mut PredicateObligations<'tcx>, -) -> ty::GenericArgsRef<'tcx> { +) -> ty::GenericArgs<'tcx> { let tcx = selcx.tcx(); let alias_def_id = match alias_term.kind { @@ -1636,7 +1636,7 @@ fn confirm_builtin_candidate<'cx, 'tcx>( let ty::Adt(def, args) = self_ty.kind() else { bug!("only field representing types can implement `Field`") }; - let Some(FieldInfo { base, ty, .. }) = def.field_representing_type_info(tcx, args) else { + let Some(FieldInfo { base, ty, .. }) = def.field_representing_type_info(tcx, *args) else { bug!("only field representing types can implement `Field`") }; if tcx.is_lang_item(item_def_id, LangItem::FieldBase) { @@ -1958,7 +1958,7 @@ fn confirm_async_fn_kind_helper_candidate<'cx, 'tcx>( tupled_inputs_ty, tupled_upvars_ty, coroutine_captures_by_ref_ty, - ] = **obligation.predicate.args + ] = *obligation.predicate.args.as_slice() else { bug!(); }; diff --git a/compiler/rustc_trait_selection/src/traits/select/_match.rs b/compiler/rustc_trait_selection/src/traits/select/_match.rs index 27de754aa7dc9..2e8d296e19f0a 100644 --- a/compiler/rustc_trait_selection/src/traits/select/_match.rs +++ b/compiler/rustc_trait_selection/src/traits/select/_match.rs @@ -42,9 +42,9 @@ impl<'tcx> TypeRelation> for MatchAgainstFreshVars<'tcx> { a_ty: Ty<'tcx>, _: Ty<'tcx>, _: DefId, - a_args: ty::GenericArgsRef<'tcx>, - b_args: ty::GenericArgsRef<'tcx>, - _: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>, + a_args: ty::GenericArgs<'tcx>, + b_args: ty::GenericArgs<'tcx>, + _: impl FnOnce(ty::GenericArgs<'tcx>) -> Ty<'tcx>, ) -> RelateResult<'tcx, Ty<'tcx>> { relate::relate_args_invariantly(self, a_args, b_args)?; Ok(a_ty) diff --git a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs index 7228c55b404b4..8a770bea8468b 100644 --- a/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs +++ b/compiler/rustc_trait_selection/src/traits/select/candidate_assembly.rs @@ -1497,7 +1497,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // encountering query cycles instead. if let ty::Adt(def, args) = obligation.predicate.self_ty().skip_binder().kind() && let Some(FieldInfo { base, ty, .. }) = - def.field_representing_type_info(self.tcx(), args) + def.field_representing_type_info(self.tcx(), *args) // NOTE: these bounds have to be kept in sync with the definition of the `Field` trait // in `library/core/src/field.rs` as well as the new trait solver `fn // consider_builtin_field_candidate` in diff --git a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs index 1fb8c84176fac..88bb711844cb1 100644 --- a/compiler/rustc_trait_selection/src/traits/select/confirmation.rs +++ b/compiler/rustc_trait_selection/src/traits/select/confirmation.rs @@ -13,7 +13,7 @@ use rustc_attr_ir::lang_items::LangItem; use rustc_infer::infer::{BoundRegionConversionTime, DefineOpaqueTypes, InferOk}; use rustc_infer::traits::ObligationCauseCode; use rustc_middle::traits::{BuiltinImplSource, SignatureMismatchData}; -use rustc_middle::ty::{self, GenericArgsRef, SizedTraitKind, Ty, Unnormalized, Upcast}; +use rustc_middle::ty::{self, GenericArgs, SizedTraitKind, Ty, Unnormalized, Upcast}; use rustc_next_trait_solver::solve::flatten_answer_tree; use rustc_span::def_id::DefId; use rustc_span::{bug, span_bug}; @@ -399,7 +399,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { fn vtable_impl( &mut self, impl_def_id: DefId, - args: Normalized<'tcx, GenericArgsRef<'tcx>>, + args: Normalized<'tcx, GenericArgs<'tcx>>, cause: &ObligationCause<'tcx>, recursion_depth: usize, param_env: ty::ParamEnv<'tcx>, diff --git a/compiler/rustc_trait_selection/src/traits/select/mod.rs b/compiler/rustc_trait_selection/src/traits/select/mod.rs index 432fa2e142d88..e280184169844 100644 --- a/compiler/rustc_trait_selection/src/traits/select/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/select/mod.rs @@ -25,9 +25,9 @@ use rustc_middle::ty::abstract_const::NotConstEvaluatable; use rustc_middle::ty::error::TypeErrorToStringExt; use rustc_middle::ty::print::{PrintTraitRefExt as _, with_no_trimmed_paths}; use rustc_middle::ty::{ - self, CandidatePreferenceMode, CantBeErased, DeepRejectCtxt, GenericArgsRef, - PolyProjectionClause, SizedTraitKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, TypingMode, - Unnormalized, Upcast, elaborate, may_use_unstable_feature, + self, CandidatePreferenceMode, CantBeErased, DeepRejectCtxt, GenericArgs, PolyProjectionClause, + SizedTraitKind, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, TypingMode, Unnormalized, Upcast, + elaborate, may_use_unstable_feature, }; use rustc_next_trait_solver::solve::AliasBoundKind; use rustc_span::bug; @@ -1680,7 +1680,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { // want, but fixing it causes some ambiguity: // . if !generics.is_own_empty() - && obligation.predicate.args[generics.parent_count..].iter().any(|&p| { + && obligation.predicate.args.as_slice()[generics.parent_count..].iter().any(|&p| { p.has_non_region_infer() && match p.kind() { ty::GenericArgKind::Const(ct) => { @@ -2372,7 +2372,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { &mut self, impl_def_id: DefId, obligation: &PolyTraitObligation<'tcx>, - ) -> Normalized<'tcx, GenericArgsRef<'tcx>> { + ) -> Normalized<'tcx, GenericArgs<'tcx>> { let impl_trait_header = self.tcx().impl_trait_header(impl_def_id); match self.match_impl(impl_def_id, impl_trait_header, obligation) { Ok(args) => args, @@ -2389,7 +2389,7 @@ impl<'tcx> SelectionContext<'_, 'tcx> { impl_def_id: DefId, impl_trait_header: ty::ImplTraitHeader<'tcx>, obligation: &PolyTraitObligation<'tcx>, - ) -> Result>, ()> { + ) -> Result>, ()> { let placeholder_obligation = self.infcx.enter_forall_and_leak_universe(obligation.predicate); let placeholder_obligation_trait_ref = placeholder_obligation.trait_ref; @@ -2703,8 +2703,8 @@ impl<'tcx> SelectionContext<'_, 'tcx> { cause: &ObligationCause<'tcx>, recursion_depth: usize, param_env: ty::ParamEnv<'tcx>, - def_id: DefId, // of impl or trait - args: GenericArgsRef<'tcx>, // for impl or trait + def_id: DefId, // of impl or trait + args: GenericArgs<'tcx>, // for impl or trait parent_trait_pred: ty::Binder<'tcx, ty::TraitClause<'tcx>>, ) -> PredicateObligations<'tcx> { let tcx = self.tcx(); diff --git a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs index 987e2af81984b..5627f4d196ecf 100644 --- a/compiler/rustc_trait_selection/src/traits/specialize/mod.rs +++ b/compiler/rustc_trait_selection/src/traits/specialize/mod.rs @@ -21,9 +21,7 @@ use rustc_middle::query::LocalCrate; use rustc_middle::traits::query::NoSolution; use rustc_middle::ty::fast_reject::{self, TreatParams}; use rustc_middle::ty::print::PrintTraitRefExt as _; -use rustc_middle::ty::{ - self, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized, -}; +use rustc_middle::ty::{self, GenericArgs, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized}; use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span, bug, sym}; use specialization_graph::GraphExt; use tracing::{debug, instrument}; @@ -87,9 +85,9 @@ pub fn translate_args<'tcx>( infcx: &InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, source_impl: DefId, - source_args: GenericArgsRef<'tcx>, + source_args: GenericArgs<'tcx>, target_node: specialization_graph::Node, -) -> GenericArgsRef<'tcx> { +) -> GenericArgs<'tcx> { translate_args_with_cause( infcx, param_env, @@ -110,10 +108,10 @@ pub fn translate_args_with_cause<'tcx>( infcx: &InferCtxt<'tcx>, param_env: ty::ParamEnv<'tcx>, source_impl: DefId, - source_args: GenericArgsRef<'tcx>, + source_args: GenericArgs<'tcx>, target_node: specialization_graph::Node, cause: &ObligationCause<'tcx>, -) -> GenericArgsRef<'tcx> { +) -> GenericArgs<'tcx> { debug!( "translate_args({:?}, {:?}, {:?}, {:?})", param_env, source_impl, source_args, target_node @@ -157,7 +155,7 @@ fn fulfill_implication<'tcx>( source_impl: DefId, target_impl: DefId, cause: &ObligationCause<'tcx>, -) -> Result, NoSolution> { +) -> Result, NoSolution> { debug!( "fulfill_implication({:?}, trait_ref={:?} |- {:?} applies)", param_env, source_trait_ref, target_impl diff --git a/compiler/rustc_trait_selection/src/traits/wf.rs b/compiler/rustc_trait_selection/src/traits/wf.rs index 41e6797e71d2d..2b43e5887aae7 100644 --- a/compiler/rustc_trait_selection/src/traits/wf.rs +++ b/compiler/rustc_trait_selection/src/traits/wf.rs @@ -11,8 +11,8 @@ use rustc_infer::traits::{ ObligationCauseCode, PredicateObligation, PredicateObligations, WellFormedLoc, }; use rustc_middle::ty::{ - self, DelayedSet, GenericArgsRef, PredicateProxy, Term, TermKind, Ty, TyCtxt, - TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, + self, DelayedSet, GenericArgs, PredicateProxy, Term, TermKind, Ty, TyCtxt, TypeSuperVisitable, + TypeVisitable, TypeVisitableExt, TypeVisitor, }; use rustc_session::diagnostics::feature_err; use rustc_span::def_id::{DefId, LocalDefId}; @@ -274,7 +274,7 @@ enum Elaborate { /// /// Note that bounds that can be expressed as associated item bounds are **not** /// super predicates. This means that form 2 and 3 from above are only relevant if -/// the [`GenericArgsRef`] of the projection type are not its identity arguments. +/// the [`GenericArgs`] of the projection type are not its identity arguments. fn extend_cause_with_original_assoc_item_obligation<'tcx>( tcx: TyCtxt<'tcx>, item: Option<&hir::Item<'tcx>>, @@ -532,7 +532,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { data.args.visit_with(self); } - fn add_wf_preds_for_projection_args(&mut self, args: GenericArgsRef<'tcx>) { + fn add_wf_preds_for_projection_args(&mut self, args: GenericArgs<'tcx>) { let tcx = self.tcx(); let cause = self.cause(ObligationCauseCode::WellFormed(WellFormedLoc::None)); let param_env = self.param_env; @@ -583,7 +583,7 @@ impl<'a, 'tcx> WfPredicates<'a, 'tcx> { fn nominal_obligations( &mut self, def_id: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, mut push_obligation: impl FnMut(&mut Self, PredicateObligation<'tcx>), ) { // PERF: `Sized`'s predicates include `MetaSized`, but both are compiler implemented marker diff --git a/compiler/rustc_transmute/src/layout/tree.rs b/compiler/rustc_transmute/src/layout/tree.rs index 43e2008c5a441..a7a5f0494cae8 100644 --- a/compiler/rustc_transmute/src/layout/tree.rs +++ b/compiler/rustc_transmute/src/layout/tree.rs @@ -600,7 +600,7 @@ pub(crate) mod rustc { match layout.variants { Variants::Single { index } => { let field = &def.variant(index).fields[i]; - field.ty(cx.tcx(), args).skip_norm_wip() + field.ty(cx.tcx(), *args).skip_norm_wip() } Variants::Empty => panic!("there is no field in Variants::Empty types"), // Discriminant field for enums (where applicable). diff --git a/compiler/rustc_ty_utils/src/instance.rs b/compiler/rustc_ty_utils/src/instance.rs index 0ded7482bb6c4..38c79df64c051 100644 --- a/compiler/rustc_ty_utils/src/instance.rs +++ b/compiler/rustc_ty_utils/src/instance.rs @@ -6,7 +6,7 @@ use rustc_infer::infer::TyCtxtInferExt; use rustc_middle::query::Providers; use rustc_middle::traits::{BuiltinImplSource, CodegenObligationError}; use rustc_middle::ty::{ - self, ClosureKind, GenericArgsRef, Instance, PseudoCanonicalInput, TyCtxt, TypeVisitableExt, + self, ClosureKind, GenericArgs, Instance, PseudoCanonicalInput, TyCtxt, TypeVisitableExt, Unnormalized, }; use rustc_span::{bug, sym}; @@ -16,7 +16,7 @@ use traits::translate_args; fn resolve_instance_raw<'tcx>( tcx: TyCtxt<'tcx>, - key: ty::PseudoCanonicalInput<'tcx, (DefId, GenericArgsRef<'tcx>)>, + key: ty::PseudoCanonicalInput<'tcx, (DefId, GenericArgs<'tcx>)>, ) -> Result>, ErrorGuaranteed> { let PseudoCanonicalInput { typing_env, value: (def_id, args) } = key; @@ -111,7 +111,7 @@ fn resolve_associated_item<'tcx>( trait_item_id: DefId, typing_env: ty::TypingEnv<'tcx>, trait_id: DefId, - rcvr_args: GenericArgsRef<'tcx>, + rcvr_args: GenericArgs<'tcx>, ) -> Result>, ErrorGuaranteed> { debug!(?trait_item_id, ?typing_env, ?trait_id, ?rcvr_args, "resolve_associated_item"); diff --git a/compiler/rustc_ty_utils/src/layout.rs b/compiler/rustc_ty_utils/src/layout.rs index 83f9f6d2f87f0..5d680b26c0221 100644 --- a/compiler/rustc_ty_utils/src/layout.rs +++ b/compiler/rustc_ty_utils/src/layout.rs @@ -996,7 +996,7 @@ fn variant_info_for_coroutine<'tcx>( cx: &LayoutCx<'tcx>, layout: TyAndLayout<'tcx>, def_id: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> (Vec, Option) { use itertools::Itertools; diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index 094cf5aec0bd1..522444651778d 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -5,7 +5,7 @@ use rustc_data_structures::fx::FxHashSet; use rustc_hir::def_id::DefId; use rustc_middle::query::Providers; use rustc_middle::ty::util::{AlwaysRequiresDrop, needs_drop_components}; -use rustc_middle::ty::{self, EarlyBinder, GenericArgsRef, Ty, TyCtxt, Unnormalized}; +use rustc_middle::ty::{self, EarlyBinder, GenericArgs, Ty, TyCtxt, Unnormalized}; use rustc_span::bug; use rustc_structures::Limit; use tracing::{debug, instrument}; @@ -167,7 +167,7 @@ impl<'tcx, F> NeedsDropTypes<'tcx, F> { impl<'tcx, F, I> Iterator for NeedsDropTypes<'tcx, F> where - F: Fn(ty::AdtDef<'tcx>, GenericArgsRef<'tcx>) -> NeedsDropResult, + F: Fn(ty::AdtDef<'tcx>, GenericArgs<'tcx>) -> NeedsDropResult, I: Iterator>, { type Item = NeedsDropResult>; @@ -385,7 +385,7 @@ fn drop_tys_helper<'tcx>( }) } - let adt_components = move |adt_def: ty::AdtDef<'tcx>, args: GenericArgsRef<'tcx>| { + let adt_components = move |adt_def: ty::AdtDef<'tcx>, args: GenericArgs<'tcx>| { if adt_def.is_manually_drop() { debug!("drop_tys_helper: `{:?}` is manually drop", adt_def); Ok(Vec::new()) diff --git a/compiler/rustc_ty_utils/src/opaque_types.rs b/compiler/rustc_ty_utils/src/opaque_types.rs index 1b951ccb70ea3..5e4289a663695 100644 --- a/compiler/rustc_ty_utils/src/opaque_types.rs +++ b/compiler/rustc_ty_utils/src/opaque_types.rs @@ -130,10 +130,10 @@ impl<'tcx> OpaqueTypeCollector<'tcx> { // Only check that the parent generics of the TAIT/RPIT are unique. // the args owned by the opaque are going to always be duplicate // lifetime params for RPITs, and empty for TAITs. - match self - .tcx - .uses_unique_generic_params(&alias_ty.args[..parent_count], CheckRegions::FromFunction) - { + match self.tcx.uses_unique_generic_params( + &alias_ty.args.as_slice()[..parent_count], + CheckRegions::FromFunction, + ) { Ok(()) => { // FIXME: implement higher kinded lifetime bounds on nested opaque types. They are not // supported at all, so this is sound to do, but once we want to support them, you'll diff --git a/compiler/rustc_ty_walk/src/lib.rs b/compiler/rustc_ty_walk/src/lib.rs index 0ca1b06f05e3b..06c1fc8c27c07 100644 --- a/compiler/rustc_ty_walk/src/lib.rs +++ b/compiler/rustc_ty_walk/src/lib.rs @@ -96,7 +96,7 @@ pub fn walk_types<'tcx, V: SpannedTypeVisitor<'tcx>>( }; for field in def.all_fields() { let span = tcx.def_ident_span(field.did).unwrap(); - let ty = field.ty(tcx, args); + let ty = field.ty(tcx, *args); try_visit!(visitor.visit(span, ty)); } for (clause, span) in tcx.explicit_clauses_of(item).instantiate_identity(tcx) { @@ -114,8 +114,8 @@ pub fn walk_types<'tcx, V: SpannedTypeVisitor<'tcx>>( .trait_ref .path .span; - let args = - &tcx.impl_trait_ref(item).instantiate_identity().skip_norm_wip().args[1..]; + let args = tcx.impl_trait_ref(item).instantiate_identity().skip_norm_wip().args; + let args = &args.as_slice()[1..]; try_visit!(visitor.visit(span, args)); } let span = match tcx.hir_node_by_def_id(item).ty() { diff --git a/compiler/rustc_type_ir/src/binder.rs b/compiler/rustc_type_ir/src/binder.rs index d9b5ec7356e3e..8cd4cbd677c69 100644 --- a/compiler/rustc_type_ir/src/binder.rs +++ b/compiler/rustc_type_ir/src/binder.rs @@ -508,7 +508,7 @@ where { } -impl<'s, I: Interner, Iter: IntoIterator> EarlyBinder +impl EarlyBinder where Iter::Item: Deref, ::Target: Copy + TypeFoldable, @@ -516,8 +516,8 @@ where pub fn iter_instantiated_copied( self, cx: I, - args: &'s [I::GenericArg], - ) -> IterInstantiatedCopied<'s, I, Iter> { + args: I::GenericArgs, + ) -> IterInstantiatedCopied { IterInstantiatedCopied { it: self.value.into_iter(), cx, args } } @@ -528,21 +528,19 @@ where } } -pub struct IterInstantiatedCopied<'a, I: Interner, Iter: IntoIterator> { +pub struct IterInstantiatedCopied { it: Iter::IntoIter, cx: I, - args: &'a [I::GenericArg], + args: I::GenericArgs, } -impl<'a, I: Interner, Iter: IntoIterator> Clone - for IterInstantiatedCopied<'a, I, Iter> -{ - fn clone(&self) -> IterInstantiatedCopied<'a, I, Iter> { +impl> Clone for IterInstantiatedCopied { + fn clone(&self) -> IterInstantiatedCopied { IterInstantiatedCopied { it: self.it.clone(), cx: self.cx, args: self.args } } } -impl Iterator for IterInstantiatedCopied<'_, I, Iter> +impl Iterator for IterInstantiatedCopied where Iter::Item: Deref, ::Target: Copy + TypeFoldable, @@ -560,7 +558,7 @@ where } } -impl DoubleEndedIterator for IterInstantiatedCopied<'_, I, Iter> +impl DoubleEndedIterator for IterInstantiatedCopied where Iter::IntoIter: DoubleEndedIterator, Iter::Item: Deref, @@ -573,7 +571,7 @@ where } } -impl ExactSizeIterator for IterInstantiatedCopied<'_, I, Iter> +impl ExactSizeIterator for IterInstantiatedCopied where Iter::IntoIter: ExactSizeIterator, Iter::Item: Deref, diff --git a/compiler/rustc_type_ir/src/inherent.rs b/compiler/rustc_type_ir/src/inherent.rs index 4fd92194c5d81..579a22d738df5 100644 --- a/compiler/rustc_type_ir/src/inherent.rs +++ b/compiler/rustc_type_ir/src/inherent.rs @@ -397,9 +397,9 @@ pub trait GenericArgs>: original_args: &[I::GenericArg], ) -> I::GenericArgs; - fn split_closure_args(self) -> ty::ClosureArgsParts; - fn split_coroutine_closure_args(self) -> ty::CoroutineClosureArgsParts; - fn split_coroutine_args(self) -> ty::CoroutineArgsParts; + fn split_closure_args<'a>(&'a self) -> ty::ClosureArgsParts<'a, I>; + fn split_coroutine_closure_args<'a>(&'a self) -> ty::CoroutineClosureArgsParts<'a, I>; + fn split_coroutine_args<'a>(&'a self) -> ty::CoroutineArgsParts<'a, I>; fn as_closure(self) -> ty::ClosureArgs { ty::ClosureArgs { args: self } diff --git a/compiler/rustc_type_ir/src/interner.rs b/compiler/rustc_type_ir/src/interner.rs index 159c2939875b0..bf9eae49322b8 100644 --- a/compiler/rustc_type_ir/src/interner.rs +++ b/compiler/rustc_type_ir/src/interner.rs @@ -113,7 +113,9 @@ pub trait Interner: type Span: Span; type GenericArgs: GenericArgs; - type GenericArgsSlice: Copy + Debug + Hash + Eq + SliceLike; + type GenericArgsSlice<'a>: Copy + Debug + Hash + Eq + SliceLike + where + Self: 'a; type GenericArg: GenericArg; type Term: Term; @@ -299,11 +301,11 @@ pub trait Interner: type AdtDef: AdtDef; fn adt_def(self, adt_def_id: Self::AdtId) -> Self::AdtDef; - fn trait_ref_and_own_args_for_alias( + fn trait_ref_and_own_args_for_alias<'a>( self, def_id: Self::TraitAssocTermId, - args: Self::GenericArgs, - ) -> (ty::TraitRef, Self::GenericArgsSlice); + args: &'a Self::GenericArgs, + ) -> (ty::TraitRef, Self::GenericArgsSlice<'a>); fn mk_args(self, args: &[Self::GenericArg]) -> Self::GenericArgs; diff --git a/compiler/rustc_type_ir/src/region_constraint.rs b/compiler/rustc_type_ir/src/region_constraint.rs index a866f849f25e2..fedadb96f7d4c 100644 --- a/compiler/rustc_type_ir/src/region_constraint.rs +++ b/compiler/rustc_type_ir/src/region_constraint.rs @@ -1037,7 +1037,8 @@ fn rewrite_alias_ty_outlives_constraints_in_universe_for_eager_placeholder_handl current_index: DebruijnIndex::ZERO, }; let escaping_outlives = bound_outlives.skip_binder().fold_with(&mut replacer); - let bound_vars = bound_outlives.bound_vars().iter().chain( + let bound_vars = bound_outlives.bound_vars(); + let bound_vars = bound_vars.iter().chain( core::mem::take(&mut replacer.regions) .into_iter() .map(|(_, bound_region)| BoundVariableKind::Region(bound_region.kind)), diff --git a/compiler/rustc_type_ir/src/term_kind.rs b/compiler/rustc_type_ir/src/term_kind.rs index 0c151e678a614..05e676467a749 100644 --- a/compiler/rustc_type_ir/src/term_kind.rs +++ b/compiler/rustc_type_ir/src/term_kind.rs @@ -299,8 +299,14 @@ impl AliasTerm { /// For example, if this is a projection of `::Item<'a>`, /// then this function would return a `T: StreamingIterator` trait reference and /// `['a]` as the own args. - pub fn trait_ref_and_own_args(self, interner: I) -> (ty::TraitRef, I::GenericArgsSlice) { - interner.trait_ref_and_own_args_for_alias(self.expect_projection_def_id(), self.args) + pub fn trait_ref_and_own_args<'a>( + &'a self, + interner: I, + ) -> (ty::TraitRef, I::GenericArgsSlice<'a>) + where + I: 'a, + { + interner.trait_ref_and_own_args_for_alias(self.expect_projection_def_id(), &self.args) } /// Extracts the underlying trait reference from this projection. @@ -317,7 +323,7 @@ impl AliasTerm { /// Extract the own args from this projection. /// For example, if this is a projection of `::Item<'a>`, /// then this function would return the slice `['a]` as the own args. - pub fn own_args(self, interner: I) -> I::GenericArgsSlice { + pub fn own_args<'a>(&'a self, interner: I) -> I::GenericArgsSlice<'a> { self.trait_ref_and_own_args(interner).1 } } diff --git a/compiler/rustc_type_ir/src/ty_kind.rs b/compiler/rustc_type_ir/src/ty_kind.rs index e996f6684515a..d96250b969f00 100644 --- a/compiler/rustc_type_ir/src/ty_kind.rs +++ b/compiler/rustc_type_ir/src/ty_kind.rs @@ -284,7 +284,7 @@ pub enum TyKind { /// the type of the coroutine, we convert them to higher ranked /// lifetimes bound by the witness itself. /// - /// This contains the `DefId` and the `GenericArgsRef` of the coroutine. + /// This contains the `DefId` and the `GenericArg` of the coroutine. /// The actual witness types are computed on MIR by the `mir_coroutine_witnesses` query. /// /// Looking at the following example, the witness for this coroutine @@ -606,10 +606,16 @@ impl AliasTy { /// For example, if this is a projection of `::Item<'a>`, /// then this function would return a `T: StreamingIterator` trait reference and /// `['a]` as the own args. - pub fn trait_ref_and_own_args(self, interner: I) -> (ty::TraitRef, I::GenericArgsSlice) { + pub fn trait_ref_and_own_args<'a>( + &'a self, + interner: I, + ) -> (ty::TraitRef, I::GenericArgsSlice<'a>) + where + I: 'a, + { let AliasTyKind::Projection { def_id } = self.kind else { panic!("expected a projection") }; - interner.trait_ref_and_own_args_for_alias(def_id.into(), self.args) + interner.trait_ref_and_own_args_for_alias(def_id.into(), &self.args) } /// Extracts the underlying trait reference from this projection. diff --git a/compiler/rustc_type_ir/src/ty_kind/closure.rs b/compiler/rustc_type_ir/src/ty_kind/closure.rs index 2b9908f4337ef..4d3a2d862045e 100644 --- a/compiler/rustc_type_ir/src/ty_kind/closure.rs +++ b/compiler/rustc_type_ir/src/ty_kind/closure.rs @@ -117,9 +117,9 @@ pub struct ClosureArgs { impl Eq for ClosureArgs {} /// Struct returned by `split()`. -pub struct ClosureArgsParts { +pub struct ClosureArgsParts<'a, I: Interner + 'a> { /// This is the args of the typeck root. - pub parent_args: I::GenericArgsSlice, + pub parent_args: I::GenericArgsSlice<'a>, /// Represents the maximum calling capability of the closure. pub closure_kind_ty: I::Ty, /// Captures the closure's signature. This closure signature is "tupled", and @@ -133,7 +133,10 @@ pub struct ClosureArgsParts { impl ClosureArgs { /// Construct `ClosureArgs` from `ClosureArgsParts`, containing `Args` /// for the closure parent, alongside additional closure-specific components. - pub fn new(cx: I, parts: ClosureArgsParts) -> ClosureArgs { + pub fn new<'a>(cx: I, parts: ClosureArgsParts<'a, I>) -> ClosureArgs + where + I: 'a, + { ClosureArgs { args: cx.mk_args_from_iter(parts.parent_args.iter().chain([ parts.closure_kind_ty.into(), @@ -145,12 +148,12 @@ impl ClosureArgs { /// Divides the closure args into their respective components. /// The ordering assumed here must match that used by `ClosureArgs::new` above. - fn split(self) -> ClosureArgsParts { + fn split<'a>(&'a self) -> ClosureArgsParts<'a, I> { self.args.split_closure_args() } /// Returns the generic parameters of the closure's parent. - pub fn parent_args(self) -> I::GenericArgsSlice { + pub fn parent_args<'a>(&'a self) -> I::GenericArgsSlice<'a> { self.split().parent_args } @@ -219,9 +222,9 @@ impl Eq for CoroutineClosureArgs {} /// /// See [`CoroutineClosureSignature`] for how these arguments are put together /// to make a callable [`ty::FnSig`] suitable for typeck and borrowck. -pub struct CoroutineClosureArgsParts { +pub struct CoroutineClosureArgsParts<'a, I: Interner + 'a> { /// This is the args of the typeck root. - pub parent_args: I::GenericArgsSlice, + pub parent_args: I::GenericArgsSlice<'a>, /// Represents the maximum calling capability of the closure. pub closure_kind_ty: I::Ty, /// Represents all of the relevant parts of the coroutine returned by this @@ -247,7 +250,10 @@ pub struct CoroutineClosureArgsParts { } impl CoroutineClosureArgs { - pub fn new(cx: I, parts: CoroutineClosureArgsParts) -> CoroutineClosureArgs { + pub fn new<'a>(cx: I, parts: CoroutineClosureArgsParts<'a, I>) -> CoroutineClosureArgs + where + I: 'a, + { CoroutineClosureArgs { args: cx.mk_args_from_iter(parts.parent_args.iter().chain([ parts.closure_kind_ty.into(), @@ -258,11 +264,11 @@ impl CoroutineClosureArgs { } } - fn split(self) -> CoroutineClosureArgsParts { + fn split<'a>(&'a self) -> CoroutineClosureArgsParts<'a, I> { self.args.split_coroutine_closure_args() } - pub fn parent_args(self) -> I::GenericArgsSlice { + pub fn parent_args<'a>(&'a self) -> I::GenericArgsSlice<'a> { self.split().parent_args } @@ -384,7 +390,7 @@ impl CoroutineClosureSignature { pub fn to_coroutine( self, cx: I, - parent_args: I::GenericArgsSlice, + parent_args: I::GenericArgsSlice<'_>, coroutine_kind_ty: I::Ty, coroutine_def_id: I::CoroutineId, tupled_upvars_ty: I::Ty, @@ -412,7 +418,7 @@ impl CoroutineClosureSignature { pub fn to_coroutine_given_kind_and_upvars( self, cx: I, - parent_args: I::GenericArgsSlice, + parent_args: I::GenericArgsSlice<'_>, coroutine_def_id: I::CoroutineId, goal_kind: ty::ClosureKind, env_region: Region, @@ -569,9 +575,9 @@ pub struct CoroutineArgs { impl Eq for CoroutineArgs {} -pub struct CoroutineArgsParts { +pub struct CoroutineArgsParts<'a, I: Interner + 'a> { /// This is the args of the typeck root. - pub parent_args: I::GenericArgsSlice, + pub parent_args: I::GenericArgsSlice<'a>, /// The coroutines returned by a coroutine-closure's `AsyncFnOnce`/`AsyncFnMut` /// implementations must be distinguished since the former takes the closure's @@ -596,7 +602,10 @@ pub struct CoroutineArgsParts { impl CoroutineArgs { /// Construct `CoroutineArgs` from `CoroutineArgsParts`, containing `Args` /// for the coroutine parent, alongside additional coroutine-specific components. - pub fn new(cx: I, parts: CoroutineArgsParts) -> CoroutineArgs { + pub fn new<'a>(cx: I, parts: CoroutineArgsParts<'a, I>) -> CoroutineArgs + where + I: 'a, + { CoroutineArgs { args: cx.mk_args_from_iter(parts.parent_args.iter().chain([ parts.kind_ty.into(), @@ -610,12 +619,12 @@ impl CoroutineArgs { /// Divides the coroutine args into their respective components. /// The ordering assumed here must match that used by `CoroutineArgs::new` above. - fn split(self) -> CoroutineArgsParts { + fn split<'a>(&'a self) -> CoroutineArgsParts<'a, I> { self.args.split_coroutine_args() } /// Returns the generic parameters of the coroutine's parent. - pub fn parent_args(self) -> I::GenericArgsSlice { + pub fn parent_args<'a>(&'a self) -> I::GenericArgsSlice<'a> { self.split().parent_args } From d2cbecf62401d6e1e0e2ed3a7c66b618e0c9bbd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Wed, 28 Oct 2026 14:36:13 +0100 Subject: [PATCH 06/18] fixup clippy and rustdoc --- compiler/rustc_middle/src/ty/generic_args.rs | 7 ++++++ src/librustdoc/clean/mod.rs | 12 ++++------ src/librustdoc/clean/utils.rs | 22 ++++++++--------- .../src/default_union_representation.rs | 4 ++-- .../clippy/clippy_lints/src/dereference.rs | 6 +++-- .../clippy_lints/src/derivable_impls.rs | 4 ++-- .../derive/derive_partial_eq_without_eq.rs | 2 +- .../clippy/clippy_lints/src/eta_reduction.rs | 2 +- .../clippy/clippy_lints/src/format_args.rs | 6 ++--- .../clippy_lints/src/functions/result.rs | 2 +- .../src/implied_bounds_in_impls.rs | 2 +- .../clippy_lints/src/large_const_arrays.rs | 2 +- .../clippy_lints/src/large_enum_variant.rs | 2 +- .../matches/significant_drop_in_scrutinee.rs | 2 +- .../src/methods/return_and_then.rs | 2 +- .../unnecessary_fallible_conversions.rs | 2 +- .../src/methods/unnecessary_to_owned.rs | 9 ++----- .../src/needless_borrows_for_generic_args.rs | 4 ++-- .../clippy/clippy_lints/src/non_copy_const.rs | 10 ++++---- .../src/non_send_fields_in_send_ty.rs | 2 +- .../src/only_used_in_recursion.rs | 11 +++++---- .../clippy/clippy_lints/src/ptr/ptr_arg.rs | 4 ++-- .../src/significant_drop_tightening.rs | 2 +- .../src/transmute/transmute_undefined_repr.rs | 10 ++++---- .../src/try_from_instead_of_from_str.rs | 2 +- .../src/unconditional_recursion.rs | 2 +- .../clippy_lints/src/useless_conversion.rs | 4 ++-- .../clippy_lints/src/volatile_composites.rs | 2 +- src/tools/clippy/clippy_utils/src/lib.rs | 17 ++++++++----- src/tools/clippy/clippy_utils/src/ty/mod.rs | 24 +++++++++---------- 30 files changed, 96 insertions(+), 86 deletions(-) diff --git a/compiler/rustc_middle/src/ty/generic_args.rs b/compiler/rustc_middle/src/ty/generic_args.rs index 4d2d8f704f9e5..bd4df2d5bc478 100644 --- a/compiler/rustc_middle/src/ty/generic_args.rs +++ b/compiler/rustc_middle/src/ty/generic_args.rs @@ -439,6 +439,13 @@ impl<'tcx> GenericArgs<'tcx> { Self::from_args(List::empty()) } + /// Exposes the underlying pointer. Relying on this for equality won't always be supported. + /// Be careful. + #[deprecated = "do not call this"] + pub fn as_ptr(&self) -> *const () { + std::ptr::from_ref(self.0).cast() + } + #[inline] pub fn iter(self) -> ::IntoIter { self.into_iter() diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index bb9b9dc4f731b..ef808d982b38f 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -46,9 +46,7 @@ use rustc_hir::{self as hir, HirId, PredicateOrigin}; use rustc_hir_analysis::{lower_const_arg_for_rustdoc, lower_ty}; use rustc_middle::middle::resolve::Reexport; use rustc_middle::middle::resolve_bound_vars as rbv; -use rustc_middle::ty::{ - self, AdtKind, GenericArgsRef, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized, -}; +use rustc_middle::ty::{self, AdtKind, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized}; use rustc_span::hygiene::{AstPass, MacroKind}; use rustc_span::symbol::{Ident, Symbol, kw}; use rustc_span::{ExpnKind, bug, span_bug}; @@ -596,7 +594,7 @@ fn projection_to_path_segment<'tcx>( args: GenericArgs::AngleBracketed { args: clean_middle_generic_args( cx, - proj.map_bound(|ty| &ty.args[generics.parent_count..]), + proj.map_bound(|ty| cx.tcx.mk_args(&ty.args.as_slice()[generics.parent_count..])), false, def_id, ), @@ -2352,7 +2350,7 @@ pub(crate) fn clean_middle_ty<'tcx>( args: GenericArgs::AngleBracketed { args: clean_middle_generic_args( cx, - alias_ty.map_bound(|ty| ty.args.as_slice()), + alias_ty.map_bound(|ty| ty.args), true, def_id, ), @@ -2428,7 +2426,7 @@ pub(crate) fn clean_middle_ty<'tcx>( fn clean_middle_opaque_bounds<'tcx>( cx: &mut DocContext<'tcx>, impl_trait_def_id: DefId, - args: ty::GenericArgsRef<'tcx>, + args: ty::GenericArgs<'tcx>, ) -> Type { let mut has_sized = false; @@ -2578,7 +2576,7 @@ pub(crate) fn clean_variant_def(variant: &ty::VariantDef, cx: &mut DocContext<'_ pub(crate) fn clean_variant_def_with_args<'tcx>( variant: &ty::VariantDef, - args: &GenericArgsRef<'tcx>, + args: &ty::GenericArgs<'tcx>, cx: &mut DocContext<'tcx>, ) -> Item { let discriminant = match variant.discr { diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index 57e5ec2c4f0fb..87514e8e9e6af 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -14,7 +14,7 @@ use rustc_hir::def::{DefKind, Res}; use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId}; use rustc_metadata::rendered_const; use rustc_middle::mir; -use rustc_middle::ty::{self, GenericArgKind, GenericArgsRef, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{self, GenericArgKind, TyCtxt, TypeVisitableExt}; use rustc_span::def_id::ModId; use rustc_span::symbol::{Symbol, kw, sym}; use tracing::{debug, warn}; @@ -89,7 +89,7 @@ pub(crate) fn krate(cx: &mut DocContext<'_>) -> Crate { pub(crate) fn clean_middle_generic_args<'tcx>( cx: &mut DocContext<'tcx>, - args: ty::Binder<'tcx, &'tcx [ty::GenericArg<'tcx>]>, + args: ty::Binder<'tcx, ty::GenericArgs<'tcx>>, mut has_self: bool, owner: DefId, ) -> ThinVec { @@ -106,20 +106,18 @@ pub(crate) fn clean_middle_generic_args<'tcx>( let generics = cx.tcx.generics_of(owner); let args = if !has_self && generics.has_own_self() { has_self = true; - [cx.tcx.types.trait_object_dummy_self.into()] - .into_iter() - .chain(args.iter().copied()) - .collect::>() - .into() + cx.tcx.mk_args_from_iter( + [cx.tcx.types.trait_object_dummy_self.into()].into_iter().chain(args.iter()), + ) } else { - std::borrow::Cow::from(args) + args }; let mut elision_has_failed_once_before = false; // Calculates where the parent trait's generic parameters end let index_offset = generics.count() - args.len(); - let clean_arg = |(index, &arg): (usize, &ty::GenericArg<'tcx>)| { + let clean_arg = |(index, arg): (usize, ty::GenericArg<'tcx>)| { // Elide the self type. if has_self && index == 0 { return None; @@ -215,7 +213,7 @@ fn clean_middle_generic_args_with_constraints<'tcx>( did: DefId, has_self: bool, mut constraints: ThinVec, - args: ty::Binder<'tcx, GenericArgsRef<'tcx>>, + args: ty::Binder<'tcx, ty::GenericArgs<'tcx>>, ) -> GenericArgs { if cx.tcx.is_trait(did) && cx.tcx.trait_def(did).paren_sugar @@ -235,7 +233,7 @@ fn clean_middle_generic_args_with_constraints<'tcx>( return GenericArgs::Parenthesized { inputs, output }; } - let args = clean_middle_generic_args(cx, args.map_bound(|args| &args[..]), has_self, did); + let args = clean_middle_generic_args(cx, args, has_self, did); GenericArgs::AngleBracketed { args, constraints } } @@ -245,7 +243,7 @@ pub(super) fn clean_middle_path<'tcx>( did: DefId, has_self: bool, constraints: ThinVec, - args: ty::Binder<'tcx, GenericArgsRef<'tcx>>, + args: ty::Binder<'tcx, ty::GenericArgs<'tcx>>, ) -> Path { let def_kind = cx.tcx.def_kind(did); let name = cx.tcx.opt_item_name(did).unwrap_or(sym::dummy); diff --git a/src/tools/clippy/clippy_lints/src/default_union_representation.rs b/src/tools/clippy/clippy_lints/src/default_union_representation.rs index 829783c39b298..9e2a1e5b9d08b 100644 --- a/src/tools/clippy/clippy_lints/src/default_union_representation.rs +++ b/src/tools/clippy/clippy_lints/src/default_union_representation.rs @@ -86,13 +86,13 @@ fn is_union_with_two_non_zst_fields<'tcx>(cx: &LateContext<'tcx>, item: &Item<'t .skip_norm_wip() .kind() { - adt_def.all_fields().filter(|f| !is_zst(cx, f, args)).count() >= 2 + adt_def.all_fields().filter(|f| !is_zst(cx, f, *args)).count() >= 2 } else { false } } -fn is_zst<'tcx>(cx: &LateContext<'tcx>, field: &FieldDef, args: ty::GenericArgsRef<'tcx>) -> bool { +fn is_zst<'tcx>(cx: &LateContext<'tcx>, field: &FieldDef, args: ty::GenericArgs<'tcx>) -> bool { let ty = field.ty(cx.tcx, args).skip_norm_wip(); if let Ok(layout) = cx.layout_of(ty) { layout.is_zst() diff --git a/src/tools/clippy/clippy_lints/src/dereference.rs b/src/tools/clippy/clippy_lints/src/dereference.rs index 6257ec51eb8da..ba99c6ebb32b5 100644 --- a/src/tools/clippy/clippy_lints/src/dereference.rs +++ b/src/tools/clippy/clippy_lints/src/dereference.rs @@ -380,7 +380,9 @@ impl<'tcx> LateLintPass<'tcx> for Dereferencing<'tcx> { && let Some(trait_id) = cx.tcx.trait_of_assoc(fn_id) && let arg_ty = cx.tcx.erase_and_anonymize_regions(adjusted_ty) && let ty::Ref(_, sub_ty, _) = *arg_ty.kind() - && let args = typeck.node_args_opt(hir_id).map_or_default(|args| &args[1..]) + && let args = typeck + .node_args_opt(hir_id) + .map_or_default(|args| cx.tcx.mk_args(&args.as_slice()[1..])) && let impl_ty = if cx .tcx .fn_sig(fn_id) @@ -404,7 +406,7 @@ impl<'tcx> LateLintPass<'tcx> for Dereferencing<'tcx> { cx, impl_ty, trait_id, - &args[..cx.tcx.generics_of(trait_id).own_params.len() - 1], + &args.as_slice()[..cx.tcx.generics_of(trait_id).own_params.len() - 1], )) // If there's an inherent method, or a method from another trait, // with the same name that's also implemented on this same type, diff --git a/src/tools/clippy/clippy_lints/src/derivable_impls.rs b/src/tools/clippy/clippy_lints/src/derivable_impls.rs index 7277cc095dffa..c09e52f43f2af 100644 --- a/src/tools/clippy/clippy_lints/src/derivable_impls.rs +++ b/src/tools/clippy/clippy_lints/src/derivable_impls.rs @@ -11,7 +11,7 @@ use rustc_hir::{ }; use rustc_lint::{LateContext, LateLintPass, impl_lint_pass}; use rustc_middle::ty::adjustment::{Adjust, PointerCoercion}; -use rustc_middle::ty::{self, AdtDef, GenericArgsRef, Ty, TypeckResults, VariantDef}; +use rustc_middle::ty::{self, AdtDef, GenericArgs, Ty, TypeckResults, VariantDef}; use rustc_span::sym; declare_clippy_lint! { @@ -98,7 +98,7 @@ fn check_struct<'tcx>( self_ty: &hir::Ty<'_>, func_expr: &Expr<'_>, adt_def: AdtDef<'_>, - ty_args: GenericArgsRef<'_>, + ty_args: GenericArgs<'_>, typeck_results: &'tcx TypeckResults<'tcx>, is_const: bool, ) { diff --git a/src/tools/clippy/clippy_lints/src/derive/derive_partial_eq_without_eq.rs b/src/tools/clippy/clippy_lints/src/derive/derive_partial_eq_without_eq.rs index 271a7003caa31..566c590e79b96 100644 --- a/src/tools/clippy/clippy_lints/src/derive/derive_partial_eq_without_eq.rs +++ b/src/tools/clippy/clippy_lints/src/derive/derive_partial_eq_without_eq.rs @@ -29,7 +29,7 @@ pub(super) fn check<'tcx>( // If all of our fields implement `Eq`, we can implement `Eq` too && adt .all_fields() - .map(|f| f.ty(cx.tcx, args)) + .map(|f| f.ty(cx.tcx, *args)) .all(|ty| implements_trait_with_env(cx.tcx, typing_env, ty.skip_norm_wip(), eq_trait_def_id, None, &[])) { span_lint_hir_and_then( diff --git a/src/tools/clippy/clippy_lints/src/eta_reduction.rs b/src/tools/clippy/clippy_lints/src/eta_reduction.rs index e3674fcf0d0b6..6ebca6342b24e 100644 --- a/src/tools/clippy/clippy_lints/src/eta_reduction.rs +++ b/src/tools/clippy/clippy_lints/src/eta_reduction.rs @@ -355,7 +355,7 @@ fn has_late_bound_to_non_late_bound_regions(from_sig: FnSig<'_>, to_sig: FnSig<' fn check_ty(from_ty: Ty<'_>, to_ty: Ty<'_>) -> bool { match (from_ty.kind(), to_ty.kind()) { - (&ty::Adt(_, from_subs), &ty::Adt(_, to_subs)) => check_subs(from_subs, to_subs), + (&ty::Adt(_, from_subs), &ty::Adt(_, to_subs)) => check_subs(from_subs.as_slice(), to_subs.as_slice()), (&ty::Array(from_ty, _), &ty::Array(to_ty, _)) | (&ty::Slice(from_ty), &ty::Slice(to_ty)) => { check_ty(from_ty, to_ty) }, diff --git a/src/tools/clippy/clippy_lints/src/format_args.rs b/src/tools/clippy/clippy_lints/src/format_args.rs index 55824af734891..6828596a1781e 100644 --- a/src/tools/clippy/clippy_lints/src/format_args.rs +++ b/src/tools/clippy/clippy_lints/src/format_args.rs @@ -27,7 +27,7 @@ use rustc_errors::SuggestionStyle::{CompletelyHidden, ShowCode}; use rustc_hir::{Expr, ExprKind}; use rustc_lint::{LateContext, LateLintPass, LintContext as _, impl_lint_pass}; use rustc_middle::ty::adjustment::{Adjust, Adjustment, DerefAdjustKind}; -use rustc_middle::ty::{self, GenericArg, List, TraitRef, Ty, TyCtxt, Unnormalized, Upcast as _}; +use rustc_middle::ty::{self, GenericArg, TraitRef, Ty, TyCtxt, Unnormalized, Upcast as _}; use rustc_span::edition::Edition::Edition2021; use rustc_span::{BytePos, Pos as _, Span, Symbol}; use rustc_trait_selection::infer::TyCtxtInferExt as _; @@ -885,7 +885,7 @@ impl<'tcx> FormatArgsExpr<'_, 'tcx> { }; let pointer_debug = derived_debug && adt.all_fields().any(|f| { - self.has_pointer_debug(tcx.normalize_erasing_regions(typing_env, f.ty(tcx, args)), depth) + self.has_pointer_debug(tcx.normalize_erasing_regions(typing_env, f.ty(tcx, *args)), depth) }); self.has_pointer_format.insert(ty, pointer_debug); pointer_debug @@ -900,7 +900,7 @@ fn make_ty_msrv_map(tcx: TyCtxt<'_>) -> FxHashMap, Option> .into_iter() .filter_map(|(name, feature)| { tcx.get_diagnostic_item(name).map(|def_id| { - let ty = Ty::new_adt(tcx, tcx.adt_def(def_id), List::empty()); + let ty = Ty::new_adt(tcx, tcx.adt_def(def_id), ty::GenericArgs::empty()); (ty, feature) }) }) diff --git a/src/tools/clippy/clippy_lints/src/functions/result.rs b/src/tools/clippy/clippy_lints/src/functions/result.rs index a2121bb431b4e..1b3278fd59032 100644 --- a/src/tools/clippy/clippy_lints/src/functions/result.rs +++ b/src/tools/clippy/clippy_lints/src/functions/result.rs @@ -134,7 +134,7 @@ fn check_result_large_err<'tcx>( && let hir::Node::Item(item) = cx.tcx.hir_node_by_def_id(local_def_id) && let hir::ItemKind::Enum(_, _, ref def) = item.kind { - let variants_size = AdtVariantInfo::new(cx, *adt, subst); + let variants_size = AdtVariantInfo::new(cx, *adt, *subst); if let Some((first_variant, variants)) = variants_size.split_first() && first_variant.size >= large_err_threshold { diff --git a/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs b/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs index 60b69fd53311e..3c490ac020a04 100644 --- a/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs +++ b/src/tools/clippy/clippy_lints/src/implied_bounds_in_impls.rs @@ -181,7 +181,7 @@ fn try_resolve_type<'tcx>( /// Here i32 != i64, so this will return false. fn is_same_generics<'tcx>( tcx: TyCtxt<'tcx>, - trait_predicate_args: &'tcx [ty::GenericArg<'tcx>], + trait_predicate_args: ty::GenericArgs<'tcx>, implied_by_args: &'tcx [GenericArg<'tcx>], implied_args: &'tcx [GenericArg<'tcx>], implied_by_def_id: DefId, diff --git a/src/tools/clippy/clippy_lints/src/large_const_arrays.rs b/src/tools/clippy/clippy_lints/src/large_const_arrays.rs index 4d8ef09d17da3..c7bde177a8021 100644 --- a/src/tools/clippy/clippy_lints/src/large_const_arrays.rs +++ b/src/tools/clippy/clippy_lints/src/large_const_arrays.rs @@ -49,7 +49,7 @@ impl LargeConstArrays { match ty.kind() { ty::Adt(adt_def, args) => adt_def .all_fields() - .any(|f| self.check_impl(cx, f.ty(cx.tcx, args).skip_norm_wip())), + .any(|f| self.check_impl(cx, f.ty(cx.tcx, *args).skip_norm_wip())), ty::Array(element_type, cst) => { let normalized = cx .tcx diff --git a/src/tools/clippy/clippy_lints/src/large_enum_variant.rs b/src/tools/clippy/clippy_lints/src/large_enum_variant.rs index 947657bef5da3..b16c25ff544cb 100644 --- a/src/tools/clippy/clippy_lints/src/large_enum_variant.rs +++ b/src/tools/clippy/clippy_lints/src/large_enum_variant.rs @@ -79,7 +79,7 @@ impl<'tcx> LateLintPass<'tcx> for LargeEnumVariant { && adt.variants().len() > 1 && !item.span.in_external_macro(cx.tcx.sess.source_map()) { - let variants_size = AdtVariantInfo::new(cx, *adt, subst); + let variants_size = AdtVariantInfo::new(cx, *adt, *subst); let mut difference = variants_size[0].size - variants_size[1].size; if difference > self.maximum_size_difference_allowed { diff --git a/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs b/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs index 3581f7a93ef07..153c2bf6a7319 100644 --- a/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs +++ b/src/tools/clippy/clippy_lints/src/matches/significant_drop_in_scrutinee.rs @@ -202,7 +202,7 @@ impl<'a, 'tcx> SigDropChecker<'a, 'tcx> { rustc_middle::ty::Adt(adt, args) => { // if some field has significant drop, adt.all_fields() - .map(|field| field.ty(self.cx.tcx, args)) + .map(|field| field.ty(self.cx.tcx, *args)) .any(|ty| self.has_sig_drop_attr_impl(ty.skip_norm_wip())) // or if there is no generic lifetime and.. // (to avoid false positive on `Ref<'a, MutexGuard>`) diff --git a/src/tools/clippy/clippy_lints/src/methods/return_and_then.rs b/src/tools/clippy/clippy_lints/src/methods/return_and_then.rs index 404ad551919f5..09c26bcdf2847 100644 --- a/src/tools/clippy/clippy_lints/src/methods/return_and_then.rs +++ b/src/tools/clippy/clippy_lints/src/methods/return_and_then.rs @@ -32,7 +32,7 @@ pub(super) fn check<'tcx>( let has_ref_type = matches!(recv_type.kind(), ty::Adt(_, args) if args .first() - .and_then(|arg0: &GenericArg<'tcx>| GenericArg::as_type(*arg0)) + .and_then(|arg0: GenericArg<'tcx>| GenericArg::as_type(arg0)) .is_some_and(Ty::is_ref)); let has_temporaries = for_each_unconsumed_temporary(cx, recv, |_| ControlFlow::Break(())).is_break(); if has_ref_type && has_temporaries { diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_fallible_conversions.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_fallible_conversions.rs index c2b777e13739e..1ca4e5374ce3e 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_fallible_conversions.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_fallible_conversions.rs @@ -80,7 +80,7 @@ impl FunctionKind { fn check<'tcx>( cx: &LateContext<'tcx>, expr: &Expr<'_>, - node_args: ty::GenericArgsRef<'tcx>, + node_args: ty::GenericArgs<'tcx>, kind: FunctionKind, primary_span: Span, ) { diff --git a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs index c7e5e58b57afa..84cdefee365d8 100644 --- a/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs +++ b/src/tools/clippy/clippy_lints/src/methods/unnecessary_to_owned.rs @@ -17,7 +17,7 @@ use rustc_lint::LateContext; use rustc_middle::mir::Mutability; use rustc_middle::ty::adjustment::{Adjust, Adjustment, DerefAdjustKind, OverloadedDeref}; use rustc_middle::ty::{ - self, ClauseKind, GenericArg, GenericArgKind, GenericArgsRef, ParamTy, ProjectionClause, TraitClause, Ty, + self, ClauseKind, GenericArg, GenericArgKind, GenericArgs, ParamTy, ProjectionClause, TraitClause, Ty, }; use rustc_span::Symbol; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; @@ -451,12 +451,7 @@ fn skip_addr_of_ancestors<'tcx>( fn get_callee_generic_args_and_args<'tcx>( cx: &LateContext<'tcx>, expr: &'tcx Expr<'tcx>, -) -> Option<( - DefId, - GenericArgsRef<'tcx>, - Option<&'tcx Expr<'tcx>>, - &'tcx [Expr<'tcx>], -)> { +) -> Option<(DefId, GenericArgs<'tcx>, Option<&'tcx Expr<'tcx>>, &'tcx [Expr<'tcx>])> { if let ExprKind::Call(callee, args) = expr.kind && let callee_ty = cx.typeck_results().expr_ty(callee) && let ty::FnDef(callee_def_id, _) = callee_ty.kind() diff --git a/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs b/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs index 840f915b71beb..865f71700bc98 100644 --- a/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs +++ b/src/tools/clippy/clippy_lints/src/needless_borrows_for_generic_args.rs @@ -167,7 +167,7 @@ fn needless_borrow_count<'tcx>( cx: &LateContext<'tcx>, possible_borrowers: &mut Vec<(LocalDefId, PossibleBorrowerMap<'tcx, 'tcx>)>, fn_id: DefId, - callee_args: ty::GenericArgsRef<'tcx>, + callee_args: ty::GenericArgs<'tcx>, arg_index: usize, param_ty: ParamTy, mut expr: &Expr<'tcx>, @@ -244,7 +244,7 @@ fn needless_borrow_count<'tcx>( // `args_with_referent_ty` can be constructed outside of `check_referent` because the same // elements are modified each time `check_referent` is called. - let mut args_with_referent_ty = callee_args.to_vec(); + let mut args_with_referent_ty = callee_args.as_slice().to_vec(); let mut check_reference_and_referent = |reference: &Expr<'tcx>, referent: &Expr<'tcx>| { if let ExprKind::Field(base, _) = &referent.kind diff --git a/src/tools/clippy/clippy_lints/src/non_copy_const.rs b/src/tools/clippy/clippy_lints/src/non_copy_const.rs index a9d747e2757f7..42382470ec1ca 100644 --- a/src/tools/clippy/clippy_lints/src/non_copy_const.rs +++ b/src/tools/clippy/clippy_lints/src/non_copy_const.rs @@ -34,8 +34,8 @@ use rustc_lint::{LateContext, LateLintPass, LintContext as _, impl_lint_pass}; use rustc_middle::mir::{ConstValue, UnevaluatedConst}; use rustc_middle::ty::adjustment::{Adjust, Adjustment, DerefAdjustKind}; use rustc_middle::ty::{ - self, EarlyBinder, GenericArgs, GenericArgsRef, Instance, Ty, TyCtxt, TypeFolder, TypeSuperFoldable as _, - TypeckResults, TypingEnv, Unnormalized, + self, EarlyBinder, GenericArgs, Instance, Ty, TyCtxt, TypeFolder, TypeSuperFoldable as _, TypeckResults, TypingEnv, + Unnormalized, }; use rustc_span::DUMMY_SP; use std::collections::hash_map::Entry; @@ -378,7 +378,7 @@ impl<'tcx> NonCopyConst<'tcx> { tcx: TyCtxt<'tcx>, typing_env: TypingEnv<'tcx>, typeck: &'tcx TypeckResults<'tcx>, - gen_args: GenericArgsRef<'tcx>, + gen_args: GenericArgs<'tcx>, e: &'tcx Expr<'tcx>, ) -> bool { // Make sure to instantiate all types coming from `typeck` with `gen_args`. @@ -572,7 +572,7 @@ impl<'tcx> NonCopyConst<'tcx> { typeck: &'tcx TypeckResults<'tcx>, mut src_expr: &'tcx Expr<'tcx>, mut init_typeck: &'tcx TypeckResults<'tcx>, - mut init_args: GenericArgsRef<'tcx>, + mut init_args: GenericArgs<'tcx>, mut init_expr: &'tcx Expr<'tcx>, ) -> Option> { // Make sure to instantiate all types coming from `init_typeck` with `init_args`. @@ -945,7 +945,7 @@ fn get_const_hir_value<'tcx>( tcx: TyCtxt<'tcx>, typing_env: TypingEnv<'tcx>, did: DefId, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Option<(&'tcx TypeckResults<'tcx>, &'tcx Expr<'tcx>)> { let did = did.as_local()?; let (did, ct_rhs) = match tcx.hir_node(tcx.local_def_id_to_hir_id(did)) { diff --git a/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs b/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs index bd4feea78f5a2..ad883a9b80bc0 100644 --- a/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs +++ b/src/tools/clippy/clippy_lints/src/non_send_fields_in_send_ty.rs @@ -100,7 +100,7 @@ impl<'tcx> LateLintPass<'tcx> for NonSendFieldInSendTy { .as_local() .map(|local_def_id| cx.tcx.local_def_id_to_hir_id(local_def_id)) && !is_lint_allowed(cx, NON_SEND_FIELDS_IN_SEND_TY, field_hir_id) - && let field_ty = field.ty(cx.tcx, impl_trait_args).skip_norm_wip() + && let field_ty = field.ty(cx.tcx, *impl_trait_args).skip_norm_wip() && !ty_allowed_in_send(cx, field_ty, send_trait) && let Node::Field(field_def) = cx.tcx.hir_node(field_hir_id) { diff --git a/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs b/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs index 744b521a56129..167944cb21c68 100644 --- a/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs +++ b/src/tools/clippy/clippy_lints/src/only_used_in_recursion.rs @@ -10,7 +10,7 @@ use rustc_hir::{ TraitItemKind, }; use rustc_lint::{LateContext, LateLintPass, impl_lint_pass}; -use rustc_middle::ty::{self, ConstKind, GenericArgKind, GenericArgsRef}; +use rustc_middle::ty::{self, ConstKind, GenericArgKind, GenericArgs}; use rustc_span::Span; use rustc_span::symbol::{Ident, kw}; use std::iter; @@ -336,7 +336,9 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { ( trait_item_id, FnKind::ImplTraitFn( - std::ptr::from_ref(cx.tcx.erase_and_anonymize_regions(trait_ref.args)) as usize + #[allow(deprecated)] + cx.tcx.erase_and_anonymize_regions(trait_ref.args).as_ptr() + as usize, ), usize::from(sig.decl.implicit_self().has_implicit_self()), ) @@ -480,7 +482,7 @@ impl<'tcx> LateLintPass<'tcx> for OnlyUsedInRecursion { } } -fn has_matching_args(kind: FnKind, args: GenericArgsRef<'_>) -> bool { +fn has_matching_args(kind: FnKind, args: GenericArgs<'_>) -> bool { match kind { FnKind::Fn => true, FnKind::TraitFn => args.iter().enumerate().all(|(idx, subst)| match subst.kind() { @@ -488,6 +490,7 @@ fn has_matching_args(kind: FnKind, args: GenericArgsRef<'_>) -> bool { GenericArgKind::Type(ty) => matches!(*ty.kind(), ty::Param(ty) if ty.index as usize == idx), GenericArgKind::Const(c) => matches!(c.kind(), ConstKind::Param(c) if c.index as usize == idx), }), - FnKind::ImplTraitFn(expected_args) => std::ptr::from_ref(args) as usize == expected_args, + #[allow(deprecated)] + FnKind::ImplTraitFn(expected_args) => args.as_ptr() as usize == expected_args, } } diff --git a/src/tools/clippy/clippy_lints/src/ptr/ptr_arg.rs b/src/tools/clippy/clippy_lints/src/ptr/ptr_arg.rs index b5fcc10f613ee..6c3189cc00c81 100644 --- a/src/tools/clippy/clippy_lints/src/ptr/ptr_arg.rs +++ b/src/tools/clippy/clippy_lints/src/ptr/ptr_arg.rs @@ -15,7 +15,7 @@ use rustc_infer::infer::TyCtxtInferExt as _; use rustc_infer::traits::{Obligation, ObligationCause}; use rustc_lint::LateContext; use rustc_middle::hir::nested_filter; -use rustc_middle::ty::{self, Binder, ClauseKind, ExistentialPredicate, List, PredicateKind, Ty}; +use rustc_middle::ty::{self, Binder, ClauseKind, ExistentialPredicate, GenericArgs, PredicateKind, Ty}; use rustc_span::Span; use rustc_span::symbol::Symbol; use rustc_trait_selection::infer::InferCtxtExt as _; @@ -177,7 +177,7 @@ impl<'tcx> DerefTy<'tcx> { Self::Path => Ty::new_adt( cx.tcx, cx.tcx.adt_def(cx.tcx.get_diagnostic_item(sym::Path).unwrap()), - List::empty(), + GenericArgs::empty(), ), Self::Slice(_, ty) => Ty::new_slice(cx.tcx, ty), } diff --git a/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs b/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs index 064c78d9d1eec..5af6aa1f632e9 100644 --- a/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs +++ b/src/tools/clippy/clippy_lints/src/significant_drop_tightening.rs @@ -180,7 +180,7 @@ impl<'cx, 'others, 'tcx> AttrChecker<'cx, 'others, 'tcx> { match ty.kind() { rustc_middle::ty::Adt(a, b) => { for f in a.all_fields() { - let ty = f.ty(self.cx.tcx, b).skip_norm_wip(); + let ty = f.ty(self.cx.tcx, *b).skip_norm_wip(); if self.has_sig_drop_attr(ty, depth) { return true; } diff --git a/src/tools/clippy/clippy_lints/src/transmute/transmute_undefined_repr.rs b/src/tools/clippy/clippy_lints/src/transmute/transmute_undefined_repr.rs index 83eca20266684..881cf56b6713d 100644 --- a/src/tools/clippy/clippy_lints/src/transmute/transmute_undefined_repr.rs +++ b/src/tools/clippy/clippy_lints/src/transmute/transmute_undefined_repr.rs @@ -3,7 +3,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::ty::is_c_void; use rustc_hir::Expr; use rustc_lint::LateContext; -use rustc_middle::ty::{self, GenericArgsRef, IntTy, Ty, UintTy, Unnormalized}; +use rustc_middle::ty::{self, IntTy, Ty, UintTy, Unnormalized}; #[expect(clippy::too_many_lines)] pub(super) fn check<'tcx>( @@ -96,7 +96,7 @@ pub(super) fn check<'tcx>( (from_ty.kind(), to_ty.kind()) && from_def == to_def { - if same_except_params(from_subs, to_subs) { + if same_except_params(*from_subs, *to_subs) { return false; } Some(from_def.did()) @@ -322,12 +322,14 @@ fn is_size_pair(ty: Ty<'_>) -> bool { } } -fn same_except_params<'tcx>(subs1: GenericArgsRef<'tcx>, subs2: GenericArgsRef<'tcx>) -> bool { +fn same_except_params<'tcx>(subs1: ty::GenericArgs<'tcx>, subs2: ty::GenericArgs<'tcx>) -> bool { for (t1, t2) in subs1.terms().zip(subs2.terms()).filter(|(t1, t2)| t1 != t2) { match (t1.kind(), t2.kind()) { (ty::TermKind::Ty(ty1), ty::TermKind::Ty(ty2)) => match (ty1.kind(), ty2.kind()) { (ty::Param(_), _) | (_, ty::Param(_)) => (), - (ty::Adt(adt1, subs1), ty::Adt(adt2, subs2)) if adt1 == adt2 && same_except_params(subs1, subs2) => (), + (ty::Adt(adt1, subs1), ty::Adt(adt2, subs2)) if adt1 == adt2 && same_except_params(*subs1, *subs2) => { + () + }, _ => return false, }, // FIXME: check const parameters better as well. Currently this will consider `Array<5>` the same as diff --git a/src/tools/clippy/clippy_lints/src/try_from_instead_of_from_str.rs b/src/tools/clippy/clippy_lints/src/try_from_instead_of_from_str.rs index c0ea44efe9e99..6c15b17537d32 100644 --- a/src/tools/clippy/clippy_lints/src/try_from_instead_of_from_str.rs +++ b/src/tools/clippy/clippy_lints/src/try_from_instead_of_from_str.rs @@ -173,7 +173,7 @@ impl<'tcx> LateLintPass<'tcx> for TryFromInsteadOfFromStr { && let trait_ref = cx.tcx.impl_trait_ref(impl_def_id) && let instantiated_trait_ref = trait_ref.instantiate_identity().skip_normalization() // We check if the "from" item is a non-mutable `&str`. - && let [_, from_arg] = &**instantiated_trait_ref.args + && let [_, from_arg] = instantiated_trait_ref.args.as_slice() && let Some(from_ty) = from_arg.as_type() && from_ty.is_imm_ref_str() // We check that the trait is `TryFrom`. diff --git a/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs b/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs index e3b76b2b83452..e9b6802cb82e1 100644 --- a/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs +++ b/src/tools/clippy/clippy_lints/src/unconditional_recursion.rs @@ -426,7 +426,7 @@ fn check_from(cx: &LateContext<'_>, method_span: Span, method_def_id: LocalDefId // which calls back into our `From::from` again (`Into` is not specializable). // rustc's unconditional_recursion already catches calling `From::from` directly if let Some((fn_def_id, node_args)) = fn_def_id_with_node_args(cx, expr) - && let [s1, s2] = **node_args + && let [s1, s2] = *node_args.as_slice() && let (Some(s1), Some(s2)) = (s1.as_type(), s2.as_type()) && let Some(trait_def_id) = cx.tcx.trait_of_assoc(fn_def_id) && cx.tcx.is_diagnostic_item(sym::Into, trait_def_id) diff --git a/src/tools/clippy/clippy_lints/src/useless_conversion.rs b/src/tools/clippy/clippy_lints/src/useless_conversion.rs index 08197757c0553..4b7d9f3dd8fed 100644 --- a/src/tools/clippy/clippy_lints/src/useless_conversion.rs +++ b/src/tools/clippy/clippy_lints/src/useless_conversion.rs @@ -13,7 +13,7 @@ use rustc_infer::traits::Obligation; use rustc_lint::{LateContext, LateLintPass, impl_lint_pass}; use rustc_middle::traits::ObligationCause; use rustc_middle::ty::adjustment::{Adjust, AutoBorrow, AutoBorrowMutability}; -use rustc_middle::ty::{self, EarlyBinder, GenericArg, GenericArgsRef, Ty, TypeVisitableExt as _}; +use rustc_middle::ty::{self, EarlyBinder, GenericArg, GenericArgs, Ty, TypeVisitableExt as _}; use rustc_span::Span; use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _; @@ -86,7 +86,7 @@ fn into_iter_bound<'tcx>( into_iter_did: DefId, into_iter_receiver: Ty<'tcx>, param_index: u32, - node_args: GenericArgsRef<'tcx>, + node_args: GenericArgs<'tcx>, ) -> Option { let mut into_iter_span = None; diff --git a/src/tools/clippy/clippy_lints/src/volatile_composites.rs b/src/tools/clippy/clippy_lints/src/volatile_composites.rs index f4bfca1f98c1f..ad41e359385bb 100644 --- a/src/tools/clippy/clippy_lints/src/volatile_composites.rs +++ b/src/tools/clippy/clippy_lints/src/volatile_composites.rs @@ -91,7 +91,7 @@ fn is_struct_repr_transparent<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> boo && let [fieldty] = adt_def .all_fields() .filter_map(|field| { - let fty = field.ty(cx.tcx, args).skip_norm_wip(); + let fty = field.ty(cx.tcx, *args).skip_norm_wip(); if is_zero_sized_ty(cx, fty) { None } else { Some(fty) } }) .collect::>() diff --git a/src/tools/clippy/clippy_utils/src/lib.rs b/src/tools/clippy/clippy_utils/src/lib.rs index 31b96bd4f9085..eb5befb52c3e4 100644 --- a/src/tools/clippy/clippy_utils/src/lib.rs +++ b/src/tools/clippy/clippy_utils/src/lib.rs @@ -108,8 +108,8 @@ use rustc_middle::mir::{AggregateKind, Operand, RETURN_PLACE, Rvalue, StatementK use rustc_middle::ty::adjustment::{Adjust, Adjustment, AutoBorrow, DerefAdjustKind, PointerCoercion}; use rustc_middle::ty::layout::IntegerExt as _; use rustc_middle::ty::{ - self as rustc_ty, Binder, BorrowKind, ClosureKind, EarlyBinder, GenericArgKind, GenericArgsRef, IntTy, Ty, TyCtxt, - TypeFlags, TypeVisitableExt as _, TypeckResults, UintTy, UpvarCapture, + self as rustc_ty, Binder, BorrowKind, ClosureKind, EarlyBinder, GenericArgKind, IntTy, Ty, TyCtxt, TypeFlags, + TypeVisitableExt as _, TypeckResults, UintTy, UpvarCapture, }; use rustc_session::config::Input; use rustc_span::hygiene::{ExpnKind, MacroKind}; @@ -2102,7 +2102,7 @@ pub fn fn_def_id(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option { pub fn fn_def_id_with_node_args<'tcx>( cx: &LateContext<'tcx>, expr: &Expr<'_>, -) -> Option<(DefId, GenericArgsRef<'tcx>)> { +) -> Option<(DefId, rustc_ty::GenericArgs<'tcx>)> { let typeck = cx.typeck_results(); match &expr.kind { ExprKind::MethodCall(..) => Some(( @@ -3240,7 +3240,7 @@ pub fn get_path_from_caller_to_method_type<'tcx>( tcx: TyCtxt<'tcx>, from: LocalDefId, method: DefId, - args: GenericArgsRef<'tcx>, + args: rustc_ty::GenericArgs<'tcx>, ) -> String { let assoc_item = tcx.associated_item(method); let def_id = assoc_item.container_id(tcx); @@ -3253,7 +3253,12 @@ pub fn get_path_from_caller_to_method_type<'tcx>( } } -fn get_path_to_ty<'tcx>(tcx: TyCtxt<'tcx>, from: LocalDefId, ty: Ty<'tcx>, args: GenericArgsRef<'tcx>) -> String { +fn get_path_to_ty<'tcx>( + tcx: TyCtxt<'tcx>, + from: LocalDefId, + ty: Ty<'tcx>, + args: rustc_ty::GenericArgs<'tcx>, +) -> String { match ty.kind() { rustc_ty::Adt(adt, _) => get_path_to_callee(tcx, from, adt.did()), // TODO these types need to be recursively resolved as well @@ -3494,7 +3499,7 @@ pub fn expr_requires_coercion<'tcx>(cx: &LateContext<'tcx>, expr: &Expr<'tcx>) - v_def .fields .iter() - .any(|field| field.ty(cx.tcx, generic_args).has_type_flags(TypeFlags::HAS_TY_PARAM)) + .any(|field| field.ty(cx.tcx, *generic_args).has_type_flags(TypeFlags::HAS_TY_PARAM)) } else { false } diff --git a/src/tools/clippy/clippy_utils/src/ty/mod.rs b/src/tools/clippy/clippy_utils/src/ty/mod.rs index 17787740dad55..358f961f9097b 100644 --- a/src/tools/clippy/clippy_utils/src/ty/mod.rs +++ b/src/tools/clippy/clippy_utils/src/ty/mod.rs @@ -24,7 +24,7 @@ use rustc_middle::ty::adjustment::{Adjust, Adjustment, DerefAdjustKind}; use rustc_middle::ty::layout::{LayoutError, LayoutOf as _, TyAndLayout}; use rustc_middle::ty::{ self, AdtDef, AliasTy, AssocItem, AssocTag, Binder, BoundRegion, BoundVarIndexKind, FnSig, GenericArg, - GenericArgKind, GenericArgsRef, IntTy, ProjectionAliasTy, Region, RegionKind, TraitRef, Ty, TyCtxt, + GenericArgKind, GenericArgs, IntTy, ProjectionAliasTy, Region, RegionKind, TraitRef, Ty, TyCtxt, TypeSuperVisitable as _, TypeVisitable, TypeVisitableExt as _, TypeVisitor, UintTy, Unnormalized, VariantDef, VariantDiscr, }; @@ -72,7 +72,7 @@ pub fn can_partially_move_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool ty::Param(_) => false, ty::Adt(def, subs) => def .all_fields() - .any(|f| !is_copy(cx, f.ty(cx.tcx, subs).skip_norm_wip())), + .any(|f| !is_copy(cx, f.ty(cx.tcx, *subs).skip_norm_wip())), _ => true, } } @@ -301,7 +301,7 @@ pub fn implements_trait_with_env_from_iter<'tcx>( "`DefId` must belong to a trait or trait alias" ); #[cfg(debug_assertions)] - assert_generic_args_match(tcx, trait_id, trait_ref.args); + assert_generic_args_match(tcx, trait_id, trait_ref.args.as_slice()); let obligation = Obligation::new(tcx, ObligationCause::dummy(), param_env, trait_ref); infcx @@ -487,7 +487,7 @@ pub fn needs_ordered_drop<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { ty::Array(ty, _) => needs_ordered_drop_inner(cx, *ty, seen), ty::Adt(adt, subs) => adt .all_fields() - .map(|f| f.ty(cx.tcx, subs).skip_norm_wip()) + .map(|f| f.ty(cx.tcx, *subs).skip_norm_wip()) .any(|ty| needs_ordered_drop_inner(cx, ty, seen)), _ => true, } @@ -1007,7 +1007,7 @@ pub struct AdtVariantInfo { impl AdtVariantInfo { /// Returns ADT variants ordered by size - pub fn new<'tcx>(cx: &LateContext<'tcx>, adt: AdtDef<'tcx>, subst: GenericArgsRef<'tcx>) -> Vec { + pub fn new<'tcx>(cx: &LateContext<'tcx>, adt: AdtDef<'tcx>, subst: GenericArgs<'tcx>) -> Vec { let mut variants_size = adt .variants() .iter() @@ -1081,7 +1081,7 @@ pub fn approx_ty_size<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> u64 { .map(|v| { v.fields .iter() - .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst).skip_norm_wip())) + .map(|field| approx_ty_size(cx, field.ty(cx.tcx, *subst).skip_norm_wip())) .sum::() }) .sum(), @@ -1091,7 +1091,7 @@ pub fn approx_ty_size<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> u64 { .map(|v| { v.fields .iter() - .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst).skip_norm_wip())) + .map(|field| approx_ty_size(cx, field.ty(cx.tcx, *subst).skip_norm_wip())) .sum::() }) .max() @@ -1102,7 +1102,7 @@ pub fn approx_ty_size<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> u64 { .map(|v| { v.fields .iter() - .map(|field| approx_ty_size(cx, field.ty(cx.tcx, subst).skip_norm_wip())) + .map(|field| approx_ty_size(cx, field.ty(cx.tcx, *subst).skip_norm_wip())) .max() .unwrap_or_default() }) @@ -1183,7 +1183,7 @@ pub fn make_projection<'tcx>( tcx: TyCtxt<'tcx>, container_id: DefId, assoc_ty: Symbol, - args: GenericArgsRef<'tcx>, + args: GenericArgs<'tcx>, ) -> Option> { let Some(assoc_item) = tcx.associated_items(container_id).find_by_ident_and_kind( tcx, @@ -1195,7 +1195,7 @@ pub fn make_projection<'tcx>( return None; }; #[cfg(debug_assertions)] - assert_generic_args_match(tcx, assoc_item.def_id, args); + assert_generic_args_match(tcx, assoc_item.def_id, args.as_slice()); let kind = if let DefKind::Impl { of_trait: false } = tcx.def_kind(tcx.parent(assoc_item.def_id)) { ty::AliasTyKind::Inherent { @@ -1494,7 +1494,7 @@ pub fn get_field_def_id_by_name(ty: Ty<'_>, name: Symbol) -> Option { pub fn option_arg_ty<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option> { match *ty.kind() { ty::Adt(adt, args) - if let [arg] = &**args + if let [arg] = *args.as_slice() && let Some(arg) = arg.as_type() && adt.is_diag_item(cx, sym::Option) => { @@ -1541,7 +1541,7 @@ pub fn has_non_owning_mutable_access<'tcx>(cx: &LateContext<'tcx>, iter_ty: Ty<' .types() .any(|arg_ty| has_non_owning_mutable_access_inner(cx, visited, arg_ty)), ty::Adt(adt_def, args) => adt_def.all_fields().any(|field| { - has_non_owning_mutable_access_inner(cx, visited, normalize_ty(cx, field.ty(cx.tcx, args))) + has_non_owning_mutable_access_inner(cx, visited, normalize_ty(cx, field.ty(cx.tcx, *args))) }), ty::Array(elem_ty, _) | ty::Slice(elem_ty) => has_non_owning_mutable_access_inner(cx, visited, *elem_ty), ty::RawPtr(pointee_ty, mutability) | ty::Ref(_, pointee_ty, mutability) => { From 68e8bdf870acefdaf598039737a8cf27e1ede3fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Wed, 28 Oct 2026 15:48:20 +0100 Subject: [PATCH 07/18] fixup gcc --- compiler/rustc_codegen_gcc/src/context.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/compiler/rustc_codegen_gcc/src/context.rs b/compiler/rustc_codegen_gcc/src/context.rs index b57e0fb2cd23a..fc9292ea5e815 100644 --- a/compiler/rustc_codegen_gcc/src/context.rs +++ b/compiler/rustc_codegen_gcc/src/context.rs @@ -507,7 +507,7 @@ impl<'gcc, 'tcx> MiscCodegenMethods<'tcx> for CodegenCx<'gcc, 'tcx> { tcx, self.typing_env(), def_id, - ty::List::empty(), + ty::GenericArgs::empty(), DUMMY_SP, ); From 101dc61e0797a3bd58f04e8a462a4e2694036b6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jana=20D=C3=B6nszelmann?= Date: Wed, 28 Oct 2026 16:01:21 +0100 Subject: [PATCH 08/18] fixup miri --- src/tools/miri/src/intrinsics/math.rs | 4 ++-- src/tools/miri/src/intrinsics/mod.rs | 2 +- src/tools/miri/src/shims/native_lib/mod.rs | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/tools/miri/src/intrinsics/math.rs b/src/tools/miri/src/intrinsics/math.rs index 96c7e881d1b66..7716e446a3965 100644 --- a/src/tools/miri/src/intrinsics/math.rs +++ b/src/tools/miri/src/intrinsics/math.rs @@ -19,7 +19,7 @@ fn sqrt<'tcx, F: Float + FloatConvert + Into>( /// Determine which float operation on which type this is. fn is_host_unary_float_op( intrinsic_name: &str, - generic_args: ty::GenericArgsRef<'_>, + generic_args: ty::GenericArgs<'_>, ) -> Option<(FloatTy, HostUnaryFloatOp)> { let host_float_op = match intrinsic_name { "sin" => HostUnaryFloatOp::Sin, @@ -92,7 +92,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { fn emulate_math_intrinsic( &mut self, intrinsic_name: &str, - generic_args: ty::GenericArgsRef<'tcx>, + generic_args: ty::GenericArgs<'tcx>, args: &[OpTy<'tcx>], dest: &PlaceTy<'tcx>, ) -> InterpResult<'tcx, EmulateItemResult> { diff --git a/src/tools/miri/src/intrinsics/mod.rs b/src/tools/miri/src/intrinsics/mod.rs index 247571a0f36f4..6a17d6e250de6 100644 --- a/src/tools/miri/src/intrinsics/mod.rs +++ b/src/tools/miri/src/intrinsics/mod.rs @@ -81,7 +81,7 @@ pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> { fn emulate_intrinsic_by_name( &mut self, intrinsic_name: &str, - generic_args: ty::GenericArgsRef<'tcx>, + generic_args: ty::GenericArgs<'tcx>, args: &[OpTy<'tcx>], dest: &PlaceTy<'tcx>, ret: Option, diff --git a/src/tools/miri/src/shims/native_lib/mod.rs b/src/tools/miri/src/shims/native_lib/mod.rs index 157ac022f7a14..3dc616e8d6f39 100644 --- a/src/tools/miri/src/shims/native_lib/mod.rs +++ b/src/tools/miri/src/shims/native_lib/mod.rs @@ -368,7 +368,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { &self, orig_ty: Ty<'tcx>, adt_def: ty::AdtDef<'tcx>, - args: &'tcx ty::List>, + args: ty::GenericArgs<'tcx>, ) -> Result> { let this = self.eval_context_ref(); // TODO: unions, etc. @@ -419,7 +419,7 @@ trait EvalContextExtPriv<'tcx>: crate::MiriInterpCxExt<'tcx> { } Ok(match layout.ty.kind() { // Scalar types have already been handled above. - ty::Adt(adt_def, args) => self.adt_to_ffitype(layout.ty, *adt_def, args)?, + ty::Adt(adt_def, args) => self.adt_to_ffitype(layout.ty, *adt_def, *args)?, // Rust uses `()` as return type for `void` function, which becomes `Tuple([])`. ty::Tuple(t_list) if t_list.len() == 0 => FfiType::void(), _ => return Err(layout.ty), From 23d352a1d7c657b2eb6055e0fdc1bbe1310730c6 Mon Sep 17 00:00:00 2001 From: bjorn3 <17426603+bjorn3@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:15:44 +0100 Subject: [PATCH 09/18] Use getrandom instead of /scheme/rand on Redox OS This would allow more flexibility in how we implement getting randomness in Redox OS by only requiring changes to relibc and randd. In addition it reduces the amount of Redox specific code libstd uses. --- library/std/src/random.rs | 3 +-- library/std/src/sys/random/mod.rs | 6 +----- library/std/src/sys/random/redox.rs | 12 ------------ 3 files changed, 2 insertions(+), 19 deletions(-) delete mode 100644 library/std/src/sys/random/redox.rs diff --git a/library/std/src/random.rs b/library/std/src/random.rs index 853756fcd32b6..b57ce1d1e5989 100644 --- a/library/std/src/random.rs +++ b/library/std/src/random.rs @@ -102,9 +102,8 @@ use crate::sys::random as sys; /// Solaris | [`arc4random_buf`](https://docs.oracle.com/cd/E88353_01/html/E37843/arc4random-3c.html) /// Vita | `arc4random_buf` /// Hermit | `read_entropy` -/// Horizon, Cygwin | `getrandom` +/// Horizon, Cygwin, Redox | `getrandom` /// AIX, Hurd, QNX | `/dev/urandom` -/// Redox | `/scheme/rand` /// RTEMS | [`arc4random_buf`](https://docs.rtems.org/branches/main/bsp-howto/getentropy.html) /// SGX | [`rdrand`](https://en.wikipedia.org/wiki/RDRAND) /// SOLID | `SOLID_RNG_SampleRandomBytes` diff --git a/library/std/src/sys/random/mod.rs b/library/std/src/sys/random/mod.rs index bc3dd501730b7..23f6ce8d25eb4 100644 --- a/library/std/src/sys/random/mod.rs +++ b/library/std/src/sys/random/mod.rs @@ -44,7 +44,7 @@ cfg_select! { mod hermit; pub use hermit::fill_bytes; } - any(target_os = "horizon", target_os = "cygwin") => { + any(target_os = "horizon", target_os = "cygwin", target_os = "redox") => { // FIXME(horizon): add arc4random_buf to shim-3ds mod getrandom; pub use getrandom::fill_bytes; @@ -53,10 +53,6 @@ cfg_select! { mod unix_legacy; pub use unix_legacy::fill_bytes; } - target_os = "redox" => { - mod redox; - pub use redox::fill_bytes; - } target_os = "motor" => { mod motor; pub use motor::fill_bytes; diff --git a/library/std/src/sys/random/redox.rs b/library/std/src/sys/random/redox.rs deleted file mode 100644 index b004335a35176..0000000000000 --- a/library/std/src/sys/random/redox.rs +++ /dev/null @@ -1,12 +0,0 @@ -use crate::fs::File; -use crate::io::Read; -use crate::sync::OnceLock; - -static SCHEME: OnceLock = OnceLock::new(); - -pub fn fill_bytes(bytes: &mut [u8]) { - SCHEME - .get_or_try_init(|| File::open("/scheme/rand")) - .and_then(|mut scheme| scheme.read_exact(bytes)) - .expect("failed to generate random data"); -} From e33a98d9e0d0f54b9b4df912f837d102e8718724 Mon Sep 17 00:00:00 2001 From: Ben Kimock Date: Tue, 27 Oct 2026 18:37:37 -0400 Subject: [PATCH 10/18] Use a fixed-length encoding for hash disambiguators in v0 symbols --- compiler/rustc_span/src/def_id.rs | 5 +++++ compiler/rustc_symbol_mangling/src/v0.rs | 22 ++++++++++++++++++---- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_span/src/def_id.rs b/compiler/rustc_span/src/def_id.rs index 7a51bc4af828a..9134e652987c9 100644 --- a/compiler/rustc_span/src/def_id.rs +++ b/compiler/rustc_span/src/def_id.rs @@ -201,6 +201,11 @@ impl StableCrateId { StableCrateId(hasher.finish()) } + #[inline] + pub fn as_hash(self) -> Hash64 { + self.0 + } + #[inline] pub fn as_u64(self) -> u64 { self.0.as_u64() diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index 7bab29c658e66..07bad8dc8a604 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -160,7 +160,7 @@ pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> Strin p.path_append_ns( |p| { p.push("C"); - p.push_disambiguator({ + p.push_disambiguator_fixed_len({ let mut hasher = StableHasher::new(); // Incorporate the rustc version to ensure #[rustc_std_internal_symbol] functions // get a different symbol name depending on the rustc version. @@ -169,8 +169,7 @@ pub fn mangle_internal_symbol<'tcx>(tcx: TyCtxt<'tcx>, item_name: &str) -> Strin // abi incompatibility with the standard library. hasher.write(tcx.sess.cfg_version.as_bytes()); - let hash: Hash64 = hasher.finish(); - hash.as_u64() + hasher.finish() }); p.push_ident("__rustc"); Ok(()) @@ -260,6 +259,21 @@ impl<'tcx> V0SymbolMangler<'tcx> { self.push_opt_integer_62("s", dis); } + /// Use instead of push_disambiguator when the disambiguator is a hash. The value of the hash + /// will be converted to a fixed-length base 62 integer, which ensures that the length of + /// mangled names is not occasionally shorter due to the hash value. This fixed-length encoding + /// prevents binary sizes from fluctuating between builds of the compiler. + fn push_disambiguator_fixed_len(&mut self, dis: Hash64) { + let x = dis.as_u64(); + if let Some(x) = x.checked_sub(1) { + self.push("s"); + if let Some(x) = x.checked_sub(1) { + self.out.push_str(&x.to_base_fixed_len(62)); + } + self.out.push('_'); + } + } + fn push_ident(&mut self, ident: &str) { push_ident(ident, &mut self.out) } @@ -922,7 +936,7 @@ impl<'tcx> Printer<'tcx> for V0SymbolMangler<'tcx> { self.push("C"); if !self.is_exportable { let stable_crate_id = self.tcx.stable_crate_id(cnum); - self.push_disambiguator(stable_crate_id.as_u64()); + self.push_disambiguator_fixed_len(stable_crate_id.as_hash()); } let name = self.tcx.crate_name(cnum); self.push_ident(name.as_str()); From 119529b3f7ffe1c081af99d59652e80a62f10d20 Mon Sep 17 00:00:00 2001 From: EFanZh Date: Thu, 29 Oct 2026 07:24:47 +0000 Subject: [PATCH 11/18] Add behavior tests for `Arc` and `Rc` --- tests/assembly-llvm/x86_64-rc-arc.rs | 207 ++++++++++++++++++ .../lib-optimizations/rc-arc-optimizations.rs | 49 +++++ 2 files changed, 256 insertions(+) create mode 100644 tests/assembly-llvm/x86_64-rc-arc.rs create mode 100644 tests/codegen-llvm/lib-optimizations/rc-arc-optimizations.rs diff --git a/tests/assembly-llvm/x86_64-rc-arc.rs b/tests/assembly-llvm/x86_64-rc-arc.rs new file mode 100644 index 0000000000000..8bb8c11bb606d --- /dev/null +++ b/tests/assembly-llvm/x86_64-rc-arc.rs @@ -0,0 +1,207 @@ +//! This test pins the behaviors of some `Rc` and `Arc` operations so that changes are noticed. +//! These operations are frequently used, so they should behave as expected. + +//@ only-unix +//@ only-x86_64 +//@ compile-flags: --crate-type=lib -Z merge-functions=disabled -C opt-level=3 -C llvm-args=-x86-asm-syntax=intel +//@ assembly-output: emit-asm + +use std::mem; +use std::rc::{Rc, Weak as RcWeak}; +use std::sync::{Arc, Weak as ArcWeak}; + +// CHECK-LABEL: rc_new: +// CHECK-DAG: mov edi, 24 +// CHECK-DAG: mov esi, 8 +// CHECK-NEXT: call qword ptr {{.*}}__rust_alloc +// CHECK-NEXT: test rax, rax +// CHECK-NEXT: je [[RC_NEW_ALLOC_FAIL:\..+]] +// CHECK-DAG: mov qword ptr [rax], 1 +// CHECK-DAG: mov qword ptr [rax + 8], 1 +// CHECK-DAG: mov qword ptr [rax + 16], rbx +// CHECK-DAG: pop rbx +// CHECK: ret +// CHECK-NEXT: [[RC_NEW_ALLOC_FAIL]]: +// CHECK: mov edi, [[#N:]] +// CHECK-NEXT: mov esi, [[#32-N]] +// CHECK-NEXT: call qword ptr {{.*}}handle_alloc_error +#[unsafe(no_mangle)] +pub fn rc_new(x: usize) -> Rc { + Rc::new(x) +} + +// CHECK-LABEL: rc_deref: +// CHECK: mov rax, qword ptr [rdi] +// CHECK-NEXT: add rax, 16 +// CHECK-NEXT: ret +#[unsafe(no_mangle)] +pub fn rc_deref(rc: &Rc) -> &usize { + rc +} + +// CHECK-LABEL: rc_increment: +// CHECK: mov rax, qword ptr [rdi] +// CHECK-NEXT: inc qword ptr [rax] +// CHECK-NEXT: je [[RC_INCREMENT_OVERFLOW:\..+]] +// CHECK-NEXT: ret +// CHECK-NEXT: [[RC_INCREMENT_OVERFLOW]]: +// CHECK-NEXT: ud2 +#[unsafe(no_mangle)] +pub fn rc_increment(rc: &Rc) { + mem::forget(Rc::clone(rc)); +} + +// CHECK-LABEL: rc_decrement: +// CHECK: push rax +// CHECK: mov qword ptr [rsp], rdi +// CHECK-NEXT: dec qword ptr [rdi] +// CHECK-NEXT: je [[RC_DECREMENT_DROP_SLOW:\..+]] +// CHECK-NEXT: pop rax +// CHECK: ret +// CHECK-NEXT: [[RC_DECREMENT_DROP_SLOW]]: +// CHECK: mov rdi, rsp +// CHECK-NEXT: call qword ptr {{.*}}drop_slow +// CHECK-NEXT: pop rax +// CHECK: ret +#[unsafe(no_mangle)] +pub fn rc_decrement(rc: Rc) { + drop(rc); +} + +// CHECK-LABEL: rc_downgrade: +// CHECK: mov rax, qword ptr [rdi] +// CHECK-NEXT: inc qword ptr [rax + 8] +// CHECK-NEXT: je [[RC_DOWNGRADE_OVERFLOW:\..+]] +// CHECK: ret +// CHECK-NEXT: [[RC_DOWNGRADE_OVERFLOW]]: +// CHECK-NEXT: ud2 +#[unsafe(no_mangle)] +pub fn rc_downgrade(rc: &Rc) { + mem::forget(Rc::downgrade(rc)); +} + +// CHECK-LABEL: rc_upgrade: +// CHECK: mov rax, qword ptr [rdi] +// CHECK-NEXT: cmp rax, -1 +// CHECK-NEXT: je [[RC_UPGRADE_RET:\..+]] +// CHECK-NEXT: mov rcx, qword ptr [rax] +// CHECK-NEXT: test rcx, rcx +// CHECK-NEXT: je [[RC_UPGRADE_RET]] +// CHECK-NEXT: inc rcx +// CHECK-NEXT: mov qword ptr [rax], rcx +// CHECK-NEXT: je [[RC_UPGRADE_OVERFLOW:\..+]] +// CHECK-NEXT: [[RC_UPGRADE_RET]]: +// CHECK-NEXT: ret +// CHECK-NEXT: [[RC_UPGRADE_OVERFLOW]]: +// CHECK-NEXT: ud2 +#[unsafe(no_mangle)] +pub fn rc_upgrade(weak: &RcWeak) { + mem::forget(weak.upgrade()); +} + +// CHECK-LABEL: arc_new: +// CHECK-DAG: mov edi, 24 +// CHECK-DAG: mov esi, 8 +// CHECK-NEXT: call qword ptr {{.*}}__rust_alloc +// CHECK-NEXT: test rax, rax +// CHECK-NEXT: je [[ARC_NEW_ALLOC_FAIL:\..+]] +// CHECK-DAG: mov qword ptr [rax], 1 +// CHECK-DAG: mov qword ptr [rax + 8], 1 +// CHECK-DAG: mov qword ptr [rax + 16], rbx +// CHECK-DAG: pop rbx +// CHECK: ret +// CHECK-NEXT: [[ARC_NEW_ALLOC_FAIL]]: +// CHECK: mov edi, [[#N:]] +// CHECK-NEXT: mov esi, [[#32-N]] +// CHECK-NEXT: call qword ptr {{.*}}handle_alloc_error +#[unsafe(no_mangle)] +pub fn arc_new(x: usize) -> Arc { + Arc::new(x) +} + +// CHECK-LABEL: arc_deref: +// CHECK: mov rax, qword ptr [rdi] +// CHECK-NEXT: add rax, 16 +// CHECK-NEXT: ret +#[unsafe(no_mangle)] +pub fn arc_deref(arc: &Arc) -> &usize { + arc +} + +// CHECK-LABEL: arc_increment: +// CHECK: mov rax, qword ptr [rdi] +// CHECK-NEXT: lock inc qword ptr [rax] +// CHECK-NEXT: jle [[ARC_INCREMENT_OVERFLOW:\..+]] +// CHECK-NEXT: ret +// CHECK-NEXT: [[ARC_INCREMENT_OVERFLOW]]: +// CHECK-NEXT: ud2 +#[unsafe(no_mangle)] +pub fn arc_increment(arc: &Arc) { + mem::forget(Arc::clone(arc)); +} + +// CHECK-LABEL: arc_decrement: +// CHECK: push rax +// CHECK: mov qword ptr [rsp], rdi +// CHECK-NEXT: lock dec qword ptr [rdi] +// CHECK-NEXT: jne [[ARC_DECREMENT_RET:\..+]] +// CHECK-NEXT: #MEMBARRIER +// CHECK: mov rdi, rsp +// CHECK-NEXT: call qword ptr {{.*}}drop_slow +// CHECK-NEXT: [[ARC_DECREMENT_RET]]: +// CHECK-NEXT: pop rax +// CHECK: ret +#[unsafe(no_mangle)] +pub fn arc_decrement(arc: Arc) { + drop(arc); +} + +// CHECK-LABEL: arc_downgrade: +// CHECK: push rax +// CHECK: mov rcx, qword ptr [rdi] +// CHECK-NEXT: jmp [[ARC_DOWNGRADE_LOAD_WEAK:\..+]] +// CHECK: [[ARC_DOWNGRADE_PAUSE:\..+]]: +// CHECK-NEXT: pause +// CHECK-NEXT: [[ARC_DOWNGRADE_LOAD_WEAK]]: +// CHECK-NEXT: mov rax, qword ptr [rcx + 8] +// CHECK: [[ARC_DOWNGRADE_RETRY:\..+]]: +// CHECK-NEXT: cmp rax, -1 +// CHECK-NEXT: je [[ARC_DOWNGRADE_PAUSE]] +// CHECK-NEXT: test rax, rax +// CHECK-NEXT: js [[ARC_DOWNGRADE_OVERFLOW:\..+]] +// CHECK-NEXT: lea rdx, [rax + 1] +// CHECK-NEXT: lock cmpxchg qword ptr [rcx + 8], rdx +// CHECK-NEXT: jne [[ARC_DOWNGRADE_RETRY]] +// CHECK: pop rax +// CHECK: ret +// CHECK: [[ARC_DOWNGRADE_OVERFLOW]]: +// CHECK: lea rdi, {{.*}}] +// CHECK-NEXT: call qword ptr {{.*}}panic_arc_overflow +#[unsafe(no_mangle)] +pub fn arc_downgrade(arc: &Arc) { + mem::forget(Arc::downgrade(arc)); +} + +// CHECK-LABEL: arc_upgrade: +// CHECK: push rax +// CHECK: mov rcx, qword ptr [rdi] +// CHECK-NEXT: cmp rcx, -1 +// CHECK-NEXT: je [[ARC_UPGRADE_RET:\..+]] +// CHECK-NEXT: mov rax, qword ptr [rcx] +// CHECK: [[ARC_UPGRADE_RETRY:\..+]]: +// CHECK-NEXT: test rax, rax +// CHECK-NEXT: je [[ARC_UPGRADE_RET]] +// CHECK-NEXT: js [[ARC_UPGRADE_OVERFLOW:\..+]] +// CHECK-NEXT: lea rdx, [rax + 1] +// CHECK-NEXT: lock cmpxchg qword ptr [rcx], rdx +// CHECK-NEXT: jne [[ARC_UPGRADE_RETRY]] +// CHECK-NEXT: [[ARC_UPGRADE_RET]]: +// CHECK-NEXT: pop rax +// CHECK: ret +// CHECK: [[ARC_UPGRADE_OVERFLOW]]: +// CHECK: lea rdi, {{.*}}] +// CHECK-NEXT: call qword ptr {{.*}}panic_arc_overflow +#[unsafe(no_mangle)] +pub fn arc_upgrade(weak: &ArcWeak) { + mem::forget(weak.upgrade()); +} diff --git a/tests/codegen-llvm/lib-optimizations/rc-arc-optimizations.rs b/tests/codegen-llvm/lib-optimizations/rc-arc-optimizations.rs new file mode 100644 index 0000000000000..a544ed99077a4 --- /dev/null +++ b/tests/codegen-llvm/lib-optimizations/rc-arc-optimizations.rs @@ -0,0 +1,49 @@ +//@ compile-flags: -O -Z merge-functions=disabled + +#![crate_type = "lib"] + +use std::rc::{self, Rc}; +use std::sync::{self, Arc}; + +// Ensures that we can create an array of `Weak`s using `memset`. + +#[no_mangle] +pub fn array_of_rc_weak() -> [rc::Weak; 100] { + // CHECK-LABEL: @array_of_rc_weak( + // CHECK-NEXT: start: + // CHECK-NEXT: call void @llvm.memset. + // CHECK-NEXT: ret void + [(); 100].map(|()| rc::Weak::new()) +} + +#[no_mangle] +pub fn array_of_sync_weak() -> [sync::Weak; 100] { + // CHECK-LABEL: @array_of_sync_weak( + // CHECK-NEXT: start: + // CHECK-NEXT: call void @llvm.memset. + // CHECK-NEXT: ret void + [(); 100].map(|()| sync::Weak::new()) +} + +// Asserts that converting from `&Option>` and `&Option>` to `Option<&T>` required +// checking for `None`. + +#[no_mangle] +pub fn option_rc_as_deref_using_cmp(rc: &Option>) -> Option<&u32> { + // CHECK-LABEL: @option_rc_as_deref_using_cmp(ptr + // CHECK-NEXT: start: + // CHECK-NEXT: load ptr, ptr + // CHECK-NEXT: icmp + // CHECK: ret ptr + rc.as_deref() +} + +#[no_mangle] +pub fn option_arc_as_deref_using_cmp(arc: &Option>) -> Option<&u32> { + // CHECK-LABEL: @option_arc_as_deref_using_cmp(ptr + // CHECK-NEXT: start: + // CHECK-NEXT: load ptr, ptr + // CHECK-NEXT: icmp + // CHECK: ret ptr + arc.as_deref() +} From 1ddda918b444eb80f00e9d6b24a8d7c8a0cf3320 Mon Sep 17 00:00:00 2001 From: Amirhossein Akhlaghpour Date: Wed, 28 Oct 2026 12:35:43 +0330 Subject: [PATCH 12/18] fix RegionEq direction in canonical query responses Signed-off-by: Amirhossein Akhlaghpour --- .../src/infer/canonical/query_response.rs | 2 +- .../rustc_type_ir/src/search_graph/mod.rs | 5 ++ ...-auto-trait-impl-recursion-162850-small.rs | 49 +++++++++++++++++++ 3 files changed, 55 insertions(+), 1 deletion(-) create mode 100644 tests/ui/traits/next-solver/manual-auto-trait-impl-recursion-162850-small.rs diff --git a/compiler/rustc_infer/src/infer/canonical/query_response.rs b/compiler/rustc_infer/src/infer/canonical/query_response.rs index a0c8eb22a8273..cd4892ab633b5 100644 --- a/compiler/rustc_infer/src/infer/canonical/query_response.rs +++ b/compiler/rustc_infer/src/infer/canonical/query_response.rs @@ -642,7 +642,7 @@ pub fn make_query_region_constraints<'tcx>( } ConstraintKind::VarEqVar | ConstraintKind::VarEqReg | ConstraintKind::RegEqReg => { - let constraint = ty::RegionEqPredicate(c.sup, c.sub).into(); + let constraint = ty::RegionEqPredicate(c.sub, c.sup).into(); QueryRegionConstraint { constraint, category: origin.to_constraint_category(), diff --git a/compiler/rustc_type_ir/src/search_graph/mod.rs b/compiler/rustc_type_ir/src/search_graph/mod.rs index e427cdcdc8acb..ee24e6a7a7343 100644 --- a/compiler/rustc_type_ir/src/search_graph/mod.rs +++ b/compiler/rustc_type_ir/src/search_graph/mod.rs @@ -1399,6 +1399,11 @@ impl, X: Cx> SearchGraph { // See tests/ui/traits/next-solver/cycles/fixpoint-rerun-all-cycle-heads.rs // for an example. // + // FIXME: We should assert that region constraints match when both results + // have certainty `Yes` but the weakened leak check means there + // may be additional constraints involving leaked placeholders. + // See `tests/ui/traits/next-solver/cycles/leak-check-coinductive-cycle.rs`. + // // Check whether we reached a fixpoint, either because the final result // is equal to the provisional result of the previous iteration, or because // this was only the head of either coinductive or inductive cycles, and the diff --git a/tests/ui/traits/next-solver/manual-auto-trait-impl-recursion-162850-small.rs b/tests/ui/traits/next-solver/manual-auto-trait-impl-recursion-162850-small.rs new file mode 100644 index 0000000000000..89c7a22d03c27 --- /dev/null +++ b/tests/ui/traits/next-solver/manual-auto-trait-impl-recursion-162850-small.rs @@ -0,0 +1,49 @@ +//@ check-pass +//@ compile-flags: -Znext-solver=globally + +// Keep the `RegionEq` direction consistent when registering and collecting +// region constraints to avoid the overflow in #162850 + +#![allow(unused)] + +struct RawVec(std::marker::PhantomData); + +unsafe impl Send for RawVec {} + +pub struct MyVec(RawVec); + +impl MyVec { + pub fn new() -> Self { + panic!() + } +} + +pub trait IntoParallelIterator { + type Iter; + + fn into_par_iter(self) -> Self::Iter; +} + +impl IntoParallelIterator for MyVec { + type Iter = T; + + fn into_par_iter(self) -> Self::Iter { + todo!() + } +} + +struct Recursive(MyVec>, R); + +trait HasAssoc<'a> { + type Assoc; +} + +fn foo<'a, T>() +where + T: HasAssoc<'a>, + T::Assoc: Send, +{ + _ = MyVec::>::new().into_par_iter(); +} + +fn main() {} From 558c1ec6c56c35a3663046622592cd1b233e9383 Mon Sep 17 00:00:00 2001 From: dianne Date: Thu, 29 Oct 2026 01:50:02 -0700 Subject: [PATCH 13/18] remove unnecessary fast path from borrowck --- compiler/rustc_borrowck/src/dataflow.rs | 10 ---------- compiler/rustc_borrowck/src/places_conflict.rs | 8 ++++++-- 2 files changed, 6 insertions(+), 12 deletions(-) diff --git a/compiler/rustc_borrowck/src/dataflow.rs b/compiler/rustc_borrowck/src/dataflow.rs index 7ac9f489f92a4..a0e462d90cd04 100644 --- a/compiler/rustc_borrowck/src/dataflow.rs +++ b/compiler/rustc_borrowck/src/dataflow.rs @@ -448,16 +448,6 @@ impl<'a, 'tcx> Borrows<'a, 'tcx> { .map(|bs| bs.iter().copied()) .into_flat_iter(); - // If the borrowed place is a local with no projections, all other borrows of this - // local must conflict. This is purely an optimization so we don't have to call - // `places_conflict::borrow_conflicts_with_place` for every borrow. - if place.projection.is_empty() { - if !self.body.local_decls[place.local].is_ref_to_static() { - state.kill_all(other_borrows_of_local); - } - return; - } - // By passing `PlaceConflictBias::NoOverlap`, we conservatively assume that any given // pair of array indices are not equal, so that when `places_conflict` returns true, we // will be assured that two places being compared definitely denotes the same sets of diff --git a/compiler/rustc_borrowck/src/places_conflict.rs b/compiler/rustc_borrowck/src/places_conflict.rs index 6da86c2afd02f..a35965ea9e265 100644 --- a/compiler/rustc_borrowck/src/places_conflict.rs +++ b/compiler/rustc_borrowck/src/places_conflict.rs @@ -223,8 +223,12 @@ fn place_components_conflict<'tcx>( debug!("borrow_conflicts_with_place: shallow access behind ptr"); return false; } - (ProjectionElem::Deref, ty::Ref(_, _, hir::Mutability::Not), _) => { - // Shouldn't be tracked + (ProjectionElem::Deref, ty::Ref(_, _, hir::Mutability::Not), _) + if !(base.projection.is_empty() + && body.local_decls[borrow_local].is_ref_to_thread_local()) => + { + // The only shared borrows we track are from temporaries created as references + // to thread-local statics. See `crate::place_ext::PlaceExt::ignore_borrow`. bug!("Tracking borrow behind shared reference."); } (ProjectionElem::Deref, ty::Ref(_, _, hir::Mutability::Mut), AccessDepth::Drop) => { From 5dbf24c9512596439ae6791470fcee9ca2ccd291 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 29 Oct 2026 09:08:27 +0100 Subject: [PATCH 14/18] use native interpreter impl for funnel shifts intrinsics --- .../src/interpret/intrinsics.rs | 58 ++++++++++++++- .../src/interpret/intrinsics/simd.rs | 70 ++++++------------- library/core/src/intrinsics/fallback.rs | 14 +--- library/core/src/intrinsics/mod.rs | 35 ++++------ .../tests/fail/intrinsics/funnel_shl.stderr | 2 +- .../tests/fail/intrinsics/funnel_shr.stderr | 2 +- .../intrinsics/simd-funnel_shl-too-far.rs | 2 +- .../intrinsics/simd-funnel_shl-too-far.stderr | 2 +- .../intrinsics/simd-funnel_shr-too-far.rs | 2 +- .../intrinsics/simd-funnel_shr-too-far.stderr | 2 +- 10 files changed, 99 insertions(+), 90 deletions(-) diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics.rs b/compiler/rustc_const_eval/src/interpret/intrinsics.rs index 678fc35c07a7c..69a3912427abe 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics.rs @@ -12,9 +12,8 @@ use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_ast::{IntTy, UintTy}; use rustc_middle::mir::interpret::{CTFE_ALLOC_SALT, read_target_uint, write_target_uint}; use rustc_middle::mir::{self, BinOp, ConstValue, NonDivergingIntrinsic}; -use rustc_middle::ty; use rustc_middle::ty::layout::TyAndLayout; -use rustc_middle::ty::{FloatTy, Ty, TyCtxt, TypeVisitableExt}; +use rustc_middle::ty::{self, FloatTy, ScalarInt, Ty, TyCtxt, TypeVisitableExt}; use rustc_span::{Symbol, bug, span_bug, sym}; use tracing::trace; @@ -376,6 +375,17 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { let r = self.read_immediate(&args[1])?; self.exact_div(&l, &r, dest)?; } + sym::unchecked_funnel_shl | sym::unchecked_funnel_shr => { + let shift_left = intrinsic_name == sym::unchecked_funnel_shl; + + let l = self.read_immediate(&args[0])?; + let r = self.read_immediate(&args[1])?; + let shift = self.read_immediate(&args[2])?; + + let result = self.funnel_shift(&l, &r, &shift, shift_left)?; + self.write_scalar(result, dest)?; + } + sym::copy => { self.copy_intrinsic(&args[0], &args[1], &args[2], /*nonoverlapping*/ false)?; } @@ -969,6 +979,50 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { }) } + pub fn funnel_shift( + &self, + left: &ImmTy<'tcx, M::Provenance>, + right: &ImmTy<'tcx, M::Provenance>, + shift_bits: &ImmTy<'tcx, M::Provenance>, + shift_left: bool, + ) -> InterpResult<'tcx, Scalar> { + let size = left.layout.size; + let left = left.to_scalar().to_bits(size)?; + let right = right.to_scalar().to_bits(size)?; + let shift_bits = shift_bits.to_scalar().to_bits(shift_bits.layout.size)?; // can have different size + + if shift_bits >= size.bits().into() { + throw_ub_format!( + "overflowing shift by {shift_bits} in {} funnel shift", + if shift_left { "left" } else { "right" } + ); + } + let inv_shift_bits = u32::try_from(u128::from(size.bits()) - shift_bits).unwrap(); + + // A funnel shift left by S can be implemented as `(x << S) | y.unbounded_shr(SIZE - S)`. + // The `unbounded_shr` is needed because otherwise if `S = 0`, it would be `x | y` + // when it should be `x`. + // + // This selects the least-significant `SIZE - S` bits of `x`, followed by the `S` most + // significant bits of `y`. As `left` and `right` both occupy the lower `SIZE` bits, + // we can treat the lower `SIZE` bits as an integer of the right width and use + // the same implementation, but on a zero-extended `x` and `y`. This works because + // `x << S` just pushes the `SIZE-S` MSBs out, and `y >> (SIZE - S)` shifts in + // zeros, as it is zero-extended. To the lower `SIZE` bits, this looks just like a + // funnel shift left. + // + // Note that the `unbounded_sh{l,r}`s are needed only in case we are using this on + // `u128xN` and `inv_shift_bits == 128`. + let result_bits = if shift_left { + (left << shift_bits) | right.unbounded_shr(inv_shift_bits) + } else { + left.unbounded_shl(inv_shift_bits) | (right >> shift_bits) + }; + + let (result, _overflow) = ScalarInt::truncate_from_uint(result_bits, size); + interp_ok(result.into()) + } + /// Offsets a pointer by some multiple of its type, returning an error if the pointer leaves its /// allocation. pub fn ptr_offset_inbounds( diff --git a/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs b/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs index a31d1ec4e920d..f29f7311d9ff8 100644 --- a/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs +++ b/compiler/rustc_const_eval/src/interpret/intrinsics/simd.rs @@ -3,7 +3,7 @@ use rustc_abi::{BackendRepr, Endian}; use rustc_apfloat::ieee::{Double, Half, Quad, Single}; use rustc_apfloat::{Float, Round}; use rustc_middle::mir::interpret::{InterpErrorKind, Pointer, UndefinedBehaviorInfo}; -use rustc_middle::ty::{FloatTy, ScalarInt, SimdAlign}; +use rustc_middle::ty::{FloatTy, SimdAlign}; use rustc_middle::{err_ub_format, mir, throw_unsup_format, ty}; use rustc_span::{Symbol, bug, span_bug, sym}; use tracing::trace; @@ -758,54 +758,30 @@ impl<'tcx, M: Machine<'tcx>> InterpCx<'tcx, M> { } } sym::simd_funnel_shl | sym::simd_funnel_shr => { - let (left, _) = self.project_to_simd(&args[0])?; - let (right, _) = self.project_to_simd(&args[1])?; - let (shift, _) = self.project_to_simd(&args[2])?; - let (dest, _) = self.project_to_simd(&dest)?; - - let (len, elem_ty) = args[0].layout.ty.simd_size_and_type(*self.tcx); - let (elem_size, _signed) = elem_ty.int_size_and_signed(*self.tcx); - let elem_size_bits = u128::from(elem_size.bits()); - - let is_left = intrinsic_name == sym::simd_funnel_shl; - - for i in 0..len { - let left = - self.read_scalar(&self.project_index(&left, i)?)?.to_bits(elem_size)?; - let right = - self.read_scalar(&self.project_index(&right, i)?)?.to_bits(elem_size)?; - let shift_bits = - self.read_scalar(&self.project_index(&shift, i)?)?.to_bits(elem_size)?; - - if shift_bits >= elem_size_bits { - throw_ub_format!( - "overflowing shift by {shift_bits} in `{intrinsic_name}` in lane {i}" - ); - } - let inv_shift_bits = u32::try_from(elem_size_bits - shift_bits).unwrap(); - - // A funnel shift left by S can be implemented as `(x << S) | y.unbounded_shr(SIZE - S)`. - // The `unbounded_shr` is needed because otherwise if `S = 0`, it would be `x | y` - // when it should be `x`. - // - // This selects the least-significant `SIZE - S` bits of `x`, followed by the `S` most - // significant bits of `y`. As `left` and `right` both occupy the lower `SIZE` bits, - // we can treat the lower `SIZE` bits as an integer of the right width and use - // the same implementation, but on a zero-extended `x` and `y`. This works because - // `x << S` just pushes the `SIZE-S` MSBs out, and `y >> (SIZE - S)` shifts in - // zeros, as it is zero-extended. To the lower `SIZE` bits, this looks just like a - // funnel shift left. - // - // Note that the `unbounded_sh{l,r}`s are needed only in case we are using this on - // `u128xN` and `inv_shift_bits == 128`. - let result_bits = if is_left { - (left << shift_bits) | right.unbounded_shr(inv_shift_bits) - } else { - left.unbounded_shl(inv_shift_bits) | (right >> shift_bits) - }; - let (result, _overflow) = ScalarInt::truncate_from_uint(result_bits, elem_size); + let shift_left = intrinsic_name == sym::simd_funnel_shl; + + let (left, left_len) = self.project_to_simd(&args[0])?; + let (right, right_len) = self.project_to_simd(&args[1])?; + let (shift, shift_len) = self.project_to_simd(&args[2])?; + let (dest, dest_len) = self.project_to_simd(&dest)?; + assert_eq!(dest_len, left_len); + assert_eq!(dest_len, right_len); + assert_eq!(dest_len, shift_len); + + for i in 0..dest_len { + let left = self.read_immediate(&self.project_index(&left, i)?)?; + let right = self.read_immediate(&self.project_index(&right, i)?)?; + let shift_bits = self.read_immediate(&self.project_index(&shift, i)?)?; let dest = self.project_index(&dest, i)?; + + let result = self.funnel_shift(&left, &right, &shift_bits, shift_left) + .map_err_kind(|_err| { + err_ub_format!( + "overflowing shift by {shift_bits} in `{intrinsic_name}` in lane {i}" + ) + })?; + self.write_scalar(result, &dest)?; } } diff --git a/library/core/src/intrinsics/fallback.rs b/library/core/src/intrinsics/fallback.rs index 3e6829ab16b18..c587e22dc4659 100644 --- a/library/core/src/intrinsics/fallback.rs +++ b/library/core/src/intrinsics/fallback.rs @@ -152,8 +152,7 @@ impl_disjoint_bitor! { i8, i16, i32, i64, i128, isize, } -#[rustc_const_unstable(feature = "core_intrinsics_fallbacks", issue = "none")] -pub const trait FunnelShift: Copy + 'static { +pub trait FunnelShift: Copy + 'static { /// We just need the trait indirection to handle different types /// since calling intrinsics with generics doesn't work. /// @@ -175,14 +174,9 @@ pub const trait FunnelShift: Copy + 'static { macro_rules! impl_funnel_shifts { ($($type:ident),*) => {$( - #[rustc_const_unstable(feature = "core_intrinsics_fallbacks", issue = "none")] - const impl FunnelShift for $type { - #[cfg_attr(miri, track_caller)] + impl FunnelShift for $type { #[inline] unsafe fn unchecked_funnel_shl(self, right: Self, shift: u32) -> Self { - // This implementation is also used by Miri so we have to check the precondition. - // SAFETY: this is guaranteed by the caller - unsafe { super::assume(shift < $type::BITS) }; if shift == 0 { self } else { @@ -202,12 +196,8 @@ macro_rules! impl_funnel_shifts { } } - #[cfg_attr(miri, track_caller)] #[inline] unsafe fn unchecked_funnel_shr(self, right: Self, shift: u32) -> Self { - // This implementation is also used by Miri so we have to check the precondition. - // SAFETY: this is guaranteed by the caller - unsafe { super::assume(shift < $type::BITS) }; if shift == 0 { right } else { diff --git a/library/core/src/intrinsics/mod.rs b/library/core/src/intrinsics/mod.rs index 64cf978a4b0e4..f3eb6d1d1289f 100644 --- a/library/core/src/intrinsics/mod.rs +++ b/library/core/src/intrinsics/mod.rs @@ -2122,8 +2122,9 @@ pub const unsafe fn unchecked_mul(x: T, y: T) -> T; #[rustc_nounwind] #[rustc_intrinsic] #[rustc_allow_const_fn_unstable(const_trait_impl)] +#[cfg_attr(miri, track_caller)] #[miri::intrinsic_fallback_is_spec] -pub const fn rotate_left(x: T, shift: u32) -> T { +pub const fn rotate_left(x: T, shift: u32) -> T { // Make sure to call the intrinsic for `funnel_shl`, not the fallback impl. // SAFETY: we modulo `shift` so that the result is definitely less than the size of // `T` in bits. @@ -2144,8 +2145,9 @@ pub const fn rotate_left(x: T, shift: u32) -> #[rustc_nounwind] #[rustc_intrinsic] #[rustc_allow_const_fn_unstable(const_trait_impl)] +#[cfg_attr(miri, track_caller)] #[miri::intrinsic_fallback_is_spec] -pub const fn rotate_right(x: T, shift: u32) -> T { +pub const fn rotate_right(x: T, shift: u32) -> T { // Make sure to call the intrinsic for `funnel_shr`, not the fallback impl. // SAFETY: we modulo `shift` so that the result is definitely less than the size of // `T` in bits. @@ -2239,17 +2241,11 @@ pub const fn saturating_sub(a: T, b: T) -> T; /// /// Safe versions of this intrinsic are available on the integer primitives /// via the `funnel_shl` method. For example, [`u32::funnel_shl`]. -#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] -#[track_caller] -#[rustc_allow_const_fn_unstable(const_trait_impl, core_intrinsics_fallbacks)] -#[miri::intrinsic_fallback_is_spec] -pub const unsafe fn unchecked_funnel_shl( - a: T, - b: T, - shift: u32, -) -> T { +#[rustc_intrinsic_const_stable_indirect] +#[rustc_do_not_const_check] // Use built-in impl to avoid const-checks in the fallback body. +pub const unsafe fn unchecked_funnel_shl(a: T, b: T, shift: u32) -> T { // SAFETY: caller ensures that `shift` is in-range unsafe { a.unchecked_funnel_shl(b, shift) } } @@ -2267,17 +2263,11 @@ pub const unsafe fn unchecked_funnel_shl( /// /// Safer versions of this intrinsic are available on the integer primitives /// via the `funnel_shr` method. For example, [`u32::funnel_shr`] -#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] #[rustc_nounwind] -#[track_caller] -#[rustc_allow_const_fn_unstable(const_trait_impl, core_intrinsics_fallbacks)] -#[miri::intrinsic_fallback_is_spec] -pub const unsafe fn unchecked_funnel_shr( - a: T, - b: T, - shift: u32, -) -> T { +#[rustc_intrinsic_const_stable_indirect] +#[rustc_do_not_const_check] // Ise built-in impl to avoid const-checks in the fallback body. +pub const unsafe fn unchecked_funnel_shr(a: T, b: T, shift: u32) -> T { // SAFETY: caller ensures that `shift` is in-range unsafe { a.unchecked_funnel_shr(b, shift) } } @@ -3489,11 +3479,10 @@ pub const fn maximumf128(x: f128, y: f128) -> f128 { /// The stabilized versions of this intrinsic are available on the float /// primitives via the `abs` method. For example, [`f32::abs`]. #[rustc_nounwind] -#[rustc_const_unstable(feature = "core_intrinsics", issue = "none")] -#[rustc_intrinsic_const_stable_indirect] #[rustc_intrinsic] +#[rustc_intrinsic_const_stable_indirect] +#[rustc_do_not_const_check] // Use built-in impl to avoid const-checks in the fallback body. #[miri::intrinsic_fallback_is_spec] -#[rustc_do_not_const_check] // use built-in impl to avoid const-checks in the fallback body. pub const fn fabs(x: T) -> T { T::from_bits(x.to_bits() & !T::SIGN_MASK) } diff --git a/src/tools/miri/tests/fail/intrinsics/funnel_shl.stderr b/src/tools/miri/tests/fail/intrinsics/funnel_shl.stderr index 900203d1b9b35..2d79a0793a250 100644 --- a/src/tools/miri/tests/fail/intrinsics/funnel_shl.stderr +++ b/src/tools/miri/tests/fail/intrinsics/funnel_shl.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: `assume` called with `false` +error: Undefined Behavior: overflowing shift by 32 in left funnel shift --> tests/fail/intrinsics/funnel_shl.rs:LL:CC | LL | std::intrinsics::unchecked_funnel_shl(1_u32, 2, 32); diff --git a/src/tools/miri/tests/fail/intrinsics/funnel_shr.stderr b/src/tools/miri/tests/fail/intrinsics/funnel_shr.stderr index 2b2e85f9f9b71..53b31952cd95e 100644 --- a/src/tools/miri/tests/fail/intrinsics/funnel_shr.stderr +++ b/src/tools/miri/tests/fail/intrinsics/funnel_shr.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: `assume` called with `false` +error: Undefined Behavior: overflowing shift by 32 in right funnel shift --> tests/fail/intrinsics/funnel_shr.rs:LL:CC | LL | std::intrinsics::unchecked_funnel_shr(1_u32, 2, 32); diff --git a/src/tools/miri/tests/fail/intrinsics/simd-funnel_shl-too-far.rs b/src/tools/miri/tests/fail/intrinsics/simd-funnel_shl-too-far.rs index 54cecc23f9e71..311e8af6a49de 100644 --- a/src/tools/miri/tests/fail/intrinsics/simd-funnel_shl-too-far.rs +++ b/src/tools/miri/tests/fail/intrinsics/simd-funnel_shl-too-far.rs @@ -7,6 +7,6 @@ fn main() { unsafe { let x = i32x2::from_array([1, 1]); let y = i32x2::from_array([100, 0]); - simd_funnel_shl(x, x, y); //~ERROR: overflowing shift by 100 in `simd_funnel_shl` in lane 0 + simd_funnel_shl(x, x, y); //~ERROR: overflowing shift by 100_i32 in `simd_funnel_shl` in lane 0 } } diff --git a/src/tools/miri/tests/fail/intrinsics/simd-funnel_shl-too-far.stderr b/src/tools/miri/tests/fail/intrinsics/simd-funnel_shl-too-far.stderr index 00c7c39a8856f..fdc06da103d44 100644 --- a/src/tools/miri/tests/fail/intrinsics/simd-funnel_shl-too-far.stderr +++ b/src/tools/miri/tests/fail/intrinsics/simd-funnel_shl-too-far.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: overflowing shift by 100 in `simd_funnel_shl` in lane 0 +error: Undefined Behavior: overflowing shift by 100_i32 in `simd_funnel_shl` in lane 0 --> tests/fail/intrinsics/simd-funnel_shl-too-far.rs:LL:CC | LL | simd_funnel_shl(x, x, y); diff --git a/src/tools/miri/tests/fail/intrinsics/simd-funnel_shr-too-far.rs b/src/tools/miri/tests/fail/intrinsics/simd-funnel_shr-too-far.rs index 6fb2daa488484..c9297dac33ac5 100644 --- a/src/tools/miri/tests/fail/intrinsics/simd-funnel_shr-too-far.rs +++ b/src/tools/miri/tests/fail/intrinsics/simd-funnel_shr-too-far.rs @@ -7,6 +7,6 @@ fn main() { unsafe { let x = i32x2::from_array([1, 1]); let y = i32x2::from_array([20, 40]); - simd_funnel_shr(x, x, y); //~ERROR: overflowing shift by 40 in `simd_funnel_shr` in lane 1 + simd_funnel_shr(x, x, y); //~ERROR: overflowing shift by 40_i32 in `simd_funnel_shr` in lane 1 } } diff --git a/src/tools/miri/tests/fail/intrinsics/simd-funnel_shr-too-far.stderr b/src/tools/miri/tests/fail/intrinsics/simd-funnel_shr-too-far.stderr index 2f6c6cd71ea6d..9d3263c655f41 100644 --- a/src/tools/miri/tests/fail/intrinsics/simd-funnel_shr-too-far.stderr +++ b/src/tools/miri/tests/fail/intrinsics/simd-funnel_shr-too-far.stderr @@ -1,4 +1,4 @@ -error: Undefined Behavior: overflowing shift by 40 in `simd_funnel_shr` in lane 1 +error: Undefined Behavior: overflowing shift by 40_i32 in `simd_funnel_shr` in lane 1 --> tests/fail/intrinsics/simd-funnel_shr-too-far.rs:LL:CC | LL | simd_funnel_shr(x, x, y); From 2b154bd719f22467bbde29b4230f52d5daf4a9d0 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Thu, 29 Oct 2026 11:56:17 +0100 Subject: [PATCH 15/18] fix MaybeDangling validity logic for ZST at usize::MAX --- compiler/rustc_const_eval/src/interpret/validity.rs | 5 +++-- .../miri/tests/pass/both_borrows/maybe_dangling.rs | 12 ++++++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_const_eval/src/interpret/validity.rs b/compiler/rustc_const_eval/src/interpret/validity.rs index edfd8b9488e74..3b6424819a1da 100644 --- a/compiler/rustc_const_eval/src/interpret/validity.rs +++ b/compiler/rustc_const_eval/src/interpret/validity.rs @@ -655,9 +655,10 @@ impl<'rt, 'tcx, M: Machine<'tcx>> ValidityVisitor<'rt, 'tcx, M> { // Try to compute the end address. Cannot use `Size` addition as that also applies // the "max obj size" bound. let addr = Size::from_bytes(addr.to_target_usize(*self.ecx.tcx)).bytes(); - if addr + // addr + size must fit into usize, i.e., `sum <= usize::MAX`. + if !addr .checked_add(size.bytes()) - .is_none_or(|result| result >= self.ecx.target_usize_max()) + .is_some_and(|result| result <= self.ecx.target_usize_max()) { throw_validation_failure!( self.path, diff --git a/src/tools/miri/tests/pass/both_borrows/maybe_dangling.rs b/src/tools/miri/tests/pass/both_borrows/maybe_dangling.rs index 028dcef8fa2d3..1aa12d9a97e80 100644 --- a/src/tools/miri/tests/pass/both_borrows/maybe_dangling.rs +++ b/src/tools/miri/tests/pass/both_borrows/maybe_dangling.rs @@ -7,20 +7,21 @@ #![feature(maybe_dangling)] use std::mem::{self, MaybeDangling}; -use std::ptr::drop_in_place; +use std::ptr; fn main() { boxy(); reference(); write_through_shared_ref(); large(); + zst_at_the_end(); } fn boxy() { let mut x = MaybeDangling::new(Box::new(1)); // make the box dangle - unsafe { drop_in_place(x.as_mut()) }; + unsafe { ptr::drop_in_place(x.as_mut()) }; // move the dangling box (without `MaybeDangling` this causes UB) let x: MaybeDangling> = x; @@ -64,3 +65,10 @@ fn large() { // Used to be rejected due to faulty logic for the "does this fit the address space" check. let _x: MaybeDangling<&i8> = unsafe { mem::transmute(usize::MAX - 127) }; } + +fn zst_at_the_end() { + // usize::MAX is valid for ZST. + let ptr: *const () = ptr::without_provenance::<()>(usize::MAX); + let ref_ = unsafe { &*ptr }; + let _x = MaybeDangling::new(ref_); +} From ae72ce3c6759daae7647f6ce4484457e7fb60130 Mon Sep 17 00:00:00 2001 From: Web4everyone32 Date: Thu, 29 Oct 2026 11:33:51 +0000 Subject: [PATCH 16/18] use adt_async_drop_tys for nested ADTs in needs_async_drop --- compiler/rustc_ty_utils/src/needs_drop.rs | 24 +- tests/crashes/142155.rs | 12 - ...utine.main-{closure#0}.StateTransform.diff | 113 +++++----- ...utine.main-{closure#1}.StateTransform.diff | 113 +++++----- ...d_in_vec.build-{closure#0}.built.after.mir | 213 ++++++------------ ...ncelled-future-drops-sync-fields-164901.rs | 56 +++++ ...op_order-on-async-block-with-drop-field.rs | 15 ++ 7 files changed, 263 insertions(+), 283 deletions(-) delete mode 100644 tests/crashes/142155.rs create mode 100644 tests/ui/async-await/async-drop/cancelled-future-drops-sync-fields-164901.rs create mode 100644 tests/ui/drop/tail_expr_drop_order-on-async-block-with-drop-field.rs diff --git a/compiler/rustc_ty_utils/src/needs_drop.rs b/compiler/rustc_ty_utils/src/needs_drop.rs index 094cf5aec0bd1..99aa75fbb98f5 100644 --- a/compiler/rustc_ty_utils/src/needs_drop.rs +++ b/compiler/rustc_ty_utils/src/needs_drop.rs @@ -52,7 +52,7 @@ fn needs_async_drop_raw<'tcx>( query.value, query.typing_env, adt_has_async_dtor, - DropTysOptions::default().recurse_into_box_for_async_drop(), + DropTysOptions::default().async_drop(), ) .filter(filter_array_elements_async(tcx, query.typing_env)) .next() @@ -335,7 +335,9 @@ enum DtorType { struct DropTysOptions { only_significant: bool, exhaustive: bool, - async_drop_recurses_into_box: bool, + /// Compute async drop components: query `adt_async_drop_tys` for nested + /// ADTs and recurse into `Box`. + async_drop: bool, } impl DropTysOptions { @@ -349,8 +351,8 @@ impl DropTysOptions { self } - fn recurse_into_box_for_async_drop(mut self) -> Self { - self.async_drop_recurses_into_box = true; + fn async_drop(mut self) -> Self { + self.async_drop = true; self } } @@ -369,11 +371,17 @@ fn drop_tys_helper<'tcx>( fn with_query_cache<'tcx>( tcx: TyCtxt<'tcx>, iter: impl IntoIterator>, + async_drop: bool, ) -> NeedsDropResult>> { iter.into_iter().try_fold(Vec::new(), |mut vec, subty| { match subty.kind() { ty::Adt(adt_id, args) => { - for subty in tcx.adt_drop_tys(adt_id.did())? { + let adt_tys = if async_drop { + tcx.adt_async_drop_tys(adt_id.did())? + } else { + tcx.adt_drop_tys(adt_id.did())? + }; + for subty in adt_tys { vec.push( EarlyBinder::bind(tcx, subty).instantiate(tcx, args).skip_norm_wip(), ); @@ -389,7 +397,7 @@ fn drop_tys_helper<'tcx>( if adt_def.is_manually_drop() { debug!("drop_tys_helper: `{:?}` is manually drop", adt_def); Ok(Vec::new()) - } else if options.async_drop_recurses_into_box && adt_def.is_box() { + } else if options.async_drop && adt_def.is_box() { let box_components = match args.as_slice() { [boxed_ty, allocator_ty] => { let boxed_ty = boxed_ty.expect_ty(); @@ -442,7 +450,7 @@ fn drop_tys_helper<'tcx>( // ADTs are `needs_drop` exactly if they `impl Drop` or if any of their "transitive" // fields do. There can be no cycles here, because ADTs cannot contain themselves as // fields. - with_query_cache(tcx, field_tys) + with_query_cache(tcx, field_tys, options.async_drop) } } .map(|v| v.into_iter()) @@ -506,7 +514,7 @@ fn adt_async_drop_tys<'tcx>( tcx.type_of(def_id).instantiate_identity().skip_norm_wip(), ty::TypingEnv::non_body_analysis(tcx, def_id), adt_has_dtor, - DropTysOptions::default().recurse_into_box_for_async_drop(), + DropTysOptions::default().async_drop(), ) .collect::, _>>() .map(|components| tcx.mk_type_list(&components)) diff --git a/tests/crashes/142155.rs b/tests/crashes/142155.rs deleted file mode 100644 index 8c0769bf2b586..0000000000000 --- a/tests/crashes/142155.rs +++ /dev/null @@ -1,12 +0,0 @@ -//@ known-bug: #142155 -//@ needs-rustc-debug-assertions -//@ edition: 2021 - -#![warn(tail_expr_drop_order)] -use core::future::Future; - -fn f() -> impl Future> { - async { Some("nope".into()) } -} - -fn main() {} diff --git a/tests/mir-opt/coroutine/coroutine.main-{closure#0}.StateTransform.diff b/tests/mir-opt/coroutine/coroutine.main-{closure#0}.StateTransform.diff index d9d65147e1e83..70d5034fc50e0 100644 --- a/tests/mir-opt/coroutine/coroutine.main-{closure#0}.StateTransform.diff +++ b/tests/mir-opt/coroutine/coroutine.main-{closure#0}.StateTransform.diff @@ -44,7 +44,7 @@ - StorageLive(_5); - StorageLive(_6); - _6 = &_2; -- _5 = ::clone(move _6) -> [return: bb1, unwind: bb31]; +- _5 = ::clone(move _6) -> [return: bb1, unwind: bb29]; + _18 = copy (_1.0: &mut {coroutine@$DIR/coroutine.rs:19:5: 19:18}); + _17 = discriminant((*_18)); + switchInt(move _17) -> [0: bb35, 1: bb33, 2: bb32, 3: bb30, 4: bb31, otherwise: bb34]; @@ -53,7 +53,7 @@ bb1: { StorageDead(_6); StorageLive(_7); -- _7 = Location::<'_>::caller() -> [return: bb2, unwind: bb30]; +- _7 = Location::<'_>::caller() -> [return: bb2, unwind: bb28]; + _7 = Location::<'_>::caller() -> [return: bb2, unwind: bb21]; } @@ -65,7 +65,7 @@ bb3: { StorageDead(_5); -- _3 = yield(move _4) -> [resume: bb4, drop: bb18]; +- _3 = yield(move _4) -> [resume: bb4, drop: bb17]; + _0 = CoroutineState::<(&str, String, &Location<'_>), ()>::Yielded(move _4); + StorageDead(_3); + StorageDead(_4); @@ -79,7 +79,7 @@ bb5: { StorageDead(_4); -- drop(_3) -> [return: bb6, unwind: bb34]; +- drop(_3) -> [return: bb6, unwind: bb32]; + drop(_3) -> [return: bb6, unwind: bb25]; } @@ -94,7 +94,7 @@ StorageLive(_12); StorageLive(_13); - _13 = &_2; -- _12 = ::clone(move _13) -> [return: bb7, unwind: bb28]; +- _12 = ::clone(move _13) -> [return: bb7, unwind: bb26]; + _13 = &(((*_18) as variant#4).0: std::string::String); + _12 = ::clone(move _13) -> [return: bb7, unwind: bb19]; } @@ -103,7 +103,7 @@ StorageDead(_13); StorageLive(_14); StorageLive(_15); -- _15 = Location::<'_>::caller() -> [return: bb8, unwind: bb24]; +- _15 = Location::<'_>::caller() -> [return: bb8, unwind: bb22]; + _15 = Location::<'_>::caller() -> [return: bb8, unwind: bb15]; } @@ -133,7 +133,7 @@ bb11: { StorageDead(_9); -- drop(_8) -> [return: bb12, unwind: bb27]; +- drop(_8) -> [return: bb12, unwind: bb25]; + drop(_8) -> [return: bb12, unwind: bb18]; } @@ -142,13 +142,13 @@ StorageDead(_11); StorageDead(_8); - _0 = const (); -- drop(_2) -> [return: bb13, unwind: bb36]; +- drop(_2) -> [return: bb13, unwind: bb34]; + _16 = const (); + drop((((*_18) as variant#4).0: std::string::String)) -> [return: bb13, unwind: bb27]; } bb13: { -- drop(_1) -> [return: bb14, unwind: bb37]; +- drop(_1) -> [return: bb14, unwind: bb35]; + goto -> bb14; } @@ -167,23 +167,25 @@ - bb16: { - StorageDead(_9); +- StorageDead(_15); +- StorageDead(_11); +- StorageDead(_8); +- goto -> bb19; + bb16 (cleanup): { + StorageDead(_12); + StorageDead(_10); - goto -> bb17; ++ goto -> bb17; } - bb17: { -- StorageDead(_15); -- StorageDead(_11); -- StorageDead(_8); -- goto -> bb21; + bb17 (cleanup): { + StorageDead(_9); -+ goto -> bb18; + goto -> bb18; } - bb18: { +- StorageDead(_4); +- StorageDead(_3); - goto -> bb19; + bb18 (cleanup): { + StorageDead(_15); @@ -191,18 +193,17 @@ } - bb19: { -- StorageDead(_4); +- drop(_2) -> [return: bb20, unwind: bb36]; + bb19 (cleanup): { + StorageDead(_13); + StorageDead(_12); + StorageDead(_10); + StorageDead(_9); - goto -> bb20; ++ goto -> bb20; } - bb20: { -- StorageDead(_3); -- goto -> bb21; +- drop(_1) -> [return: bb21, unwind: bb35]; + bb20 (cleanup): { + StorageDead(_11); + StorageDead(_8); @@ -210,71 +211,71 @@ } - bb21: { -- drop(_2) -> [return: bb22, unwind: bb38]; +- coroutine_drop; + bb21 (cleanup): { + StorageDead(_7); + drop(_5) -> [return: bb23, unwind terminate(cleanup)]; } -- bb22: { -- drop(_1) -> [return: bb23, unwind: bb37]; -+ bb22 (cleanup): { + bb22 (cleanup): { +- StorageDead(_14); +- drop(_12) -> [return: bb23, unwind terminate(cleanup)]; + StorageDead(_6); + goto -> bb23; } -- bb23: { -- coroutine_drop; -+ bb23 (cleanup): { + bb23 (cleanup): { +- StorageDead(_12); +- StorageDead(_10); + StorageDead(_5); -+ goto -> bb24; + goto -> bb24; } bb24 (cleanup): { -- StorageDead(_14); -- drop(_12) -> [return: bb25, unwind terminate(cleanup)]; +- StorageDead(_9); + StorageDead(_4); -+ goto -> bb25; + goto -> bb25; } bb25 (cleanup): { -- StorageDead(_12); -- StorageDead(_10); +- StorageDead(_15); +- goto -> bb27; + StorageDead(_3); - goto -> bb26; ++ goto -> bb26; } bb26 (cleanup): { +- StorageDead(_13); +- StorageDead(_12); +- StorageDead(_10); - StorageDead(_9); - goto -> bb27; + drop((((*_18) as variant#4).0: std::string::String)) -> [return: bb27, unwind terminate(cleanup)]; } bb27 (cleanup): { -- StorageDead(_15); -- goto -> bb29; +- StorageDead(_11); +- StorageDead(_8); +- goto -> bb33; + goto -> bb28; } bb28 (cleanup): { -- StorageDead(_13); -- StorageDead(_12); -- StorageDead(_10); -- StorageDead(_9); - goto -> bb29; +- StorageDead(_7); +- drop(_5) -> [return: bb30, unwind terminate(cleanup)]; ++ goto -> bb29; } bb29 (cleanup): { -- StorageDead(_11); -- StorageDead(_8); -- goto -> bb35; +- StorageDead(_6); +- goto -> bb30; + discriminant((*_18)) = 2; + resume; } - bb30 (cleanup): { -- StorageDead(_7); -- drop(_5) -> [return: bb32, unwind terminate(cleanup)]; +- StorageDead(_5); +- goto -> bb31; + bb30: { + StorageLive(_3); + StorageLive(_4); @@ -283,7 +284,7 @@ } - bb31 (cleanup): { -- StorageDead(_6); +- StorageDead(_4); - goto -> bb32; + bb31: { + StorageLive(_8); @@ -295,40 +296,30 @@ } - bb32 (cleanup): { -- StorageDead(_5); +- StorageDead(_3); - goto -> bb33; + bb32: { + assert(const false, "coroutine resumed after panicking") -> [success: bb32, unwind continue]; } - bb33 (cleanup): { -- StorageDead(_4); -- goto -> bb34; +- drop(_2) -> [return: bb34, unwind terminate(cleanup)]; + bb33: { + assert(const false, "coroutine resumed after completion") -> [success: bb33, unwind continue]; } - bb34 (cleanup): { -- StorageDead(_3); -- goto -> bb35; +- drop(_1) -> [return: bb35, unwind terminate(cleanup)]; + bb34: { + unreachable; } - bb35 (cleanup): { -- drop(_2) -> [return: bb36, unwind terminate(cleanup)]; -- } -- -- bb36 (cleanup): { -- drop(_1) -> [return: bb37, unwind terminate(cleanup)]; -- } -- -- bb37 (cleanup): { - resume; - } - -- bb38 (cleanup): { -- drop(_1) -> [return: bb37, unwind terminate(cleanup)]; +- bb36 (cleanup): { +- drop(_1) -> [return: bb35, unwind terminate(cleanup)]; + bb35: { + (((*_18) as variant#4).0: std::string::String) = move _2; + StorageLive(_3); diff --git a/tests/mir-opt/coroutine/coroutine.main-{closure#1}.StateTransform.diff b/tests/mir-opt/coroutine/coroutine.main-{closure#1}.StateTransform.diff index d25c2f61b722a..25b60ef5698ff 100644 --- a/tests/mir-opt/coroutine/coroutine.main-{closure#1}.StateTransform.diff +++ b/tests/mir-opt/coroutine/coroutine.main-{closure#1}.StateTransform.diff @@ -44,7 +44,7 @@ - StorageLive(_5); - StorageLive(_6); - _6 = &_2; -- _5 = ::clone(move _6) -> [return: bb1, unwind: bb31]; +- _5 = ::clone(move _6) -> [return: bb1, unwind: bb29]; + _18 = copy (_1.0: &mut {coroutine@$DIR/coroutine.rs:26:5: 26:18}); + _17 = discriminant((*_18)); + switchInt(move _17) -> [0: bb35, 1: bb33, 2: bb32, 3: bb30, 4: bb31, otherwise: bb34]; @@ -53,7 +53,7 @@ bb1: { StorageDead(_6); StorageLive(_7); -- _7 = Location::<'_>::caller() -> [return: bb2, unwind: bb30]; +- _7 = Location::<'_>::caller() -> [return: bb2, unwind: bb28]; + _7 = Location::<'_>::caller() -> [return: bb2, unwind: bb21]; } @@ -65,7 +65,7 @@ bb3: { StorageDead(_5); -- _3 = yield(move _4) -> [resume: bb4, drop: bb18]; +- _3 = yield(move _4) -> [resume: bb4, drop: bb17]; + _0 = CoroutineState::<(&str, String, &Location<'_>), ()>::Yielded(move _4); + StorageDead(_3); + StorageDead(_4); @@ -79,7 +79,7 @@ bb5: { StorageDead(_4); -- drop(_3) -> [return: bb6, unwind: bb34]; +- drop(_3) -> [return: bb6, unwind: bb32]; + drop(_3) -> [return: bb6, unwind: bb25]; } @@ -94,7 +94,7 @@ StorageLive(_12); StorageLive(_13); - _13 = &_2; -- _12 = ::clone(move _13) -> [return: bb7, unwind: bb28]; +- _12 = ::clone(move _13) -> [return: bb7, unwind: bb26]; + _13 = &(((*_18) as variant#4).0: std::string::String); + _12 = ::clone(move _13) -> [return: bb7, unwind: bb19]; } @@ -103,7 +103,7 @@ StorageDead(_13); StorageLive(_14); StorageLive(_15); -- _15 = Location::<'_>::caller() -> [return: bb8, unwind: bb24]; +- _15 = Location::<'_>::caller() -> [return: bb8, unwind: bb22]; + _15 = Location::<'_>::caller() -> [return: bb8, unwind: bb15]; } @@ -133,7 +133,7 @@ bb11: { StorageDead(_9); -- drop(_8) -> [return: bb12, unwind: bb27]; +- drop(_8) -> [return: bb12, unwind: bb25]; + drop(_8) -> [return: bb12, unwind: bb18]; } @@ -142,13 +142,13 @@ StorageDead(_11); StorageDead(_8); - _0 = const (); -- drop(_2) -> [return: bb13, unwind: bb36]; +- drop(_2) -> [return: bb13, unwind: bb34]; + _16 = const (); + drop((((*_18) as variant#4).0: std::string::String)) -> [return: bb13, unwind: bb27]; } bb13: { -- drop(_1) -> [return: bb14, unwind: bb37]; +- drop(_1) -> [return: bb14, unwind: bb35]; + goto -> bb14; } @@ -167,23 +167,25 @@ - bb16: { - StorageDead(_9); +- StorageDead(_15); +- StorageDead(_11); +- StorageDead(_8); +- goto -> bb19; + bb16 (cleanup): { + StorageDead(_12); + StorageDead(_10); - goto -> bb17; ++ goto -> bb17; } - bb17: { -- StorageDead(_15); -- StorageDead(_11); -- StorageDead(_8); -- goto -> bb21; + bb17 (cleanup): { + StorageDead(_9); -+ goto -> bb18; + goto -> bb18; } - bb18: { +- StorageDead(_4); +- StorageDead(_3); - goto -> bb19; + bb18 (cleanup): { + StorageDead(_15); @@ -191,18 +193,17 @@ } - bb19: { -- StorageDead(_4); +- drop(_2) -> [return: bb20, unwind: bb36]; + bb19 (cleanup): { + StorageDead(_13); + StorageDead(_12); + StorageDead(_10); + StorageDead(_9); - goto -> bb20; ++ goto -> bb20; } - bb20: { -- StorageDead(_3); -- goto -> bb21; +- drop(_1) -> [return: bb21, unwind: bb35]; + bb20 (cleanup): { + StorageDead(_11); + StorageDead(_8); @@ -210,71 +211,71 @@ } - bb21: { -- drop(_2) -> [return: bb22, unwind: bb38]; +- coroutine_drop; + bb21 (cleanup): { + StorageDead(_7); + drop(_5) -> [return: bb23, unwind terminate(cleanup)]; } -- bb22: { -- drop(_1) -> [return: bb23, unwind: bb37]; -+ bb22 (cleanup): { + bb22 (cleanup): { +- StorageDead(_14); +- drop(_12) -> [return: bb23, unwind terminate(cleanup)]; + StorageDead(_6); + goto -> bb23; } -- bb23: { -- coroutine_drop; -+ bb23 (cleanup): { + bb23 (cleanup): { +- StorageDead(_12); +- StorageDead(_10); + StorageDead(_5); -+ goto -> bb24; + goto -> bb24; } bb24 (cleanup): { -- StorageDead(_14); -- drop(_12) -> [return: bb25, unwind terminate(cleanup)]; +- StorageDead(_9); + StorageDead(_4); -+ goto -> bb25; + goto -> bb25; } bb25 (cleanup): { -- StorageDead(_12); -- StorageDead(_10); +- StorageDead(_15); +- goto -> bb27; + StorageDead(_3); - goto -> bb26; ++ goto -> bb26; } bb26 (cleanup): { +- StorageDead(_13); +- StorageDead(_12); +- StorageDead(_10); - StorageDead(_9); - goto -> bb27; + drop((((*_18) as variant#4).0: std::string::String)) -> [return: bb27, unwind terminate(cleanup)]; } bb27 (cleanup): { -- StorageDead(_15); -- goto -> bb29; +- StorageDead(_11); +- StorageDead(_8); +- goto -> bb33; + goto -> bb28; } bb28 (cleanup): { -- StorageDead(_13); -- StorageDead(_12); -- StorageDead(_10); -- StorageDead(_9); - goto -> bb29; +- StorageDead(_7); +- drop(_5) -> [return: bb30, unwind terminate(cleanup)]; ++ goto -> bb29; } bb29 (cleanup): { -- StorageDead(_11); -- StorageDead(_8); -- goto -> bb35; +- StorageDead(_6); +- goto -> bb30; + discriminant((*_18)) = 2; + resume; } - bb30 (cleanup): { -- StorageDead(_7); -- drop(_5) -> [return: bb32, unwind terminate(cleanup)]; +- StorageDead(_5); +- goto -> bb31; + bb30: { + StorageLive(_3); + StorageLive(_4); @@ -283,7 +284,7 @@ } - bb31 (cleanup): { -- StorageDead(_6); +- StorageDead(_4); - goto -> bb32; + bb31: { + StorageLive(_8); @@ -295,40 +296,30 @@ } - bb32 (cleanup): { -- StorageDead(_5); +- StorageDead(_3); - goto -> bb33; + bb32: { + assert(const false, "coroutine resumed after panicking") -> [success: bb32, unwind continue]; } - bb33 (cleanup): { -- StorageDead(_4); -- goto -> bb34; +- drop(_2) -> [return: bb34, unwind terminate(cleanup)]; + bb33: { + assert(const false, "coroutine resumed after completion") -> [success: bb33, unwind continue]; } - bb34 (cleanup): { -- StorageDead(_3); -- goto -> bb35; +- drop(_1) -> [return: bb35, unwind terminate(cleanup)]; + bb34: { + unreachable; } - bb35 (cleanup): { -- drop(_2) -> [return: bb36, unwind terminate(cleanup)]; -- } -- -- bb36 (cleanup): { -- drop(_1) -> [return: bb37, unwind terminate(cleanup)]; -- } -- -- bb37 (cleanup): { - resume; - } - -- bb38 (cleanup): { -- drop(_1) -> [return: bb37, unwind terminate(cleanup)]; +- bb36 (cleanup): { +- drop(_1) -> [return: bb35, unwind terminate(cleanup)]; + bb35: { + (((*_18) as variant#4).0: std::string::String) = move _2; + StorageLive(_3); diff --git a/tests/mir-opt/coroutine/unwind_in_vec.build-{closure#0}.built.after.mir b/tests/mir-opt/coroutine/unwind_in_vec.build-{closure#0}.built.after.mir index db46970999856..663d954d9b545 100644 --- a/tests/mir-opt/coroutine/unwind_in_vec.build-{closure#0}.built.after.mir +++ b/tests/mir-opt/coroutine/unwind_in_vec.build-{closure#0}.built.after.mir @@ -37,7 +37,7 @@ yields () FakeRead(ForLet(None), _3); StorageLive(_4); StorageLive(_5); - _5 = Box::<[String; 5]>::new_uninit() -> [return: bb1, unwind: bb50]; + _5 = Box::<[String; 5]>::new_uninit() -> [return: bb1, unwind: bb44]; } bb1: { @@ -46,7 +46,7 @@ yields () StorageLive(_8); _8 = const "0"; _7 = &(*_8); - _6 = ::to_string(move _7) -> [return: bb2, unwind: bb47]; + _6 = ::to_string(move _7) -> [return: bb2, unwind: bb41]; } bb2: { @@ -56,7 +56,7 @@ yields () StorageLive(_11); _11 = const "1"; _10 = &(*_11); - _9 = ::to_string(move _10) -> [return: bb3, unwind: bb43]; + _9 = ::to_string(move _10) -> [return: bb3, unwind: bb37]; } bb3: { @@ -66,7 +66,7 @@ yields () StorageLive(_14); _14 = const "2"; _13 = &(*_14); - _12 = ::to_string(move _13) -> [return: bb4, unwind: bb38]; + _12 = ::to_string(move _13) -> [return: bb4, unwind: bb32]; } bb4: { @@ -76,7 +76,7 @@ yields () StorageLive(_17); _17 = const "3"; _16 = &(*_17); - _15 = ::to_string(move _16) -> [return: bb5, unwind: bb32]; + _15 = ::to_string(move _16) -> [return: bb5, unwind: bb26]; } bb5: { @@ -86,44 +86,44 @@ yields () StorageLive(_20); _20 = const "4"; _19 = &(*_20); - _18 = ::to_string(move _19) -> [return: bb6, unwind: bb24]; + _18 = ::to_string(move _19) -> [return: bb6, unwind: bb18]; } bb6: { StorageDead(_19); (((*_5).1: std::mem::ManuallyDrop<[std::string::String; 5]>).0: [std::string::String; 5]) = [move _6, move _9, move _12, move _15, move _18]; - drop(_18) -> [return: bb7, unwind: bb25, drop: bb15]; + drop(_18) -> [return: bb7, unwind: bb19]; } bb7: { StorageDead(_18); - drop(_15) -> [return: bb8, unwind: bb26, drop: bb16]; + drop(_15) -> [return: bb8, unwind: bb20]; } bb8: { StorageDead(_15); - drop(_12) -> [return: bb9, unwind: bb27, drop: bb17]; + drop(_12) -> [return: bb9, unwind: bb21]; } bb9: { StorageDead(_12); - drop(_9) -> [return: bb10, unwind: bb28, drop: bb18]; + drop(_9) -> [return: bb10, unwind: bb22]; } bb10: { StorageDead(_9); - drop(_6) -> [return: bb11, unwind: bb29, drop: bb19]; + drop(_6) -> [return: bb11, unwind: bb23]; } bb11: { StorageDead(_6); _4 = move _5; - drop(_5) -> [return: bb12, unwind: bb22]; + drop(_5) -> [return: bb12, unwind: bb16]; } bb12: { StorageDead(_5); - _0 = std::boxed::box_assume_init_into_vec_unsafe::(move _4) -> [return: bb13, unwind: bb23]; + _0 = std::boxed::box_assume_init_into_vec_unsafe::(move _4) -> [return: bb13, unwind: bb17]; } bb13: { @@ -134,7 +134,7 @@ yields () StorageDead(_11); StorageDead(_8); StorageDead(_3); - drop(_1) -> [return: bb14, unwind: bb52, drop: bb21]; + drop(_1) -> [return: bb14, unwind: bb46, drop: bb15]; } bb14: { @@ -142,66 +142,61 @@ yields () } bb15: { - StorageDead(_18); - drop(_15) -> [return: bb16, unwind: bb53]; + coroutine_drop; } - bb16: { - StorageDead(_15); - drop(_12) -> [return: bb17, unwind: bb54]; + bb16 (cleanup): { + StorageDead(_5); + goto -> bb17; } - bb17: { - StorageDead(_12); - drop(_9) -> [return: bb18, unwind: bb55]; + bb17 (cleanup): { + drop(_4) -> [return: bb25, unwind terminate(cleanup)]; } - bb18: { - StorageDead(_9); - drop(_6) -> [return: bb19, unwind: bb56]; + bb18 (cleanup): { + StorageDead(_19); + goto -> bb19; } - bb19: { - StorageDead(_6); - drop(_5) -> [return: bb20, unwind: bb57]; + bb19 (cleanup): { + StorageDead(_18); + drop(_15) -> [return: bb20, unwind terminate(cleanup)]; } - bb20: { - StorageDead(_5); - StorageDead(_4); - StorageDead(_20); - StorageDead(_17); - StorageDead(_14); - StorageDead(_11); - StorageDead(_8); - StorageDead(_3); - drop(_1) -> [return: bb21, unwind: bb52]; + bb20 (cleanup): { + StorageDead(_15); + drop(_12) -> [return: bb21, unwind terminate(cleanup)]; } - bb21: { - coroutine_drop; + bb21 (cleanup): { + StorageDead(_12); + drop(_9) -> [return: bb22, unwind terminate(cleanup)]; } bb22 (cleanup): { - StorageDead(_5); - goto -> bb23; + StorageDead(_9); + drop(_6) -> [return: bb23, unwind terminate(cleanup)]; } bb23 (cleanup): { - drop(_4) -> [return: bb31, unwind terminate(cleanup)]; + StorageDead(_6); + drop(_5) -> [return: bb24, unwind terminate(cleanup)]; } bb24 (cleanup): { - StorageDead(_19); + StorageDead(_5); goto -> bb25; } bb25 (cleanup): { - StorageDead(_18); - drop(_15) -> [return: bb26, unwind terminate(cleanup)]; + StorageDead(_4); + StorageDead(_20); + goto -> bb31; } bb26 (cleanup): { + StorageDead(_16); StorageDead(_15); drop(_12) -> [return: bb27, unwind terminate(cleanup)]; } @@ -223,159 +218,95 @@ yields () bb30 (cleanup): { StorageDead(_5); + StorageDead(_4); goto -> bb31; } bb31 (cleanup): { - StorageDead(_4); - StorageDead(_20); - goto -> bb37; - } - - bb32 (cleanup): { - StorageDead(_16); - StorageDead(_15); - drop(_12) -> [return: bb33, unwind terminate(cleanup)]; - } - - bb33 (cleanup): { - StorageDead(_12); - drop(_9) -> [return: bb34, unwind terminate(cleanup)]; - } - - bb34 (cleanup): { - StorageDead(_9); - drop(_6) -> [return: bb35, unwind terminate(cleanup)]; - } - - bb35 (cleanup): { - StorageDead(_6); - drop(_5) -> [return: bb36, unwind terminate(cleanup)]; - } - - bb36 (cleanup): { - StorageDead(_5); - StorageDead(_4); - goto -> bb37; - } - - bb37 (cleanup): { StorageDead(_17); - goto -> bb42; + goto -> bb36; } - bb38 (cleanup): { + bb32 (cleanup): { StorageDead(_13); StorageDead(_12); - drop(_9) -> [return: bb39, unwind terminate(cleanup)]; + drop(_9) -> [return: bb33, unwind terminate(cleanup)]; } - bb39 (cleanup): { + bb33 (cleanup): { StorageDead(_9); - drop(_6) -> [return: bb40, unwind terminate(cleanup)]; + drop(_6) -> [return: bb34, unwind terminate(cleanup)]; } - bb40 (cleanup): { + bb34 (cleanup): { StorageDead(_6); - drop(_5) -> [return: bb41, unwind terminate(cleanup)]; + drop(_5) -> [return: bb35, unwind terminate(cleanup)]; } - bb41 (cleanup): { + bb35 (cleanup): { StorageDead(_5); StorageDead(_4); - goto -> bb42; + goto -> bb36; } - bb42 (cleanup): { + bb36 (cleanup): { StorageDead(_14); - goto -> bb46; + goto -> bb40; } - bb43 (cleanup): { + bb37 (cleanup): { StorageDead(_10); StorageDead(_9); - drop(_6) -> [return: bb44, unwind terminate(cleanup)]; + drop(_6) -> [return: bb38, unwind terminate(cleanup)]; } - bb44 (cleanup): { + bb38 (cleanup): { StorageDead(_6); - drop(_5) -> [return: bb45, unwind terminate(cleanup)]; + drop(_5) -> [return: bb39, unwind terminate(cleanup)]; } - bb45 (cleanup): { + bb39 (cleanup): { StorageDead(_5); StorageDead(_4); - goto -> bb46; + goto -> bb40; } - bb46 (cleanup): { + bb40 (cleanup): { StorageDead(_11); - goto -> bb49; + goto -> bb43; } - bb47 (cleanup): { + bb41 (cleanup): { StorageDead(_7); StorageDead(_6); - drop(_5) -> [return: bb48, unwind terminate(cleanup)]; + drop(_5) -> [return: bb42, unwind terminate(cleanup)]; } - bb48 (cleanup): { + bb42 (cleanup): { StorageDead(_5); StorageDead(_4); - goto -> bb49; + goto -> bb43; } - bb49 (cleanup): { + bb43 (cleanup): { StorageDead(_8); - goto -> bb51; + goto -> bb45; } - bb50 (cleanup): { + bb44 (cleanup): { StorageDead(_5); StorageDead(_4); - goto -> bb51; + goto -> bb45; } - bb51 (cleanup): { + bb45 (cleanup): { StorageDead(_3); - drop(_1) -> [return: bb52, unwind terminate(cleanup)]; + drop(_1) -> [return: bb46, unwind terminate(cleanup)]; } - bb52 (cleanup): { + bb46 (cleanup): { resume; } - - bb53 (cleanup): { - StorageDead(_15); - drop(_12) -> [return: bb54, unwind terminate(cleanup)]; - } - - bb54 (cleanup): { - StorageDead(_12); - drop(_9) -> [return: bb55, unwind terminate(cleanup)]; - } - - bb55 (cleanup): { - StorageDead(_9); - drop(_6) -> [return: bb56, unwind terminate(cleanup)]; - } - - bb56 (cleanup): { - StorageDead(_6); - drop(_5) -> [return: bb57, unwind terminate(cleanup)]; - } - - bb57 (cleanup): { - StorageDead(_5); - StorageDead(_4); - StorageDead(_20); - StorageDead(_17); - StorageDead(_14); - StorageDead(_11); - StorageDead(_8); - StorageDead(_3); - drop(_1) -> [return: bb52, unwind terminate(cleanup)]; - } } ALLOC0 (size: 1, align: 1) { diff --git a/tests/ui/async-await/async-drop/cancelled-future-drops-sync-fields-164901.rs b/tests/ui/async-await/async-drop/cancelled-future-drops-sync-fields-164901.rs new file mode 100644 index 0000000000000..280e123eb0b78 --- /dev/null +++ b/tests/ui/async-await/async-drop/cancelled-future-drops-sync-fields-164901.rs @@ -0,0 +1,56 @@ +//@ run-pass +//@ edition: 2024 + +// Regression test for . +// Types with only a sync `Drop` impl nested inside another ADT were treated +// as needing async drop, so a cancelled future leaked them. + +#![feature(async_drop)] +#![allow(incomplete_features)] + +use std::future::Future; +use std::pin::pin; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::task::{Context, Waker}; + +static DROPS: AtomicUsize = AtomicUsize::new(0); + +struct D; +impl Drop for D { + fn drop(&mut self) { + DROPS.fetch_add(1, Ordering::Relaxed); + } +} + +struct Wrapper(T); + +fn poll_once_then_drop(f: impl Future) { + let mut f = Box::pin(f); + let _ = f.as_mut().poll(&mut Context::from_waker(Waker::noop())); +} + +fn main() { + poll_once_then_drop(async { + let _d = D; + std::future::pending::<()>().await + }); + assert_eq!(DROPS.load(Ordering::Relaxed), 1); + + poll_once_then_drop(async { + let _o = Some(D); + std::future::pending::<()>().await + }); + assert_eq!(DROPS.load(Ordering::Relaxed), 2); + + poll_once_then_drop(async { + let _w = Wrapper(D); + std::future::pending::<()>().await + }); + assert_eq!(DROPS.load(Ordering::Relaxed), 3); + + poll_once_then_drop(async { + let _p = pin!(D); + std::future::pending::<()>().await + }); + assert_eq!(DROPS.load(Ordering::Relaxed), 4); +} diff --git a/tests/ui/drop/tail_expr_drop_order-on-async-block-with-drop-field.rs b/tests/ui/drop/tail_expr_drop_order-on-async-block-with-drop-field.rs new file mode 100644 index 0000000000000..69e9a8e06dc86 --- /dev/null +++ b/tests/ui/drop/tail_expr_drop_order-on-async-block-with-drop-field.rs @@ -0,0 +1,15 @@ +//@ edition: 2021 +//@ check-pass + +// Regression test for . +// The tail expr drop order lint used to ICE on this async block. It stopped +// once types with only a sync `Drop` were no longer treated as needing async drop. + +#![warn(tail_expr_drop_order)] +use core::future::Future; + +fn f() -> impl Future> { + async { Some("nope".into()) } +} + +fn main() {} From b6997cd4c34e21b90d6bb919cee9aeb900709fb9 Mon Sep 17 00:00:00 2001 From: Tess4552 Date: Mon, 26 Oct 2026 14:47:24 +0100 Subject: [PATCH 17/18] reflection: doc attributes from adts, fields, and variants --- .../src/const_eval/machine.rs | 50 ++++++++++++++- .../src/const_eval/type_info.rs | 25 +++++++- .../rustc_hir_analysis/src/check/intrinsic.rs | 22 +++++++ compiler/rustc_span/src/symbol.rs | 2 + library/core/src/intrinsics/reflection.rs | 21 +++++++ library/core/src/mem/type_info.rs | 63 +++++++++++++++++++ library/coretests/tests/mem/type_info.rs | 38 +++++++++++ 7 files changed, 219 insertions(+), 2 deletions(-) diff --git a/compiler/rustc_const_eval/src/const_eval/machine.rs b/compiler/rustc_const_eval/src/const_eval/machine.rs index cb9432f9832e5..8a55060e68a0d 100644 --- a/compiler/rustc_const_eval/src/const_eval/machine.rs +++ b/compiler/rustc_const_eval/src/const_eval/machine.rs @@ -4,8 +4,8 @@ use std::{fmt, mem}; use rustc_abi::{Align, FIRST_VARIANT, FieldIdx, Size, VariantIdx}; use rustc_ast::Mutability; -use rustc_attr_ir::find_attr; use rustc_attr_ir::lang_items::LangItem; +use rustc_attr_ir::{HasAttrs, find_attr}; use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry}; use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::{CRATE_HIR_ID, HirId}; @@ -796,6 +796,54 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> { )?; } + sym::type_id_docs => { + let ty = ecx.read_type_id(&args[0])?; + let attrs = match ty.kind() { + ty::Adt(def, args) + if let Some(FieldInfo { base, variant_idx, field_idx, .. }) = + def.field_representing_type_info(ecx.tcx(), args) => + { + match base.kind() { + ty::Adt(base_def, _) => { + let field = &base_def.variants()[variant_idx].fields[field_idx]; + field.did.get_attrs(&ecx.tcx) + } + ty::Tuple(_) => &[], + _ => { + // only adts and tuples have fields + span_bug!(ecx.cur_span(), "expected adt or tuple type, got {ty}"); + } + } + } + ty::Adt(def, _) => def.did().get_attrs(&ecx.tcx), + _ => &[], + }; + + ecx.write_doc_attributes(dest, attrs)?; + } + + sym::type_id_variant_docs => { + let base = ecx.read_type_id(&args[0])?; + + if let ty::Adt(def, _) = base.kind() { + let variant_idx = ecx.read_target_usize(&args[1])? as usize; + if variant_idx >= def.variants().len() { + throw_ub!(BoundsCheckFailed { + len: def.variants().len() as u64, + index: variant_idx as u64 + }); + } + let variant_idx = VariantIdx::from_usize(variant_idx); + + ecx.write_doc_attributes( + dest, + def.variant(variant_idx).def_id.get_attrs(&ecx.tcx), + )?; + } else { + span_bug!(ecx.cur_span(), "expected enum type, got {base}") + }; + } + sym::type_id_variant_non_exhaustive => { let base = ecx.read_type_id(&args[0])?; diff --git a/compiler/rustc_const_eval/src/const_eval/type_info.rs b/compiler/rustc_const_eval/src/const_eval/type_info.rs index 0df2e9b5fd0ae..d028b312c7820 100644 --- a/compiler/rustc_const_eval/src/const_eval/type_info.rs +++ b/compiler/rustc_const_eval/src/const_eval/type_info.rs @@ -3,6 +3,7 @@ mod adt; use std::borrow::Cow; use rustc_abi::{ExternAbi, FieldIdx}; +use rustc_ast::attr::AttributeExt; use rustc_attr_ir::lang_items::LangItem; use rustc_middle::ty::layout::TyAndLayout; use rustc_middle::ty::{self, FnHeader, FnSigKind, FnSigTys, ScalarInt, Ty, TyCtxt}; @@ -16,7 +17,7 @@ use crate::interpret::{ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { // A general method to write an array to a static slice place. - fn allocate_fill_and_write_slice_ptr( + pub(crate) fn allocate_fill_and_write_slice_ptr( &mut self, slice_place: &impl Writeable<'tcx, CtfeProvenance>, len: u64, @@ -346,4 +347,26 @@ impl<'tcx> InterpCx<'tcx, CompileTimeMachine<'tcx>> { interp_ok(()) } + + pub(crate) fn write_doc_attributes( + &mut self, + place: &impl Writeable<'tcx, CtfeProvenance>, + attrs: &'tcx [rustc_attr_ir::Attribute], + ) -> InterpResult<'tcx> { + let docs = attrs.iter().filter_map(|x| x.doc_str()).collect::>(); + + self.allocate_fill_and_write_slice_ptr(place, docs.len() as _, |this, i, place| { + let doc = docs[i as usize]; + + let ptr = this.allocate_bytes_dedup(doc.as_str().as_bytes())?; + + this.write_immediate( + Immediate::ScalarPair( + Scalar::from_pointer(ptr, this), + Scalar::from_target_usize(doc.as_str().len() as u64, this), + ), + &place, + ) + }) + } } diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index 0aa3e97568729..06fcdcddc2e45 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -171,6 +171,7 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi | sym::trunc | sym::type_id | sym::type_id_array_len + | sym::type_id_docs | sym::type_id_element_ty | sym::type_id_eq | sym::type_id_field_representing_type @@ -183,6 +184,7 @@ fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hi | sym::type_id_points_to | sym::type_id_size_of | sym::type_id_type_of + | sym::type_id_variant_docs | sym::type_id_variant_name | sym::type_id_variant_non_exhaustive | sym::type_id_variants @@ -316,6 +318,26 @@ pub(crate) fn check_intrinsic_type( sym::type_id_variant_name => { (0, 0, vec![type_id_ty(), tcx.types.usize], Ty::new_static_str(tcx)) } + sym::type_id_variant_docs => ( + 0, + 0, + vec![type_id_ty(), tcx.types.usize], + Ty::new_imm_ref( + tcx, + tcx.lifetimes.re_static, + Ty::new_slice(tcx, Ty::new_static_str(tcx)), + ), + ), + sym::type_id_docs => ( + 0, + 0, + vec![type_id_ty()], + Ty::new_imm_ref( + tcx, + tcx.lifetimes.re_static, + Ty::new_slice(tcx, Ty::new_static_str(tcx)), + ), + ), sym::type_id_variant_non_exhaustive => { (0, 0, vec![type_id_ty(), tcx.types.usize], tcx.types.bool) } diff --git a/compiler/rustc_span/src/symbol.rs b/compiler/rustc_span/src/symbol.rs index c3e275971056d..9af345003ecde 100644 --- a/compiler/rustc_span/src/symbol.rs +++ b/compiler/rustc_span/src/symbol.rs @@ -2206,6 +2206,7 @@ symbols! { type_changing_struct_update, type_id, type_id_array_len, + type_id_docs, type_id_element_ty, type_id_eq, type_id_field_representing_type, @@ -2218,6 +2219,7 @@ symbols! { type_id_points_to, type_id_size_of, type_id_type_of, + type_id_variant_docs, type_id_variant_name, type_id_variant_non_exhaustive, type_id_variants, diff --git a/library/core/src/intrinsics/reflection.rs b/library/core/src/intrinsics/reflection.rs index f0e0f9d66e033..0e38a38298c39 100644 --- a/library/core/src/intrinsics/reflection.rs +++ b/library/core/src/intrinsics/reflection.rs @@ -119,6 +119,19 @@ pub fn type_id_variants(_id: crate::any::TypeId) -> usize; #[rustc_comptime] pub fn type_id_variant_name(_base: crate::any::TypeId, _variant_index: usize) -> &'static str; +/// Gets the raw documentation attributes of the variant represented by the base `TypeId` and variant_idx. +/// +/// The more user-friendly version of this intrinsic is [`core::mem::type_info::VariantId::docs`]. +/// +/// [`TypeId`]: crate::any::TypeId +#[rustc_intrinsic] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_comptime] +pub fn type_id_variant_docs( + _base: crate::any::TypeId, + _variant_index: usize, +) -> &'static [&'static str]; + /// Returns true when the variant represented by the base `TypeId` and variant_idx is non /// exhaustive. /// @@ -192,3 +205,11 @@ pub fn type_id_points_mutably(_id: crate::any::TypeId) -> bool; #[unstable(feature = "core_intrinsics", issue = "none")] #[rustc_comptime] pub fn type_id_function_ptr(_type_id: crate::any::TypeId) -> Option; + +/// Returns the raw documentation attributes given a `TypeId` which represents a structure, enumeration, union or `FieldId`. +/// +/// The more user-friendly version of this intrinsic is [`core::any::TypeId::docs`]. +#[rustc_intrinsic] +#[unstable(feature = "core_intrinsics", issue = "none")] +#[rustc_comptime] +pub fn type_id_docs(_type_id: crate::any::TypeId) -> &'static [&'static str]; diff --git a/library/core/src/mem/type_info.rs b/library/core/src/mem/type_info.rs index 71a9627c24f9c..94b65f76dfb81 100644 --- a/library/core/src/mem/type_info.rs +++ b/library/core/src/mem/type_info.rs @@ -656,6 +656,26 @@ impl TypeId { pub fn function_ptr(self) -> Option { intrinsics::reflection::type_id_function_ptr(self) } + + /// Returns the raw documentation attributes when given a `TypeId` which represents a structure, enumeration or union. + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// #[doc = "first"] + /// /** second + /// * third + /// */ + /// struct A; + /// + /// assert_eq!(const { TypeId::of::().docs() }, ["first", " second\n* third\n"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn docs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_docs(self) + } } /// Variant representing type ID. Representing a variant of an enum. @@ -698,6 +718,28 @@ impl VariantId { intrinsics::reflection::type_id_variant_name(self.base, self.variant) } + /// Returns the raw documentation attributes when given a `VariantId`. + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// enum A { + /// #[doc = "first"] + /// /** second + /// * third*/ + /// B, + /// C, + /// } + /// + /// assert_eq!(const { TypeId::of::().variant(0).docs() }, ["first", " second\n * third"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn docs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_variant_docs(self.base, self.variant) + } + /// Returns whether this variant is marked with `#[non_exhaustive]`. #[unstable(feature = "type_info", issue = "146922")] #[rustc_const_unstable(feature = "type_info", issue = "146922")] @@ -766,6 +808,27 @@ impl FieldId { pub fn name(self) -> &'static str { intrinsics::field_representing_type_name(self.frt_type_id) } + + /// Returns the raw documentation attributes when given a `FieldId`. + /// ``` + /// #![feature(type_info)] + /// # use std::any::TypeId; + /// + /// struct A { + /// #[doc = "first"] + /// /// second + /// first: u8, + /// } + /// + /// assert_eq!(const { TypeId::of::().field(0, 0).docs() }, ["first", " second"]); + /// ``` + #[unstable(feature = "type_info", issue = "146922")] + #[rustc_const_unstable(feature = "type_info", issue = "146922")] + #[rustc_comptime] + pub fn docs(self) -> &'static [&'static str] { + intrinsics::reflection::type_id_docs(self.frt_type_id) + } + /// Returns the offset of the field wrt to its containing type. /// /// ``` diff --git a/library/coretests/tests/mem/type_info.rs b/library/coretests/tests/mem/type_info.rs index 865b6a269afff..1f88a7d9a0cfb 100644 --- a/library/coretests/tests/mem/type_info.rs +++ b/library/coretests/tests/mem/type_info.rs @@ -57,8 +57,12 @@ fn test_tuples() { #[test] fn test_structs() { const { + ///test-doc struct TestStruct { + #[doc = "first-doc 1"] + ///first-doc 2 first: u8, + /// second-doc second: u16, reference: &'static u16, } @@ -66,14 +70,17 @@ fn test_structs() { let ty_id = TypeId::of::(); assert!(!ty_id.non_exhaustive()); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.docs() == &["test-doc"]); assert!(ty_id.variants() == 1); assert!(ty_id.fields(0) == 3); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.field(0, 0).offset() == offset_of!(TestStruct, first)); assert!(ty_id.field(0, 0).name() == "first"); + assert!(ty_id.field(0, 0).docs() == &["first-doc 1", "first-doc 2"]); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); assert!(ty_id.field(0, 1).offset() == offset_of!(TestStruct, second)); assert!(ty_id.field(0, 1).name() == "second"); + assert!(ty_id.field(0, 1).docs() == &[" second-doc"]); assert!(ty_id.field(0, 2).type_id() == TypeId::of::<&u16>()); assert!(ty_id.field(0, 2).offset() == offset_of!(TestStruct, reference)); assert!(ty_id.field(0, 2).name() == "reference"); @@ -97,16 +104,20 @@ fn test_structs() { assert!(ty_id.fields(0) == 2); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.field(0, 0).name() == "0"); + assert!(ty_id.field(0, 0).docs() == &[""; 0]); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); assert!(ty_id.field(0, 1).name() == "1"); + assert!(ty_id.field(0, 1).docs() == &[""; 0]); } const { + ///doc struct Generics<'a, T, const C: u64> { a: &'a T, } let ty_id = TypeId::of::>(); + assert!(ty_id.docs() == &["doc"]); assert!(ty_id.fields(0) == 1); assert!(ty_id.generics().len() == 3); @@ -123,28 +134,37 @@ fn test_structs() { #[test] fn test_unions() { const { + ///test-doc 1 + ///test-doc 2 union TestUnion { + #[doc = "first-doc"] first: i16, + ///second-doc second: u16, } let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.docs() == &["test-doc 1", "test-doc 2"]); assert!(ty_id.variants() == 1); assert!(ty_id.fields(0) == 2); assert!(ty_id.field(0, 0).name() == "first"); + assert!(ty_id.field(0, 0).docs() == &["first-doc"]); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.field(0, 1).name() == "second"); + assert!(ty_id.field(0, 1).docs() == &["second-doc"]); assert!(ty_id.field(0, 1).type_id() == TypeId::of::()); } const { + ///doc union Generics<'a, T: Copy, const C: u64> { a: T, z: &'a (), } let ty_id = TypeId::of::>(); + assert!(ty_id.docs() == &["doc"]); assert!(ty_id.fields(0) == 2); assert!(ty_id.field(0, 1).offset() == offset_of!(Generics<'static, i32, 1_u64>, a)); assert!(ty_id.field(0, 1).offset() == offset_of!(Generics<'static, i32, 1_u64>, z)); @@ -163,12 +183,17 @@ fn test_unions() { #[test] fn test_enums() { const { + ///doc enum E { + ///somedoc Some(u32), + ///nonedoc None, #[non_exhaustive] + ///foompdoc Foomp { a: (), + ///bdoc b: &'static str, }, } @@ -176,23 +201,28 @@ fn test_enums() { let ty_id = TypeId::of::(); assert!(!ty_id.non_exhaustive()); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.docs() == &["doc"]); assert!(ty_id.variants() == 3); assert!(ty_id.variant(0).name() == "Some"); + assert!(ty_id.variant(0).docs() == &["somedoc"]); assert!(!ty_id.variant(0).non_exhaustive()); assert!(ty_id.fields(0) == 1); assert!(ty_id.field(0, 0).type_id() == TypeId::of::()); assert!(ty_id.variant(1).name() == "None"); + assert!(ty_id.variant(1).docs() == &["nonedoc"]); assert!(!ty_id.variant(1).non_exhaustive()); assert!(ty_id.fields(1) == 0); assert!(ty_id.variant(2).name() == "Foomp"); + assert!(ty_id.variant(2).docs() == &["foompdoc"]); assert!(ty_id.variant(2).non_exhaustive()); assert!(ty_id.fields(2) == 2); assert!(ty_id.field(2, 0).type_id() == TypeId::of::<()>()); assert!(ty_id.field(2, 1).type_id() == TypeId::of::<&str>()); assert!(ty_id.field(2, 1).name() == "b"); + assert!(ty_id.field(2, 1).docs() == &["bdoc"]); assert!(ty_id.generics().is_empty()); } @@ -224,45 +254,53 @@ fn test_primitives() { let Type { kind: Bool, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Char, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(!ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Int, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(!ty_id.is_signed()); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Float, .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == Some(size_of::())); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); let Type { kind: Str(_ty), .. } = (const { Type::of::() }) else { panic!() }; let ty_id = TypeId::of::(); assert!(ty_id.size() == None); + assert!(ty_id.docs() == &[""; 0]); assert!(ty_id.variants() == 1); } } From b1b7ce4fb8f487e681c413b9ede5f5a5555ba6dd Mon Sep 17 00:00:00 2001 From: Oli Scherer Date: Thu, 29 Oct 2026 13:06:54 +0100 Subject: [PATCH 18/18] Fix ICE in prelude edition lint --- .../src/method/prelude_edition_lints.rs | 21 ++++++++----------- .../prelude-migration/nested-use-statement.rs | 19 +++++++++++++++++ .../nested-use-statement.stderr | 16 ++++++++++++++ 3 files changed, 44 insertions(+), 12 deletions(-) create mode 100644 tests/ui/rust-2024/prelude-migration/nested-use-statement.rs create mode 100644 tests/ui/rust-2024/prelude-migration/nested-use-statement.stderr diff --git a/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs b/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs index 7a60c7472cf45..dae5664f39b40 100644 --- a/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs +++ b/compiler/rustc_hir_typeck/src/method/prelude_edition_lints.rs @@ -1,11 +1,11 @@ use std::fmt::Write; +use hir::HirId; use hir::def_id::DefId; -use hir::{HirId, ItemKind}; use rustc_ast::join_path_idents; use rustc_attr_ir::lang_items::LangItem; use rustc_errors::{Applicability, Diag, DiagCtxtHandle, Diagnostic, Level}; -use rustc_hir as hir; +use rustc_hir::{self as hir, Node}; use rustc_lint::{ARRAY_INTO_ITER, BOXED_SLICE_INTO_ITER}; use rustc_lint_defs::builtin::{RUST_2021_PRELUDE_COLLISIONS, RUST_2024_PRELUDE_COLLISIONS}; use rustc_middle::ty::{self, Ty, TyCtxt}; @@ -436,12 +436,16 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let import_items: Vec<_> = applicable_trait .import_ids .iter() - .map(|&import_id| self.tcx.hir_expect_item(import_id)) + .map(|&import_id| match self.tcx.hir_node_by_def_id(import_id) { + Node::NestedUseTree(tree) => *tree, + Node::Item(it) => it.expect_use(), + node => span_bug!(span, "expected use tree, found {node:#?}"), + }) .collect(); // Find an identifier with which this trait was imported (note that `_` doesn't count). for item in import_items.iter() { - match item.expect_use().kind { + match item.kind { hir::UseKind::Single(ident) => { if ident.name != kw::Underscore { return Some(format!("{}", ident.name)); @@ -454,14 +458,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // All that is left is `_`! We need to use the full path. It doesn't matter which one we // pick, so just take the first one. - match import_items[0].kind { - ItemKind::Use(tree) => { - Some(join_path_idents(tree.prefix.segments.iter().map(|seg| seg.ident))) - } - _ => { - span_bug!(span, "unexpected item kind, expected a use: {:?}", import_items[0].kind); - } - } + Some(join_path_idents(import_items[0].prefix.segments.iter().map(|seg| seg.ident))) } /// Creates a string version of the `expr` that includes explicit adjustments. diff --git a/tests/ui/rust-2024/prelude-migration/nested-use-statement.rs b/tests/ui/rust-2024/prelude-migration/nested-use-statement.rs new file mode 100644 index 0000000000000..9f42d523ddea4 --- /dev/null +++ b/tests/ui/rust-2024/prelude-migration/nested-use-statement.rs @@ -0,0 +1,19 @@ +//! This test used to ICE because the lint did not handle +//! nested use trees in the new HIR representation. + +//@ check-pass + +#[warn(rust_2024_prelude_collisions)] +fn main() { + ().into_future() + //~^ WARN: `into_future` will become ambiguous + //~| WARN: is a hard error in Rust 2024 +} +#[rustfmt::skip] +use future::{IntoFuture}; +mod future { + pub trait IntoFuture { + fn into_future(&self) {} + } + impl IntoFuture for () {} +} diff --git a/tests/ui/rust-2024/prelude-migration/nested-use-statement.stderr b/tests/ui/rust-2024/prelude-migration/nested-use-statement.stderr new file mode 100644 index 0000000000000..af720c2141d73 --- /dev/null +++ b/tests/ui/rust-2024/prelude-migration/nested-use-statement.stderr @@ -0,0 +1,16 @@ +warning: trait method `into_future` will become ambiguous in Rust 2024 + --> $DIR/nested-use-statement.rs:8:5 + | +LL | ().into_future() + | ^^^^^^^^^^^^^^^^ help: disambiguate the associated function: `IntoFuture::into_future(&())` + | + = warning: this is accepted in the current edition (Rust 2015) but is a hard error in Rust 2024! + = note: for more information, see +note: the lint level is defined here + --> $DIR/nested-use-statement.rs:6:8 + | +LL | #[warn(rust_2024_prelude_collisions)] + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +warning: 1 warning emitted +