1use hir_def::type_ref::Mutability;
4use hir_ide::db::HirDatabase;
5use itertools::Itertools;
6use rustc_hash::{FxHashMap, FxHashSet};
7
8use crate::{ModuleDef, ScopeDef, Semantics, SemanticsScope, Type};
9
10mod expr;
11pub use expr::Expr;
12
13mod tactics;
14
15#[derive(Debug, Hash, PartialEq, Eq)]
17enum NewTypesKey {
18 ImplMethod,
19 StructProjection,
20}
21
22#[derive(Debug)]
25enum AlternativeExprs<'db> {
26 Few(FxHashSet<Expr<'db>>),
28 Many,
30}
31
32impl<'db> AlternativeExprs<'db> {
33 fn new(threshold: usize, exprs: impl Iterator<Item = Expr<'db>>) -> AlternativeExprs<'db> {
39 let mut it = AlternativeExprs::Few(Default::default());
40 it.extend_with_threshold(threshold, exprs);
41 it
42 }
43
44 fn exprs(&self, ty: &Type<'db>) -> Vec<Expr<'db>> {
49 match self {
50 AlternativeExprs::Few(exprs) => exprs.iter().cloned().collect(),
51 AlternativeExprs::Many => vec![Expr::Many(ty.clone())],
52 }
53 }
54
55 fn extend_with_threshold(&mut self, threshold: usize, exprs: impl Iterator<Item = Expr<'db>>) {
61 match self {
62 AlternativeExprs::Few(tts) => {
63 for it in exprs {
64 if tts.len() > threshold {
65 *self = AlternativeExprs::Many;
66 break;
67 }
68
69 tts.insert(it);
70 }
71 }
72 AlternativeExprs::Many => (),
73 }
74 }
75
76 fn is_many(&self) -> bool {
77 matches!(self, AlternativeExprs::Many)
78 }
79}
80
81#[derive(Debug)]
91struct LookupTable<'db> {
92 db: &'db dyn HirDatabase,
93 data: FxHashMap<Type<'db>, AlternativeExprs<'db>>,
95 new_types: FxHashMap<NewTypesKey, Vec<Type<'db>>>,
97 types_wishlist: FxHashSet<Type<'db>>,
99 many_threshold: usize,
101}
102
103impl<'db> LookupTable<'db> {
104 fn new(db: &'db dyn HirDatabase, many_threshold: usize, goal: Type<'db>) -> Self {
106 Self {
107 db,
108 many_threshold,
109 data: Default::default(),
110 types_wishlist: FxHashSet::from_iter([goal]),
111 new_types: FxHashMap::from_iter([
112 (NewTypesKey::ImplMethod, Vec::new()),
113 (NewTypesKey::StructProjection, Vec::new()),
114 ]),
115 }
116 }
117
118 fn find(&mut self, ty: &Type<'db>) -> Option<Vec<Expr<'db>>> {
120 let res = self
121 .data
122 .get_key_value(ty)
123 .or_else(|| self.data.iter().find(|(t, _)| t.could_unify_with_deeply(self.db, ty)))
124 .map(|(t, tts)| tts.exprs(t));
125
126 if res.is_none() {
127 self.types_wishlist.insert(ty.clone());
128 }
129
130 if let Some(res) = &res
132 && res.len() > self.many_threshold
133 {
134 return Some(vec![Expr::Many(ty.clone())]);
135 }
136
137 res
138 }
139
140 fn find_autoref(&mut self, db: &'db dyn HirDatabase, ty: &Type<'db>) -> Option<Vec<Expr<'db>>> {
145 let res = self
146 .data
147 .get_key_value(ty)
148 .or_else(|| self.data.iter().find(|(t, _)| t.could_unify_with_deeply(db, ty)))
149 .map(|(t, it)| it.exprs(t))
150 .or_else(|| {
151 self.data
152 .iter()
153 .find(|(t, _)| {
154 t.add_reference(db, Mutability::Shared).could_unify_with_deeply(db, ty)
155 })
156 .map(|(t, it)| {
157 it.exprs(t)
158 .into_iter()
159 .map(|expr| Expr::Reference(Box::new(expr)))
160 .collect()
161 })
162 });
163
164 if res.is_none() {
165 self.types_wishlist.insert(ty.clone());
166 }
167
168 if let Some(res) = &res
170 && res.len() > self.many_threshold
171 {
172 return Some(vec![Expr::Many(ty.clone())]);
173 }
174
175 res
176 }
177
178 fn insert(&mut self, ty: Type<'db>, exprs: impl Iterator<Item = Expr<'db>>) {
184 let ty = ty.instantiate_with_errors(self.db);
185 match self.data.get_mut(&ty) {
186 Some(it) => {
187 it.extend_with_threshold(self.many_threshold, exprs);
188 if it.is_many() {
189 self.types_wishlist.remove(&ty);
190 }
191 }
192 None => {
193 self.data.insert(ty.clone(), AlternativeExprs::new(self.many_threshold, exprs));
194 for it in self.new_types.values_mut() {
195 it.push(ty.clone());
196 }
197 }
198 }
199 }
200
201 fn iter_types(&self) -> impl Iterator<Item = Type<'db>> + '_ {
203 self.data.keys().cloned()
204 }
205
206 fn new_types(&mut self, key: NewTypesKey) -> Vec<Type<'db>> {
210 match self.new_types.get_mut(&key) {
211 Some(it) => std::mem::take(it),
212 None => Vec::new(),
213 }
214 }
215
216 fn types_wishlist(&mut self) -> &FxHashSet<Type<'db>> {
218 &self.types_wishlist
219 }
220}
221
222#[derive(Debug)]
224pub struct TermSearchCtx<'a, 'db, DB: HirDatabase> {
225 pub sema: &'a Semantics<'db, DB>,
227 pub scope: &'a SemanticsScope<'db>,
229 pub goal: Type<'db>,
231 pub config: TermSearchConfig,
233}
234
235#[derive(Debug, Clone, Copy)]
237pub struct TermSearchConfig {
238 pub many_alternatives_threshold: usize,
240 pub fuel: u64,
242}
243
244impl Default for TermSearchConfig {
245 fn default() -> Self {
246 Self { many_alternatives_threshold: 1, fuel: 1200 }
247 }
248}
249
250pub fn term_search<'db, DB: HirDatabase>(ctx: &TermSearchCtx<'_, 'db, DB>) -> Vec<Expr<'db>> {
272 let module = ctx.scope.module();
273 let mut defs = FxHashSet::default();
274 defs.insert(ScopeDef::ModuleDef(ModuleDef::Module(module)));
275
276 ctx.scope.process_all_names(&mut |_, def| {
277 defs.insert(def);
278 });
279
280 let mut lookup =
281 LookupTable::new(ctx.sema.db, ctx.config.many_alternatives_threshold, ctx.goal.clone());
282 let fuel = std::cell::Cell::new(ctx.config.fuel);
283
284 let should_continue = &|| {
285 let remaining = fuel.get();
286 fuel.set(remaining.saturating_sub(1));
287 if remaining == 0 {
288 tracing::debug!("fuel exhausted");
289 }
290 remaining > 0
291 };
292
293 let mut solutions: Vec<Expr<'db>> = tactics::trivial(ctx, &defs, &mut lookup).collect();
295 solutions.extend(tactics::famous_types(ctx, &defs, &mut lookup));
297 solutions.extend(tactics::assoc_const(ctx, &defs, &mut lookup));
298
299 while should_continue() {
300 solutions.extend(tactics::data_constructor(ctx, &defs, &mut lookup, should_continue));
301 solutions.extend(tactics::free_function(ctx, &defs, &mut lookup, should_continue));
302 solutions.extend(tactics::impl_method(ctx, &defs, &mut lookup, should_continue));
303 solutions.extend(tactics::struct_projection(ctx, &defs, &mut lookup, should_continue));
304 solutions.extend(tactics::impl_static_method(ctx, &defs, &mut lookup, should_continue));
305 solutions.extend(tactics::make_tuple(ctx, &defs, &mut lookup, should_continue));
306 }
307
308 solutions.into_iter().filter(|it| !it.is_many()).unique().collect()
309}