1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
use std::{
    cmp::{max, min},
    collections::HashMap,
};

use levenshtein::levenshtein;
use rustdoc_types as types;
use smallvec::{smallvec, SmallVec};
use tracing::{instrument, trace};

use crate::query::*;

#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub enum Similarity {
    /// Represents how digitally similar two objects are.
    Discrete(DiscreteSimilarity),

    /// Represents how analogly similar two objects are.
    Continuous(f32),
}

impl Similarity {
    pub fn score(&self) -> f32 {
        match self {
            Discrete(Equivalent) => 0.0,
            Discrete(Subequal) => 0.25,
            Discrete(Different) => 1.0,
            Continuous(s) => *s,
        }
    }
}

use Similarity::*;

#[derive(Debug, Clone, PartialEq)]
pub struct Similarities(pub SmallVec<[Similarity; 10]>);

impl Similarities {
    /// Calculate objective similarity for sorting.
    pub fn score(&self) -> f32 {
        let sum: f32 = self.0.iter().map(|sim| sim.score()).sum();
        sum / self.0.len() as f32
    }
}

impl PartialOrd for Similarities {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        (self.score()).partial_cmp(&other.score())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum DiscreteSimilarity {
    /// Indicates that two types are the same.
    ///
    /// For example:
    /// - `i32` and `i32`
    /// - `Result<i32, ()>` and `Result<i32, ()>`
    Equivalent,

    /// Indicates that two types are partially equal.
    ///
    /// For example:
    /// - an unbound generic type `T` and `i32`
    /// - an unbound generic type `T` and `Option<U>`
    Subequal,

