Skip to main content

hir/
term_search.rs

1//! Term search
2
3use 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/// Key for lookup table to query new types reached.
16#[derive(Debug, Hash, PartialEq, Eq)]
17enum NewTypesKey {
18    ImplMethod,
19    StructProjection,
20}
21
22/// Helper enum to squash big number of alternative trees into `Many` variant as there is too many
23/// to take into account.
24#[derive(Debug)]
25enum AlternativeExprs<'db> {
26    /// There are few trees, so we keep track of them all
27    Few(FxHashSet<Expr<'db>>),
28    /// There are too many trees to keep track of
29    Many,
30}
31
32impl<'db> AlternativeExprs<'db> {
33    /// Construct alternative trees
34    ///
35    /// # Arguments
36    /// `threshold` - threshold value for many trees (more than that is many)
37    /// `exprs` - expressions iterator
38    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    /// Get type trees stored in alternative trees (or `Expr::Many` in case of many)
45    ///
46    /// # Arguments
47    /// `ty` - Type of expressions queried (this is used to give type to `Expr::Many`)
48    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    /// Extend alternative expressions
56    ///
57    /// # Arguments
58    /// `threshold` - threshold value for many trees (more than that is many)
59    /// `exprs` - expressions iterator
60    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/// # Lookup table for term search
82///
83/// Lookup table keeps all the state during term search.
84/// This means it knows what types and how are reachable.
85///
86/// The secondary functionality for lookup table is to keep track of new types reached since last
87/// iteration as well as keeping track of which `ScopeDef` items have been used.
88/// Both of them are to speed up the term search by leaving out types / ScopeDefs that likely do
89/// not produce any new results.
90#[derive(Debug)]
91struct LookupTable<'db> {
92    db: &'db dyn HirDatabase,
93    /// All the `Expr`s in "value" produce the type of "key"
94    data: FxHashMap<Type<'db>, AlternativeExprs<'db>>,
95    /// New types reached since last query by the `NewTypesKey`
96    new_types: FxHashMap<NewTypesKey, Vec<Type<'db>>>,
97    /// Types queried but not present
98    types_wishlist: FxHashSet<Type<'db>>,
99    /// Threshold to squash trees to `Many`
100    many_threshold: usize,
101}
102
103impl<'db> LookupTable<'db> {
104    /// Initialize lookup table
105    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    /// Find all `Expr`s that unify with the `ty`
119    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        // Collapse suggestions if there are many
131        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    /// Same as find but automatically creates shared reference of types in the lookup
141    ///
142    /// For example if we have type `i32` in data and we query for `&i32` it map all the type
143    /// trees we have for `i32` with `Expr::Reference` and returns them.
144    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        // Collapse suggestions if there are many
169        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    /// Insert new type trees for type
179    ///
180    /// Note that the types have to be the same, unification is not enough as unification is not
181    /// transitive. For example `Vec<i32>` and `FxHashSet<i32>` both unify with `Iterator<Item = i32>`,
182    /// but they clearly do not unify themselves.
183    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    /// Iterate all the reachable types
202    fn iter_types(&self) -> impl Iterator<Item = Type<'db>> + '_ {
203        self.data.keys().cloned()
204    }
205
206    /// Query new types reached since last query by key
207    ///
208    /// Create new key if you wish to query it to avoid conflicting with existing queries.
209    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    /// Types queried but not found
217    fn types_wishlist(&mut self) -> &FxHashSet<Type<'db>> {
218        &self.types_wishlist
219    }
220}
221
222/// Context for the `term_search` function
223#[derive(Debug)]
224pub struct TermSearchCtx<'a, 'db, DB: HirDatabase> {
225    /// Semantics for the program
226    pub sema: &'a Semantics<'db, DB>,
227    /// Semantic scope, captures context for the term search
228    pub scope: &'a SemanticsScope<'db>,
229    /// Target / expected output type
230    pub goal: Type<'db>,
231    /// Configuration for term search
232    pub config: TermSearchConfig,
233}
234
235/// Configuration options for the term search
236#[derive(Debug, Clone, Copy)]
237pub struct TermSearchConfig {
238    /// Indicate when to squash multiple trees to `Many` as there are too many to keep track
239    pub many_alternatives_threshold: usize,
240    /// Fuel for term search in "units of work"
241    pub fuel: u64,
242}
243
244impl Default for TermSearchConfig {
245    fn default() -> Self {
246        Self { many_alternatives_threshold: 1, fuel: 1200 }
247    }
248}
249
250/// # Term search
251///
252/// Search for terms (expressions) that unify with the `goal` type.
253///
254/// # Arguments
255/// * `ctx` - Context for term search
256///
257/// Internally this function uses Breadth First Search to find path to `goal` type.
258/// The general idea is following:
259/// 1. Populate lookup (frontier for BFS) from values (local variables, statics, constants, etc)
260///    as well as from well knows values (such as `true/false` and `()`)
261/// 2. Iteratively expand the frontier (or contents of the lookup) by trying different type
262///    transformation tactics. For example functions take as from set of types (arguments) to some
263///    type (return type). Other transformations include methods on type, type constructors and
264///    projections to struct fields (field access).
265/// 3. If we run out of fuel (term search takes too long) we stop iterating.
266/// 4. Return all the paths (type trees) that take us to the `goal` type.
267///
268/// Note that there are usually more ways we can get to the `goal` type but some are discarded to
269/// reduce the memory consumption. It is also unlikely anyone is willing ti browse through
270/// thousands of possible responses so we currently take first 10 from every tactic.
271pub 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    // Try trivial tactic first, also populates lookup table
294    let mut solutions: Vec<Expr<'db>> = tactics::trivial(ctx, &defs, &mut lookup).collect();
295    // Use well known types tactic before iterations as it does not depend on other tactics
296    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}