utoipa_gen/component/
into_params.rs

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
use std::borrow::Cow;

use proc_macro2::TokenStream;
use quote::{quote, quote_spanned, ToTokens};
use syn::{
    parse::Parse, punctuated::Punctuated, spanned::Spanned, token::Comma, Attribute, Data, Field,
    Generics, Ident,
};

use crate::{
    component::{
        self,
        features::{
            self,
            attributes::{
                AdditionalProperties, AllowReserved, Example, Explode, Format, Ignore, Inline,
                IntoParamsNames, Nullable, ReadOnly, Rename, RenameAll, SchemaWith, Style,
                WriteOnly, XmlAttr,
            },
            validation::{
                ExclusiveMaximum, ExclusiveMinimum, MaxItems, MaxLength, Maximum, MinItems,
                MinLength, Minimum, MultipleOf, Pattern,
            },
        },
        FieldRename,
    },
    doc_comment::CommentAttributes,
    parse_utils::LitBoolOrExprPath,
    Array, Diagnostics, OptionExt, Required, ToTokensDiagnostics,
};

use super::{
    features::{
        impl_into_inner, impl_merge, parse_features, pop_feature, Feature, FeaturesExt, IntoInner,
        Merge, ToTokensExt,
    },
    serde::{self, SerdeContainer, SerdeValue},
    ComponentSchema, Container, TypeTree,
};

impl_merge!(IntoParamsFeatures, FieldFeatures);

/// Container attribute `#[into_params(...)]`.
pub struct IntoParamsFeatures(Vec<Feature>);

impl Parse for IntoParamsFeatures {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        Ok(Self(parse_features!(
            input as Style,
            features::attributes::ParameterIn,
            IntoParamsNames,
            RenameAll
        )))
    }
}

impl_into_inner!(IntoParamsFeatures);

#[cfg_attr(feature = "debug", derive(Debug))]
pub struct IntoParams {
    /// Attributes tagged on the whole struct or enum.
    pub attrs: Vec<Attribute>,
    /// Generics required to complete the definition.
    pub generics: Generics,
    /// Data within the struct or enum.
    pub data: Data,
    /// Name of the struct or enum.
    pub ident: Ident,
}

impl ToTokensDiagnostics for IntoParams {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) -> Result<(), Diagnostics> {
        let ident = &self.ident;
        let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();

        let mut into_params_features = self
            .attrs
            .iter()
            .filter(|attr| attr.path().is_ident("into_params"))
            .map(|attribute| {
                attribute
                    .parse_args::<IntoParamsFeatures>()
                    .map(IntoParamsFeatures::into_inner)
                    .map_err(Diagnostics::from)
            })
            .collect::<Result<Vec<_>, Diagnostics>>()?
            .into_iter()
            .reduce(|acc, item| acc.merge(item));
        let serde_container = serde::parse_container(&self.attrs)?;

        // #[param] is only supported over fields
        if self.attrs.iter().any(|attr| attr.path().is_ident("param")) {
            return Err(Diagnostics::with_span(
                ident.span(),
                "found `param` attribute in unsupported context",
            )
            .help("Did you mean `into_params`?"));
        }

        let names = into_params_features.as_mut().and_then(|features| {
            let into_params_names = pop_feature!(features => Feature::IntoParamsNames(_));
            IntoInner::<Option<IntoParamsNames>>::into_inner(into_params_names)
                .map(|names| names.into_values())
        });

        let style = pop_feature!(into_params_features => Feature::Style(_));
        let parameter_in = pop_feature!(into_params_features => Feature::ParameterIn(_));
        let rename_all = pop_feature!(into_params_features => Feature::RenameAll(_));

