juniper_codegen/graphql_interface/
attr.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
//! Code generation for `#[graphql_interface]` macro.

use std::mem;

use proc_macro2::{Span, TokenStream};
use quote::quote;
use syn::{ext::IdentExt as _, parse_quote, spanned::Spanned};

use crate::common::{
    diagnostic, field,
    parse::{self, TypeExt as _},
    path_eq_single, rename, scalar, SpanContainer,
};

use super::{enum_idents, Attr, Definition};

/// [`diagnostic::Scope`] of errors for `#[graphql_interface]` macro.
const ERR: diagnostic::Scope = diagnostic::Scope::InterfaceAttr;

/// Expands `#[graphql_interface]` macro into generated code.
pub fn expand(attr_args: TokenStream, body: TokenStream) -> syn::Result<TokenStream> {
    if let Ok(mut ast) = syn::parse2::<syn::ItemTrait>(body.clone()) {
        let trait_attrs = parse::attr::unite(("graphql_interface", &attr_args), &ast.attrs);
        ast.attrs = parse::attr::strip(["graphql_interface", "graphql"], ast.attrs);
        return expand_on_trait(trait_attrs, ast);
    }
    if let Ok(mut ast) = syn::parse2::<syn::DeriveInput>(body) {
        let trait_attrs = parse::attr::unite(("graphql_interface", &attr_args), &ast.attrs);
        ast.attrs = parse::attr::strip(["graphql_interface", "graphql"], ast.attrs);
        return expand_on_derive_input(trait_attrs, ast);
    }

    Err(syn::Error::new(
        Span::call_site(),
        "#[graphql_interface] attribute is applicable to trait and struct \
         definitions only",
    ))
}

