]> git.lizzy.rs Git - rust.git/blob - crates/hir-ty/src/traits.rs
fix: handle lifetime variables in projection normalization
[rust.git] / crates / hir-ty / src / traits.rs
1 //! Trait solving using Chalk.
2
3 use std::{env::var, sync::Arc};
4
5 use chalk_ir::GoalData;
6 use chalk_recursive::Cache;
7 use chalk_solve::{logging_db::LoggingRustIrDatabase, Solver};
8
9 use base_db::CrateId;
10 use hir_def::{lang_item::LangItemTarget, TraitId};
11 use stdx::panic_context;
12 use syntax::SmolStr;
13
14 use crate::{
15     db::HirDatabase, infer::unify::InferenceTable, AliasEq, AliasTy, Canonical, DomainGoal, Goal,
16     Guidance, InEnvironment, Interner, ProjectionTy, Solution, TraitRefExt, Ty, TyKind,
17     WhereClause,
18 };
19
20 /// This controls how much 'time' we give the Chalk solver before giving up.
21 const CHALK_SOLVER_FUEL: i32 = 100;
22
23 #[derive(Debug, Copy, Clone)]
24 pub(crate) struct ChalkContext<'a> {
25     pub(crate) db: &'a dyn HirDatabase,
26     pub(crate) krate: CrateId,
27 }
28
29 fn create_chalk_solver() -> chalk_recursive::RecursiveSolver<Interner> {
30     let overflow_depth =
31         var("CHALK_OVERFLOW_DEPTH").ok().and_then(|s| s.parse().ok()).unwrap_or(500);
32     let max_size = var("CHALK_SOLVER_MAX_SIZE").ok().and_then(|s| s.parse().ok()).unwrap_or(150);
33     chalk_recursive::RecursiveSolver::new(overflow_depth, max_size, Some(Cache::new()))
34 }
35
36 /// A set of clauses that we assume to be true. E.g. if we are inside this function:
37 /// ```rust
38 /// fn foo<T: Default>(t: T) {}
39 /// ```
40 /// we assume that `T: Default`.
41 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
42 pub struct TraitEnvironment {
43     pub krate: CrateId,
44     // FIXME make this a BTreeMap
45     pub(crate) traits_from_clauses: Vec<(Ty, TraitId)>,
46     pub env: chalk_ir::Environment<Interner>,
47 }
48
49 impl TraitEnvironment {
50     pub fn empty(krate: CrateId) -> Self {
51         TraitEnvironment {
52             krate,
53             traits_from_clauses: Vec::new(),
54             env: chalk_ir::Environment::new(Interner),
55         }
56     }
57
58     pub fn traits_in_scope_from_clauses<'a>(
59         &'a self,
60         ty: Ty,
61     ) -> impl Iterator<Item = TraitId> + 'a {
62         self.traits_from_clauses
63             .iter()
64             .filter_map(move |(self_ty, trait_id)| (*self_ty == ty).then(|| *trait_id))
65     }
66 }
67
68 pub(crate) fn normalize_projection_query(
69     db: &dyn HirDatabase,
70     projection: ProjectionTy,
71     env: Arc<TraitEnvironment>,
72 ) -> Option<Ty> {
73     let mut table = InferenceTable::new(db, env.clone());
74     let ty = table.normalize_projection_ty(projection);
75     Some(table.resolve_completely(ty))
76 }
77
78 /// Solve a trait goal using Chalk.
79 pub(crate) fn trait_solve_query(
80     db: &dyn HirDatabase,
81     krate: CrateId,
82     goal: Canonical<InEnvironment<Goal>>,
83 ) -> Option<Solution> {
84     let _p = profile::span("trait_solve_query").detail(|| match &goal.value.goal.data(Interner) {
85         GoalData::DomainGoal(DomainGoal::Holds(WhereClause::Implemented(it))) => {
86             db.trait_data(it.hir_trait_id()).name.to_string()
87         }
88         GoalData::DomainGoal(DomainGoal::Holds(WhereClause::AliasEq(_))) => "alias_eq".to_string(),
89         _ => "??".to_string(),
90     });
91     tracing::info!("trait_solve_query({:?})", goal.value.goal);
92
93     if let GoalData::DomainGoal(DomainGoal::Holds(WhereClause::AliasEq(AliasEq {
94         alias: AliasTy::Projection(projection_ty),
95         ..
96     }))) = &goal.value.goal.data(Interner)
97     {
98         if let TyKind::BoundVar(_) = projection_ty.self_type_parameter(Interner).kind(Interner) {
99             // Hack: don't ask Chalk to normalize with an unknown self type, it'll say that's impossible
100             return Some(Solution::Ambig(Guidance::Unknown));
101         }
102     }
103
104     // We currently don't deal with universes (I think / hope they're not yet
105     // relevant for our use cases?)
106     let u_canonical = chalk_ir::UCanonical { canonical: goal, universes: 1 };
107     solve(db, krate, &u_canonical)
108 }
109
110 fn solve(
111     db: &dyn HirDatabase,
112     krate: CrateId,
113     goal: &chalk_ir::UCanonical<chalk_ir::InEnvironment<chalk_ir::Goal<Interner>>>,
114 ) -> Option<chalk_solve::Solution<Interner>> {
115     let context = ChalkContext { db, krate };
116     tracing::debug!("solve goal: {:?}", goal);
117     let mut solver = create_chalk_solver();
118
119     let fuel = std::cell::Cell::new(CHALK_SOLVER_FUEL);
120
121     let should_continue = || {
122         db.unwind_if_cancelled();
123         let remaining = fuel.get();
124         fuel.set(remaining - 1);
125         if remaining == 0 {
126             tracing::debug!("fuel exhausted");
127         }
128         remaining > 0
129     };
130
131     let mut solve = || {
132         let _ctx = if is_chalk_debug() || is_chalk_print() {
133             Some(panic_context::enter(format!("solving {:?}", goal)))
134         } else {
135             None
136         };
137         let solution = if is_chalk_print() {
138             let logging_db =
139                 LoggingRustIrDatabaseLoggingOnDrop(LoggingRustIrDatabase::new(context));
140             solver.solve_limited(&logging_db.0, goal, &should_continue)
141         } else {
142             solver.solve_limited(&context, goal, &should_continue)
143         };
144
145         tracing::debug!("solve({:?}) => {:?}", goal, solution);
146
147         solution
148     };
149
150     // don't set the TLS for Chalk unless Chalk debugging is active, to make
151     // extra sure we only use it for debugging
152     if is_chalk_debug() {
153         crate::tls::set_current_program(db, solve)
154     } else {
155         solve()
156     }
157 }
158
159 struct LoggingRustIrDatabaseLoggingOnDrop<'a>(LoggingRustIrDatabase<Interner, ChalkContext<'a>>);
160
161 impl<'a> Drop for LoggingRustIrDatabaseLoggingOnDrop<'a> {
162     fn drop(&mut self) {
163         eprintln!("chalk program:\n{}", self.0);
164     }
165 }
166
167 fn is_chalk_debug() -> bool {
168     std::env::var("CHALK_DEBUG").is_ok()
169 }
170
171 fn is_chalk_print() -> bool {
172     std::env::var("CHALK_PRINT").is_ok()
173 }
174
175 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
176 pub enum FnTrait {
177     FnOnce,
178     FnMut,
179     Fn,
180 }
181
182 impl FnTrait {
183     const fn lang_item_name(self) -> &'static str {
184         match self {
185             FnTrait::FnOnce => "fn_once",
186             FnTrait::FnMut => "fn_mut",
187             FnTrait::Fn => "fn",
188         }
189     }
190
191     pub fn get_id(&self, db: &dyn HirDatabase, krate: CrateId) -> Option<TraitId> {
192         let target = db.lang_item(krate, SmolStr::new_inline(self.lang_item_name()))?;
193         match target {
194             LangItemTarget::TraitId(t) => Some(t),
195             _ => None,
196         }
197     }
198 }