frontend 0.4.1

rustc's frontend with no LLVM and no std: parsing through MIR, as a library
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
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
//! Check properties that are required by built-in traits and set
//! up data structures required by type-checking/codegen.

// `#![no_std]`: these arrive with the standard prelude and name no path, so a `std::`
// search cannot see them - and a `#[derive]` can use them without the name appearing
// in this file at all, which is why they are not trimmed by inspection.
use alloc::borrow::ToOwned;
use alloc::boxed::Box;
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use alloc::collections::BTreeMap;

use crate::rustc_data_structures::fx::FxHashSet;
use crate::rustc_errors::{ErrorGuaranteed, MultiSpan};
use crate::rustc_hir as hir;
use crate::rustc_hir::ItemKind;
use crate::rustc_hir::attrs::lang_items::LangItem;
use crate::rustc_hir::def_id::{DefId, LocalDefId};
use crate::rustc_infer::infer::{self, InferCtxt, RegionResolutionError, SubregionOrigin, TyCtxtInferExt};
use crate::rustc_infer::traits::{Obligation, TraitErrors};
use crate::rustc_middle::ty::adjustment::CoerceUnsizedInfo;
use crate::rustc_middle::ty::print::PrintTraitRefExt as _;
use crate::rustc_middle::ty::{
    self, Ty, TyCtxt, TypeVisitableExt, TypingMode, Unnormalized, suggest_constraining_type_params,
};
use crate::rustc_span::{DUMMY_SP, Ident, Span, Symbol, sym};
use crate::rustc_trait_selection::error_reporting::InferCtxtErrorExt;
use crate::rustc_trait_selection::traits::misc::{
    ConstParamTyImplementationError, CopyImplementationError, InfringingFieldsReason,
    type_allowed_to_implement_const_param_ty, type_allowed_to_implement_copy,
};
use crate::rustc_trait_selection::traits::{self, ObligationCause, ObligationCtxt};
use tracing::debug;

use crate::rustc_hir_analysis::diagnostics;

mod coerce_shared;

pub(super) fn check_trait<'tcx>(
    tcx: TyCtxt<'tcx>,
    trait_def_id: DefId,
    impl_def_id: LocalDefId,
    impl_header: ty::ImplTraitHeader<'tcx>,
) -> Result<(), ErrorGuaranteed> {
    let checker = Checker { tcx, impl_def_id, impl_header };
    match tcx.as_lang_item(trait_def_id) {
        Some(LangItem::Drop) => visit_implementation_of_drop(&checker),
        Some(LangItem::AsyncDrop) => visit_implementation_of_drop(&checker),
        Some(LangItem::Copy) => visit_implementation_of_copy(&checker),
        Some(LangItem::Unpin) => visit_implementation_of_unpin(&checker),
        Some(LangItem::ConstParamTy) => visit_implementation_of_const_param_ty(&checker),
        Some(LangItem::CoerceUnsized) => visit_implementation_of_coerce_unsized(&checker),
        Some(LangItem::Reborrow) => visit_implementation_of_reborrow(&checker),
        Some(LangItem::CoerceShared) => visit_implementation_of_coerce_shared(&checker),
        Some(LangItem::DispatchFromDyn) => visit_implementation_of_dispatch_from_dyn(&checker),
        Some(LangItem::CoercePointeeValidated) => {
            visit_implementation_of_coerce_pointee_validity(&checker)
        }
        _ => Ok(()),
    }
}

struct Checker<'tcx> {
    tcx: TyCtxt<'tcx>,
    impl_def_id: LocalDefId,
    impl_header: ty::ImplTraitHeader<'tcx>,
}

fn visit_implementation_of_drop(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
    let tcx = checker.tcx;
    let impl_did = checker.impl_def_id;
    // Destructors only work on local ADT types.
    match checker.impl_header.trait_ref.instantiate_identity().skip_norm_wip().self_ty().kind() {
        ty::Adt(def, _) if def.did().is_local() => return Ok(()),
        ty::Error(_) => return Ok(()),
        _ => {}
    }

    let impl_ = tcx.hir_expect_item(impl_did).expect_impl();

    Err(tcx.dcx().emit_err(diagnostics::DropImplOnWrongItem {
        span: impl_.self_ty.span,
        trait_: tcx.item_name(checker.impl_header.trait_ref.skip_binder().def_id),
    }))
}

