predawn-macro 0.9.0

Macros for predawn
Documentation
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
use std::collections::HashMap;

use from_attr::{AttrsValue, FromAttr};
use http::HeaderName;
use proc_macro2::TokenStream;
use quote::quote;
use quote_use::quote_use;
use syn::{
    parse_quote, spanned::Spanned, Attribute, Data, DataEnum, DataStruct, DataUnion, DeriveInput,
    Expr, ExprLit, Field, Fields, FieldsNamed, FieldsUnnamed, Generics, Ident, Lit, LitInt, Member,
    Type,
};

use crate::util;

#[derive(FromAttr, Default)]
#[attribute(idents = [single_response])]
struct StructAttr {
    status: Option<LitInt>,
}

pub(crate) fn generate(input: DeriveInput) -> syn::Result<TokenStream> {
    let DeriveInput {
        attrs,
        ident,
        generics,
        data,
        ..
    } = input;

    let StructAttr {
        status: status_code,
    } = match StructAttr::from_attributes(&attrs) {
        Ok(Some(AttrsValue {
            value: struct_attr, ..
        })) => struct_attr,
        Ok(None) => Default::default(),
        Err(AttrsValue { value: e, .. }) => return Err(e),
    };

    let status_code_value = util::extract_status_code_value(status_code)?;

    let fields = match data {
        Data::Struct(DataStruct { fields, .. }) => fields,
        Data::Enum(DataEnum { enum_token, .. }) => {
            return Err(syn::Error::new(
                enum_token.span,
                "`SingleResponse` can only be derived for structs",
            ))
        }
        Data::Union(DataUnion { union_token, .. }) => {
            return Err(syn::Error::new(
                union_token.span,
                "`SingleResponse` can only be derived for structs",
            ))
        }
    };

    let fields = match fields {
        Fields::Named(FieldsNamed { named, .. }) if !named.is_empty() => named,
        Fields::Unnamed(FieldsUnnamed { unnamed, .. }) if !unnamed.is_empty() => unnamed,
        _ => return Ok(generate_unit(&ident, status_code_value)),
    };

    let fields_len = fields.len();
    let mut fields = fields.into_iter();

    let last = fields
        .next_back()
        .expect("unreachable: fields is not empty");

    let mut header_names = HashMap::new();

    let mut insert_api_headers = Vec::new();
    let mut insert_http_headers = Vec::new();
    let mut errors = Vec::new();

    fields.enumerate().for_each(|(idx, field)| {
        match handle_single_field(field, idx, &mut header_names) {
            Ok((insert_api_header, insert_http_header)) => {
                insert_api_headers.push(insert_api_header);
                insert_http_headers.push(insert_http_header);
            }
            Err(e) => {
                errors.push(e);
            }
        }
    });

    let description = util::extract_description(&attrs);
    let description = util::generate_string_expr(&description);

    match handle_last_field(last, fields_len - 1, &mut header_names) {
        Ok(Last::Header {
            insert_api_header,
            insert_http_header,
        }) => {
            insert_api_headers.push(insert_api_header);
            insert_http_headers.push(insert_http_header);

            if let Some(e) = errors.into_iter().reduce(|mut a, b| {
                a.combine(b);
                a
            }) {
                return Err(e);
            }

            let expand = generate_only_headers(
                &generics,
                &ident,
                status_code_value,
                description,
                insert_api_headers,
                insert_http_headers,
            );

            Ok(expand)
        }
        Ok(Last::Body { member, ty }) => {
            let into_response_arg = parse_quote!(self.#member);

            if let Some(e) = errors.into_iter().reduce(|mut a, b| {
                a.combine(b);
                a
            }) {
                return Err(e);
            }

            let expand = if insert_api_headers.is_empty() {
                generate_only_body(
                    &generics,
                    &ident,
                    status_code_value,
                    description,
                    ty,
                    into_response_arg,
                )
            } else {
                generate_body_and_headers(
                    &generics,
                    &ident,
                    status_code_value,
                    description,
                    insert_api_headers,
                    insert_http_headers,
                    ty,
                    into_response_arg,
                )
            };

            Ok(expand)
        }
        Err(e) => {
            errors.push(e);

            let e = errors
                .into_iter()
                .reduce(|mut a, b| {
                    a.combine(b);
                    a
                })
                .expect("unreachable: errors at least one element");

            Err(e)
        }
    }
}

fn generate_unit(ident: &Ident, status_code_value: u16) -> TokenStream {
    quote_use! {
        # use core::default::Default;
        # use std::collections::BTreeMap;
        # use predawn::{SingleResponse, MultiResponse};
        # use predawn::into_response::IntoResponse;
        # use predawn::api_response::ApiResponse;
        # use predawn::response::Response;
        # use predawn::openapi::{self, Schema};
        # use predawn::http::StatusCode;

        impl SingleResponse for #ident {
            const STATUS_CODE: u16 = #status_code_value;

            fn response(_: &mut BTreeMap<String, Schema>, _: &mut Vec<String>) -> openapi::Response {
                Default::default()
            }
        }

        impl IntoResponse for #ident {
            type Error = <() as IntoResponse>::Error;

            fn into_response(self) -> Result<Response, Self::Error> {
                let mut response = <() as IntoResponse>::into_response(())?;
                *response.status_mut() = StatusCode::from_u16(#status_code_value).unwrap();
                Ok(response)
            }
        }

        impl ApiResponse for #ident {
            fn responses(schemas: &mut BTreeMap<String, Schema>, schemas_in_progress: &mut Vec<String>) -> Option<BTreeMap<StatusCode, openapi::Response>> {
                Some(<Self as MultiResponse>::responses(schemas, schemas_in_progress))
            }
        }
    }
}

