-
Notifications
You must be signed in to change notification settings - Fork 426
/
mod.rs
2377 lines (2095 loc) · 82.9 KB
/
mod.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
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(clippy::single_match)]
pub mod duplicate;
pub mod parse_impl;
pub mod span_container;
use proc_macro2::{Span, TokenStream};
use proc_macro_error::abort;
use quote::quote;
use span_container::SpanContainer;
use std::collections::HashMap;
use syn::{
parse, parse_quote, punctuated::Punctuated, spanned::Spanned, Attribute, Lit, Meta, MetaList,
MetaNameValue, NestedMeta, Token,
};
pub fn juniper_path(is_internal: bool) -> syn::Path {
let name = if is_internal { "crate" } else { "juniper" };
syn::parse_str::<syn::Path>(name).unwrap()
}
/// Returns the name of a type.
/// If the type does not end in a simple ident, `None` is returned.
pub fn name_of_type(ty: &syn::Type) -> Option<syn::Ident> {
let path_opt = match ty {
syn::Type::Path(ref type_path) => Some(&type_path.path),
syn::Type::Reference(ref reference) => match &*reference.elem {
syn::Type::Path(ref type_path) => Some(&type_path.path),
syn::Type::TraitObject(ref trait_obj) => {
match trait_obj.bounds.iter().next().unwrap() {
syn::TypeParamBound::Trait(ref trait_bound) => Some(&trait_bound.path),
_ => None,
}
}
_ => None,
},
_ => None,
};
let path = path_opt?;
path.segments
.iter()
.last()
.map(|segment| segment.ident.clone())
}
/// Compares a path to a one-segment string value,
/// return true if equal.
pub fn path_eq_single(path: &syn::Path, value: &str) -> bool {
path.segments.len() == 1 && path.segments[0].ident == value
}
/// Check if a type is a reference to another type.
pub fn type_is_ref_of(ty: &syn::Type, target: &syn::Type) -> bool {
match ty {
syn::Type::Reference(_ref) => &*_ref.elem == target,
_ => false,
}
}
/// Check if a Type is a simple identifier.
pub fn type_is_identifier(ty: &syn::Type, name: &str) -> bool {
match ty {
syn::Type::Path(ref type_path) => path_eq_single(&type_path.path, name),
_ => false,
}
}
/// Check if a Type is a reference to a given identifier.
pub fn type_is_identifier_ref(ty: &syn::Type, name: &str) -> bool {
match ty {
syn::Type::Reference(_ref) => type_is_identifier(&*_ref.elem, name),
_ => false,
}
}
#[derive(Debug)]
pub struct DeprecationAttr {
pub reason: Option<String>,
}
pub fn find_graphql_attr(attrs: &[Attribute]) -> Option<&Attribute> {
attrs
.iter()
.find(|attr| path_eq_single(&attr.path, "graphql"))
}
pub fn get_deprecated(attrs: &[Attribute]) -> Option<SpanContainer<DeprecationAttr>> {
attrs
.iter()
.filter_map(|attr| match attr.parse_meta() {
Ok(Meta::List(ref list)) if list.path.is_ident("deprecated") => {
let val = get_deprecated_meta_list(list);
Some(SpanContainer::new(list.path.span(), None, val))
}
Ok(Meta::Path(ref path)) if path.is_ident("deprecated") => Some(SpanContainer::new(
path.span(),
None,
DeprecationAttr { reason: None },
)),
_ => None,
})
.next()
}
fn get_deprecated_meta_list(list: &MetaList) -> DeprecationAttr {
for meta in &list.nested {
if let NestedMeta::Meta(Meta::NameValue(ref nv)) = *meta {
if nv.path.is_ident("note") {
match nv.lit {
Lit::Str(ref strlit) => {
return DeprecationAttr {
reason: Some(strlit.value()),
};
}
_ => abort!(syn::Error::new(
nv.lit.span(),
"only strings are allowed for deprecation",
)),
}
} else {
abort!(syn::Error::new(
nv.path.span(),
"unrecognized setting on #[deprecated(..)] attribute",
));
}
}
}
DeprecationAttr { reason: None }
}
// Gets doc comment.
pub fn get_doc_comment(attrs: &[Attribute]) -> Option<SpanContainer<String>> {
if let Some(items) = get_doc_attr(attrs) {
if let Some(doc_strings) = get_doc_strings(&items) {
return Some(doc_strings.map(|strings| join_doc_strings(&strings)));
}
}
None
}
// Concatenates doc strings into one string.
fn join_doc_strings(docs: &[String]) -> String {
// Note: this is guaranteed since this function is only called
// from get_doc_strings().
debug_assert!(!docs.is_empty());
let last_index = docs.len() - 1;
docs.iter()
.map(|s| s.as_str().trim_end())
// Trim leading space.
.map(|s| if s.starts_with(' ') { &s[1..] } else { s })
// Add newline, exept when string ends in a continuation backslash or is the last line.
.enumerate()
.fold(String::new(), |mut buffer, (index, s)| {
if index == last_index {
buffer.push_str(s);
} else if s.ends_with('\\') {
buffer.push_str(s.trim_end_matches('\\'));
buffer.push(' ');
} else {
buffer.push_str(s);
buffer.push('\n');
}
buffer
})
}
// Gets doc strings from doc comment attributes.
fn get_doc_strings(items: &[MetaNameValue]) -> Option<SpanContainer<Vec<String>>> {
let mut span = None;
let comments = items
.iter()
.filter_map(|item| {
if item.path.is_ident("doc") {
match item.lit {
Lit::Str(ref strlit) => {
if span.is_none() {
span = Some(strlit.span());
}
Some(strlit.value())
}
_ => abort!(syn::Error::new(
item.lit.span(),
"doc attributes only have string literal"
)),
}
} else {
None
}
})
.collect::<Vec<_>>();
span.map(|span| SpanContainer::new(span, None, comments))
}
// Gets doc comment attributes.
fn get_doc_attr(attrs: &[Attribute]) -> Option<Vec<MetaNameValue>> {
let mut docs = Vec::new();
for attr in attrs {
match attr.parse_meta() {
Ok(Meta::NameValue(ref nv)) if nv.path.is_ident("doc") => docs.push(nv.clone()),
_ => {}
}
}
if !docs.is_empty() {
return Some(docs);
}
None
}
// Note: duplicated from juniper crate!
#[doc(hidden)]
pub fn to_camel_case(s: &str) -> String {
let mut dest = String::new();
for (i, part) in s.split('_').enumerate() {
if i > 0 && part.len() == 1 {
dest.push_str(&part.to_uppercase());
} else if i > 0 && part.len() > 1 {
let first = part
.chars()
.next()
.unwrap()
.to_uppercase()
.collect::<String>();
let second = &part[1..];
dest.push_str(&first);
dest.push_str(second);
} else if i == 0 {
dest.push_str(part);
}
}
dest
}
pub(crate) fn to_upper_snake_case(s: &str) -> String {
let mut last_lower = false;
let mut upper = String::new();
for c in s.chars() {
if c == '_' {
last_lower = false;
} else if c.is_lowercase() {
last_lower = true;
} else if c.is_uppercase() {
if last_lower {
upper.push('_');
}
last_lower = false;
}
for u in c.to_uppercase() {
upper.push(u);
}
}
upper
}
#[doc(hidden)]
pub fn is_valid_name(field_name: &str) -> bool {
let mut chars = field_name.chars();
match chars.next() {
// first char can't be a digit
Some(c) if c.is_ascii_alphabetic() || c == '_' => (),
// can't be an empty string or any other character
_ => return false,
};
chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
#[derive(Default, Debug)]
pub struct ObjectAttributes {
pub name: Option<SpanContainer<String>>,
pub description: Option<SpanContainer<String>>,
pub context: Option<SpanContainer<syn::Type>>,
pub scalar: Option<SpanContainer<syn::Type>>,
pub interfaces: Vec<SpanContainer<syn::Type>>,
pub no_async: Option<SpanContainer<()>>,
pub derive_fields: Option<SpanContainer<()>>,
}
impl syn::parse::Parse for ObjectAttributes {
fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
let mut output = Self {
name: None,
description: None,
context: None,
scalar: None,
interfaces: Vec::new(),
no_async: None,
derive_fields: None,
};
while !input.is_empty() {
let ident: syn::Ident = input.parse()?;
match ident.to_string().as_str() {
"name" => {
input.parse::<syn::Token![=]>()?;
let val = input.parse::<syn::LitStr>()?;
output.name = Some(SpanContainer::new(
ident.span(),
Some(val.span()),
val.value(),
));
}
"description" => {
input.parse::<syn::Token![=]>()?;
let val = input.parse::<syn::LitStr>()?;
output.description = Some(SpanContainer::new(
ident.span(),
Some(val.span()),
val.value(),
));
}
"context" | "Context" => {
input.parse::<syn::Token![=]>()?;
// TODO: remove legacy support for string based Context.
let ctx = if let Ok(val) = input.parse::<syn::LitStr>() {
eprintln!("DEPRECATION WARNING: using a string literal for the Context is deprecated");
eprintln!("Use a normal type instead - example: 'Context = MyContextType'");
syn::parse_str::<syn::Type>(&val.value())?
} else {
input.parse::<syn::Type>()?
};
output.context = Some(SpanContainer::new(ident.span(), Some(ctx.span()), ctx));
}
"scalar" | "Scalar" => {
input.parse::<syn::Token![=]>()?;
let val = input.parse::<syn::Type>()?;
output.scalar = Some(SpanContainer::new(ident.span(), Some(val.span()), val));
}
"interfaces" => {
input.parse::<syn::Token![=]>()?;
let content;
syn::bracketed!(content in input);
output.interfaces =
syn::punctuated::Punctuated::<syn::Type, syn::Token![,]>::parse_terminated(
&content,
)?
.into_iter()
.map(|interface| {
SpanContainer::new(ident.span(), Some(interface.span()), interface)
})
.collect();
}
// FIXME: make this unneccessary.
"noasync" => {
output.no_async = Some(SpanContainer::new(ident.span(), None, ()));
}
"derive_fields" => {
output.derive_fields = Some(SpanContainer::new(ident.span(), None, ()));
}
_ => {
return Err(syn::Error::new(ident.span(), "unknown attribute"));
}
}
if input.lookahead1().peek(syn::Token![,]) {
input.parse::<syn::Token![,]>()?;
}
}
Ok(output)
}
}
impl ObjectAttributes {
pub fn from_attrs(attrs: &[syn::Attribute]) -> syn::parse::Result<Self> {
let attr_opt = find_graphql_attr(attrs);
if let Some(attr) = attr_opt {
// Need to unwrap outer (), which are not present for proc macro attributes,
// but are present for regular ones.
let mut a: Self = attr.parse_args()?;
if a.description.is_none() {
a.description = get_doc_comment(attrs);
}
Ok(a)
} else {
let mut a = Self::default();
a.description = get_doc_comment(attrs);
Ok(a)
}
}
}
#[derive(Default, Debug)]
pub struct ObjectInfoAttributes {
pub context: Option<SpanContainer<syn::Type>>,
pub scalar: Option<SpanContainer<syn::Type>>,
}
impl syn::parse::Parse for ObjectInfoAttributes {
fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
let mut output = Self {
context: None,
scalar: None,
};
while !input.is_empty() {
let ident: syn::Ident = input.parse()?;
match ident.to_string().as_str() {
"context" | "Context" => {
input.parse::<syn::Token![=]>()?;
// TODO: remove legacy support for string based Context.
let ctx = if let Ok(val) = input.parse::<syn::LitStr>() {
eprintln!("DEPRECATION WARNING: using a string literal for the Context is deprecated");
eprintln!("Use a normal type instead - example: 'Context = MyContextType'");
syn::parse_str::<syn::Type>(&val.value())?
} else {
input.parse::<syn::Type>()?
};
output.context = Some(SpanContainer::new(ident.span(), Some(ctx.span()), ctx));
}
"scalar" | "Scalar" => {
input.parse::<syn::Token![=]>()?;
let val = input.parse::<syn::Type>()?;
output.scalar = Some(SpanContainer::new(ident.span(), Some(val.span()), val));
}
_ => {
return Err(syn::Error::new(ident.span(), "unknown attribute"));
}
}
if input.lookahead1().peek(syn::Token![,]) {
input.parse::<syn::Token![,]>()?;
}
}
Ok(output)
}
}
impl ObjectInfoAttributes {
pub fn from_attrs(attrs: &[syn::Attribute]) -> syn::parse::Result<Self> {
let attr_opt = find_graphql_attr(attrs);
if let Some(attr) = attr_opt {
// Need to unwrap outer (), which are not present for proc macro attributes,
// but are present for regular ones.
let a: Self = attr.parse_args()?;
Ok(a)
} else {
let a = Self::default();
Ok(a)
}
}
}
#[derive(Debug)]
pub struct FieldAttributeArgument {
pub name: syn::Ident,
pub rename: Option<SpanContainer<syn::LitStr>>,
pub default: Option<syn::Expr>,
pub description: Option<syn::LitStr>,
}
impl parse::Parse for FieldAttributeArgument {
fn parse(input: parse::ParseStream) -> parse::Result<Self> {
let name = input.parse()?;
let mut arg = Self {
name,
rename: None,
default: None,
description: None,
};
let content;
syn::parenthesized!(content in input);
while !content.is_empty() {
let name = content.parse::<syn::Ident>()?;
content.parse::<Token![=]>()?;
match name.to_string().as_str() {
"name" => {
let val: syn::LitStr = content.parse()?;
arg.rename = Some(SpanContainer::new(name.span(), Some(val.span()), val));
}
"description" => {
arg.description = Some(content.parse()?);
}
"default" => {
arg.default = Some(content.parse()?);
}
_ => return Err(syn::Error::new(name.span(), "unknown attribute")),
}
// Discard trailing comma.
content.parse::<Token![,]>().ok();
}
Ok(arg)
}
}
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum FieldAttributeParseMode {
Object,
Impl,
}
enum FieldAttribute {
Name(SpanContainer<syn::LitStr>),
Description(SpanContainer<syn::LitStr>),
Deprecation(SpanContainer<DeprecationAttr>),
Skip(SpanContainer<syn::Ident>),
Arguments(HashMap<String, FieldAttributeArgument>),
Default(SpanContainer<Option<syn::Expr>>),
}
impl parse::Parse for FieldAttribute {
fn parse(input: parse::ParseStream) -> parse::Result<Self> {
let ident = input.parse::<syn::Ident>()?;
match ident.to_string().as_str() {
"name" => {
input.parse::<Token![=]>()?;
let lit = input.parse::<syn::LitStr>()?;
let raw = lit.value();
if !is_valid_name(&raw) {
Err(syn::Error::new(lit.span(), "name consists of not allowed characters. (must match /^[_a-zA-Z][_a-zA-Z0-9]*$/)"))
} else {
Ok(FieldAttribute::Name(SpanContainer::new(
ident.span(),
Some(lit.span()),
lit,
)))
}
}
"description" => {
input.parse::<Token![=]>()?;
let lit = input.parse::<syn::LitStr>()?;
Ok(FieldAttribute::Description(SpanContainer::new(
ident.span(),
Some(lit.span()),
lit,
)))
}
"deprecated" | "deprecation" => {
let reason = if input.peek(Token![=]) {
input.parse::<Token![=]>()?;
Some(input.parse::<syn::LitStr>()?)
} else {
None
};
Ok(FieldAttribute::Deprecation(SpanContainer::new(
ident.span(),
reason.as_ref().map(|val| val.span()),
DeprecationAttr {
reason: reason.map(|val| val.value()),
},
)))
}
"skip" => Ok(FieldAttribute::Skip(SpanContainer::new(
ident.span(),
None,
ident,
))),
"arguments" => {
let arg_content;
syn::parenthesized!(arg_content in input);
let args = Punctuated::<FieldAttributeArgument, Token![,]>::parse_terminated(
&arg_content,
)?;
let map = args
.into_iter()
.map(|arg| (arg.name.to_string(), arg))
.collect();
Ok(FieldAttribute::Arguments(map))
}
"default" => {
let default_expr = if input.peek(Token![=]) {
input.parse::<Token![=]>()?;
let lit = input.parse::<syn::LitStr>()?;
let default_expr = lit.parse::<syn::Expr>()?;
SpanContainer::new(ident.span(), Some(lit.span()), Some(default_expr))
} else {
SpanContainer::new(ident.span(), None, None)
};
Ok(FieldAttribute::Default(default_expr))
}
_ => Err(syn::Error::new(ident.span(), "unknown attribute")),
}
}
}
#[derive(Default)]
pub struct FieldAttributes {
pub name: Option<SpanContainer<String>>,
pub description: Option<SpanContainer<String>>,
pub deprecation: Option<SpanContainer<DeprecationAttr>>,
// Only relevant for GraphQLObject derive.
pub skip: Option<SpanContainer<syn::Ident>>,
/// Only relevant for object macro.
pub arguments: HashMap<String, FieldAttributeArgument>,
/// Only relevant for object input objects.
pub default: Option<SpanContainer<Option<syn::Expr>>>,
}
impl parse::Parse for FieldAttributes {
fn parse(input: syn::parse::ParseStream) -> syn::parse::Result<Self> {
let items = Punctuated::<FieldAttribute, Token![,]>::parse_terminated(&input)?;
let mut output = Self {
name: None,
description: None,
deprecation: None,
skip: None,
arguments: Default::default(),
default: None,
};
for item in items {
match item {
FieldAttribute::Name(name) => {
output.name = Some(name.map(|val| val.value()));
}
FieldAttribute::Description(name) => {
output.description = Some(name.map(|val| val.value()));
}
FieldAttribute::Deprecation(attr) => {
output.deprecation = Some(attr);
}
FieldAttribute::Skip(ident) => {
output.skip = Some(ident);
}
FieldAttribute::Arguments(args) => {
output.arguments = args;
}
FieldAttribute::Default(expr) => {
output.default = Some(expr);
}
}
}
if !input.is_empty() {
Err(input.error("Unexpected input"))
} else {
Ok(output)
}
}
}
impl FieldAttributes {
pub fn from_attrs(
attrs: &[syn::Attribute],
_mode: FieldAttributeParseMode,
) -> syn::parse::Result<Self> {
let doc_comment = get_doc_comment(&attrs);
let deprecation = get_deprecated(&attrs);
let attr_opt = attrs.into_iter().find(|attr| attr.path.is_ident("graphql"));
let mut output = match attr_opt {
Some(attr) => attr.parse_args()?,
None => Self::default(),
};
// Check for regular doc comment.
if output.description.is_none() {
output.description = doc_comment;
}
if output.deprecation.is_none() {
output.deprecation = deprecation;
}
Ok(output)
}
pub fn argument(&self, name: &str) -> Option<&FieldAttributeArgument> {
self.arguments.get(name)
}
}
#[derive(Debug)]
pub struct GraphQLTypeDefinitionFieldArg {
pub name: String,
pub description: Option<String>,
pub default: Option<syn::Expr>,
pub _type: Box<syn::Type>,
}
#[derive(Debug)]
pub struct GraphQLTypeDefinitionField {
pub name: String,
pub _type: syn::Type,
pub description: Option<String>,
pub deprecation: Option<DeprecationAttr>,
pub args: Vec<GraphQLTypeDefinitionFieldArg>,
pub resolver_code: TokenStream,
pub is_type_inferred: bool,
pub is_async: bool,
pub default: Option<TokenStream>,
pub span: Span,
}
impl syn::spanned::Spanned for GraphQLTypeDefinitionField {
fn span(&self) -> Span {
self.span
}
}
impl<'a> syn::spanned::Spanned for &'a GraphQLTypeDefinitionField {
fn span(&self) -> Span {
self.span
}
}
/// Definition of a graphql type based on information extracted
/// by various macros.
/// The definition can be rendered to Rust code.
#[derive(Debug)]
pub struct GraphQLTypeDefiniton {
pub name: String,
pub _type: syn::Type,
pub context: Option<syn::Type>,
pub scalar: Option<syn::Type>,
pub description: Option<String>,
pub fields: Vec<GraphQLTypeDefinitionField>,
pub generics: syn::Generics,
pub interfaces: Option<Vec<syn::Type>>,
// Due to syn parsing differences,
// when parsing an impl the type generics are included in the type
// directly, but in syn::DeriveInput, the type generics are
// in the generics field.
// This flag signifies if the type generics need to be
// included manually.
pub include_type_generics: bool,
// This flag indicates if the field resolvers derived from the type
// struct should be included.
pub include_struct_fields: bool,
// This flag indicates if the generated code should always be
// generic over the ScalarValue.
// If false, the scalar is only generic if a generic parameter
// is specified manually.
pub generic_scalar: bool,
// FIXME: make this redundant.
pub no_async: bool,
}
impl GraphQLTypeDefiniton {
#[allow(unused)]
fn has_async_field(&self) -> bool {
self.fields.iter().any(|field| field.is_async)
}
fn field_definition_tokens(&self) -> Vec<TokenStream> {
self.fields
.iter()
.map(|field| {
let args = field.args.iter().map(|arg| {
let arg_type = &arg._type;
let arg_name = &arg.name;
let description = match arg.description.as_ref() {
Some(value) => quote!( .description( #value ) ),
None => quote!(),
};
// Code.
match arg.default.as_ref() {
Some(value) => quote!(
.argument(
registry.arg_with_default::<#arg_type>(#arg_name, &#value, info)
#description
)
),
None => quote!(
.argument(
registry.arg::<#arg_type>(#arg_name, info)
#description
)
),
}
});
let description = match field.description.as_ref() {
Some(description) => quote!( .description(#description) ),
None => quote!(),
};
let deprecation = match field.deprecation.as_ref() {
Some(deprecation) => {
if let Some(reason) = deprecation.reason.as_ref() {
quote!( .deprecated(Some(#reason)) )
} else {
quote!( .deprecated(None) )
}
}
None => quote!(),
};
let field_name = &field.name;
let _type = &field._type;
quote! {
registry
.field_convert::<#_type, _, Self::Context>(#field_name, info)
#(#args)*
#description
#deprecation
}
})
.collect()
}
fn resolve_matches_tokens(
&self,
scalar: &TokenStream,
juniper_crate_name: &syn::Path,
) -> Vec<TokenStream> {
self.fields.iter().map(|field| {
let name = &field.name;
let code = &field.resolver_code;
if field.is_async {
quote!(
#name => {
panic!("Tried to resolve async field {} on type {:?} with a sync resolver",
#name,
<Self as #juniper_crate_name::GraphQLType<#scalar>>::name(_info)
);
},
)
} else {
let _type = if field.is_type_inferred {
quote!()
} else {
let _type = &field._type;
quote!(: #_type)
};
quote!(
#name => {
let res #_type = (|| { #code })();
#juniper_crate_name::IntoResolvable::into(
res,
executor.context()
)
.and_then(|res| {
match res {
Some((ctx, r)) => executor.replaced_context(ctx).resolve_with_ctx(&(), &r),
None => Ok(#juniper_crate_name::Value::null()),
}
})
},
)
}
}).collect()
}
pub fn into_tokens(self, juniper_crate_name: &str) -> TokenStream {
let juniper_crate_name = syn::parse_str::<syn::Path>(juniper_crate_name).unwrap();
let name = &self.name;
let ty = &self._type;
let context = self
.context
.as_ref()
.map(|ctx| quote!( #ctx ))
.unwrap_or_else(|| quote!(()));
let scalar = self
.scalar
.as_ref()
.map(|s| quote!( #s ))
.unwrap_or_else(|| {
if self.generic_scalar {
// If generic_scalar is true, we always insert a generic scalar.
// See more comments below.
quote!(__S)
} else {
quote!(#juniper_crate_name::DefaultScalarValue)
}
});
let field_definitions = if self.include_struct_fields {
let impl_fields = self.field_definition_tokens();
let impl_fields = quote!(vec![ #( #impl_fields ),* ]);
let struct_fields = quote!(
<Self as #juniper_crate_name::GraphQLTypeInfo<#scalar>>::fields(info, registry)
);
quote!({
let fields = vec![ #impl_fields, #struct_fields ].concat();
let mut mapping: std::collections::HashMap<&str, Vec<&_>> =
std::collections::HashMap::with_capacity(fields.len());
for item in &fields {
let name = item.name.as_str();
if let Some(vals) = mapping.get_mut(name) {
vals.push(item);
} else {
mapping.insert(name, vec![item]);
}
}
let duplicates = mapping
.into_iter()
.filter_map(|(name, spanned)| {
if spanned.len() > 1 {
Some(name.to_string())
} else {
None
}
})
.collect::<Vec<_>>();
if !duplicates.is_empty() {
duplicates.iter().for_each(|field| {
panic!("Field with the same name `{}` defined in both struct and impl on type {:?}",
field,
<Self as #juniper_crate_name::GraphQLType<#scalar>>::name(info)
);
})
}
fields
})
} else {
let impl_fields = self.field_definition_tokens();
quote!(vec![ #( #impl_fields ),* ])
};
let resolve_matches = if self.include_struct_fields {
let impl_matches = self.resolve_matches_tokens(&scalar, &juniper_crate_name);
quote!(match field {
#( #impl_matches )*
_ => <Self as #juniper_crate_name::GraphQLTypeInfo<#scalar>>
::resolve_field(self, _info, field, args, executor)
})
} else {
let impl_matches = self.resolve_matches_tokens(&scalar, &juniper_crate_name);
quote!(match field {
#( #impl_matches )*
_ => {
panic!("Field {} not found on type {:?}",
field,
<Self as #juniper_crate_name::GraphQLType<#scalar>>::name(_info)
);
}
})
};
let description = self
.description
.as_ref()
.map(|description| quote!( .description(#description) ));
let interfaces = self.interfaces.as_ref().map(|items| {
quote!(
.interfaces(&[
#( registry.get_type::< #items >(&()) ,)*
])
)
});
// Preserve the original type_generics before modification,
// since alteration makes them invalid if self.generic_scalar
// is specified.
let (_, type_generics, _) = self.generics.split_for_impl();
let mut generics = self.generics.clone();
if self.scalar.is_none() && self.generic_scalar {
// No custom scalar specified, but always generic specified.
// Therefore we inject the generic scalar.
generics.params.push(parse_quote!(__S));
let where_clause = generics.where_clause.get_or_insert(parse_quote!(where));
// Insert ScalarValue constraint.
where_clause
.predicates
.push(parse_quote!(__S: #juniper_crate_name::ScalarValue));
}
let type_generics_tokens = if self.include_type_generics {
Some(type_generics)
} else {
None
};
let (impl_generics, _, where_clause) = generics.split_for_impl();
let resolve_field_async = {
let resolve_matches_async = self.fields.iter().map(|field| {
let name = &field.name;
let code = &field.resolver_code;
let _type = if field.is_type_inferred {
quote!()
} else {
let _type = &field._type;
quote!(: #_type)
};
if field.is_async {
quote!(
#name => {
let f = async move {