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