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
use rustc_errors::{Applicability, StashKey};
use rustc_hir as hir;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::intravisit;
use rustc_hir::intravisit::Visitor;
use rustc_hir::{HirId, Node};
use rustc_middle::hir::nested_filter;
use rustc_middle::ty::subst::InternalSubsts;
use rustc_middle::ty::util::IntTypeExt;
use rustc_middle::ty::{self, DefIdTree, Ty, TyCtxt, TypeFolder, TypeSuperFoldable, TypeVisitable};
use rustc_span::symbol::Ident;
use rustc_span::{Span, DUMMY_SP};

use super::ItemCtxt;
use super::{bad_placeholder, is_suggestable_infer_ty};
use crate::errors::UnconstrainedOpaqueType;

/// Computes the relevant generic parameter for a potential generic const argument.
///
/// This should be called using the query `tcx.opt_const_param_of`.
pub(super) fn opt_const_param_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<DefId> {
    use hir::*;
    let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);

    match tcx.hir().get(hir_id) {
        Node::AnonConst(_) => (),
        _ => return None,
    };

    let parent_node_id = tcx.hir().get_parent_node(hir_id);
    let parent_node = tcx.hir().get(parent_node_id);

    let (generics, arg_idx) = match parent_node {
        // This match arm is for when the def_id appears in a GAT whose
        // path can't be resolved without typechecking e.g.
        //
        // trait Foo {
        //   type Assoc<const N: usize>;
        //   fn foo() -> Self::Assoc<3>;
        // }
        //
        // In the above code we would call this query with the def_id of 3 and
        // the parent_node we match on would be the hir node for Self::Assoc<3>
        //
        // `Self::Assoc<3>` cant be resolved without typechecking here as we
        // didnt write <Self as Foo>::Assoc<3>. If we did then another match
        // arm would handle this.
        //
        // I believe this match arm is only needed for GAT but I am not 100% sure - BoxyUwU
        Node::Ty(hir_ty @ Ty { kind: TyKind::Path(QPath::TypeRelative(_, segment)), .. }) => {
            // Find the Item containing the associated type so we can create an ItemCtxt.
            // Using the ItemCtxt convert the HIR for the unresolved assoc type into a
            // ty which is a fully resolved projection.
            // For the code example above, this would mean converting Self::Assoc<3>
            // into a ty::Projection(<Self as Foo>::Assoc<3>)
            let item_hir_id = tcx
                .hir()
                .parent_iter(hir_id)
                .filter(|(_, node)| matches!(node, Node::Item(_)))
                .map(|(id, _)| id)
                .next()
                .unwrap();
            let item_did = tcx.hir().local_def_id(item_hir_id).to_def_id();
            let item_ctxt = &ItemCtxt::new(tcx, item_did) as &dyn crate::astconv::AstConv<'_>;
            let ty = item_ctxt.ast_ty_to_ty(hir_ty);

            // Iterate through the generics of the projection to find the one that corresponds to
            // the def_id that this query was called with. We filter to only type and const args here
            // as a precaution for if it's ever allowed to elide lifetimes in GAT's. It currently isn't
            // but it can't hurt to be safe ^^
            if let ty::Projection(projection) = ty.kind() {
                let generics = tcx.generics_of(projection.item_def_id);

                let arg_index = segment
                    .args
                    .and_then(|args| {
                        args.args
                            .iter()
                            .filter(|arg| arg.is_ty_or_const())
                            .position(|arg| arg.hir_id() == hir_id)
                    })
                    .unwrap_or_else(|| {
                        bug!("no arg matching AnonConst in segment");
                    });

                (generics, arg_index)
            } else {
                // I dont think it's possible to reach this but I'm not 100% sure - BoxyUwU
                tcx.sess.delay_span_bug(
                    tcx.def_span(def_id),
                    "unexpected non-GAT usage of an anon const",
                );
                return None;
            }
        }
        Node::Expr(&Expr {
            kind:
                ExprKind::MethodCall(segment, ..) | ExprKind::Path(QPath::TypeRelative(_, segment)),
            ..
        }) => {
            let body_owner = tcx.hir().enclosing_body_owner(hir_id);
            let tables = tcx.typeck(body_owner);
            // This may fail in case the method/path does not actually exist.
            // As there is no relevant param for `def_id`, we simply return
            // `None` here.
            let type_dependent_def = tables.type_dependent_def_id(parent_node_id)?;
            let idx = segment
                .args
                .and_then(|args| {
                    args.args
                        .iter()
                        .filter(|arg| arg.is_ty_or_const())
                        .position(|arg| arg.hir_id() == hir_id)
                })
                .unwrap_or_else(|| {
                    bug!("no arg matching AnonConst in segment");
                });

            (tcx.generics_of(type_dependent_def), idx)
        }

        Node::Ty(&Ty { kind: TyKind::Path(_), .. })
        | Node::Expr(&Expr { kind: ExprKind::Path(_) | ExprKind::Struct(..), .. })
        | Node::TraitRef(..)
        | Node::Pat(_) => {
            let path = match parent_node {
                Node::Ty(&Ty { kind: TyKind::Path(QPath::Resolved(_, path)), .. })
                | Node::TraitRef(&TraitRef { path, .. }) => &*path,
                Node::Expr(&Expr {
                    kind:
                        ExprKind::Path(QPath::Resolved(_, path))
                        | ExprKind::Struct(&QPath::Resolved(_, path), ..),
                    ..
                }) => {
                    let body_owner = tcx.hir().enclosing_body_owner(hir_id);
                    let _tables = tcx.typeck(body_owner);
                    &*path
                }
                Node::Pat(pat) => {
                    if let Some(path) = get_path_containing_arg_in_pat(pat, hir_id) {
                        path
                    } else {
                        tcx.sess.delay_span_bug(
                            tcx.def_span(def_id),
                            &format!("unable to find const parent for {} in pat {:?}", hir_id, pat),
                        );
                        return None;
                    }
                }
                _ => {
                    tcx.sess.delay_span_bug(
                        tcx.def_span(def_id),
                        &format!("unexpected const parent path {:?}", parent_node),
                    );
                    return None;
                }
            };

            // We've encountered an `AnonConst` in some path, so we need to
            // figure out which generic parameter it corresponds to and return
            // the relevant type.
            let Some((arg_index, segment)) = path.segments.iter().find_map(|seg| {
                let args = seg.args?;
                args.args
                .iter()
                .filter(|arg| arg.is_ty_or_const())
                .position(|arg| arg.hir_id() == hir_id)
                .map(|index| (index, seg)).or_else(|| args.bindings
                    .iter()
                    .filter_map(TypeBinding::opt_const)
                    .position(|ct| ct.hir_id == hir_id)
                    .map(|idx| (idx, seg)))
            }) else {
                tcx.sess.delay_span_bug(
                    tcx.def_span(def_id),
                    "no arg matching AnonConst in path",
                );
                return None;
            };

            let generics = match tcx.res_generics_def_id(segment.res) {
                Some(def_id) => tcx.generics_of(def_id),
                None => {
                    tcx.sess.delay_span_bug(
                        tcx.def_span(def_id),
                        &format!("unexpected anon const res {:?} in path: {:?}", segment.res, path),
                    );
                    return None;
                }
            };

            (generics, arg_index)
        }
        _ => return None,
    };

    debug!(?parent_node);
    debug!(?generics, ?arg_idx);
    generics
        .params
        .iter()
        .filter(|param| param.kind.is_ty_or_const())
        .nth(match generics.has_self && generics.parent.is_none() {
            true => arg_idx + 1,
            false => arg_idx,
        })
        .and_then(|param| match param.kind {
            ty::GenericParamDefKind::Const { .. } => {
                debug!(?param);
                Some(param.def_id)
            }
            _ => None,
        })
}

