From a24df5b3cdeb49334d6cde1c4d983b2354616824 Mon Sep 17 00:00:00 2001 From: Jack Huey Date: Tue, 3 Mar 2020 11:25:03 -0500 Subject: [PATCH] Reintegrate chalk using chalk-solve --- Cargo.lock | 98 +++ .../infer/canonical/canonicalizer.rs | 12 +- src/librustc_interface/tests.rs | 1 + src/librustc_middle/Cargo.toml | 1 + src/librustc_middle/dep_graph/dep_node.rs | 1 + src/librustc_middle/query/mod.rs | 10 + src/librustc_middle/traits/chalk.rs | 366 +++++++++ src/librustc_middle/traits/mod.rs | 9 + src/librustc_middle/ty/context.rs | 35 +- src/librustc_session/options.rs | 2 + .../traits/chalk_fulfill.rs | 262 +++++++ src/librustc_trait_selection/traits/engine.rs | 10 +- .../traits/error_reporting/mod.rs | 21 +- src/librustc_trait_selection/traits/mod.rs | 3 + src/librustc_trait_selection/traits/select.rs | 14 +- src/librustc_traits/Cargo.toml | 4 + src/librustc_traits/chalk/db.rs | 521 +++++++++++++ src/librustc_traits/chalk/lowering.rs | 722 ++++++++++++++++++ src/librustc_traits/chalk/mod.rs | 227 ++++++ src/librustc_traits/lib.rs | 2 + src/librustc_ty/ty.rs | 7 +- src/test/ui/chalkify/basic.rs | 12 + src/test/ui/chalkify/builtin-copy-clone.rs | 44 ++ src/test/ui/chalkify/chalk_initial_program.rs | 16 + .../ui/chalkify/chalk_initial_program.stderr | 12 + src/test/ui/chalkify/generic_impls.rs | 18 + src/test/ui/chalkify/generic_impls.stderr | 27 + src/test/ui/chalkify/impl_wf.rs | 47 ++ src/test/ui/chalkify/impl_wf.stderr | 12 + src/test/ui/chalkify/inherent_impl.rs | 42 + src/test/ui/chalkify/inherent_impl_min.rs | 27 + src/test/ui/chalkify/lower_env1.rs | 14 + src/test/ui/chalkify/lower_env2.rs | 16 + src/test/ui/chalkify/lower_env3.rs | 16 + src/test/ui/chalkify/lower_impl.rs | 17 + src/test/ui/chalkify/lower_struct.rs | 8 + src/test/ui/chalkify/lower_trait.rs | 11 + .../ui/chalkify/lower_trait_higher_rank.rs | 9 + .../ui/chalkify/lower_trait_where_clause.rs | 16 + src/test/ui/chalkify/println.rs | 7 + src/test/ui/chalkify/projection.rs | 25 + .../recursive_where_clause_on_type.rs | 35 + .../recursive_where_clause_on_type.stderr | 10 + src/test/ui/chalkify/super_trait.rs | 19 + src/test/ui/chalkify/trait_implied_bound.rs | 18 + src/test/ui/chalkify/type_implied_bound.rs | 29 + src/test/ui/chalkify/type_inference.rs | 28 + src/test/ui/chalkify/type_inference.stderr | 12 + src/test/ui/chalkify/type_wf.rs | 32 + src/tools/tidy/src/deps.rs | 4 + 50 files changed, 2890 insertions(+), 21 deletions(-) create mode 100644 src/librustc_middle/traits/chalk.rs create mode 100644 src/librustc_trait_selection/traits/chalk_fulfill.rs create mode 100644 src/librustc_traits/chalk/db.rs create mode 100644 src/librustc_traits/chalk/lowering.rs create mode 100644 src/librustc_traits/chalk/mod.rs create mode 100644 src/test/ui/chalkify/basic.rs create mode 100644 src/test/ui/chalkify/builtin-copy-clone.rs create mode 100644 src/test/ui/chalkify/chalk_initial_program.rs create mode 100644 src/test/ui/chalkify/chalk_initial_program.stderr create mode 100644 src/test/ui/chalkify/generic_impls.rs create mode 100644 src/test/ui/chalkify/generic_impls.stderr create mode 100644 src/test/ui/chalkify/impl_wf.rs create mode 100644 src/test/ui/chalkify/impl_wf.stderr create mode 100644 src/test/ui/chalkify/inherent_impl.rs create mode 100644 src/test/ui/chalkify/inherent_impl_min.rs create mode 100644 src/test/ui/chalkify/lower_env1.rs create mode 100644 src/test/ui/chalkify/lower_env2.rs create mode 100644 src/test/ui/chalkify/lower_env3.rs create mode 100644 src/test/ui/chalkify/lower_impl.rs create mode 100644 src/test/ui/chalkify/lower_struct.rs create mode 100644 src/test/ui/chalkify/lower_trait.rs create mode 100644 src/test/ui/chalkify/lower_trait_higher_rank.rs create mode 100644 src/test/ui/chalkify/lower_trait_where_clause.rs create mode 100644 src/test/ui/chalkify/println.rs create mode 100644 src/test/ui/chalkify/projection.rs create mode 100644 src/test/ui/chalkify/recursive_where_clause_on_type.rs create mode 100644 src/test/ui/chalkify/recursive_where_clause_on_type.stderr create mode 100644 src/test/ui/chalkify/super_trait.rs create mode 100644 src/test/ui/chalkify/trait_implied_bound.rs create mode 100644 src/test/ui/chalkify/type_implied_bound.rs create mode 100644 src/test/ui/chalkify/type_inference.rs create mode 100644 src/test/ui/chalkify/type_inference.stderr create mode 100644 src/test/ui/chalkify/type_wf.rs diff --git a/Cargo.lock b/Cargo.lock index 375e5672229..6b28f1513d2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -429,6 +429,77 @@ dependencies = [ "rustc-std-workspace-core", ] +[[package]] +name = "chalk-derive" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d4620afad4d4d9e63f915cfa10c930b7a3c9c3ca5cd88dd771ff8e5bf04ea10" +dependencies = [ + "proc-macro2 1.0.3", + "quote 1.0.2", + "syn 1.0.11", + "synstructure 0.12.1", +] + +[[package]] +name = "chalk-engine" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ca6e5cef10197789da0b4ec310eda58da4c55530613b2323432642a97372735" +dependencies = [ + "chalk-macros", + "rustc-hash", +] + +[[package]] +name = "chalk-ir" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d45df5fb6328527f976e8a32c9e1c9970084d937ebe93d0d34f5bbf4231cb956" +dependencies = [ + "chalk-derive", + "chalk-engine", + "chalk-macros", +] + +[[package]] +name = "chalk-macros" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e4782d108e420a1fcf94d8a919cf248db33c5071678e87d9c2d4f20ed1feb32" +dependencies = [ + "lazy_static 1.4.0", +] + +[[package]] +name = "chalk-rust-ir" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0ec96dbe0ab5fdbadfca4179ec2e1d35f0439c3b53a74988b1aec239c63eb08" +dependencies = [ + "chalk-derive", + "chalk-engine", + "chalk-ir", + "chalk-macros", +] + +[[package]] +name = "chalk-solve" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfb99fa9530f0e101475fb60adc931f51bdea05b4642a48928b814d7f0141a6b" +dependencies = [ + "chalk-derive", + "chalk-engine", + "chalk-ir", + "chalk-macros", + "chalk-rust-ir", + "ena", + "itertools 0.9.0", + "petgraph", + "rustc-hash", +] + [[package]] name = "chrono" version = "0.4.6" @@ -1102,6 +1173,12 @@ dependencies = [ "winapi 0.3.8", ] +[[package]] +name = "fixedbitset" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86d4de0081402f5e88cdac65c8dcdcc73118c1a7a465e2a05f0da05843a8ea33" + [[package]] name = "flate2" version = "1.0.12" @@ -2328,6 +2405,12 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "ordermap" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a86ed3f5f244b372d6b1a00b72ef7f8876d0bc6a78a4c9985c53614041512063" + [[package]] name = "ordslice" version = "0.3.0" @@ -2496,6 +2579,16 @@ dependencies = [ "sha-1", ] +[[package]] +name = "petgraph" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3659d1ee90221741f65dd128d9998311b0e40c5d3c23a62445938214abce4f" +dependencies = [ + "fixedbitset", + "ordermap", +] + [[package]] name = "phf" version = "0.7.24" @@ -4002,6 +4095,7 @@ dependencies = [ "arena", "bitflags", "byteorder", + "chalk-ir", "log", "measureme", "polonius-engine", @@ -4301,10 +4395,14 @@ dependencies = [ name = "rustc_traits" version = "0.0.0" dependencies = [ + "chalk-ir", + "chalk-rust-ir", + "chalk-solve", "log", "rustc_ast", "rustc_data_structures", "rustc_hir", + "rustc_index", "rustc_infer", "rustc_middle", "rustc_span", diff --git a/src/librustc_infer/infer/canonical/canonicalizer.rs b/src/librustc_infer/infer/canonical/canonicalizer.rs index acb9329afbf..20af9b22a97 100644 --- a/src/librustc_infer/infer/canonical/canonicalizer.rs +++ b/src/librustc_infer/infer/canonical/canonicalizer.rs @@ -353,8 +353,10 @@ impl<'cx, 'tcx> TypeFolder<'tcx> for Canonicalizer<'cx, 'tcx> { // `TyVar(vid)` is unresolved, track its universe index in the canonicalized // result. Err(mut ui) => { - // FIXME: perf problem described in #55921. - ui = ty::UniverseIndex::ROOT; + if !self.infcx.unwrap().tcx.sess.opts.debugging_opts.chalk { + // FIXME: perf problem described in #55921. + ui = ty::UniverseIndex::ROOT; + } self.canonicalize_ty_var( CanonicalVarInfo { kind: CanonicalVarKind::Ty(CanonicalTyVarKind::General(ui)), @@ -439,8 +441,10 @@ impl<'cx, 'tcx> TypeFolder<'tcx> for Canonicalizer<'cx, 'tcx> { // `ConstVar(vid)` is unresolved, track its universe index in the // canonicalized result Err(mut ui) => { - // FIXME: perf problem described in #55921. - ui = ty::UniverseIndex::ROOT; + if !self.infcx.unwrap().tcx.sess.opts.debugging_opts.chalk { + // FIXME: perf problem described in #55921. + ui = ty::UniverseIndex::ROOT; + } return self.canonicalize_const_var( CanonicalVarInfo { kind: CanonicalVarKind::Const(ui) }, ct, diff --git a/src/librustc_interface/tests.rs b/src/librustc_interface/tests.rs index 1c20ea9e824..69237b81a82 100644 --- a/src/librustc_interface/tests.rs +++ b/src/librustc_interface/tests.rs @@ -525,6 +525,7 @@ fn test_debugging_options_tracking_hash() { tracked!(always_encode_mir, true); tracked!(asm_comments, true); tracked!(binary_dep_depinfo, true); + tracked!(chalk, true); tracked!(codegen_backend, Some("abc".to_string())); tracked!(crate_attr, vec!["abc".to_string()]); tracked!(debug_macros, true); diff --git a/src/librustc_middle/Cargo.toml b/src/librustc_middle/Cargo.toml index 398ba4d72d4..8a1317ba289 100644 --- a/src/librustc_middle/Cargo.toml +++ b/src/librustc_middle/Cargo.toml @@ -31,6 +31,7 @@ rustc_serialize = { path = "../libserialize", package = "serialize" } rustc_ast = { path = "../librustc_ast" } rustc_span = { path = "../librustc_span" } byteorder = { version = "1.3" } +chalk-ir = "0.10.0" smallvec = { version = "1.0", features = ["union", "may_dangle"] } measureme = "0.7.1" rustc_session = { path = "../librustc_session" } diff --git a/src/librustc_middle/dep_graph/dep_node.rs b/src/librustc_middle/dep_graph/dep_node.rs index 19b85aa3c51..33037900880 100644 --- a/src/librustc_middle/dep_graph/dep_node.rs +++ b/src/librustc_middle/dep_graph/dep_node.rs @@ -51,6 +51,7 @@ use crate::mir; use crate::mir::interpret::{GlobalId, LitToConstInput}; +use crate::traits; use crate::traits::query::{ CanonicalPredicateGoal, CanonicalProjectionGoal, CanonicalTyGoal, CanonicalTypeOpAscribeUserTypeGoal, CanonicalTypeOpEqGoal, CanonicalTypeOpNormalizeGoal, diff --git a/src/librustc_middle/query/mod.rs b/src/librustc_middle/query/mod.rs index b0c44238148..760fded55d6 100644 --- a/src/librustc_middle/query/mod.rs +++ b/src/librustc_middle/query/mod.rs @@ -1,6 +1,7 @@ use crate::dep_graph::SerializedDepNodeIndex; use crate::mir; use crate::mir::interpret::{GlobalId, LitToConstInput}; +use crate::traits; use crate::traits::query::{ CanonicalPredicateGoal, CanonicalProjectionGoal, CanonicalTyGoal, CanonicalTypeOpAscribeUserTypeGoal, CanonicalTypeOpEqGoal, CanonicalTypeOpNormalizeGoal, @@ -1154,6 +1155,15 @@ rustc_queries! { desc { "evaluating trait selection obligation `{}`", goal.value.value } } + query evaluate_goal( + goal: traits::ChalkCanonicalGoal<'tcx> + ) -> Result< + &'tcx Canonical<'tcx, canonical::QueryResponse<'tcx, ()>>, + NoSolution + > { + desc { "evaluating trait selection obligation `{}`", goal.value } + } + /// Do not call this query directly: part of the `Eq` type-op query type_op_ascribe_user_type( goal: CanonicalTypeOpAscribeUserTypeGoal<'tcx> diff --git a/src/librustc_middle/traits/chalk.rs b/src/librustc_middle/traits/chalk.rs new file mode 100644 index 00000000000..b963af96f50 --- /dev/null +++ b/src/librustc_middle/traits/chalk.rs @@ -0,0 +1,366 @@ +//! Types required for Chalk-related queries +//! +//! The primary purpose of this file is defining an implementation for the +//! `chalk_ir::interner::Interner` trait. The primary purpose of this trait, as +//! its name suggest, is to provide an abstraction boundary for creating +//! interned Chalk types. + +use chalk_ir::{GoalData, Parameter}; + +use rustc_middle::mir::Mutability; +use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeVisitor}; +use rustc_middle::ty::{self, Ty, TyCtxt}; + +use rustc_hir::def_id::DefId; + +use smallvec::SmallVec; + +use std::cmp::Ordering; +use std::fmt; +use std::hash::{Hash, Hasher}; + +/// Since Chalk doesn't have full support for all Rust builtin types yet, we +/// need to use an enum here, rather than just `DefId`. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum RustDefId { + Adt(DefId), + Str, + Never, + Slice, + Array, + Ref(Mutability), + RawPtr, + + Trait(DefId), + + Impl(DefId), + + FnDef(DefId), + + AssocTy(DefId), +} + +#[derive(Copy, Clone)] +pub struct RustInterner<'tcx> { + pub tcx: TyCtxt<'tcx>, +} + +/// We don't ever actually need this. It's only required for derives. +impl<'tcx> Hash for RustInterner<'tcx> { + fn hash(&self, _state: &mut H) {} +} + +/// We don't ever actually need this. It's only required for derives. +impl<'tcx> Ord for RustInterner<'tcx> { + fn cmp(&self, _other: &Self) -> Ordering { + Ordering::Equal + } +} + +/// We don't ever actually need this. It's only required for derives. +impl<'tcx> PartialOrd for RustInterner<'tcx> { + fn partial_cmp(&self, _other: &Self) -> Option { + None + } +} + +/// We don't ever actually need this. It's only required for derives. +impl<'tcx> PartialEq for RustInterner<'tcx> { + fn eq(&self, _other: &Self) -> bool { + false + } +} + +/// We don't ever actually need this. It's only required for derives. +impl<'tcx> Eq for RustInterner<'tcx> {} + +impl fmt::Debug for RustInterner<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "RustInterner") + } +} + +// Right now, there is no interning at all. I was running into problems with +// adding interning in `ty/context.rs` for Chalk types with +// `parallel-compiler = true`. -jackh726 +impl<'tcx> chalk_ir::interner::Interner for RustInterner<'tcx> { + type InternedType = Box>; + type InternedLifetime = Box>; + type InternedParameter = Box>; + type InternedGoal = Box>; + type InternedGoals = Vec>; + type InternedSubstitution = Vec>; + type InternedProgramClause = Box>; + type InternedProgramClauses = Vec>; + type InternedQuantifiedWhereClauses = Vec>; + type InternedParameterKinds = Vec>; + type InternedCanonicalVarKinds = Vec>; + type DefId = RustDefId; + type Identifier = (); + + fn debug_program_clause_implication( + pci: &chalk_ir::ProgramClauseImplication, + fmt: &mut fmt::Formatter<'_>, + ) -> Option { + let mut write = || { + write!(fmt, "{:?}", pci.consequence)?; + + let conditions = pci.conditions.interned(); + + let conds = conditions.len(); + if conds == 0 { + return Ok(()); + } + + write!(fmt, " :- ")?; + for cond in &conditions[..conds - 1] { + write!(fmt, "{:?}, ", cond)?; + } + write!(fmt, "{:?}", conditions[conds - 1])?; + Ok(()) + }; + Some(write()) + } + + fn debug_application_ty( + application_ty: &chalk_ir::ApplicationTy, + fmt: &mut fmt::Formatter<'_>, + ) -> Option { + let chalk_ir::ApplicationTy { name, substitution } = application_ty; + Some(write!(fmt, "{:?}{:?}", name, chalk_ir::debug::Angle(substitution.interned()))) + } + + fn debug_substitution( + substitution: &chalk_ir::Substitution, + fmt: &mut fmt::Formatter<'_>, + ) -> Option { + Some(write!(fmt, "{:?}", substitution.interned())) + } + + fn debug_separator_trait_ref( + separator_trait_ref: &chalk_ir::SeparatorTraitRef<'_, Self>, + fmt: &mut fmt::Formatter<'_>, + ) -> Option { + let substitution = &separator_trait_ref.trait_ref.substitution; + let parameters = substitution.interned(); + Some(write!( + fmt, + "{:?}{}{:?}{:?}", + parameters[0], + separator_trait_ref.separator, + separator_trait_ref.trait_ref.trait_id, + chalk_ir::debug::Angle(¶meters[1..]) + )) + } + + fn debug_quantified_where_clauses( + clauses: &chalk_ir::QuantifiedWhereClauses, + fmt: &mut fmt::Formatter<'_>, + ) -> Option { + Some(write!(fmt, "{:?}", clauses.interned())) + } + + fn debug_alias( + alias_ty: &chalk_ir::AliasTy, + fmt: &mut fmt::Formatter<'_>, + ) -> Option { + match alias_ty { + chalk_ir::AliasTy::Projection(projection_ty) => { + Self::debug_projection_ty(projection_ty, fmt) + } + chalk_ir::AliasTy::Opaque(opaque_ty) => Self::debug_opaque_ty(opaque_ty, fmt), + } + } + + fn debug_projection_ty( + projection_ty: &chalk_ir::ProjectionTy, + fmt: &mut fmt::Formatter<'_>, + ) -> Option { + Some(write!( + fmt, + "projection: {:?} {:?}", + projection_ty.associated_ty_id, projection_ty.substitution, + )) + } + + fn debug_opaque_ty( + opaque_ty: &chalk_ir::OpaqueTy, + fmt: &mut fmt::Formatter<'_>, + ) -> Option { + Some(write!(fmt, "{:?}", opaque_ty.opaque_ty_id)) + } + + fn intern_ty(&self, ty: chalk_ir::TyData) -> Self::InternedType { + Box::new(ty) + } + + fn ty_data<'a>(&self, ty: &'a Self::InternedType) -> &'a chalk_ir::TyData { + ty + } + + fn intern_lifetime(&self, lifetime: chalk_ir::LifetimeData) -> Self::InternedLifetime { + Box::new(lifetime) + } + + fn lifetime_data<'a>( + &self, + lifetime: &'a Self::InternedLifetime, + ) -> &'a chalk_ir::LifetimeData { + &lifetime + } + + fn intern_parameter( + &self, + parameter: chalk_ir::ParameterData, + ) -> Self::InternedParameter { + Box::new(parameter) + } + + fn parameter_data<'a>( + &self, + parameter: &'a Self::InternedParameter, + ) -> &'a chalk_ir::ParameterData { + ¶meter + } + + fn intern_goal(&self, goal: GoalData) -> Self::InternedGoal { + Box::new(goal) + } + + fn goal_data<'a>(&self, goal: &'a Self::InternedGoal) -> &'a GoalData { + &goal + } + + fn intern_goals( + &self, + data: impl IntoIterator, E>>, + ) -> Result { + data.into_iter().collect::, _>>() + } + + fn goals_data<'a>(&self, goals: &'a Self::InternedGoals) -> &'a [chalk_ir::Goal] { + goals + } + + fn intern_substitution( + &self, + data: impl IntoIterator, E>>, + ) -> Result { + data.into_iter().collect::, _>>() + } + + fn substitution_data<'a>( + &self, + substitution: &'a Self::InternedSubstitution, + ) -> &'a [Parameter] { + substitution + } + + fn intern_program_clause( + &self, + data: chalk_ir::ProgramClauseData, + ) -> Self::InternedProgramClause { + Box::new(data) + } + + fn program_clause_data<'a>( + &self, + clause: &'a Self::InternedProgramClause, + ) -> &'a chalk_ir::ProgramClauseData { + &clause + } + + fn intern_program_clauses( + &self, + data: impl IntoIterator, E>>, + ) -> Result { + data.into_iter().collect::, _>>() + } + + fn program_clauses_data<'a>( + &self, + clauses: &'a Self::InternedProgramClauses, + ) -> &'a [chalk_ir::ProgramClause] { + clauses + } + + fn intern_quantified_where_clauses( + &self, + data: impl IntoIterator, E>>, + ) -> Result { + data.into_iter().collect::, _>>() + } + + fn quantified_where_clauses_data<'a>( + &self, + clauses: &'a Self::InternedQuantifiedWhereClauses, + ) -> &'a [chalk_ir::QuantifiedWhereClause] { + clauses + } + + fn intern_parameter_kinds( + &self, + data: impl IntoIterator, E>>, + ) -> Result { + data.into_iter().collect::, _>>() + } + + fn parameter_kinds_data<'a>( + &self, + parameter_kinds: &'a Self::InternedParameterKinds, + ) -> &'a [chalk_ir::ParameterKind<()>] { + parameter_kinds + } + + fn intern_canonical_var_kinds( + &self, + data: impl IntoIterator, E>>, + ) -> Result { + data.into_iter().collect::, _>>() + } + + fn canonical_var_kinds_data<'a>( + &self, + canonical_var_kinds: &'a Self::InternedCanonicalVarKinds, + ) -> &'a [chalk_ir::ParameterKind] { + canonical_var_kinds + } +} + +impl<'tcx> chalk_ir::interner::HasInterner for RustInterner<'tcx> { + type Interner = Self; +} + +#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)] +pub enum ChalkEnvironmentClause<'tcx> { + /// A normal rust `ty::Predicate` in the environment. + Predicate(ty::Predicate<'tcx>), + /// A special clause in the environment that gets lowered to + /// `chalk_ir::FromEnv::Ty`. + TypeFromEnv(Ty<'tcx>), +} + +impl<'tcx> TypeFoldable<'tcx> for &'tcx ty::List> { + fn super_fold_with>(&self, folder: &mut F) -> Self { + let v = self.iter().map(|t| t.fold_with(folder)).collect::>(); + folder.tcx().intern_chalk_environment_clause_list(&v) + } + + fn super_visit_with>(&self, visitor: &mut V) -> bool { + self.iter().any(|t| t.visit_with(visitor)) + } +} +/// We have to elaborate the environment of a chalk goal *before* +/// canonicalization. This type wraps the predicate and the elaborated +/// environment. +#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, HashStable, TypeFoldable)] +pub struct ChalkEnvironmentAndGoal<'tcx> { + pub environment: &'tcx ty::List>, + pub goal: ty::Predicate<'tcx>, +} + +impl<'tcx> fmt::Display for ChalkEnvironmentAndGoal<'tcx> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "environment: {:?}, goal: {}", self.environment, self.goal) + } +} diff --git a/src/librustc_middle/traits/mod.rs b/src/librustc_middle/traits/mod.rs index 3a05d577bfa..43a347fec2a 100644 --- a/src/librustc_middle/traits/mod.rs +++ b/src/librustc_middle/traits/mod.rs @@ -2,11 +2,13 @@ //! //! [rustc dev guide]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html +mod chalk; pub mod query; pub mod select; pub mod specialization_graph; mod structural_impls; +use crate::infer::canonical::Canonical; use crate::mir::interpret::ErrorHandled; use crate::ty::subst::SubstsRef; use crate::ty::{self, AdtKind, Ty, TyCtxt}; @@ -23,10 +25,17 @@ use std::rc::Rc; pub use self::select::{EvaluationCache, EvaluationResult, OverflowError, SelectionCache}; +pub type ChalkCanonicalGoal<'tcx> = Canonical<'tcx, ChalkEnvironmentAndGoal<'tcx>>; + pub use self::ObligationCauseCode::*; pub use self::SelectionError::*; pub use self::Vtable::*; +pub use self::chalk::{ + ChalkEnvironmentAndGoal, ChalkEnvironmentClause, RustDefId as ChalkRustDefId, + RustInterner as ChalkRustInterner, +}; + /// Depending on the stage of compilation, we want projection to be /// more or less conservative. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, HashStable)] diff --git a/src/librustc_middle/ty/context.rs b/src/librustc_middle/ty/context.rs index e43eb01ad96..fc68a347dfd 100644 --- a/src/librustc_middle/ty/context.rs +++ b/src/librustc_middle/ty/context.rs @@ -93,6 +93,8 @@ pub struct CtxtInterners<'tcx> { projs: InternedSet<'tcx, List>, place_elems: InternedSet<'tcx, List>>, const_: InternedSet<'tcx, Const<'tcx>>, + + chalk_environment_clause_list: InternedSet<'tcx, List>>, } impl<'tcx> CtxtInterners<'tcx> { @@ -109,6 +111,8 @@ impl<'tcx> CtxtInterners<'tcx> { projs: Default::default(), place_elems: Default::default(), const_: Default::default(), + + chalk_environment_clause_list: Default::default(), } } @@ -1997,6 +2001,14 @@ impl<'tcx> Borrow> for Interned<'tcx, Const<'tcx>> { } } +impl<'tcx> Borrow<[traits::ChalkEnvironmentClause<'tcx>]> + for Interned<'tcx, List>> +{ + fn borrow<'a>(&'a self) -> &'a [traits::ChalkEnvironmentClause<'tcx>] { + &self.0[..] + } +} + macro_rules! direct_interners { ($($name:ident: $method:ident($ty:ty)),+) => { $(impl<'tcx> PartialEq for Interned<'tcx, $ty> { @@ -2044,7 +2056,9 @@ slice_interners!( existential_predicates: _intern_existential_predicates(ExistentialPredicate<'tcx>), predicates: _intern_predicates(Predicate<'tcx>), projs: _intern_projs(ProjectionKind), - place_elems: _intern_place_elems(PlaceElem<'tcx>) + place_elems: _intern_place_elems(PlaceElem<'tcx>), + chalk_environment_clause_list: + _intern_chalk_environment_clause_list(traits::ChalkEnvironmentClause<'tcx>) ); impl<'tcx> TyCtxt<'tcx> { @@ -2430,6 +2444,13 @@ impl<'tcx> TyCtxt<'tcx> { if ts.is_empty() { List::empty() } else { self._intern_canonical_var_infos(ts) } } + pub fn intern_chalk_environment_clause_list( + self, + ts: &[traits::ChalkEnvironmentClause<'tcx>], + ) -> &'tcx List> { + if ts.is_empty() { List::empty() } else { self._intern_chalk_environment_clause_list(ts) } + } + pub fn mk_fn_sig( self, inputs: I, @@ -2487,6 +2508,18 @@ impl<'tcx> TyCtxt<'tcx> { self.mk_substs(iter::once(self_ty.into()).chain(rest.iter().cloned())) } + pub fn mk_chalk_environment_clause_list< + I: InternAs< + [traits::ChalkEnvironmentClause<'tcx>], + &'tcx List>, + >, + >( + self, + iter: I, + ) -> I::Output { + iter.intern_with(|xs| self.intern_chalk_environment_clause_list(xs)) + } + /// Walks upwards from `id` to find a node which might change lint levels with attributes. /// It stops at `bound` and just returns it if reached. pub fn maybe_lint_level_root_bounded(self, mut id: HirId, bound: HirId) -> HirId { diff --git a/src/librustc_session/options.rs b/src/librustc_session/options.rs index 1d314238b86..689fbf3b95a 100644 --- a/src/librustc_session/options.rs +++ b/src/librustc_session/options.rs @@ -768,6 +768,8 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options, "select which borrowck is used (`mir` or `migrate`) (default: `migrate`)"), borrowck_stats: bool = (false, parse_bool, [UNTRACKED], "gather borrowck statistics (default: no)"), + chalk: bool = (false, parse_bool, [TRACKED], + "enable the experimental Chalk-based trait solving engine"), codegen_backend: Option = (None, parse_opt_string, [TRACKED], "the backend to use"), control_flow_guard: CFGuard = (CFGuard::Disabled, parse_cfguard, [UNTRACKED], diff --git a/src/librustc_trait_selection/traits/chalk_fulfill.rs b/src/librustc_trait_selection/traits/chalk_fulfill.rs new file mode 100644 index 00000000000..115e4a0e629 --- /dev/null +++ b/src/librustc_trait_selection/traits/chalk_fulfill.rs @@ -0,0 +1,262 @@ +//! Defines a Chalk-based `TraitEngine` + +use crate::infer::canonical::OriginalQueryValues; +use crate::infer::InferCtxt; +use crate::traits::query::NoSolution; +use crate::traits::{ + ChalkEnvironmentAndGoal, ChalkEnvironmentClause, FulfillmentError, FulfillmentErrorCode, + ObligationCause, PredicateObligation, SelectionError, TraitEngine, +}; +use rustc_data_structures::fx::FxHashSet; +use rustc_hir::def_id::DefId; +use rustc_middle::ty::{self, Ty, TyCtxt}; + +pub struct FulfillmentContext<'tcx> { + obligations: FxHashSet>, +} + +impl FulfillmentContext<'tcx> { + crate fn new() -> Self { + FulfillmentContext { obligations: FxHashSet::default() } + } +} + +fn environment<'tcx>( + tcx: TyCtxt<'tcx>, + def_id: DefId, +) -> &'tcx ty::List> { + use rustc_hir::{ForeignItemKind, ImplItemKind, ItemKind, Node, TraitItemKind}; + use rustc_middle::ty::subst::GenericArgKind; + + debug!("environment(def_id = {:?})", def_id); + + // The environment of an impl Trait type is its defining function's environment. + if let Some(parent) = ty::is_impl_trait_defn(tcx, def_id) { + return environment(tcx, parent); + } + + // Compute the bounds on `Self` and the type parameters. + let ty::InstantiatedPredicates { predicates, .. } = + tcx.predicates_of(def_id).instantiate_identity(tcx); + + let clauses = predicates.into_iter().map(|pred| ChalkEnvironmentClause::Predicate(pred)); + + let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local()); + let node = tcx.hir().get(hir_id); + + enum NodeKind { + TraitImpl, + InherentImpl, + Fn, + Other, + }; + + let node_kind = match node { + Node::TraitItem(item) => match item.kind { + TraitItemKind::Fn(..) => NodeKind::Fn, + _ => NodeKind::Other, + }, + + Node::ImplItem(item) => match item.kind { + ImplItemKind::Fn(..) => NodeKind::Fn, + _ => NodeKind::Other, + }, + + Node::Item(item) => match item.kind { + ItemKind::Impl { of_trait: Some(_), .. } => NodeKind::TraitImpl, + ItemKind::Impl { of_trait: None, .. } => NodeKind::InherentImpl, + ItemKind::Fn(..) => NodeKind::Fn, + _ => NodeKind::Other, + }, + + Node::ForeignItem(item) => match item.kind { + ForeignItemKind::Fn(..) => NodeKind::Fn, + _ => NodeKind::Other, + }, + + // FIXME: closures? + _ => NodeKind::Other, + }; + + // FIXME(eddyb) isn't the unordered nature of this a hazard? + let mut inputs = FxHashSet::default(); + + match node_kind { + // In a trait impl, we assume that the header trait ref and all its + // constituents are well-formed. + NodeKind::TraitImpl => { + let trait_ref = tcx.impl_trait_ref(def_id).expect("not an impl"); + + inputs.extend(trait_ref.substs.iter().flat_map(|&arg| arg.walk())); + } + + // In an inherent impl, we assume that the receiver type and all its + // constituents are well-formed. + NodeKind::InherentImpl => { + let self_ty = tcx.type_of(def_id); + inputs.extend(self_ty.walk()); + } + + // In an fn, we assume that the arguments and all their constituents are + // well-formed. + NodeKind::Fn => { + let fn_sig = tcx.fn_sig(def_id); + let fn_sig = tcx.liberate_late_bound_regions(def_id, &fn_sig); + + inputs.extend(fn_sig.inputs().iter().flat_map(|ty| ty.walk())); + } + + NodeKind::Other => (), + } + let input_clauses = inputs.into_iter().filter_map(|arg| { + match arg.unpack() { + GenericArgKind::Type(ty) => Some(ChalkEnvironmentClause::TypeFromEnv(ty)), + + // FIXME(eddyb) no WF conditions from lifetimes? + GenericArgKind::Lifetime(_) => None, + + // FIXME(eddyb) support const generics in Chalk + GenericArgKind::Const(_) => None, + } + }); + + tcx.mk_chalk_environment_clause_list(clauses.chain(input_clauses)) +} + +/// We need to wrap a `ty::Predicate` in an elaborated environment *before* we +/// canonicalize. This is due to the fact that we insert extra clauses into the +/// environment for all input types (`FromEnv`). +fn in_environment( + infcx: &InferCtxt<'_, 'tcx>, + obligation: &PredicateObligation<'tcx>, +) -> ChalkEnvironmentAndGoal<'tcx> { + assert!(!infcx.is_in_snapshot()); + let obligation = infcx.resolve_vars_if_possible(obligation); + + let environment = match obligation.param_env.def_id { + Some(def_id) => environment(infcx.tcx, def_id), + None if obligation.param_env.caller_bounds.is_empty() => ty::List::empty(), + _ => bug!("non-empty `ParamEnv` with no def-id"), + }; + + ChalkEnvironmentAndGoal { environment, goal: obligation.predicate } +} + +impl TraitEngine<'tcx> for FulfillmentContext<'tcx> { + fn normalize_projection_type( + &mut self, + infcx: &InferCtxt<'_, 'tcx>, + _param_env: ty::ParamEnv<'tcx>, + projection_ty: ty::ProjectionTy<'tcx>, + _cause: ObligationCause<'tcx>, + ) -> Ty<'tcx> { + infcx.tcx.mk_ty(ty::Projection(projection_ty)) + } + + fn register_predicate_obligation( + &mut self, + infcx: &InferCtxt<'_, 'tcx>, + obligation: PredicateObligation<'tcx>, + ) { + assert!(!infcx.is_in_snapshot()); + let obligation = infcx.resolve_vars_if_possible(&obligation); + + self.obligations.insert(obligation); + } + + fn select_all_or_error( + &mut self, + infcx: &InferCtxt<'_, 'tcx>, + ) -> Result<(), Vec>> { + self.select_where_possible(infcx)?; + + if self.obligations.is_empty() { + Ok(()) + } else { + let errors = self + .obligations + .iter() + .map(|obligation| FulfillmentError { + obligation: obligation.clone(), + code: FulfillmentErrorCode::CodeAmbiguity, + points_at_arg_span: false, + }) + .collect(); + Err(errors) + } + } + + fn select_where_possible( + &mut self, + infcx: &InferCtxt<'_, 'tcx>, + ) -> Result<(), Vec>> { + let mut errors = Vec::new(); + let mut next_round = FxHashSet::default(); + let mut making_progress; + + loop { + making_progress = false; + + // We iterate over all obligations, and record if we are able + // to unambiguously prove at least one obligation. + for obligation in self.obligations.drain() { + let goal_in_environment = in_environment(infcx, &obligation); + let mut orig_values = OriginalQueryValues::default(); + let canonical_goal = + infcx.canonicalize_query(&goal_in_environment, &mut orig_values); + + match infcx.tcx.evaluate_goal(canonical_goal) { + Ok(response) => { + if response.is_proven() { + making_progress = true; + + match infcx.instantiate_query_response_and_region_obligations( + &obligation.cause, + obligation.param_env, + &orig_values, + &response, + ) { + Ok(infer_ok) => next_round.extend( + infer_ok.obligations.into_iter().map(|obligation| { + assert!(!infcx.is_in_snapshot()); + infcx.resolve_vars_if_possible(&obligation) + }), + ), + + Err(_err) => errors.push(FulfillmentError { + obligation: obligation, + code: FulfillmentErrorCode::CodeSelectionError( + SelectionError::Unimplemented, + ), + points_at_arg_span: false, + }), + } + } else { + // Ambiguous: retry at next round. + next_round.insert(obligation); + } + } + + Err(NoSolution) => errors.push(FulfillmentError { + obligation: obligation, + code: FulfillmentErrorCode::CodeSelectionError( + SelectionError::Unimplemented, + ), + points_at_arg_span: false, + }), + } + } + next_round = std::mem::replace(&mut self.obligations, next_round); + + if !making_progress { + break; + } + } + + if errors.is_empty() { Ok(()) } else { Err(errors) } + } + + fn pending_obligations(&self) -> Vec> { + self.obligations.iter().map(|obligation| obligation.clone()).collect() + } +} diff --git a/src/librustc_trait_selection/traits/engine.rs b/src/librustc_trait_selection/traits/engine.rs index c6a3dfa698e..4d477886979 100644 --- a/src/librustc_trait_selection/traits/engine.rs +++ b/src/librustc_trait_selection/traits/engine.rs @@ -1,14 +1,18 @@ use rustc_middle::ty::TyCtxt; -use super::FulfillmentContext; use super::TraitEngine; +use super::{ChalkFulfillmentContext, FulfillmentContext}; pub trait TraitEngineExt<'tcx> { fn new(tcx: TyCtxt<'tcx>) -> Box; } impl<'tcx> TraitEngineExt<'tcx> for dyn TraitEngine<'tcx> { - fn new(_tcx: TyCtxt<'tcx>) -> Box { - Box::new(FulfillmentContext::new()) + fn new(tcx: TyCtxt<'tcx>) -> Box { + if tcx.sess.opts.debugging_opts.chalk { + Box::new(ChalkFulfillmentContext::new()) + } else { + Box::new(FulfillmentContext::new()) + } } } diff --git a/src/librustc_trait_selection/traits/error_reporting/mod.rs b/src/librustc_trait_selection/traits/error_reporting/mod.rs index 19ed6b50f92..cf333b4dfe9 100644 --- a/src/librustc_trait_selection/traits/error_reporting/mod.rs +++ b/src/librustc_trait_selection/traits/error_reporting/mod.rs @@ -570,12 +570,21 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { } ty::Predicate::WellFormed(ty) => { - // WF predicates cannot themselves make - // errors. They can only block due to - // ambiguity; otherwise, they always - // degenerate into other obligations - // (which may fail). - span_bug!(span, "WF predicate not satisfied for {:?}", ty); + if !self.tcx.sess.opts.debugging_opts.chalk { + // WF predicates cannot themselves make + // errors. They can only block due to + // ambiguity; otherwise, they always + // degenerate into other obligations + // (which may fail). + span_bug!(span, "WF predicate not satisfied for {:?}", ty); + } else { + // FIXME: we'll need a better message which takes into account + // which bounds actually failed to hold. + self.tcx.sess.struct_span_err( + span, + &format!("the type `{}` is not well-formed (chalk)", ty), + ) + } } ty::Predicate::ConstEvaluatable(..) => { diff --git a/src/librustc_trait_selection/traits/mod.rs b/src/librustc_trait_selection/traits/mod.rs index c5dbe816295..778430fc2ca 100644 --- a/src/librustc_trait_selection/traits/mod.rs +++ b/src/librustc_trait_selection/traits/mod.rs @@ -4,6 +4,7 @@ #[allow(dead_code)] pub mod auto_trait; +mod chalk_fulfill; pub mod codegen; mod coherence; mod engine; @@ -69,6 +70,8 @@ pub use self::util::{ supertrait_def_ids, supertraits, transitive_bounds, SupertraitDefIds, Supertraits, }; +pub use self::chalk_fulfill::FulfillmentContext as ChalkFulfillmentContext; + pub use rustc_infer::traits::*; /// Whether to skip the leak check, as part of a future compatibility warning step. diff --git a/src/librustc_trait_selection/traits/select.rs b/src/librustc_trait_selection/traits/select.rs index 27d3b2ec9cb..b595f77e4d6 100644 --- a/src/librustc_trait_selection/traits/select.rs +++ b/src/librustc_trait_selection/traits/select.rs @@ -2877,11 +2877,15 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { trait_ref, )?); - obligations.push(Obligation::new( - obligation.cause.clone(), - obligation.param_env, - ty::Predicate::ClosureKind(closure_def_id, substs, kind), - )); + // FIXME: Chalk + + if !self.tcx().sess.opts.debugging_opts.chalk { + obligations.push(Obligation::new( + obligation.cause.clone(), + obligation.param_env, + ty::Predicate::ClosureKind(closure_def_id, substs, kind), + )); + } Ok(VtableClosureData { closure_def_id, substs, nested: obligations }) } diff --git a/src/librustc_traits/Cargo.toml b/src/librustc_traits/Cargo.toml index 839558f38fd..e485bc2929b 100644 --- a/src/librustc_traits/Cargo.toml +++ b/src/librustc_traits/Cargo.toml @@ -13,8 +13,12 @@ log = { version = "0.4" } rustc_middle = { path = "../librustc_middle" } rustc_data_structures = { path = "../librustc_data_structures" } rustc_hir = { path = "../librustc_hir" } +rustc_index = { path = "../librustc_index" } rustc_ast = { path = "../librustc_ast" } rustc_span = { path = "../librustc_span" } +chalk-ir = "0.10.0" +chalk-rust-ir = "0.10.0" +chalk-solve = "0.10.0" smallvec = { version = "1.0", features = ["union", "may_dangle"] } rustc_infer = { path = "../librustc_infer" } rustc_trait_selection = { path = "../librustc_trait_selection" } diff --git a/src/librustc_traits/chalk/db.rs b/src/librustc_traits/chalk/db.rs new file mode 100644 index 00000000000..0cec583bb56 --- /dev/null +++ b/src/librustc_traits/chalk/db.rs @@ -0,0 +1,521 @@ +//! Provides the `RustIrDatabase` implementation for `chalk-solve` +//! +//! The purpose of the `chalk_solve::RustIrDatabase` is to get data about +//! specific types, such as bounds, where clauses, or fields. This file contains +//! the minimal logic to assemble the types for `chalk-solve` by calling out to +//! either the `TyCtxt` (for information about types) or +//! `crate::chalk::lowering` (to lower rustc types into Chalk types). + +use rustc_middle::traits::{ChalkRustDefId as RustDefId, ChalkRustInterner as RustInterner}; +use rustc_middle::ty::subst::{InternalSubsts, Subst, SubstsRef}; +use rustc_middle::ty::{self, AssocItemContainer, AssocKind, TyCtxt}; + +use rustc_hir::def_id::DefId; + +use rustc_span::symbol::sym; + +use std::fmt; +use std::sync::Arc; + +use crate::chalk::lowering::LowerInto; + +pub struct RustIrDatabase<'tcx> { + pub tcx: TyCtxt<'tcx>, + pub interner: RustInterner<'tcx>, +} + +impl fmt::Debug for RustIrDatabase<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "RustIrDatabase") + } +} + +impl<'tcx> chalk_solve::RustIrDatabase> for RustIrDatabase<'tcx> { + fn interner(&self) -> &RustInterner<'tcx> { + &self.interner + } + + fn associated_ty_data( + &self, + assoc_type_id: chalk_ir::AssocTypeId>, + ) -> Arc>> { + let def_id = match assoc_type_id.0 { + RustDefId::AssocTy(def_id) => def_id, + _ => bug!("Did not use `AssocTy` variant when expecting associated type."), + }; + let assoc_item = self.tcx.associated_item(def_id); + let trait_def_id = match assoc_item.container { + AssocItemContainer::TraitContainer(def_id) => def_id, + _ => unimplemented!("Not possible??"), + }; + match assoc_item.kind { + AssocKind::Type => {} + _ => unimplemented!("Not possible??"), + } + let bound_vars = bound_vars_for_item(self.tcx, def_id); + let binders = binders_for(&self.interner, bound_vars); + // FIXME(chalk): this really isn't right I don't think. The functions + // for GATs are a bit hard to figure out. Are these supposed to be where + // clauses or bounds? + let predicates = self.tcx.predicates_defined_on(def_id).predicates; + let where_clauses: Vec<_> = predicates + .into_iter() + .map(|(wc, _)| wc.subst(self.tcx, &bound_vars)) + .filter_map(|wc| LowerInto::>>>::lower_into(wc, &self.interner)).collect(); + + Arc::new(chalk_rust_ir::AssociatedTyDatum { + trait_id: chalk_ir::TraitId(RustDefId::Trait(trait_def_id)), + id: assoc_type_id, + name: (), + binders: chalk_ir::Binders::new( + binders, + chalk_rust_ir::AssociatedTyDatumBound { bounds: vec![], where_clauses }, + ), + }) + } + + fn trait_datum( + &self, + trait_id: chalk_ir::TraitId>, + ) -> Arc>> { + let def_id = match trait_id.0 { + RustDefId::Trait(def_id) => def_id, + _ => bug!("Did not use `Trait` variant when expecting trait."), + }; + let trait_def = self.tcx.trait_def(def_id); + + let bound_vars = bound_vars_for_item(self.tcx, def_id); + let binders = binders_for(&self.interner, bound_vars); + let predicates = self.tcx.predicates_defined_on(def_id).predicates; + let where_clauses: Vec<_> = predicates + .into_iter() + .map(|(wc, _)| wc.subst(self.tcx, &bound_vars)) + .filter_map(|wc| LowerInto::>>>::lower_into(wc, &self.interner)).collect(); + + let well_known = + if self.tcx.lang_items().sized_trait().map(|t| def_id == t).unwrap_or(false) { + Some(chalk_rust_ir::WellKnownTrait::SizedTrait) + } else if self.tcx.lang_items().copy_trait().map(|t| def_id == t).unwrap_or(false) { + Some(chalk_rust_ir::WellKnownTrait::CopyTrait) + } else if self.tcx.lang_items().clone_trait().map(|t| def_id == t).unwrap_or(false) { + Some(chalk_rust_ir::WellKnownTrait::CloneTrait) + } else { + None + }; + Arc::new(chalk_rust_ir::TraitDatum { + id: trait_id, + binders: chalk_ir::Binders::new( + binders, + chalk_rust_ir::TraitDatumBound { where_clauses }, + ), + flags: chalk_rust_ir::TraitFlags { + auto: trait_def.has_auto_impl, + marker: trait_def.is_marker, + upstream: !def_id.is_local(), + fundamental: self.tcx.has_attr(def_id, sym::fundamental), + non_enumerable: true, + coinductive: false, + }, + associated_ty_ids: vec![], + well_known, + }) + } + + fn struct_datum( + &self, + struct_id: chalk_ir::StructId>, + ) -> Arc>> { + match struct_id.0 { + RustDefId::Adt(adt_def_id) => { + let adt_def = self.tcx.adt_def(adt_def_id); + + let bound_vars = bound_vars_for_item(self.tcx, adt_def_id); + let binders = binders_for(&self.interner, bound_vars); + + let predicates = self.tcx.predicates_of(adt_def_id).predicates; + let where_clauses: Vec<_> = predicates + .into_iter() + .map(|(wc, _)| wc.subst(self.tcx, bound_vars)) + .filter_map(|wc| LowerInto::>>>::lower_into(wc, &self.interner)) + .collect(); + let fields = match adt_def.adt_kind() { + ty::AdtKind::Struct | ty::AdtKind::Union => { + let variant = adt_def.non_enum_variant(); + variant + .fields + .iter() + .map(|field| { + self.tcx + .type_of(field.did) + .subst(self.tcx, bound_vars) + .lower_into(&self.interner) + }) + .collect() + } + // FIXME(chalk): handle enums; force_impl_for requires this + ty::AdtKind::Enum => vec![], + }; + let struct_datum = Arc::new(chalk_rust_ir::StructDatum { + id: struct_id, + binders: chalk_ir::Binders::new( + binders, + chalk_rust_ir::StructDatumBound { fields, where_clauses }, + ), + flags: chalk_rust_ir::StructFlags { + upstream: !adt_def_id.is_local(), + fundamental: adt_def.is_fundamental(), + }, + }); + return struct_datum; + } + RustDefId::Ref(_) => { + return Arc::new(chalk_rust_ir::StructDatum { + id: struct_id, + binders: chalk_ir::Binders::new( + chalk_ir::ParameterKinds::from( + &self.interner, + vec![ + chalk_ir::ParameterKind::Lifetime(()), + chalk_ir::ParameterKind::Ty(()), + ], + ), + chalk_rust_ir::StructDatumBound { fields: vec![], where_clauses: vec![] }, + ), + flags: chalk_rust_ir::StructFlags { upstream: false, fundamental: false }, + }); + } + RustDefId::Array | RustDefId::Slice => { + return Arc::new(chalk_rust_ir::StructDatum { + id: struct_id, + binders: chalk_ir::Binders::new( + chalk_ir::ParameterKinds::from( + &self.interner, + Some(chalk_ir::ParameterKind::Ty(())), + ), + chalk_rust_ir::StructDatumBound { fields: vec![], where_clauses: vec![] }, + ), + flags: chalk_rust_ir::StructFlags { upstream: false, fundamental: false }, + }); + } + RustDefId::Str | RustDefId::Never | RustDefId::FnDef(_) => { + return Arc::new(chalk_rust_ir::StructDatum { + id: struct_id, + binders: chalk_ir::Binders::new( + chalk_ir::ParameterKinds::new(&self.interner), + chalk_rust_ir::StructDatumBound { fields: vec![], where_clauses: vec![] }, + ), + flags: chalk_rust_ir::StructFlags { upstream: false, fundamental: false }, + }); + } + + _ => bug!("Used not struct variant when expecting struct variant."), + } + } + + fn impl_datum( + &self, + impl_id: chalk_ir::ImplId>, + ) -> Arc>> { + let def_id = match impl_id.0 { + RustDefId::Impl(def_id) => def_id, + _ => bug!("Did not use `Impl` variant when expecting impl."), + }; + let bound_vars = bound_vars_for_item(self.tcx, def_id); + let binders = binders_for(&self.interner, bound_vars); + + let trait_ref = self.tcx.impl_trait_ref(def_id).expect("not an impl"); + let trait_ref = trait_ref.subst(self.tcx, bound_vars); + + let predicates = self.tcx.predicates_of(def_id).predicates; + let where_clauses: Vec<_> = predicates + .into_iter() + .map(|(wc, _)| wc.subst(self.tcx, bound_vars)) + .filter_map(|wc| LowerInto::>>>::lower_into(wc, &self.interner)).collect(); + + let value = chalk_rust_ir::ImplDatumBound { + trait_ref: trait_ref.lower_into(&self.interner), + where_clauses, + }; + + Arc::new(chalk_rust_ir::ImplDatum { + polarity: chalk_rust_ir::Polarity::Positive, + binders: chalk_ir::Binders::new(binders, value), + impl_type: chalk_rust_ir::ImplType::Local, + associated_ty_value_ids: vec![], + }) + } + + fn impls_for_trait( + &self, + trait_id: chalk_ir::TraitId>, + parameters: &[chalk_ir::Parameter>], + ) -> Vec>> { + let def_id: DefId = match trait_id.0 { + RustDefId::Trait(def_id) => def_id, + _ => bug!("Did not use `Trait` variant when expecting trait."), + }; + + // FIXME(chalk): use TraitDef::for_each_relevant_impl, but that will + // require us to be able to interconvert `Ty<'tcx>`, and we're + // not there yet. + + let all_impls = self.tcx.all_impls(def_id); + let matched_impls = all_impls.into_iter().filter(|impl_def_id| { + use chalk_ir::could_match::CouldMatch; + let trait_ref = self.tcx.impl_trait_ref(*impl_def_id).unwrap(); + let bound_vars = bound_vars_for_item(self.tcx, *impl_def_id); + + let self_ty = trait_ref.self_ty(); + let self_ty = self_ty.subst(self.tcx, bound_vars); + let lowered_ty = self_ty.lower_into(&self.interner); + + parameters[0].assert_ty_ref(&self.interner).could_match(&self.interner, &lowered_ty) + }); + + let impls = matched_impls + .map(|matched_impl| chalk_ir::ImplId(RustDefId::Impl(matched_impl))) + .collect(); + impls + } + + fn impl_provided_for( + &self, + auto_trait_id: chalk_ir::TraitId>, + struct_id: chalk_ir::StructId>, + ) -> bool { + let trait_def_id: DefId = match auto_trait_id.0 { + RustDefId::Trait(def_id) => def_id, + _ => bug!("Did not use `Trait` variant when expecting trait."), + }; + let adt_def_id: DefId = match struct_id.0 { + RustDefId::Adt(def_id) => def_id, + _ => bug!("Did not use `Adt` variant when expecting adt."), + }; + let all_impls = self.tcx.all_impls(trait_def_id); + for impl_def_id in all_impls { + let trait_ref = self.tcx.impl_trait_ref(impl_def_id).unwrap(); + let self_ty = trait_ref.self_ty(); + match self_ty.kind { + ty::Adt(adt_def, _) => { + if adt_def.did == adt_def_id { + return true; + } + } + _ => {} + } + } + return false; + } + + fn associated_ty_value( + &self, + associated_ty_id: chalk_rust_ir::AssociatedTyValueId>, + ) -> Arc>> { + let def_id = match associated_ty_id.0 { + RustDefId::AssocTy(def_id) => def_id, + _ => bug!("Did not use `AssocTy` variant when expecting associated type."), + }; + let assoc_item = self.tcx.associated_item(def_id); + let impl_id = match assoc_item.container { + AssocItemContainer::TraitContainer(def_id) => def_id, + _ => unimplemented!("Not possible??"), + }; + match assoc_item.kind { + AssocKind::Type => {} + _ => unimplemented!("Not possible??"), + } + let bound_vars = bound_vars_for_item(self.tcx, def_id); + let binders = binders_for(&self.interner, bound_vars); + let ty = self.tcx.type_of(def_id); + + Arc::new(chalk_rust_ir::AssociatedTyValue { + impl_id: chalk_ir::ImplId(RustDefId::Impl(impl_id)), + associated_ty_id: chalk_ir::AssocTypeId(RustDefId::AssocTy(def_id)), + value: chalk_ir::Binders::new( + binders, + chalk_rust_ir::AssociatedTyValueBound { ty: ty.lower_into(&self.interner) }, + ), + }) + } + + fn custom_clauses(&self) -> Vec>> { + vec![] + } + + fn local_impls_to_coherence_check( + &self, + _trait_id: chalk_ir::TraitId>, + ) -> Vec>> { + unimplemented!() + } + + fn opaque_ty_data( + &self, + _id: chalk_ir::OpaqueTyId>, + ) -> Arc>> { + unimplemented!() + } + + /// Since Chalk can't handle all Rust types currently, we have to handle + /// some specially for now. Over time, these `Some` returns will change to + /// `None` and eventually this function will be removed. + fn force_impl_for( + &self, + well_known: chalk_rust_ir::WellKnownTrait, + ty: &chalk_ir::TyData>, + ) -> Option { + use chalk_ir::TyData::*; + match well_known { + chalk_rust_ir::WellKnownTrait::SizedTrait => match ty { + Apply(apply) => match apply.name { + chalk_ir::TypeName::Struct(chalk_ir::StructId(rust_def_id)) => { + use rustc_middle::traits::ChalkRustDefId::*; + match rust_def_id { + Never | Array | RawPtr | FnDef(_) | Ref(_) => Some(true), + + Adt(adt_def_id) => { + let adt_def = self.tcx.adt_def(adt_def_id); + match adt_def.adt_kind() { + ty::AdtKind::Struct | ty::AdtKind::Union => None, + ty::AdtKind::Enum => { + let constraint = self.tcx.adt_sized_constraint(adt_def_id); + if constraint.0.len() > 0 { + unimplemented!() + } else { + Some(true) + } + } + } + } + + Str | Slice => Some(false), + + Trait(_) | Impl(_) | AssocTy(_) => panic!(), + } + } + _ => None, + }, + Dyn(_) | Alias(_) | Placeholder(_) | Function(_) | InferenceVar(_) + | BoundVar(_) => None, + }, + chalk_rust_ir::WellKnownTrait::CopyTrait + | chalk_rust_ir::WellKnownTrait::CloneTrait => match ty { + Apply(apply) => match apply.name { + chalk_ir::TypeName::Struct(chalk_ir::StructId(rust_def_id)) => { + use rustc_middle::traits::ChalkRustDefId::*; + match rust_def_id { + Never | RawPtr | Ref(_) | Str | Slice => Some(false), + FnDef(_) | Array => Some(true), + Adt(adt_def_id) => { + let adt_def = self.tcx.adt_def(adt_def_id); + match adt_def.adt_kind() { + ty::AdtKind::Struct | ty::AdtKind::Union => None, + ty::AdtKind::Enum => { + let constraint = self.tcx.adt_sized_constraint(adt_def_id); + if constraint.0.len() > 0 { + unimplemented!() + } else { + Some(true) + } + } + } + } + Trait(_) | Impl(_) | AssocTy(_) => panic!(), + } + } + _ => None, + }, + Dyn(_) | Alias(_) | Placeholder(_) | Function(_) | InferenceVar(_) + | BoundVar(_) => None, + }, + chalk_rust_ir::WellKnownTrait::DropTrait => None, + } + } + + fn program_clauses_for_env( + &self, + environment: &chalk_ir::Environment>, + ) -> chalk_ir::ProgramClauses> { + chalk_solve::program_clauses_for_env(self, environment) + } + + fn well_known_trait_id( + &self, + well_known_trait: chalk_rust_ir::WellKnownTrait, + ) -> Option>> { + use chalk_rust_ir::WellKnownTrait::*; + let t = match well_known_trait { + SizedTrait => self + .tcx + .lang_items() + .sized_trait() + .map(|t| chalk_ir::TraitId(RustDefId::Trait(t))) + .unwrap(), + CopyTrait => self + .tcx + .lang_items() + .copy_trait() + .map(|t| chalk_ir::TraitId(RustDefId::Trait(t))) + .unwrap(), + CloneTrait => self + .tcx + .lang_items() + .clone_trait() + .map(|t| chalk_ir::TraitId(RustDefId::Trait(t))) + .unwrap(), + DropTrait => self + .tcx + .lang_items() + .drop_trait() + .map(|t| chalk_ir::TraitId(RustDefId::Trait(t))) + .unwrap(), + }; + Some(t) + } +} + +/// Creates a `InternalSubsts` that maps each generic parameter to a higher-ranked +/// var bound at index `0`. For types, we use a `BoundVar` index equal to +/// the type parameter index. For regions, we use the `BoundRegion::BrNamed` +/// variant (which has a `DefId`). +fn bound_vars_for_item(tcx: TyCtxt<'tcx>, def_id: DefId) -> SubstsRef<'tcx> { + InternalSubsts::for_item(tcx, def_id, |param, substs| match param.kind { + ty::GenericParamDefKind::Type { .. } => tcx + .mk_ty(ty::Bound( + ty::INNERMOST, + ty::BoundTy { + var: ty::BoundVar::from(param.index), + kind: ty::BoundTyKind::Param(param.name), + }, + )) + .into(), + + ty::GenericParamDefKind::Lifetime => tcx + .mk_region(ty::RegionKind::ReLateBound( + ty::INNERMOST, + ty::BoundRegion::BrAnon(substs.len() as u32), + )) + .into(), + + ty::GenericParamDefKind::Const => tcx + .mk_const(ty::Const { + val: ty::ConstKind::Bound(ty::INNERMOST, ty::BoundVar::from(param.index)), + ty: tcx.type_of(param.def_id), + }) + .into(), + }) +} + +fn binders_for<'tcx>( + interner: &RustInterner<'tcx>, + bound_vars: SubstsRef<'tcx>, +) -> chalk_ir::ParameterKinds> { + chalk_ir::ParameterKinds::from( + interner, + bound_vars.iter().map(|arg| match arg.unpack() { + ty::subst::GenericArgKind::Lifetime(_re) => chalk_ir::ParameterKind::Lifetime(()), + ty::subst::GenericArgKind::Type(_ty) => chalk_ir::ParameterKind::Ty(()), + ty::subst::GenericArgKind::Const(_const) => chalk_ir::ParameterKind::Ty(()), + }), + ) +} diff --git a/src/librustc_traits/chalk/lowering.rs b/src/librustc_traits/chalk/lowering.rs new file mode 100644 index 00000000000..70aba31a2d3 --- /dev/null +++ b/src/librustc_traits/chalk/lowering.rs @@ -0,0 +1,722 @@ +//! Contains the logic to lower rustc types into Chalk types +//! +//! In many there is a 1:1 relationship between a rustc type and a Chalk type. +//! For example, a `SubstsRef` maps almost directly to a `Substitution`. In some +//! other cases, such as `Param`s, there is no Chalk type, so we have to handle +//! accordingly. +//! +//! ## `Ty` lowering +//! Much of the `Ty` lowering is 1:1 with Chalk. (Or will be eventually). A +//! helpful table for what types lower to what can be found in the +//! [Chalk book](http://rust-lang.github.io/chalk/book/types/rust_types.html). +//! The most notable difference lies with `Param`s. To convert from rustc to +//! Chalk, we eagerly and deeply convert `Param`s to placeholders (in goals) or +//! bound variables (for clause generation through functions in `db`). +//! +//! ## `Region` lowering +//! Regions are handled in rustc and Chalk is quite differently. In rustc, there +//! is a difference between "early bound" and "late bound" regions, where only +//! the late bound regions have a `DebruijnIndex`. Moreover, in Chalk all +//! regions (Lifetimes) have an associated index. In rustc, only `BrAnon`s have +//! an index, whereas `BrNamed` don't. In order to lower regions to Chalk, we +//! convert all regions into `BrAnon` late-bound regions. +//! +//! ## `Const` lowering +//! Chalk doesn't handle consts currently, so consts are currently lowered to +//! an empty tuple. +//! +//! ## Bound variable collection +//! Another difference between rustc and Chalk lies in the handling of binders. +//! Chalk requires that we store the bound parameter kinds, whereas rustc does +//! not. To lower anything wrapped in a `Binder`, we first deeply find any bound +//! variables from the current `Binder`. + +use rustc_middle::traits::{ + ChalkEnvironmentAndGoal, ChalkEnvironmentClause, ChalkRustDefId as RustDefId, + ChalkRustInterner as RustInterner, +}; +use rustc_middle::ty::fold::TypeFolder; +use rustc_middle::ty::subst::{GenericArg, SubstsRef}; +use rustc_middle::ty::{ + self, Binder, BoundRegion, Predicate, Region, RegionKind, Ty, TyCtxt, TyKind, TypeFoldable, + TypeVisitor, +}; +use rustc_span::def_id::DefId; + +use std::collections::btree_map::{BTreeMap, Entry}; + +/// Essentially an `Into` with a `&RustInterner` parameter +crate trait LowerInto<'tcx, T> { + /// Lower a rustc construct (e.g., `ty::TraitPredicate`) to a chalk type, consuming `self`. + fn lower_into(self, interner: &RustInterner<'tcx>) -> T; +} + +impl<'tcx> LowerInto<'tcx, chalk_ir::Substitution>> for SubstsRef<'tcx> { + fn lower_into( + self, + interner: &RustInterner<'tcx>, + ) -> chalk_ir::Substitution> { + chalk_ir::Substitution::from(interner, self.iter().map(|s| s.lower_into(interner))) + } +} + +impl<'tcx> LowerInto<'tcx, chalk_ir::AliasTy>> for ty::ProjectionTy<'tcx> { + fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::AliasTy> { + chalk_ir::AliasTy::Projection(chalk_ir::ProjectionTy { + associated_ty_id: chalk_ir::AssocTypeId(RustDefId::AssocTy(self.item_def_id)), + substitution: self.substs.lower_into(interner), + }) + } +} + +impl<'tcx> LowerInto<'tcx, chalk_ir::InEnvironment>>> + for ChalkEnvironmentAndGoal<'tcx> +{ + fn lower_into( + self, + interner: &RustInterner<'tcx>, + ) -> chalk_ir::InEnvironment>> { + let clauses = self.environment.into_iter().filter_map(|clause| match clause { + ChalkEnvironmentClause::Predicate(predicate) => { + match predicate { + ty::Predicate::Trait(predicate, _) => { + let (predicate, binders, _named_regions) = + collect_bound_vars(interner, interner.tcx, predicate); + + Some( + chalk_ir::ProgramClauseData::ForAll(chalk_ir::Binders::new( + binders, + chalk_ir::ProgramClauseImplication { + consequence: chalk_ir::DomainGoal::FromEnv( + chalk_ir::FromEnv::Trait( + predicate.trait_ref.lower_into(interner), + ), + ), + conditions: chalk_ir::Goals::new(interner), + priority: chalk_ir::ClausePriority::High, + }, + )) + .intern(interner), + ) + } + // FIXME(chalk): need to add RegionOutlives/TypeOutlives + ty::Predicate::RegionOutlives(_) => None, + ty::Predicate::TypeOutlives(_) => None, + ty::Predicate::Projection(predicate) => { + let (predicate, binders, _named_regions) = + collect_bound_vars(interner, interner.tcx, predicate); + + Some( + chalk_ir::ProgramClauseData::ForAll(chalk_ir::Binders::new( + binders, + chalk_ir::ProgramClauseImplication { + consequence: chalk_ir::DomainGoal::Holds( + chalk_ir::WhereClause::AliasEq( + predicate.lower_into(interner), + ), + ), + conditions: chalk_ir::Goals::new(interner), + priority: chalk_ir::ClausePriority::High, + }, + )) + .intern(interner), + ) + } + ty::Predicate::WellFormed(..) + | ty::Predicate::ObjectSafe(..) + | ty::Predicate::ClosureKind(..) + | ty::Predicate::Subtype(..) + | ty::Predicate::ConstEvaluatable(..) => { + bug!("unexpected predicate {}", predicate) + } + } + } + ChalkEnvironmentClause::TypeFromEnv(ty) => Some( + chalk_ir::ProgramClauseData::Implies(chalk_ir::ProgramClauseImplication { + consequence: chalk_ir::DomainGoal::FromEnv(chalk_ir::FromEnv::Ty( + ty.lower_into(interner), + )), + conditions: chalk_ir::Goals::new(interner), + priority: chalk_ir::ClausePriority::High, + }) + .intern(interner), + ), + }); + + let goal: chalk_ir::GoalData> = self.goal.lower_into(&interner); + chalk_ir::InEnvironment { + environment: chalk_ir::Environment { + clauses: chalk_ir::ProgramClauses::from(&interner, clauses), + }, + goal: goal.intern(&interner), + } + } +} + +impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData>> for ty::Predicate<'tcx> { + fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GoalData> { + match self { + Predicate::Trait(predicate, _) => predicate.lower_into(interner), + // FIXME(chalk): we need to register constraints. + Predicate::RegionOutlives(_predicate) => { + chalk_ir::GoalData::All(chalk_ir::Goals::new(interner)) + } + Predicate::TypeOutlives(_predicate) => { + chalk_ir::GoalData::All(chalk_ir::Goals::new(interner)) + } + Predicate::Projection(predicate) => predicate.lower_into(interner), + Predicate::WellFormed(ty) => match ty.kind { + // These types are always WF. + ty::Str | ty::Placeholder(..) | ty::Error | ty::Never => { + chalk_ir::GoalData::All(chalk_ir::Goals::new(interner)) + } + + // FIXME(chalk): Well-formed only if ref lifetime outlives type + ty::Ref(..) => chalk_ir::GoalData::All(chalk_ir::Goals::new(interner)), + + ty::Param(..) => panic!("No Params expected."), + + // FIXME(chalk) -- ultimately I think this is what we + // want to do, and we just have rules for how to prove + // `WellFormed` for everything above, instead of + // inlining a bit the rules of the proof here. + _ => chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::WellFormed( + chalk_ir::WellFormed::Ty(ty.lower_into(interner)), + )), + }, + + // FIXME(chalk): other predicates + // + // We can defer this, but ultimately we'll want to express + // some of these in terms of chalk operations. + Predicate::ObjectSafe(..) + | Predicate::ClosureKind(..) + | Predicate::Subtype(..) + | Predicate::ConstEvaluatable(..) => { + chalk_ir::GoalData::All(chalk_ir::Goals::new(interner)) + } + } + } +} + +impl<'tcx> LowerInto<'tcx, chalk_ir::TraitRef>> + for rustc_middle::ty::TraitRef<'tcx> +{ + fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::TraitRef> { + chalk_ir::TraitRef { + trait_id: chalk_ir::TraitId(RustDefId::Trait(self.def_id)), + substitution: self.substs.lower_into(interner), + } + } +} + +impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData>> + for ty::PolyTraitPredicate<'tcx> +{ + fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GoalData> { + let (ty, binders, _named_regions) = collect_bound_vars(interner, interner.tcx, &self); + + chalk_ir::GoalData::Quantified( + chalk_ir::QuantifierKind::ForAll, + chalk_ir::Binders::new( + binders, + chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds( + chalk_ir::WhereClause::Implemented(ty.trait_ref.lower_into(interner)), + )) + .intern(interner), + ), + ) + } +} + +impl<'tcx> LowerInto<'tcx, chalk_ir::AliasEq>> + for rustc_middle::ty::ProjectionPredicate<'tcx> +{ + fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::AliasEq> { + chalk_ir::AliasEq { + ty: self.ty.lower_into(interner), + alias: self.projection_ty.lower_into(interner), + } + } +} + +impl<'tcx> LowerInto<'tcx, chalk_ir::GoalData>> + for ty::PolyProjectionPredicate<'tcx> +{ + fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::GoalData> { + let (ty, binders, _named_regions) = collect_bound_vars(interner, interner.tcx, &self); + + chalk_ir::GoalData::Quantified( + chalk_ir::QuantifierKind::ForAll, + chalk_ir::Binders::new( + binders, + chalk_ir::GoalData::DomainGoal(chalk_ir::DomainGoal::Holds( + chalk_ir::WhereClause::AliasEq(ty.lower_into(interner)), + )) + .intern(interner), + ), + ) + } +} + +impl<'tcx> LowerInto<'tcx, chalk_ir::Ty>> for Ty<'tcx> { + fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::Ty> { + use chalk_ir::TyData; + use rustc_ast::ast; + use TyKind::*; + + let empty = || chalk_ir::Substitution::empty(interner); + let struct_ty = |def_id| chalk_ir::TypeName::Struct(chalk_ir::StructId(def_id)); + let apply = |name, substitution| { + TyData::Apply(chalk_ir::ApplicationTy { name, substitution }).intern(interner) + }; + let int = |i| apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Int(i)), empty()); + let uint = |i| apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Uint(i)), empty()); + let float = |f| apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Float(f)), empty()); + + return match self.kind { + Bool => apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Bool), empty()), + Char => apply(chalk_ir::TypeName::Scalar(chalk_ir::Scalar::Char), empty()), + Int(ty) => match ty { + ast::IntTy::Isize => int(chalk_ir::IntTy::Isize), + ast::IntTy::I8 => int(chalk_ir::IntTy::I8), + ast::IntTy::I16 => int(chalk_ir::IntTy::I16), + ast::IntTy::I32 => int(chalk_ir::IntTy::I32), + ast::IntTy::I64 => int(chalk_ir::IntTy::I64), + ast::IntTy::I128 => int(chalk_ir::IntTy::I128), + }, + Uint(ty) => match ty { + ast::UintTy::Usize => uint(chalk_ir::UintTy::Usize), + ast::UintTy::U8 => uint(chalk_ir::UintTy::U8), + ast::UintTy::U16 => uint(chalk_ir::UintTy::U16), + ast::UintTy::U32 => uint(chalk_ir::UintTy::U32), + ast::UintTy::U64 => uint(chalk_ir::UintTy::U64), + ast::UintTy::U128 => uint(chalk_ir::UintTy::U128), + }, + Float(ty) => match ty { + ast::FloatTy::F32 => float(chalk_ir::FloatTy::F32), + ast::FloatTy::F64 => float(chalk_ir::FloatTy::F64), + }, + Adt(def, substs) => { + apply(struct_ty(RustDefId::Adt(def.did)), substs.lower_into(interner)) + } + Foreign(_def_id) => unimplemented!(), + Str => apply(struct_ty(RustDefId::Str), empty()), + Array(ty, _) => apply( + struct_ty(RustDefId::Array), + chalk_ir::Substitution::from1( + interner, + chalk_ir::ParameterKind::Ty(ty.lower_into(interner)).intern(interner), + ), + ), + Slice(ty) => apply( + struct_ty(RustDefId::Slice), + chalk_ir::Substitution::from1( + interner, + chalk_ir::ParameterKind::Ty(ty.lower_into(interner)).intern(interner), + ), + ), + RawPtr(_) => apply(struct_ty(RustDefId::RawPtr), empty()), + Ref(region, ty, mutability) => apply( + struct_ty(RustDefId::Ref(mutability)), + chalk_ir::Substitution::from( + interner, + [ + chalk_ir::ParameterKind::Lifetime(region.lower_into(interner)) + .intern(interner), + chalk_ir::ParameterKind::Ty(ty.lower_into(interner)).intern(interner), + ] + .iter(), + ), + ), + FnDef(def_id, _) => apply(struct_ty(RustDefId::FnDef(def_id)), empty()), + FnPtr(sig) => { + let (inputs_and_outputs, binders, _named_regions) = + collect_bound_vars(interner, interner.tcx, &sig.inputs_and_output()); + TyData::Function(chalk_ir::Fn { + num_binders: binders.len(interner), + substitution: chalk_ir::Substitution::from( + interner, + inputs_and_outputs.iter().map(|ty| { + chalk_ir::ParameterKind::Ty(ty.lower_into(interner)).intern(interner) + }), + ), + }) + .intern(interner) + } + Dynamic(_, _) => unimplemented!(), + Closure(_def_id, _) => unimplemented!(), + Generator(_def_id, _substs, _) => unimplemented!(), + GeneratorWitness(_) => unimplemented!(), + Never => apply(struct_ty(RustDefId::Never), empty()), + Tuple(substs) => { + apply(chalk_ir::TypeName::Tuple(substs.len()), substs.lower_into(interner)) + } + Projection(proj) => TyData::Alias(proj.lower_into(interner)).intern(interner), + UnnormalizedProjection(_proj) => unimplemented!(), + Opaque(_def_id, _substs) => unimplemented!(), + // This should have been done eagerly prior to this, and all Params + // should have been substituted to placeholders + Param(_) => panic!("Lowering Param when not expected."), + Bound(db, bound) => TyData::BoundVar(chalk_ir::BoundVar::new( + chalk_ir::DebruijnIndex::new(db.as_u32()), + bound.var.index(), + )) + .intern(interner), + Placeholder(_placeholder) => TyData::Placeholder(chalk_ir::PlaceholderIndex { + ui: chalk_ir::UniverseIndex { counter: _placeholder.universe.as_usize() }, + idx: _placeholder.name.as_usize(), + }) + .intern(interner), + Infer(_infer) => unimplemented!(), + Error => unimplemented!(), + }; + } +} + +impl<'tcx> LowerInto<'tcx, chalk_ir::Lifetime>> for Region<'tcx> { + fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::Lifetime> { + use rustc_middle::ty::RegionKind::*; + + match self { + ReEarlyBound(_) => { + panic!("Should have already been substituted."); + } + ReLateBound(db, br) => match br { + ty::BoundRegion::BrAnon(var) => { + chalk_ir::LifetimeData::BoundVar(chalk_ir::BoundVar::new( + chalk_ir::DebruijnIndex::new(db.as_u32()), + *var as usize, + )) + .intern(interner) + } + ty::BoundRegion::BrNamed(_def_id, _name) => unimplemented!(), + ty::BrEnv => unimplemented!(), + }, + ReFree(_) => unimplemented!(), + ReScope(_) => unimplemented!(), + ReStatic => unimplemented!(), + ReVar(_) => unimplemented!(), + RePlaceholder(placeholder_region) => { + chalk_ir::LifetimeData::Placeholder(chalk_ir::PlaceholderIndex { + ui: chalk_ir::UniverseIndex { counter: placeholder_region.universe.index() }, + idx: 0, + }) + .intern(interner) + } + ReEmpty(_) => unimplemented!(), + ReErased => unimplemented!(), + } + } +} + +impl<'tcx> LowerInto<'tcx, chalk_ir::Parameter>> for GenericArg<'tcx> { + fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::Parameter> { + match self.unpack() { + ty::subst::GenericArgKind::Type(ty) => { + chalk_ir::ParameterKind::Ty(ty.lower_into(interner)) + } + ty::subst::GenericArgKind::Lifetime(lifetime) => { + chalk_ir::ParameterKind::Lifetime(lifetime.lower_into(interner)) + } + ty::subst::GenericArgKind::Const(_) => chalk_ir::ParameterKind::Ty( + chalk_ir::TyData::Apply(chalk_ir::ApplicationTy { + name: chalk_ir::TypeName::Tuple(0), + substitution: chalk_ir::Substitution::empty(interner), + }) + .intern(interner), + ), + } + .intern(interner) + } +} + +// We lower into an Option here since there are some predicates which Chalk +// doesn't have a representation for yet (as a `WhereClause`), but are so common +// that we just are accepting the unsoundness for now. The `Option` will +// eventually be removed. +impl<'tcx> LowerInto<'tcx, Option>>> + for ty::Predicate<'tcx> +{ + fn lower_into( + self, + interner: &RustInterner<'tcx>, + ) -> Option>> { + match &self { + Predicate::Trait(predicate, _) => { + let (predicate, binders, _named_regions) = + collect_bound_vars(interner, interner.tcx, predicate); + + Some(chalk_ir::Binders::new( + binders, + chalk_ir::WhereClause::Implemented(predicate.trait_ref.lower_into(interner)), + )) + } + Predicate::RegionOutlives(_predicate) => None, + Predicate::TypeOutlives(_predicate) => None, + Predicate::Projection(_predicate) => None, + Predicate::WellFormed(_ty) => None, + + Predicate::ObjectSafe(..) + | Predicate::ClosureKind(..) + | Predicate::Subtype(..) + | Predicate::ConstEvaluatable(..) => bug!("unexpected predicate {}", &self), + } + } +} + +/// To collect bound vars, we have to do two passes. In the first pass, we +/// collect all `BoundRegion`s and `ty::Bound`s. In the second pass, we then +/// replace `BrNamed` into `BrAnon`. The two separate passes are important, +/// since we can only replace `BrNamed` with `BrAnon`s with indices *after* all +/// "real" `BrAnon`s. +/// +/// It's important to note that because of prior substitution, we may have +/// late-bound regions, even outside of fn contexts, since this is the best way +/// to prep types for chalk lowering. +crate fn collect_bound_vars<'a, 'tcx, T: TypeFoldable<'tcx>>( + interner: &RustInterner<'tcx>, + tcx: TyCtxt<'tcx>, + ty: &'a Binder, +) -> (T, chalk_ir::ParameterKinds>, BTreeMap) { + let mut bound_vars_collector = BoundVarsCollector::new(); + ty.skip_binder().visit_with(&mut bound_vars_collector); + let mut parameters = bound_vars_collector.parameters; + let named_parameters: BTreeMap = bound_vars_collector + .named_parameters + .into_iter() + .enumerate() + .map(|(i, def_id)| (def_id, (i + parameters.len()) as u32)) + .collect(); + + let mut bound_var_substitutor = NamedBoundVarSubstitutor::new(tcx, &named_parameters); + let new_ty = ty.skip_binder().fold_with(&mut bound_var_substitutor); + + for var in named_parameters.values() { + parameters.insert(*var, chalk_ir::ParameterKind::Lifetime(())); + } + + (0..parameters.len()).for_each(|i| { + parameters.get(&(i as u32)).expect("Skipped bound var index."); + }); + + let binders = chalk_ir::ParameterKinds::from(interner, parameters.into_iter().map(|(_, v)| v)); + + (new_ty, binders, named_parameters) +} + +crate struct BoundVarsCollector { + binder_index: ty::DebruijnIndex, + crate parameters: BTreeMap>, + crate named_parameters: Vec, +} + +impl BoundVarsCollector { + crate fn new() -> Self { + BoundVarsCollector { + binder_index: ty::INNERMOST, + parameters: BTreeMap::new(), + named_parameters: vec![], + } + } +} + +impl<'tcx> TypeVisitor<'tcx> for BoundVarsCollector { + fn visit_binder>(&mut self, t: &Binder) -> bool { + self.binder_index.shift_in(1); + let result = t.super_visit_with(self); + self.binder_index.shift_out(1); + result + } + + fn visit_ty(&mut self, t: Ty<'tcx>) -> bool { + match t.kind { + ty::Bound(debruijn, bound_ty) if debruijn == self.binder_index => { + match self.parameters.entry(bound_ty.var.as_u32()) { + Entry::Vacant(entry) => { + entry.insert(chalk_ir::ParameterKind::Ty(())); + } + Entry::Occupied(entry) => { + entry.get().assert_ty_ref(); + } + } + } + + _ => (), + }; + + t.super_visit_with(self) + } + + fn visit_region(&mut self, r: Region<'tcx>) -> bool { + match r { + ty::ReLateBound(index, br) if *index == self.binder_index => match br { + ty::BoundRegion::BrNamed(def_id, _name) => { + if self.named_parameters.iter().find(|d| *d == def_id).is_none() { + self.named_parameters.push(*def_id); + } + } + + ty::BoundRegion::BrAnon(var) => match self.parameters.entry(*var) { + Entry::Vacant(entry) => { + entry.insert(chalk_ir::ParameterKind::Lifetime(())); + } + Entry::Occupied(entry) => { + entry.get().assert_lifetime_ref(); + } + }, + + ty::BrEnv => unimplemented!(), + }, + + ty::ReEarlyBound(_re) => { + // FIXME(chalk): jackh726 - I think we should always have already + // substituted away `ReEarlyBound`s for `ReLateBound`s, but need to confirm. + unimplemented!(); + } + + _ => (), + }; + + r.super_visit_with(self) + } +} + +/// This is used to replace `BoundRegion::BrNamed` with `BoundRegion::BrAnon`. +/// Note: we assume that we will always have room for more bound vars. (i.e. we +/// won't ever hit the `u32` limit in `BrAnon`s). +struct NamedBoundVarSubstitutor<'a, 'tcx> { + tcx: TyCtxt<'tcx>, + binder_index: ty::DebruijnIndex, + named_parameters: &'a BTreeMap, +} + +impl<'a, 'tcx> NamedBoundVarSubstitutor<'a, 'tcx> { + fn new(tcx: TyCtxt<'tcx>, named_parameters: &'a BTreeMap) -> Self { + NamedBoundVarSubstitutor { tcx, binder_index: ty::INNERMOST, named_parameters } + } +} + +impl<'a, 'tcx> TypeFolder<'tcx> for NamedBoundVarSubstitutor<'a, 'tcx> { + fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { + self.tcx + } + + fn fold_binder>(&mut self, t: &Binder) -> Binder { + self.binder_index.shift_in(1); + let result = t.super_fold_with(self); + self.binder_index.shift_out(1); + result + } + + fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { + t.super_fold_with(self) + } + + fn fold_region(&mut self, r: Region<'tcx>) -> Region<'tcx> { + match r { + ty::ReLateBound(index, br) if *index == self.binder_index => match br { + ty::BoundRegion::BrNamed(def_id, _name) => { + match self.named_parameters.get(def_id) { + Some(idx) => { + return self.tcx.mk_region(RegionKind::ReLateBound( + *index, + BoundRegion::BrAnon(*idx), + )); + } + None => panic!("Missing `BrNamed`."), + } + } + ty::BrEnv => unimplemented!(), + ty::BoundRegion::BrAnon(_) => {} + }, + _ => (), + }; + + r.super_fold_with(self) + } +} + +/// Used to substitute `Param`s with placeholders. We do this since Chalk +/// have a notion of `Param`s. +crate struct ParamsSubstitutor<'tcx> { + tcx: TyCtxt<'tcx>, + binder_index: ty::DebruijnIndex, + list: Vec, + crate params: rustc_data_structures::fx::FxHashMap, + crate named_regions: BTreeMap, +} + +impl<'tcx> ParamsSubstitutor<'tcx> { + crate fn new(tcx: TyCtxt<'tcx>) -> Self { + ParamsSubstitutor { + tcx, + binder_index: ty::INNERMOST, + list: vec![], + params: rustc_data_structures::fx::FxHashMap::default(), + named_regions: BTreeMap::default(), + } + } +} + +impl<'tcx> TypeFolder<'tcx> for ParamsSubstitutor<'tcx> { + fn tcx<'b>(&'b self) -> TyCtxt<'tcx> { + self.tcx + } + + fn fold_binder>(&mut self, t: &Binder) -> Binder { + self.binder_index.shift_in(1); + let result = t.super_fold_with(self); + self.binder_index.shift_out(1); + result + } + + fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { + match t.kind { + // FIXME(chalk): currently we convert params to placeholders starting at + // index `0`. To support placeholders, we'll actually need to do a + // first pass to collect placeholders. Then we can insert params after. + ty::Placeholder(_) => unimplemented!(), + ty::Param(param) => match self.list.iter().position(|r| r == ¶m) { + Some(_idx) => self.tcx.mk_ty(ty::Placeholder(ty::PlaceholderType { + universe: ty::UniverseIndex::from_usize(0), + name: ty::BoundVar::from_usize(_idx), + })), + None => { + self.list.push(param); + let idx = self.list.len() - 1; + self.params.insert(idx, param); + self.tcx.mk_ty(ty::Placeholder(ty::PlaceholderType { + universe: ty::UniverseIndex::from_usize(0), + name: ty::BoundVar::from_usize(idx), + })) + } + }, + + _ => t.super_fold_with(self), + } + } + + fn fold_region(&mut self, r: Region<'tcx>) -> Region<'tcx> { + match r { + // FIXME(chalk) - jackh726 - this currently isn't hit in any tests. + // This covers any region variables in a goal, right? + ty::ReEarlyBound(_re) => match self.named_regions.get(&_re.def_id) { + Some(idx) => self.tcx.mk_region(RegionKind::ReLateBound( + self.binder_index, + BoundRegion::BrAnon(*idx), + )), + None => { + let idx = self.named_regions.len() as u32; + self.named_regions.insert(_re.def_id, idx); + self.tcx.mk_region(RegionKind::ReLateBound( + self.binder_index, + BoundRegion::BrAnon(idx), + )) + } + }, + + _ => r.super_fold_with(self), + } + } +} diff --git a/src/librustc_traits/chalk/mod.rs b/src/librustc_traits/chalk/mod.rs new file mode 100644 index 00000000000..4e635b9db09 --- /dev/null +++ b/src/librustc_traits/chalk/mod.rs @@ -0,0 +1,227 @@ +//! Calls `chalk-solve` to solve a `ty::Predicate` +//! +//! In order to call `chalk-solve`, this file must convert a +//! `ChalkCanonicalGoal` into a Chalk ucanonical goal. It then calls Chalk, and +//! converts the answer back into rustc solution. + +crate mod db; +crate mod lowering; + +use rustc_data_structures::fx::FxHashMap; + +use rustc_index::vec::IndexVec; + +use rustc_middle::infer::canonical::{CanonicalTyVarKind, CanonicalVarKind}; +use rustc_middle::traits::ChalkRustInterner; +use rustc_middle::ty::query::Providers; +use rustc_middle::ty::subst::GenericArg; +use rustc_middle::ty::{ + self, Bound, BoundVar, ParamTy, Region, RegionKind, Ty, TyCtxt, TypeFoldable, +}; + +use rustc_infer::infer::canonical::{ + Canonical, CanonicalVarValues, Certainty, QueryRegionConstraints, QueryResponse, +}; +use rustc_infer::traits::{self, ChalkCanonicalGoal, ChalkRustDefId as RustDefId}; + +use crate::chalk::db::RustIrDatabase as ChalkRustIrDatabase; +use crate::chalk::lowering::{LowerInto, ParamsSubstitutor}; + +use chalk_solve::Solution; + +crate fn provide(p: &mut Providers<'_>) { + *p = Providers { evaluate_goal, ..*p }; +} + +crate fn evaluate_goal<'tcx>( + tcx: TyCtxt<'tcx>, + obligation: ChalkCanonicalGoal<'tcx>, +) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, traits::query::NoSolution> { + let interner = ChalkRustInterner { tcx }; + + // Chalk doesn't have a notion of `Params`, so instead we use placeholders. + let mut params_substitutor = ParamsSubstitutor::new(tcx); + let obligation = obligation.fold_with(&mut params_substitutor); + let _params: FxHashMap = params_substitutor.params; + let max_universe = obligation.max_universe.index(); + + let _lowered_goal: chalk_ir::UCanonical< + chalk_ir::InEnvironment>>, + > = chalk_ir::UCanonical { + canonical: chalk_ir::Canonical { + binders: chalk_ir::CanonicalVarKinds::from( + &interner, + obligation.variables.iter().map(|v| match v.kind { + CanonicalVarKind::PlaceholderTy(_ty) => unimplemented!(), + CanonicalVarKind::PlaceholderRegion(_ui) => unimplemented!(), + CanonicalVarKind::Ty(ty) => match ty { + CanonicalTyVarKind::General(ui) => { + chalk_ir::ParameterKind::Ty(chalk_ir::UniverseIndex { + counter: ui.index(), + }) + } + CanonicalTyVarKind::Int | CanonicalTyVarKind::Float => { + // FIXME(chalk) - this is actually really important + // These variable kinds put some limits on the + // types that can be substituted (floats or ints). + // While it's unclear exactly the design here, we + // probably want some way to "register" these. + chalk_ir::ParameterKind::Ty(chalk_ir::UniverseIndex::root()) + } + }, + CanonicalVarKind::Region(ui) => { + chalk_ir::ParameterKind::Lifetime(chalk_ir::UniverseIndex { + counter: ui.index(), + }) + } + CanonicalVarKind::Const(_ui) => unimplemented!(), + CanonicalVarKind::PlaceholderConst(_pc) => unimplemented!(), + }), + ), + value: obligation.value.lower_into(&interner), + }, + universes: max_universe + 1, + }; + + let solver_choice = chalk_solve::SolverChoice::SLG { max_size: 32, expected_answers: None }; + let mut solver = solver_choice.into_solver::>(); + + let db = ChalkRustIrDatabase { tcx, interner }; + let solution = solver.solve(&db, &_lowered_goal); + + // Ideally, the code to convert *back* to rustc types would live close to + // the code to convert *from* rustc types. Right now though, we don't + // really need this and so it's really minimal. + // Right now, we also treat a `Unique` solution the same as + // `Ambig(Definite)`. This really isn't right. + let make_solution = |_subst: chalk_ir::Substitution<_>| { + let mut var_values: IndexVec> = IndexVec::new(); + _subst.parameters(&interner).iter().for_each(|p| { + // FIXME(chalk): we should move this elsewhere, since this is + // essentially inverse of lowering a `GenericArg`. + let _data = p.data(&interner); + match _data { + chalk_ir::ParameterKind::Ty(_t) => { + use chalk_ir::TyData; + use rustc_ast::ast; + + let _data = _t.data(&interner); + let kind = match _data { + TyData::Apply(_application_ty) => match _application_ty.name { + chalk_ir::TypeName::Struct(_struct_id) => match _struct_id.0 { + RustDefId::Array => unimplemented!(), + RustDefId::Slice => unimplemented!(), + _ => unimplemented!(), + }, + chalk_ir::TypeName::Scalar(scalar) => match scalar { + chalk_ir::Scalar::Bool => ty::Bool, + chalk_ir::Scalar::Char => ty::Char, + chalk_ir::Scalar::Int(int_ty) => match int_ty { + chalk_ir::IntTy::Isize => ty::Int(ast::IntTy::Isize), + chalk_ir::IntTy::I8 => ty::Int(ast::IntTy::I8), + chalk_ir::IntTy::I16 => ty::Int(ast::IntTy::I16), + chalk_ir::IntTy::I32 => ty::Int(ast::IntTy::I32), + chalk_ir::IntTy::I64 => ty::Int(ast::IntTy::I64), + chalk_ir::IntTy::I128 => ty::Int(ast::IntTy::I128), + }, + chalk_ir::Scalar::Uint(int_ty) => match int_ty { + chalk_ir::UintTy::Usize => ty::Uint(ast::UintTy::Usize), + chalk_ir::UintTy::U8 => ty::Uint(ast::UintTy::U8), + chalk_ir::UintTy::U16 => ty::Uint(ast::UintTy::U16), + chalk_ir::UintTy::U32 => ty::Uint(ast::UintTy::U32), + chalk_ir::UintTy::U64 => ty::Uint(ast::UintTy::U64), + chalk_ir::UintTy::U128 => ty::Uint(ast::UintTy::U128), + }, + chalk_ir::Scalar::Float(float_ty) => match float_ty { + chalk_ir::FloatTy::F32 => ty::Float(ast::FloatTy::F32), + chalk_ir::FloatTy::F64 => ty::Float(ast::FloatTy::F64), + }, + }, + chalk_ir::TypeName::Tuple(_size) => unimplemented!(), + chalk_ir::TypeName::OpaqueType(_ty) => unimplemented!(), + chalk_ir::TypeName::AssociatedType(_assoc_ty) => unimplemented!(), + chalk_ir::TypeName::Error => unimplemented!(), + }, + TyData::Placeholder(_placeholder) => { + unimplemented!(); + } + TyData::Alias(_alias_ty) => unimplemented!(), + TyData::Function(_quantified_ty) => unimplemented!(), + TyData::BoundVar(_bound) => Bound( + ty::DebruijnIndex::from_usize(_bound.debruijn.depth() as usize), + ty::BoundTy { + var: ty::BoundVar::from_usize(_bound.index), + kind: ty::BoundTyKind::Anon, + }, + ), + TyData::InferenceVar(_) => unimplemented!(), + TyData::Dyn(_) => unimplemented!(), + }; + let _ty: Ty<'_> = tcx.mk_ty(kind); + let _arg: GenericArg<'_> = _ty.into(); + var_values.push(_arg); + } + chalk_ir::ParameterKind::Lifetime(_l) => { + let _data = _l.data(&interner); + let _lifetime: Region<'_> = match _data { + chalk_ir::LifetimeData::BoundVar(_var) => { + tcx.mk_region(RegionKind::ReLateBound( + rustc_middle::ty::DebruijnIndex::from_usize( + _var.debruijn.depth() as usize + ), + rustc_middle::ty::BoundRegion::BrAnon(_var.index as u32), + )) + } + chalk_ir::LifetimeData::InferenceVar(_var) => unimplemented!(), + chalk_ir::LifetimeData::Placeholder(_index) => unimplemented!(), + chalk_ir::LifetimeData::Phantom(_, _) => unimplemented!(), + }; + let _arg: GenericArg<'_> = _lifetime.into(); + var_values.push(_arg); + } + } + }); + let sol = Canonical { + max_universe: ty::UniverseIndex::from_usize(0), + variables: obligation.variables.clone(), + value: QueryResponse { + var_values: CanonicalVarValues { var_values }, + region_constraints: QueryRegionConstraints::default(), + certainty: Certainty::Proven, + value: (), + }, + }; + &*tcx.arena.alloc(sol) + }; + solution + .map(|s| match s { + Solution::Unique(_subst) => { + // FIXME(chalk): handle constraints + assert!(_subst.value.constraints.is_empty()); + make_solution(_subst.value.subst) + } + Solution::Ambig(_guidance) => { + match _guidance { + chalk_solve::Guidance::Definite(_subst) => make_solution(_subst.value), + chalk_solve::Guidance::Suggested(_) => unimplemented!(), + chalk_solve::Guidance::Unknown => { + // chalk_fulfill doesn't use the var_values here, so + // let's just ignore that + let sol = Canonical { + max_universe: ty::UniverseIndex::from_usize(0), + variables: obligation.variables.clone(), + value: QueryResponse { + var_values: CanonicalVarValues { var_values: IndexVec::new() } + .make_identity(tcx), + region_constraints: QueryRegionConstraints::default(), + certainty: Certainty::Ambiguous, + value: (), + }, + }; + &*tcx.arena.alloc(sol) + } + } + } + }) + .ok_or(traits::query::NoSolution) +} diff --git a/src/librustc_traits/lib.rs b/src/librustc_traits/lib.rs index e0533b11ecf..f3dfdffda41 100644 --- a/src/librustc_traits/lib.rs +++ b/src/librustc_traits/lib.rs @@ -12,6 +12,7 @@ extern crate log; #[macro_use] extern crate rustc_middle; +mod chalk; mod dropck_outlives; mod evaluate_obligation; mod implied_outlives_bounds; @@ -25,6 +26,7 @@ pub fn provide(p: &mut Providers<'_>) { dropck_outlives::provide(p); evaluate_obligation::provide(p); implied_outlives_bounds::provide(p); + chalk::provide(p); normalize_projection_ty::provide(p); normalize_erasing_regions::provide(p); type_op::provide(p); diff --git a/src/librustc_ty/ty.rs b/src/librustc_ty/ty.rs index c5ead053a7f..6add099e75b 100644 --- a/src/librustc_ty/ty.rs +++ b/src/librustc_ty/ty.rs @@ -262,8 +262,11 @@ fn param_env(tcx: TyCtxt<'_>, def_id: DefId) -> ty::ParamEnv<'_> { // are any errors at that point, so after type checking you can be // sure that this will succeed without errors anyway. - let unnormalized_env = - ty::ParamEnv::new(tcx.intern_predicates(&predicates), traits::Reveal::UserFacing, None); + let unnormalized_env = ty::ParamEnv::new( + tcx.intern_predicates(&predicates), + traits::Reveal::UserFacing, + tcx.sess.opts.debugging_opts.chalk.then_some(def_id), + ); let body_id = def_id .as_local() diff --git a/src/test/ui/chalkify/basic.rs b/src/test/ui/chalkify/basic.rs new file mode 100644 index 00000000000..dbd60fc8bb1 --- /dev/null +++ b/src/test/ui/chalkify/basic.rs @@ -0,0 +1,12 @@ +// check-pass +// compile-flags: -Z chalk + +trait Foo {} + +struct Bar {} + +impl Foo for Bar {} + +fn main() -> () { + let _ = Bar {}; +} diff --git a/src/test/ui/chalkify/builtin-copy-clone.rs b/src/test/ui/chalkify/builtin-copy-clone.rs new file mode 100644 index 00000000000..d403514b553 --- /dev/null +++ b/src/test/ui/chalkify/builtin-copy-clone.rs @@ -0,0 +1,44 @@ +// run-pass +// compile-flags: -Z chalk + +// Test that `Clone` is correctly implemented for builtin types. + +#[derive(Copy, Clone)] +struct S(i32); + +fn test_clone(arg: T) { + let _ = arg.clone(); +} + +fn test_copy(arg: T) { + let _ = arg; + let _ = arg; +} + +fn test_copy_clone(arg: T) { + test_copy(arg); + test_clone(arg); +} + +fn foo() { } + +fn main() { + test_copy_clone(foo); + let f: fn() = foo; + test_copy_clone(f); + // FIXME: add closures when they're considered WF + test_copy_clone([1; 56]); + test_copy_clone((1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)); + test_copy_clone((1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, true, 'a', 1.1)); + test_copy_clone(()); + test_copy_clone(((1, 1), (1, 1, 1), (1.1, 1, 1, 'a'), ())); + + let a = ( + (S(1), S(0)), + ( + (S(0), S(0), S(1)), + S(0) + ) + ); + test_copy_clone(a); +} diff --git a/src/test/ui/chalkify/chalk_initial_program.rs b/src/test/ui/chalkify/chalk_initial_program.rs new file mode 100644 index 00000000000..df25bad622b --- /dev/null +++ b/src/test/ui/chalkify/chalk_initial_program.rs @@ -0,0 +1,16 @@ +// compile-flags: -Z chalk + +trait Foo { } + +impl Foo for i32 { } + +impl Foo for u32 { } + +fn gimme() { } + +// Note: this also tests that `std::process::Termination` is implemented for `()`. +fn main() { + gimme::(); + gimme::(); + gimme::(); //~ERROR the trait bound `f32: Foo` is not satisfied +} diff --git a/src/test/ui/chalkify/chalk_initial_program.stderr b/src/test/ui/chalkify/chalk_initial_program.stderr new file mode 100644 index 00000000000..f2e13a6a469 --- /dev/null +++ b/src/test/ui/chalkify/chalk_initial_program.stderr @@ -0,0 +1,12 @@ +error[E0277]: the trait bound `f32: Foo` is not satisfied + --> $DIR/chalk_initial_program.rs:15:13 + | +LL | fn gimme() { } + | --- required by this bound in `gimme` +... +LL | gimme::(); + | ^^^ the trait `Foo` is not implemented for `f32` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/src/test/ui/chalkify/generic_impls.rs b/src/test/ui/chalkify/generic_impls.rs new file mode 100644 index 00000000000..d70c6f8055d --- /dev/null +++ b/src/test/ui/chalkify/generic_impls.rs @@ -0,0 +1,18 @@ +// compile-flags: -Z chalk + +trait Foo { } + +impl Foo for (T, u32) { } + +fn gimme() { } + +fn foo() { + gimme::<(T, u32)>(); + gimme::<(Option, u32)>(); + gimme::<(Option, f32)>(); //~ ERROR +} + +fn main() { + gimme::<(i32, u32)>(); + gimme::<(i32, f32)>(); //~ ERROR +} diff --git a/src/test/ui/chalkify/generic_impls.stderr b/src/test/ui/chalkify/generic_impls.stderr new file mode 100644 index 00000000000..4ac57a2f13f --- /dev/null +++ b/src/test/ui/chalkify/generic_impls.stderr @@ -0,0 +1,27 @@ +error[E0277]: the trait bound `(std::option::Option, f32): Foo` is not satisfied + --> $DIR/generic_impls.rs:12:13 + | +LL | fn gimme() { } + | --- required by this bound in `gimme` +... +LL | gimme::<(Option, f32)>(); + | ^^^^^^^^^^^^^^^^ the trait `Foo` is not implemented for `(std::option::Option, f32)` + | + = help: the following implementations were found: + <(T, u32) as Foo> + +error[E0277]: the trait bound `(i32, f32): Foo` is not satisfied + --> $DIR/generic_impls.rs:17:13 + | +LL | fn gimme() { } + | --- required by this bound in `gimme` +... +LL | gimme::<(i32, f32)>(); + | ^^^^^^^^^^ the trait `Foo` is not implemented for `(i32, f32)` + | + = help: the following implementations were found: + <(T, u32) as Foo> + +error: aborting due to 2 previous errors + +For more information about this error, try `rustc --explain E0277`. diff --git a/src/test/ui/chalkify/impl_wf.rs b/src/test/ui/chalkify/impl_wf.rs new file mode 100644 index 00000000000..8aa87642292 --- /dev/null +++ b/src/test/ui/chalkify/impl_wf.rs @@ -0,0 +1,47 @@ +// compile-flags: -Z chalk + +trait Foo: Sized { } + +trait Bar { + type Item: Foo; +} + +impl Foo for i32 { } + +// FIXME(chalk): blocked on better handling of builtin traits for non-struct +// application types (or a workaround) +/* +impl Foo for str { } +//^ ERROR the size for values of type `str` cannot be known at compilation time +*/ + +// Implicit `T: Sized` bound. +impl Foo for Option { } + +impl Bar for () { + type Item = i32; +} + +impl Bar for Option { + type Item = Option; +} + +// FIXME(chalk): the ordering of these two errors differs between CI and local +// We need to figure out why its non-deterministic +/* +impl Bar for f32 { +//^ ERROR the trait bound `f32: Foo` is not satisfied + type Item = f32; + //^ ERROR the trait bound `f32: Foo` is not satisfied +} +*/ + +trait Baz where U: Foo { } + +impl Baz for i32 { } + +impl Baz for f32 { } +//~^ ERROR the trait bound `f32: Foo` is not satisfied + +fn main() { +} diff --git a/src/test/ui/chalkify/impl_wf.stderr b/src/test/ui/chalkify/impl_wf.stderr new file mode 100644 index 00000000000..befd688741c --- /dev/null +++ b/src/test/ui/chalkify/impl_wf.stderr @@ -0,0 +1,12 @@ +error[E0277]: the trait bound `f32: Foo` is not satisfied + --> $DIR/impl_wf.rs:43:6 + | +LL | trait Baz where U: Foo { } + | --- required by this bound in `Baz` +... +LL | impl Baz for f32 { } + | ^^^^^^^^ the trait `Foo` is not implemented for `f32` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/src/test/ui/chalkify/inherent_impl.rs b/src/test/ui/chalkify/inherent_impl.rs new file mode 100644 index 00000000000..44e120c1eeb --- /dev/null +++ b/src/test/ui/chalkify/inherent_impl.rs @@ -0,0 +1,42 @@ +// run-pass +// compile-flags: -Z chalk + +trait Foo { } + +impl Foo for i32 { } + +struct S { + x: T, +} + +fn only_foo(_x: &T) { } + +impl S { + // Test that we have the correct environment inside an inherent method. + fn dummy_foo(&self) { + only_foo(&self.x) + } +} + +trait Bar { } +impl Bar for u32 { } + +fn only_bar() { } + +impl S { + // Test that the environment of `dummy_bar` adds up with the environment + // of the inherent impl. + fn dummy_bar(&self) { + only_foo(&self.x); + only_bar::(); + } +} + +fn main() { + let s = S { + x: 5, + }; + + s.dummy_foo(); + s.dummy_bar::(); +} diff --git a/src/test/ui/chalkify/inherent_impl_min.rs b/src/test/ui/chalkify/inherent_impl_min.rs new file mode 100644 index 00000000000..774c46e401c --- /dev/null +++ b/src/test/ui/chalkify/inherent_impl_min.rs @@ -0,0 +1,27 @@ +// run-pass +// compile-flags: -Z chalk + +trait Foo { } + +impl Foo for i32 { } + +struct S { + x: T, +} + +fn only_foo(_x: &T) { } + +impl S { + // Test that we have the correct environment inside an inherent method. + fn dummy_foo(&self) { + only_foo(&self.x) + } +} + +fn main() { + let s = S { + x: 5, + }; + + s.dummy_foo(); +} diff --git a/src/test/ui/chalkify/lower_env1.rs b/src/test/ui/chalkify/lower_env1.rs new file mode 100644 index 00000000000..e3c75695921 --- /dev/null +++ b/src/test/ui/chalkify/lower_env1.rs @@ -0,0 +1,14 @@ +// check-pass +// compile-flags: -Z chalk + +#![allow(dead_code)] + +trait Foo { } + +trait Bar where Self: Foo { } + +fn bar() { +} + +fn main() { +} diff --git a/src/test/ui/chalkify/lower_env2.rs b/src/test/ui/chalkify/lower_env2.rs new file mode 100644 index 00000000000..b5432ce0e30 --- /dev/null +++ b/src/test/ui/chalkify/lower_env2.rs @@ -0,0 +1,16 @@ +// check-pass +// compile-flags: -Z chalk + +#![allow(dead_code)] + +trait Foo { } + +struct S<'a, T: ?Sized> where T: Foo { + data: &'a T, +} + +fn bar(_x: S<'_, T>) { // note that we have an implicit `T: Sized` bound +} + +fn main() { +} diff --git a/src/test/ui/chalkify/lower_env3.rs b/src/test/ui/chalkify/lower_env3.rs new file mode 100644 index 00000000000..673f08d78ab --- /dev/null +++ b/src/test/ui/chalkify/lower_env3.rs @@ -0,0 +1,16 @@ +// check-pass +// compile-flags: -Z chalk + +#![allow(dead_code)] + +trait Foo { + fn foo(&self); +} + +impl Foo for T where T: Clone { + fn foo(&self) { + } +} + +fn main() { +} diff --git a/src/test/ui/chalkify/lower_impl.rs b/src/test/ui/chalkify/lower_impl.rs new file mode 100644 index 00000000000..f586cf08391 --- /dev/null +++ b/src/test/ui/chalkify/lower_impl.rs @@ -0,0 +1,17 @@ +// check-pass +// compile-flags: -Z chalk + +trait Foo { } + +impl Foo for T where T: Iterator { } + +trait Bar { + type Assoc; +} + +impl Bar for T where T: Iterator { + type Assoc = Vec; +} + +fn main() { +} diff --git a/src/test/ui/chalkify/lower_struct.rs b/src/test/ui/chalkify/lower_struct.rs new file mode 100644 index 00000000000..94a0716d383 --- /dev/null +++ b/src/test/ui/chalkify/lower_struct.rs @@ -0,0 +1,8 @@ +// check-pass +// compile-flags: -Z chalk + +struct Foo<'a, T> where Box: Clone { + _x: std::marker::PhantomData<&'a T>, +} + +fn main() { } diff --git a/src/test/ui/chalkify/lower_trait.rs b/src/test/ui/chalkify/lower_trait.rs new file mode 100644 index 00000000000..d8f6180ceb3 --- /dev/null +++ b/src/test/ui/chalkify/lower_trait.rs @@ -0,0 +1,11 @@ +// check-pass +// compile-flags: -Z chalk + +trait Bar { } + +trait Foo { + type Assoc: Bar + ?Sized; +} + +fn main() { +} diff --git a/src/test/ui/chalkify/lower_trait_higher_rank.rs b/src/test/ui/chalkify/lower_trait_higher_rank.rs new file mode 100644 index 00000000000..a48979491a1 --- /dev/null +++ b/src/test/ui/chalkify/lower_trait_higher_rank.rs @@ -0,0 +1,9 @@ +// check-pass +// compile-flags: -Z chalk + +trait Foo where for<'a> F: Fn(&'a (u8, u16)) -> &'a u8 +{ +} + +fn main() { +} diff --git a/src/test/ui/chalkify/lower_trait_where_clause.rs b/src/test/ui/chalkify/lower_trait_where_clause.rs new file mode 100644 index 00000000000..19cff8db7cb --- /dev/null +++ b/src/test/ui/chalkify/lower_trait_where_clause.rs @@ -0,0 +1,16 @@ +// check-pass +// compile-flags: -Z chalk + +use std::borrow::Borrow; + +trait Foo<'a, 'b, T, U> +where + T: Borrow + ?Sized, + U: ?Sized + 'b, + 'a: 'b, + Box:, // NOTE(#53696) this checks an empty list of bounds. +{ +} + +fn main() { +} diff --git a/src/test/ui/chalkify/println.rs b/src/test/ui/chalkify/println.rs new file mode 100644 index 00000000000..cf36aef8afa --- /dev/null +++ b/src/test/ui/chalkify/println.rs @@ -0,0 +1,7 @@ +// check-pass +// compile-flags: -Z chalk + +fn main() { + // FIXME(chalk): Require `RegionOutlives`/`TypeOutlives`/`Subtype` support + //println!("hello"); +} diff --git a/src/test/ui/chalkify/projection.rs b/src/test/ui/chalkify/projection.rs new file mode 100644 index 00000000000..d6a8dd7a4a2 --- /dev/null +++ b/src/test/ui/chalkify/projection.rs @@ -0,0 +1,25 @@ +// run-pass +// compile-flags: -Z chalk + +trait Foo { } + +trait Bar { + type Item: Foo; +} + +impl Foo for i32 { } +impl Bar for i32 { + type Item = i32; +} + +fn only_foo() { } + +fn only_bar() { + // `T` implements `Bar` hence `::Item` must also implement `Bar` + only_foo::() +} + +fn main() { + only_bar::(); + only_foo::<::Item>(); +} diff --git a/src/test/ui/chalkify/recursive_where_clause_on_type.rs b/src/test/ui/chalkify/recursive_where_clause_on_type.rs new file mode 100644 index 00000000000..6ee13f5e7a1 --- /dev/null +++ b/src/test/ui/chalkify/recursive_where_clause_on_type.rs @@ -0,0 +1,35 @@ +// FIXME(chalk): should fail, see comments +// check-pass +// compile-flags: -Z chalk + +#![feature(trivial_bounds)] + +trait Bar { + fn foo(); +} +trait Foo: Bar { } + +struct S where S: Foo; +//~^ WARN Trait bound S: Foo does not depend on any type or lifetime parameters + +impl Foo for S { +} + +fn bar() { + T::foo(); +} + +fn foo() { + bar::() +} + +fn main() { + // For some reason, the error is duplicated... + + // FIXME(chalk): this order of this duplicate error seems non-determistic + // and causes test to fail + /* + foo::() // ERROR the type `S` is not well-formed (chalk) + //^ ERROR the type `S` is not well-formed (chalk) + */ +} diff --git a/src/test/ui/chalkify/recursive_where_clause_on_type.stderr b/src/test/ui/chalkify/recursive_where_clause_on_type.stderr new file mode 100644 index 00000000000..a5b7ef7fdb2 --- /dev/null +++ b/src/test/ui/chalkify/recursive_where_clause_on_type.stderr @@ -0,0 +1,10 @@ +warning: Trait bound S: Foo does not depend on any type or lifetime parameters + --> $DIR/recursive_where_clause_on_type.rs:12:19 + | +LL | struct S where S: Foo; + | ^^^ + | + = note: `#[warn(trivial_bounds)]` on by default + +warning: 1 warning emitted + diff --git a/src/test/ui/chalkify/super_trait.rs b/src/test/ui/chalkify/super_trait.rs new file mode 100644 index 00000000000..eeff9fd9b80 --- /dev/null +++ b/src/test/ui/chalkify/super_trait.rs @@ -0,0 +1,19 @@ +// run-pass +// compile-flags: -Z chalk + +trait Foo { } +trait Bar: Foo { } + +impl Foo for i32 { } +impl Bar for i32 { } + +fn only_foo() { } + +fn only_bar() { + // `T` implements `Bar` hence `T` must also implement `Foo` + only_foo::() +} + +fn main() { + only_bar::() +} diff --git a/src/test/ui/chalkify/trait_implied_bound.rs b/src/test/ui/chalkify/trait_implied_bound.rs new file mode 100644 index 00000000000..8a2e1cf5990 --- /dev/null +++ b/src/test/ui/chalkify/trait_implied_bound.rs @@ -0,0 +1,18 @@ +// run-pass +// compile-flags: -Z chalk + +trait Foo { } +trait Bar where U: Foo { } + +impl Foo for i32 { } +impl Bar for i32 { } + +fn only_foo() { } + +fn only_bar>() { + only_foo::() +} + +fn main() { + only_bar::() +} diff --git a/src/test/ui/chalkify/type_implied_bound.rs b/src/test/ui/chalkify/type_implied_bound.rs new file mode 100644 index 00000000000..8673f5319bd --- /dev/null +++ b/src/test/ui/chalkify/type_implied_bound.rs @@ -0,0 +1,29 @@ +// run-pass +// compile-flags: -Z chalk + +trait Eq { } +trait Hash: Eq { } + +impl Eq for i32 { } +impl Hash for i32 { } + +struct Set { + _x: T, +} + +fn only_eq() { } + +fn take_a_set(_: &Set) { + // `Set` is an input type of `take_a_set`, hence we know that + // `T` must implement `Hash`, and we know in turn that `T` must + // implement `Eq`. + only_eq::() +} + +fn main() { + let set = Set { + _x: 5, + }; + + take_a_set(&set); +} diff --git a/src/test/ui/chalkify/type_inference.rs b/src/test/ui/chalkify/type_inference.rs new file mode 100644 index 00000000000..5175c5d062a --- /dev/null +++ b/src/test/ui/chalkify/type_inference.rs @@ -0,0 +1,28 @@ +// compile-flags: -Z chalk + +trait Foo { } +impl Foo for i32 { } + +trait Bar { } +impl Bar for i32 { } +impl Bar for u32 { } + +fn only_foo(_x: T) { } + +fn only_bar(_x: T) { } + +fn main() { + let x = 5.0; + + // The only type which implements `Foo` is `i32`, so the chalk trait solver + // is expecting a variable of type `i32`. This behavior differs from the + // old-style trait solver. I guess this will change, that's why I'm + // adding that test. + // FIXME(chalk): partially blocked on float/int special casing + only_foo(x); //~ ERROR the trait bound `f64: Foo` is not satisfied + + // Here we have two solutions so we get back the behavior of the old-style + // trait solver. + // FIXME(chalk): blocked on float/int special casing + //only_bar(x); // ERROR the trait bound `{float}: Bar` is not satisfied +} diff --git a/src/test/ui/chalkify/type_inference.stderr b/src/test/ui/chalkify/type_inference.stderr new file mode 100644 index 00000000000..ee9e67c6c78 --- /dev/null +++ b/src/test/ui/chalkify/type_inference.stderr @@ -0,0 +1,12 @@ +error[E0277]: the trait bound `f64: Foo` is not satisfied + --> $DIR/type_inference.rs:22:5 + | +LL | fn only_foo(_x: T) { } + | --- required by this bound in `only_foo` +... +LL | only_foo(x); + | ^^^^^^^^ the trait `Foo` is not implemented for `f64` + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0277`. diff --git a/src/test/ui/chalkify/type_wf.rs b/src/test/ui/chalkify/type_wf.rs new file mode 100644 index 00000000000..396baf814a0 --- /dev/null +++ b/src/test/ui/chalkify/type_wf.rs @@ -0,0 +1,32 @@ +// FIXME(chalk): should have an error, see below +// check-pass +// compile-flags: -Z chalk + +trait Foo { } + +struct S { + x: T, +} + +impl Foo for i32 { } +impl Foo for Option { } + +fn main() { + let s = S { + x: 5, + }; + + // FIXME(chalk): blocked on float/int special handling. Needs to know that {float}: !i32 + /* + let s = S { // ERROR the trait bound `{float}: Foo` is not satisfied + x: 5.0, + }; + */ + + // FIXME(chalk): blocked on float/int special handling. Needs to know that {float}: Sized + /* + let s = S { + x: Some(5.0), + }; + */ +} diff --git a/src/tools/tidy/src/deps.rs b/src/tools/tidy/src/deps.rs index 1423f1db385..d3c7b7a068b 100644 --- a/src/tools/tidy/src/deps.rs +++ b/src/tools/tidy/src/deps.rs @@ -80,6 +80,10 @@ const WHITELIST: &[&str] = &[ "c2-chacha", "cc", "cfg-if", + "chalk-derive", + "chalk-engine", + "chalk-ir", + "chalk-macros", "cloudabi", "cmake", "compiler_builtins",