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