From f2ade37867c2276ac186386f37c2ee607ef7150b Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 25 Jun 2024 12:39:04 +0200 Subject: [PATCH 01/12] Add `input_file` method on `LlvmFileCheck` --- src/tools/run-make-support/src/llvm.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/tools/run-make-support/src/llvm.rs b/src/tools/run-make-support/src/llvm.rs index 7f42223bf7f5a..4c9e9a5323025 100644 --- a/src/tools/run-make-support/src/llvm.rs +++ b/src/tools/run-make-support/src/llvm.rs @@ -180,6 +180,13 @@ impl LlvmFilecheck { self.cmd.arg(path.as_ref()); self } + + /// `--input-file` option. + pub fn input_file>(&mut self, input_file: P) -> &mut Self { + self.cmd.arg("--input-file"); + self.cmd.arg(input_file.as_ref()); + self + } } impl LlvmObjdump { From 221dd303566f16d4982d1c128e94089e342c194b Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 25 Jun 2024 12:39:19 +0200 Subject: [PATCH 02/12] Migrate `run-make/llvm-ident` to `rmake.rs` --- .../tidy/src/allowed_run_make_makefiles.txt | 1 - tests/run-make/llvm-ident/Makefile | 19 --------- tests/run-make/llvm-ident/rmake.rs | 40 +++++++++++++++++++ 3 files changed, 40 insertions(+), 20 deletions(-) delete mode 100644 tests/run-make/llvm-ident/Makefile create mode 100644 tests/run-make/llvm-ident/rmake.rs diff --git a/src/tools/tidy/src/allowed_run_make_makefiles.txt b/src/tools/tidy/src/allowed_run_make_makefiles.txt index 07073ef5d40c7..53e2662fa9fe0 100644 --- a/src/tools/tidy/src/allowed_run_make_makefiles.txt +++ b/src/tools/tidy/src/allowed_run_make_makefiles.txt @@ -92,7 +92,6 @@ run-make/link-cfg/Makefile run-make/link-framework/Makefile run-make/link-path-order/Makefile run-make/linkage-attr-on-static/Makefile -run-make/llvm-ident/Makefile run-make/long-linker-command-lines-cmd-exe/Makefile run-make/long-linker-command-lines/Makefile run-make/longjmp-across-rust/Makefile diff --git a/tests/run-make/llvm-ident/Makefile b/tests/run-make/llvm-ident/Makefile deleted file mode 100644 index e583e6018e0bf..0000000000000 --- a/tests/run-make/llvm-ident/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -include ../tools.mk - -# only-linux - -all: - # `-Ccodegen-units=16 -Copt-level=2` is used here to trigger thin LTO - # across codegen units to test deduplication of the named metadata - # (see `LLVMRustPrepareThinLTOImport` for details). - echo 'fn main(){}' | $(RUSTC) - --emit=link,obj -Csave-temps -Ccodegen-units=16 -Copt-level=2 --target=$(TARGET) - - # `llvm-dis` is used here since `--emit=llvm-ir` does not emit LLVM IR - # for temporary outputs. - "$(LLVM_BIN_DIR)"/llvm-dis $(TMPDIR)/*.bc - - # Check LLVM IR files (including temporary outputs) have `!llvm.ident` - # named metadata, reusing the related codegen test. - set -e; for f in $(TMPDIR)/*.ll; do \ - $(LLVM_FILECHECK) --input-file $$f ../../codegen/llvm-ident.rs; \ - done diff --git a/tests/run-make/llvm-ident/rmake.rs b/tests/run-make/llvm-ident/rmake.rs new file mode 100644 index 0000000000000..1ca0d96778f3e --- /dev/null +++ b/tests/run-make/llvm-ident/rmake.rs @@ -0,0 +1,40 @@ +//@ only-linux + +use run_make_support::llvm::llvm_bin_dir; +use run_make_support::{cmd, env_var, llvm_filecheck, read_dir, rustc, source_root}; + +use std::ffi::OsStr; + +fn main() { + // `-Ccodegen-units=16 -Copt-level=2` is used here to trigger thin LTO + // across codegen units to test deduplication of the named metadata + // (see `LLVMRustPrepareThinLTOImport` for details). + rustc() + .emit("link,obj") + .arg("-Csave-temps") + .codegen_units(16) + .opt_level("2") + .target(&env_var("TARGET")) + .arg("-") + .stdin("fn main(){}") + .run(); + + // `llvm-dis` is used here since `--emit=llvm-ir` does not emit LLVM IR + // for temporary outputs. + let mut files = Vec::new(); + read_dir(".", |path| { + if path.is_file() && path.extension().is_some_and(|ext| ext == OsStr::new("bc")) { + files.push(path.to_path_buf()); + } + }); + cmd(llvm_bin_dir().join("llvm-dis")).args(&files).run(); + + // Check LLVM IR files (including temporary outputs) have `!llvm.ident` + // named metadata, reusing the related codegen test. + let llvm_ident_path = source_root().join("tests/codegen/llvm-ident.rs"); + read_dir(".", |path| { + if path.is_file() && path.extension().is_some_and(|ext| ext == OsStr::new("ll")) { + llvm_filecheck().input_file(path).arg(&llvm_ident_path).run(); + } + }); +} From 91562514cc4a7843d20c456658a1a04771b94f38 Mon Sep 17 00:00:00 2001 From: Urgau Date: Sat, 22 Jun 2024 12:38:10 +0200 Subject: [PATCH 03/12] Make `Span` optional in `BufferedEarlyLint` --- compiler/rustc_builtin_macros/src/format.rs | 2 +- compiler/rustc_lint/src/context.rs | 18 ++++++++++++++++-- compiler/rustc_lint/src/early.rs | 2 +- compiler/rustc_lint_defs/src/lib.rs | 4 ++-- compiler/rustc_session/src/parse.rs | 12 +++++++++++- 5 files changed, 31 insertions(+), 7 deletions(-) diff --git a/compiler/rustc_builtin_macros/src/format.rs b/compiler/rustc_builtin_macros/src/format.rs index 5cb0407bd59e6..42948eb72dc84 100644 --- a/compiler/rustc_builtin_macros/src/format.rs +++ b/compiler/rustc_builtin_macros/src/format.rs @@ -555,7 +555,7 @@ fn make_format_args( }; let arg_name = args.explicit_args()[index].kind.ident().unwrap(); ecx.buffered_early_lint.push(BufferedEarlyLint { - span: arg_name.span.into(), + span: Some(arg_name.span.into()), node_id: rustc_ast::CRATE_NODE_ID, lint_id: LintId::of(NAMED_ARGUMENTS_USED_POSITIONALLY), diagnostic: BuiltinLintDiag::NamedArgumentUsedPositionally { diff --git a/compiler/rustc_lint/src/context.rs b/compiler/rustc_lint/src/context.rs index 9f0f116cbd030..e1c75de479e69 100644 --- a/compiler/rustc_lint/src/context.rs +++ b/compiler/rustc_lint/src/context.rs @@ -532,7 +532,7 @@ pub struct EarlyContext<'a> { } impl EarlyContext<'_> { - /// Emit a lint at the appropriate level, with an optional associated span and an existing + /// Emit a lint at the appropriate level, with an associated span and an existing /// diagnostic. /// /// [`lint_level`]: rustc_middle::lint::lint_level#decorate-signature @@ -543,7 +543,21 @@ impl EarlyContext<'_> { span: MultiSpan, diagnostic: BuiltinLintDiag, ) { - self.opt_span_lint(lint, Some(span), |diag| { + self.opt_span_lint_with_diagnostics(lint, Some(span), diagnostic); + } + + /// Emit a lint at the appropriate level, with an optional associated span and an existing + /// diagnostic. + /// + /// [`lint_level`]: rustc_middle::lint::lint_level#decorate-signature + #[rustc_lint_diagnostics] + pub fn opt_span_lint_with_diagnostics( + &self, + lint: &'static Lint, + span: Option, + diagnostic: BuiltinLintDiag, + ) { + self.opt_span_lint(lint, span, |diag| { diagnostics::decorate_lint(self.sess(), diagnostic, diag); }); } diff --git a/compiler/rustc_lint/src/early.rs b/compiler/rustc_lint/src/early.rs index 329221612b587..1820f7bbe4821 100644 --- a/compiler/rustc_lint/src/early.rs +++ b/compiler/rustc_lint/src/early.rs @@ -46,7 +46,7 @@ impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> { fn inlined_check_id(&mut self, id: ast::NodeId) { for early_lint in self.context.buffered.take(id) { let BufferedEarlyLint { span, node_id: _, lint_id, diagnostic } = early_lint; - self.context.span_lint_with_diagnostics(lint_id.lint, span, diagnostic); + self.context.opt_span_lint_with_diagnostics(lint_id.lint, span, diagnostic); } } diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index b44eb25216770..7f6412342d5f4 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -754,7 +754,7 @@ pub enum BuiltinLintDiag { #[derive(Debug)] pub struct BufferedEarlyLint { /// The span of code that we are linting on. - pub span: MultiSpan, + pub span: Option, /// The `NodeId` of the AST node that generated the lint. pub node_id: NodeId, @@ -792,7 +792,7 @@ impl LintBuffer { self.add_early_lint(BufferedEarlyLint { lint_id: LintId::of(lint), node_id, - span: span.into(), + span: Some(span.into()), diagnostic, }); } diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index 200505aaea209..1554c3a4b6981 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -306,10 +306,20 @@ impl ParseSess { span: impl Into, node_id: NodeId, diagnostic: BuiltinLintDiag, + ) { + self.opt_span_buffer_lint(lint, Some(span.into()), node_id, diagnostic) + } + + pub fn opt_span_buffer_lint( + &self, + lint: &'static Lint, + span: Option, + node_id: NodeId, + diagnostic: BuiltinLintDiag, ) { self.buffered_lints.with_lock(|buffered_lints| { buffered_lints.push(BufferedEarlyLint { - span: span.into(), + span, node_id, lint_id: LintId::of(lint), diagnostic, From 4fc8318dcc79154504afcf523da78ab08a278ca8 Mon Sep 17 00:00:00 2001 From: Urgau Date: Sat, 8 Jun 2024 13:26:37 +0200 Subject: [PATCH 04/12] Disallow setting built-in cfgs via set the command-line --- compiler/rustc_lint/messages.ftl | 4 ++ .../rustc_lint/src/context/diagnostics.rs | 3 + compiler/rustc_lint/src/lints.rs | 10 +++ compiler/rustc_lint_defs/src/builtin.rs | 34 ++++++++++ compiler/rustc_lint_defs/src/lib.rs | 5 ++ compiler/rustc_session/src/config.rs | 5 +- compiler/rustc_session/src/config/cfg.rs | 65 +++++++++++++++++++ tests/codegen/aarch64-struct-align-128.rs | 14 ++-- tests/codegen/default-requires-uwtable.rs | 10 +-- tests/codegen/repr/transparent-sysv64.rs | 6 +- tests/debuginfo/thread-names.rs | 4 +- tests/ui/cfg/disallowed-cli-cfgs-allow.rs | 4 ++ ...sallowed-cli-cfgs.debug_assertions_.stderr | 8 +++ ...isallowed-cli-cfgs.overflow_checks_.stderr | 8 +++ .../ui/cfg/disallowed-cli-cfgs.panic_.stderr | 8 +++ .../disallowed-cli-cfgs.proc_macro_.stderr | 8 +++ ...sallowed-cli-cfgs.relocation_model_.stderr | 8 +++ tests/ui/cfg/disallowed-cli-cfgs.rs | 35 ++++++++++ .../cfg/disallowed-cli-cfgs.sanitize_.stderr | 8 +++ ....sanitizer_cfi_generalize_pointers_.stderr | 8 +++ ...s.sanitizer_cfi_normalize_integers_.stderr | 8 +++ .../disallowed-cli-cfgs.target_abi_.stderr | 8 +++ .../disallowed-cli-cfgs.target_arch_.stderr | 8 +++ .../disallowed-cli-cfgs.target_endian_.stderr | 8 +++ .../disallowed-cli-cfgs.target_env_.stderr | 8 +++ .../disallowed-cli-cfgs.target_family_.stderr | 8 +++ ...disallowed-cli-cfgs.target_feature_.stderr | 8 +++ ...allowed-cli-cfgs.target_has_atomic_.stderr | 8 +++ ....target_has_atomic_equal_alignment_.stderr | 8 +++ ...-cfgs.target_has_atomic_load_store_.stderr | 8 +++ .../cfg/disallowed-cli-cfgs.target_os_.stderr | 8 +++ ...owed-cli-cfgs.target_pointer_width_.stderr | 8 +++ ...lowed-cli-cfgs.target_thread_local_.stderr | 8 +++ .../disallowed-cli-cfgs.target_vendor_.stderr | 8 +++ tests/ui/cfg/disallowed-cli-cfgs.test_.stderr | 8 +++ .../cfg/disallowed-cli-cfgs.ub_checks_.stderr | 8 +++ tests/ui/cfg/disallowed-cli-cfgs.unix_.stderr | 8 +++ .../cfg/disallowed-cli-cfgs.windows_.stderr | 8 +++ tests/ui/test-attrs/test-vs-cfg-test.rs | 2 +- 39 files changed, 382 insertions(+), 19 deletions(-) create mode 100644 tests/ui/cfg/disallowed-cli-cfgs-allow.rs create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.debug_assertions_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.overflow_checks_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.panic_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.proc_macro_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.relocation_model_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.rs create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.sanitize_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.sanitizer_cfi_generalize_pointers_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.sanitizer_cfi_normalize_integers_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.target_abi_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.target_arch_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.target_endian_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.target_env_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.target_family_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.target_feature_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.target_has_atomic_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.target_has_atomic_equal_alignment_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.target_has_atomic_load_store_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.target_os_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.target_pointer_width_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.target_thread_local_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.target_vendor_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.test_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.ub_checks_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.unix_.stderr create mode 100644 tests/ui/cfg/disallowed-cli-cfgs.windows_.stderr diff --git a/compiler/rustc_lint/messages.ftl b/compiler/rustc_lint/messages.ftl index 46cf87d1e3c17..6197407fe12fe 100644 --- a/compiler/rustc_lint/messages.ftl +++ b/compiler/rustc_lint/messages.ftl @@ -745,6 +745,10 @@ lint_undropped_manually_drops = calls to `std::mem::drop` with `std::mem::Manual .label = argument has type `{$arg_ty}` .suggestion = use `std::mem::ManuallyDrop::into_inner` to get the inner value +lint_unexpected_builtin_cfg = unexpected `--cfg {$cfg}` flag + .controlled_by = config `{$cfg_name}` is only supposed to be controlled by `{$controlled_by}` + .incoherent = manually setting a built-in cfg does create incoherent behaviors + lint_unexpected_cfg_add_build_rs_println = or consider adding `{$build_rs_println}` to the top of the `build.rs` lint_unexpected_cfg_add_cargo_feature = consider using a Cargo feature instead lint_unexpected_cfg_add_cargo_toml_lint_cfg = or consider adding in `Cargo.toml` the `check-cfg` lint config for the lint:{$cargo_toml_lint_cfg} diff --git a/compiler/rustc_lint/src/context/diagnostics.rs b/compiler/rustc_lint/src/context/diagnostics.rs index 05e075205c4b7..a494c0c15246d 100644 --- a/compiler/rustc_lint/src/context/diagnostics.rs +++ b/compiler/rustc_lint/src/context/diagnostics.rs @@ -437,5 +437,8 @@ pub(super) fn decorate_lint(sess: &Session, diagnostic: BuiltinLintDiag, diag: & BuiltinLintDiag::OutOfScopeMacroCalls { path } => { lints::OutOfScopeMacroCalls { path }.decorate_lint(diag) } + BuiltinLintDiag::UnexpectedBuiltinCfg { cfg, cfg_name, controlled_by } => { + lints::UnexpectedBuiltinCfg { cfg, cfg_name, controlled_by }.decorate_lint(diag) + } } } diff --git a/compiler/rustc_lint/src/lints.rs b/compiler/rustc_lint/src/lints.rs index 14084405d0ee1..c1ad23844cd0b 100644 --- a/compiler/rustc_lint/src/lints.rs +++ b/compiler/rustc_lint/src/lints.rs @@ -2321,6 +2321,16 @@ pub mod unexpected_cfg_value { } } +#[derive(LintDiagnostic)] +#[diag(lint_unexpected_builtin_cfg)] +#[note(lint_controlled_by)] +#[note(lint_incoherent)] +pub struct UnexpectedBuiltinCfg { + pub(crate) cfg: String, + pub(crate) cfg_name: Symbol, + pub(crate) controlled_by: &'static str, +} + #[derive(LintDiagnostic)] #[diag(lint_macro_use_deprecated)] #[help] diff --git a/compiler/rustc_lint_defs/src/builtin.rs b/compiler/rustc_lint_defs/src/builtin.rs index a023d6161df0c..d39b35d2a7605 100644 --- a/compiler/rustc_lint_defs/src/builtin.rs +++ b/compiler/rustc_lint_defs/src/builtin.rs @@ -105,6 +105,7 @@ declare_lint_pass! { UNCONDITIONAL_RECURSION, UNCOVERED_PARAM_IN_PROJECTION, UNDEFINED_NAKED_FUNCTION_ABI, + UNEXPECTED_BUILTIN_CFGS, UNEXPECTED_CFGS, UNFULFILLED_LINT_EXPECTATIONS, UNINHABITED_STATIC, @@ -3269,6 +3270,39 @@ declare_lint! { "detects unexpected names and values in `#[cfg]` conditions", } +declare_lint! { + /// The `unexpected_builtin_cfgs` lint detects builtin cfgs set via the `--cfg` flag. + /// + /// ### Example + /// + /// ```text + /// rustc --cfg unix + /// ``` + /// + /// ```rust,ignore (needs command line option) + /// fn main() {} + /// ``` + /// + /// This will produce: + /// + /// ```text + /// error: unexpected `--cfg unix` flag + /// | + /// = note: config `unix` is only supposed to be controlled by `--target` + /// = note: manually setting a built-in cfg does create incoherent behaviors + /// = note: `#[deny(unexpected_builtin_cfgs)]` on by default + /// ``` + /// + /// ### Explanation + /// + /// Setting builtin cfgs can and does produce incoherent behavior, it's better to the use + /// the appropriate `rustc` flag that controls the config. For example setting the `windows` + /// cfg but on Linux based target. + pub UNEXPECTED_BUILTIN_CFGS, + Deny, + "detects builtin cfgs set via the `--cfg`" +} + declare_lint! { /// The `repr_transparent_external_private_fields` lint /// detects types marked `#[repr(transparent)]` that (transitively) diff --git a/compiler/rustc_lint_defs/src/lib.rs b/compiler/rustc_lint_defs/src/lib.rs index 7f6412342d5f4..009b93d13a5c3 100644 --- a/compiler/rustc_lint_defs/src/lib.rs +++ b/compiler/rustc_lint_defs/src/lib.rs @@ -747,6 +747,11 @@ pub enum BuiltinLintDiag { OutOfScopeMacroCalls { path: String, }, + UnexpectedBuiltinCfg { + cfg: String, + cfg_name: Symbol, + controlled_by: &'static str, + }, } /// Lints that are buffered up early on in the `Session` before the diff --git a/compiler/rustc_session/src/config.rs b/compiler/rustc_session/src/config.rs index 839cc51efcea8..18bb4bea93d17 100644 --- a/compiler/rustc_session/src/config.rs +++ b/compiler/rustc_session/src/config.rs @@ -1299,7 +1299,10 @@ pub(crate) const fn default_lib_output() -> CrateType { } pub fn build_configuration(sess: &Session, mut user_cfg: Cfg) -> Cfg { - // Combine the configuration requested by the session (command line) with + // First disallow some configuration given on the command line + cfg::disallow_cfgs(sess, &user_cfg); + + // Then combine the configuration requested by the session (command line) with // some default and generated configuration items. user_cfg.extend(cfg::default_configuration(sess)); user_cfg diff --git a/compiler/rustc_session/src/config/cfg.rs b/compiler/rustc_session/src/config/cfg.rs index 2fa04bbe345e8..60a1be944ae57 100644 --- a/compiler/rustc_session/src/config/cfg.rs +++ b/compiler/rustc_session/src/config/cfg.rs @@ -17,9 +17,13 @@ //! - Add the activation logic in [`default_configuration`] //! - Add the cfg to [`CheckCfg::fill_well_known`] (and related files), //! so that the compiler can know the cfg is expected +//! - Add the cfg in [`disallow_cfgs`] to disallow users from setting it via `--cfg` //! - Add the feature gating in `compiler/rustc_feature/src/builtin_attrs.rs` +use rustc_ast::ast; use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexSet}; +use rustc_lint_defs::builtin::UNEXPECTED_BUILTIN_CFGS; +use rustc_lint_defs::BuiltinLintDiag; use rustc_span::symbol::{sym, Symbol}; use rustc_target::abi::Align; use rustc_target::spec::{PanicStrategy, RelocModel, SanitizerSet}; @@ -83,6 +87,67 @@ impl<'a, T: Eq + Hash + Copy + 'a> Extend<&'a T> for ExpectedValues { } } +/// Disallow builtin cfgs from the CLI. +pub(crate) fn disallow_cfgs(sess: &Session, user_cfgs: &Cfg) { + let disallow = |cfg: &(Symbol, Option), controlled_by| { + let cfg_name = cfg.0; + let cfg = if let Some(value) = cfg.1 { + format!(r#"{}="{}""#, cfg_name, value) + } else { + format!("{}", cfg_name) + }; + sess.psess.opt_span_buffer_lint( + UNEXPECTED_BUILTIN_CFGS, + None, + ast::CRATE_NODE_ID, + BuiltinLintDiag::UnexpectedBuiltinCfg { cfg, cfg_name, controlled_by }, + ) + }; + + // We want to restrict setting builtin cfgs that will produce incoherent behavior + // between the cfg and the rustc cli flag that sets it. + // + // The tests are in tests/ui/cfg/disallowed-cli-cfgs.rs. + + // By-default all builtin cfgs are disallowed, only those are allowed: + // - test: as it makes sense to the have the `test` cfg active without the builtin + // test harness. See Cargo `harness = false` config. + // + // Cargo `--cfg test`: https://github.com/rust-lang/cargo/blob/bc89bffa5987d4af8f71011c7557119b39e44a65/src/cargo/core/compiler/mod.rs#L1124 + + for cfg in user_cfgs { + match cfg { + (sym::overflow_checks, None) => disallow(cfg, "-C overflow-checks"), + (sym::debug_assertions, None) => disallow(cfg, "-C debug-assertions"), + (sym::ub_checks, None) => disallow(cfg, "-Z ub-checks"), + (sym::sanitize, None | Some(_)) => disallow(cfg, "-Z sanitizer"), + ( + sym::sanitizer_cfi_generalize_pointers | sym::sanitizer_cfi_normalize_integers, + None | Some(_), + ) => disallow(cfg, "-Z sanitizer=cfi"), + (sym::proc_macro, None) => disallow(cfg, "--crate-type proc-macro"), + (sym::panic, Some(sym::abort | sym::unwind)) => disallow(cfg, "-C panic"), + (sym::target_feature, Some(_)) => disallow(cfg, "-C target-feature"), + (sym::unix, None) + | (sym::windows, None) + | (sym::relocation_model, Some(_)) + | (sym::target_abi, None | Some(_)) + | (sym::target_arch, Some(_)) + | (sym::target_endian, Some(_)) + | (sym::target_env, None | Some(_)) + | (sym::target_family, Some(_)) + | (sym::target_os, Some(_)) + | (sym::target_pointer_width, Some(_)) + | (sym::target_vendor, None | Some(_)) + | (sym::target_has_atomic, Some(_)) + | (sym::target_has_atomic_equal_alignment, Some(_)) + | (sym::target_has_atomic_load_store, Some(_)) + | (sym::target_thread_local, None) => disallow(cfg, "--target"), + _ => {} + } + } +} + /// Generate the default configs for a given session pub(crate) fn default_configuration(sess: &Session) -> Cfg { let mut ret = Cfg::default(); diff --git a/tests/codegen/aarch64-struct-align-128.rs b/tests/codegen/aarch64-struct-align-128.rs index d1b4132d501f7..1d9307c32d6d0 100644 --- a/tests/codegen/aarch64-struct-align-128.rs +++ b/tests/codegen/aarch64-struct-align-128.rs @@ -1,12 +1,12 @@ // Test that structs aligned to 128 bits are passed with the correct ABI on aarch64. -//@ revisions:linux darwin windows +//@ revisions: linux darwin win //@[linux] compile-flags: --target aarch64-unknown-linux-gnu //@[darwin] compile-flags: --target aarch64-apple-darwin -//@[windows] compile-flags: --target aarch64-pc-windows-msvc +//@[win] compile-flags: --target aarch64-pc-windows-msvc //@[linux] needs-llvm-components: aarch64 //@[darwin] needs-llvm-components: aarch64 -//@[windows] needs-llvm-components: aarch64 +//@[win] needs-llvm-components: aarch64 #![feature(no_core, lang_items)] #![crate_type = "lib"] @@ -41,7 +41,7 @@ pub struct Wrapped8 { extern "C" { // linux: declare void @test_8([2 x i64], [2 x i64], [2 x i64]) // darwin: declare void @test_8([2 x i64], [2 x i64], [2 x i64]) - // windows: declare void @test_8([2 x i64], [2 x i64], [2 x i64]) + // win: declare void @test_8([2 x i64], [2 x i64], [2 x i64]) fn test_8(a: Align8, b: Transparent8, c: Wrapped8); } @@ -71,7 +71,7 @@ pub struct Wrapped16 { extern "C" { // linux: declare void @test_16([2 x i64], [2 x i64], i128) // darwin: declare void @test_16(i128, i128, i128) - // windows: declare void @test_16(i128, i128, i128) + // win: declare void @test_16(i128, i128, i128) fn test_16(a: Align16, b: Transparent16, c: Wrapped16); } @@ -96,7 +96,7 @@ pub struct WrappedI128 { extern "C" { // linux: declare void @test_i128(i128, i128, i128) // darwin: declare void @test_i128(i128, i128, i128) - // windows: declare void @test_i128(i128, i128, i128) + // win: declare void @test_i128(i128, i128, i128) fn test_i128(a: I128, b: TransparentI128, c: WrappedI128); } @@ -123,7 +123,7 @@ pub struct WrappedPacked { extern "C" { // linux: declare void @test_packed([2 x i64], [2 x i64], [2 x i64]) // darwin: declare void @test_packed([2 x i64], [2 x i64], [2 x i64]) - // windows: declare void @test_packed([2 x i64], [2 x i64], [2 x i64]) + // win: declare void @test_packed([2 x i64], [2 x i64], [2 x i64]) fn test_packed(a: Packed, b: TransparentPacked, c: WrappedPacked); } diff --git a/tests/codegen/default-requires-uwtable.rs b/tests/codegen/default-requires-uwtable.rs index 567bd55ecc3f2..3cb35cea022a5 100644 --- a/tests/codegen/default-requires-uwtable.rs +++ b/tests/codegen/default-requires-uwtable.rs @@ -1,9 +1,9 @@ -//@ revisions: WINDOWS ANDROID +//@ revisions: WINDOWS_ ANDROID_ //@ compile-flags: -C panic=abort -Copt-level=0 -//@ [WINDOWS] compile-flags: --target=x86_64-pc-windows-msvc -//@ [WINDOWS] needs-llvm-components: x86 -//@ [ANDROID] compile-flags: --target=armv7-linux-androideabi -//@ [ANDROID] needs-llvm-components: arm +//@ [WINDOWS_] compile-flags: --target=x86_64-pc-windows-msvc +//@ [WINDOWS_] needs-llvm-components: x86 +//@ [ANDROID_] compile-flags: --target=armv7-linux-androideabi +//@ [ANDROID_] needs-llvm-components: arm #![feature(no_core, lang_items)] #![crate_type = "lib"] diff --git a/tests/codegen/repr/transparent-sysv64.rs b/tests/codegen/repr/transparent-sysv64.rs index afb06dcc1bdf7..068414976c523 100644 --- a/tests/codegen/repr/transparent-sysv64.rs +++ b/tests/codegen/repr/transparent-sysv64.rs @@ -1,12 +1,12 @@ -//@ revisions: linux apple windows +//@ revisions: linux apple win //@ compile-flags: -O -C no-prepopulate-passes //@[linux] compile-flags: --target x86_64-unknown-linux-gnu //@[linux] needs-llvm-components: x86 //@[apple] compile-flags: --target x86_64-apple-darwin //@[apple] needs-llvm-components: x86 -//@[windows] compile-flags: --target x86_64-pc-windows-msvc -//@[windows] needs-llvm-components: x86 +//@[win] compile-flags: --target x86_64-pc-windows-msvc +//@[win] needs-llvm-components: x86 #![feature(no_core, lang_items)] #![crate_type = "lib"] diff --git a/tests/debuginfo/thread-names.rs b/tests/debuginfo/thread-names.rs index 1b9ada6fc52dd..6b3b0c7f4b231 100644 --- a/tests/debuginfo/thread-names.rs +++ b/tests/debuginfo/thread-names.rs @@ -1,8 +1,8 @@ //@ compile-flags:-g -//@ revisions: macos windows +//@ revisions: macos win // We can't set the main thread name on Linux because it renames the process (#97191) //@[macos] only-macos -//@[windows] only-windows +//@[win] only-windows //@ ignore-sgx //@ ignore-windows-gnu diff --git a/tests/ui/cfg/disallowed-cli-cfgs-allow.rs b/tests/ui/cfg/disallowed-cli-cfgs-allow.rs new file mode 100644 index 0000000000000..83fe19958a38f --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs-allow.rs @@ -0,0 +1,4 @@ +//@ check-pass +//@ compile-flags: --cfg unix -Aunexpected_builtin_cfgs + +fn main() {} diff --git a/tests/ui/cfg/disallowed-cli-cfgs.debug_assertions_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.debug_assertions_.stderr new file mode 100644 index 0000000000000..6aa84d9a2d858 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.debug_assertions_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg debug_assertions` flag + | + = note: config `debug_assertions` is only supposed to be controlled by `-C debug-assertions` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.overflow_checks_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.overflow_checks_.stderr new file mode 100644 index 0000000000000..05b420d32872c --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.overflow_checks_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg overflow_checks` flag + | + = note: config `overflow_checks` is only supposed to be controlled by `-C overflow-checks` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.panic_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.panic_.stderr new file mode 100644 index 0000000000000..dce88bb031d74 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.panic_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg panic="abort"` flag + | + = note: config `panic` is only supposed to be controlled by `-C panic` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.proc_macro_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.proc_macro_.stderr new file mode 100644 index 0000000000000..357b5baa1599b --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.proc_macro_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg proc_macro` flag + | + = note: config `proc_macro` is only supposed to be controlled by `--crate-type proc-macro` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.relocation_model_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.relocation_model_.stderr new file mode 100644 index 0000000000000..f11955a3ee5f5 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.relocation_model_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg relocation_model="a"` flag + | + = note: config `relocation_model` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.rs b/tests/ui/cfg/disallowed-cli-cfgs.rs new file mode 100644 index 0000000000000..714c01f4bc6ed --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.rs @@ -0,0 +1,35 @@ +//@ check-fail +//@ revisions: overflow_checks_ debug_assertions_ ub_checks_ sanitize_ +//@ revisions: sanitizer_cfi_generalize_pointers_ sanitizer_cfi_normalize_integers_ +//@ revisions: proc_macro_ panic_ target_feature_ unix_ windows_ target_abi_ +//@ revisions: target_arch_ target_endian_ target_env_ target_family_ target_os_ +//@ revisions: target_pointer_width_ target_vendor_ target_has_atomic_ +//@ revisions: target_has_atomic_equal_alignment_ target_has_atomic_load_store_ +//@ revisions: target_thread_local_ relocation_model_ + +//@ [overflow_checks_]compile-flags: --cfg overflow_checks +//@ [debug_assertions_]compile-flags: --cfg debug_assertions +//@ [ub_checks_]compile-flags: --cfg ub_checks +//@ [sanitize_]compile-flags: --cfg sanitize="cfi" +//@ [sanitizer_cfi_generalize_pointers_]compile-flags: --cfg sanitizer_cfi_generalize_pointers +//@ [sanitizer_cfi_normalize_integers_]compile-flags: --cfg sanitizer_cfi_normalize_integers +//@ [proc_macro_]compile-flags: --cfg proc_macro +//@ [panic_]compile-flags: --cfg panic="abort" +//@ [target_feature_]compile-flags: --cfg target_feature="sse3" +//@ [unix_]compile-flags: --cfg unix +//@ [windows_]compile-flags: --cfg windows +//@ [target_abi_]compile-flags: --cfg target_abi="gnu" +//@ [target_arch_]compile-flags: --cfg target_arch="arm" +//@ [target_endian_]compile-flags: --cfg target_endian="little" +//@ [target_env_]compile-flags: --cfg target_env +//@ [target_family_]compile-flags: --cfg target_family="unix" +//@ [target_os_]compile-flags: --cfg target_os="linux" +//@ [target_pointer_width_]compile-flags: --cfg target_pointer_width="32" +//@ [target_vendor_]compile-flags: --cfg target_vendor +//@ [target_has_atomic_]compile-flags: --cfg target_has_atomic="32" +//@ [target_has_atomic_equal_alignment_]compile-flags: --cfg target_has_atomic_equal_alignment="32" +//@ [target_has_atomic_load_store_]compile-flags: --cfg target_has_atomic_load_store="32" +//@ [target_thread_local_]compile-flags: --cfg target_thread_local +//@ [relocation_model_]compile-flags: --cfg relocation_model="a" + +fn main() {} diff --git a/tests/ui/cfg/disallowed-cli-cfgs.sanitize_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.sanitize_.stderr new file mode 100644 index 0000000000000..d23c3ac5080a6 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.sanitize_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg sanitize="cfi"` flag + | + = note: config `sanitize` is only supposed to be controlled by `-Z sanitizer` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.sanitizer_cfi_generalize_pointers_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.sanitizer_cfi_generalize_pointers_.stderr new file mode 100644 index 0000000000000..6352586147238 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.sanitizer_cfi_generalize_pointers_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg sanitizer_cfi_generalize_pointers` flag + | + = note: config `sanitizer_cfi_generalize_pointers` is only supposed to be controlled by `-Z sanitizer=cfi` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.sanitizer_cfi_normalize_integers_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.sanitizer_cfi_normalize_integers_.stderr new file mode 100644 index 0000000000000..4736321388ba1 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.sanitizer_cfi_normalize_integers_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg sanitizer_cfi_normalize_integers` flag + | + = note: config `sanitizer_cfi_normalize_integers` is only supposed to be controlled by `-Z sanitizer=cfi` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.target_abi_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.target_abi_.stderr new file mode 100644 index 0000000000000..35810b4e3cc1c --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.target_abi_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg target_abi="gnu"` flag + | + = note: config `target_abi` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.target_arch_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.target_arch_.stderr new file mode 100644 index 0000000000000..0882b6bdcedca --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.target_arch_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg target_arch="arm"` flag + | + = note: config `target_arch` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.target_endian_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.target_endian_.stderr new file mode 100644 index 0000000000000..d6aa01a685202 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.target_endian_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg target_endian="little"` flag + | + = note: config `target_endian` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.target_env_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.target_env_.stderr new file mode 100644 index 0000000000000..2ab305927e39d --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.target_env_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg target_env` flag + | + = note: config `target_env` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.target_family_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.target_family_.stderr new file mode 100644 index 0000000000000..e1c21261328d1 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.target_family_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg target_family="unix"` flag + | + = note: config `target_family` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.target_feature_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.target_feature_.stderr new file mode 100644 index 0000000000000..37385b49f7971 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.target_feature_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg target_feature="sse3"` flag + | + = note: config `target_feature` is only supposed to be controlled by `-C target-feature` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.target_has_atomic_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.target_has_atomic_.stderr new file mode 100644 index 0000000000000..7eb9da5373c8d --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.target_has_atomic_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg target_has_atomic="32"` flag + | + = note: config `target_has_atomic` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.target_has_atomic_equal_alignment_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.target_has_atomic_equal_alignment_.stderr new file mode 100644 index 0000000000000..34d6c3e67b959 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.target_has_atomic_equal_alignment_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg target_has_atomic_equal_alignment="32"` flag + | + = note: config `target_has_atomic_equal_alignment` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.target_has_atomic_load_store_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.target_has_atomic_load_store_.stderr new file mode 100644 index 0000000000000..ef5ab6236ea7c --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.target_has_atomic_load_store_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg target_has_atomic_load_store="32"` flag + | + = note: config `target_has_atomic_load_store` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.target_os_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.target_os_.stderr new file mode 100644 index 0000000000000..190008995662c --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.target_os_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg target_os="linux"` flag + | + = note: config `target_os` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.target_pointer_width_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.target_pointer_width_.stderr new file mode 100644 index 0000000000000..8516ef70986bc --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.target_pointer_width_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg target_pointer_width="32"` flag + | + = note: config `target_pointer_width` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.target_thread_local_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.target_thread_local_.stderr new file mode 100644 index 0000000000000..b09d01d606f18 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.target_thread_local_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg target_thread_local` flag + | + = note: config `target_thread_local` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.target_vendor_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.target_vendor_.stderr new file mode 100644 index 0000000000000..7cd122e16aa3c --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.target_vendor_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg target_vendor` flag + | + = note: config `target_vendor` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.test_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.test_.stderr new file mode 100644 index 0000000000000..96b5beb021062 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.test_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg test` flag + | + = note: config `test` is only supposed to be controlled by `--test` + = note: see for more information + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.ub_checks_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.ub_checks_.stderr new file mode 100644 index 0000000000000..aedc050f9b80f --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.ub_checks_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg ub_checks` flag + | + = note: config `ub_checks` is only supposed to be controlled by `-Z ub-checks` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.unix_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.unix_.stderr new file mode 100644 index 0000000000000..005a5758b65c4 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.unix_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg unix` flag + | + = note: config `unix` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/cfg/disallowed-cli-cfgs.windows_.stderr b/tests/ui/cfg/disallowed-cli-cfgs.windows_.stderr new file mode 100644 index 0000000000000..d9fc7142801a1 --- /dev/null +++ b/tests/ui/cfg/disallowed-cli-cfgs.windows_.stderr @@ -0,0 +1,8 @@ +error: unexpected `--cfg windows` flag + | + = note: config `windows` is only supposed to be controlled by `--target` + = note: manually setting a built-in cfg does create incoherent behaviors + = note: `#[deny(unexpected_builtin_cfgs)]` on by default + +error: aborting due to 1 previous error + diff --git a/tests/ui/test-attrs/test-vs-cfg-test.rs b/tests/ui/test-attrs/test-vs-cfg-test.rs index d7d9e61103c9a..2735303642fbe 100644 --- a/tests/ui/test-attrs/test-vs-cfg-test.rs +++ b/tests/ui/test-attrs/test-vs-cfg-test.rs @@ -1,5 +1,5 @@ //@ run-pass -//@ compile-flags: --cfg test +//@ compile-flags: --cfg test -Aunexpected_builtin_cfgs // Make sure `--cfg test` does not inject test harness From b6074fffd1d1a8d1eee4e3b9e9431761761b80c1 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Tue, 25 Jun 2024 19:03:39 +0300 Subject: [PATCH 05/12] resolve: Tweak some naming around import ambiguities --- .../src/effective_visibilities.rs | 2 +- compiler/rustc_resolve/src/imports.rs | 74 ++++++++----------- compiler/rustc_resolve/src/late.rs | 2 +- compiler/rustc_resolve/src/lib.rs | 14 ++-- 4 files changed, 42 insertions(+), 50 deletions(-) diff --git a/compiler/rustc_resolve/src/effective_visibilities.rs b/compiler/rustc_resolve/src/effective_visibilities.rs index aab4a3366daa5..dabed23883866 100644 --- a/compiler/rustc_resolve/src/effective_visibilities.rs +++ b/compiler/rustc_resolve/src/effective_visibilities.rs @@ -99,7 +99,7 @@ impl<'r, 'a, 'tcx> EffectiveVisibilitiesVisitor<'r, 'a, 'tcx> { // is the maximum value among visibilities of bindings corresponding to that def id. for (binding, eff_vis) in visitor.import_effective_visibilities.iter() { let NameBindingKind::Import { import, .. } = binding.kind else { unreachable!() }; - if !binding.is_ambiguity() { + if !binding.is_ambiguity_recursive() { if let Some(node_id) = import.id() { r.effective_visibilities.update_eff_vis(r.local_def_id(node_id), eff_vis, r.tcx) } diff --git a/compiler/rustc_resolve/src/imports.rs b/compiler/rustc_resolve/src/imports.rs index 96a4647b94281..3896fe4c4fa64 100644 --- a/compiler/rustc_resolve/src/imports.rs +++ b/compiler/rustc_resolve/src/imports.rs @@ -325,8 +325,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { } match (old_binding.is_glob_import(), binding.is_glob_import()) { (true, true) => { - // FIXME: remove `!binding.is_ambiguity()` after delete the warning ambiguity. - if !binding.is_ambiguity() + // FIXME: remove `!binding.is_ambiguity_recursive()` after delete the warning ambiguity. + if !binding.is_ambiguity_recursive() && let NameBindingKind::Import { import: old_import, .. } = old_binding.kind && let NameBindingKind::Import { import, .. } = binding.kind @@ -337,21 +337,17 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { // imported from the same glob-import statement. resolution.binding = Some(binding); } else if res != old_binding.res() { - let binding = if warn_ambiguity { - this.warn_ambiguity(AmbiguityKind::GlobVsGlob, old_binding, binding) - } else { - this.ambiguity(AmbiguityKind::GlobVsGlob, old_binding, binding) - }; - resolution.binding = Some(binding); + resolution.binding = Some(this.new_ambiguity_binding( + AmbiguityKind::GlobVsGlob, + old_binding, + binding, + warn_ambiguity, + )); } else if !old_binding.vis.is_at_least(binding.vis, this.tcx) { // We are glob-importing the same item but with greater visibility. resolution.binding = Some(binding); - } else if binding.is_ambiguity() { - resolution.binding = - Some(self.arenas.alloc_name_binding(NameBindingData { - warn_ambiguity: true, - ..(*binding).clone() - })); + } else if binding.is_ambiguity_recursive() { + resolution.binding = Some(this.new_warn_ambiguity_binding(binding)); } } (old_glob @ true, false) | (old_glob @ false, true) => { @@ -361,24 +357,26 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { && nonglob_binding.expansion != LocalExpnId::ROOT && glob_binding.res() != nonglob_binding.res() { - resolution.binding = Some(this.ambiguity( + resolution.binding = Some(this.new_ambiguity_binding( AmbiguityKind::GlobVsExpanded, nonglob_binding, glob_binding, + false, )); } else { resolution.binding = Some(nonglob_binding); } - if let Some(old_binding) = resolution.shadowed_glob { - assert!(old_binding.is_glob_import()); - if glob_binding.res() != old_binding.res() { - resolution.shadowed_glob = Some(this.ambiguity( + if let Some(old_shadowed_glob) = resolution.shadowed_glob { + assert!(old_shadowed_glob.is_glob_import()); + if glob_binding.res() != old_shadowed_glob.res() { + resolution.shadowed_glob = Some(this.new_ambiguity_binding( AmbiguityKind::GlobVsGlob, - old_binding, + old_shadowed_glob, glob_binding, + false, )); - } else if !old_binding.vis.is_at_least(binding.vis, this.tcx) { + } else if !old_shadowed_glob.vis.is_at_least(binding.vis, this.tcx) { resolution.shadowed_glob = Some(glob_binding); } } else { @@ -397,29 +395,21 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { }) } - fn ambiguity( + fn new_ambiguity_binding( &self, - kind: AmbiguityKind, + ambiguity_kind: AmbiguityKind, primary_binding: NameBinding<'a>, secondary_binding: NameBinding<'a>, + warn_ambiguity: bool, ) -> NameBinding<'a> { - self.arenas.alloc_name_binding(NameBindingData { - ambiguity: Some((secondary_binding, kind)), - ..(*primary_binding).clone() - }) + let ambiguity = Some((secondary_binding, ambiguity_kind)); + let data = NameBindingData { ambiguity, warn_ambiguity, ..*primary_binding }; + self.arenas.alloc_name_binding(data) } - fn warn_ambiguity( - &self, - kind: AmbiguityKind, - primary_binding: NameBinding<'a>, - secondary_binding: NameBinding<'a>, - ) -> NameBinding<'a> { - self.arenas.alloc_name_binding(NameBindingData { - ambiguity: Some((secondary_binding, kind)), - warn_ambiguity: true, - ..(*primary_binding).clone() - }) + fn new_warn_ambiguity_binding(&self, binding: NameBinding<'a>) -> NameBinding<'a> { + assert!(binding.is_ambiguity_recursive()); + self.arenas.alloc_name_binding(NameBindingData { warn_ambiguity: true, ..*binding }) } // Use `f` to mutate the resolution of the name in the module. @@ -1381,8 +1371,8 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { target_bindings[ns].get(), ) { Ok(other_binding) => { - is_redundant = - binding.res() == other_binding.res() && !other_binding.is_ambiguity(); + is_redundant = binding.res() == other_binding.res() + && !other_binding.is_ambiguity_recursive(); if is_redundant { redundant_span[ns] = Some((other_binding.span, other_binding.is_import())); @@ -1455,7 +1445,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { .resolution(import.parent_scope.module, key) .borrow() .binding() - .is_some_and(|binding| binding.is_warn_ambiguity()); + .is_some_and(|binding| binding.warn_ambiguity_recursive()); let _ = self.try_define( import.parent_scope.module, key, @@ -1480,7 +1470,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { module.for_each_child(self, |this, ident, _, binding| { let res = binding.res().expect_non_local(); - let error_ambiguity = binding.is_ambiguity() && !binding.warn_ambiguity; + let error_ambiguity = binding.is_ambiguity_recursive() && !binding.warn_ambiguity; if res != def::Res::Err && !error_ambiguity { let mut reexport_chain = SmallVec::new(); let mut next_binding = binding; diff --git a/compiler/rustc_resolve/src/late.rs b/compiler/rustc_resolve/src/late.rs index 5ab6ba23a7da6..66a1c05289b7d 100644 --- a/compiler/rustc_resolve/src/late.rs +++ b/compiler/rustc_resolve/src/late.rs @@ -3730,7 +3730,7 @@ impl<'a: 'ast, 'b, 'ast, 'tcx> LateResolutionVisitor<'a, 'b, 'ast, 'tcx> { let ls_binding = self.maybe_resolve_ident_in_lexical_scope(ident, ValueNS)?; let (res, binding) = match ls_binding { LexicalScopeBinding::Item(binding) - if is_syntactic_ambiguity && binding.is_ambiguity() => + if is_syntactic_ambiguity && binding.is_ambiguity_recursive() => { // For ambiguous bindings we don't know all their definitions and cannot check // whether they can be shadowed by fresh bindings or not, so force an error. diff --git a/compiler/rustc_resolve/src/lib.rs b/compiler/rustc_resolve/src/lib.rs index 3a831a7f19e06..94cdce1025fe5 100644 --- a/compiler/rustc_resolve/src/lib.rs +++ b/compiler/rustc_resolve/src/lib.rs @@ -694,10 +694,12 @@ impl<'a> fmt::Debug for Module<'a> { } /// Records a possibly-private value, type, or module definition. -#[derive(Clone, Debug)] +#[derive(Clone, Copy, Debug)] struct NameBindingData<'a> { kind: NameBindingKind<'a>, ambiguity: Option<(NameBinding<'a>, AmbiguityKind)>, + /// Produce a warning instead of an error when reporting ambiguities inside this binding. + /// May apply to indirect ambiguities under imports, so `ambiguity.is_some()` is not required. warn_ambiguity: bool, expansion: LocalExpnId, span: Span, @@ -718,7 +720,7 @@ impl<'a> ToNameBinding<'a> for NameBinding<'a> { } } -#[derive(Clone, Debug)] +#[derive(Clone, Copy, Debug)] enum NameBindingKind<'a> { Res(Res), Module(Module<'a>), @@ -830,18 +832,18 @@ impl<'a> NameBindingData<'a> { } } - fn is_ambiguity(&self) -> bool { + fn is_ambiguity_recursive(&self) -> bool { self.ambiguity.is_some() || match self.kind { - NameBindingKind::Import { binding, .. } => binding.is_ambiguity(), + NameBindingKind::Import { binding, .. } => binding.is_ambiguity_recursive(), _ => false, } } - fn is_warn_ambiguity(&self) -> bool { + fn warn_ambiguity_recursive(&self) -> bool { self.warn_ambiguity || match self.kind { - NameBindingKind::Import { binding, .. } => binding.is_warn_ambiguity(), + NameBindingKind::Import { binding, .. } => binding.warn_ambiguity_recursive(), _ => false, } } From 6402909f42566cfee84b8b66aec409adfcfc1e85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9my=20Rakic?= Date: Tue, 25 Jun 2024 19:55:06 +0000 Subject: [PATCH 06/12] delay bug in RPITIT refinement checking with resolution errors --- .../src/check/compare_impl_item/refine.rs | 8 +++---- .../in-trait/refine-resolution-errors.rs | 23 +++++++++++++++++++ .../in-trait/refine-resolution-errors.stderr | 16 +++++++++++++ 3 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 tests/ui/impl-trait/in-trait/refine-resolution-errors.rs create mode 100644 tests/ui/impl-trait/in-trait/refine-resolution-errors.stderr diff --git a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs index 6cdbd692f73be..ad3324f79e271 100644 --- a/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs +++ b/compiler/rustc_hir_analysis/src/check/compare_impl_item/refine.rs @@ -171,10 +171,10 @@ pub(super) fn check_refining_return_position_impl_trait_in_trait<'tcx>( } // Resolve any lifetime variables that may have been introduced during normalization. let Ok((trait_bounds, impl_bounds)) = infcx.fully_resolve((trait_bounds, impl_bounds)) else { - // This code path is not reached in any tests, but may be reachable. If - // this is triggered, it should be converted to `delayed_bug` and the - // triggering case turned into a test. - tcx.dcx().bug("encountered errors when checking RPITIT refinement (resolution)"); + // If resolution didn't fully complete, we cannot continue checking RPITIT refinement, and + // delay a bug as the original code contains load-bearing errors. + tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (resolution)"); + return; }; // For quicker lookup, use an `IndexSet` (we don't use one earlier because diff --git a/tests/ui/impl-trait/in-trait/refine-resolution-errors.rs b/tests/ui/impl-trait/in-trait/refine-resolution-errors.rs new file mode 100644 index 0000000000000..a9936c7bc3fee --- /dev/null +++ b/tests/ui/impl-trait/in-trait/refine-resolution-errors.rs @@ -0,0 +1,23 @@ +// This is a non-regression test for issue #126670 where RPITIT refinement checking encountered +// errors during resolution and ICEd. + +//@ edition: 2018 + +pub trait Mirror { + type Assoc; +} +impl Mirror for () { + //~^ ERROR the type parameter `T` is not constrained + type Assoc = T; +} + +pub trait First { + async fn first() -> <() as Mirror>::Assoc; + //~^ ERROR type annotations needed +} + +impl First for () { + async fn first() {} +} + +fn main() {} diff --git a/tests/ui/impl-trait/in-trait/refine-resolution-errors.stderr b/tests/ui/impl-trait/in-trait/refine-resolution-errors.stderr new file mode 100644 index 0000000000000..0f5573dda04c1 --- /dev/null +++ b/tests/ui/impl-trait/in-trait/refine-resolution-errors.stderr @@ -0,0 +1,16 @@ +error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates + --> $DIR/refine-resolution-errors.rs:9:6 + | +LL | impl Mirror for () { + | ^ unconstrained type parameter + +error[E0282]: type annotations needed + --> $DIR/refine-resolution-errors.rs:15:5 + | +LL | async fn first() -> <() as Mirror>::Assoc; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot infer type + +error: aborting due to 2 previous errors + +Some errors have detailed explanations: E0207, E0282. +For more information about an error, try `rustc --explain E0207`. From 133e7b10a45bddd4ef5ba265d848ce0a1976e8ae Mon Sep 17 00:00:00 2001 From: The 8472 Date: Sun, 23 Jun 2024 22:16:22 +0200 Subject: [PATCH 07/12] fix Drop items getting leaked in Filter::next_chunk The optimization only makes sense for non-drop elements anyway. Use the default implementation for items that are Drop instead. It also simplifies the implementation. --- library/core/src/iter/adapters/filter.rs | 88 ++++++++++++------------ 1 file changed, 43 insertions(+), 45 deletions(-) diff --git a/library/core/src/iter/adapters/filter.rs b/library/core/src/iter/adapters/filter.rs index ca23d1b13a88b..1c99f3938e270 100644 --- a/library/core/src/iter/adapters/filter.rs +++ b/library/core/src/iter/adapters/filter.rs @@ -3,7 +3,7 @@ use crate::iter::{adapters::SourceIter, FusedIterator, InPlaceIterable, TrustedF use crate::num::NonZero; use crate::ops::Try; use core::array; -use core::mem::{ManuallyDrop, MaybeUninit}; +use core::mem::MaybeUninit; use core::ops::ControlFlow; /// An iterator that filters the elements of `iter` with `predicate`. @@ -27,6 +27,41 @@ impl Filter { } } +impl Filter +where + I: Iterator, + P: FnMut(&I::Item) -> bool, +{ + #[inline] + fn next_chunk_dropless( + &mut self, + ) -> Result<[I::Item; N], array::IntoIter> { + let mut array: [MaybeUninit; N] = [const { MaybeUninit::uninit() }; N]; + let mut initialized = 0; + + let result = self.iter.try_for_each(|element| { + let idx = initialized; + initialized = idx + (self.predicate)(&element) as usize; + + // SAFETY: Loop conditions ensure the index is in bounds. + unsafe { array.get_unchecked_mut(idx) }.write(element); + + if initialized < N { ControlFlow::Continue(()) } else { ControlFlow::Break(()) } + }); + + match result { + ControlFlow::Break(()) => { + // SAFETY: The loop above is only explicitly broken when the array has been fully initialized + Ok(unsafe { MaybeUninit::array_assume_init(array) }) + } + ControlFlow::Continue(()) => { + // SAFETY: The range is in bounds since the loop breaks when reaching N elements. + Err(unsafe { array::IntoIter::new_unchecked(array, 0..initialized) }) + } + } + } +} + #[stable(feature = "core_impl_debug", since = "1.9.0")] impl fmt::Debug for Filter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { @@ -64,52 +99,15 @@ where fn next_chunk( &mut self, ) -> Result<[Self::Item; N], array::IntoIter> { - let mut array: [MaybeUninit; N] = [const { MaybeUninit::uninit() }; N]; - - struct Guard<'a, T> { - array: &'a mut [MaybeUninit], - initialized: usize, - } - - impl Drop for Guard<'_, T> { - #[inline] - fn drop(&mut self) { - if const { crate::mem::needs_drop::() } { - // SAFETY: self.initialized is always <= N, which also is the length of the array. - unsafe { - core::ptr::drop_in_place(MaybeUninit::slice_assume_init_mut( - self.array.get_unchecked_mut(..self.initialized), - )); - } - } + let fun = const { + if crate::mem::needs_drop::() { + array::iter_next_chunk:: + } else { + Self::next_chunk_dropless:: } - } - - let mut guard = Guard { array: &mut array, initialized: 0 }; - - let result = self.iter.try_for_each(|element| { - let idx = guard.initialized; - guard.initialized = idx + (self.predicate)(&element) as usize; - - // SAFETY: Loop conditions ensure the index is in bounds. - unsafe { guard.array.get_unchecked_mut(idx) }.write(element); - - if guard.initialized < N { ControlFlow::Continue(()) } else { ControlFlow::Break(()) } - }); + }; - let guard = ManuallyDrop::new(guard); - - match result { - ControlFlow::Break(()) => { - // SAFETY: The loop above is only explicitly broken when the array has been fully initialized - Ok(unsafe { MaybeUninit::array_assume_init(array) }) - } - ControlFlow::Continue(()) => { - let initialized = guard.initialized; - // SAFETY: The range is in bounds since the loop breaks when reaching N elements. - Err(unsafe { array::IntoIter::new_unchecked(array, 0..initialized) }) - } - } + fun(self) } #[inline] From 2be2d77c501730caedae8db2f0a0f02db57ae505 Mon Sep 17 00:00:00 2001 From: The 8472 Date: Mon, 24 Jun 2024 19:56:22 +0200 Subject: [PATCH 08/12] add comments explaining optimizations for Filter::next_chunk --- library/core/src/iter/adapters/filter.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/library/core/src/iter/adapters/filter.rs b/library/core/src/iter/adapters/filter.rs index 1c99f3938e270..ba49070329c22 100644 --- a/library/core/src/iter/adapters/filter.rs +++ b/library/core/src/iter/adapters/filter.rs @@ -41,8 +41,9 @@ where let result = self.iter.try_for_each(|element| { let idx = initialized; + // branchless index update combined with unconditionally copying the value even when + // it is filtered reduces branching and dependencies in the loop. initialized = idx + (self.predicate)(&element) as usize; - // SAFETY: Loop conditions ensure the index is in bounds. unsafe { array.get_unchecked_mut(idx) }.write(element); @@ -99,6 +100,7 @@ where fn next_chunk( &mut self, ) -> Result<[Self::Item; N], array::IntoIter> { + // avoid codegen for the dead branch let fun = const { if crate::mem::needs_drop::() { array::iter_next_chunk:: From 0d7aef9738b25ed4f84d11deb0add8d5345613b0 Mon Sep 17 00:00:00 2001 From: The 8472 Date: Tue, 25 Jun 2024 23:22:27 +0200 Subject: [PATCH 09/12] regression test for leaks in the the Filter::next_chunk implementation previously next_chunk would forget items rejected by the filter --- library/core/tests/iter/adapters/filter.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/library/core/tests/iter/adapters/filter.rs b/library/core/tests/iter/adapters/filter.rs index a2050d89d8564..167851e33336e 100644 --- a/library/core/tests/iter/adapters/filter.rs +++ b/library/core/tests/iter/adapters/filter.rs @@ -1,4 +1,5 @@ use core::iter::*; +use std::rc::Rc; #[test] fn test_iterator_filter_count() { @@ -50,3 +51,15 @@ fn test_double_ended_filter() { assert_eq!(it.next().unwrap(), &2); assert_eq!(it.next_back(), None); } + +#[test] +fn test_next_chunk_does_not_leak() { + let drop_witness: [_; 5] = std::array::from_fn(|_| Rc::new(())); + + let v = (0..5).map(|i| drop_witness[i].clone()).collect::>(); + let _ = v.into_iter().filter(|_| false).next_chunk::<1>(); + + for ref w in drop_witness { + assert_eq!(Rc::strong_count(w), 1); + } +} From 275d922dab9c98d3a8f01f79d3f2381f26a4a99b Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Fri, 21 Jun 2024 12:39:55 -0400 Subject: [PATCH 10/12] Rename tcx to cx --- .../src/solve/alias_relate.rs | 6 +- .../src/solve/assembly/mod.rs | 85 ++++---- .../src/solve/assembly/structural_traits.rs | 112 +++++----- .../src/solve/eval_ctxt/mod.rs | 22 +- .../src/solve/inspect/build.rs | 4 +- .../rustc_next_trait_solver/src/solve/mod.rs | 12 +- .../src/solve/normalizes_to/inherent.rs | 18 +- .../src/solve/normalizes_to/mod.rs | 199 +++++++++--------- .../src/solve/normalizes_to/opaque_types.rs | 6 +- .../src/solve/normalizes_to/weak_types.rs | 10 +- .../src/solve/project_goals.rs | 6 +- .../src/solve/search_graph.rs | 60 +++--- .../src/solve/trait_goals.rs | 140 ++++++------ 13 files changed, 333 insertions(+), 347 deletions(-) diff --git a/compiler/rustc_next_trait_solver/src/solve/alias_relate.rs b/compiler/rustc_next_trait_solver/src/solve/alias_relate.rs index 5a95f4edf1915..d8c1dc8b4e9f3 100644 --- a/compiler/rustc_next_trait_solver/src/solve/alias_relate.rs +++ b/compiler/rustc_next_trait_solver/src/solve/alias_relate.rs @@ -32,14 +32,14 @@ where &mut self, goal: Goal, ) -> QueryResult { - let tcx = self.cx(); + let cx = self.cx(); let Goal { param_env, predicate: (lhs, rhs, direction) } = goal; debug_assert!(lhs.to_alias_term().is_some() || rhs.to_alias_term().is_some()); // Structurally normalize the lhs. let lhs = if let Some(alias) = lhs.to_alias_term() { let term = self.next_term_infer_of_kind(lhs); - self.add_normalizes_to_goal(goal.with(tcx, ty::NormalizesTo { alias, term })); + self.add_normalizes_to_goal(goal.with(cx, ty::NormalizesTo { alias, term })); term } else { lhs @@ -48,7 +48,7 @@ where // Structurally normalize the rhs. let rhs = if let Some(alias) = rhs.to_alias_term() { let term = self.next_term_infer_of_kind(rhs); - self.add_normalizes_to_goal(goal.with(tcx, ty::NormalizesTo { alias, term })); + self.add_normalizes_to_goal(goal.with(cx, ty::NormalizesTo { alias, term })); term } else { rhs diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs index ee7279a43b2cf..21439530c08f6 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/mod.rs @@ -36,11 +36,11 @@ where { fn self_ty(self) -> I::Ty; - fn trait_ref(self, tcx: I) -> ty::TraitRef; + fn trait_ref(self, cx: I) -> ty::TraitRef; - fn with_self_ty(self, tcx: I, self_ty: I::Ty) -> Self; + fn with_self_ty(self, cx: I, self_ty: I::Ty) -> Self; - fn trait_def_id(self, tcx: I) -> I::DefId; + fn trait_def_id(self, cx: I) -> I::DefId; /// Try equating an assumption predicate against a goal's predicate. If it /// holds, then execute the `then` callback, which should do any additional @@ -82,7 +82,7 @@ where assumption: I::Clause, ) -> Result, NoSolution> { Self::probe_and_match_goal_against_assumption(ecx, source, goal, assumption, |ecx| { - let tcx = ecx.cx(); + let cx = ecx.cx(); let ty::Dynamic(bounds, _, _) = goal.predicate.self_ty().kind() else { panic!("expected object type in `probe_and_consider_object_bound_candidate`"); }; @@ -91,7 +91,7 @@ where structural_traits::predicates_for_object_candidate( ecx, goal.param_env, - goal.predicate.trait_ref(tcx), + goal.predicate.trait_ref(cx), bounds, ), ); @@ -340,15 +340,15 @@ where goal: Goal, candidates: &mut Vec>, ) { - let tcx = self.cx(); - tcx.for_each_relevant_impl( - goal.predicate.trait_def_id(tcx), + let cx = self.cx(); + cx.for_each_relevant_impl( + goal.predicate.trait_def_id(cx), goal.predicate.self_ty(), |impl_def_id| { // For every `default impl`, there's always a non-default `impl` // that will *also* apply. There's no reason to register a candidate // for this impl, since it is *not* proof that the trait goal holds. - if tcx.impl_is_default(impl_def_id) { + if cx.impl_is_default(impl_def_id) { return; } @@ -366,8 +366,8 @@ where goal: Goal, candidates: &mut Vec>, ) { - let tcx = self.cx(); - let trait_def_id = goal.predicate.trait_def_id(tcx); + let cx = self.cx(); + let trait_def_id = goal.predicate.trait_def_id(cx); // N.B. When assembling built-in candidates for lang items that are also // `auto` traits, then the auto trait candidate that is assembled in @@ -378,47 +378,47 @@ where // `solve::trait_goals` instead. let result = if let Err(guar) = goal.predicate.error_reported() { G::consider_error_guaranteed_candidate(self, guar) - } else if tcx.trait_is_auto(trait_def_id) { + } else if cx.trait_is_auto(trait_def_id) { G::consider_auto_trait_candidate(self, goal) - } else if tcx.trait_is_alias(trait_def_id) { + } else if cx.trait_is_alias(trait_def_id) { G::consider_trait_alias_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::Sized) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::Sized) { G::consider_builtin_sized_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::Copy) - || tcx.is_lang_item(trait_def_id, TraitSolverLangItem::Clone) + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::Copy) + || cx.is_lang_item(trait_def_id, TraitSolverLangItem::Clone) { G::consider_builtin_copy_clone_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::PointerLike) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::PointerLike) { G::consider_builtin_pointer_like_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::FnPtrTrait) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::FnPtrTrait) { G::consider_builtin_fn_ptr_trait_candidate(self, goal) } else if let Some(kind) = self.cx().fn_trait_kind_from_def_id(trait_def_id) { G::consider_builtin_fn_trait_candidates(self, goal, kind) } else if let Some(kind) = self.cx().async_fn_trait_kind_from_def_id(trait_def_id) { G::consider_builtin_async_fn_trait_candidates(self, goal, kind) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::AsyncFnKindHelper) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::AsyncFnKindHelper) { G::consider_builtin_async_fn_kind_helper_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::Tuple) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::Tuple) { G::consider_builtin_tuple_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::PointeeTrait) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::PointeeTrait) { G::consider_builtin_pointee_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::Future) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::Future) { G::consider_builtin_future_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::Iterator) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::Iterator) { G::consider_builtin_iterator_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::FusedIterator) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::FusedIterator) { G::consider_builtin_fused_iterator_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::AsyncIterator) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::AsyncIterator) { G::consider_builtin_async_iterator_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::Coroutine) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::Coroutine) { G::consider_builtin_coroutine_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::DiscriminantKind) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::DiscriminantKind) { G::consider_builtin_discriminant_kind_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::AsyncDestruct) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::AsyncDestruct) { G::consider_builtin_async_destruct_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::Destruct) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::Destruct) { G::consider_builtin_destruct_candidate(self, goal) - } else if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::TransmuteTrait) { + } else if cx.is_lang_item(trait_def_id, TraitSolverLangItem::TransmuteTrait) { G::consider_builtin_transmute_candidate(self, goal) } else { Err(NoSolution) @@ -428,7 +428,7 @@ where // There may be multiple unsize candidates for a trait with several supertraits: // `trait Foo: Bar + Bar` and `dyn Foo: Unsize>` - if tcx.is_lang_item(trait_def_id, TraitSolverLangItem::Unsize) { + if cx.is_lang_item(trait_def_id, TraitSolverLangItem::Unsize) { candidates.extend(G::consider_structural_builtin_unsize_candidates(self, goal)); } } @@ -557,8 +557,8 @@ where goal: Goal, candidates: &mut Vec>, ) { - let tcx = self.cx(); - if !tcx.trait_may_be_implemented_via_object(goal.predicate.trait_def_id(tcx)) { + let cx = self.cx(); + if !cx.trait_may_be_implemented_via_object(goal.predicate.trait_def_id(cx)) { return; } @@ -596,7 +596,7 @@ where }; // Do not consider built-in object impls for non-object-safe types. - if bounds.principal_def_id().is_some_and(|def_id| !tcx.trait_is_object_safe(def_id)) { + if bounds.principal_def_id().is_some_and(|def_id| !cx.trait_is_object_safe(def_id)) { return; } @@ -614,7 +614,7 @@ where self, CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal, - bound.with_self_ty(tcx, self_ty), + bound.with_self_ty(cx, self_ty), )); } } @@ -624,14 +624,13 @@ where // since we don't need to look at any supertrait or anything if we are doing // a projection goal. if let Some(principal) = bounds.principal() { - let principal_trait_ref = principal.with_self_ty(tcx, self_ty); - for (idx, assumption) in D::elaborate_supertraits(tcx, principal_trait_ref).enumerate() - { + let principal_trait_ref = principal.with_self_ty(cx, self_ty); + for (idx, assumption) in D::elaborate_supertraits(cx, principal_trait_ref).enumerate() { candidates.extend(G::probe_and_consider_object_bound_candidate( self, CandidateSource::BuiltinImpl(BuiltinImplSource::Object(idx)), goal, - assumption.upcast(tcx), + assumption.upcast(cx), )); } } @@ -649,11 +648,11 @@ where goal: Goal, candidates: &mut Vec>, ) { - let tcx = self.cx(); + let cx = self.cx(); candidates.extend(self.probe_trait_candidate(CandidateSource::CoherenceUnknowable).enter( |ecx| { - let trait_ref = goal.predicate.trait_ref(tcx); + let trait_ref = goal.predicate.trait_ref(cx); if ecx.trait_ref_is_knowable(goal.param_env, trait_ref)? { Err(NoSolution) } else { @@ -678,9 +677,9 @@ where goal: Goal, candidates: &mut Vec>, ) { - let tcx = self.cx(); + let cx = self.cx(); let trait_goal: Goal> = - goal.with(tcx, goal.predicate.trait_ref(tcx)); + goal.with(cx, goal.predicate.trait_ref(cx)); let mut trait_candidates_from_env = vec![]; self.probe(|_| ProbeKind::ShadowedEnvProbing).enter(|ecx| { diff --git a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs index 2df039c766cf5..0cef8d9f4bc34 100644 --- a/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs +++ b/compiler/rustc_next_trait_solver/src/solve/assembly/structural_traits.rs @@ -23,7 +23,7 @@ where D: SolverDelegate, I: Interner, { - let tcx = ecx.cx(); + let cx = ecx.cx(); match ty.kind() { ty::Uint(_) | ty::Int(_) @@ -36,7 +36,7 @@ where | ty::Char => Ok(vec![]), // Treat `str` like it's defined as `struct str([u8]);` - ty::Str => Ok(vec![ty::Binder::dummy(Ty::new_slice(tcx, Ty::new_u8(tcx)))]), + ty::Str => Ok(vec![ty::Binder::dummy(Ty::new_slice(cx, Ty::new_u8(cx)))]), ty::Dynamic(..) | ty::Param(..) @@ -79,21 +79,21 @@ where .cx() .bound_coroutine_hidden_types(def_id) .into_iter() - .map(|bty| bty.instantiate(tcx, args)) + .map(|bty| bty.instantiate(cx, args)) .collect()), // For `PhantomData`, we pass `T`. ty::Adt(def, args) if def.is_phantom_data() => Ok(vec![ty::Binder::dummy(args.type_at(0))]), ty::Adt(def, args) => { - Ok(def.all_field_tys(tcx).iter_instantiated(tcx, args).map(ty::Binder::dummy).collect()) + Ok(def.all_field_tys(cx).iter_instantiated(cx, args).map(ty::Binder::dummy).collect()) } ty::Alias(ty::Opaque, ty::AliasTy { def_id, args, .. }) => { // We can resolve the `impl Trait` to its concrete type, // which enforces a DAG between the functions requiring // the auto trait bounds in question. - Ok(vec![ty::Binder::dummy(tcx.type_of(def_id).instantiate(tcx, args))]) + Ok(vec![ty::Binder::dummy(cx.type_of(def_id).instantiate(cx, args))]) } } } @@ -247,18 +247,18 @@ where // Returns a binder of the tupled inputs types and output type from a builtin callable type. pub(in crate::solve) fn extract_tupled_inputs_and_output_from_callable( - tcx: I, + cx: I, self_ty: I::Ty, goal_kind: ty::ClosureKind, ) -> Result>, NoSolution> { match self_ty.kind() { // keep this in sync with assemble_fn_pointer_candidates until the old solver is removed. ty::FnDef(def_id, args) => { - let sig = tcx.fn_sig(def_id); - if sig.skip_binder().is_fn_trait_compatible() && !tcx.has_target_features(def_id) { + let sig = cx.fn_sig(def_id); + if sig.skip_binder().is_fn_trait_compatible() && !cx.has_target_features(def_id) { Ok(Some( - sig.instantiate(tcx, args) - .map_bound(|sig| (Ty::new_tup(tcx, sig.inputs().as_slice()), sig.output())), + sig.instantiate(cx, args) + .map_bound(|sig| (Ty::new_tup(cx, sig.inputs().as_slice()), sig.output())), )) } else { Err(NoSolution) @@ -268,7 +268,7 @@ pub(in crate::solve) fn extract_tupled_inputs_and_output_from_callable { if sig.is_fn_trait_compatible() { Ok(Some( - sig.map_bound(|sig| (Ty::new_tup(tcx, sig.inputs().as_slice()), sig.output())), + sig.map_bound(|sig| (Ty::new_tup(cx, sig.inputs().as_slice()), sig.output())), )) } else { Err(NoSolution) @@ -323,10 +323,10 @@ pub(in crate::solve) fn extract_tupled_inputs_and_output_from_callable { // which enforces the closure is actually callable with the given trait. When we // know the kind already, we can short-circuit this check. pub(in crate::solve) fn extract_tupled_inputs_and_output_from_async_callable( - tcx: I, + cx: I, self_ty: I::Ty, goal_kind: ty::ClosureKind, env_region: I::Region, @@ -422,9 +422,7 @@ pub(in crate::solve) fn extract_tupled_inputs_and_output_from_async_callable { - let bound_sig = self_ty.fn_sig(tcx); + let bound_sig = self_ty.fn_sig(cx); let sig = bound_sig.skip_binder(); - let future_trait_def_id = tcx.require_lang_item(TraitSolverLangItem::Future); + let future_trait_def_id = cx.require_lang_item(TraitSolverLangItem::Future); // `FnDef` and `FnPtr` only implement `AsyncFn*` when their // return type implements `Future`. let nested = vec![ bound_sig - .rebind(ty::TraitRef::new(tcx, future_trait_def_id, [sig.output()])) - .upcast(tcx), + .rebind(ty::TraitRef::new(cx, future_trait_def_id, [sig.output()])) + .upcast(cx), ]; - let future_output_def_id = tcx.require_lang_item(TraitSolverLangItem::FutureOutput); - let future_output_ty = Ty::new_projection(tcx, future_output_def_id, [sig.output()]); + let future_output_def_id = cx.require_lang_item(TraitSolverLangItem::FutureOutput); + let future_output_ty = Ty::new_projection(cx, future_output_def_id, [sig.output()]); Ok(( bound_sig.rebind(AsyncCallableRelevantTypes { - tupled_inputs_ty: Ty::new_tup(tcx, sig.inputs().as_slice()), + tupled_inputs_ty: Ty::new_tup(cx, sig.inputs().as_slice()), output_coroutine_ty: sig.output(), coroutine_return_ty: future_output_ty, }), @@ -483,13 +481,13 @@ pub(in crate::solve) fn extract_tupled_inputs_and_output_from_async_callable( - tcx: I, + cx: I, goal_kind: ty::ClosureKind, goal_region: I::Region, def_id: I::DefId, @@ -573,9 +571,9 @@ fn coroutine_closure_to_certain_coroutine( sig: ty::CoroutineClosureSignature, ) -> I::Ty { sig.to_coroutine_given_kind_and_upvars( - tcx, + cx, args.parent_args(), - tcx.coroutine_for_closure(def_id), + cx.coroutine_for_closure(def_id), goal_kind, goal_region, args.tupled_upvars_ty(), @@ -589,20 +587,20 @@ fn coroutine_closure_to_certain_coroutine( /// /// Note that we do not also push a `AsyncFnKindHelper` goal here. fn coroutine_closure_to_ambiguous_coroutine( - tcx: I, + cx: I, goal_kind: ty::ClosureKind, goal_region: I::Region, def_id: I::DefId, args: ty::CoroutineClosureArgs, sig: ty::CoroutineClosureSignature, ) -> I::Ty { - let upvars_projection_def_id = tcx.require_lang_item(TraitSolverLangItem::AsyncFnKindUpvars); + let upvars_projection_def_id = cx.require_lang_item(TraitSolverLangItem::AsyncFnKindUpvars); let tupled_upvars_ty = Ty::new_projection( - tcx, + cx, upvars_projection_def_id, [ I::GenericArg::from(args.kind_ty()), - Ty::from_closure_kind(tcx, goal_kind).into(), + Ty::from_closure_kind(cx, goal_kind).into(), goal_region.into(), sig.tupled_inputs_ty.into(), args.tupled_upvars_ty().into(), @@ -610,10 +608,10 @@ fn coroutine_closure_to_ambiguous_coroutine( ], ); sig.to_coroutine( - tcx, + cx, args.parent_args(), - Ty::from_closure_kind(tcx, goal_kind), - tcx.coroutine_for_closure(def_id), + Ty::from_closure_kind(cx, goal_kind), + cx.coroutine_for_closure(def_id), tupled_upvars_ty, ) } @@ -668,28 +666,28 @@ where D: SolverDelegate, I: Interner, { - let tcx = ecx.cx(); + let cx = ecx.cx(); let mut requirements = vec![]; requirements - .extend(tcx.super_predicates_of(trait_ref.def_id).iter_instantiated(tcx, trait_ref.args)); + .extend(cx.super_predicates_of(trait_ref.def_id).iter_instantiated(cx, trait_ref.args)); // FIXME(associated_const_equality): Also add associated consts to // the requirements here. - for associated_type_def_id in tcx.associated_type_def_ids(trait_ref.def_id) { + for associated_type_def_id in cx.associated_type_def_ids(trait_ref.def_id) { // associated types that require `Self: Sized` do not show up in the built-in // implementation of `Trait for dyn Trait`, and can be dropped here. - if tcx.generics_require_sized_self(associated_type_def_id) { + if cx.generics_require_sized_self(associated_type_def_id) { continue; } requirements - .extend(tcx.item_bounds(associated_type_def_id).iter_instantiated(tcx, trait_ref.args)); + .extend(cx.item_bounds(associated_type_def_id).iter_instantiated(cx, trait_ref.args)); } let mut replace_projection_with = HashMap::default(); for bound in object_bounds.iter() { if let ty::ExistentialPredicate::Projection(proj) = bound.skip_binder() { - let proj = proj.with_self_ty(tcx, trait_ref.self_ty()); + let proj = proj.with_self_ty(cx, trait_ref.self_ty()); let old_ty = replace_projection_with.insert(proj.def_id(), bound.rebind(proj)); assert_eq!( old_ty, @@ -709,7 +707,7 @@ where folder .nested .into_iter() - .chain(folded_requirements.into_iter().map(|clause| Goal::new(tcx, param_env, clause))) + .chain(folded_requirements.into_iter().map(|clause| Goal::new(cx, param_env, clause))) .collect() } diff --git a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs index 04dce2780b07b..87342eefb33e5 100644 --- a/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/eval_ctxt/mod.rs @@ -239,14 +239,14 @@ where /// This function takes care of setting up the inference context, setting the anchor, /// and registering opaques from the canonicalized input. fn enter_canonical( - tcx: I, + cx: I, search_graph: &'a mut search_graph::SearchGraph, canonical_input: CanonicalInput, canonical_goal_evaluation: &mut ProofTreeBuilder, f: impl FnOnce(&mut EvalCtxt<'_, D>, Goal) -> R, ) -> R { let (ref delegate, input, var_values) = - SolverDelegate::build_with_canonical(tcx, search_graph.solver_mode(), &canonical_input); + SolverDelegate::build_with_canonical(cx, search_graph.solver_mode(), &canonical_input); let mut ecx = EvalCtxt { delegate, @@ -292,9 +292,9 @@ where /// Instead of calling this function directly, use either [EvalCtxt::evaluate_goal] /// if you're inside of the solver or [SolverDelegateEvalExt::evaluate_root_goal] if you're /// outside of it. - #[instrument(level = "debug", skip(tcx, search_graph, goal_evaluation), ret)] + #[instrument(level = "debug", skip(cx, search_graph, goal_evaluation), ret)] fn evaluate_canonical_goal( - tcx: I, + cx: I, search_graph: &'a mut search_graph::SearchGraph, canonical_input: CanonicalInput, goal_evaluation: &mut ProofTreeBuilder, @@ -307,12 +307,12 @@ where // The actual solver logic happens in `ecx.compute_goal`. let result = ensure_sufficient_stack(|| { search_graph.with_new_goal( - tcx, + cx, canonical_input, &mut canonical_goal_evaluation, |search_graph, canonical_goal_evaluation| { EvalCtxt::enter_canonical( - tcx, + cx, search_graph, canonical_input, canonical_goal_evaluation, @@ -506,7 +506,7 @@ where /// /// Goals for the next step get directly added to the nested goals of the `EvalCtxt`. fn evaluate_added_goals_step(&mut self) -> Result, NoSolution> { - let tcx = self.cx(); + let cx = self.cx(); let mut goals = core::mem::take(&mut self.nested_goals); // If this loop did not result in any progress, what's our final certainty. @@ -516,7 +516,7 @@ where // RHS does not affect projection candidate assembly. let unconstrained_rhs = self.next_term_infer_of_kind(goal.predicate.term); let unconstrained_goal = goal.with( - tcx, + cx, ty::NormalizesTo { alias: goal.predicate.alias, term: unconstrained_rhs }, ); @@ -777,7 +777,7 @@ where // NOTE: this check is purely an optimization, the structural eq would // always fail if the term is not an inference variable. if term.is_infer() { - let tcx = self.cx(); + let cx = self.cx(); // We need to relate `alias` to `term` treating only the outermost // constructor as rigid, relating any contained generic arguments as // normal. We do this by first structurally equating the `term` @@ -787,8 +787,8 @@ where // Alternatively we could modify `Equate` for this case by adding another // variant to `StructurallyRelateAliases`. let identity_args = self.fresh_args_for_item(alias.def_id); - let rigid_ctor = ty::AliasTerm::new_from_args(tcx, alias.def_id, identity_args); - let ctor_term = rigid_ctor.to_term(tcx); + let rigid_ctor = ty::AliasTerm::new_from_args(cx, alias.def_id, identity_args); + let ctor_term = rigid_ctor.to_term(cx); let obligations = self.delegate.eq_structurally_relating_aliases(param_env, term, ctor_term)?; debug_assert!(obligations.is_empty()); diff --git a/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs b/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs index 4fc58e06d67dc..b50676e8d5327 100644 --- a/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs +++ b/compiler/rustc_next_trait_solver/src/solve/inspect/build.rs @@ -323,13 +323,13 @@ impl, I: Interner> ProofTreeBuilder { pub fn finalize_canonical_goal_evaluation( &mut self, - tcx: I, + cx: I, ) -> Option { self.as_mut().map(|this| match this { DebugSolver::CanonicalGoalEvaluation(evaluation) => { let final_revision = mem::take(&mut evaluation.final_revision).unwrap(); let final_revision = - tcx.intern_canonical_goal_evaluation_step(final_revision.finalize()); + cx.intern_canonical_goal_evaluation_step(final_revision.finalize()); let kind = WipCanonicalGoalEvaluationKind::Interned { final_revision }; assert_eq!(evaluation.kind.replace(kind), None); final_revision diff --git a/compiler/rustc_next_trait_solver/src/solve/mod.rs b/compiler/rustc_next_trait_solver/src/solve/mod.rs index e29ae7ac0a26c..24055d6cd832b 100644 --- a/compiler/rustc_next_trait_solver/src/solve/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/mod.rs @@ -34,7 +34,7 @@ use crate::delegate::SolverDelegate; /// How many fixpoint iterations we should attempt inside of the solver before bailing /// with overflow. /// -/// We previously used `tcx.recursion_limit().0.checked_ilog2().unwrap_or(0)` for this. +/// We previously used `cx.recursion_limit().0.checked_ilog2().unwrap_or(0)` for this. /// However, it feels unlikely that uncreasing the recursion limit by a power of two /// to get one more itereation is every useful or desirable. We now instead used a constant /// here. If there ever ends up some use-cases where a bigger number of fixpoint iterations @@ -285,7 +285,7 @@ where } fn response_no_constraints_raw( - tcx: I, + cx: I, max_universe: ty::UniverseIndex, variables: I::CanonicalVars, certainty: Certainty, @@ -294,10 +294,10 @@ fn response_no_constraints_raw( max_universe, variables, value: Response { - var_values: ty::CanonicalVarValues::make_identity(tcx, variables), - // FIXME: maybe we should store the "no response" version in tcx, like - // we do for tcx.types and stuff. - external_constraints: tcx.mk_external_constraints(ExternalConstraintsData::default()), + var_values: ty::CanonicalVarValues::make_identity(cx, variables), + // FIXME: maybe we should store the "no response" version in cx, like + // we do for cx.types and stuff. + external_constraints: cx.mk_external_constraints(ExternalConstraintsData::default()), certainty, }, defining_opaque_types: Default::default(), diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/inherent.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/inherent.rs index 004ecf2d2c4f7..25e8708a3322c 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/inherent.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/inherent.rs @@ -19,21 +19,21 @@ where &mut self, goal: Goal>, ) -> QueryResult { - let tcx = self.cx(); - let inherent = goal.predicate.alias.expect_ty(tcx); + let cx = self.cx(); + let inherent = goal.predicate.alias.expect_ty(cx); - let impl_def_id = tcx.parent(inherent.def_id); + let impl_def_id = cx.parent(inherent.def_id); let impl_args = self.fresh_args_for_item(impl_def_id); // Equate impl header and add impl where clauses self.eq( goal.param_env, inherent.self_ty(), - tcx.type_of(impl_def_id).instantiate(tcx, impl_args), + cx.type_of(impl_def_id).instantiate(cx, impl_args), )?; // Equate IAT with the RHS of the project goal - let inherent_args = inherent.rebase_inherent_args_onto_impl(impl_args, tcx); + let inherent_args = inherent.rebase_inherent_args_onto_impl(impl_args, cx); // Check both where clauses on the impl and IAT // @@ -43,12 +43,12 @@ where // and I don't think the assoc item where-bounds are allowed to be coinductive. self.add_goals( GoalSource::Misc, - tcx.predicates_of(inherent.def_id) - .iter_instantiated(tcx, inherent_args) - .map(|pred| goal.with(tcx, pred)), + cx.predicates_of(inherent.def_id) + .iter_instantiated(cx, inherent_args) + .map(|pred| goal.with(cx, pred)), ); - let normalized = tcx.type_of(inherent.def_id).instantiate(tcx, inherent_args); + let normalized = cx.type_of(inherent.def_id).instantiate(cx, inherent_args); self.instantiate_normalizes_to_term(goal, normalized.into()); self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) } diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs index bc5233c4887fa..4e8cb4384f462 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/mod.rs @@ -84,16 +84,16 @@ where self.self_ty() } - fn trait_ref(self, tcx: I) -> ty::TraitRef { - self.alias.trait_ref(tcx) + fn trait_ref(self, cx: I) -> ty::TraitRef { + self.alias.trait_ref(cx) } - fn with_self_ty(self, tcx: I, self_ty: I::Ty) -> Self { - self.with_self_ty(tcx, self_ty) + fn with_self_ty(self, cx: I, self_ty: I::Ty) -> Self { + self.with_self_ty(cx, self_ty) } - fn trait_def_id(self, tcx: I) -> I::DefId { - self.trait_def_id(tcx) + fn trait_def_id(self, cx: I) -> I::DefId { + self.trait_def_id(cx) } fn probe_and_match_goal_against_assumption( @@ -105,7 +105,7 @@ where ) -> Result, NoSolution> { if let Some(projection_pred) = assumption.as_projection_clause() { if projection_pred.projection_def_id() == goal.predicate.def_id() { - let tcx = ecx.cx(); + let cx = ecx.cx(); ecx.probe_trait_candidate(source).enter(|ecx| { let assumption_projection_pred = ecx.instantiate_binder_with_infer(projection_pred); @@ -120,9 +120,9 @@ where // Add GAT where clauses from the trait's definition ecx.add_goals( GoalSource::Misc, - tcx.own_predicates_of(goal.predicate.def_id()) - .iter_instantiated(tcx, goal.predicate.alias.args) - .map(|pred| goal.with(tcx, pred)), + cx.own_predicates_of(goal.predicate.def_id()) + .iter_instantiated(cx, goal.predicate.alias.args) + .map(|pred| goal.with(cx, pred)), ); then(ecx) @@ -140,19 +140,19 @@ where goal: Goal>, impl_def_id: I::DefId, ) -> Result, NoSolution> { - let tcx = ecx.cx(); + let cx = ecx.cx(); - let goal_trait_ref = goal.predicate.alias.trait_ref(tcx); - let impl_trait_ref = tcx.impl_trait_ref(impl_def_id); + let goal_trait_ref = goal.predicate.alias.trait_ref(cx); + let impl_trait_ref = cx.impl_trait_ref(impl_def_id); if !ecx.cx().args_may_unify_deep( - goal.predicate.alias.trait_ref(tcx).args, + goal.predicate.alias.trait_ref(cx).args, impl_trait_ref.skip_binder().args, ) { return Err(NoSolution); } // We have to ignore negative impls when projecting. - let impl_polarity = tcx.impl_polarity(impl_def_id); + let impl_polarity = cx.impl_polarity(impl_def_id); match impl_polarity { ty::ImplPolarity::Negative => return Err(NoSolution), ty::ImplPolarity::Reservation => { @@ -163,22 +163,22 @@ where ecx.probe_trait_candidate(CandidateSource::Impl(impl_def_id)).enter(|ecx| { let impl_args = ecx.fresh_args_for_item(impl_def_id); - let impl_trait_ref = impl_trait_ref.instantiate(tcx, impl_args); + let impl_trait_ref = impl_trait_ref.instantiate(cx, impl_args); ecx.eq(goal.param_env, goal_trait_ref, impl_trait_ref)?; - let where_clause_bounds = tcx + let where_clause_bounds = cx .predicates_of(impl_def_id) - .iter_instantiated(tcx, impl_args) - .map(|pred| goal.with(tcx, pred)); + .iter_instantiated(cx, impl_args) + .map(|pred| goal.with(cx, pred)); ecx.add_goals(GoalSource::ImplWhereBound, where_clause_bounds); // Add GAT where clauses from the trait's definition ecx.add_goals( GoalSource::Misc, - tcx.own_predicates_of(goal.predicate.def_id()) - .iter_instantiated(tcx, goal.predicate.alias.args) - .map(|pred| goal.with(tcx, pred)), + cx.own_predicates_of(goal.predicate.def_id()) + .iter_instantiated(cx, goal.predicate.alias.args) + .map(|pred| goal.with(cx, pred)), ); // In case the associated item is hidden due to specialization, we have to @@ -195,21 +195,21 @@ where }; let error_response = |ecx: &mut EvalCtxt<'_, D>, msg: &str| { - let guar = tcx.delay_bug(msg); - let error_term = match goal.predicate.alias.kind(tcx) { - ty::AliasTermKind::ProjectionTy => Ty::new_error(tcx, guar).into(), - ty::AliasTermKind::ProjectionConst => Const::new_error(tcx, guar).into(), + let guar = cx.delay_bug(msg); + let error_term = match goal.predicate.alias.kind(cx) { + ty::AliasTermKind::ProjectionTy => Ty::new_error(cx, guar).into(), + ty::AliasTermKind::ProjectionConst => Const::new_error(cx, guar).into(), kind => panic!("expected projection, found {kind:?}"), }; ecx.instantiate_normalizes_to_term(goal, error_term); ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) }; - if !tcx.has_item_definition(target_item_def_id) { + if !cx.has_item_definition(target_item_def_id) { return error_response(ecx, "missing item"); } - let target_container_def_id = tcx.parent(target_item_def_id); + let target_container_def_id = cx.parent(target_item_def_id); // Getting the right args here is complex, e.g. given: // - a goal ` as Trait>::Assoc` @@ -229,22 +229,22 @@ where target_container_def_id, )?; - if !tcx.check_args_compatible(target_item_def_id, target_args) { + if !cx.check_args_compatible(target_item_def_id, target_args) { return error_response(ecx, "associated item has mismatched arguments"); } // Finally we construct the actual value of the associated type. - let term = match goal.predicate.alias.kind(tcx) { + let term = match goal.predicate.alias.kind(cx) { ty::AliasTermKind::ProjectionTy => { - tcx.type_of(target_item_def_id).map_bound(|ty| ty.into()) + cx.type_of(target_item_def_id).map_bound(|ty| ty.into()) } ty::AliasTermKind::ProjectionConst => { - if tcx.features().associated_const_equality() { + if cx.features().associated_const_equality() { panic!("associated const projection is not supported yet") } else { ty::EarlyBinder::bind( Const::new_error_with_message( - tcx, + cx, "associated const projection is not supported yet", ) .into(), @@ -254,7 +254,7 @@ where kind => panic!("expected projection, found {kind:?}"), }; - ecx.instantiate_normalizes_to_term(goal, term.instantiate(tcx, target_args)); + ecx.instantiate_normalizes_to_term(goal, term.instantiate(cx, target_args)); ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) }) } @@ -316,10 +316,10 @@ where goal: Goal, goal_kind: ty::ClosureKind, ) -> Result, NoSolution> { - let tcx = ecx.cx(); + let cx = ecx.cx(); let tupled_inputs_and_output = match structural_traits::extract_tupled_inputs_and_output_from_callable( - tcx, + cx, goal.predicate.self_ty(), goal_kind, )? { @@ -329,19 +329,19 @@ where } }; let output_is_sized_pred = tupled_inputs_and_output.map_bound(|(_, output)| { - ty::TraitRef::new(tcx, tcx.require_lang_item(TraitSolverLangItem::Sized), [output]) + ty::TraitRef::new(cx, cx.require_lang_item(TraitSolverLangItem::Sized), [output]) }); let pred = tupled_inputs_and_output .map_bound(|(inputs, output)| ty::ProjectionPredicate { projection_term: ty::AliasTerm::new( - tcx, + cx, goal.predicate.def_id(), [goal.predicate.self_ty(), inputs], ), term: output.into(), }) - .upcast(tcx); + .upcast(cx); // A built-in `Fn` impl only holds if the output is sized. // (FIXME: technically we only need to check this if the type is a fn ptr...) @@ -350,7 +350,7 @@ where CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal, pred, - [(GoalSource::ImplWhereBound, goal.with(tcx, output_is_sized_pred))], + [(GoalSource::ImplWhereBound, goal.with(cx, output_is_sized_pred))], ) } @@ -359,27 +359,23 @@ where goal: Goal, goal_kind: ty::ClosureKind, ) -> Result, NoSolution> { - let tcx = ecx.cx(); + let cx = ecx.cx(); let env_region = match goal_kind { ty::ClosureKind::Fn | ty::ClosureKind::FnMut => goal.predicate.alias.args.region_at(2), // Doesn't matter what this region is - ty::ClosureKind::FnOnce => Region::new_static(tcx), + ty::ClosureKind::FnOnce => Region::new_static(cx), }; let (tupled_inputs_and_output_and_coroutine, nested_preds) = structural_traits::extract_tupled_inputs_and_output_from_async_callable( - tcx, + cx, goal.predicate.self_ty(), goal_kind, env_region, )?; let output_is_sized_pred = tupled_inputs_and_output_and_coroutine.map_bound( |AsyncCallableRelevantTypes { output_coroutine_ty: output_ty, .. }| { - ty::TraitRef::new( - tcx, - tcx.require_lang_item(TraitSolverLangItem::Sized), - [output_ty], - ) + ty::TraitRef::new(cx, cx.require_lang_item(TraitSolverLangItem::Sized), [output_ty]) }, ); @@ -390,23 +386,23 @@ where output_coroutine_ty, coroutine_return_ty, }| { - let (projection_term, term) = if tcx + let (projection_term, term) = if cx .is_lang_item(goal.predicate.def_id(), TraitSolverLangItem::CallOnceFuture) { ( ty::AliasTerm::new( - tcx, + cx, goal.predicate.def_id(), [goal.predicate.self_ty(), tupled_inputs_ty], ), output_coroutine_ty.into(), ) - } else if tcx + } else if cx .is_lang_item(goal.predicate.def_id(), TraitSolverLangItem::CallRefFuture) { ( ty::AliasTerm::new( - tcx, + cx, goal.predicate.def_id(), [ I::GenericArg::from(goal.predicate.self_ty()), @@ -416,13 +412,13 @@ where ), output_coroutine_ty.into(), ) - } else if tcx.is_lang_item( + } else if cx.is_lang_item( goal.predicate.def_id(), TraitSolverLangItem::AsyncFnOnceOutput, ) { ( ty::AliasTerm::new( - tcx, + cx, goal.predicate.def_id(), [ I::GenericArg::from(goal.predicate.self_ty()), @@ -440,7 +436,7 @@ where ty::ProjectionPredicate { projection_term, term } }, ) - .upcast(tcx); + .upcast(cx); // A built-in `AsyncFn` impl only holds if the output is sized. // (FIXME: technically we only need to check this if the type is a fn ptr...) @@ -449,9 +445,9 @@ where CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal, pred, - [goal.with(tcx, output_is_sized_pred)] + [goal.with(cx, output_is_sized_pred)] .into_iter() - .chain(nested_preds.into_iter().map(|pred| goal.with(tcx, pred))) + .chain(nested_preds.into_iter().map(|pred| goal.with(cx, pred))) .map(|goal| (GoalSource::ImplWhereBound, goal)), ) } @@ -514,8 +510,8 @@ where ecx: &mut EvalCtxt<'_, D>, goal: Goal, ) -> Result, NoSolution> { - let tcx = ecx.cx(); - let metadata_def_id = tcx.require_lang_item(TraitSolverLangItem::Metadata); + let cx = ecx.cx(); + let metadata_def_id = cx.require_lang_item(TraitSolverLangItem::Metadata); assert_eq!(metadata_def_id, goal.predicate.def_id()); ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| { let metadata_ty = match goal.predicate.self_ty().kind() { @@ -537,16 +533,16 @@ where | ty::CoroutineWitness(..) | ty::Never | ty::Foreign(..) - | ty::Dynamic(_, _, ty::DynStar) => Ty::new_unit(tcx), + | ty::Dynamic(_, _, ty::DynStar) => Ty::new_unit(cx), - ty::Error(e) => Ty::new_error(tcx, e), + ty::Error(e) => Ty::new_error(cx, e), - ty::Str | ty::Slice(_) => Ty::new_usize(tcx), + ty::Str | ty::Slice(_) => Ty::new_usize(cx), ty::Dynamic(_, _, ty::Dyn) => { - let dyn_metadata = tcx.require_lang_item(TraitSolverLangItem::DynMetadata); - tcx.type_of(dyn_metadata) - .instantiate(tcx, &[I::GenericArg::from(goal.predicate.self_ty())]) + let dyn_metadata = cx.require_lang_item(TraitSolverLangItem::DynMetadata); + cx.type_of(dyn_metadata) + .instantiate(cx, &[I::GenericArg::from(goal.predicate.self_ty())]) } ty::Alias(_, _) | ty::Param(_) | ty::Placeholder(..) => { @@ -555,26 +551,26 @@ where // FIXME(ptr_metadata): This impl overlaps with the other impls and shouldn't // exist. Instead, `Pointee` should be a supertrait of `Sized`. let sized_predicate = ty::TraitRef::new( - tcx, - tcx.require_lang_item(TraitSolverLangItem::Sized), + cx, + cx.require_lang_item(TraitSolverLangItem::Sized), [I::GenericArg::from(goal.predicate.self_ty())], ); // FIXME(-Znext-solver=coinductive): Should this be `GoalSource::ImplWhereBound`? - ecx.add_goal(GoalSource::Misc, goal.with(tcx, sized_predicate)); - Ty::new_unit(tcx) + ecx.add_goal(GoalSource::Misc, goal.with(cx, sized_predicate)); + Ty::new_unit(cx) } - ty::Adt(def, args) if def.is_struct() => match def.struct_tail_ty(tcx) { - None => Ty::new_unit(tcx), + ty::Adt(def, args) if def.is_struct() => match def.struct_tail_ty(cx) { + None => Ty::new_unit(cx), Some(tail_ty) => { - Ty::new_projection(tcx, metadata_def_id, [tail_ty.instantiate(tcx, args)]) + Ty::new_projection(cx, metadata_def_id, [tail_ty.instantiate(cx, args)]) } }, - ty::Adt(_, _) => Ty::new_unit(tcx), + ty::Adt(_, _) => Ty::new_unit(cx), ty::Tuple(elements) => match elements.last() { - None => Ty::new_unit(tcx), - Some(tail_ty) => Ty::new_projection(tcx, metadata_def_id, [tail_ty]), + None => Ty::new_unit(cx), + Some(tail_ty) => Ty::new_projection(cx, metadata_def_id, [tail_ty]), }, ty::Infer( @@ -601,8 +597,8 @@ where }; // Coroutines are not futures unless they come from `async` desugaring - let tcx = ecx.cx(); - if !tcx.coroutine_is_async(def_id) { + let cx = ecx.cx(); + if !cx.coroutine_is_async(def_id) { return Err(NoSolution); } @@ -616,7 +612,7 @@ where projection_term: ty::AliasTerm::new(ecx.cx(), goal.predicate.def_id(), [self_ty]), term, } - .upcast(tcx), + .upcast(cx), // Technically, we need to check that the future type is Sized, // but that's already proven by the coroutine being WF. [], @@ -633,8 +629,8 @@ where }; // Coroutines are not Iterators unless they come from `gen` desugaring - let tcx = ecx.cx(); - if !tcx.coroutine_is_gen(def_id) { + let cx = ecx.cx(); + if !cx.coroutine_is_gen(def_id) { return Err(NoSolution); } @@ -648,7 +644,7 @@ where projection_term: ty::AliasTerm::new(ecx.cx(), goal.predicate.def_id(), [self_ty]), term, } - .upcast(tcx), + .upcast(cx), // Technically, we need to check that the iterator type is Sized, // but that's already proven by the generator being WF. [], @@ -672,8 +668,8 @@ where }; // Coroutines are not AsyncIterators unless they come from `gen` desugaring - let tcx = ecx.cx(); - if !tcx.coroutine_is_async_gen(def_id) { + let cx = ecx.cx(); + if !cx.coroutine_is_async_gen(def_id) { return Err(NoSolution); } @@ -682,12 +678,12 @@ where // Take `AsyncIterator` and turn it into the corresponding // coroutine yield ty `Poll>`. let wrapped_expected_ty = Ty::new_adt( - tcx, - tcx.adt_def(tcx.require_lang_item(TraitSolverLangItem::Poll)), - tcx.mk_args(&[Ty::new_adt( - tcx, - tcx.adt_def(tcx.require_lang_item(TraitSolverLangItem::Option)), - tcx.mk_args(&[expected_ty.into()]), + cx, + cx.adt_def(cx.require_lang_item(TraitSolverLangItem::Poll)), + cx.mk_args(&[Ty::new_adt( + cx, + cx.adt_def(cx.require_lang_item(TraitSolverLangItem::Option)), + cx.mk_args(&[expected_ty.into()]), ) .into()]), ); @@ -708,18 +704,17 @@ where }; // `async`-desugared coroutines do not implement the coroutine trait - let tcx = ecx.cx(); - if !tcx.is_general_coroutine(def_id) { + let cx = ecx.cx(); + if !cx.is_general_coroutine(def_id) { return Err(NoSolution); } let coroutine = args.as_coroutine(); - let term = if tcx - .is_lang_item(goal.predicate.def_id(), TraitSolverLangItem::CoroutineReturn) + let term = if cx.is_lang_item(goal.predicate.def_id(), TraitSolverLangItem::CoroutineReturn) { coroutine.return_ty().into() - } else if tcx.is_lang_item(goal.predicate.def_id(), TraitSolverLangItem::CoroutineYield) { + } else if cx.is_lang_item(goal.predicate.def_id(), TraitSolverLangItem::CoroutineYield) { coroutine.yield_ty().into() } else { panic!("unexpected associated item `{:?}` for `{self_ty:?}`", goal.predicate.def_id()) @@ -737,7 +732,7 @@ where ), term, } - .upcast(tcx), + .upcast(cx), // Technically, we need to check that the coroutine type is Sized, // but that's already proven by the coroutine being WF. [], @@ -884,29 +879,29 @@ where impl_trait_ref: rustc_type_ir::TraitRef, target_container_def_id: I::DefId, ) -> Result { - let tcx = self.cx(); + let cx = self.cx(); Ok(if target_container_def_id == impl_trait_ref.def_id { // Default value from the trait definition. No need to rebase. goal.predicate.alias.args } else if target_container_def_id == impl_def_id { // Same impl, no need to fully translate, just a rebase from // the trait is sufficient. - goal.predicate.alias.args.rebase_onto(tcx, impl_trait_ref.def_id, impl_args) + goal.predicate.alias.args.rebase_onto(cx, impl_trait_ref.def_id, impl_args) } else { let target_args = self.fresh_args_for_item(target_container_def_id); let target_trait_ref = - tcx.impl_trait_ref(target_container_def_id).instantiate(tcx, target_args); + cx.impl_trait_ref(target_container_def_id).instantiate(cx, target_args); // Relate source impl to target impl by equating trait refs. self.eq(goal.param_env, impl_trait_ref, target_trait_ref)?; // Also add predicates since they may be needed to constrain the // target impl's params. self.add_goals( GoalSource::Misc, - tcx.predicates_of(target_container_def_id) - .iter_instantiated(tcx, target_args) - .map(|pred| goal.with(tcx, pred)), + cx.predicates_of(target_container_def_id) + .iter_instantiated(cx, target_args) + .map(|pred| goal.with(cx, pred)), ); - goal.predicate.alias.args.rebase_onto(tcx, impl_trait_ref.def_id, target_args) + goal.predicate.alias.args.rebase_onto(cx, impl_trait_ref.def_id, target_args) }) } } diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/opaque_types.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/opaque_types.rs index a16f9e64f2f74..120f96d24bda3 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/opaque_types.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/opaque_types.rs @@ -18,7 +18,7 @@ where &mut self, goal: Goal>, ) -> QueryResult { - let tcx = self.cx(); + let cx = self.cx(); let opaque_ty = goal.predicate.alias; let expected = goal.predicate.term.as_type().expect("no such thing as an opaque const"); @@ -86,7 +86,7 @@ where } (Reveal::All, _) => { // FIXME: Add an assertion that opaque type storage is empty. - let actual = tcx.type_of(opaque_ty.def_id).instantiate(tcx, opaque_ty.args); + let actual = cx.type_of(opaque_ty.def_id).instantiate(cx, opaque_ty.args); self.eq(goal.param_env, expected, actual)?; self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) } @@ -98,7 +98,7 @@ where /// /// FIXME: Interner argument is needed to constrain the `I` parameter. pub fn uses_unique_placeholders_ignoring_regions( - _interner: I, + _cx: I, args: I::GenericArgs, ) -> Result<(), NotUniqueParam> { let mut seen = GrowableBitSet::default(); diff --git a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/weak_types.rs b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/weak_types.rs index ca90bc17cc7d8..14e68dd52b6c1 100644 --- a/compiler/rustc_next_trait_solver/src/solve/normalizes_to/weak_types.rs +++ b/compiler/rustc_next_trait_solver/src/solve/normalizes_to/weak_types.rs @@ -18,18 +18,18 @@ where &mut self, goal: Goal>, ) -> QueryResult { - let tcx = self.cx(); + let cx = self.cx(); let weak_ty = goal.predicate.alias; // Check where clauses self.add_goals( GoalSource::Misc, - tcx.predicates_of(weak_ty.def_id) - .iter_instantiated(tcx, weak_ty.args) - .map(|pred| goal.with(tcx, pred)), + cx.predicates_of(weak_ty.def_id) + .iter_instantiated(cx, weak_ty.args) + .map(|pred| goal.with(cx, pred)), ); - let actual = tcx.type_of(weak_ty.def_id).instantiate(tcx, weak_ty.args); + let actual = cx.type_of(weak_ty.def_id).instantiate(cx, weak_ty.args); self.instantiate_normalizes_to_term(goal, actual.into()); self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) diff --git a/compiler/rustc_next_trait_solver/src/solve/project_goals.rs b/compiler/rustc_next_trait_solver/src/solve/project_goals.rs index a430dbb408c5c..d945288007174 100644 --- a/compiler/rustc_next_trait_solver/src/solve/project_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/project_goals.rs @@ -14,10 +14,10 @@ where &mut self, goal: Goal>, ) -> QueryResult { - let tcx = self.cx(); - let projection_term = goal.predicate.projection_term.to_term(tcx); + let cx = self.cx(); + let projection_term = goal.predicate.projection_term.to_term(cx); let goal = goal.with( - tcx, + cx, ty::PredicateKind::AliasRelate( projection_term, goal.predicate.term, diff --git a/compiler/rustc_next_trait_solver/src/solve/search_graph.rs b/compiler/rustc_next_trait_solver/src/solve/search_graph.rs index d3ad55d6491b0..2cd3b10f56adb 100644 --- a/compiler/rustc_next_trait_solver/src/solve/search_graph.rs +++ b/compiler/rustc_next_trait_solver/src/solve/search_graph.rs @@ -164,7 +164,7 @@ impl SearchGraph { /// the remaining depth of all nested goals to prevent hangs /// in case there is exponential blowup. fn allowed_depth_for_nested( - tcx: I, + cx: I, stack: &IndexVec>, ) -> Option { if let Some(last) = stack.raw.last() { @@ -178,18 +178,18 @@ impl SearchGraph { SolverLimit(last.available_depth.0 - 1) }) } else { - Some(SolverLimit(tcx.recursion_limit())) + Some(SolverLimit(cx.recursion_limit())) } } fn stack_coinductive_from( - tcx: I, + cx: I, stack: &IndexVec>, head: StackDepth, ) -> bool { stack.raw[head.index()..] .iter() - .all(|entry| entry.input.value.goal.predicate.is_coinductive(tcx)) + .all(|entry| entry.input.value.goal.predicate.is_coinductive(cx)) } // When encountering a solver cycle, the result of the current goal @@ -247,8 +247,8 @@ impl SearchGraph { /// so we use a separate cache. Alternatively we could use /// a single cache and share it between coherence and ordinary /// trait solving. - pub(super) fn global_cache(&self, tcx: I) -> I::EvaluationCache { - tcx.evaluation_cache(self.mode) + pub(super) fn global_cache(&self, cx: I) -> I::EvaluationCache { + cx.evaluation_cache(self.mode) } /// Probably the most involved method of the whole solver. @@ -257,24 +257,24 @@ impl SearchGraph { /// handles caching, overflow, and coinductive cycles. pub(super) fn with_new_goal>( &mut self, - tcx: I, + cx: I, input: CanonicalInput, inspect: &mut ProofTreeBuilder, mut prove_goal: impl FnMut(&mut Self, &mut ProofTreeBuilder) -> QueryResult, ) -> QueryResult { self.check_invariants(); // Check for overflow. - let Some(available_depth) = Self::allowed_depth_for_nested(tcx, &self.stack) else { + let Some(available_depth) = Self::allowed_depth_for_nested(cx, &self.stack) else { if let Some(last) = self.stack.raw.last_mut() { last.encountered_overflow = true; } inspect .canonical_goal_evaluation_kind(inspect::WipCanonicalGoalEvaluationKind::Overflow); - return Self::response_no_constraints(tcx, input, Certainty::overflow(true)); + return Self::response_no_constraints(cx, input, Certainty::overflow(true)); }; - if let Some(result) = self.lookup_global_cache(tcx, input, available_depth, inspect) { + if let Some(result) = self.lookup_global_cache(cx, input, available_depth, inspect) { debug!("global cache hit"); return result; } @@ -287,12 +287,12 @@ impl SearchGraph { if let Some(entry) = cache_entry .with_coinductive_stack .as_ref() - .filter(|p| Self::stack_coinductive_from(tcx, &self.stack, p.head)) + .filter(|p| Self::stack_coinductive_from(cx, &self.stack, p.head)) .or_else(|| { cache_entry .with_inductive_stack .as_ref() - .filter(|p| !Self::stack_coinductive_from(tcx, &self.stack, p.head)) + .filter(|p| !Self::stack_coinductive_from(cx, &self.stack, p.head)) }) { debug!("provisional cache hit"); @@ -315,7 +315,7 @@ impl SearchGraph { inspect.canonical_goal_evaluation_kind( inspect::WipCanonicalGoalEvaluationKind::CycleInStack, ); - let is_coinductive_cycle = Self::stack_coinductive_from(tcx, &self.stack, stack_depth); + let is_coinductive_cycle = Self::stack_coinductive_from(cx, &self.stack, stack_depth); let usage_kind = if is_coinductive_cycle { HasBeenUsed::COINDUCTIVE_CYCLE } else { @@ -328,9 +328,9 @@ impl SearchGraph { return if let Some(result) = self.stack[stack_depth].provisional_result { result } else if is_coinductive_cycle { - Self::response_no_constraints(tcx, input, Certainty::Yes) + Self::response_no_constraints(cx, input, Certainty::Yes) } else { - Self::response_no_constraints(tcx, input, Certainty::overflow(false)) + Self::response_no_constraints(cx, input, Certainty::overflow(false)) }; } else { // No entry, we push this goal on the stack and try to prove it. @@ -355,9 +355,9 @@ impl SearchGraph { // not tracked by the cache key and from outside of this anon task, it // must not be added to the global cache. Notably, this is the case for // trait solver cycles participants. - let ((final_entry, result), dep_node) = tcx.with_cached_task(|| { + let ((final_entry, result), dep_node) = cx.with_cached_task(|| { for _ in 0..FIXPOINT_STEP_LIMIT { - match self.fixpoint_step_in_task(tcx, input, inspect, &mut prove_goal) { + match self.fixpoint_step_in_task(cx, input, inspect, &mut prove_goal) { StepResult::Done(final_entry, result) => return (final_entry, result), StepResult::HasChanged => debug!("fixpoint changed provisional results"), } @@ -366,17 +366,17 @@ impl SearchGraph { debug!("canonical cycle overflow"); let current_entry = self.pop_stack(); debug_assert!(current_entry.has_been_used.is_empty()); - let result = Self::response_no_constraints(tcx, input, Certainty::overflow(false)); + let result = Self::response_no_constraints(cx, input, Certainty::overflow(false)); (current_entry, result) }); - let proof_tree = inspect.finalize_canonical_goal_evaluation(tcx); + let proof_tree = inspect.finalize_canonical_goal_evaluation(cx); // We're now done with this goal. In case this goal is involved in a larger cycle // do not remove it from the provisional cache and update its provisional result. // We only add the root of cycles to the global cache. if let Some(head) = final_entry.non_root_cycle_participant { - let coinductive_stack = Self::stack_coinductive_from(tcx, &self.stack, head); + let coinductive_stack = Self::stack_coinductive_from(cx, &self.stack, head); let entry = self.provisional_cache.get_mut(&input).unwrap(); entry.stack_depth = None; @@ -396,8 +396,8 @@ impl SearchGraph { // participant is on the stack. This is necessary to prevent unstable // results. See the comment of `StackEntry::cycle_participants` for // more details. - self.global_cache(tcx).insert( - tcx, + self.global_cache(cx).insert( + cx, input, proof_tree, reached_depth, @@ -418,15 +418,15 @@ impl SearchGraph { /// this goal. fn lookup_global_cache>( &mut self, - tcx: I, + cx: I, input: CanonicalInput, available_depth: SolverLimit, inspect: &mut ProofTreeBuilder, ) -> Option> { let CacheData { result, proof_tree, additional_depth, encountered_overflow } = self - .global_cache(tcx) + .global_cache(cx) // FIXME: Awkward `Limit -> usize -> Limit`. - .get(tcx, input, self.stack.iter().map(|e| e.input), available_depth.0)?; + .get(cx, input, self.stack.iter().map(|e| e.input), available_depth.0)?; // If we're building a proof tree and the current cache entry does not // contain a proof tree, we do not use the entry but instead recompute @@ -467,7 +467,7 @@ impl SearchGraph { /// point we are done. fn fixpoint_step_in_task( &mut self, - tcx: I, + cx: I, input: CanonicalInput, inspect: &mut ProofTreeBuilder, prove_goal: &mut F, @@ -506,9 +506,9 @@ impl SearchGraph { let reached_fixpoint = if let Some(r) = stack_entry.provisional_result { r == result } else if stack_entry.has_been_used == HasBeenUsed::COINDUCTIVE_CYCLE { - Self::response_no_constraints(tcx, input, Certainty::Yes) == result + Self::response_no_constraints(cx, input, Certainty::Yes) == result } else if stack_entry.has_been_used == HasBeenUsed::INDUCTIVE_CYCLE { - Self::response_no_constraints(tcx, input, Certainty::overflow(false)) == result + Self::response_no_constraints(cx, input, Certainty::overflow(false)) == result } else { false }; @@ -528,11 +528,11 @@ impl SearchGraph { } fn response_no_constraints( - tcx: I, + cx: I, goal: CanonicalInput, certainty: Certainty, ) -> QueryResult { - Ok(super::response_no_constraints_raw(tcx, goal.max_universe, goal.variables, certainty)) + Ok(super::response_no_constraints_raw(cx, goal.max_universe, goal.variables, certainty)) } #[allow(rustc::potential_query_instability)] diff --git a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs index 9746c836aff55..2bc9d35c2b020 100644 --- a/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs +++ b/compiler/rustc_next_trait_solver/src/solve/trait_goals.rs @@ -30,8 +30,8 @@ where self.trait_ref } - fn with_self_ty(self, tcx: I, self_ty: I::Ty) -> Self { - self.with_self_ty(tcx, self_ty) + fn with_self_ty(self, cx: I, self_ty: I::Ty) -> Self { + self.with_self_ty(cx, self_ty) } fn trait_def_id(self, _: I) -> I::DefId { @@ -43,18 +43,17 @@ where goal: Goal>, impl_def_id: I::DefId, ) -> Result, NoSolution> { - let tcx = ecx.cx(); + let cx = ecx.cx(); - let impl_trait_ref = tcx.impl_trait_ref(impl_def_id); - if !tcx - .args_may_unify_deep(goal.predicate.trait_ref.args, impl_trait_ref.skip_binder().args) + let impl_trait_ref = cx.impl_trait_ref(impl_def_id); + if !cx.args_may_unify_deep(goal.predicate.trait_ref.args, impl_trait_ref.skip_binder().args) { return Err(NoSolution); } // An upper bound of the certainty of this goal, used to lower the certainty // of reservation impl to ambiguous during coherence. - let impl_polarity = tcx.impl_polarity(impl_def_id); + let impl_polarity = cx.impl_polarity(impl_def_id); let maximal_certainty = match (impl_polarity, goal.predicate.polarity) { // In intercrate mode, this is ambiguous. But outside of intercrate, // it's not a real impl. @@ -77,13 +76,13 @@ where ecx.probe_trait_candidate(CandidateSource::Impl(impl_def_id)).enter(|ecx| { let impl_args = ecx.fresh_args_for_item(impl_def_id); ecx.record_impl_args(impl_args); - let impl_trait_ref = impl_trait_ref.instantiate(tcx, impl_args); + let impl_trait_ref = impl_trait_ref.instantiate(cx, impl_args); ecx.eq(goal.param_env, goal.predicate.trait_ref, impl_trait_ref)?; - let where_clause_bounds = tcx + let where_clause_bounds = cx .predicates_of(impl_def_id) - .iter_instantiated(tcx, impl_args) - .map(|pred| goal.with(tcx, pred)); + .iter_instantiated(cx, impl_args) + .map(|pred| goal.with(cx, pred)); ecx.add_goals(GoalSource::ImplWhereBound, where_clause_bounds); ecx.evaluate_added_goals_and_make_canonical_response(maximal_certainty) @@ -181,13 +180,13 @@ where return Err(NoSolution); } - let tcx = ecx.cx(); + let cx = ecx.cx(); ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc).enter(|ecx| { - let nested_obligations = tcx + let nested_obligations = cx .predicates_of(goal.predicate.def_id()) - .iter_instantiated(tcx, goal.predicate.trait_ref.args) - .map(|p| goal.with(tcx, p)); + .iter_instantiated(cx, goal.predicate.trait_ref.args) + .map(|p| goal.with(cx, p)); // FIXME(-Znext-solver=coinductive): Should this be `GoalSource::ImplWhereBound`? ecx.add_goals(GoalSource::Misc, nested_obligations); ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) @@ -232,13 +231,13 @@ where return Err(NoSolution); } - let tcx = ecx.cx(); + let cx = ecx.cx(); // But if there are inference variables, we have to wait until it's resolved. if (goal.param_env, goal.predicate.self_ty()).has_non_region_infer() { return ecx.forced_ambiguity(MaybeCause::Ambiguity); } - if tcx.layout_is_pointer_like(goal.param_env, goal.predicate.self_ty()) { + if cx.layout_is_pointer_like(goal.param_env, goal.predicate.self_ty()) { ecx.probe_builtin_trait_candidate(BuiltinImplSource::Misc) .enter(|ecx| ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)) } else { @@ -286,10 +285,10 @@ where return Err(NoSolution); } - let tcx = ecx.cx(); + let cx = ecx.cx(); let tupled_inputs_and_output = match structural_traits::extract_tupled_inputs_and_output_from_callable( - tcx, + cx, goal.predicate.self_ty(), goal_kind, )? { @@ -299,14 +298,14 @@ where } }; let output_is_sized_pred = tupled_inputs_and_output.map_bound(|(_, output)| { - ty::TraitRef::new(tcx, tcx.require_lang_item(TraitSolverLangItem::Sized), [output]) + ty::TraitRef::new(cx, cx.require_lang_item(TraitSolverLangItem::Sized), [output]) }); let pred = tupled_inputs_and_output .map_bound(|(inputs, _)| { - ty::TraitRef::new(tcx, goal.predicate.def_id(), [goal.predicate.self_ty(), inputs]) + ty::TraitRef::new(cx, goal.predicate.def_id(), [goal.predicate.self_ty(), inputs]) }) - .upcast(tcx); + .upcast(cx); // A built-in `Fn` impl only holds if the output is sized. // (FIXME: technically we only need to check this if the type is a fn ptr...) Self::probe_and_consider_implied_clause( @@ -314,7 +313,7 @@ where CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal, pred, - [(GoalSource::ImplWhereBound, goal.with(tcx, output_is_sized_pred))], + [(GoalSource::ImplWhereBound, goal.with(cx, output_is_sized_pred))], ) } @@ -327,20 +326,20 @@ where return Err(NoSolution); } - let tcx = ecx.cx(); + let cx = ecx.cx(); let (tupled_inputs_and_output_and_coroutine, nested_preds) = structural_traits::extract_tupled_inputs_and_output_from_async_callable( - tcx, + cx, goal.predicate.self_ty(), goal_kind, // This region doesn't matter because we're throwing away the coroutine type - Region::new_static(tcx), + Region::new_static(cx), )?; let output_is_sized_pred = tupled_inputs_and_output_and_coroutine.map_bound( |AsyncCallableRelevantTypes { output_coroutine_ty, .. }| { ty::TraitRef::new( - tcx, - tcx.require_lang_item(TraitSolverLangItem::Sized), + cx, + cx.require_lang_item(TraitSolverLangItem::Sized), [output_coroutine_ty], ) }, @@ -349,12 +348,12 @@ where let pred = tupled_inputs_and_output_and_coroutine .map_bound(|AsyncCallableRelevantTypes { tupled_inputs_ty, .. }| { ty::TraitRef::new( - tcx, + cx, goal.predicate.def_id(), [goal.predicate.self_ty(), tupled_inputs_ty], ) }) - .upcast(tcx); + .upcast(cx); // A built-in `AsyncFn` impl only holds if the output is sized. // (FIXME: technically we only need to check this if the type is a fn ptr...) Self::probe_and_consider_implied_clause( @@ -362,9 +361,9 @@ where CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal, pred, - [goal.with(tcx, output_is_sized_pred)] + [goal.with(cx, output_is_sized_pred)] .into_iter() - .chain(nested_preds.into_iter().map(|pred| goal.with(tcx, pred))) + .chain(nested_preds.into_iter().map(|pred| goal.with(cx, pred))) .map(|goal| (GoalSource::ImplWhereBound, goal)), ) } @@ -437,8 +436,8 @@ where }; // Coroutines are not futures unless they come from `async` desugaring - let tcx = ecx.cx(); - if !tcx.coroutine_is_async(def_id) { + let cx = ecx.cx(); + if !cx.coroutine_is_async(def_id) { return Err(NoSolution); } @@ -463,8 +462,8 @@ where }; // Coroutines are not iterators unless they come from `gen` desugaring - let tcx = ecx.cx(); - if !tcx.coroutine_is_gen(def_id) { + let cx = ecx.cx(); + if !cx.coroutine_is_gen(def_id) { return Err(NoSolution); } @@ -489,8 +488,8 @@ where }; // Coroutines are not iterators unless they come from `gen` desugaring - let tcx = ecx.cx(); - if !tcx.coroutine_is_gen(def_id) { + let cx = ecx.cx(); + if !cx.coroutine_is_gen(def_id) { return Err(NoSolution); } @@ -513,8 +512,8 @@ where }; // Coroutines are not iterators unless they come from `gen` desugaring - let tcx = ecx.cx(); - if !tcx.coroutine_is_async_gen(def_id) { + let cx = ecx.cx(); + if !cx.coroutine_is_async_gen(def_id) { return Err(NoSolution); } @@ -540,8 +539,8 @@ where }; // `async`-desugared coroutines do not implement the coroutine trait - let tcx = ecx.cx(); - if !tcx.is_general_coroutine(def_id) { + let cx = ecx.cx(); + if !cx.is_general_coroutine(def_id) { return Err(NoSolution); } @@ -550,8 +549,8 @@ where ecx, CandidateSource::BuiltinImpl(BuiltinImplSource::Misc), goal, - ty::TraitRef::new(tcx, goal.predicate.def_id(), [self_ty, coroutine.resume_ty()]) - .upcast(tcx), + ty::TraitRef::new(cx, goal.predicate.def_id(), [self_ty, coroutine.resume_ty()]) + .upcast(cx), // Technically, we need to check that the coroutine types are Sized, // but that's already proven by the coroutine being WF. [], @@ -727,7 +726,7 @@ where b_data: I::BoundExistentialPredicates, b_region: I::Region, ) -> Vec> { - let tcx = self.cx(); + let cx = self.cx(); let Goal { predicate: (a_ty, _b_ty), .. } = goal; let mut responses = vec![]; @@ -745,7 +744,7 @@ where )); } else if let Some(a_principal) = a_data.principal() { for new_a_principal in - D::elaborate_supertraits(self.cx(), a_principal.with_self_ty(tcx, a_ty)).skip(1) + D::elaborate_supertraits(self.cx(), a_principal.with_self_ty(cx, a_ty)).skip(1) { responses.extend(self.consider_builtin_upcast_to_principal( goal, @@ -755,7 +754,7 @@ where b_data, b_region, Some(new_a_principal.map_bound(|trait_ref| { - ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref) + ty::ExistentialTraitRef::erase_self_ty(cx, trait_ref) })), )); } @@ -770,11 +769,11 @@ where b_data: I::BoundExistentialPredicates, b_region: I::Region, ) -> Result, NoSolution> { - let tcx = self.cx(); + let cx = self.cx(); let Goal { predicate: (a_ty, _), .. } = goal; // Can only unsize to an object-safe trait. - if b_data.principal_def_id().is_some_and(|def_id| !tcx.trait_is_object_safe(def_id)) { + if b_data.principal_def_id().is_some_and(|def_id| !cx.trait_is_object_safe(def_id)) { return Err(NoSolution); } @@ -783,24 +782,20 @@ where // (i.e. the principal, all of the associated types match, and any auto traits) ecx.add_goals( GoalSource::ImplWhereBound, - b_data.iter().map(|pred| goal.with(tcx, pred.with_self_ty(tcx, a_ty))), + b_data.iter().map(|pred| goal.with(cx, pred.with_self_ty(cx, a_ty))), ); // The type must be `Sized` to be unsized. ecx.add_goal( GoalSource::ImplWhereBound, goal.with( - tcx, - ty::TraitRef::new( - tcx, - tcx.require_lang_item(TraitSolverLangItem::Sized), - [a_ty], - ), + cx, + ty::TraitRef::new(cx, cx.require_lang_item(TraitSolverLangItem::Sized), [a_ty]), ), ); // The type must outlive the lifetime of the `dyn` we're unsizing into. - ecx.add_goal(GoalSource::Misc, goal.with(tcx, ty::OutlivesPredicate(a_ty, b_region))); + ecx.add_goal(GoalSource::Misc, goal.with(cx, ty::OutlivesPredicate(a_ty, b_region))); ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes) }) } @@ -941,28 +936,28 @@ where a_args: I::GenericArgs, b_args: I::GenericArgs, ) -> Result, NoSolution> { - let tcx = self.cx(); + let cx = self.cx(); let Goal { predicate: (_a_ty, b_ty), .. } = goal; - let unsizing_params = tcx.unsizing_params_for_adt(def.def_id()); + let unsizing_params = cx.unsizing_params_for_adt(def.def_id()); // We must be unsizing some type parameters. This also implies // that the struct has a tail field. if unsizing_params.is_empty() { return Err(NoSolution); } - let tail_field_ty = def.struct_tail_ty(tcx).unwrap(); + let tail_field_ty = def.struct_tail_ty(cx).unwrap(); - let a_tail_ty = tail_field_ty.instantiate(tcx, a_args); - let b_tail_ty = tail_field_ty.instantiate(tcx, b_args); + let a_tail_ty = tail_field_ty.instantiate(cx, a_args); + let b_tail_ty = tail_field_ty.instantiate(cx, b_args); // Instantiate just the unsizing params from B into A. The type after // this instantiation must be equal to B. This is so we don't unsize // unrelated type parameters. - let new_a_args = tcx.mk_args_from_iter(a_args.iter().enumerate().map(|(i, a)| { + let new_a_args = cx.mk_args_from_iter(a_args.iter().enumerate().map(|(i, a)| { if unsizing_params.contains(i as u32) { b_args.get(i).unwrap() } else { a } })); - let unsized_a_ty = Ty::new_adt(tcx, def, new_a_args); + let unsized_a_ty = Ty::new_adt(cx, def, new_a_args); // Finally, we require that `TailA: Unsize` for the tail field // types. @@ -970,10 +965,10 @@ where self.add_goal( GoalSource::ImplWhereBound, goal.with( - tcx, + cx, ty::TraitRef::new( - tcx, - tcx.require_lang_item(TraitSolverLangItem::Unsize), + cx, + cx.require_lang_item(TraitSolverLangItem::Unsize), [a_tail_ty, b_tail_ty], ), ), @@ -998,25 +993,24 @@ where a_tys: I::Tys, b_tys: I::Tys, ) -> Result, NoSolution> { - let tcx = self.cx(); + let cx = self.cx(); let Goal { predicate: (_a_ty, b_ty), .. } = goal; let (&a_last_ty, a_rest_tys) = a_tys.split_last().unwrap(); let b_last_ty = b_tys.last().unwrap(); // Instantiate just the tail field of B., and require that they're equal. - let unsized_a_ty = - Ty::new_tup_from_iter(tcx, a_rest_tys.iter().copied().chain([b_last_ty])); + let unsized_a_ty = Ty::new_tup_from_iter(cx, a_rest_tys.iter().copied().chain([b_last_ty])); self.eq(goal.param_env, unsized_a_ty, b_ty)?; // Similar to ADTs, require that we can unsize the tail. self.add_goal( GoalSource::ImplWhereBound, goal.with( - tcx, + cx, ty::TraitRef::new( - tcx, - tcx.require_lang_item(TraitSolverLangItem::Unsize), + cx, + cx.require_lang_item(TraitSolverLangItem::Unsize), [a_last_ty, b_last_ty], ), ), From cf0251d92ced77d926a2292df96cb9ad3ce14f97 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 17 Jun 2024 18:47:09 +1000 Subject: [PATCH 11/12] Fix a span in `parse_ty_bare_fn`. It currently goes one token too far. Example: line 259 of `tests/ui/abi/compatibility.rs`: ``` test_abi_compatible!(fn_fn, fn(), fn(i32) -> i32); ``` This commit changes the span for the second element from `fn(),` to `fn()`, i.e. removes the extraneous comma. --- compiler/rustc_ast/src/ast.rs | 3 ++- compiler/rustc_parse/src/parser/ty.rs | 2 +- tests/ui/rust-2024/safe-outside-extern.gated.stderr | 2 +- tests/ui/rust-2024/safe-outside-extern.ungated.stderr | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index 30c54ef2d3c41..4a3ce0e0c3066 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -2126,7 +2126,8 @@ pub struct BareFnTy { pub ext: Extern, pub generic_params: ThinVec, pub decl: P, - /// Span of the `fn(...) -> ...` part. + /// Span of the `[unsafe] [extern] fn(...) -> ...` part, i.e. everything + /// after the generic params (if there are any, e.g. `for<'a>`). pub decl_span: Span, } diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index fcd623b477f5d..d2043c353fed9 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -608,7 +608,7 @@ impl<'a> Parser<'a> { self.dcx().emit_err(FnPointerCannotBeAsync { span: whole_span, qualifier: span }); } // FIXME(gen_blocks): emit a similar error for `gen fn()` - let decl_span = span_start.to(self.token.span); + let decl_span = span_start.to(self.prev_token.span); Ok(TyKind::BareFn(P(BareFnTy { ext, safety, generic_params: params, decl, decl_span }))) } diff --git a/tests/ui/rust-2024/safe-outside-extern.gated.stderr b/tests/ui/rust-2024/safe-outside-extern.gated.stderr index ea7aa1814459d..18a3361f35b8e 100644 --- a/tests/ui/rust-2024/safe-outside-extern.gated.stderr +++ b/tests/ui/rust-2024/safe-outside-extern.gated.stderr @@ -26,7 +26,7 @@ error: function pointers cannot be declared with `safe` safety qualifier --> $DIR/safe-outside-extern.rs:24:14 | LL | type FnPtr = safe fn(i32, i32) -> i32; - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^ error: aborting due to 5 previous errors diff --git a/tests/ui/rust-2024/safe-outside-extern.ungated.stderr b/tests/ui/rust-2024/safe-outside-extern.ungated.stderr index 908f5b504eb23..9ea6d451e8c47 100644 --- a/tests/ui/rust-2024/safe-outside-extern.ungated.stderr +++ b/tests/ui/rust-2024/safe-outside-extern.ungated.stderr @@ -26,7 +26,7 @@ error: function pointers cannot be declared with `safe` safety qualifier --> $DIR/safe-outside-extern.rs:24:14 | LL | type FnPtr = safe fn(i32, i32) -> i32; - | ^^^^^^^^^^^^^^^^^^^^^^^^^ + | ^^^^^^^^^^^^^^^^^^^^^^^^ error[E0658]: `unsafe extern {}` blocks and `safe` keyword are experimental --> $DIR/safe-outside-extern.rs:4:1 From 0addda65788642c9967cd151eff953be1ddee32f Mon Sep 17 00:00:00 2001 From: yukang Date: Wed, 26 Jun 2024 08:44:59 +0800 Subject: [PATCH 12/12] Fix bad replacement for unsafe extern block suggestion --- compiler/rustc_ast_passes/src/ast_validation.rs | 2 +- compiler/rustc_ast_passes/src/errors.rs | 2 +- tests/ui/parser/fn-header-semantic-fail.stderr | 16 ++++++++++------ .../ui/parser/no-const-fn-in-extern-block.stderr | 8 +++++--- tests/ui/parser/unsafe-foreign-mod-2.stderr | 8 +++++--- ...-on-unadorned-extern-block.edition2021.stderr | 16 ++++++++++------ ...-on-unadorned-extern-block.edition2024.stderr | 16 ++++++++++------ .../unsafe-on-extern-block-issue-126756.fixed | 10 ++++++++++ .../unsafe-on-extern-block-issue-126756.rs | 10 ++++++++++ .../unsafe-on-extern-block-issue-126756.stderr | 13 +++++++++++++ 10 files changed, 75 insertions(+), 26 deletions(-) create mode 100644 tests/ui/rust-2024/unsafe-extern-blocks/unsafe-on-extern-block-issue-126756.fixed create mode 100644 tests/ui/rust-2024/unsafe-extern-blocks/unsafe-on-extern-block-issue-126756.rs create mode 100644 tests/ui/rust-2024/unsafe-extern-blocks/unsafe-on-extern-block-issue-126756.stderr diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 79717c969d79a..6cff5392f958a 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -464,7 +464,7 @@ impl<'a> AstValidator<'a> { { self.dcx().emit_err(errors::InvalidSafetyOnExtern { item_span: span, - block: self.current_extern_span(), + block: self.current_extern_span().shrink_to_lo(), }); } } diff --git a/compiler/rustc_ast_passes/src/errors.rs b/compiler/rustc_ast_passes/src/errors.rs index 96c476b271c60..965d8fac712ae 100644 --- a/compiler/rustc_ast_passes/src/errors.rs +++ b/compiler/rustc_ast_passes/src/errors.rs @@ -221,7 +221,7 @@ pub enum ExternBlockSuggestion { pub struct InvalidSafetyOnExtern { #[primary_span] pub item_span: Span, - #[suggestion(code = "", applicability = "maybe-incorrect")] + #[suggestion(code = "unsafe ", applicability = "machine-applicable", style = "verbose")] pub block: Span, } diff --git a/tests/ui/parser/fn-header-semantic-fail.stderr b/tests/ui/parser/fn-header-semantic-fail.stderr index 29404f1793ba8..b519ddbe2b436 100644 --- a/tests/ui/parser/fn-header-semantic-fail.stderr +++ b/tests/ui/parser/fn-header-semantic-fail.stderr @@ -81,11 +81,13 @@ LL | async fn fe1(); error: items in unadorned `extern` blocks cannot have safety qualifiers --> $DIR/fn-header-semantic-fail.rs:47:9 | -LL | extern "C" { - | ---------- help: add unsafe to this `extern` block -LL | async fn fe1(); LL | unsafe fn fe2(); | ^^^^^^^^^^^^^^^^ + | +help: add unsafe to this `extern` block + | +LL | unsafe extern "C" { + | ++++++ error: functions in `extern` blocks cannot have qualifiers --> $DIR/fn-header-semantic-fail.rs:48:9 @@ -135,11 +137,13 @@ LL | const async unsafe extern "C" fn fe5(); error: items in unadorned `extern` blocks cannot have safety qualifiers --> $DIR/fn-header-semantic-fail.rs:50:9 | -LL | extern "C" { - | ---------- help: add unsafe to this `extern` block -... LL | const async unsafe extern "C" fn fe5(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + | +help: add unsafe to this `extern` block + | +LL | unsafe extern "C" { + | ++++++ error: functions cannot be both `const` and `async` --> $DIR/fn-header-semantic-fail.rs:50:9 diff --git a/tests/ui/parser/no-const-fn-in-extern-block.stderr b/tests/ui/parser/no-const-fn-in-extern-block.stderr index f575acc839d1c..8c23824a70888 100644 --- a/tests/ui/parser/no-const-fn-in-extern-block.stderr +++ b/tests/ui/parser/no-const-fn-in-extern-block.stderr @@ -18,11 +18,13 @@ LL | const unsafe fn bar(); error: items in unadorned `extern` blocks cannot have safety qualifiers --> $DIR/no-const-fn-in-extern-block.rs:4:5 | -LL | extern "C" { - | ---------- help: add unsafe to this `extern` block -... LL | const unsafe fn bar(); | ^^^^^^^^^^^^^^^^^^^^^^ + | +help: add unsafe to this `extern` block + | +LL | unsafe extern "C" { + | ++++++ error: aborting due to 3 previous errors diff --git a/tests/ui/parser/unsafe-foreign-mod-2.stderr b/tests/ui/parser/unsafe-foreign-mod-2.stderr index e59352395ed6e..77a383d5efa26 100644 --- a/tests/ui/parser/unsafe-foreign-mod-2.stderr +++ b/tests/ui/parser/unsafe-foreign-mod-2.stderr @@ -13,11 +13,13 @@ LL | extern "C" unsafe { error: items in unadorned `extern` blocks cannot have safety qualifiers --> $DIR/unsafe-foreign-mod-2.rs:4:5 | -LL | extern "C" unsafe { - | ----------------- help: add unsafe to this `extern` block -... LL | unsafe fn foo(); | ^^^^^^^^^^^^^^^^ + | +help: add unsafe to this `extern` block + | +LL | unsafe extern "C" unsafe { + | ++++++ error: aborting due to 3 previous errors diff --git a/tests/ui/rust-2024/unsafe-extern-blocks/safe-unsafe-on-unadorned-extern-block.edition2021.stderr b/tests/ui/rust-2024/unsafe-extern-blocks/safe-unsafe-on-unadorned-extern-block.edition2021.stderr index 411cf48b4866a..e90613357b1ca 100644 --- a/tests/ui/rust-2024/unsafe-extern-blocks/safe-unsafe-on-unadorned-extern-block.edition2021.stderr +++ b/tests/ui/rust-2024/unsafe-extern-blocks/safe-unsafe-on-unadorned-extern-block.edition2021.stderr @@ -1,20 +1,24 @@ error: items in unadorned `extern` blocks cannot have safety qualifiers --> $DIR/safe-unsafe-on-unadorned-extern-block.rs:10:5 | -LL | extern "C" { - | ---------- help: add unsafe to this `extern` block -LL | LL | safe static TEST1: i32; | ^^^^^^^^^^^^^^^^^^^^^^^ + | +help: add unsafe to this `extern` block + | +LL | unsafe extern "C" { + | ++++++ error: items in unadorned `extern` blocks cannot have safety qualifiers --> $DIR/safe-unsafe-on-unadorned-extern-block.rs:12:5 | -LL | extern "C" { - | ---------- help: add unsafe to this `extern` block -... LL | safe fn test1(i: i32); | ^^^^^^^^^^^^^^^^^^^^^^ + | +help: add unsafe to this `extern` block + | +LL | unsafe extern "C" { + | ++++++ error: aborting due to 2 previous errors diff --git a/tests/ui/rust-2024/unsafe-extern-blocks/safe-unsafe-on-unadorned-extern-block.edition2024.stderr b/tests/ui/rust-2024/unsafe-extern-blocks/safe-unsafe-on-unadorned-extern-block.edition2024.stderr index b634adc299960..1207ee158cc13 100644 --- a/tests/ui/rust-2024/unsafe-extern-blocks/safe-unsafe-on-unadorned-extern-block.edition2024.stderr +++ b/tests/ui/rust-2024/unsafe-extern-blocks/safe-unsafe-on-unadorned-extern-block.edition2024.stderr @@ -13,20 +13,24 @@ LL | | } error: items in unadorned `extern` blocks cannot have safety qualifiers --> $DIR/safe-unsafe-on-unadorned-extern-block.rs:10:5 | -LL | extern "C" { - | ---------- help: add unsafe to this `extern` block -LL | LL | safe static TEST1: i32; | ^^^^^^^^^^^^^^^^^^^^^^^ + | +help: add unsafe to this `extern` block + | +LL | unsafe extern "C" { + | ++++++ error: items in unadorned `extern` blocks cannot have safety qualifiers --> $DIR/safe-unsafe-on-unadorned-extern-block.rs:12:5 | -LL | extern "C" { - | ---------- help: add unsafe to this `extern` block -... LL | safe fn test1(i: i32); | ^^^^^^^^^^^^^^^^^^^^^^ + | +help: add unsafe to this `extern` block + | +LL | unsafe extern "C" { + | ++++++ error: aborting due to 3 previous errors diff --git a/tests/ui/rust-2024/unsafe-extern-blocks/unsafe-on-extern-block-issue-126756.fixed b/tests/ui/rust-2024/unsafe-extern-blocks/unsafe-on-extern-block-issue-126756.fixed new file mode 100644 index 0000000000000..2ff595cc44d1e --- /dev/null +++ b/tests/ui/rust-2024/unsafe-extern-blocks/unsafe-on-extern-block-issue-126756.fixed @@ -0,0 +1,10 @@ +//@ run-rustfix + +#![feature(unsafe_extern_blocks)] +#![allow(dead_code)] + +unsafe extern "C" { + unsafe fn foo(); //~ ERROR items in unadorned `extern` blocks cannot have safety qualifiers +} + +fn main() {} diff --git a/tests/ui/rust-2024/unsafe-extern-blocks/unsafe-on-extern-block-issue-126756.rs b/tests/ui/rust-2024/unsafe-extern-blocks/unsafe-on-extern-block-issue-126756.rs new file mode 100644 index 0000000000000..6fe43f7a5b46d --- /dev/null +++ b/tests/ui/rust-2024/unsafe-extern-blocks/unsafe-on-extern-block-issue-126756.rs @@ -0,0 +1,10 @@ +//@ run-rustfix + +#![feature(unsafe_extern_blocks)] +#![allow(dead_code)] + +extern "C" { + unsafe fn foo(); //~ ERROR items in unadorned `extern` blocks cannot have safety qualifiers +} + +fn main() {} diff --git a/tests/ui/rust-2024/unsafe-extern-blocks/unsafe-on-extern-block-issue-126756.stderr b/tests/ui/rust-2024/unsafe-extern-blocks/unsafe-on-extern-block-issue-126756.stderr new file mode 100644 index 0000000000000..05d23d001ada7 --- /dev/null +++ b/tests/ui/rust-2024/unsafe-extern-blocks/unsafe-on-extern-block-issue-126756.stderr @@ -0,0 +1,13 @@ +error: items in unadorned `extern` blocks cannot have safety qualifiers + --> $DIR/unsafe-on-extern-block-issue-126756.rs:7:5 + | +LL | unsafe fn foo(); + | ^^^^^^^^^^^^^^^^ + | +help: add unsafe to this `extern` block + | +LL | unsafe extern "C" { + | ++++++ + +error: aborting due to 1 previous error +