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
use darling::{util::Flag, FromDeriveInput, FromField, FromVariant};
use proc_macro2::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use syn::{DeriveInput, Ident, Index, Member, Path};

use crate::generators::{self as gen, CodedVariant};

#[derive(FromDeriveInput)]
#[darling(supports(enum_any), attributes(sdk_error))]
struct Error {
    ident: Ident,

    data: darling::ast::Data<ErrorVariant, darling::util::Ignored>,

    /// The path to a const set to the module name.
    module_name: Option<syn::Path>,

    /// Whether to sequentially autonumber the error codes.
    /// This option exists as a convenience for runtimes that
    /// only append errors or release only breaking changes.
    #[darling(rename = "autonumber")]
    autonumber: Flag,

    /// Whether the `into_abort` function should return itself. This can only be used when the type
    /// being annotated is the dispatcher error type so it is only for internal use.
    #[darling(rename = "abort_self")]
    abort_self: Flag,
}

#[derive(FromVariant)]
#[darling(attributes(sdk_error))]
struct ErrorVariant {
    ident: Ident,

    fields: darling::ast::Fields<ErrorField>,

    /// The explicit ID of the error code. Overrides any autonumber set on the error enum.
    #[darling(rename = "code")]
    code: Option<u32>,

    #[darling(rename = "transparent")]
    transparent: Flag,

    #[darling(rename = "abort")]
    abort: Flag,
}

impl CodedVariant for ErrorVariant {
    const FIELD_NAME: &'static str = "code";

    fn ident(&self) -> &Ident {
        &self.ident
    }

    fn code(&self) -> Option<u32> {
        self.code
    }
}

#[derive(FromField)]
#[darling(forward_attrs(source, from))]
struct ErrorField {
    ident: Option<Ident>,

    attrs: Vec<syn::Attribute>,
}

pub fn derive_error(input: DeriveInput) -> TokenStream {
    let error = match Error::from_derive_input(&input) {
        Ok(error) => error,
        Err(e) => return e.write_errors(),
    };

    let error_ty_ident = &error.ident;

    let module_name = error
        .module_name
        .unwrap_or_else(|| syn::parse_quote!(MODULE_NAME));

    let (module_name_body, code_body, abort_body) = convert_variants(
        &format_ident!("self"),
        module_name,
        &error.data.as_ref().take_enum().unwrap(),
        error.autonumber.is_present(),
        error.abort_self.is_present(),
    );

    let sdk_crate = gen::sdk_crate_path();

    gen::wrap_in_const(quote! {
        use #sdk_crate::{self as __sdk, error::Error as _};

        #[automatically_derived]
        impl __sdk::error::Error for #error_ty_ident {
            fn module_name(&self) -> &str {
                #module_name_body
            }

            fn code(&self) -> u32 {
                #code_body
            }

            fn into_abort(self) -> Result<__sdk::dispatcher::Error, Self> {
                #abort_body
            }
        }

        #[automatically_derived]
        impl From<#error_ty_ident> for __sdk::error::RuntimeError {
            fn from(err: #error_ty_ident) -> Self {
                Self::new(err.module_name(), err.code(), &err.to_string())
            }
        }
    })
}

