1 //! Trait solving using Chalk.
5 use chalk_ir::cast::Cast;
6 use chalk_solve::{logging_db::LoggingRustIrDatabase, Solver};
9 use hir_def::{lang_item::LangItemTarget, TraitId};
10 use stdx::panic_context;
13 db::HirDatabase, AliasEq, AliasTy, Canonical, DomainGoal, Guidance, HirDisplay, InEnvironment,
14 Interner, Solution, TraitRefExt, Ty, TyKind, WhereClause,
17 /// This controls how much 'time' we give the Chalk solver before giving up.
18 const CHALK_SOLVER_FUEL: i32 = 100;
20 #[derive(Debug, Copy, Clone)]
21 pub(crate) struct ChalkContext<'a> {
22 pub(crate) db: &'a dyn HirDatabase,
23 pub(crate) krate: CrateId,
26 fn create_chalk_solver() -> chalk_recursive::RecursiveSolver<Interner> {
28 var("CHALK_OVERFLOW_DEPTH").ok().and_then(|s| s.parse().ok()).unwrap_or(100);
29 let caching_enabled = true;
30 let max_size = var("CHALK_SOLVER_MAX_SIZE").ok().and_then(|s| s.parse().ok()).unwrap_or(30);
31 chalk_recursive::RecursiveSolver::new(overflow_depth, max_size, caching_enabled)
34 /// A set of clauses that we assume to be true. E.g. if we are inside this function:
36 /// fn foo<T: Default>(t: T) {}
38 /// we assume that `T: Default`.
39 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
40 pub struct TraitEnvironment {
41 // When we're using Chalk's Ty we can make this a BTreeMap since it's Ord,
42 // but for now it's too annoying...
43 pub(crate) traits_from_clauses: Vec<(Ty, TraitId)>,
44 pub env: chalk_ir::Environment<Interner>,
47 impl TraitEnvironment {
48 pub(crate) fn traits_in_scope_from_clauses<'a>(
51 ) -> impl Iterator<Item = TraitId> + 'a {
52 self.traits_from_clauses.iter().filter_map(move |(self_ty, trait_id)| {
62 impl Default for TraitEnvironment {
63 fn default() -> Self {
65 traits_from_clauses: Vec::new(),
66 env: chalk_ir::Environment::new(&Interner),
71 /// Solve a trait goal using Chalk.
72 pub(crate) fn trait_solve_query(
75 goal: Canonical<InEnvironment<DomainGoal>>,
76 ) -> Option<Solution> {
77 let _p = profile::span("trait_solve_query").detail(|| match &goal.value.goal {
78 DomainGoal::Holds(WhereClause::Implemented(it)) => {
79 db.trait_data(it.hir_trait_id()).name.to_string()
81 DomainGoal::Holds(WhereClause::AliasEq(_)) => "alias_eq".to_string(),
82 _ => "??".to_string(),
84 log::info!("trait_solve_query({})", goal.value.goal.display(db));
86 if let DomainGoal::Holds(WhereClause::AliasEq(AliasEq {
87 alias: AliasTy::Projection(projection_ty),
89 })) = &goal.value.goal
91 if let TyKind::BoundVar(_) = projection_ty.self_type_parameter(&Interner).kind(&Interner) {
92 // Hack: don't ask Chalk to normalize with an unknown self type, it'll say that's impossible
93 return Some(Solution::Ambig(Guidance::Unknown));
97 let canonical = goal.cast(&Interner);
99 // We currently don't deal with universes (I think / hope they're not yet
100 // relevant for our use cases?)
101 let u_canonical = chalk_ir::UCanonical { canonical, universes: 1 };
102 solve(db, krate, &u_canonical)
106 db: &dyn HirDatabase,
108 goal: &chalk_ir::UCanonical<chalk_ir::InEnvironment<chalk_ir::Goal<Interner>>>,
109 ) -> Option<chalk_solve::Solution<Interner>> {
110 let context = ChalkContext { db, krate };
111 log::debug!("solve goal: {:?}", goal);
112 let mut solver = create_chalk_solver();
114 let fuel = std::cell::Cell::new(CHALK_SOLVER_FUEL);
116 let should_continue = || {
117 context.db.check_canceled();
118 let remaining = fuel.get();
119 fuel.set(remaining - 1);
121 log::debug!("fuel exhausted");
127 let _ctx = if is_chalk_debug() || is_chalk_print() {
128 Some(panic_context::enter(format!("solving {:?}", goal)))
132 let solution = if is_chalk_print() {
134 LoggingRustIrDatabaseLoggingOnDrop(LoggingRustIrDatabase::new(context));
135 let solution = solver.solve_limited(&logging_db.0, goal, &should_continue);
138 solver.solve_limited(&context, goal, &should_continue)
141 log::debug!("solve({:?}) => {:?}", goal, solution);
146 // don't set the TLS for Chalk unless Chalk debugging is active, to make
147 // extra sure we only use it for debugging
149 if is_chalk_debug() { crate::tls::set_current_program(db, solve) } else { solve() };
154 struct LoggingRustIrDatabaseLoggingOnDrop<'a>(LoggingRustIrDatabase<Interner, ChalkContext<'a>>);
156 impl<'a> Drop for LoggingRustIrDatabaseLoggingOnDrop<'a> {
158 eprintln!("chalk program:\n{}", self.0);
162 fn is_chalk_debug() -> bool {
163 std::env::var("CHALK_DEBUG").is_ok()
166 fn is_chalk_print() -> bool {
167 std::env::var("CHALK_PRINT").is_ok()
170 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
178 fn lang_item_name(self) -> &'static str {
180 FnTrait::FnOnce => "fn_once",
181 FnTrait::FnMut => "fn_mut",
186 pub fn get_id(&self, db: &dyn HirDatabase, krate: CrateId) -> Option<TraitId> {
187 let target = db.lang_item(krate, self.lang_item_name().into())?;
189 LangItemTarget::TraitId(t) => Some(t),