fn generate_only_headers(
    generics: &Generics,
    ident: &Ident,
    status_code_value: u16,
    description: Expr,
    insert_api_headers: Vec<TokenStream>,
    insert_http_headers: Vec<TokenStream>,
) -> TokenStream {
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    let headers_len = insert_api_headers.len();

    quote_use! {
        # use core::default::Default;
        # use std::collections::BTreeMap;
        # use predawn::{SingleResponse, MultiResponse};
        # use predawn::into_response::IntoResponse;
        # use predawn::api_response::ApiResponse;
        # use predawn::response::Response;
        # use predawn::openapi::{self, Schema};
        # use predawn::response_error::InvalidHeaderValue;
        # use predawn::__internal::indexmap::IndexMap;
        # use predawn::http::StatusCode;

        impl #impl_generics SingleResponse for #ident #ty_generics #where_clause {
            const STATUS_CODE: u16 = #status_code_value;

            fn response(schemas: &mut BTreeMap<String, Schema>, schemas_in_progress: &mut Vec<String>) -> openapi::Response {
                let mut headers = IndexMap::with_capacity(#headers_len);

                #(#insert_api_headers)*

                openapi::Response {
                    description: #description,
                    headers,
                    content: Default::default(),
                    links: Default::default(),
                    extensions: Default::default(),
                }
            }
        }

        impl #impl_generics IntoResponse for #ident #ty_generics #where_clause {
            type Error = InvalidHeaderValue;

            fn into_response(self) -> Result<Response, <Self as IntoResponse>::Error> {
                let mut response = <() as IntoResponse>::into_response(()).unwrap();

                *response.status_mut() = StatusCode::from_u16(#status_code_value).unwrap();

                #(
                    let _: () = #insert_http_headers?;
                )*

                Ok(response)
            }
        }

        impl #impl_generics ApiResponse for #ident #ty_generics #where_clause {
            fn responses(schemas: &mut BTreeMap<String, Schema>, schemas_in_progress: &mut Vec<String>) -> Option<BTreeMap<StatusCode, openapi::Response>> {
                Some(<Self as MultiResponse>::responses(schemas, schemas_in_progress))
            }
        }
    }
}

