Unnamed repository; edit this file 'description' to name the repository.
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
//! Tactics for term search
//!
//! All the tactics take following arguments
//! * `ctx` - Context for the term search
//! * `defs` - Set of items in scope at term search target location
//! * `lookup` - Lookup table for types
//! * `should_continue` - Function that indicates when to stop iterating
//!
//! And they return iterator that yields type trees that unify with the `goal` type.

use std::iter;

use hir_ty::db::HirDatabase;
use hir_ty::mir::BorrowKind;
use hir_ty::TyBuilder;
use itertools::Itertools;
use rustc_hash::FxHashSet;

use crate::{
    Adt, AssocItem, Enum, GenericDef, GenericParam, HasVisibility, Impl, ModuleDef, ScopeDef, Type,
    TypeParam, Variant,
};

use crate::term_search::{Expr, TermSearchConfig};

use super::{LookupTable, NewTypesKey, TermSearchCtx};

/// # Trivial tactic
///
/// Attempts to fulfill the goal by trying items in scope
/// Also works as a starting point to move all items in scope to lookup table.
///
/// # Arguments
/// * `ctx` - Context for the term search
/// * `defs` - Set of items in scope at term search target location
/// * `lookup` - Lookup table for types
///
/// Returns iterator that yields elements that unify with `goal`.
///
/// _Note that there is no use of calling this tactic in every iteration as the output does not
/// depend on the current state of `lookup`_
pub(super) fn trivial<'a, DB: HirDatabase>(
    ctx: &'a TermSearchCtx<'a, DB>,
    defs: &'a FxHashSet<ScopeDef>,
    lookup: &'a mut LookupTable,
) -> impl Iterator<Item = Expr> + 'a {
    let db = ctx.sema.db;
    defs.iter().filter_map(|def| {
        let expr = match def {
            ScopeDef::ModuleDef(ModuleDef::Const(it)) => Some(Expr::Const(*it)),
            ScopeDef::ModuleDef(ModuleDef::Static(it)) => Some(Expr::Static(*it)),
            ScopeDef::GenericParam(GenericParam::ConstParam(it)) => Some(Expr::ConstParam(*it)),
            ScopeDef::Local(it) => {
                if ctx.config.enable_borrowcheck {
                    let borrowck = db.borrowck(it.parent).ok()?;

                    let invalid = borrowck.iter().any(|b| {
                        b.partially_moved.iter().any(|moved| {
                            Some(&moved.local) == b.mir_body.binding_locals.get(it.binding_id)
                        }) || b.borrow_regions.iter().any(|region| {
                            // Shared borrows are fine
                            Some(&region.local) == b.mir_body.binding_locals.get(it.binding_id)
                                && region.kind != BorrowKind::Shared
                        })
                    });

                    if invalid {
                        return None;
                    }
                }

                Some(Expr::Local(*it))
            }
            _ => None,
        }?;

        lookup.mark_exhausted(*def);

        let ty = expr.ty(db);
        lookup.insert(ty.clone(), std::iter::once(expr.clone()));

        // Don't suggest local references as they are not valid for return
        if matches!(expr, Expr::Local(_))
            && ty.contains_reference(db)
            && ctx.config.enable_borrowcheck
        {
            return None;
        }

        ty.could_unify_with_deeply(db, &ctx.goal).then_some(expr)
    })
}

/// # Associated constant tactic
///
/// Attempts to fulfill the goal by trying constants defined as associated items.
/// Only considers them on types that are in scope.
///
/// # Arguments
/// * `ctx` - Context for the term search
/// * `defs` - Set of items in scope at term search target location
/// * `lookup` - Lookup table for types
///
/// Returns iterator that yields elements that unify with `goal`.
///
/// _Note that there is no use of calling this tactic in every iteration as the output does not
/// depend on the current state of `lookup`_
pub(super) fn assoc_const<'a, DB: HirDatabase>(
    ctx: &'a TermSearchCtx<'a, DB>,
    defs: &'a FxHashSet<ScopeDef>,
    lookup: &'a mut LookupTable,
) -> impl Iterator<Item = Expr> + 'a {
    let db = ctx.sema.db;
    let module = ctx.scope.module();

    defs.iter()
        .filter_map(|def| match def {
            ScopeDef::ModuleDef(ModuleDef::Adt(it)) => Some(it),
            _ => None,
        })
        .flat_map(|it| Impl::all_for_type(db, it.ty(db)))
        .filter(|it| !it.is_unsafe(db))
        .flat_map(|it| it.items(db))
        .filter(move |it| it.is_visible_from(db, module))
        .filter_map(AssocItem::as_const)
        .filter_map(|it| {
            let expr = Expr::Const(it);
            let ty = it.ty(db);

            if ty.contains_unknown() {
                return None;
            }

            lookup.insert(ty.clone(), std::iter::once(expr.clone()));

            ty.could_unify_with_deeply(db, &ctx.goal).then_some(expr)
        })
}