fn visit_implementation_of_copy(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
    let tcx = checker.tcx;
    let impl_header = checker.impl_header;
    let impl_did = checker.impl_def_id;
    debug!("visit_implementation_of_copy: impl_did={:?}", impl_did);

    let self_type = impl_header.trait_ref.instantiate_identity().skip_norm_wip().self_ty();
    debug!("visit_implementation_of_copy: self_type={:?} (bound)", self_type);

    let param_env = tcx.param_env(impl_did);
    assert!(!self_type.has_escaping_bound_vars());

    debug!("visit_implementation_of_copy: self_type={:?} (free)", self_type);

    if let ty::ImplPolarity::Negative = impl_header.polarity {
        return Ok(());
    }

    let cause = traits::ObligationCause::misc(DUMMY_SP, impl_did);
    match type_allowed_to_implement_copy(tcx, param_env, self_type, cause, impl_header.safety) {
        Ok(()) => Ok(()),
        Err(CopyImplementationError::InfringingFields(fields)) => {
            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
            Err(infringing_fields_error(
                tcx,
                fields.into_iter().map(|(field, ty, reason)| (tcx.def_span(field.did), ty, reason)),
                LangItem::Copy,
                impl_did,
                span,
            ))
        }
        Err(CopyImplementationError::NotAnAdt) => {
            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
            Err(tcx.dcx().emit_err(diagnostics::CopyImplOnNonAdt { span }))
        }
        Err(CopyImplementationError::HasDestructor(did)) => {
            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
            let impl_ = tcx.def_span(did);
            Err(tcx.dcx().emit_err(diagnostics::CopyImplOnTypeWithDtor { span, impl_ }))
        }
        Err(CopyImplementationError::HasUnsafeFields) => {
            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
            Err(tcx
                .dcx()
                .span_delayed_bug(span, format!("cannot implement `Copy` for `{}`", self_type)))
        }
    }
}

fn visit_implementation_of_unpin(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
    let tcx = checker.tcx;
    let impl_header = checker.impl_header;
    let impl_did = checker.impl_def_id;
    debug!("visit_implementation_of_unpin: impl_did={:?}", impl_did);

    let self_type = impl_header.trait_ref.instantiate_identity().skip_norm_wip().self_ty();
    debug!("visit_implementation_of_unpin: self_type={:?}", self_type);

    let span = tcx.def_span(impl_did);

    if tcx.features().pin_ergonomics() {
        match self_type.kind() {
            // Soundness concerns: a type `T` annotated with `#[pin_v2]` is allowed to project
            // `Pin<&mut T>` to its field `Pin<&mut U>` safely (even if `U: !Unpin`).
            // If `T` is allowed to impl `Unpin` manually (note that `Unpin` is a safe trait,
            // which cannot carry safety properties), then `&mut U` could be obtained from
            // `&mut T` that dereferenced by `Pin<&mut T>`, which breaks the safety contract of
            // `Pin<&mut U>` for `U: !Unpin`.
            ty::Adt(adt, _) if adt.is_pin_project() => {
                return Err(tcx.dcx().emit_err(crate::rustc_hir_analysis::diagnostics::ImplUnpinForPinProjectedType {
                    span,
                    adt_span: tcx.def_span(adt.did()),
                    adt_name: tcx.item_name(adt.did()),
                }));
            }
            ty::Adt(_, _) => {}
            // `extern type`s have no fields, so they can't be structurally pinned.
            ty::Foreign(_) => {}
            _ => {
                return Err(tcx.dcx().span_delayed_bug(span, "impl of `Unpin` for a non-adt type"));
            }
        };
    }
    Ok(())
}

fn visit_implementation_of_const_param_ty(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
    let tcx = checker.tcx;
    let header = checker.impl_header;
    let impl_did = checker.impl_def_id;
    let self_type = header.trait_ref.instantiate_identity().skip_norm_wip().self_ty();
    assert!(!self_type.has_escaping_bound_vars());

    let param_env = tcx.param_env(impl_did);

    if let ty::ImplPolarity::Negative = header.polarity {
        return Ok(());
    }

    if tcx.features().const_param_ty_unchecked() {
        return Ok(());
    }

    if !tcx.features().adt_const_params() {
        match *self_type.kind() {
            ty::Adt(adt, _) if adt.is_struct() => {
                let struct_vis = tcx.visibility(adt.did());
                for variant in adt.variants() {
                    for field in &variant.fields {
                        if struct_vis.greater_than(field.vis, tcx) {
                            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
                            return Err(tcx
                                .dcx()
                                .emit_err(diagnostics::ConstParamTyFieldVisMismatch { span }));
                        }
                    }
                }
            }

            _ => {}
        }
    }

    let cause = traits::ObligationCause::misc(DUMMY_SP, impl_did);
    match type_allowed_to_implement_const_param_ty(tcx, param_env, self_type, cause) {
        Ok(()) => Ok(()),
        Err(ConstParamTyImplementationError::InfrigingFields(fields)) => {
            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
            Err(infringing_fields_error(
                tcx,
                fields.into_iter().map(|(field, ty, reason)| (tcx.def_span(field.did), ty, reason)),
                LangItem::ConstParamTy,
                impl_did,
                span,
            ))
        }
        Err(ConstParamTyImplementationError::NotAnAdtOrBuiltinAllowed) => {
            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
            Err(tcx.dcx().emit_err(diagnostics::ConstParamTyImplOnNonAdt { span }))
        }
        Err(ConstParamTyImplementationError::NonExhaustive(attr_span)) => {
            let defn_span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
            Err(tcx
                .dcx()
                .emit_err(diagnostics::ConstParamTyImplOnNonExhaustive { defn_span, attr_span }))
        }
        Err(ConstParamTyImplementationError::InvalidInnerTyOfBuiltinTy(infringing_tys)) => {
            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
            Err(infringing_fields_error(
                tcx,
                infringing_tys.into_iter().map(|(ty, reason)| (span, ty, reason)),
                LangItem::ConstParamTy,
                impl_did,
                span,
            ))
        }
        Err(ConstParamTyImplementationError::UnsizedConstParamsFeatureRequired) => {
            let span = tcx.hir_expect_item(impl_did).expect_impl().self_ty.span;
            Err(tcx.dcx().emit_err(diagnostics::ConstParamTyImplOnUnsized { span }))
        }
    }
}