        let params = self
            .get_struct_fields(&names.as_ref())?
            .enumerate()
            .map(|(index, field)| {
                let field_features = match parse_field_features(field) {
                    Ok(features) => features,
                    Err(error) => return Err(error),
                };
                match serde::parse_value(&field.attrs) {
                    Ok(serde_value) => Ok((index, field, serde_value, field_features)),
                    Err(diagnostics) => Err(diagnostics)
                }
            })
            .collect::<Result<Vec<_>, Diagnostics>>()?
            .into_iter()
            .filter_map(|(index, field, field_serde_params, field_features)| {
                if field_serde_params.skip {
                    None
                } else {
                    Some((index, field, field_serde_params, field_features))
                }
            })
            .map(|(index, field, field_serde_params, field_features)| {
                let name = names.as_ref()
                    .map_try(|names| names.get(index).ok_or_else(|| Diagnostics::with_span(
                        ident.span(),
                        format!("There is no name specified in the names(...) container attribute for tuple struct field {}", index),
                    )));
                let name = match name {
                    Ok(name) => name,
                    Err(diagnostics) => return Err(diagnostics)
                };
                let param = Param::new(field, field_serde_params, field_features, FieldParamContainerAttributes {
                        rename_all: rename_all.as_ref().and_then(|feature| {
                            match feature {
                                Feature::RenameAll(rename_all) => Some(rename_all),
                                _ => None
                            }
                        }),
                        style: &style,
                        parameter_in: &parameter_in,
                        name,
                    }, &serde_container, &self.generics)?;


                Ok(param.to_token_stream())
            })
            .collect::<Result<Array<TokenStream>, Diagnostics>>()?;

        tokens.extend(quote! {
            impl #impl_generics utoipa::IntoParams for #ident #ty_generics #where_clause {
                fn into_params(parameter_in_provider: impl Fn() -> Option<utoipa::openapi::path::ParameterIn>) -> Vec<utoipa::openapi::path::Parameter> {
                    #params.into_iter().filter(Option::is_some).flatten().collect()
                }
            }
        });

        Ok(())
    }
}

fn parse_field_features(field: &Field) -> Result<Vec<Feature>, Diagnostics> {
    Ok(field
        .attrs
        .iter()
        .filter(|attribute| attribute.path().is_ident("param"))
        .map(|attribute| {
            attribute
                .parse_args::<FieldFeatures>()
                .map(FieldFeatures::into_inner)
        })
        .collect::<Result<Vec<_>, syn::Error>>()?
        .into_iter()
        .reduce(|acc, item| acc.merge(item))
        .unwrap_or_default())
}

impl IntoParams {
    fn get_struct_fields(
        &self,
        field_names: &Option<&Vec<String>>,
    ) -> Result<impl Iterator<Item = &Field>, Diagnostics> {
        let ident = &self.ident;
        match &self.data {
            Data::Struct(data_struct) => match &data_struct.fields {
                syn::Fields::Named(named_fields) => {
                    if field_names.is_some() {
                        return Err(Diagnostics::with_span(
                            ident.span(),
                            "`#[into_params(names(...))]` is not supported attribute on a struct with named fields")
                        );
                    }
                    Ok(named_fields.named.iter())
                }
                syn::Fields::Unnamed(unnamed_fields) => {
                    match self.validate_unnamed_field_names(&unnamed_fields.unnamed, field_names) {
                        None => Ok(unnamed_fields.unnamed.iter()),
                        Some(diagnostics) => Err(diagnostics),
                    }
                }
                _ => Err(Diagnostics::with_span(
                    ident.span(),
                    "Unit type struct is not supported",
                )),
            },
            _ => Err(Diagnostics::with_span(
                ident.span(),
                "Only struct type is supported",
            )),
        }
    }

    fn validate_unnamed_field_names(
        &self,
        unnamed_fields: &Punctuated<Field, Comma>,
        field_names: &Option<&Vec<String>>,
    ) -> Option<Diagnostics> {
        let ident = &self.ident;
        match field_names {
            Some(names) => {
                if names.len() != unnamed_fields.len() {
                    Some(Diagnostics::with_span(
                        ident.span(),
                        format!("declared names amount '{}' does not match to the unnamed fields amount '{}' in type: {}", 
                            names.len(), unnamed_fields.len(), ident)
                    )
                        .help(r#"Did you forget to add a field name to `#[into_params(names(... , "field_name"))]`"#)
                        .help("Or have you added extra name but haven't defined a type?")
                    )
                } else {
                    None
                }
            }
            None => Some(
                Diagnostics::with_span(
                    ident.span(),
                    "struct with unnamed fields must have explicit name declarations.",
                )
                .help(format!(
                    "Try defining `#[into_params(names(...))]` over your type: {}",
                    ident
                )),
            ),
        }
    }
}

#[cfg_attr(feature = "debug", derive(Debug))]
pub struct FieldParamContainerAttributes<'a> {
    /// See [`IntoParamsAttr::style`].
    style: &'a Option<Feature>,
    /// See [`IntoParamsAttr::names`]. The name that applies to this field.
    name: Option<&'a String>,
    /// See [`IntoParamsAttr::parameter_in`].
    parameter_in: &'a Option<Feature>,
    /// Custom rename all if serde attribute is not present.
    rename_all: Option<&'a RenameAll>,
}