/// # Data constructor tactic
///
/// Attempts different data constructors for enums and structs in scope
///
/// Updates lookup by new types reached and returns iterator that yields
/// elements that unify with `goal`.
///
/// # Arguments
/// * `ctx` - Context for the term search
/// * `defs` - Set of items in scope at term search target location
/// * `lookup` - Lookup table for types
/// * `should_continue` - Function that indicates when to stop iterating
pub(super) fn data_constructor<'a, DB: HirDatabase>(
    ctx: &'a TermSearchCtx<'a, DB>,
    defs: &'a FxHashSet<ScopeDef>,
    lookup: &'a mut LookupTable,
    should_continue: &'a dyn std::ops::Fn() -> bool,
) -> impl Iterator<Item = Expr> + 'a {
    let db = ctx.sema.db;
    let module = ctx.scope.module();
    fn variant_helper(
        db: &dyn HirDatabase,
        lookup: &mut LookupTable,
        should_continue: &dyn std::ops::Fn() -> bool,
        parent_enum: Enum,
        variant: Variant,
        config: &TermSearchConfig,
    ) -> Vec<(Type, Vec<Expr>)> {
        // Ignore unstable
        if variant.is_unstable(db) {
            return Vec::new();
        }

        let generics = GenericDef::from(variant.parent_enum(db));
        let Some(type_params) = generics
            .type_or_const_params(db)
            .into_iter()
            .map(|it| it.as_type_param(db))
            .collect::<Option<Vec<TypeParam>>>()
        else {
            // Ignore enums with const generics
            return Vec::new();
        };

        // We currently do not check lifetime bounds so ignore all types that have something to do
        // with them
        if !generics.lifetime_params(db).is_empty() {
            return Vec::new();
        }

        // Only account for stable type parameters for now, unstable params can be default
        // tho, for example in `Box<T, #[unstable] A: Allocator>`
        if type_params.iter().any(|it| it.is_unstable(db) && it.default(db).is_none()) {
            return Vec::new();
        }

        let non_default_type_params_len =
            type_params.iter().filter(|it| it.default(db).is_none()).count();

        let enum_ty_shallow = Adt::from(parent_enum).ty(db);
        let generic_params = lookup
            .types_wishlist()
            .clone()
            .into_iter()
            .filter(|ty| ty.could_unify_with(db, &enum_ty_shallow))
            .map(|it| it.type_arguments().collect::<Vec<Type>>())
            .chain((non_default_type_params_len == 0).then_some(Vec::new()));

        generic_params
            .filter(|_| should_continue())
            .filter_map(move |generics| {
                // Insert default type params
                let mut g = generics.into_iter();
                let generics: Vec<_> = type_params
                    .iter()
                    .map(|it| it.default(db).or_else(|| g.next()))
                    .collect::<Option<_>>()?;

                let enum_ty = Adt::from(parent_enum).ty_with_args(db, generics.iter().cloned());

                // Ignore types that have something to do with lifetimes
                if config.enable_borrowcheck && enum_ty.contains_reference(db) {
                    return None;
                }

                // Early exit if some param cannot be filled from lookup
                let param_exprs: Vec<Vec<Expr>> = variant
                    .fields(db)
                    .into_iter()
                    .map(|field| lookup.find(db, &field.ty_with_args(db, generics.iter().cloned())))
                    .collect::<Option<_>>()?;

                // Note that we need special case for 0 param constructors because of multi cartesian
                // product
                let variant_exprs: Vec<Expr> = if param_exprs.is_empty() {
                    vec![Expr::Variant { variant, generics, params: Vec::new() }]
                } else {
                    param_exprs
                        .into_iter()
                        .multi_cartesian_product()
                        .map(|params| Expr::Variant { variant, generics: generics.clone(), params })
                        .collect()
                };
                lookup.insert(enum_ty.clone(), variant_exprs.iter().cloned());

                Some((enum_ty, variant_exprs))
            })
            .collect()
    }
    defs.iter()
        .filter_map(move |def| match def {
            ScopeDef::ModuleDef(ModuleDef::Variant(it)) => {
                let variant_exprs = variant_helper(
                    db,
                    lookup,
                    should_continue,
                    it.parent_enum(db),
                    *it,
                    &ctx.config,
                );
                if variant_exprs.is_empty() {
                    return None;
                }
                if GenericDef::from(it.parent_enum(db))
                    .type_or_const_params(db)
                    .into_iter()
                    .filter_map(|it| it.as_type_param(db))
                    .all(|it| it.default(db).is_some())
                {
                    lookup.mark_fulfilled(ScopeDef::ModuleDef(ModuleDef::Variant(*it)));
                }
                Some(variant_exprs)
            }
            ScopeDef::ModuleDef(ModuleDef::Adt(Adt::Enum(enum_))) => {
                let exprs: Vec<(Type, Vec<Expr>)> = enum_
                    .variants(db)
                    .into_iter()
                    .flat_map(|it| {
                        variant_helper(db, lookup, should_continue, *enum_, it, &ctx.config)
                    })
                    .collect();

                if exprs.is_empty() {
                    return None;
                }

                if GenericDef::from(*enum_)
                    .type_or_const_params(db)
                    .into_iter()
                    .filter_map(|it| it.as_type_param(db))
                    .all(|it| it.default(db).is_some())
                {
                    lookup.mark_fulfilled(ScopeDef::ModuleDef(ModuleDef::Adt(Adt::Enum(*enum_))));
                }

                Some(exprs)
            }
            ScopeDef::ModuleDef(ModuleDef::Adt(Adt::Struct(it))) => {
                // Ignore unstable and not visible
                if it.is_unstable(db) || !it.is_visible_from(db, module) {
                    return None;
                }

                let generics = GenericDef::from(*it);

                // Ignore const params for now
                let type_params = generics
                    .type_or_const_params(db)
                    .into_iter()
                    .map(|it| it.as_type_param(db))
                    .collect::<Option<Vec<TypeParam>>>()?;

                // We currently do not check lifetime bounds so ignore all types that have something to do
                // with them
                if !generics.lifetime_params(db).is_empty() {
                    return None;
                }

                // Only account for stable type parameters for now, unstable params can be default
                // tho, for example in `Box<T, #[unstable] A: Allocator>`
                if type_params.iter().any(|it| it.is_unstable(db) && it.default(db).is_none()) {
                    return None;
                }

                let non_default_type_params_len =
                    type_params.iter().filter(|it| it.default(db).is_none()).count();

                let struct_ty_shallow = Adt::from(*it).ty(db);
                let generic_params = lookup
                    .types_wishlist()
                    .clone()
                    .into_iter()
                    .filter(|ty| ty.could_unify_with(db, &struct_ty_shallow))
                    .map(|it| it.type_arguments().collect::<Vec<Type>>())
                    .chain((non_default_type_params_len == 0).then_some(Vec::new()));

                let exprs = generic_params
                    .filter(|_| should_continue())
                    .filter_map(|generics| {
                        // Insert default type params
                        let mut g = generics.into_iter();
                        let generics: Vec<_> = type_params
                            .iter()
                            .map(|it| it.default(db).or_else(|| g.next()))
                            .collect::<Option<_>>()?;

                        let struct_ty = Adt::from(*it).ty_with_args(db, generics.iter().cloned());

                        // Ignore types that have something to do with lifetimes
                        if ctx.config.enable_borrowcheck && struct_ty.contains_reference(db) {
                            return None;
                        }
                        let fields = it.fields(db);
                        // Check if all fields are visible, otherwise we cannot fill them
                        if fields.iter().any(|it| !it.is_visible_from(db, module)) {
                            return None;
                        }

                        // Early exit if some param cannot be filled from lookup
                        let param_exprs: Vec<Vec<Expr>> = fields
                            .into_iter()
                            .map(|field| {
                                lookup.find(db, &field.ty_with_args(db, generics.iter().cloned()))
                            })
                            .collect::<Option<_>>()?;

                        // Note that we need special case for 0 param constructors because of multi cartesian
                        // product
                        let struct_exprs: Vec<Expr> = if param_exprs.is_empty() {
                            vec![Expr::Struct { strukt: *it, generics, params: Vec::new() }]
                        } else {
                            param_exprs
                                .into_iter()
                                .multi_cartesian_product()
                                .map(|params| Expr::Struct {
                                    strukt: *it,
                                    generics: generics.clone(),
                                    params,
                                })
                                .collect()
                        };

                        if non_default_type_params_len == 0 {
                            // Fulfilled only if there are no generic parameters
                            lookup.mark_fulfilled(ScopeDef::ModuleDef(ModuleDef::Adt(
                                Adt::Struct(*it),
                            )));
                        }
                        lookup.insert(struct_ty.clone(), struct_exprs.iter().cloned());

                        Some((struct_ty, struct_exprs))
                    })
                    .collect();
                Some(exprs)
            }
            _ => None,
        })
        .flatten()
        .filter_map(|(ty, exprs)| ty.could_unify_with_deeply(db, &ctx.goal).then_some(exprs))
        .flatten()
}