fn visit_implementation_of_coerce_unsized(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
    let tcx = checker.tcx;
    let impl_did = checker.impl_def_id;
    debug!("visit_implementation_of_coerce_unsized: impl_did={:?}", impl_did);

    // Just compute this for the side-effects, in particular reporting
    // errors; other parts of the code may demand it for the info of
    // course.
    tcx.ensure_result().coerce_unsized_info(impl_did)
}

fn visit_implementation_of_reborrow(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
    let tcx = checker.tcx;
    let impl_did = checker.impl_def_id;
    debug!("visit_implementation_of_reborrow: impl_did={:?}", impl_did);

    // Just compute this for the side-effects, in particular reporting
    // errors; other parts of the code may demand it for the info of
    // course.
    reborrow_info(tcx, impl_did)
}

fn visit_implementation_of_coerce_shared(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
    let tcx = checker.tcx;
    let impl_did = checker.impl_def_id;
    debug!("visit_implementation_of_coerce_shared: impl_did={:?}", impl_did);

    // Just compute this for the side-effects, in particular reporting
    // errors; other parts of the code may demand it for the info of
    // course.
    coerce_shared::coerce_shared_info(tcx, impl_did)
}

fn is_from_coerce_pointee_derive(tcx: TyCtxt<'_>, span: Span) -> bool {
    span.ctxt()
        .outer_expn_data()
        .macro_def_id
        .is_some_and(|def_id| tcx.is_diagnostic_item(sym::CoercePointee, def_id))
}