    /// Indicates that two types are not similar at all.
    ///
    /// For example:
    /// - `i32` and `Option<bool>`
    Different,
}

use DiscreteSimilarity::*;

pub trait Compare<Rhs> {
    fn compare(
        &self,
        rhs: &Rhs,
        krate: &types::Crate,
        generics: &mut types::Generics,
        substs: &mut HashMap<String, Type>,
    ) -> SmallVec<[Similarity; 10]>;
}

impl Compare<types::Item> for Query {
    #[instrument(skip(krate))]
    fn compare(
        &self,
        item: &types::Item,
        krate: &types::Crate,
        generics: &mut types::Generics,
        substs: &mut HashMap<String, Type>,
    ) -> SmallVec<[Similarity; 10]> {
        let mut sims = smallvec![];

        match (&self.name, &item.name) {
            (Some(q), Some(i)) => sims.append(&mut q.compare(i, krate, generics, substs)),
            (Some(_), None) => sims.push(Discrete(Different)),
            _ => {}
        }
        trace!(?sims);

        if let Some(ref kind) = self.kind {
            sims.append(&mut kind.compare(&item.inner, krate, generics, substs))
        }
        trace!(?sims);

        sims
    }
}

impl Compare<String> for Symbol {
    #[instrument]
    fn compare(
        &self,
        symbol: &String,
        _: &types::Crate,
        _: &mut types::Generics,
        _: &mut HashMap<String, Type>,
    ) -> SmallVec<[Similarity; 10]> {
        use std::cmp::max;
        smallvec![Continuous(
            levenshtein(self, symbol) as f32 / max(self.len(), symbol.len()) as f32
        )]
    }
}

impl Compare<types::ItemEnum> for QueryKind {
    #[instrument(skip(krate))]
    fn compare(
        &self,
        kind: &types::ItemEnum,
        krate: &types::Crate,
        generics: &mut types::Generics,
        substs: &mut HashMap<String, Type>,
    ) -> SmallVec<[Similarity; 10]> {
        use types::ItemEnum::*;
        use QueryKind::*;

        match (self, kind) {
            (FunctionQuery(q), Function(i)) => q.compare(i, krate, generics, substs),
            (FunctionQuery(q), Method(i)) => q.compare(i, krate, generics, substs),
            (FunctionQuery(_), _) => smallvec![Discrete(Different)],
        }
    }
}

impl Compare<types::Function> for Function {
    #[instrument(skip(krate))]
    fn compare(
        &self,
        function: &types::Function,
        krate: &types::Crate,
        generics: &mut types::Generics,
        substs: &mut HashMap<String, Type>,
    ) -> SmallVec<[Similarity; 10]> {
        generics
            .params
            .append(&mut function.generics.params.clone());
        generics
            .where_predicates
            .append(&mut function.generics.where_predicates.clone());
        self.decl.compare(&function.decl, krate, generics, substs)
    }
}

impl Compare<types::Method> for Function {
    #[instrument(skip(krate))]
    fn compare(
        &self,
        method: &types::Method,
        krate: &types::Crate,
        generics: &mut types::Generics,
        substs: &mut HashMap<String, Type>,
    ) -> SmallVec<[Similarity; 10]> {
        generics.params.append(&mut method.generics.params.clone());
        generics
            .where_predicates
            .append(&mut method.generics.where_predicates.clone());
        self.decl.compare(&method.decl, krate, generics, substs)
    }
}

impl Compare<types::FnDecl> for FnDecl {
    #[instrument(skip(krate))]
    fn compare(
        &self,
        decl: &types::FnDecl,
        krate: &types::Crate,
        generics: &mut types::Generics,
        substs: &mut HashMap<String, Type>,
    ) -> SmallVec<[Similarity; 10]> {
        let mut sims = smallvec![];

        if let Some(ref inputs) = self.inputs {
            inputs.iter().enumerate().for_each(|(idx, q)| {
                if let Some(i) = decl.inputs.get(idx) {
                    sims.append(&mut q.compare(i, krate, generics, substs))
                }
            });

            if inputs.len() != decl.inputs.len() {
                // FIXME: Replace this line below with `usize::abs_diff` once it got stablized.
                let abs_diff =
                    max(inputs.len(), decl.inputs.len()) - min(inputs.len(), decl.inputs.len());
                sims.append::<[Similarity; 10]>(&mut smallvec![Discrete(Different); abs_diff])
            } else if inputs.is_empty() && decl.inputs.is_empty() {
                sims.push(Discrete(Equivalent));
            }
        }
        trace!(?sims);

        if let Some(ref output) = self.output {
            sims.append(&mut output.compare(&decl.output, krate, generics, substs));
        }
        trace!(?sims);

        sims
    }
}

impl Compare<(String, types::Type)> for Argument {
    #[instrument(skip(krate))]
    fn compare(
        &self,
        arg: &(String, types::Type),
        krate: &types::Crate,
        generics: &mut types::Generics,
        substs: &mut HashMap<String, Type>,
    ) -> SmallVec<[Similarity; 10]> {
        let mut sims = smallvec![];

        if let Some(ref name) = self.name {
            sims.append(&mut name.compare(&arg.0, krate, generics, substs));
        }
        trace!(?sims);

        if let Some(ref type_) = self.ty {
            sims.append(&mut type_.compare(&arg.1, krate, generics, substs));
        }
        trace!(?sims);

        sims
    }
}

impl Compare<Option<types::Type>> for FnRetTy {
    #[instrument(skip(krate))]
    fn compare(
        &self,
        ret_ty: &Option<types::Type>,
        krate: &types::Crate,
        generics: &mut types::Generics,
        substs: &mut HashMap<String, Type>,
    ) -> SmallVec<[Similarity; 10]> {
        match (self, ret_ty) {
            (FnRetTy::Return(q), Some(i)) => q.compare(i, krate, generics, substs),
            (FnRetTy::DefaultReturn, None) => smallvec![Discrete(Equivalent)],
            _ => smallvec![Discrete(Different)],
        }
    }
}

fn compare_type(
    lhs: &Type,
    rhs: &types::Type,
    krate: &types::Crate,
    generics: &mut types::Generics,
    substs: &mut HashMap<String, Type>,
    allow_recursion: bool,
) -> SmallVec<[Similarity; 10]> {
    use {crate::query::Type::*, types::Type};

    match (lhs, rhs) {
        (q, Type::Generic(i)) if i == "Self" => {
            let mut i = None;
            for where_predicate in &generics.where_predicates {
                if let types::WherePredicate::EqPredicate {
                    lhs: Type::Generic(lhs),
                    rhs,
                } = where_predicate
                {
                    if lhs == "Self" {
                        i = Some(rhs).cloned();
                        break;
                    }
                }
            }
            let i = &i.unwrap(); // SAFETY: `Self` only appears in definitions of associated items.
            q.compare(i, krate, generics, substs)
        }
        (q, Type::Generic(i)) => match substs.get(i) {
            Some(i) => {
                if q == i {
                    smallvec![Discrete(Equivalent)]
                } else {
                    smallvec![Discrete(Different)]
                }
            }
            None => {
                substs.insert(i.clone(), q.clone());
                smallvec![Discrete(Subequal)]
            }
        },
        (q, Type::ResolvedPath { id, .. })
            if krate
                .index
                .get(id)
                .map(|i| matches!(i.inner, types::ItemEnum::Typedef(_)))
                .unwrap_or(false)
                && allow_recursion =>
        {
            let sims_typedef = compare_type(lhs, rhs, krate, generics, substs, false);
            if let Some(types::Item {
                inner: types::ItemEnum::Typedef(types::Typedef { type_: ref i, .. }),
                ..
            }) = krate.index.get(id)
            {
                // TODO: Acknowledge `generics` of `types::Typedef` to get more accurate search results.
                let sims_adt = q.compare(i, krate, generics, substs);
                let sum = |sims: &SmallVec<[Similarity; 10]>| -> f32 {
                    sims.iter().map(Similarity::score).sum()
                };
                if sum(&sims_adt) < sum(&sims_typedef) {
                    return sims_adt;
                }
            }
            sims_typedef
        }
        (Tuple(q), Type::Tuple(i)) => {
            let mut sims = q
                .iter()
                .zip(i.iter())
                .filter_map(|(q, i)| q.as_ref().map(|q| q.compare(i, krate, generics, substs)))
                .flatten()
                .collect::<SmallVec<_>>();

            // They are both tuples.
            sims.push(Discrete(Equivalent));

            // FIXME: Replace this line below with `usize::abs_diff` once it got stablized.
            let abs_diff = max(q.len(), i.len()) - min(q.len(), i.len());
            sims.append::<[Similarity; 10]>(&mut smallvec![Discrete(Different); abs_diff]);

            sims
        }
        (Slice(q), Type::Slice(i)) => {
            // They are both slices.
            let mut sims = smallvec![Discrete(Equivalent)];

            if let Some(q) = q {
                sims.append(&mut q.compare(i, krate, generics, substs));
            }

            sims
        }
        (
            RawPointer {
                mutable: q_mut,
                type_: q,
            },
            Type::RawPointer {
                mutable: i_mut,
                type_: i,
            },
        )
        | (
            BorrowedRef {
                mutable: q_mut,
                type_: q,
            },
            Type::BorrowedRef {
                mutable: i_mut,
                type_: i,
                ..
            },
        ) => {
            if q_mut == i_mut {
                q.compare(i, krate, generics, substs)
            } else {
                let mut sims = q.compare(i, krate, generics, substs);
                sims.push(Discrete(Subequal));
                sims
            }
        }
        (q, Type::RawPointer { type_: i, .. } | Type::BorrowedRef { type_: i, .. }) => {
            let mut sims = q.compare(i, krate, generics, substs);
            sims.push(Discrete(Subequal));
            sims
        }
        (RawPointer { type_: q, .. } | BorrowedRef { type_: q, .. }, i) => {
            let mut sims = q.compare(i, krate, generics, substs);
            sims.push(Discrete(Subequal));
            sims
        }
        (
            UnresolvedPath {
                name: q,
                args: q_args,
            },
            Type::ResolvedPath {
                name: i,
                args: i_args,
                ..
            },
        ) => {
            let mut sims = q.compare(i, krate, generics, substs);

            match (q_args, i_args) {
                (Some(q), Some(i)) => match (&**q, &**i) {
                    (
                        GenericArgs::AngleBracketed { args: ref q },
                        types::GenericArgs::AngleBracketed { args: ref i, .. },
                    ) => {
                        let q = q.iter().map(|q| {
                            q.as_ref().map(|q| match q {
                                GenericArg::Type(q) => q,
                            })
                        });
                        let i = i.iter().map(|i| match i {
                            types::GenericArg::Type(t) => Some(t),
                            _ => None,
                        });
                        q.zip(i).for_each(|(q, i)| match (q, i) {
                            (Some(q), Some(i)) => {
                                sims.append(&mut q.compare(i, krate, generics, substs))
                            }
                            (Some(_), None) => sims.push(Discrete(Different)),
                            (None, _) => {}
                        });
                    }
                    // TODO: Support `GenericArgs::Parenthesized`.
                    (_, _) => {}
                },
                (Some(q), None) => {
                    let GenericArgs::AngleBracketed { args: ref q } = **q;
                    sims.append::<[Similarity; 10]>(&mut smallvec![Discrete(Different); q.len()])
                }
                (None, _) => {}
            }

            sims
        }
        (Primitive(q), Type::Primitive(i)) => q.compare(i, krate, generics, substs),
        _ => smallvec![Discrete(Different)],
    }
}

impl Compare<types::Type> for Type {
    #[instrument(skip(krate))]
    fn compare(
        &self,
        type_: &types::Type,
        krate: &types::Crate,
        generics: &mut types::Generics,
        substs: &mut HashMap<String, Type>,
    ) -> SmallVec<[Similarity; 10]> {
        compare_type(self, type_, krate, generics, substs, true)
    }
}

impl Compare<String> for PrimitiveType {
    #[instrument]
    fn compare(
        &self,
        prim_ty: &String,
        _: &types::Crate,
        _: &mut types::Generics,
        _: &mut HashMap<String, Type>,
    ) -> SmallVec<[Similarity; 10]> {
        if self.as_str() == prim_ty {
            smallvec![Discrete(Equivalent)]
        } else {
            smallvec![Discrete(Different)]
        }
    }
}