fn get_path_containing_arg_in_pat<'hir>(
    pat: &'hir hir::Pat<'hir>,
    arg_id: HirId,
) -> Option<&'hir hir::Path<'hir>> {
    use hir::*;

    let is_arg_in_path = |p: &hir::Path<'_>| {
        p.segments
            .iter()
            .filter_map(|seg| seg.args)
            .flat_map(|args| args.args)
            .any(|arg| arg.hir_id() == arg_id)
    };
    let mut arg_path = None;
    pat.walk(|pat| match pat.kind {
        PatKind::Struct(QPath::Resolved(_, path), _, _)
        | PatKind::TupleStruct(QPath::Resolved(_, path), _, _)
        | PatKind::Path(QPath::Resolved(_, path))
            if is_arg_in_path(path) =>
        {
            arg_path = Some(path);
            false
        }
        _ => true,
    });
    arg_path
}

pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> {
    let def_id = def_id.expect_local();
    use rustc_hir::*;

    let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);

    let icx = ItemCtxt::new(tcx, def_id.to_def_id());

    match tcx.hir().get(hir_id) {
        Node::TraitItem(item) => match item.kind {
            TraitItemKind::Fn(..) => {
                let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
                tcx.mk_fn_def(def_id.to_def_id(), substs)
            }
            TraitItemKind::Const(ty, body_id) => body_id
                .and_then(|body_id| {
                    if is_suggestable_infer_ty(ty) {
                        Some(infer_placeholder_type(
                            tcx, def_id, body_id, ty.span, item.ident, "constant",
                        ))
                    } else {
                        None
                    }
                })
                .unwrap_or_else(|| icx.to_ty(ty)),
            TraitItemKind::Type(_, Some(ty)) => icx.to_ty(ty),
            TraitItemKind::Type(_, None) => {
                span_bug!(item.span, "associated type missing default");
            }
        },

        Node::ImplItem(item) => match item.kind {
            ImplItemKind::Fn(..) => {
                let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
                tcx.mk_fn_def(def_id.to_def_id(), substs)
            }
            ImplItemKind::Const(ty, body_id) => {
                if is_suggestable_infer_ty(ty) {
                    infer_placeholder_type(tcx, def_id, body_id, ty.span, item.ident, "constant")
                } else {
                    icx.to_ty(ty)
                }
            }
            ImplItemKind::TyAlias(ty) => {
                if tcx.impl_trait_ref(tcx.hir().get_parent_item(hir_id)).is_none() {
                    check_feature_inherent_assoc_ty(tcx, item.span);
                }

                icx.to_ty(ty)
            }
        },

        Node::Item(item) => {
            match item.kind {
                ItemKind::Static(ty, .., body_id) => {
                    if is_suggestable_infer_ty(ty) {
                        infer_placeholder_type(
                            tcx,
                            def_id,
                            body_id,
                            ty.span,
                            item.ident,
                            "static variable",
                        )
                    } else {
                        icx.to_ty(ty)
                    }
                }
                ItemKind::Const(ty, body_id) => {
                    if is_suggestable_infer_ty(ty) {
                        infer_placeholder_type(
                            tcx, def_id, body_id, ty.span, item.ident, "constant",
                        )
                    } else {
                        icx.to_ty(ty)
                    }
                }
                ItemKind::TyAlias(self_ty, _) => icx.to_ty(self_ty),
                ItemKind::Impl(hir::Impl { self_ty, .. }) => icx.to_ty(*self_ty),
                ItemKind::Fn(..) => {
                    let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
                    tcx.mk_fn_def(def_id.to_def_id(), substs)
                }
                ItemKind::Enum(..) | ItemKind::Struct(..) | ItemKind::Union(..) => {
                    let def = tcx.adt_def(def_id);
                    let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
                    tcx.mk_adt(def, substs)
                }
                ItemKind::OpaqueTy(OpaqueTy { origin: hir::OpaqueTyOrigin::TyAlias, .. }) => {
                    find_opaque_ty_constraints_for_tait(tcx, def_id)
                }
                // Opaque types desugared from `impl Trait`.
                ItemKind::OpaqueTy(OpaqueTy { origin: hir::OpaqueTyOrigin::FnReturn(owner) | hir::OpaqueTyOrigin::AsyncFn(owner), in_trait, .. }) => {
                    if in_trait {
                        span_bug!(item.span, "impl-trait in trait has no default")
                    } else {
                        find_opaque_ty_constraints_for_rpit(tcx, def_id, owner)
                    }
                }
                ItemKind::Trait(..)
                | ItemKind::TraitAlias(..)
                | ItemKind::Macro(..)
                | ItemKind::Mod(..)
                | ItemKind::ForeignMod { .. }
                | ItemKind::GlobalAsm(..)
                | ItemKind::ExternCrate(..)
                | ItemKind::Use(..) => {
                    span_bug!(
                        item.span,
                        "compute_type_of_item: unexpected item type: {:?}",
                        item.kind
                    );
                }
            }
        }

        Node::ForeignItem(foreign_item) => match foreign_item.kind {
            ForeignItemKind::Fn(..) => {
                let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
                tcx.mk_fn_def(def_id.to_def_id(), substs)
            }
            ForeignItemKind::Static(t, _) => icx.to_ty(t),
            ForeignItemKind::Type => tcx.mk_foreign(def_id.to_def_id()),
        },

        Node::Ctor(&ref def) | Node::Variant(Variant { data: ref def, .. }) => match *def {
            VariantData::Unit(..) | VariantData::Struct(..) => {
                tcx.type_of(tcx.hir().get_parent_item(hir_id))
            }
            VariantData::Tuple(..) => {
                let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
                tcx.mk_fn_def(def_id.to_def_id(), substs)
            }
        },

        Node::Field(field) => icx.to_ty(field.ty),

        Node::Expr(&Expr { kind: ExprKind::Closure{..}, .. }) => tcx.typeck(def_id).node_type(hir_id),

        Node::AnonConst(_) if let Some(param) = tcx.opt_const_param_of(def_id) => {
            // We defer to `type_of` of the corresponding parameter
            // for generic arguments.
            tcx.type_of(param)
        }

        Node::AnonConst(_) => {
            let parent_node = tcx.hir().get(tcx.hir().get_parent_node(hir_id));
            match parent_node {
                Node::Ty(&Ty { kind: TyKind::Array(_, ref constant), .. })
                | Node::Expr(&Expr { kind: ExprKind::Repeat(_, ref constant), .. })
                    if constant.hir_id() == hir_id =>
                {
                    tcx.types.usize
                }
                Node::Ty(&Ty { kind: TyKind::Typeof(ref e), .. }) if e.hir_id == hir_id => {
                    tcx.typeck(def_id).node_type(e.hir_id)
                }

                Node::Expr(&Expr { kind: ExprKind::ConstBlock(ref anon_const), .. })
                    if anon_const.hir_id == hir_id =>
                {
                    let substs = InternalSubsts::identity_for_item(tcx, def_id.to_def_id());
                    substs.as_inline_const().ty()
                }

                Node::Expr(&Expr { kind: ExprKind::InlineAsm(asm), .. })
                | Node::Item(&Item { kind: ItemKind::GlobalAsm(asm), .. })
                    if asm.operands.iter().any(|(op, _op_sp)| match op {
                        hir::InlineAsmOperand::Const { anon_const }
                        | hir::InlineAsmOperand::SymFn { anon_const } => anon_const.hir_id == hir_id,
                        _ => false,
                    }) =>
                {
                    tcx.typeck(def_id).node_type(hir_id)
                }

                Node::Variant(Variant { disr_expr: Some(ref e), .. }) if e.hir_id == hir_id => tcx
                    .adt_def(tcx.hir().get_parent_item(hir_id))
                    .repr()
                    .discr_type()
                    .to_ty(tcx),

                Node::TypeBinding(binding @ &TypeBinding { hir_id: binding_id, ..  })
                    if let Node::TraitRef(trait_ref) = tcx.hir().get(
                        tcx.hir().get_parent_node(binding_id)
                    ) =>
                {
                  let Some(trait_def_id) = trait_ref.trait_def_id() else {
                    return tcx.ty_error_with_message(DUMMY_SP, "Could not find trait");
                  };
                  let assoc_items = tcx.associated_items(trait_def_id);
                  let assoc_item = assoc_items.find_by_name_and_kind(
                    tcx, binding.ident, ty::AssocKind::Const, def_id.to_def_id(),
                  );
                  if let Some(assoc_item) = assoc_item {
                    tcx.type_of(assoc_item.def_id)
                  } else {
                      // FIXME(associated_const_equality): add a useful error message here.
                      tcx.ty_error_with_message(
                        DUMMY_SP,
                        "Could not find associated const on trait",
                    )
                  }
                }

                Node::GenericParam(&GenericParam {
                    hir_id: param_hir_id,
                    kind: GenericParamKind::Const { default: Some(ct), .. },
                    ..
                }) if ct.hir_id == hir_id => tcx.type_of(tcx.hir().local_def_id(param_hir_id)),

                x =>
                  tcx.ty_error_with_message(
                    DUMMY_SP,
                    &format!("unexpected const parent in type_of(): {x:?}"),
                ),
            }
        }

        Node::GenericParam(param) => match &param.kind {
            GenericParamKind::Type { default: Some(ty), .. }
            | GenericParamKind::Const { ty, .. } => icx.to_ty(ty),
            x => bug!("unexpected non-type Node::GenericParam: {:?}", x),
        },

        x => {
            bug!("unexpected sort of node in type_of(): {:?}", x);
        }
    }
}