/// # Free function tactic
///
/// Attempts to call different functions in scope with parameters from lookup table.
/// Functions that include generics are not used for performance reasons.
///
/// Updates lookup by new types reached and returns iterator that yields
/// elements that unify with `goal`.
///
/// # Arguments
/// * `ctx` - Context for the term search
/// * `defs` - Set of items in scope at term search target location
/// * `lookup` - Lookup table for types
/// * `should_continue` - Function that indicates when to stop iterating
pub(super) fn free_function<'a, DB: HirDatabase>(
    ctx: &'a TermSearchCtx<'a, DB>,
    defs: &'a FxHashSet<ScopeDef>,
    lookup: &'a mut LookupTable,
    should_continue: &'a dyn std::ops::Fn() -> bool,
) -> impl Iterator<Item = Expr> + 'a {
    let db = ctx.sema.db;
    let module = ctx.scope.module();
    defs.iter()
        .filter_map(move |def| match def {
            ScopeDef::ModuleDef(ModuleDef::Function(it)) => {
                let generics = GenericDef::from(*it);

                // Ignore const params for now
                let type_params = generics
                    .type_or_const_params(db)
                    .into_iter()
                    .map(|it| it.as_type_param(db))
                    .collect::<Option<Vec<TypeParam>>>()?;

                // Ignore lifetimes as we do not check them
                if !generics.lifetime_params(db).is_empty() {
                    return None;
                }

                // Only account for stable type parameters for now, unstable params can be default
                // tho, for example in `Box<T, #[unstable] A: Allocator>`
                if type_params.iter().any(|it| it.is_unstable(db) && it.default(db).is_none()) {
                    return None;
                }

                let non_default_type_params_len =
                    type_params.iter().filter(|it| it.default(db).is_none()).count();

                // Ignore bigger number of generics for now as they kill the performance
                if non_default_type_params_len > 0 {
                    return None;
                }

                let generic_params = lookup
                    .iter_types()
                    .collect::<Vec<_>>() // Force take ownership
                    .into_iter()
                    .permutations(non_default_type_params_len);

                let exprs: Vec<_> = generic_params
                    .filter(|_| should_continue())
                    .filter_map(|generics| {
                        // Insert default type params
                        let mut g = generics.into_iter();
                        let generics: Vec<_> = type_params
                            .iter()
                            .map(|it| match it.default(db) {
                                Some(ty) => Some(ty),
                                None => {
                                    let generic = g.next().expect("Missing type param");
                                    // Filter out generics that do not unify due to trait bounds
                                    it.ty(db).could_unify_with(db, &generic).then_some(generic)
                                }
                            })
                            .collect::<Option<_>>()?;

                        let ret_ty = it.ret_type_with_args(db, generics.iter().cloned());
                        // Filter out private and unsafe functions
                        if !it.is_visible_from(db, module)
                            || it.is_unsafe_to_call(db)
                            || it.is_unstable(db)
                            || ctx.config.enable_borrowcheck && ret_ty.contains_reference(db)
                            || ret_ty.is_raw_ptr()
                        {
                            return None;
                        }

                        // Early exit if some param cannot be filled from lookup
                        let param_exprs: Vec<Vec<Expr>> = it
                            .params_without_self_with_args(db, generics.iter().cloned())
                            .into_iter()
                            .map(|field| {
                                let ty = field.ty();
                                match ty.is_mutable_reference() {
                                    true => None,
                                    false => lookup.find_autoref(db, ty),
                                }
                            })
                            .collect::<Option<_>>()?;

                        // Note that we need special case for 0 param constructors because of multi cartesian
                        // product
                        let fn_exprs: Vec<Expr> = if param_exprs.is_empty() {
                            vec![Expr::Function { func: *it, generics, params: Vec::new() }]
                        } else {
                            param_exprs
                                .into_iter()
                                .multi_cartesian_product()
                                .map(|params| Expr::Function {
                                    func: *it,
                                    generics: generics.clone(),

                                    params,
                                })
                                .collect()
                        };

                        lookup.mark_fulfilled(ScopeDef::ModuleDef(ModuleDef::Function(*it)));
                        lookup.insert(ret_ty.clone(), fn_exprs.iter().cloned());
                        Some((ret_ty, fn_exprs))
                    })
                    .collect();
                Some(exprs)
            }
            _ => None,
        })
        .flatten()
        .filter_map(|(ty, exprs)| ty.could_unify_with_deeply(db, &ctx.goal).then_some(exprs))
        .flatten()
}

