Skip to content

Commit

Permalink
Auto merge of #118937 - lcnr:rename-solver-flag, r=compiler-errors
Browse files Browse the repository at this point in the history
`-Ztrait-solver=next` to `-Znext-solver`

renames the feature flag to enable the new trait solver.

still want some feedback before merging: https://rust-lang.zulipchat.com/#narrow/stream/364551-t-types.2Ftrait-system-refactor/topic/renaming.20the.20feature.20flag.20to.20.60-Znew-solver.60.

The idea is to make it easier to add another option, e.g. to enable the solver in wfcheck or to optionally change its behavior to our new coinduction approach.

r? `@compiler-errors`
  • Loading branch information
bors committed Dec 14, 2023
2 parents 529047c + fa03289 commit 2ecba0f
Show file tree
Hide file tree
Showing 274 changed files with 345 additions and 333 deletions.
2 changes: 1 addition & 1 deletion compiler/rustc_borrowck/src/region_infer/opaque_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,7 +315,7 @@ fn check_opaque_type_well_formed<'tcx>(
parent_def_id = tcx.local_parent(parent_def_id);
}

// FIXME(-Ztrait-solver=next): We probably should use `DefiningAnchor::Error`
// FIXME(-Znext-solver): We probably should use `DefiningAnchor::Error`
// and prepopulate this `InferCtxt` with known opaque values, rather than
// using the `Bind` anchor here. For now it's fine.
let infcx = tcx
Expand Down
6 changes: 3 additions & 3 deletions compiler/rustc_borrowck/src/type_check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1003,16 +1003,16 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
reported_errors: Default::default(),
};

// FIXME(-Ztrait-solver=next): A bit dubious that we're only registering
// FIXME(-Znext-solver): A bit dubious that we're only registering
// predefined opaques in the typeck root.
if infcx.next_trait_solver() && !infcx.tcx.is_typeck_child(body.source.def_id()) {
checker.register_predefined_opaques_in_new_solver();
checker.register_predefined_opaques_for_next_solver();
}

checker
}