fn generate_only_body(
    generics: &Generics,
    ident: &Ident,
    status_code_value: u16,
    description: Expr,
    body_type: Type,
    into_response_arg: Expr,
) -> TokenStream {
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    quote_use! {
        # use core::default::Default;
        # use std::collections::BTreeMap;
        # use predawn::{SingleResponse, MultiResponse};
        # use predawn::into_response::IntoResponse;
        # use predawn::api_response::ApiResponse;
        # use predawn::response::Response;
        # use predawn::MultiResponseMediaType;
        # use predawn::openapi::{self, Schema};
        # use predawn::http::StatusCode;

        impl #impl_generics SingleResponse for #ident #ty_generics #where_clause {
            const STATUS_CODE: u16 = #status_code_value;

            fn response(schemas: &mut BTreeMap<String, Schema>, schemas_in_progress: &mut Vec<String>) -> openapi::Response {
                openapi::Response {
                    description: #description,
                    headers: Default::default(),
                    content: <#body_type as MultiResponseMediaType>::content(schemas, schemas_in_progress),
                    links: Default::default(),
                    extensions: Default::default(),
                }
            }
        }

        impl #impl_generics IntoResponse for #ident #ty_generics #where_clause {
            type Error = <#body_type as IntoResponse>::Error;

            fn into_response(self) -> Result<Response, <Self as IntoResponse>::Error> {
                let mut response = <#body_type as IntoResponse>::into_response(#into_response_arg)?;
                *response.status_mut() = StatusCode::from_u16(#status_code_value).unwrap();
                Ok(response)
            }
        }

        impl #impl_generics ApiResponse for #ident #ty_generics #where_clause {
            fn responses(schemas: &mut BTreeMap<String, Schema>, schemas_in_progress: &mut Vec<String>) -> Option<BTreeMap<StatusCode, openapi::Response>> {
                Some(<Self as MultiResponse>::responses(schemas, schemas_in_progress))
            }
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn generate_body_and_headers(
    generics: &Generics,
    ident: &Ident,
    status_code_value: u16,
    description: Expr,
    insert_api_headers: Vec<TokenStream>,
    insert_http_headers: Vec<TokenStream>,
    body_type: Type,
    into_response_arg: Expr,
) -> TokenStream {
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    let headers_len = insert_api_headers.len();

    quote_use! {
        # use core::default::Default;
        # use std::collections::BTreeMap;
        # use predawn::{SingleResponse, MultiResponse};
        # use predawn::into_response::IntoResponse;
        # use predawn::api_response::ApiResponse;
        # use predawn::response::Response;
        # use predawn::MultiResponseMediaType;
        # use predawn::openapi::{self, Schema};
        # use predawn::either::Either;
        # use predawn::response_error::InvalidHeaderValue;
        # use predawn::__internal::indexmap::IndexMap;
        # use predawn::http::StatusCode;

        impl #impl_generics SingleResponse for #ident #ty_generics #where_clause {
            const STATUS_CODE: u16 = #status_code_value;

            fn response(schemas: &mut BTreeMap<String, Schema>, schemas_in_progress: &mut Vec<String>) -> openapi::Response {
                let mut headers = IndexMap::with_capacity(#headers_len);

                #(#insert_api_headers)*

                openapi::Response {
                    description: #description,
                    headers,
                    content: <#body_type as MultiResponseMediaType>::content(schemas, schemas_in_progress),
                    links: Default::default(),
                    extensions: Default::default(),
                }
            }
        }

        impl #impl_generics IntoResponse for #ident #ty_generics #where_clause {
            type Error = Either<<#body_type as IntoResponse>::Error, InvalidHeaderValue>;

            fn into_response(self) -> Result<Response, <Self as IntoResponse>::Error> {
                let mut response = <#body_type as IntoResponse>::into_response(#into_response_arg).map_err(Either::Left)?;

                *response.status_mut() = StatusCode::from_u16(#status_code_value).unwrap();

                #(
                    let _: () = #insert_http_headers.map_err(Either::Right)?;
                )*

                Ok(response)
            }
        }

        impl #impl_generics ApiResponse for #ident #ty_generics #where_clause {
            fn responses(schemas: &mut BTreeMap<String, Schema>, schemas_in_progress: &mut Vec<String>) -> Option<BTreeMap<StatusCode, openapi::Response>> {
                Some(<Self as MultiResponse>::responses(schemas, schemas_in_progress))
            }
        }
    }
}