/// # Impl method tactic
///
/// Attempts to call methods on types from lookup table.
/// This includes both functions from direct impl blocks as well as functions from traits.
/// Methods defined in impl blocks that are generic and methods that are themselves have
/// generics are ignored for performance reasons.
///
/// Updates lookup by new types reached and returns iterator that yields
/// elements that unify with `goal`.
///
/// # Arguments
/// * `ctx` - Context for the term search
/// * `defs` - Set of items in scope at term search target location
/// * `lookup` - Lookup table for types
/// * `should_continue` - Function that indicates when to stop iterating
pub(super) fn impl_method<'a, DB: HirDatabase>(
    ctx: &'a TermSearchCtx<'a, DB>,
    _defs: &'a FxHashSet<ScopeDef>,
    lookup: &'a mut LookupTable,
    should_continue: &'a dyn std::ops::Fn() -> bool,
) -> impl Iterator<Item = Expr> + 'a {
    let db = ctx.sema.db;
    let module = ctx.scope.module();
    lookup
        .new_types(NewTypesKey::ImplMethod)
        .into_iter()
        .flat_map(|ty| {
            Impl::all_for_type(db, ty.clone()).into_iter().map(move |imp| (ty.clone(), imp))
        })
        .flat_map(|(ty, imp)| imp.items(db).into_iter().map(move |item| (imp, ty.clone(), item)))
        .filter_map(|(imp, ty, it)| match it {
            AssocItem::Function(f) => Some((imp, ty, f)),
            _ => None,
        })
        .filter_map(move |(imp, ty, it)| {
            let fn_generics = GenericDef::from(it);
            let imp_generics = GenericDef::from(imp);

            // Ignore const params for now
            let imp_type_params = imp_generics
                .type_or_const_params(db)
                .into_iter()
                .map(|it| it.as_type_param(db))
                .collect::<Option<Vec<TypeParam>>>()?;

            // Ignore const params for now
            let fn_type_params = fn_generics
                .type_or_const_params(db)
                .into_iter()
                .map(|it| it.as_type_param(db))
                .collect::<Option<Vec<TypeParam>>>()?;

            // Ignore all functions that have something to do with lifetimes as we don't check them
            if !fn_generics.lifetime_params(db).is_empty() {
                return None;
            }

            // Ignore functions without self param
            if !it.has_self_param(db) {
                return None;
            }

            // Filter out private and unsafe functions
            if !it.is_visible_from(db, module) || it.is_unsafe_to_call(db) || it.is_unstable(db) {
                return None;
            }

            // Only account for stable type parameters for now, unstable params can be default
            // tho, for example in `Box<T, #[unstable] A: Allocator>`
            if imp_type_params.iter().any(|it| it.is_unstable(db) && it.default(db).is_none())
                || fn_type_params.iter().any(|it| it.is_unstable(db) && it.default(db).is_none())
            {
                return None;
            }

            // Double check that we have fully known type
            if ty.type_arguments().any(|it| it.contains_unknown()) {
                return None;
            }

            let non_default_fn_type_params_len =
                fn_type_params.iter().filter(|it| it.default(db).is_none()).count();

            // Ignore functions with generics for now as they kill the performance
            // Also checking bounds for generics is problematic
            if non_default_fn_type_params_len > 0 {
                return None;
            }

            let generic_params = lookup
                .iter_types()
                .collect::<Vec<_>>() // Force take ownership
                .into_iter()
                .permutations(non_default_fn_type_params_len);

            let exprs: Vec<_> = generic_params
                .filter(|_| should_continue())
                .filter_map(|generics| {
                    // Insert default type params
                    let mut g = generics.into_iter();
                    let generics: Vec<_> = ty
                        .type_arguments()
                        .map(Some)
                        .chain(fn_type_params.iter().map(|it| match it.default(db) {
                            Some(ty) => Some(ty),
                            None => {
                                let generic = g.next().expect("Missing type param");
                                // Filter out generics that do not unify due to trait bounds
                                it.ty(db).could_unify_with(db, &generic).then_some(generic)
                            }
                        }))
                        .collect::<Option<_>>()?;

                    let ret_ty = it.ret_type_with_args(
                        db,
                        ty.type_arguments().chain(generics.iter().cloned()),
                    );
                    // Filter out functions that return references
                    if ctx.config.enable_borrowcheck && ret_ty.contains_reference(db)
                        || ret_ty.is_raw_ptr()
                    {
                        return None;
                    }

                    // Ignore functions that do not change the type
                    if ty.could_unify_with_deeply(db, &ret_ty) {
                        return None;
                    }

                    let self_ty = it
                        .self_param(db)
                        .expect("No self param")
                        .ty_with_args(db, ty.type_arguments().chain(generics.iter().cloned()));

                    // Ignore functions that have different self type
                    if !self_ty.autoderef(db).any(|s_ty| ty == s_ty) {
                        return None;
                    }

                    let target_type_exprs = lookup.find(db, &ty).expect("Type not in lookup");

                    // Early exit if some param cannot be filled from lookup
                    let param_exprs: Vec<Vec<Expr>> = it
                        .params_without_self_with_args(
                            db,
                            ty.type_arguments().chain(generics.iter().cloned()),
                        )
                        .into_iter()
                        .map(|field| lookup.find_autoref(db, field.ty()))
                        .collect::<Option<_>>()?;

                    let fn_exprs: Vec<Expr> = std::iter::once(target_type_exprs)
                        .chain(param_exprs)
                        .multi_cartesian_product()
                        .map(|params| {
                            let mut params = params.into_iter();
                            let target = Box::new(params.next().unwrap());
                            Expr::Method {
                                func: it,
                                generics: generics.clone(),
                                target,
                                params: params.collect(),
                            }
                        })
                        .collect();

                    lookup.insert(ret_ty.clone(), fn_exprs.iter().cloned());
                    Some((ret_ty, fn_exprs))
                })
                .collect();
            Some(exprs)
        })
        .flatten()
        .filter_map(|(ty, exprs)| ty.could_unify_with_deeply(db, &ctx.goal).then_some(exprs))
        .flatten()
}