/// Expands `#[graphql_interface]` macro placed on the given trait definition.
fn expand_on_trait(
    attrs: Vec<syn::Attribute>,
    mut ast: syn::ItemTrait,
) -> syn::Result<TokenStream> {
    let attr = Attr::from_attrs(["graphql_interface", "graphql"], &attrs)?;

    let trait_ident = &ast.ident;
    let trait_span = ast.span();

    let name = attr
        .name
        .clone()
        .map(SpanContainer::into_inner)
        .unwrap_or_else(|| trait_ident.unraw().to_string())
        .into_boxed_str();
    if !attr.is_internal && name.starts_with("__") {
        ERR.no_double_underscore(
            attr.name
                .as_ref()
                .map(SpanContainer::span_ident)
                .unwrap_or_else(|| trait_ident.span()),
        );
    }

    let scalar = scalar::Type::parse(attr.scalar.as_deref(), &ast.generics);

    diagnostic::abort_if_dirty();

    let renaming = attr
        .rename_fields
        .as_deref()
        .copied()
        .unwrap_or(rename::Policy::CamelCase);

    let fields = ast
        .items
        .iter_mut()
        .filter_map(|item| {
            if let syn::TraitItem::Fn(m) = item {
                return parse_trait_method(m, &renaming);
            }
            None
        })
        .collect::<Vec<_>>();

    diagnostic::abort_if_dirty();

    if fields.is_empty() {
        ERR.emit_custom(trait_span, "must have at least one field");
    }
    if !field::all_different(&fields) {
        ERR.emit_custom(trait_span, "must have a different name for each field");
    }

    diagnostic::abort_if_dirty();

    let context = attr
        .context
        .as_deref()
        .cloned()
        .or_else(|| {
            fields.iter().find_map(|f| {
                f.arguments.as_ref().and_then(|f| {
                    f.iter()
                        .find_map(field::MethodArgument::context_ty)
                        .cloned()
                })
            })
        })
        .unwrap_or_else(|| parse_quote! { () });

    let (enum_ident, enum_alias_ident) = enum_idents(trait_ident, attr.r#enum.as_deref());

    let generated_code = Definition {
        generics: ast.generics.clone(),
        vis: ast.vis.clone(),
        enum_ident,
        enum_alias_ident,
        name,
        description: attr.description.map(SpanContainer::into_inner),
        context,
        scalar,
        fields,
        implemented_for: attr
            .implemented_for
            .into_iter()
            .map(SpanContainer::into_inner)
            .collect(),
        implements: attr
            .implements
            .into_iter()
            .map(SpanContainer::into_inner)
            .collect(),
        suppress_dead_code: None,
        src_intra_doc_link: format!("trait@{trait_ident}").into_boxed_str(),
    };

    Ok(quote! {
        // Omit enforcing `# Errors` and `# Panics` sections in GraphQL descriptions.
        #[allow(clippy::missing_errors_doc, clippy::missing_panics_doc)]
        #ast
        #generated_code
    })
}

/// Parses a [`field::Definition`] from the given trait method definition.
///
/// Returns [`None`] if the parsing fails, or the method field is ignored.
#[must_use]
fn parse_trait_method(
    method: &mut syn::TraitItemFn,
    renaming: &rename::Policy,
) -> Option<field::Definition> {
    let method_ident = &method.sig.ident;
    let method_attrs = method.attrs.clone();

    // Remove repeated attributes from the method, to omit incorrect expansion.
    method.attrs = mem::take(&mut method.attrs)
        .into_iter()
        .filter(|attr| !path_eq_single(attr.path(), "graphql"))
        .collect();

    let attr = field::Attr::from_attrs("graphql", &method_attrs)
        .map_err(diagnostic::emit_error)
        .ok()?;

    if attr.ignore.is_some() {
        return None;
    }

    if method.default.is_some() {
        return err_default_impl_block(&method.default);
    }

    let name = attr
        .name
        .as_ref()
        .map(|m| m.as_ref().value())
        .unwrap_or_else(|| renaming.apply(&method_ident.unraw().to_string()));
    if name.starts_with("__") {
        ERR.no_double_underscore(
            attr.name
                .as_ref()
                .map(SpanContainer::span_ident)
                .unwrap_or_else(|| method_ident.span()),
        );
        return None;
    }

    let arguments = method
        .sig
        .inputs
        .iter_mut()
        .filter_map(|arg| match arg {
            syn::FnArg::Receiver(_) => None,
            syn::FnArg::Typed(arg) => field::MethodArgument::parse(arg, renaming, &ERR),
        })
        .collect();

    let mut ty = match &method.sig.output {
        syn::ReturnType::Default => parse_quote! { () },
        syn::ReturnType::Type(_, ty) => ty.unparenthesized().clone(),
    };
    ty.lifetimes_anonymized();

    Some(field::Definition {
        name,
        ty,
        description: attr.description.map(SpanContainer::into_inner),
        deprecated: attr.deprecated.map(SpanContainer::into_inner),
        ident: method_ident.clone(),
        arguments: Some(arguments),
        has_receiver: method.sig.receiver().is_some(),
        is_async: method.sig.asyncness.is_some(),
    })
}

/// Expands `#[graphql_interface]` macro placed on the given struct.
fn expand_on_derive_input(
    attrs: Vec<syn::Attribute>,
    mut ast: syn::DeriveInput,
) -> syn::Result<TokenStream> {
    let attr = Attr::from_attrs(["graphql_interface", "graphql"], &attrs)?;

    let struct_ident = &ast.ident;
    let struct_span = ast.span();

    let data = match &mut ast.data {
        syn::Data::Struct(data) => data,
        syn::Data::Enum(_) | syn::Data::Union(_) => {
            return Err(ERR.custom_error(
                ast.span(),
                "#[graphql_interface] attribute is applicable to trait and \
                 struct definitions only",
            ));
        }
    };

    let name = attr
        .name
        .clone()
        .map(SpanContainer::into_inner)
        .unwrap_or_else(|| struct_ident.unraw().to_string())
        .into_boxed_str();
    if !attr.is_internal && name.starts_with("__") {
        ERR.no_double_underscore(
            attr.name
                .as_ref()
                .map(SpanContainer::span_ident)
                .unwrap_or_else(|| struct_ident.span()),
        );
    }

    let scalar = scalar::Type::parse(attr.scalar.as_deref(), &ast.generics);

    diagnostic::abort_if_dirty();

    let renaming = attr
        .rename_fields
        .as_deref()
        .copied()
        .unwrap_or(rename::Policy::CamelCase);

    let fields = data
        .fields
        .iter_mut()
        .filter_map(|f| parse_struct_field(f, &renaming))
        .collect::<Vec<_>>();

    diagnostic::abort_if_dirty();

    if fields.is_empty() {
        ERR.emit_custom(struct_span, "must have at least one field");
    }
    if !field::all_different(&fields) {
        ERR.emit_custom(struct_span, "must have a different name for each field");
    }

    diagnostic::abort_if_dirty();

    let context = attr
        .context
        .as_deref()
        .cloned()
        .or_else(|| {
            fields.iter().find_map(|f| {
                f.arguments.as_ref().and_then(|f| {
                    f.iter()
                        .find_map(field::MethodArgument::context_ty)
                        .cloned()
                })
            })
        })
        .unwrap_or_else(|| parse_quote! { () });

    let (enum_ident, enum_alias_ident) = enum_idents(struct_ident, attr.r#enum.as_deref());
    let generated_code = Definition {
        generics: ast.generics.clone(),
        vis: ast.vis.clone(),
        enum_ident,
        enum_alias_ident,
        name,
        description: attr.description.map(SpanContainer::into_inner),
        context,
        scalar,
        fields,
        implemented_for: attr
            .implemented_for
            .into_iter()
            .map(SpanContainer::into_inner)
            .collect(),
        implements: attr
            .implements
            .into_iter()
            .map(SpanContainer::into_inner)
            .collect(),
        suppress_dead_code: None,
        src_intra_doc_link: format!("struct@{struct_ident}").into_boxed_str(),
    };

    Ok(quote! {
        #[allow(dead_code)]
        #ast
        #generated_code
    })
}

/// Parses a [`field::Definition`] from the given struct field definition.
///
/// Returns [`None`] if the parsing fails, or the struct field is ignored.
#[must_use]
fn parse_struct_field(
    field: &mut syn::Field,
    renaming: &rename::Policy,
) -> Option<field::Definition> {
    let field_ident = field.ident.as_ref().or_else(|| err_unnamed_field(&field))?;
    let field_attrs = field.attrs.clone();

    // Remove repeated attributes from the method, to omit incorrect expansion.
    field.attrs = mem::take(&mut field.attrs)
        .into_iter()
        .filter(|attr| !path_eq_single(attr.path(), "graphql"))
        .collect();

    let attr = field::Attr::from_attrs("graphql", &field_attrs)
        .map_err(diagnostic::emit_error)
        .ok()?;

    if attr.ignore.is_some() {
        return None;
    }

    let name = attr
        .name
        .as_ref()
        .map(|m| m.as_ref().value())
        .unwrap_or_else(|| renaming.apply(&field_ident.unraw().to_string()));
    if name.starts_with("__") {
        ERR.no_double_underscore(
            attr.name
                .as_ref()
                .map(SpanContainer::span_ident)
                .unwrap_or_else(|| field_ident.span()),
        );
        return None;
    }

    let mut ty = field.ty.clone();
    ty.lifetimes_anonymized();

    Some(field::Definition {
        name,
        ty,
        description: attr.description.map(SpanContainer::into_inner),
        deprecated: attr.deprecated.map(SpanContainer::into_inner),
        ident: field_ident.clone(),
        arguments: None,
        has_receiver: false,
        is_async: false,
    })
}

/// Emits "trait method can't have default implementation" [`syn::Error`]
/// pointing to the given `span`.
fn err_default_impl_block<T, S: Spanned>(span: &S) -> Option<T> {
    ERR.emit_custom(
        span.span(),
        "trait method can't have default implementation",
    );
    None
}

/// Emits "expected named struct field" [`syn::Error`] pointing to the given
/// `span`.
pub(crate) fn err_unnamed_field<T, S: Spanned>(span: &S) -> Option<T> {
    ERR.emit_custom(span.span(), "expected named struct field");
    None
}