fn visit_implementation_of_dispatch_from_dyn(checker: &Checker<'_>) -> Result<(), ErrorGuaranteed> {
    let tcx = checker.tcx;
    let impl_did = checker.impl_def_id;
    let trait_ref = checker.impl_header.trait_ref.instantiate_identity().skip_norm_wip();
    debug!("visit_implementation_of_dispatch_from_dyn: impl_did={:?}", impl_did);

    let span = tcx.def_span(impl_did);
    let trait_name = "DispatchFromDyn";

    let source = trait_ref.self_ty();
    let target = {
        assert!(tcx.is_lang_item(trait_ref.def_id, LangItem::DispatchFromDyn));

        trait_ref.args.type_at(1)
    };

    // Check `CoercePointee` impl is WF -- if not, then there's no reason to report
    // redundant errors for `DispatchFromDyn`. This is best effort, though.
    let mut res = Ok(());
    tcx.for_each_relevant_impl(
        tcx.require_lang_item(LangItem::CoerceUnsized, span),
        source,
        |impl_def_id| {
            res = res.and(tcx.ensure_result().coerce_unsized_info(impl_def_id));
        },
    );
    res?;

    debug!("visit_implementation_of_dispatch_from_dyn: {:?} -> {:?}", source, target);

    let param_env = tcx.param_env(impl_did);

    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
    let cause = ObligationCause::misc(span, impl_did);

    // Later parts of the compiler rely on all DispatchFromDyn types to be ABI-compatible with raw
    // pointers. This is enforced here: we only allow impls for references, raw pointers, and things
    // that are effectively repr(transparent) newtypes around types that already hav a
    // DispatchedFromDyn impl. We cannot literally use repr(transparent) on those types since some
    // of them support an allocator, but we ensure that for the cases where the type implements this
    // trait, they *do* satisfy the repr(transparent) rules, and then we assume that everything else
    // in the compiler (in particular, all the call ABI logic) will treat them as repr(transparent)
    // even if they do not carry that attribute.
    match (source.kind(), target.kind()) {
        (&ty::Pat(_, pat_a), &ty::Pat(_, pat_b)) => {
            if pat_a != pat_b {
                return Err(tcx.dcx().emit_err(diagnostics::CoerceSamePatKind {
                    span,
                    trait_name,
                    pat_a: pat_a.to_string(),
                    pat_b: pat_b.to_string(),
                }));
            }
            Ok(())
        }

        (&ty::Ref(r_a, _, mutbl_a), ty::Ref(r_b, _, mutbl_b))
            if r_a == *r_b && mutbl_a == *mutbl_b =>
        {
            Ok(())
        }
        (&ty::RawPtr(_, a_mutbl), &ty::RawPtr(_, b_mutbl)) if a_mutbl == b_mutbl => Ok(()),
        (&ty::Adt(def_a, args_a), &ty::Adt(def_b, args_b))
            if def_a.is_struct() && def_b.is_struct() =>
        {
            if def_a != def_b {
                let source_path = tcx.def_path_str(def_a.did());
                let target_path = tcx.def_path_str(def_b.did());
                return Err(tcx.dcx().emit_err(diagnostics::CoerceSameStruct {
                    span,
                    trait_name,
                    note: true,
                    source_path,
                    target_path,
                }));
            }

            if def_a.repr().c() || def_a.repr().packed() {
                return Err(tcx.dcx().emit_err(diagnostics::DispatchFromDynRepr { span }));
            }

            let fields = &def_a.non_enum_variant().fields;

            let mut res = Ok(());
            let coerced_fields = fields
                .iter_enumerated()
                .filter_map(|(i, field)| {
                    // Ignore PhantomData fields
                    let unnormalized_ty = tcx.type_of(field.did).instantiate_identity();
                    if tcx
                        .try_normalize_erasing_regions(
                            ty::TypingEnv::non_body_analysis(tcx, def_a.did()),
                            unnormalized_ty,
                        )
                        .unwrap_or(unnormalized_ty.skip_norm_wip())
                        .is_phantom_data()
                    {
                        return None;
                    }

                    let ty_a = field.ty(tcx, args_a).skip_norm_wip();
                    let ty_b = field.ty(tcx, args_b).skip_norm_wip();

                    // FIXME: We could do normalization here, but is it really worth it?
                    if ty_a == ty_b {
                        // Allow 1-ZSTs that don't mention type params.
                        //
                        // Allowing type params here would allow us to possibly transmute
                        // between ZSTs, which may be used to create library unsoundness.
                        if let Ok(layout) =
                            tcx.layout_of(infcx.typing_env(param_env).as_query_input(ty_a))
                            && layout.is_1zst()
                            && !ty_a.has_non_region_param()
                        {
                            // ignore 1-ZST fields
                            return None;
                        }

                        res = Err(tcx.dcx().emit_err(diagnostics::DispatchFromDynZST {
                            span,
                            name: field.ident(tcx),
                            ty: ty_a,
                        }));

                        None
                    } else {
                        Some((i, ty_a, ty_b, tcx.def_span(field.did)))
                    }
                })
                .collect::<Vec<_>>();
            res?;

            if coerced_fields.is_empty() {
                return Err(tcx.dcx().emit_err(diagnostics::CoerceNoField {
                    span,
                    trait_name,
                    note: true,
                }));
            } else if let &[(_, ty_a, ty_b, field_span)] = &coerced_fields[..] {
                let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
                ocx.register_obligation(Obligation::new(
                    tcx,
                    cause.clone(),
                    param_env,
                    ty::TraitRef::new(tcx, trait_ref.def_id, [ty_a, ty_b]),
                ));
                let errors = ocx.evaluate_obligations_error_on_ambiguity();
                if let TraitErrors::HasErrors(errors) = errors {
                    if is_from_coerce_pointee_derive(tcx, span) {
                        return Err(tcx.dcx().emit_err(diagnostics::CoerceFieldValidity {
                            span,
                            trait_name,
                            ty: trait_ref.self_ty(),
                            field_span,
                            field_ty: ty_a,
                        }));
                    } else {
                        return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
                    }
                }

                // Finally, resolve all regions.
                ocx.resolve_regions_and_report_errors(impl_did, param_env, [])?;

                Ok(())
            } else {
                return Err(tcx.dcx().emit_err(diagnostics::CoerceMulti {
                    span,
                    trait_name,
                    number: coerced_fields.len(),
                    fields: coerced_fields.iter().map(|(_, _, _, s)| *s).collect::<Vec<_>>().into(),
                }));
            }
        }
        _ => Err(tcx.dcx().emit_err(diagnostics::CoerceUnsizedNonStruct { span, trait_name })),
    }
}