/// # Struct projection tactic
///
/// Attempts different struct fields (`foo.bar.baz`)
///
/// Updates lookup by new types reached and returns iterator that yields
/// elements that unify with `goal`.
///
/// # Arguments
/// * `ctx` - Context for the term search
/// * `defs` - Set of items in scope at term search target location
/// * `lookup` - Lookup table for types
/// * `should_continue` - Function that indicates when to stop iterating
pub(super) fn struct_projection<'a, DB: HirDatabase>(
    ctx: &'a TermSearchCtx<'a, DB>,
    _defs: &'a FxHashSet<ScopeDef>,
    lookup: &'a mut LookupTable,
    should_continue: &'a dyn std::ops::Fn() -> bool,
) -> impl Iterator<Item = Expr> + 'a {
    let db = ctx.sema.db;
    let module = ctx.scope.module();
    lookup
        .new_types(NewTypesKey::StructProjection)
        .into_iter()
        .map(|ty| (ty.clone(), lookup.find(db, &ty).expect("Expr not in lookup")))
        .filter(|_| should_continue())
        .flat_map(move |(ty, targets)| {
            ty.fields(db).into_iter().filter_map(move |(field, filed_ty)| {
                if !field.is_visible_from(db, module) {
                    return None;
                }
                let exprs = targets
                    .clone()
                    .into_iter()
                    .map(move |target| Expr::Field { field, expr: Box::new(target) });
                Some((filed_ty, exprs))
            })
        })
        .filter_map(|(ty, exprs)| ty.could_unify_with_deeply(db, &ctx.goal).then_some(exprs))
        .flatten()
}