pub(super) fn register_predefined_opaques_in_new_solver(&mut self) {
pub(super) fn register_predefined_opaques_for_next_solver(&mut self) {
// OK to use the identity arguments for each opaque type key, since
// we remap opaques from HIR typeck back to their definition params.
let opaques: Vec<_> = self
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copied from https://github.com/rust-lang/rust/blob/46455dc65069387f2dc46612f13fd45452ab301a/tests/ui/coroutine/gen_block_iterate.rs
// revisions: next old
//compile-flags: --edition 2024 -Zunstable-options
//[next] compile-flags: -Ztrait-solver=next
//[next] compile-flags: -Znext-solver
// run-pass
#![feature(gen_blocks)]

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_hir_analysis/src/check/compare_impl_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ fn compare_method_predicate_entailment<'tcx>(
if check_implied_wf == CheckImpliedWfMode::Check && !(impl_sig, trait_sig).references_error() {
// Select obligations to make progress on inference before processing
// the wf obligation below.
// FIXME(-Ztrait-solver=next): Not needed when the hack below is removed.
// FIXME(-Znext-solver): Not needed when the hack below is removed.
let errors = ocx.select_where_possible();
if !errors.is_empty() {
let reported = infcx.err_ctxt().report_fulfillment_errors(errors);
Expand All @@ -333,7 +333,7 @@ fn compare_method_predicate_entailment<'tcx>(
// trigger the lint. Instead, let's only consider type outlives and
// region outlives obligations.
//
// FIXME(-Ztrait-solver=next): Try removing this hack again once
// FIXME(-Znext-solver): Try removing this hack again once
// the new solver is stable.
let mut wf_args: smallvec::SmallVec<[_; 4]> =
unnormalized_impl_sig.inputs_and_output.iter().map(|ty| ty.into()).collect();
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/coercion.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1019,7 +1019,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// Returns false if the coercion creates any obligations that result in
/// errors.
pub fn can_coerce(&self, expr_ty: Ty<'tcx>, target: Ty<'tcx>) -> bool {
// FIXME(-Ztrait-solver=next): We need to structurally resolve both types here.
// FIXME(-Znext-solver): We need to structurally resolve both types here.
let source = self.resolve_vars_with_obligations(expr_ty);
debug!("coercion::can_with_predicates({:?} -> {:?})", source, target);

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/fn_ctxt/_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
/// version (resolve_vars_if_possible), this version will
/// also select obligations if it seems useful, in an effort
/// to get more type information.
// FIXME(-Ztrait-solver=next): A lot of the calls to this method should
// FIXME(-Znext-solver): A lot of the calls to this method should
// probably be `try_structurally_resolve_type` or `structurally_resolve_type` instead.
#[instrument(skip(self), level = "debug", ret)]
pub(in super::super) fn resolve_vars_with_obligations(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_infer/src/infer/canonical/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ impl<'tcx> InferCtxt<'tcx> {
/// variable, then you'll get a new inference variable; if it is a
/// universally quantified variable, you get a placeholder.
///
/// FIXME(-Ztrait-solver=next): This is public because it's used by the
/// FIXME(-Znext-solver): This is public because it's used by the
/// new trait solver which has a different canonicalization routine.
/// We should somehow deduplicate all of this.
pub fn instantiate_canonical_var(
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_infer/src/infer/canonical/substitute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use rustc_middle::ty::fold::{FnMutDelegate, TypeFoldable};
use rustc_middle::ty::GenericArgKind;
use rustc_middle::ty::{self, TyCtxt};

/// FIXME(-Ztrait-solver=next): This or public because it is shared with the
/// FIXME(-Znext-solver): This or public because it is shared with the
/// new trait solver implementation. We should deduplicate canonicalization.
pub trait CanonicalExt<'tcx, V> {
/// Instantiate the wrapped value, replacing each canonical value
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_infer/src/traits/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ pub enum FulfillmentErrorCode<'tcx> {
CodeSubtypeError(ExpectedFound<Ty<'tcx>>, TypeError<'tcx>), // always comes from a SubtypePredicate
CodeConstEquateError(ExpectedFound<Const<'tcx>>, TypeError<'tcx>),
CodeAmbiguity {
/// Overflow reported from the new solver `-Ztrait-solver=next`, which will
/// Overflow reported from the new solver `-Znext-solver`, which will
/// be reported as an regular error as opposed to a fatal error.
overflow: bool,
},
Expand Down
12 changes: 7 additions & 5 deletions compiler/rustc_interface/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@ use rustc_session::config::{
build_configuration, build_session_options, rustc_optgroups, BranchProtection, CFGuard, Cfg,
DebugInfo, DumpMonoStatsFormat, ErrorOutputType, ExternEntry, ExternLocation, Externs,
FunctionReturn, InliningThreshold, Input, InstrumentCoverage, InstrumentXRay,
LinkSelfContained, LinkerPluginLto, LocationDetail, LtoCli, MirSpanview, OomStrategy, Options,
OutFileName, OutputType, OutputTypes, PAuthKey, PacRet, Passes, Polonius,
ProcMacroExecutionStrategy, Strip, SwitchWithOptPath, SymbolManglingVersion, TraitSolver,
WasiExecModel,
LinkSelfContained, LinkerPluginLto, LocationDetail, LtoCli, MirSpanview, NextSolverConfig,
OomStrategy, Options, OutFileName, OutputType, OutputTypes, PAuthKey, PacRet, Passes, Polonius,
ProcMacroExecutionStrategy, Strip, SwitchWithOptPath, SymbolManglingVersion, WasiExecModel,
};
use rustc_session::lint::Level;
use rustc_session::search_paths::SearchPath;
Expand Down Expand Up @@ -781,6 +780,10 @@ fn test_unstable_options_tracking_hash() {
tracked!(mir_opt_level, Some(4));
tracked!(move_size_limit, Some(4096));
tracked!(mutable_noalias, false);
tracked!(
next_solver,
Some(NextSolverConfig { coherence: true, globally: false, dump_tree: Default::default() })
);
tracked!(no_generate_arange_section, true);
tracked!(no_jump_tables, true);
tracked!(no_link, true);
Expand Down Expand Up @@ -822,7 +825,6 @@ fn test_unstable_options_tracking_hash() {
tracked!(thir_unsafeck, true);
tracked!(tiny_const_eval_limit, true);
tracked!(tls_model, Some(TlsModel::GeneralDynamic));
tracked!(trait_solver, TraitSolver::NextCoherence);
tracked!(translate_remapped_path_to_local_path, false);
tracked!(trap_unreachable, Some(false));
tracked!(treat_err_as_bug, NonZeroUsize::new(1));
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/traits/solve/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use rustc_data_structures::sync::Lock;
use rustc_query_system::cache::WithDepNode;
use rustc_query_system::dep_graph::DepNodeIndex;
use rustc_session::Limit;
/// The trait solver cache used by `-Ztrait-solver=next`.
/// The trait solver cache used by `-Znext-solver`.
///
/// FIXME(@lcnr): link to some official documentation of how
/// this works.
Expand Down
8 changes: 2 additions & 6 deletions compiler/rustc_middle/src/ty/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2240,15 +2240,11 @@ impl<'tcx> TyCtxt<'tcx> {
}

pub fn next_trait_solver_globally(self) -> bool {
self.sess.opts.unstable_opts.trait_solver == rustc_session::config::TraitSolver::Next
self.sess.opts.unstable_opts.next_solver.map_or(false, |c| c.globally)
}

pub fn next_trait_solver_in_coherence(self) -> bool {
matches!(
self.sess.opts.unstable_opts.trait_solver,
rustc_session::config::TraitSolver::Next
| rustc_session::config::TraitSolver::NextCoherence
)
self.sess.opts.unstable_opts.next_solver.map_or(false, |c| c.coherence)
}

pub fn is_impl_trait_in_trait(self, def_id: DefId) -> bool {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/fast_reject.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ pub enum TreatParams {
///
/// N.B. during deep rejection, this acts identically to `ForLookup`.
///
/// FIXME(-Ztrait-solver=next): Remove this variant and cleanup
/// FIXME(-Znext-solver): Remove this variant and cleanup
/// the code.
NextSolverLookup,
}
Expand Down
25 changes: 13 additions & 12 deletions compiler/rustc_session/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -755,13 +755,14 @@ pub enum PrintKind {
}

#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
pub enum TraitSolver {
/// Classic trait solver in `rustc_trait_selection::traits::select`
Classic,
/// Experimental trait solver in `rustc_trait_selection::solve`
Next,
/// Use the new trait solver during coherence
NextCoherence,
pub struct NextSolverConfig {
/// Whether the new trait solver should be enabled in coherence.
pub coherence: bool,
/// Whether the new trait solver should be enabled everywhere.
/// This is only `true` if `coherence` is also enabled.
pub globally: bool,
/// Whether to dump proof trees after computing a proof tree.
pub dump_tree: DumpSolverProofTree,
}

#[derive(Default, Debug, Copy, Clone, Hash, PartialEq, Eq)]
Expand Down Expand Up @@ -3220,10 +3221,10 @@ pub(crate) mod dep_tracking {
use super::{
BranchProtection, CFGuard, CFProtection, CrateType, DebugInfo, DebugInfoCompression,
ErrorOutputType, FunctionReturn, InliningThreshold, InstrumentCoverage, InstrumentXRay,
LinkerPluginLto, LocationDetail, LtoCli, OomStrategy, OptLevel, OutFileName, OutputType,
OutputTypes, Polonius, RemapPathScopeComponents, ResolveDocLinks, SourceFileHashAlgorithm,
SplitDwarfKind, SwitchWithOptPath, SymbolManglingVersion, TraitSolver, TrimmedDefPaths,
WasiExecModel,
LinkerPluginLto, LocationDetail, LtoCli, NextSolverConfig, OomStrategy, OptLevel,
OutFileName, OutputType, OutputTypes, Polonius, RemapPathScopeComponents, ResolveDocLinks,
SourceFileHashAlgorithm, SplitDwarfKind, SwitchWithOptPath, SymbolManglingVersion,
TrimmedDefPaths, WasiExecModel,
};
use crate::lint;
use crate::utils::NativeLib;
Expand Down Expand Up @@ -3326,7 +3327,7 @@ pub(crate) mod dep_tracking {
BranchProtection,
OomStrategy,
LanguageIdentifier,
TraitSolver,
NextSolverConfig,
Polonius,
InliningThreshold,
FunctionReturn,
Expand Down
73 changes: 44 additions & 29 deletions compiler/rustc_session/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,8 +396,7 @@ mod desc {
pub const parse_instrument_xray: &str = "either a boolean (`yes`, `no`, `on`, `off`, etc), or a comma separated list of settings: `always` or `never` (mutually exclusive), `ignore-loops`, `instruction-threshold=N`, `skip-entry`, `skip-exit`";
pub const parse_unpretty: &str = "`string` or `string=string`";
pub const parse_treat_err_as_bug: &str = "either no value or a non-negative number";
pub const parse_trait_solver: &str =
"one of the supported solver modes (`classic`, `next`, or `next-coherence`)";
pub const parse_next_solver_config: &str = "a comma separated list of solver configurations: `globally` (default), `coherence`, `dump-tree`, `dump-tree-on-error";
pub const parse_lto: &str =
"either a boolean (`yes`, `no`, `on`, `off`, etc), `thin`, `fat`, or omitted";
pub const parse_linker_plugin_lto: &str =
Expand Down Expand Up @@ -429,7 +428,6 @@ mod desc {
"a `,` separated combination of `bti`, `b-key`, `pac-ret`, or `leaf`";
pub const parse_proc_macro_execution_strategy: &str =
"one of supported execution strategies (`same-thread`, or `cross-thread`)";
pub const parse_dump_solver_proof_tree: &str = "one of: `always`, `on-request`, `on-error`";
pub const parse_remap_path_scope: &str = "comma separated list of scopes: `macro`, `diagnostics`, `unsplit-debuginfo`, `split-debuginfo`, `split-debuginfo-path`, `object`, `all`";
pub const parse_inlining_threshold: &str =
"either a boolean (`yes`, `no`, `on`, `off`, etc), or a non-negative number";
Expand Down Expand Up @@ -1032,15 +1030,48 @@ mod parse {
}
}

pub(crate) fn parse_trait_solver(slot: &mut TraitSolver, v: Option<&str>) -> bool {
match v {
Some("classic") => *slot = TraitSolver::Classic,
Some("next") => *slot = TraitSolver::Next,
Some("next-coherence") => *slot = TraitSolver::NextCoherence,
// default trait solver is subject to change..
Some("default") => *slot = TraitSolver::Classic,
_ => return false,
pub(crate) fn parse_next_solver_config(
slot: &mut Option<NextSolverConfig>,
v: Option<&str>,
) -> bool {
if let Some(config) = v {
let mut coherence = false;
let mut globally = true;
let mut dump_tree = None;
for c in config.split(',') {
match c {
"globally" => globally = true,
"coherence" => {
globally = false;
coherence = true;
}
"dump-tree" => {
if dump_tree.replace(DumpSolverProofTree::Always).is_some() {
return false;
}
}
"dump-tree-on-error" => {
if dump_tree.replace(DumpSolverProofTree::OnError).is_some() {
return false;
}
}
_ => return false,
}
}

*slot = Some(NextSolverConfig {
coherence: coherence || globally,
globally,
dump_tree: dump_tree.unwrap_or_default(),
});
} else {
*slot = Some(NextSolverConfig {
coherence: true,
globally: true,
dump_tree: Default::default(),
});
}

true
}

Expand Down Expand Up @@ -1305,19 +1336,6 @@ mod parse {
true
}

pub(crate) fn parse_dump_solver_proof_tree(
slot: &mut DumpSolverProofTree,
v: Option<&str>,
) -> bool {
match v {
None | Some("always") => *slot = DumpSolverProofTree::Always,
Some("never") => *slot = DumpSolverProofTree::Never,
Some("on-error") => *slot = DumpSolverProofTree::OnError,
_ => return false,
};
true
}

pub(crate) fn parse_inlining_threshold(slot: &mut InliningThreshold, v: Option<&str>) -> bool {
match v {
Some("always" | "yes") => {
Expand Down Expand Up @@ -1591,9 +1609,6 @@ options! {
"output statistics about monomorphization collection"),
dump_mono_stats_format: DumpMonoStatsFormat = (DumpMonoStatsFormat::Markdown, parse_dump_mono_stats, [UNTRACKED],
"the format to use for -Z dump-mono-stats (`markdown` (default) or `json`)"),
dump_solver_proof_tree: DumpSolverProofTree = (DumpSolverProofTree::Never, parse_dump_solver_proof_tree, [UNTRACKED],
"dump a proof tree for every goal evaluated by the new trait solver. If the flag is specified without any options after it
then it defaults to `always`. If the flag is not specified at all it defaults to `on-request`."),
dwarf_version: Option<u32> = (None, parse_opt_number, [TRACKED],
"version of DWARF debug information to emit (default: 2 or 4, depending on platform)"),
dylib_lto: bool = (false, parse_bool, [UNTRACKED],
Expand Down Expand Up @@ -1722,6 +1737,8 @@ options! {
"the size at which the `large_assignments` lint starts to be emitted"),
mutable_noalias: bool = (true, parse_bool, [TRACKED],
"emit noalias metadata for mutable references (default: yes)"),
next_solver: Option<NextSolverConfig> = (None, parse_next_solver_config, [TRACKED],
"enable and configure the next generation trait solver used by rustc"),
nll_facts: bool = (false, parse_bool, [UNTRACKED],
"dump facts from NLL analysis into side files (default: no)"),
nll_facts_dir: String = ("nll-facts".to_string(), parse_string, [UNTRACKED],
Expand Down Expand Up @@ -1922,8 +1939,6 @@ written to standard error output)"),
"for every macro invocation, print its name and arguments (default: no)"),
track_diagnostics: bool = (false, parse_bool, [UNTRACKED],
"tracks where in rustc a diagnostic was emitted"),
trait_solver: TraitSolver = (TraitSolver::Classic, parse_trait_solver, [TRACKED],
"specify the trait solver mode used by rustc (default: classic)"),
// Diagnostics are considered side-effects of a query (see `QuerySideEffects`) and are saved
// alongside query results and changes to translation options can affect diagnostics - so
// translation options should be tracked.
Expand Down
11 changes: 6 additions & 5 deletions compiler/rustc_trait_selection/src/solve/eval_ctxt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,9 +200,10 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> {
let result = f(&mut ecx);

let tree = ecx.inspect.finalize();
if let (Some(tree), DumpSolverProofTree::Always) =
(&tree, infcx.tcx.sess.opts.unstable_opts.dump_solver_proof_tree)
{
if let (Some(tree), DumpSolverProofTree::Always) = (
&tree,
infcx.tcx.sess.opts.unstable_opts.next_solver.map(|c| c.dump_tree).unwrap_or_default(),
) {
let mut lock = std::io::stdout().lock();
let _ = lock.write_fmt(format_args!("{tree:?}\n"));
let _ = lock.flush();
Expand Down Expand Up @@ -377,7 +378,7 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> {
//
// This assert was removed as it did not hold for goals constraining
// an inference variable to a recursive alias, e.g. in
// tests/ui/traits/new-solver/overflow/recursive-self-normalization.rs.
// tests/ui/traits/next-solver/overflow/recursive-self-normalization.rs.
//
// Once we have decided on how to handle trait-system-refactor-initiative#75,
// we should re-add an assert here.
Expand Down Expand Up @@ -421,7 +422,7 @@ impl<'a, 'tcx> EvalCtxt<'a, 'tcx> {
self.compute_const_evaluatable_goal(Goal { param_env, predicate: ct })
}
ty::PredicateKind::ConstEquate(_, _) => {
bug!("ConstEquate should not be emitted when `-Ztrait-solver=next` is active")
bug!("ConstEquate should not be emitted when `-Znext-solver` is active")
}
ty::PredicateKind::NormalizesTo(predicate) => {
self.compute_normalizes_to_goal(Goal { param_env, predicate })
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_trait_selection/src/solve/inspect/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ impl<'tcx> ProofTreeBuilder<'tcx> {
GenerateProofTree::Never => ProofTreeBuilder::new_noop(),
GenerateProofTree::IfEnabled => {
let opts = &tcx.sess.opts.unstable_opts;
match opts.dump_solver_proof_tree {
match opts.next_solver.map(|c| c.dump_tree).unwrap_or_default() {
DumpSolverProofTree::Always => ProofTreeBuilder::new_root(),
// `OnError` is handled by reevaluating goals in error
// reporting with `GenerateProofTree::Yes`.
Expand Down
Loading

0 comments on commit 2ecba0f

Please sign in to comment.