pub(crate) fn reborrow_info<'tcx>(
    tcx: TyCtxt<'tcx>,
    impl_did: LocalDefId,
) -> Result<(), ErrorGuaranteed> {
    debug!("compute_reborrow_info(impl_did={:?})", impl_did);
    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
    let span = tcx.def_span(impl_did);
    let trait_name = "Reborrow";

    let reborrow_trait = tcx.require_lang_item(LangItem::Reborrow, span);

    let source = tcx.type_of(impl_did).instantiate_identity().skip_norm_wip();
    let trait_ref = tcx.impl_trait_ref(impl_did).instantiate_identity().skip_norm_wip();

    if trait_impl_lifetime_params_count(tcx, impl_did) != 1 {
        return Err(tcx
            .dcx()
            .emit_err(diagnostics::CoerceSharedNotSingleLifetimeParam { span, trait_name }));
    }

    assert_eq!(trait_ref.def_id, reborrow_trait);
    let param_env = tcx.param_env(impl_did);
    assert!(!source.has_escaping_bound_vars());

    let (def, args) = match source.kind() {
        &ty::Adt(def, args) if def.is_struct() => (def, args),
        _ => {
            // Note: reusing error here as it takes trait_name as argument.
            return Err(tcx
                .dcx()
                .emit_err(diagnostics::CoerceUnsizedNonStruct { span, trait_name }));
        }
    };

    let lifetimes_count = generic_lifetime_params_count(args);
    let data_fields = collect_reborrow_data_fields(tcx, def, args);

    if lifetimes_count != 1 {
        let item = tcx.hir_expect_item(impl_did);
        let _span = if let ItemKind::Impl(hir::Impl { of_trait: Some(of_trait), .. }) = &item.kind {
            of_trait.trait_ref.path.span
        } else {
            tcx.def_span(impl_did)
        };

        return Err(tcx.dcx().emit_err(diagnostics::CoerceSharedMulti { span, trait_name }));
    }

    if data_fields.is_empty() {
        return Ok(());
    }

    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
    // We've found some data fields. They must all be either be Copy or Reborrow.
    for mut field in data_fields {
        field.ty = ocx
            .deeply_normalize(
                &traits::ObligationCause::misc(field.span, impl_did),
                param_env,
                Unnormalized::new_wip(field.ty),
            )
            .map_err(|errors| infcx.err_ctxt().report_fulfillment_errors(errors))?;
        if field_type_is_reborrow(
            tcx,
            &infcx,
            reborrow_trait,
            impl_did,
            param_env,
            field.ty,
            field.span,
        ) {
            // Field implements Reborrow, check remaining fields.
            continue;
        }

        // Field does not implement Reborrow: it must be Copy.
        assert_field_type_is_copy(tcx, &infcx, impl_did, param_env, field.ty, field.span)?;
    }

    Ok(())
}

fn trait_impl_lifetime_params_count(tcx: TyCtxt<'_>, did: LocalDefId) -> usize {
    tcx.generics_of(did)
        .own_params
        .iter()
        .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
        .count()
}

fn generic_lifetime_params_count(args: &[ty::GenericArg<'_>]) -> usize {
    args.iter().filter(|arg| arg.as_region().is_some()).count()
}

#[derive(Clone, Copy)]
struct ReborrowDataField<'tcx> {
    ident: Ident,
    name: Symbol,
    ty: Ty<'tcx>,
    span: Span,
}

fn collect_reborrow_data_fields<'tcx>(
    tcx: TyCtxt<'tcx>,
    def: ty::AdtDef<'tcx>,
    args: ty::GenericArgsRef<'tcx>,
) -> Vec<ReborrowDataField<'tcx>> {
    def.non_enum_variant()
        .fields
        .iter()
        .filter_map(|field| {
            let ty = field.ty(tcx, args).skip_norm_wip();
            (!ty.is_phantom_data()).then_some(ReborrowDataField {
                ident: field.ident(tcx),
                name: field.name,
                ty,
                span: tcx.def_span(field.did),
            })
        })
        .collect()
}

fn field_type_is_reborrow<'tcx>(
    tcx: TyCtxt<'tcx>,
    infcx: &InferCtxt<'tcx>,
    reborrow_trait: DefId,
    impl_did: LocalDefId,
    param_env: ty::ParamEnv<'tcx>,
    ty: Ty<'tcx>,
    span: Span,
) -> bool {
    if ty.ref_mutability() == Some(ty::Mutability::Mut) {
        // Mutable references are Reborrow but not really.
        return true;
    }

    let ocx = ObligationCtxt::new(infcx);
    let cause = traits::ObligationCause::misc(span, impl_did);
    ocx.register_obligation(Obligation::new(
        tcx,
        cause,
        param_env,
        ty::TraitRef::new(tcx, reborrow_trait, [ty]),
    ));
    ocx.evaluate_obligations_error_on_ambiguity().no_errors()
}

fn field_type_is_copy<'tcx>(
    tcx: TyCtxt<'tcx>,
    infcx: &InferCtxt<'tcx>,
    impl_did: LocalDefId,
    param_env: ty::ParamEnv<'tcx>,
    ty: Ty<'tcx>,
    span: Span,
) -> bool {
    let copy_trait = tcx.require_lang_item(LangItem::Copy, span);
    let ocx = ObligationCtxt::new(infcx);
    let cause = traits::ObligationCause::misc(span, impl_did);
    ocx.register_obligation(Obligation::new(
        tcx,
        cause,
        param_env,
        ty::TraitRef::new(tcx, copy_trait, [ty]),
    ));
    ocx.evaluate_obligations_error_on_ambiguity().no_errors()
}

fn assert_field_type_is_copy<'tcx>(
    tcx: TyCtxt<'tcx>,
    infcx: &InferCtxt<'tcx>,
    impl_did: LocalDefId,
    param_env: ty::ParamEnv<'tcx>,
    ty: Ty<'tcx>,
    span: Span,
) -> Result<(), ErrorGuaranteed> {
    let copy_trait = tcx.require_lang_item(LangItem::Copy, span);
    let ocx = ObligationCtxt::new_with_diagnostics(infcx);
    let cause = traits::ObligationCause::misc(span, impl_did);
    let obligation =
        Obligation::new(tcx, cause, param_env, ty::TraitRef::new(tcx, copy_trait, [ty]));
    ocx.register_obligation(obligation);
    let errors = ocx.evaluate_obligations_error_on_ambiguity();

    if let TraitErrors::HasErrors(errors) = errors {
        Err(infcx.err_ctxt().report_fulfillment_errors(errors))
    } else {
        Ok(())
    }
}

