]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/structured_errors/sized_unsized_cast.rs
Rollup merge of #87685 - notriddle:lazy-from-docs, r=dtolnay
[rust.git] / compiler / rustc_typeck / src / structured_errors / sized_unsized_cast.rs
1 use crate::structured_errors::StructuredDiagnostic;
2 use rustc_errors::{DiagnosticBuilder, DiagnosticId};
3 use rustc_middle::ty::{Ty, TypeFoldable};
4 use rustc_session::Session;
5 use rustc_span::Span;
6
7 pub struct SizedUnsizedCast<'tcx> {
8     pub sess: &'tcx Session,
9     pub span: Span,
10     pub expr_ty: Ty<'tcx>,
11     pub cast_ty: String,
12 }
13
14 impl<'tcx> StructuredDiagnostic<'tcx> for SizedUnsizedCast<'tcx> {
15     fn session(&self) -> &Session {
16         self.sess
17     }
18
19     fn code(&self) -> DiagnosticId {
20         rustc_errors::error_code!(E0607)
21     }
22
23     fn diagnostic_common(&self) -> DiagnosticBuilder<'tcx> {
24         if self.expr_ty.references_error() {
25             self.sess.diagnostic().struct_dummy()
26         } else {
27             self.sess.struct_span_fatal_with_code(
28                 self.span,
29                 &format!(
30                     "cannot cast thin pointer `{}` to fat pointer `{}`",
31                     self.expr_ty, self.cast_ty
32                 ),
33                 self.code(),
34             )
35         }
36     }
37
38     fn diagnostic_extended(&self, mut err: DiagnosticBuilder<'tcx>) -> DiagnosticBuilder<'tcx> {
39         err.help(
40             "Thin pointers are \"simple\" pointers: they are purely a reference to a
41 memory address.
42
43 Fat pointers are pointers referencing \"Dynamically Sized Types\" (also
44 called DST). DST don't have a statically known size, therefore they can
45 only exist behind some kind of pointers that contain additional
46 information. Slices and trait objects are DSTs. In the case of slices,
47 the additional information the fat pointer holds is their size.
48
49 To fix this error, don't try to cast directly between thin and fat
50 pointers.
51
52 For more information about casts, take a look at The Book:
53 https://doc.rust-lang.org/reference/expressions/operator-expr.html#type-cast-expressions",
54         );
55         err
56     }
57 }