fn convert_variants(
    enum_binding: &Ident,
    module_name: Path,
    variants: &[&ErrorVariant],
    autonumber: bool,
    abort_self: bool,
) -> (TokenStream, TokenStream, TokenStream) {
    if variants.is_empty() {
        return (quote!(#module_name), quote!(0), quote!(Err(#enum_binding)));
    }

    let mut next_autonumber = 0u32;
    let mut reserved_numbers = std::collections::BTreeSet::new();

    let (module_name_matches, (code_matches, abort_matches)): (Vec<_>, (Vec<_>, Vec<_>)) = variants
        .iter()
        .map(|variant| {
            let variant_ident = &variant.ident;

            if variant.transparent.is_present() {
                // Transparently forward everything to the source.
                let mut maybe_sources = variant
                    .fields
                    .iter()
                    .enumerate()
                    .filter(|(_, f)| (!f.attrs.is_empty()))
                    .map(|(i, f)| (i, f.ident.clone()));
                let source = maybe_sources.next();
                if maybe_sources.count() != 0 {
                    variant_ident
                        .span()
                        .unwrap()
                        .error("multiple error sources specified for variant")
                        .emit();
                    return (quote!(), (quote!(), quote!()));
                }
                if source.is_none() {
                    variant_ident
                        .span()
                        .unwrap()
                        .error("no source error specified for variant")
                        .emit();
                    return (quote!(), (quote!(), quote!()));
                }
                let (field_index, field_ident) = source.unwrap();

                let field = match field_ident {
                    Some(ident) => Member::Named(ident),
                    None => Member::Unnamed(Index {
                        index: field_index as u32,
                        span: variant_ident.span(),
                    }),
                };

                // Get all other fields that are needed for forwarding in abort variants.
                let non_source_fields = variant
                    .fields
                    .iter()
                    .enumerate()
                    .filter(|(i, _)| i != &field_index)
                    .map(|(i, f)| {
                        let pat = match f.ident {
                            Some(ref ident) => Member::Named(ident.clone()),
                            None => Member::Unnamed(Index {
                                index: i as u32,
                                span: variant_ident.span(),
                            }),
                        };
                        let ident = Ident::new(&format!("__a{i}"), variant_ident.span());
                        let binding = quote!( #pat: #ident, );

                        binding
                    });
                let non_source_field_bindings = non_source_fields.clone();

                let source = quote!(source);
                let module_name = quote_spanned!(variant_ident.span()=> #source.module_name());
                let code = quote_spanned!(variant_ident.span()=> #source.code());
                let abort_reclaim = quote!(Self::#variant_ident { #field: e, #(#non_source_fields)* });
                let abort = quote_spanned!(variant_ident.span()=> #source.into_abort().map_err(|e| #abort_reclaim));

                (
                    quote! {
                        Self::#variant_ident { #field: #source, .. } => #module_name,
                    },
                    (
                        quote! {
                            Self::#variant_ident { #field: #source, .. } => #code,
                        },
                        quote! {
                            Self::#variant_ident { #field: #source, #(#non_source_field_bindings)* } => #abort,
                        },
                    ),
                )
            } else {
                // Regular case without forwarding.
                let code = match variant.code {
                    Some(code) => {
                        if reserved_numbers.contains(&code) {
                            variant_ident
                                .span()
                                .unwrap()
                                .error(format!("code {code} already used"))
                                .emit();
                            return (quote!(), (quote!(), quote!()));
                        }
                        reserved_numbers.insert(code);
                        code
                    }
                    None if autonumber => {
                        let mut reserved_successors = reserved_numbers.range(next_autonumber..);
                        while reserved_successors.next() == Some(&next_autonumber) {
                            next_autonumber += 1;
                        }
                        let code = next_autonumber;
                        reserved_numbers.insert(code);
                        next_autonumber += 1;
                        code
                    }
                    None => {
                        variant_ident
                            .span()
                            .unwrap()
                            .error("missing `code` for variant")
                            .emit();
                        return (quote!(), (quote!(), quote!()));
                    }
                };

                let abort = if variant.abort.is_present() {
                    quote!{
                        Self::#variant_ident(err) => Ok(err),
                    }
                } else {
                    quote!{
                        Self::#variant_ident { .. } => Err(#enum_binding),
                    }
                };

                (
                    quote! {
                        Self::#variant_ident { .. } => #module_name,
                    },
                    (
                        quote! {
                            Self::#variant_ident { .. } => #code,
                        },
                        abort,
                    ),
                )
            }
        })
        .unzip();

    let abort_body = if abort_self {
        quote!(Ok(self))
    } else {
        quote! {
            match #enum_binding {
                #(#abort_matches)*
            }
        }
    };

    (
        quote! {
            match #enum_binding {
                #(#module_name_matches)*
            }
        },
        quote! {
            match #enum_binding {
                #(#code_matches)*
            }
        },
        abort_body,
    )
}

#[cfg(test)]
mod tests {
    #[test]
    fn generate_error_impl_auto_abort() {
        let expected: syn::Stmt = syn::parse_quote!(
            const _: () = {
                use ::oasis_runtime_sdk::{self as __sdk, error::Error as _};
                #[automatically_derived]
                impl __sdk::error::Error for Error {
                    fn module_name(&self) -> &str {
                        match self {
                            Self::Error0 { .. } => MODULE_NAME,
                            Self::Error2 { .. } => MODULE_NAME,
                            Self::Error1 { .. } => MODULE_NAME,
                            Self::Error3 { .. } => MODULE_NAME,
                            Self::ErrorAbort { .. } => MODULE_NAME,
                        }
                    }
                    fn code(&self) -> u32 {
                        match self {
                            Self::Error0 { .. } => 0u32,
                            Self::Error2 { .. } => 2u32,
                            Self::Error1 { .. } => 1u32,
                            Self::Error3 { .. } => 3u32,
                            Self::ErrorAbort { .. } => 4u32,
                        }
                    }
                    fn into_abort(self) -> Result<__sdk::dispatcher::Error, Self> {
                        match self {
                            Self::Error0 { .. } => Err(self),
                            Self::Error2 { .. } => Err(self),
                            Self::Error1 { .. } => Err(self),
                            Self::Error3 { .. } => Err(self),
                            Self::ErrorAbort(err) => Ok(err),
                        }
                    }
                }
                #[automatically_derived]
                impl From<Error> for __sdk::error::RuntimeError {
                    fn from(err: Error) -> Self {
                        Self::new(err.module_name(), err.code(), &err.to_string())
                    }
                }
            };
        );

        let input: syn::DeriveInput = syn::parse_quote!(
            #[derive(Error)]
            #[sdk_error(autonumber)]
            pub enum Error {
                Error0,
                #[sdk_error(code = 2)]
                Error2 {
                    payload: Vec<u8>,
                },
                Error1(String),
                Error3,
                #[sdk_error(abort)]
                ErrorAbort(sdk::dispatcher::Error),
            }
        );
        let error_derivation = super::derive_error(input);
        let actual: syn::Stmt = syn::parse2(error_derivation).unwrap();

        crate::assert_empty_diff!(actual, expected);
    }

    #[test]
    fn generate_error_impl_manual() {
        let expected: syn::Stmt = syn::parse_quote!(
            const _: () = {
                use ::oasis_runtime_sdk::{self as __sdk, error::Error as _};
                #[automatically_derived]
                impl __sdk::error::Error for Error {
                    fn module_name(&self) -> &str {
                        THE_MODULE_NAME
                    }
                    fn code(&self) -> u32 {
                        0
                    }
                    fn into_abort(self) -> Result<__sdk::dispatcher::Error, Self> {
                        Err(self)
                    }
                }
                #[automatically_derived]
                impl From<Error> for __sdk::error::RuntimeError {
                    fn from(err: Error) -> Self {
                        Self::new(err.module_name(), err.code(), &err.to_string())
                    }
                }
            };
        );

        let input: syn::DeriveInput = syn::parse_quote!(
            #[derive(Error)]
            #[sdk_error(autonumber, module_name = "THE_MODULE_NAME")]
            pub enum Error {}
        );
        let error_derivation = super::derive_error(input);
        let actual: syn::Stmt = syn::parse2(error_derivation).unwrap();

        crate::assert_empty_diff!(actual, expected);
    }

    #[test]
    fn generate_error_impl_from() {
        let expected: syn::Stmt = syn::parse_quote!(
            const _: () = {
                use ::oasis_runtime_sdk::{self as __sdk, error::Error as _};
                #[automatically_derived]
                impl __sdk::error::Error for Error {
                    fn module_name(&self) -> &str {
                        match self {
                            Self::Foo { 0: source, .. } => source.module_name(),
                        }
                    }
                    fn code(&self) -> u32 {
                        match self {
                            Self::Foo { 0: source, .. } => source.code(),
                        }
                    }
                    fn into_abort(self) -> Result<__sdk::dispatcher::Error, Self> {
                        match self {
                            Self::Foo { 0: source } => {
                                source.into_abort().map_err(|e| Self::Foo { 0: e })
                            }
                        }
                    }
                }
                #[automatically_derived]
                impl From<Error> for __sdk::error::RuntimeError {
                    fn from(err: Error) -> Self {
                        Self::new(err.module_name(), err.code(), &err.to_string())
                    }
                }
            };
        );

        let input: syn::DeriveInput = syn::parse_quote!(
            #[derive(Error)]
            #[sdk_error(module_name = "THE_MODULE_NAME")]
            pub enum Error {
                #[sdk_error(transparent)]
                Foo(#[from] AnotherError),
            }
        );
        let error_derivation = super::derive_error(input);
        let actual: syn::Stmt = syn::parse2(error_derivation).unwrap();

        crate::assert_empty_diff!(actual, expected);
    }

    #[test]
    fn generate_error_impl_abort_self() {
        let expected: syn::Stmt = syn::parse_quote!(
            const _: () = {
                use ::oasis_runtime_sdk::{self as __sdk, error::Error as _};
                #[automatically_derived]
                impl __sdk::error::Error for Error {
                    fn module_name(&self) -> &str {
                        match self {
                            Self::Foo { .. } => THE_MODULE_NAME,
                            Self::Bar { .. } => THE_MODULE_NAME,
                        }
                    }
                    fn code(&self) -> u32 {
                        match self {
                            Self::Foo { .. } => 1u32,
                            Self::Bar { .. } => 2u32,
                        }
                    }
                    fn into_abort(self) -> Result<__sdk::dispatcher::Error, Self> {
                        Ok(self)
                    }
                }
                #[automatically_derived]
                impl From<Error> for __sdk::error::RuntimeError {
                    fn from(err: Error) -> Self {
                        Self::new(err.module_name(), err.code(), &err.to_string())
                    }
                }
            };
        );

        let input: syn::DeriveInput = syn::parse_quote!(
            #[derive(Error)]
            #[sdk_error(module_name = "THE_MODULE_NAME", abort_self)]
            pub enum Error {
                #[sdk_error(code = 1)]
                Foo,
                #[sdk_error(code = 2)]
                Bar,
            }
        );
        let error_derivation = super::derive_error(input);
        let actual: syn::Stmt = syn::parse2(error_derivation).unwrap();

        crate::assert_empty_diff!(actual, expected);
    }
}