pub(crate) fn coerce_unsized_info<'tcx>(
    tcx: TyCtxt<'tcx>,
    impl_did: LocalDefId,
) -> Result<CoerceUnsizedInfo, ErrorGuaranteed> {
    debug!("compute_coerce_unsized_info(impl_did={:?})", impl_did);
    let span = tcx.def_span(impl_did);
    let trait_name = "CoerceUnsized";

    let coerce_unsized_trait = tcx.require_lang_item(LangItem::CoerceUnsized, span);
    let unsize_trait = tcx.require_lang_item(LangItem::Unsize, span);

    let source = tcx.type_of(impl_did).instantiate_identity().skip_norm_wip();
    let trait_ref = tcx.impl_trait_ref(impl_did).instantiate_identity().skip_norm_wip();

    assert_eq!(trait_ref.def_id, coerce_unsized_trait);
    let target = trait_ref.args.type_at(1);
    debug!("visit_implementation_of_coerce_unsized: {:?} -> {:?} (bound)", source, target);

    let param_env = tcx.param_env(impl_did);
    assert!(!source.has_escaping_bound_vars());

    debug!("visit_implementation_of_coerce_unsized: {:?} -> {:?} (free)", source, target);

    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
    let cause = ObligationCause::misc(span, impl_did);
    let check_mutbl = |mt_a: ty::TypeAndMut<'tcx>,
                       mt_b: ty::TypeAndMut<'tcx>,
                       mk_ptr: &dyn Fn(Ty<'tcx>) -> Ty<'tcx>| {
        if mt_a.mutbl < mt_b.mutbl {
            infcx
                .err_ctxt()
                .report_mismatched_types(
                    &cause,
                    param_env,
                    mk_ptr(mt_b.ty),
                    target,
                    ty::error::TypeError::Mutability,
                )
                .emit();
        }
        (mt_a.ty, mt_b.ty, unsize_trait, None, span)
    };
    let (source, target, trait_def_id, kind, field_span) = match (source.kind(), target.kind()) {
        (&ty::Pat(ty_a, pat_a), &ty::Pat(ty_b, pat_b)) => {
            if pat_a != pat_b {
                return Err(tcx.dcx().emit_err(diagnostics::CoerceSamePatKind {
                    span,
                    trait_name,
                    pat_a: pat_a.to_string(),
                    pat_b: pat_b.to_string(),
                }));
            }
            (ty_a, ty_b, coerce_unsized_trait, None, span)
        }

        (&ty::Ref(r_a, ty_a, mutbl_a), &ty::Ref(r_b, ty_b, mutbl_b)) => {
            infcx.sub_regions(
                SubregionOrigin::RelateObjectBound(span),
                r_b,
                r_a,
                ty::VisibleForLeakCheck::Yes,
            );
            let mt_a = ty::TypeAndMut { ty: ty_a, mutbl: mutbl_a };
            let mt_b = ty::TypeAndMut { ty: ty_b, mutbl: mutbl_b };
            check_mutbl(mt_a, mt_b, &|ty| Ty::new_imm_ref(tcx, r_b, ty))
        }

        (&ty::Ref(_, ty_a, mutbl_a), &ty::RawPtr(ty_b, mutbl_b))
        | (&ty::RawPtr(ty_a, mutbl_a), &ty::RawPtr(ty_b, mutbl_b)) => {
            let mt_a = ty::TypeAndMut { ty: ty_a, mutbl: mutbl_a };
            let mt_b = ty::TypeAndMut { ty: ty_b, mutbl: mutbl_b };
            check_mutbl(mt_a, mt_b, &|ty| Ty::new_imm_ptr(tcx, ty))
        }

        (&ty::Adt(def_a, args_a), &ty::Adt(def_b, args_b))
            if def_a.is_struct() && def_b.is_struct() =>
        {
            if def_a != def_b {
                let source_path = tcx.def_path_str(def_a.did());
                let target_path = tcx.def_path_str(def_b.did());
                return Err(tcx.dcx().emit_err(diagnostics::CoerceSameStruct {
                    span,
                    trait_name,
                    note: true,
                    source_path,
                    target_path,
                }));
            }

            // Here we are considering a case of converting
            // `S<P0...Pn>` to `S<Q0...Qn>`. As an example, let's imagine a struct `Foo<T, U>`,
            // which acts like a pointer to `U`, but carries along some extra data of type `T`:
            //
            //     struct Foo<T, U> {
            //         extra: T,
            //         ptr: *mut U,
            //     }
            //
            // We might have an impl that allows (e.g.) `Foo<T, [i32; 3]>` to be unsized
            // to `Foo<T, [i32]>`. That impl would look like:
            //
            //   impl<T, U: Unsize<V>, V> CoerceUnsized<Foo<T, V>> for Foo<T, U> {}
            //
            // Here `U = [i32; 3]` and `V = [i32]`. At runtime,
            // when this coercion occurs, we would be changing the
            // field `ptr` from a thin pointer of type `*mut [i32;
            // 3]` to a wide pointer of type `*mut [i32]` (with
            // extra data `3`). **The purpose of this check is to
            // make sure that we know how to do this conversion.**
            //
            // To check if this impl is legal, we would walk down
            // the fields of `Foo` and consider their types with
            // both generic parameters. We are looking to find that
            // exactly one (non-phantom) field has changed its
            // type, which we will expect to be the pointer that
            // is becoming fat (we could probably generalize this
            // to multiple thin pointers of the same type becoming
            // fat, but we don't). In this case:
            //
            // - `extra` has type `T` before and type `T` after
            // - `ptr` has type `*mut U` before and type `*mut V` after
            //
            // Since just one field changed, we would then check
            // that `*mut U: CoerceUnsized<*mut V>` is implemented
            // (in other words, that we know how to do this
            // conversion). This will work out because `U:
            // Unsize<V>`, and we have a builtin rule that `*mut
            // U` can be coerced to `*mut V` if `U: Unsize<V>`.
            let fields = &def_a.non_enum_variant().fields;
            let diff_fields = fields
                .iter_enumerated()
                .filter_map(|(i, f)| {
                    let (a, b) =
                        (f.ty(tcx, args_a).skip_norm_wip(), f.ty(tcx, args_b).skip_norm_wip());

                    // Ignore PhantomData fields
                    let unnormalized_ty = tcx.type_of(f.did).instantiate_identity();
                    if tcx
                        .try_normalize_erasing_regions(
                            ty::TypingEnv::non_body_analysis(tcx, def_a.did()),
                            unnormalized_ty,
                        )
                        .unwrap_or(unnormalized_ty.skip_norm_wip())
                        .is_phantom_data()
                    {
                        return None;
                    }

                    // Ignore fields that aren't changed; it may
                    // be that we could get away with subtyping or
                    // something more accepting, but we use
                    // equality because we want to be able to
                    // perform this check without computing
                    // variance or constraining opaque types' hidden types.
                    // (This is because we may have to evaluate constraint
                    // expressions in the course of execution.)
                    // See e.g., #41936.
                    if a == b {
                        return None;
                    }

                    // Collect up all fields that were significantly changed
                    // i.e., those that contain T in coerce_unsized T -> U
                    Some((i, a, b, tcx.def_span(f.did)))
                })
                .collect::<Vec<_>>();

            if diff_fields.is_empty() {
                return Err(tcx.dcx().emit_err(diagnostics::CoerceNoField {
                    span,
                    trait_name,
                    note: true,
                }));
            } else if diff_fields.len() > 1 {
                let item = tcx.hir_expect_item(impl_did);
                let span = if let ItemKind::Impl(hir::Impl { of_trait: Some(of_trait), .. }) =
                    &item.kind
                {
                    of_trait.trait_ref.path.span
                } else {
                    tcx.def_span(impl_did)
                };

                return Err(tcx.dcx().emit_err(diagnostics::CoerceMulti {
                    span,
                    trait_name,
                    number: diff_fields.len(),
                    fields: diff_fields.iter().map(|(_, _, _, s)| *s).collect::<Vec<_>>().into(),
                }));
            }

            let (i, a, b, field_span) = diff_fields[0];
            let kind = ty::adjustment::CustomCoerceUnsized::Struct(i);
            (a, b, coerce_unsized_trait, Some(kind), field_span)
        }

        _ => {
            return Err(tcx
                .dcx()
                .emit_err(diagnostics::CoerceUnsizedNonStruct { span, trait_name }));
        }
    };

    // Register an obligation for `A: Trait<B>`.
    let ocx = ObligationCtxt::new_with_diagnostics(&infcx);
    let cause = traits::ObligationCause::misc(span, impl_did);
    let obligation = Obligation::new(
        tcx,
        cause,
        param_env,
        ty::TraitRef::new(tcx, trait_def_id, [source, target]),
    );
    ocx.register_obligation(obligation);
    let errors = ocx.evaluate_obligations_error_on_ambiguity();

    if let TraitErrors::HasErrors(errors) = errors {
        if is_from_coerce_pointee_derive(tcx, span) {
            return Err(tcx.dcx().emit_err(diagnostics::CoerceFieldValidity {
                span,
                trait_name,
                ty: trait_ref.self_ty(),
                field_span,
                field_ty: source,
            }));
        } else {
            return Err(infcx.err_ctxt().report_fulfillment_errors(errors));
        }
    }

    // Finally, resolve all regions.
    ocx.resolve_regions_and_report_errors(impl_did, param_env, [])?;

    Ok(CoerceUnsizedInfo { custom_kind: kind })
}

fn infringing_fields_error<'tcx>(
    tcx: TyCtxt<'tcx>,
    infringing_tys: impl Iterator<Item = (Span, Ty<'tcx>, InfringingFieldsReason<'tcx>)>,
    lang_item: LangItem,
    impl_did: LocalDefId,
    impl_span: Span,
) -> ErrorGuaranteed {
    let trait_did = tcx.require_lang_item(lang_item, impl_span);

    let trait_name = tcx.def_path_str(trait_did);

    // We'll try to suggest constraining type parameters to fulfill the requirements of
    // their `Copy` implementation.
    let mut errors: BTreeMap<_, Vec<_>> = Default::default();
    let mut bounds = vec![];

    let mut seen_tys = FxHashSet::default();

    let mut label_spans = Vec::new();

    for (span, ty, reason) in infringing_tys {
        // Only report an error once per type.
        if !seen_tys.insert(ty) {
            continue;
        }

        label_spans.push(span);

        match reason {
            InfringingFieldsReason::Fulfill(fulfillment_errors) => {
                for error in fulfillment_errors {
                    let error_predicate = error.obligation.predicate;
                    // Only note if it's not the root obligation, otherwise it's trivial and
                    // should be self-explanatory (i.e. a field literally doesn't implement Copy).

                    // FIXME: This error could be more descriptive, especially if the error_predicate
                    // contains a foreign type or if it's a deeply nested type...
                    if error_predicate != error.root_obligation.predicate {
                        errors
                            .entry((ty.to_string(), error_predicate.to_string()))
                            .or_default()
                            .push(error.obligation.cause.span);
                    }
                    if let ty::PredicateKind::Clause(ty::ClauseKind::Trait(ty::TraitClause {
                        trait_ref,
                        polarity: ty::ClausePolarity::Positive,
                        ..
                    })) = error_predicate.kind().skip_binder()
                    {
                        let ty = trait_ref.self_ty();
                        if let ty::Param(_) = ty.kind() {
                            bounds.push((
                                format!("{ty}"),
                                trait_ref.print_trait_sugared().to_string(),
                                Some(trait_ref.def_id),
                            ));
                        }
                    }
                }
            }
            InfringingFieldsReason::Regions(region_errors) => {
                for error in region_errors {
                    let ty = ty.to_string();
                    match error {
                        RegionResolutionError::ConcreteFailure(origin, a, b) => {
                            let predicate = format!("{b}: {a}");
                            errors
                                .entry((ty.clone(), predicate.clone()))
                                .or_default()
                                .push(origin.span());
                            if let ty::RegionKind::ReEarlyParam(ebr) = b.kind()
                                && ebr.is_named()
                            {
                                bounds.push((b.to_string(), a.to_string(), None));
                            }
                        }
                        RegionResolutionError::GenericBoundFailure(origin, a, b) => {
                            let predicate = format!("{a}: {b}");
                            errors
                                .entry((ty.clone(), predicate.clone()))
                                .or_default()
                                .push(origin.span());
                            if let infer::region_constraints::GenericKind::Param(_) = a {
                                bounds.push((a.to_string(), b.to_string(), None));
                            }
                        }
                        _ => continue,
                    }
                }
            }
        }
    }
    let mut notes = Vec::new();
    for ((ty, error_predicate), spans) in errors {
        let span: MultiSpan = spans.into();
        notes.push(diagnostics::ImplForTyRequires {
            span,
            error_predicate,
            trait_name: trait_name.clone(),
            ty,
        });
    }

    let mut err = tcx.dcx().create_err(diagnostics::TraitCannotImplForTy {
        span: impl_span,
        trait_name,
        label_spans,
        notes,
    });

    suggest_constraining_type_params(
        tcx,
        tcx.hir_get_generics(impl_did).expect("impls always have generics"),
        &mut err,
        bounds
            .iter()
            .map(|(param, constraint, def_id)| (param.as_str(), constraint.as_str(), *def_id)),
        None,
    );

    err.emit()
}