struct FieldFeatures(Vec<Feature>);

impl_into_inner!(FieldFeatures);

impl Parse for FieldFeatures {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        Ok(Self(parse_features!(
            // param features
            input as component::features::attributes::ValueType,
            Rename,
            Style,
            AllowReserved,
            Example,
            Explode,
            SchemaWith,
            component::features::attributes::Required,
            // param schema features
            Inline,
            Format,
            component::features::attributes::Default,
            WriteOnly,
            ReadOnly,
            Nullable,
            XmlAttr,
            MultipleOf,
            Maximum,
            Minimum,
            ExclusiveMaximum,
            ExclusiveMinimum,
            MaxLength,
            MinLength,
            Pattern,
            MaxItems,
            MinItems,
            AdditionalProperties,
            Ignore
        )))
    }
}

#[cfg_attr(feature = "debug", derive(Debug))]
struct Param {
    tokens: TokenStream,
}

impl Param {
    fn new(
        field: &Field,
        field_serde_params: SerdeValue,
        field_features: Vec<Feature>,
        container_attributes: FieldParamContainerAttributes<'_>,
        serde_container: &SerdeContainer,
        generics: &Generics,
    ) -> Result<Self, Diagnostics> {
        let mut tokens = TokenStream::new();
        let field_serde_params = &field_serde_params;
        let ident = &field.ident;
        let mut name = &*ident
            .as_ref()
            .map(|ident| ident.to_string())
            .or_else(|| container_attributes.name.cloned())
            .ok_or_else(||
                Diagnostics::with_span(field.span(), "No name specified for unnamed field.")
                    .help("Try adding #[into_params(names(...))] container attribute to specify the name for this field")
            )?;

        if name.starts_with("r#") {
            name = &name[2..];
        }

        let (schema_features, mut param_features) =
            Param::resolve_field_features(field_features, &container_attributes)
                .map_err(Diagnostics::from)?;

        let ignore = pop_feature!(param_features => Feature::Ignore(_));
        let rename = pop_feature!(param_features => Feature::Rename(_) as Option<Rename>)
            .map(|rename| rename.into_value());
        let rename_to = field_serde_params
            .rename
            .as_deref()
            .map(Cow::Borrowed)
            .or(rename.map(Cow::Owned));
        let rename_all = serde_container.rename_all.as_ref().or(container_attributes
            .rename_all
            .map(|rename_all| rename_all.as_rename_rule()));
        let name = super::rename::<FieldRename>(name, rename_to, rename_all)
            .unwrap_or(Cow::Borrowed(name));
        let type_tree = TypeTree::from_type(&field.ty)?;

        tokens.extend(quote! { utoipa::openapi::path::ParameterBuilder::new()
            .name(#name)
        });
        tokens.extend(
            if let Some(ref parameter_in) = &container_attributes.parameter_in {
                parameter_in.to_token_stream()
            } else {
                quote! {
                    .parameter_in(parameter_in_provider().unwrap_or_default())
                }
            },
        );

        if let Some(deprecated) = super::get_deprecated(&field.attrs) {
            tokens.extend(quote! { .deprecated(Some(#deprecated)) });
        }

        let schema_with = pop_feature!(param_features => Feature::SchemaWith(_));
        if let Some(schema_with) = schema_with {
            let schema_with = crate::as_tokens_or_diagnostics!(&schema_with);
            tokens.extend(quote! { .schema(Some(#schema_with)).build() });
        } else {
            let description =
                CommentAttributes::from_attributes(&field.attrs).as_formatted_string();
            if !description.is_empty() {
                tokens.extend(quote! { .description(Some(#description))})
            }

            let value_type = pop_feature!(param_features => Feature::ValueType(_) as Option<features::attributes::ValueType>);
            let component = value_type
                .as_ref()
                .map_try(|value_type| value_type.as_type_tree())?
                .unwrap_or(type_tree);
            let alias_type = component.get_alias_type()?;
            let alias_type_tree = alias_type.as_ref().map_try(TypeTree::from_type)?;
            let component = alias_type_tree.as_ref().unwrap_or(&component);

            let required: Option<features::attributes::Required> =
                pop_feature!(param_features => Feature::Required(_)).into_inner();
            let component_required =
                !component.is_option() && super::is_required(field_serde_params, serde_container);

            let required = match (required, component_required) {
                (Some(required_feature), _) => Into::<Required>::into(required_feature.is_true()),
                (None, component_required) => Into::<Required>::into(component_required),
            };

            tokens.extend(quote! {
                .required(#required)
            });
            tokens.extend(param_features.to_token_stream()?);

            let is_query = matches!(container_attributes.parameter_in, Some(Feature::ParameterIn(p)) if p.is_query());
            let option_is_nullable = !is_query;

            let schema = ComponentSchema::for_params(
                component::ComponentSchemaProps {
                    type_tree: component,
                    features: schema_features,
                    description: None,
                    container: &Container { generics },
                },
                option_is_nullable,
            )?;
            let schema_tokens = schema.to_token_stream();

            tokens.extend(quote! { .schema(Some(#schema_tokens)).build() });
        }

        let tokens = match ignore {
            Some(Feature::Ignore(Ignore(LitBoolOrExprPath::LitBool(bool)))) => {
                quote_spanned! {
                    bool.span() => if #bool {
                        None
                    } else {
                        Some(#tokens)
                    }
                }
            }
            Some(Feature::Ignore(Ignore(LitBoolOrExprPath::ExprPath(path)))) => {
                quote_spanned! {
                    path.span() => if #path() {
                        None
                    } else {
                        Some(#tokens)
                    }
                }
            }
            _ => quote! { Some(#tokens) },
        };

        Ok(Self { tokens })
    }

    /// Resolve [`Param`] features and split features into two [`Vec`]s. Features are split by
    /// whether they should be rendered in [`Param`] itself or in [`Param`]s schema.
    ///
    /// Method returns a tuple containing two [`Vec`]s of [`Feature`].
    fn resolve_field_features(
        mut field_features: Vec<Feature>,
        container_attributes: &FieldParamContainerAttributes<'_>,
    ) -> Result<(Vec<Feature>, Vec<Feature>), syn::Error> {
        if let Some(ref style) = container_attributes.style {
            if !field_features
                .iter()
                .any(|feature| matches!(&feature, Feature::Style(_)))
            {
                field_features.push(style.clone()); // could try to use cow to avoid cloning
            };
        }

        Ok(field_features.into_iter().fold(
            (Vec::<Feature>::new(), Vec::<Feature>::new()),
            |(mut schema_features, mut param_features), feature| {
                match feature {
                    Feature::Inline(_)
                    | Feature::Format(_)
                    | Feature::Default(_)
                    | Feature::WriteOnly(_)
                    | Feature::ReadOnly(_)
                    | Feature::Nullable(_)
                    | Feature::XmlAttr(_)
                    | Feature::MultipleOf(_)
                    | Feature::Maximum(_)
                    | Feature::Minimum(_)
                    | Feature::ExclusiveMaximum(_)
                    | Feature::ExclusiveMinimum(_)
                    | Feature::MaxLength(_)
                    | Feature::MinLength(_)
                    | Feature::Pattern(_)
                    | Feature::MaxItems(_)
                    | Feature::MinItems(_)
                    | Feature::AdditionalProperties(_) => {
                        schema_features.push(feature);
                    }
                    _ => {
                        param_features.push(feature);
                    }
                };

                (schema_features, param_features)
            },
        ))
    }
}

impl ToTokens for Param {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.tokens.to_tokens(tokens)
    }
}