/// # Famous types tactic
///
/// Attempts different values of well known types such as `true` or `false`.
///
/// Updates lookup by new types reached and returns iterator that yields
/// elements that unify with `goal`.
///
/// _Note that there is no point of calling it iteratively as the output is always the same_
///
/// # Arguments
/// * `ctx` - Context for the term search
/// * `defs` - Set of items in scope at term search target location
/// * `lookup` - Lookup table for types
pub(super) fn famous_types<'a, DB: HirDatabase>(
    ctx: &'a TermSearchCtx<'a, DB>,
    _defs: &'a FxHashSet<ScopeDef>,
    lookup: &'a mut LookupTable,
) -> impl Iterator<Item = Expr> + 'a {
    let db = ctx.sema.db;
    let module = ctx.scope.module();
    [
        Expr::FamousType { ty: Type::new(db, module.id, TyBuilder::bool()), value: "true" },
        Expr::FamousType { ty: Type::new(db, module.id, TyBuilder::bool()), value: "false" },
        Expr::FamousType { ty: Type::new(db, module.id, TyBuilder::unit()), value: "()" },
    ]
    .into_iter()
    .map(|exprs| {
        lookup.insert(exprs.ty(db), std::iter::once(exprs.clone()));
        exprs
    })
    .filter(|expr| expr.ty(db).could_unify_with_deeply(db, &ctx.goal))
}