#[instrument(skip(tcx), level = "debug")]
/// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
/// laid for "higher-order pattern unification".
/// This ensures that inference is tractable.
/// In particular, definitions of opaque types can only use other generics as arguments,
/// and they cannot repeat an argument. Example:
///
/// ```ignore (illustrative)
/// type Foo<A, B> = impl Bar<A, B>;
///
/// // Okay -- `Foo` is applied to two distinct, generic types.
/// fn a<T, U>() -> Foo<T, U> { .. }
///
/// // Not okay -- `Foo` is applied to `T` twice.
/// fn b<T>() -> Foo<T, T> { .. }
///
/// // Not okay -- `Foo` is applied to a non-generic type.
/// fn b<T>() -> Foo<T, u32> { .. }
/// ```
///
fn find_opaque_ty_constraints_for_tait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> {
    use rustc_hir::{Expr, ImplItem, Item, TraitItem};

    struct ConstraintLocator<'tcx> {
        tcx: TyCtxt<'tcx>,

        /// def_id of the opaque type whose defining uses are being checked
        def_id: LocalDefId,

        /// as we walk the defining uses, we are checking that all of them
        /// define the same hidden type. This variable is set to `Some`
        /// with the first type that we find, and then later types are
        /// checked against it (we also carry the span of that first
        /// type).
        found: Option<ty::OpaqueHiddenType<'tcx>>,
    }

    impl ConstraintLocator<'_> {
        #[instrument(skip(self), level = "debug")]
        fn check(&mut self, item_def_id: LocalDefId) {
            // Don't try to check items that cannot possibly constrain the type.
            if !self.tcx.has_typeck_results(item_def_id) {
                debug!("no constraint: no typeck results");
                return;
            }
            // Calling `mir_borrowck` can lead to cycle errors through
            // const-checking, avoid calling it if we don't have to.
            // ```rust
            // type Foo = impl Fn() -> usize; // when computing type for this
            // const fn bar() -> Foo {
            //     || 0usize
            // }
            // const BAZR: Foo = bar(); // we would mir-borrowck this, causing cycles
            // // because we again need to reveal `Foo` so we can check whether the
            // // constant does not contain interior mutability.
            // ```
            let tables = self.tcx.typeck(item_def_id);
            if let Some(_) = tables.tainted_by_errors {
                self.found = Some(ty::OpaqueHiddenType { span: DUMMY_SP, ty: self.tcx.ty_error() });
                return;
            }
            if !tables.concrete_opaque_types.contains_key(&self.def_id) {
                debug!("no constraints in typeck results");
                return;
            }
            // Use borrowck to get the type with unerased regions.
            let concrete_opaque_types = &self.tcx.mir_borrowck(item_def_id).concrete_opaque_types;
            debug!(?concrete_opaque_types);
            if let Some(&concrete_type) = concrete_opaque_types.get(&self.def_id) {
                debug!(?concrete_type, "found constraint");
                if let Some(prev) = self.found {
                    if concrete_type.ty != prev.ty && !(concrete_type, prev).references_error() {
                        prev.report_mismatch(&concrete_type, self.tcx);
                    }
                } else {
                    self.found = Some(concrete_type);
                }
            }
        }
    }

    impl<'tcx> intravisit::Visitor<'tcx> for ConstraintLocator<'tcx> {
        type NestedFilter = nested_filter::All;

        fn nested_visit_map(&mut self) -> Self::Map {
            self.tcx.hir()
        }
        fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
            if let hir::ExprKind::Closure { .. } = ex.kind {
                let def_id = self.tcx.hir().local_def_id(ex.hir_id);
                self.check(def_id);
            }
            intravisit::walk_expr(self, ex);
        }
        fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
            trace!(?it.def_id);
            // The opaque type itself or its children are not within its reveal scope.
            if it.def_id != self.def_id {
                self.check(it.def_id);
                intravisit::walk_item(self, it);
            }
        }
        fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
            trace!(?it.def_id);
            // The opaque type itself or its children are not within its reveal scope.
            if it.def_id != self.def_id {
                self.check(it.def_id);
                intravisit::walk_impl_item(self, it);
            }
        }
        fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
            trace!(?it.def_id);
            self.check(it.def_id);
            intravisit::walk_trait_item(self, it);
        }
    }

    let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
    let scope = tcx.hir().get_defining_scope(hir_id);
    let mut locator = ConstraintLocator { def_id: def_id, tcx, found: None };

    debug!(?scope);

    if scope == hir::CRATE_HIR_ID {
        tcx.hir().walk_toplevel_module(&mut locator);
    } else {
        trace!("scope={:#?}", tcx.hir().get(scope));
        match tcx.hir().get(scope) {
            // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
            // This allows our visitor to process the defining item itself, causing
            // it to pick up any 'sibling' defining uses.
            //
            // For example, this code:
            // ```
            // fn foo() {
            //     type Blah = impl Debug;
            //     let my_closure = || -> Blah { true };
            // }
            // ```
            //
            // requires us to explicitly process `foo()` in order
            // to notice the defining usage of `Blah`.
            Node::Item(it) => locator.visit_item(it),
            Node::ImplItem(it) => locator.visit_impl_item(it),
            Node::TraitItem(it) => locator.visit_trait_item(it),
            other => bug!("{:?} is not a valid scope for an opaque type item", other),
        }
    }

    match locator.found {
        Some(hidden) => hidden.ty,
        None => {
            tcx.sess.emit_err(UnconstrainedOpaqueType {
                span: tcx.def_span(def_id),
                name: tcx.item_name(tcx.local_parent(def_id).to_def_id()),
            });
            tcx.ty_error()
        }
    }
}