fn visit_implementation_of_coerce_pointee_validity(
    checker: &Checker<'_>,
) -> Result<(), ErrorGuaranteed> {
    let tcx = checker.tcx;
    let self_ty =
        tcx.impl_trait_ref(checker.impl_def_id).instantiate_identity().skip_norm_wip().self_ty();
    let span = tcx.def_span(checker.impl_def_id);
    if !tcx.is_builtin_derived(checker.impl_def_id.into()) {
        return Err(tcx.dcx().emit_err(diagnostics::CoercePointeeNoUserValidityAssertion { span }));
    }
    let ty::Adt(def, _args) = self_ty.kind() else {
        return Err(tcx.dcx().emit_err(diagnostics::CoercePointeeNotConcreteType { span }));
    };
    let did = def.did();
    // Now get a more precise span of the `struct`.
    let span = tcx.def_span(did);
    if !def.is_struct() {
        return Err(tcx
            .dcx()
            .emit_err(diagnostics::CoercePointeeNotStruct { span, kind: def.descr().into() }));
    }
    if !def.repr().transparent() {
        return Err(tcx.dcx().emit_err(diagnostics::CoercePointeeNotTransparent { span }));
    }
    if def.all_fields().next().is_none() {
        return Err(tcx.dcx().emit_err(diagnostics::CoercePointeeNoField { span }));
    }
    Ok(())
}