/// # Impl static method (without self type) tactic
///
/// Attempts different functions from impl blocks that take no self parameter.
///
/// Updates lookup by new types reached and returns iterator that yields
/// elements that unify with `goal`.
///
/// # Arguments
/// * `ctx` - Context for the term search
/// * `defs` - Set of items in scope at term search target location
/// * `lookup` - Lookup table for types
/// * `should_continue` - Function that indicates when to stop iterating
pub(super) fn impl_static_method<'a, DB: HirDatabase>(
    ctx: &'a TermSearchCtx<'a, DB>,
    _defs: &'a FxHashSet<ScopeDef>,
    lookup: &'a mut LookupTable,
    should_continue: &'a dyn std::ops::Fn() -> bool,
) -> impl Iterator<Item = Expr> + 'a {
    let db = ctx.sema.db;
    let module = ctx.scope.module();
    lookup
        .types_wishlist()
        .clone()
        .into_iter()
        .chain(iter::once(ctx.goal.clone()))
        .filter(|_| should_continue())
        .flat_map(|ty| {
            Impl::all_for_type(db, ty.clone()).into_iter().map(move |imp| (ty.clone(), imp))
        })
        .filter(|(_, imp)| !imp.is_unsafe(db))
        .flat_map(|(ty, imp)| imp.items(db).into_iter().map(move |item| (imp, ty.clone(), item)))
        .filter_map(|(imp, ty, it)| match it {
            AssocItem::Function(f) => Some((imp, ty, f)),
            _ => None,
        })
        .filter_map(move |(imp, ty, it)| {
            let fn_generics = GenericDef::from(it);
            let imp_generics = GenericDef::from(imp);

            // Ignore const params for now
            let imp_type_params = imp_generics
                .type_or_const_params(db)
                .into_iter()
                .map(|it| it.as_type_param(db))
                .collect::<Option<Vec<TypeParam>>>()?;

            // Ignore const params for now
            let fn_type_params = fn_generics
                .type_or_const_params(db)
                .into_iter()
                .map(|it| it.as_type_param(db))
                .collect::<Option<Vec<TypeParam>>>()?;

            // Ignore all functions that have something to do with lifetimes as we don't check them
            if !fn_generics.lifetime_params(db).is_empty()
                || !imp_generics.lifetime_params(db).is_empty()
            {
                return None;
            }

            // Ignore functions with self param
            if it.has_self_param(db) {
                return None;
            }

            // Filter out private and unsafe functions
            if !it.is_visible_from(db, module) || it.is_unsafe_to_call(db) || it.is_unstable(db) {
                return None;
            }

            // Only account for stable type parameters for now, unstable params can be default
            // tho, for example in `Box<T, #[unstable] A: Allocator>`
            if imp_type_params.iter().any(|it| it.is_unstable(db) && it.default(db).is_none())
                || fn_type_params.iter().any(|it| it.is_unstable(db) && it.default(db).is_none())
            {
                return None;
            }

            // Double check that we have fully known type
            if ty.type_arguments().any(|it| it.contains_unknown()) {
                return None;
            }

            let non_default_fn_type_params_len =
                fn_type_params.iter().filter(|it| it.default(db).is_none()).count();

            // Ignore functions with generics for now as they kill the performance
            // Also checking bounds for generics is problematic
            if non_default_fn_type_params_len > 0 {
                return None;
            }

            let generic_params = lookup
                .iter_types()
                .collect::<Vec<_>>() // Force take ownership
                .into_iter()
                .permutations(non_default_fn_type_params_len);

            let exprs: Vec<_> = generic_params
                .filter(|_| should_continue())
                .filter_map(|generics| {
                    // Insert default type params
                    let mut g = generics.into_iter();
                    let generics: Vec<_> = ty
                        .type_arguments()
                        .map(Some)
                        .chain(fn_type_params.iter().map(|it| match it.default(db) {
                            Some(ty) => Some(ty),
                            None => {
                                let generic = g.next().expect("Missing type param");
                                it.trait_bounds(db)
                                    .into_iter()
                                    .all(|bound| generic.impls_trait(db, bound, &[]));
                                // Filter out generics that do not unify due to trait bounds
                                it.ty(db).could_unify_with(db, &generic).then_some(generic)
                            }
                        }))
                        .collect::<Option<_>>()?;

                    let ret_ty = it.ret_type_with_args(
                        db,
                        ty.type_arguments().chain(generics.iter().cloned()),
                    );
                    // Filter out functions that return references
                    if ctx.config.enable_borrowcheck && ret_ty.contains_reference(db)
                        || ret_ty.is_raw_ptr()
                    {
                        return None;
                    }

                    // Ignore functions that do not change the type
                    // if ty.could_unify_with_deeply(db, &ret_ty) {
                    //     return None;
                    // }

                    // Early exit if some param cannot be filled from lookup
                    let param_exprs: Vec<Vec<Expr>> = it
                        .params_without_self_with_args(
                            db,
                            ty.type_arguments().chain(generics.iter().cloned()),
                        )
                        .into_iter()
                        .map(|field| lookup.find_autoref(db, field.ty()))
                        .collect::<Option<_>>()?;

                    // Note that we need special case for 0 param constructors because of multi cartesian
                    // product
                    let fn_exprs: Vec<Expr> = if param_exprs.is_empty() {
                        vec![Expr::Function { func: it, generics, params: Vec::new() }]
                    } else {
                        param_exprs
                            .into_iter()
                            .multi_cartesian_product()
                            .map(|params| Expr::Function {
                                func: it,
                                generics: generics.clone(),
                                params,
                            })
                            .collect()
                    };

                    lookup.insert(ret_ty.clone(), fn_exprs.iter().cloned());
                    Some((ret_ty, fn_exprs))
                })
                .collect();
            Some(exprs)
        })
        .flatten()
        .filter_map(|(ty, exprs)| ty.could_unify_with_deeply(db, &ctx.goal).then_some(exprs))
        .flatten()
}