fn find_opaque_ty_constraints_for_rpit(
    tcx: TyCtxt<'_>,
    def_id: LocalDefId,
    owner_def_id: LocalDefId,
) -> Ty<'_> {
    use rustc_hir::{Expr, ImplItem, Item, TraitItem};

    struct ConstraintChecker<'tcx> {
        tcx: TyCtxt<'tcx>,

        /// def_id of the opaque type whose defining uses are being checked
        def_id: LocalDefId,

        found: ty::OpaqueHiddenType<'tcx>,
    }

    impl ConstraintChecker<'_> {
        #[instrument(skip(self), level = "debug")]
        fn check(&self, def_id: LocalDefId) {
            // Use borrowck to get the type with unerased regions.
            let concrete_opaque_types = &self.tcx.mir_borrowck(def_id).concrete_opaque_types;
            debug!(?concrete_opaque_types);
            for &(def_id, concrete_type) in concrete_opaque_types {
                if def_id != self.def_id {
                    // Ignore constraints for other opaque types.
                    continue;
                }

                debug!(?concrete_type, "found constraint");

                if concrete_type.ty != self.found.ty
                    && !(concrete_type, self.found).references_error()
                {
                    self.found.report_mismatch(&concrete_type, self.tcx);
                }
            }
        }
    }

    impl<'tcx> intravisit::Visitor<'tcx> for ConstraintChecker<'tcx> {
        type NestedFilter = nested_filter::OnlyBodies;

        fn nested_visit_map(&mut self) -> Self::Map {
            self.tcx.hir()
        }
        fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
            if let hir::ExprKind::Closure { .. } = ex.kind {
                let def_id = self.tcx.hir().local_def_id(ex.hir_id);
                self.check(def_id);
            }
            intravisit::walk_expr(self, ex);
        }
        fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
            trace!(?it.def_id);
            // The opaque type itself or its children are not within its reveal scope.
            if it.def_id != self.def_id {
                self.check(it.def_id);
                intravisit::walk_item(self, it);
            }
        }
        fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
            trace!(?it.def_id);
            // The opaque type itself or its children are not within its reveal scope.
            if it.def_id != self.def_id {
                self.check(it.def_id);
                intravisit::walk_impl_item(self, it);
            }
        }
        fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
            trace!(?it.def_id);
            self.check(it.def_id);
            intravisit::walk_trait_item(self, it);
        }
    }

    let concrete = tcx.mir_borrowck(owner_def_id).concrete_opaque_types.get(&def_id).copied();

    if let Some(concrete) = concrete {
        let scope = tcx.hir().local_def_id_to_hir_id(owner_def_id);
        debug!(?scope);
        let mut locator = ConstraintChecker { def_id: def_id, tcx, found: concrete };

        match tcx.hir().get(scope) {
            Node::Item(it) => intravisit::walk_item(&mut locator, it),
            Node::ImplItem(it) => intravisit::walk_impl_item(&mut locator, it),
            Node::TraitItem(it) => intravisit::walk_trait_item(&mut locator, it),
            other => bug!("{:?} is not a valid scope for an opaque type item", other),
        }
    }

    concrete.map(|concrete| concrete.ty).unwrap_or_else(|| {
        let table = tcx.typeck(owner_def_id);
        if let Some(_) = table.tainted_by_errors {
            // Some error in the
            // owner fn prevented us from populating
            // the `concrete_opaque_types` table.
            tcx.ty_error()
        } else {
            table
                .concrete_opaque_types
                .get(&def_id)
                .copied()
                .unwrap_or_else(|| {
                    // We failed to resolve the opaque type or it
                    // resolves to itself. We interpret this as the
                    // no values of the hidden type ever being constructed,
                    // so we can just make the hidden type be `!`.
                    // For backwards compatibility reasons, we fall back to
                    // `()` until we the diverging default is changed.
                    Some(tcx.mk_diverging_default())
                })
                .expect("RPIT always have a hidden type from typeck")
        }
    })
}

