1 //! Trait solving using Chalk.
5 use chalk_ir::GoalData;
6 use chalk_recursive::Cache;
7 use chalk_solve::{logging_db::LoggingRustIrDatabase, Solver};
10 use hir_def::{lang_item::LangItemTarget, TraitId};
11 use stdx::panic_context;
14 db::HirDatabase, AliasEq, AliasTy, Canonical, DomainGoal, Goal, Guidance, InEnvironment,
15 Interner, Solution, TraitRefExt, Ty, TyKind, WhereClause,
18 /// This controls how much 'time' we give the Chalk solver before giving up.
19 const CHALK_SOLVER_FUEL: i32 = 100;
21 #[derive(Debug, Copy, Clone)]
22 pub(crate) struct ChalkContext<'a> {
23 pub(crate) db: &'a dyn HirDatabase,
24 pub(crate) krate: CrateId,
27 fn create_chalk_solver() -> chalk_recursive::RecursiveSolver<Interner> {
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()))
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 {
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>,
48 impl TraitEnvironment {
49 pub fn empty(krate: CrateId) -> Self {
52 traits_from_clauses: Vec::new(),
53 env: chalk_ir::Environment::new(&Interner),
57 pub(crate) fn traits_in_scope_from_clauses<'a>(
60 ) -> impl Iterator<Item = TraitId> + 'a {
61 self.traits_from_clauses.iter().filter_map(move |(self_ty, trait_id)| {
71 /// Solve a trait goal using Chalk.
72 pub(crate) fn trait_solve_query(
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()
81 GoalData::DomainGoal(DomainGoal::Holds(WhereClause::AliasEq(_))) => "alias_eq".to_string(),
82 _ => "??".to_string(),
84 tracing::info!("trait_solve_query({:?})", goal.value.goal);
86 if let GoalData::DomainGoal(DomainGoal::Holds(WhereClause::AliasEq(AliasEq {
87 alias: AliasTy::Projection(projection_ty),
89 }))) = &goal.value.goal.data(&Interner)
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 // 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)
104 db: &dyn HirDatabase,
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();
112 let fuel = std::cell::Cell::new(CHALK_SOLVER_FUEL);
114 let should_continue = || {
115 db.unwind_if_cancelled();
116 let remaining = fuel.get();
117 fuel.set(remaining - 1);
119 tracing::debug!("fuel exhausted");
125 let _ctx = if is_chalk_debug() || is_chalk_print() {
126 Some(panic_context::enter(format!("solving {:?}", goal)))
130 let solution = if is_chalk_print() {
132 LoggingRustIrDatabaseLoggingOnDrop(LoggingRustIrDatabase::new(context));
133 solver.solve_limited(&logging_db.0, goal, &should_continue)
135 solver.solve_limited(&context, goal, &should_continue)
138 tracing::debug!("solve({:?}) => {:?}", goal, solution);
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)
152 struct LoggingRustIrDatabaseLoggingOnDrop<'a>(LoggingRustIrDatabase<Interner, ChalkContext<'a>>);
154 impl<'a> Drop for LoggingRustIrDatabaseLoggingOnDrop<'a> {
156 eprintln!("chalk program:\n{}", self.0);
160 fn is_chalk_debug() -> bool {
161 std::env::var("CHALK_DEBUG").is_ok()
164 fn is_chalk_print() -> bool {
165 std::env::var("CHALK_PRINT").is_ok()
168 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
176 fn lang_item_name(self) -> &'static str {
178 FnTrait::FnOnce => "fn_once",
179 FnTrait::FnMut => "fn_mut",
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())?;
187 LangItemTarget::TraitId(t) => Some(t),