/// # Make tuple tactic
///
/// Attempts to create tuple types if any are listed in types wishlist
///
/// Updates lookup by new types reached and returns iterator that yields
/// elements that unify with `goal`.
///
/// # Arguments
/// * `ctx` - Context for the term search
/// * `defs` - Set of items in scope at term search target location
/// * `lookup` - Lookup table for types
/// * `should_continue` - Function that indicates when to stop iterating
pub(super) fn make_tuple<'a, DB: HirDatabase>(
    ctx: &'a TermSearchCtx<'a, DB>,
    _defs: &'a FxHashSet<ScopeDef>,
    lookup: &'a mut LookupTable,
    should_continue: &'a dyn std::ops::Fn() -> bool,
) -> impl Iterator<Item = Expr> + 'a {
    let db = ctx.sema.db;
    let module = ctx.scope.module();

    lookup
        .types_wishlist()
        .clone()
        .into_iter()
        .filter(|_| should_continue())
        .filter(|ty| ty.is_tuple())
        .filter_map(move |ty| {
            // Double check to not contain unknown
            if ty.contains_unknown() {
                return None;
            }

            // Ignore types that have something to do with lifetimes
            if ctx.config.enable_borrowcheck && ty.contains_reference(db) {
                return None;
            }

            // Early exit if some param cannot be filled from lookup
            let param_exprs: Vec<Vec<Expr>> =
                ty.type_arguments().map(|field| lookup.find(db, &field)).collect::<Option<_>>()?;

            let exprs: Vec<Expr> = param_exprs
                .into_iter()
                .multi_cartesian_product()
                .filter(|_| should_continue())
                .map(|params| {
                    let tys: Vec<Type> = params.iter().map(|it| it.ty(db)).collect();
                    let tuple_ty = Type::new_tuple(module.krate().into(), &tys);

                    let expr = Expr::Tuple { ty: tuple_ty.clone(), params };
                    lookup.insert(tuple_ty, iter::once(expr.clone()));
                    expr
                })
                .collect();

            Some(exprs)
        })
        .flatten()
        .filter_map(|expr| expr.ty(db).could_unify_with_deeply(db, &ctx.goal).then_some(expr))
}