fn handle_single_field(
    field: Field,
    idx: usize,
    header_names: &mut HashMap<String, String>,
) -> syn::Result<(TokenStream, TokenStream)> {
    let span = field.span();

    let Field {
        attrs, ident, ty, ..
    } = field;

    let Some(header_name) = extract_header_name(&attrs, header_names)? else {
        let e = syn::Error::new(span, "missing `#[header = \"xxx\"]` attribute");
        return Err(e);
    };

    let member = match ident {
        Some(ident) => Member::from(ident),
        None => Member::from(idx),
    };

    let description = util::extract_description(&attrs);
    let description = if description.is_empty() {
        quote! { None }
    } else {
        let description = util::generate_string_expr(&description);
        quote! { Some(#description) }
    };

    Ok(generate_headers(&ty, &header_name, &member, description))
}

enum Last {
    Header {
        insert_api_header: TokenStream,
        insert_http_header: TokenStream,
    },
    Body {
        member: Member,
        ty: Type,
    },
}

fn handle_last_field(
    field: Field,
    idx: usize,
    header_names: &mut HashMap<String, String>,
) -> syn::Result<Last> {
    let Field {
        attrs, ident, ty, ..
    } = field;

    let member = match ident {
        Some(ident) => Member::from(ident),
        None => Member::from(idx),
    };

    let Some(header_name) = extract_header_name(&attrs, header_names)? else {
        return Ok(Last::Body { member, ty });
    };

    let description = util::extract_description(&attrs);
    let description = if description.is_empty() {
        quote! { None }
    } else {
        let description = util::generate_string_expr(&description);
        quote! { Some(#description) }
    };

    let (insert_api_header, insert_http_header) =
        generate_headers(&ty, &header_name, &member, description);

    Ok(Last::Header {
        insert_api_header,
        insert_http_header,
    })
}

fn generate_headers<'a>(
    ty: &'a Type,
    header_name: &'a str,
    member: &'a Member,
    description: TokenStream,
) -> (TokenStream, TokenStream) {
    let insert_api_header = quote_use! {
        # use core::default::Default;
        # use std::string::ToString;
        # use predawn::openapi::{Header, ParameterSchemaOrContent, ReferenceOr};
        # use predawn::ToSchema;

        let header = Header {
            description: #description,
            style: Default::default(),
            required: <#ty as ToSchema>::REQUIRED,
            deprecated: Default::default(),
            format: ParameterSchemaOrContent::Schema(<#ty as ToSchema>::schema_ref(schemas, schemas_in_progress)),
            example: Default::default(),
            examples: Default::default(),
            extensions: Default::default(),
        };

        headers.insert(ToString::to_string(#header_name), ReferenceOr::Item(header));
    };

    let insert_http_header = quote_use! {
        # use predawn::response::{MaybeHeaderValue, ToHeaderValue};
        # use predawn::ToSchema;
        # use predawn::outcome::Outcome;
        # use predawn::response_error::InvalidHeaderValue;
        # use predawn::http::HeaderName;

        match <#ty as ToHeaderValue>::to_header_value(&self.#member) {
            MaybeHeaderValue::Value(val) => {
                response.headers_mut().insert(HeaderName::from_static(#header_name), val);
                Ok(())
            }
            MaybeHeaderValue::Error => {
                Err(InvalidHeaderValue::error(#header_name, &self.#member))
            },
            MaybeHeaderValue::None => {
                if <#ty as ToSchema>::REQUIRED {
                    Err(InvalidHeaderValue::none(#header_name, &self.#member))
                } else {
                    Ok(())
                }
            }
        }
    };

    (insert_api_header, insert_http_header)
}

fn extract_header_name<'a>(
    attrs: &'a [Attribute],
    header_names: &'a mut HashMap<String, String>,
) -> syn::Result<Option<String>> {
    let mut errors = Vec::new();
    let mut found = None;

    for attr in attrs {
        if !attr.path().is_ident("header") {
            continue;
        }

        if found.is_some() {
            let e = syn::Error::new(attr.span(), "only one `header` attribute is allowed");
            errors.push(e);
            continue;
        }

        let value = match attr.meta.require_name_value() {
            Ok(name_value) => &name_value.value,
            Err(e) => {
                errors.push(e);
                continue;
            }
        };

        let Expr::Lit(ExprLit {
            lit: Lit::Str(lit_str),
            ..
        }) = value
        else {
            let e = syn::Error::new(value.span(), "only string literal is allowed");
            errors.push(e);
            continue;
        };

        let raw_header_name = lit_str.value();
        let lit_str_span = lit_str.span();

        let header_name = match HeaderName::from_bytes(raw_header_name.as_bytes()) {
            Ok(header_name) => header_name,
            Err(e) => {
                errors.push(syn::Error::new(lit_str_span, e));
                continue;
            }
        };

        let header_name = header_name.as_str().to_string();

        match header_names.get(&header_name) {
            None => {
                header_names.insert(header_name.clone(), raw_header_name);
                found = Some(header_name);
            }
            Some(existing_raw_header_name) => {
                let e = syn::Error::new(
                    lit_str_span,
                    format!("duplicate with header name `{}`", existing_raw_header_name),
                );
                errors.push(e);
            }
        }
    }

    if let Some(e) = errors.into_iter().reduce(|mut a, b| {
        a.combine(b);
        a
    }) {
        return Err(e);
    }

    Ok(found)
}