fn infer_placeholder_type<'a>(
    tcx: TyCtxt<'a>,
    def_id: LocalDefId,
    body_id: hir::BodyId,
    span: Span,
    item_ident: Ident,
    kind: &'static str,
) -> Ty<'a> {
    // Attempts to make the type nameable by turning FnDefs into FnPtrs.
    struct MakeNameable<'tcx> {
        success: bool,
        tcx: TyCtxt<'tcx>,
    }

    impl<'tcx> MakeNameable<'tcx> {
        fn new(tcx: TyCtxt<'tcx>) -> Self {
            MakeNameable { success: true, tcx }
        }
    }

    impl<'tcx> TypeFolder<'tcx> for MakeNameable<'tcx> {
        fn tcx(&self) -> TyCtxt<'tcx> {
            self.tcx
        }

        fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
            if !self.success {
                return ty;
            }

            match ty.kind() {
                ty::FnDef(def_id, _) => self.tcx.mk_fn_ptr(self.tcx.fn_sig(*def_id)),
                // FIXME: non-capturing closures should also suggest a function pointer
                ty::Closure(..) | ty::Generator(..) => {
                    self.success = false;
                    ty
                }
                _ => ty.super_fold_with(self),
            }
        }
    }

    let ty = tcx.diagnostic_only_typeck(def_id).node_type(body_id.hir_id);

    // If this came from a free `const` or `static mut?` item,
    // then the user may have written e.g. `const A = 42;`.
    // In this case, the parser has stashed a diagnostic for
    // us to improve in typeck so we do that now.
    match tcx.sess.diagnostic().steal_diagnostic(span, StashKey::ItemNoType) {
        Some(mut err) => {
            if !ty.references_error() {
                // Only suggest adding `:` if it was missing (and suggested by parsing diagnostic)
                let colon = if span == item_ident.span.shrink_to_hi() { ":" } else { "" };

                // The parser provided a sub-optimal `HasPlaceholders` suggestion for the type.
                // We are typeck and have the real type, so remove that and suggest the actual type.
                // FIXME(eddyb) this looks like it should be functionality on `Diagnostic`.
                if let Ok(suggestions) = &mut err.suggestions {
                    suggestions.clear();
                }

                // Suggesting unnameable types won't help.
                let mut mk_nameable = MakeNameable::new(tcx);
                let ty = mk_nameable.fold_ty(ty);
                let sugg_ty = if mk_nameable.success { Some(ty) } else { None };
                if let Some(sugg_ty) = sugg_ty {
                    err.span_suggestion(
                        span,
                        &format!("provide a type for the {item}", item = kind),
                        format!("{colon} {sugg_ty}"),
                        Applicability::MachineApplicable,
                    );
                } else {
                    err.span_note(
                        tcx.hir().body(body_id).value.span,
                        &format!("however, the inferred type `{}` cannot be named", ty),
                    );
                }
            }

            err.emit();
        }
        None => {
            let mut diag = bad_placeholder(tcx, vec![span], kind);

            if !ty.references_error() {
                let mut mk_nameable = MakeNameable::new(tcx);
                let ty = mk_nameable.fold_ty(ty);
                let sugg_ty = if mk_nameable.success { Some(ty) } else { None };
                if let Some(sugg_ty) = sugg_ty {
                    diag.span_suggestion(
                        span,
                        "replace with the correct type",
                        sugg_ty,
                        Applicability::MaybeIncorrect,
                    );
                } else {
                    diag.span_note(
                        tcx.hir().body(body_id).value.span,
                        &format!("however, the inferred type `{}` cannot be named", ty),
                    );
                }
            }

            diag.emit();
        }
    }

    // Typeck doesn't expect erased regions to be returned from `type_of`.
    tcx.fold_regions(ty, |r, _| match *r {
        ty::ReErased => tcx.lifetimes.re_static,
        _ => r,
    })
}

fn check_feature_inherent_assoc_ty(tcx: TyCtxt<'_>, span: Span) {
    if !tcx.features().inherent_associated_types {
        use rustc_session::parse::feature_err;
        use rustc_span::symbol::sym;
        feature_err(
            &tcx.sess.parse_sess,
            sym::inherent_associated_types,
            span,
            "inherent associated types are unstable",
        )
        .emit();
    }
}