summaryrefslogtreecommitdiffstats
path: root/compiler/rustc_macros/src/diagnostics/diagnostic.rs
blob: 6b5b8b5932018abfb6e5d54b55dc38853885b0a5 (plain)
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
#![deny(unused_must_use)]

use crate::diagnostics::diagnostic_builder::{DiagnosticDeriveBuilder, DiagnosticDeriveKind};
use crate::diagnostics::error::{span_err, DiagnosticDeriveError};
use crate::diagnostics::utils::{build_field_mapping, SetOnce};
use proc_macro2::TokenStream;
use quote::quote;
use syn::spanned::Spanned;
use synstructure::Structure;

/// The central struct for constructing the `into_diagnostic` method from an annotated struct.
pub(crate) struct SessionDiagnosticDerive<'a> {
    structure: Structure<'a>,
    sess: syn::Ident,
    builder: DiagnosticDeriveBuilder,
}

impl<'a> SessionDiagnosticDerive<'a> {
    pub(crate) fn new(diag: syn::Ident, sess: syn::Ident, structure: Structure<'a>) -> Self {
        Self {
            builder: DiagnosticDeriveBuilder {
                diag,
                fields: build_field_mapping(&structure),
                kind: None,
                code: None,
                slug: None,
            },
            sess,
            structure,
        }
    }

    pub(crate) fn into_tokens(self) -> TokenStream {
        let SessionDiagnosticDerive { mut structure, sess, mut builder } = self;

        let ast = structure.ast();
        let (implementation, param_ty) = {
            if let syn::Data::Struct(..) = ast.data {
                let preamble = builder.preamble(&structure);
                let (attrs, args) = builder.body(&mut structure);

                let span = ast.span().unwrap();
                let diag = &builder.diag;
                let init = match (builder.kind.value(), builder.slug.value()) {
                    (None, _) => {
                        span_err(span, "diagnostic kind not specified")
                            .help("use the `#[error(...)]` attribute to create an error")
                            .emit();
                        return DiagnosticDeriveError::ErrorHandled.to_compile_error();
                    }
                    (Some(kind), None) => {
                        span_err(span, "diagnostic slug not specified")
                            .help(&format!(
                                "specify the slug as the first argument to the attribute, such as \
                                 `#[{}(typeck::example_error)]`",
                                kind.descr()
                            ))
                            .emit();
                        return DiagnosticDeriveError::ErrorHandled.to_compile_error();
                    }
                    (Some(DiagnosticDeriveKind::Lint), _) => {
                        span_err(span, "only `#[error(..)]` and `#[warning(..)]` are supported")
                            .help("use the `#[error(...)]` attribute to create a error")
                            .emit();
                        return DiagnosticDeriveError::ErrorHandled.to_compile_error();
                    }
                    (Some(DiagnosticDeriveKind::Error), Some(slug)) => {
                        quote! {
                            let mut #diag = #sess.struct_err(rustc_errors::fluent::#slug);
                        }
                    }
                    (Some(DiagnosticDeriveKind::Warn), Some(slug)) => {
                        quote! {
                            let mut #diag = #sess.struct_warn(rustc_errors::fluent::#slug);
                        }
                    }
                };

                let implementation = quote! {
                    #init
                    #preamble
                    match self {
                        #attrs
                    }
                    match self {
                        #args
                    }
                    #diag
                };
                let param_ty = match builder.kind {
                    Some((DiagnosticDeriveKind::Error, _)) => {
                        quote! { rustc_errors::ErrorGuaranteed }
                    }
                    Some((DiagnosticDeriveKind::Lint | DiagnosticDeriveKind::Warn, _)) => {
                        quote! { () }
                    }
                    _ => unreachable!(),
                };

                (implementation, param_ty)
            } else {
                span_err(
                    ast.span().unwrap(),
                    "`#[derive(SessionDiagnostic)]` can only be used on structs",
                )
                .emit();

                let implementation = DiagnosticDeriveError::ErrorHandled.to_compile_error();
                let param_ty = quote! { rustc_errors::ErrorGuaranteed };
                (implementation, param_ty)
            }
        };

        structure.gen_impl(quote! {
            gen impl<'__session_diagnostic_sess> rustc_session::SessionDiagnostic<'__session_diagnostic_sess, #param_ty>
                    for @Self
            {
                fn into_diagnostic(
                    self,
                    #sess: &'__session_diagnostic_sess rustc_session::parse::ParseSess
                ) -> rustc_errors::DiagnosticBuilder<'__session_diagnostic_sess, #param_ty> {
                    use rustc_errors::IntoDiagnosticArg;
                    #implementation
                }
            }
        })
    }
}

/// The central struct for constructing the `decorate_lint` method from an annotated struct.
pub(crate) struct LintDiagnosticDerive<'a> {
    structure: Structure<'a>,
    builder: DiagnosticDeriveBuilder,
}

impl<'a> LintDiagnosticDerive<'a> {
    pub(crate) fn new(diag: syn::Ident, structure: Structure<'a>) -> Self {
        Self {
            builder: DiagnosticDeriveBuilder {
                diag,
                fields: build_field_mapping(&structure),
                kind: None,
                code: None,
                slug: None,
            },
            structure,
        }
    }

    pub(crate) fn into_tokens(self) -> TokenStream {
        let LintDiagnosticDerive { mut structure, mut builder } = self;

        let ast = structure.ast();
        let implementation = {
            if let syn::Data::Struct(..) = ast.data {
                let preamble = builder.preamble(&structure);
                let (attrs, args) = builder.body(&mut structure);

                let diag = &builder.diag;
                let span = ast.span().unwrap();
                let init = match (builder.kind.value(), builder.slug.value()) {
                    (None, _) => {
                        span_err(span, "diagnostic kind not specified")
                            .help("use the `#[error(...)]` attribute to create an error")
                            .emit();
                        return DiagnosticDeriveError::ErrorHandled.to_compile_error();
                    }
                    (Some(kind), None) => {
                        span_err(span, "diagnostic slug not specified")
                            .help(&format!(
                                "specify the slug as the first argument to the attribute, such as \
                                 `#[{}(typeck::example_error)]`",
                                kind.descr()
                            ))
                            .emit();
                        return DiagnosticDeriveError::ErrorHandled.to_compile_error();
                    }
                    (Some(DiagnosticDeriveKind::Error | DiagnosticDeriveKind::Warn), _) => {
                        span_err(span, "only `#[lint(..)]` is supported")
                            .help("use the `#[lint(...)]` attribute to create a lint")
                            .emit();
                        return DiagnosticDeriveError::ErrorHandled.to_compile_error();
                    }
                    (Some(DiagnosticDeriveKind::Lint), Some(slug)) => {
                        quote! {
                            let mut #diag = #diag.build(rustc_errors::fluent::#slug);
                        }
                    }
                };

                let implementation = quote! {
                    #init
                    #preamble
                    match self {
                        #attrs
                    }
                    match self {
                        #args
                    }
                    #diag.emit();
                };

                implementation
            } else {
                span_err(
                    ast.span().unwrap(),
                    "`#[derive(LintDiagnostic)]` can only be used on structs",
                )
                .emit();

                DiagnosticDeriveError::ErrorHandled.to_compile_error()
            }
        };

        let diag = &builder.diag;
        structure.gen_impl(quote! {
            gen impl<'__a> rustc_errors::DecorateLint<'__a, ()> for @Self {
                fn decorate_lint(self, #diag: rustc_errors::LintDiagnosticBuilder<'__a, ()>) {
                    use rustc_errors::IntoDiagnosticArg;
                    #implementation
                }
            }
        })
    }
}