graphql-query 1.0.1

Stupendously fast and easy GraphQL Query Language handling.
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
use crate::ast::*;
use bumpalo::collections::Vec;

pub use super::{folder_simple::SimpleFolder, Path, PathSegment, VisitInfo};
pub use crate::error::{Error, Result};

pub(crate) mod private {
    use hashbrown::{hash_map::DefaultHashBuilder, HashMap};
    use std::cell::RefCell;

    use super::{ASTContext, Definition, Document, Folder, Result, Vec};
    use crate::{ast::FragmentDefinitionWithIndex, visit::VisitInfo};

    /// Private Folder context state that's kept to keep track of the current folding progress and
    /// state. This contains the AST context and optional records on fragments and the new document's
    /// definition if the `Folder` is being traversed by operation.
    pub struct FolderContext<'a> {
        pub(crate) ctx: &'a ASTContext,
        pub(crate) definitions: RefCell<Vec<'a, Definition<'a>>>,
        pub(crate) fragments: RefCell<
            HashMap<
                &'a str,
                FragmentDefinitionWithIndex<'a>,
                DefaultHashBuilder,
                &'a bumpalo::Bump,
            >,
        >,
        pub(crate) fragment_names:
            RefCell<HashMap<&'a str, &'a str, DefaultHashBuilder, &'a bumpalo::Bump>>,
        pub(crate) recurse: bool,
    }

    impl<'a> FolderContext<'a> {
        pub(crate) fn empty(ctx: &'a ASTContext) -> Self {
            FolderContext {
                ctx,
                fragments: RefCell::new(HashMap::new_in(&ctx.arena)),
                fragment_names: RefCell::new(HashMap::new_in(&ctx.arena)),
                definitions: RefCell::new(Vec::new_in(&ctx.arena)),
                recurse: false,
            }
        }

        pub(crate) fn new_vec<T>(&self) -> Vec<'_, T> {
            Vec::new_in(&self.ctx.arena)
        }

        pub(crate) fn with_document(ctx: &'a ASTContext, document: &'a Document<'a>) -> Self {
            FolderContext {
                ctx,
                fragments: RefCell::new(document.fragments_with_index(ctx)),
                fragment_names: RefCell::new(HashMap::new_in(&ctx.arena)),
                definitions: RefCell::new(Vec::new_in(&ctx.arena)),
                recurse: true,
            }
        }
    }

    pub trait FoldNode<'a>: Sized {
        fn fold_with_ctx<'b, F: Folder<'a>>(
            &self,
            info: &mut VisitInfo,
            ctx: &'a FolderContext<'a>,
            folder: &'b mut F,
        ) -> Result<Self>;
    }
}

/// Trait for a folder that carries methods that are called as callback while AST nodes
/// implementing the folder pattern are traversed and edited.
///
/// A Folder is used to traverse an GraphQL AST top-to-bottom, depth-first and to replace the AST's
/// nodes by calling the Folder's callbacks and replacing the AST nodes one by one. After an AST
/// Node is folded it's an entirely new copy, separate from the input AST, which remains untouched.
///
/// All callbacks have a default no-op implementation that return the input AST Node and hence only
/// create an unchanged copy of the AST.
/// The callbacks receive a reference to the [`ASTContext`] and must return the altered (or
/// unchanged) node that's placed into the new AST using a [Result]. This can be used to also
/// return an error and stop the folding.
///
/// This pattern is applicable to any AST node that implements the [`FoldNode`] trait.
pub trait Folder<'a> {
    /// Folds an [`OperationDefinition`] into a new node as part of a new, transformed AST, before
    /// the Operation is folded recursively
    #[inline]
    fn enter_operation(
        &mut self,
        _ctx: &'a ASTContext,
        operation: OperationDefinition<'a>,
        _info: &VisitInfo,
    ) -> Result<OperationDefinition<'a>> {
        Ok(operation)
    }

    /// Folds an [`OperationDefinition`] into a new node as part of a new, transformed AST, after
    /// the Operation has been folded.
    #[inline]
    fn leave_operation(
        &mut self,
        _ctx: &'a ASTContext,
        operation: OperationDefinition<'a>,
        _info: &VisitInfo,
    ) -> Result<OperationDefinition<'a>> {
        Ok(operation)
    }

    /// Folds a [`FragmentDefinition`] into a new node as part of a new, transformed AST, before the
    /// FragmentDefinition is folded recursively.
    #[inline]
    fn enter_fragment(
        &mut self,
        _ctx: &'a ASTContext,
        fragment: FragmentDefinition<'a>,
        _info: &VisitInfo,
    ) -> Result<FragmentDefinition<'a>> {
        Ok(fragment)
    }

    /// Folds a [`FragmentDefinition`] into a new node as part of a new, transformed AST, after the
    /// FragmentDefinition has been folded.
    #[inline]
    fn leave_fragment(
        &mut self,
        _ctx: &'a ASTContext,
        fragment: FragmentDefinition<'a>,
        _info: &VisitInfo,
    ) -> Result<FragmentDefinition<'a>> {
        Ok(fragment)
    }

    /// Folds a [`VariableDefinitions`] node into a new node as part of a new, transformed AST.
    #[inline]
    fn variable_definitions(
        &mut self,
        _ctx: &'a ASTContext,
        var_defs: VariableDefinitions<'a>,
        _info: &VisitInfo,
    ) -> Result<VariableDefinitions<'a>> {
        Ok(var_defs)
    }

    /// Folds a [`VariableDefinition`] into a new node as part of a new, transformed AST.
    #[inline]
    fn variable_definition(
        &mut self,
        _ctx: &'a ASTContext,
        var_def: VariableDefinition<'a>,
        _info: &VisitInfo,
    ) -> Result<VariableDefinition<'a>> {
        Ok(var_def)
    }

    /// Folds a [`SelectionSet`] into a new node as part of a new, transformed AST.
    #[inline]
    fn selection_set(
        &mut self,
        _ctx: &'a ASTContext,
        selection_set: SelectionSet<'a>,
        _info: &VisitInfo,
    ) -> Result<SelectionSet<'a>> {
        Ok(selection_set)
    }

    /// Folds a [`FragmentSpread`] node into a new node as part of a new, transformed AST, before
    /// the FragmentSpread is folded recursively.
    #[inline]
    fn enter_fragment_spread(
        &mut self,
        _ctx: &'a ASTContext,
        fragment_spread: FragmentSpread<'a>,
        _info: &VisitInfo,
    ) -> Result<FragmentSpread<'a>> {
        Ok(fragment_spread)
    }

    /// Folds a [`FragmentSpread`] node into a new node as part of a new, transformed AST, after
    /// the FragmentSpread has been folded.
    #[inline]
    fn leave_fragment_spread(
        &mut self,
        _ctx: &'a ASTContext,
        fragment_spread: FragmentSpread<'a>,
        _info: &VisitInfo,
    ) -> Result<FragmentSpread<'a>> {
        Ok(fragment_spread)
    }

    /// Folds an [`InlineFragment`] into a new node as part of a new, transformed AST, before the
    /// InlineFragment is folded recursively.
    #[inline]
    fn enter_inline_fragment(
        &mut self,
        _ctx: &'a ASTContext,
        inline_fragment: InlineFragment<'a>,
        _info: &VisitInfo,
    ) -> Result<InlineFragment<'a>> {
        Ok(inline_fragment)
    }

    /// Folds an [`InlineFragment`] into a new node as part of a new, transformed AST, after the
    /// InlineFragment has been folded.
    #[inline]
    fn leave_inline_fragment(
        &mut self,
        _ctx: &'a ASTContext,
        inline_fragment: InlineFragment<'a>,
        _info: &VisitInfo,
    ) -> Result<InlineFragment<'a>> {
        Ok(inline_fragment)
    }

    /// Folds a [Field] into a new node as part of a new, transformed AST, before the Field is
    /// folded recursively.
    #[inline]
    fn enter_field(
        &mut self,
        _ctx: &'a ASTContext,
        field: Field<'a>,
        _info: &VisitInfo,
    ) -> Result<Field<'a>> {
        Ok(field)
    }

    /// Folds a [Field] into a new node as part of a new, transformed AST, after the field has been
    /// folded.
    #[inline]
    fn leave_field(
        &mut self,
        _ctx: &'a ASTContext,
        field: Field<'a>,
        _info: &VisitInfo,
    ) -> Result<Field<'a>> {
        Ok(field)
    }

    /// Folds a [Directives] node into a new node as part of a new, transformed AST.
    #[inline]
    fn directives(
        &mut self,
        _ctx: &'a ASTContext,
        directives: Directives<'a>,
        _info: &VisitInfo,
    ) -> Result<Directives<'a>> {
        Ok(directives)
    }

    /// Folds a [Directive] into a new node as part of a new, transformed AST, before the Directive
    /// is folded recursively.
    #[inline]
    fn enter_directive(
        &mut self,
        _ctx: &'a ASTContext,
        directive: Directive<'a>,
        _info: &VisitInfo,
    ) -> Result<Directive<'a>> {
        Ok(directive)
    }

    /// Folds a [Directive] into a new node as part of a new, transformed AST, after the Directive
    /// has been folded.
    #[inline]
    fn leave_directive(
        &mut self,
        _ctx: &'a ASTContext,
        directive: Directive<'a>,
        _info: &VisitInfo,
    ) -> Result<Directive<'a>> {
        Ok(directive)
    }

    /// Folds a [Arguments] node into a new node as part of a new, transformed AST.
    #[inline]
    fn arguments(
        &mut self,
        _ctx: &'a ASTContext,
        arguments: Arguments<'a>,
        _info: &VisitInfo,
    ) -> Result<Arguments<'a>> {
        Ok(arguments)
    }

    /// Folds an [Argument] into a new node as part of a new, transformed AST.
    #[inline]
    fn argument(
        &mut self,
        _ctx: &'a ASTContext,
        argument: Argument<'a>,
        _info: &VisitInfo,
    ) -> Result<Argument<'a>> {
        Ok(argument)
    }

    /// Folds a [Value] node into a new node as part of a new, transformed AST.
    #[inline]
    fn value(
        &mut self,
        _ctx: &'a ASTContext,
        value: Value<'a>,
        _info: &VisitInfo,
    ) -> Result<Value<'a>> {
        Ok(value)
    }

    /// Folds a [Type] node into a new node as part of a new, transformed AST.
    #[inline]
    fn of_type(
        &mut self,
        _ctx: &'a ASTContext,
        of_type: Type<'a>,
        _info: &VisitInfo,
    ) -> Result<Type<'a>> {
        Ok(of_type)
    }

    /// Folds a [Variable] node into a new node as part of a new, transformed AST.
    #[inline]
    fn variable(
        &mut self,
        _ctx: &'a ASTContext,
        var: Variable<'a>,
        _info: &VisitInfo,
    ) -> Result<Variable<'a>> {
        Ok(var)
    }

    /// Folds a [`NamedType`] node into a new node as part of a new, transformed AST.
    #[inline]
    fn named_type(
        &mut self,
        _ctx: &'a ASTContext,
        name: NamedType<'a>,
        _info: &VisitInfo,
    ) -> Result<NamedType<'a>> {
        Ok(name)
    }
}

/// Trait for folding AST Nodes of a GraphQL language document in depth-first order using a
/// custom folder. This transforms the AST while creating a new copy of it.
///
/// The folder must implement the [Folder] trait.
pub trait FoldNode<'a>: private::FoldNode<'a> {
    /// Visit the GraphQL AST node tree recursively in depth-first order and create a transformed
    /// copy of it using the given folder. The folder must implement the [Folder] trait.
    ///
    /// This will return a [Result] containing a reference to the new copied AST Node allocated on
    /// the current AST Context's arena or an error.
    fn fold<'b, F: Folder<'a>>(
        &'a self,
        ctx: &'a ASTContext,
        folder: &'b mut F,
    ) -> Result<&'a Self> {
        let mut info = VisitInfo::default();
        let folder_ctx = ctx.alloc(private::FolderContext::empty(ctx));
        Ok(ctx.alloc(self.fold_with_ctx(&mut info, folder_ctx, folder)?))
    }
}

/// Trait for folding a GraphQL Document AST Node by traversing an operation instead of the entire
/// AST tree. This method alters the traversal of the folder and traverses starting from an operation
/// instead; folding the fragment definitions only as they're used and refered to using
/// `FragmentSpread` nodes in the operation.
///
/// If a Document should instead be transformed and copied in its entirety then `Document::fold` is
/// a better choice.
pub trait FoldDocument<'a>: private::FoldNode<'a> {
    /// Folds a GraphQL document by a given operation instead. Instead of transforming the given
    /// document in its entirety `fold_operation` will start at the defined operation instead,
    /// transforming fragments only as they're referred to via `FragmentSpread` nodes. This will
    /// create a new document that only refers to and contains the specified `operation`.
    fn fold_operation<'b, F: Folder<'a>>(
        &'a self,
        ctx: &'a ASTContext,
        operation: Option<&'a str>,
        folder: &'b mut F,
    ) -> Result<&'a Self>;
}

impl<'a, T: private::FoldNode<'a>> FoldNode<'a> for T {}

impl<'a> private::FoldNode<'a> for Type<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'b private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        folder.of_type(ctx.ctx, *self, info)
    }
}

impl<'a> private::FoldNode<'a> for Value<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        folder.value(ctx.ctx, self.clone(), info)
    }
}

impl<'a> private::FoldNode<'a> for NamedType<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        folder.named_type(ctx.ctx, *self, info)
    }
}

impl<'a> private::FoldNode<'a> for Variable<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        folder.variable(ctx.ctx, *self, info)
    }
}

impl<'a> private::FoldNode<'a> for Argument<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        let argument = folder.argument(ctx.ctx, self.clone(), info)?;

        info.path.push(PathSegment::Value);
        let value = argument.value.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        Ok(Argument {
            name: argument.name,
            value,
        })
    }
}

impl<'a> private::FoldNode<'a> for Arguments<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        let new_arguments_iter = {
            folder
                .arguments(ctx.ctx, self.clone(), info)?
                .into_iter()
                .enumerate()
                .map(|(index, argument)| {
                    info.path.push(PathSegment::Index(index));
                    let folded = argument.fold_with_ctx(info, ctx, folder);
                    info.path.pop();
                    folded
                })
        };

        let new_arguments = {
            let mut new_arguments = ctx.new_vec();
            for item in new_arguments_iter {
                new_arguments.push(item?);
            }

            new_arguments
        };

        Ok(Arguments {
            children: new_arguments,
        })
    }
}

impl<'a> private::FoldNode<'a> for Directive<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        let directive = &folder.enter_directive(ctx.ctx, self.clone(), info)?;

        info.path.push(PathSegment::Arguments);
        let arguments = directive.arguments.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        let directive = Directive {
            name: directive.name,
            arguments,
        };
        folder.leave_directive(ctx.ctx, directive, info)
    }
}

impl<'a> private::FoldNode<'a> for Directives<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        // TODO: how to make this Result dissapear
        let new_directives_iter = folder
            .directives(ctx.ctx, self.clone(), info)?
            .into_iter()
            .enumerate()
            .map(|(index, directive)| {
                info.path.push(PathSegment::Index(index));
                let folded = directive.fold_with_ctx(info, ctx, folder);
                info.path.pop();
                folded
            });

        let mut new_directives = Vec::new_in(&ctx.ctx.arena);
        for item in new_directives_iter {
            new_directives.push(item?);
        }
        Ok(Directives {
            children: new_directives,
        })
    }
}

impl<'a> private::FoldNode<'a> for VariableDefinition<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        let var_def = folder.variable_definition(ctx.ctx, self.clone(), info)?;

        info.path.push(PathSegment::Variable);
        let variable = var_def.variable.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        info.path.push(PathSegment::Type);
        let of_type = var_def.of_type.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        info.path.push(PathSegment::Value);
        let default_value = var_def.default_value.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        info.path.push(PathSegment::Directives);
        let directives = var_def.directives.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        Ok(VariableDefinition {
            variable,
            of_type,
            default_value,
            directives,
        })
    }
}

impl<'a> private::FoldNode<'a> for VariableDefinitions<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        let new_variables_iter = folder
            .variable_definitions(ctx.ctx, self.clone(), info)?
            .into_iter()
            .enumerate()
            .map(|(index, var_def)| {
                info.path.push(PathSegment::Index(index));
                let folded = var_def.fold_with_ctx(info, ctx, folder);
                info.path.pop();
                folded
            });

        let mut new_variables = Vec::new_in(&ctx.ctx.arena);
        for item in new_variables_iter {
            new_variables.push(item?);
        }
        Ok(VariableDefinitions {
            children: new_variables,
        })
    }
}

impl<'a> private::FoldNode<'a> for Field<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        let field = &folder.enter_field(ctx.ctx, self.clone(), info)?;

        info.path.push(PathSegment::Arguments);
        let arguments = field.arguments.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        info.path.push(PathSegment::Directives);
        let directives = field.directives.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        info.path.push(PathSegment::SelectionSet);
        let selection_set = field.selection_set.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        let field = Field {
            alias: field.alias,
            name: field.name,
            arguments,
            directives,
            selection_set,
        };
        folder.leave_field(ctx.ctx, field, info)
    }
}

impl<'a> private::FoldNode<'a> for FragmentSpread<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        let spread = &folder.enter_fragment_spread(ctx.ctx, self.clone(), info)?;
        let spread = if ctx.recurse {
            let fragment_name = spread.name.name;

            // Check if fragment was already visited (short borrow, released before recursion)
            let already_visited = {
                let borrowed = ctx.fragment_names.borrow();
                borrowed.get(fragment_name).copied()
            };

            let fragment_name = if let Some(fragment_name) = already_visited {
                fragment_name
            } else {
                // Get the fragment definition (short borrow of fragments)
                let fragment_and_index = ctx
                    .fragments
                    .borrow()
                    .get(spread.name.name)
                    .map(|f| (f.fragment.clone(), f.index));

                if let Some((fragment, index)) = fragment_and_index {
                    let path = info.path.clone();
                    info.path = Path::default();
                    info.path.push(PathSegment::Index(index.to_owned()));
                    let fragment = fragment.fold_with_ctx(info, ctx, folder)?;
                    info.path = path;

                    let fragment_name = fragment.name.name;
                    // TODO: was prepend before
                    ctx.definitions
                        .borrow_mut()
                        .push(Definition::Fragment(fragment));
                    ctx.fragment_names
                        .borrow_mut()
                        .insert(fragment_name, fragment_name);
                    fragment_name
                } else {
                    return Err(Error::new(
                        format!("The fragment '{}' does not exist", fragment_name),
                        None,
                    ));
                }
            };

            info.path.push(PathSegment::Directives);
            let directives = spread.directives.fold_with_ctx(info, ctx, folder)?;
            info.path.pop();

            FragmentSpread {
                name: fragment_name.into(),
                directives,
            }
        } else {
            info.path.push(PathSegment::Name);
            let name = spread.name.fold_with_ctx(info, ctx, folder)?;
            info.path.pop();

            info.path.push(PathSegment::Directives);
            let directives = spread.directives.fold_with_ctx(info, ctx, folder)?;
            info.path.pop();

            FragmentSpread { name, directives }
        };
        folder.leave_fragment_spread(ctx.ctx, spread, info)
    }
}

impl<'a> private::FoldNode<'a> for InlineFragment<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        let fragment = folder.enter_inline_fragment(ctx.ctx, self.clone(), info)?;

        let type_condition = match fragment.type_condition {
            Some(condition) => {
                info.path.push(PathSegment::Name);
                let folded = condition.fold_with_ctx(info, ctx, folder)?;
                info.path.pop();
                Some(folded)
            }
            None => None,
        };

        info.path.push(PathSegment::Directives);
        let directives = fragment.directives.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        info.path.push(PathSegment::SelectionSet);
        let selection_set = fragment.selection_set.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        let fragment = InlineFragment {
            type_condition,
            directives,
            selection_set,
        };
        folder.leave_inline_fragment(ctx.ctx, fragment, info)
    }
}

impl<'a> private::FoldNode<'a> for SelectionSet<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        let new_selections_iter = folder
            .selection_set(ctx.ctx, self.clone(), info)?
            .into_iter()
            .enumerate()
            .map(|(index, selection)| -> Result<Selection> {
                info.path.push(PathSegment::Index(index));
                let folded = match selection {
                    Selection::Field(field) => Ok(field.fold_with_ctx(info, ctx, folder)?.into()),
                    Selection::FragmentSpread(spread) => {
                        Ok(spread.fold_with_ctx(info, ctx, folder)?.into())
                    }
                    Selection::InlineFragment(fragment) => {
                        Ok(fragment.fold_with_ctx(info, ctx, folder)?.into())
                    }
                };
                info.path.pop();
                folded
            });

        let mut new_selections = Vec::new_in(&ctx.ctx.arena);
        for item in new_selections_iter {
            new_selections.push(item?);
        }
        Ok(SelectionSet {
            selections: new_selections,
        })
    }
}

impl<'a> private::FoldNode<'a> for FragmentDefinition<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        let fragment = &folder.enter_fragment(ctx.ctx, self.clone(), info)?;

        info.path.push(PathSegment::Name);
        let name = fragment.name.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        info.path.push(PathSegment::Type);
        let type_condition = fragment.type_condition.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        info.path.push(PathSegment::Directives);
        let directives = fragment.directives.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        info.path.push(PathSegment::SelectionSet);
        let selection_set = fragment.selection_set.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        let fragment = FragmentDefinition {
            name,
            type_condition,
            directives,
            selection_set,
        };
        folder.leave_fragment(ctx.ctx, fragment, info)
    }
}

impl<'a> private::FoldNode<'a> for OperationDefinition<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        let operation = &folder.enter_operation(ctx.ctx, self.clone(), info)?;

        info.path.push(PathSegment::VariableDefinitions);
        let variable_definitions = operation
            .variable_definitions
            .fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        info.path.push(PathSegment::Directives);
        let directives = operation.directives.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        info.path.push(PathSegment::SelectionSet);
        let selection_set = operation.selection_set.fold_with_ctx(info, ctx, folder)?;
        info.path.pop();

        let operation = OperationDefinition {
            operation: operation.operation,
            name: operation.name,
            variable_definitions,
            directives,
            selection_set,
        };
        folder.leave_operation(ctx.ctx, operation, info)
    }
}

impl<'a> private::FoldNode<'a> for Document<'a> {
    #[inline]
    fn fold_with_ctx<'b, F: Folder<'a>>(
        &self,
        info: &mut VisitInfo,
        ctx: &'a private::FolderContext<'a>,
        folder: &'b mut F,
    ) -> Result<Self> {
        let new_definitions_iter =
            self.definitions
                .iter()
                .enumerate()
                .map(|(index, selection)| -> Result<Definition> {
                    info.path.push(PathSegment::Index(index));
                    let folded = match selection {
                        Definition::Operation(operation) => {
                            Ok(operation.fold_with_ctx(info, ctx, folder)?.into())
                        }
                        Definition::Fragment(fragment) => {
                            Ok(fragment.fold_with_ctx(info, ctx, folder)?.into())
                        }
                    };
                    info.path.pop();
                    folded
                });
        let mut new_definitions = Vec::new_in(&ctx.ctx.arena);
        for item in new_definitions_iter.rev() {
            new_definitions.push(item?);
        }
        Ok(Document {
            definitions: new_definitions,
            size_hint: self.size_hint,
        })
    }
}

impl<'a> FoldDocument<'a> for Document<'a> {
    /// Folds a GraphQL document by a given operation instead. Instead of transforming the given
    /// document in its entirety `fold_operation` will start at the defined operation instead,
    /// transforming fragments only as they're referred to via `FragmentSpread` nodes. This will
    /// create a new document that only refers to and contains the specified `operation`.
    fn fold_operation<'b, F: Folder<'a>>(
        &'a self,
        ctx: &'a ASTContext,
        operation_name: Option<&'a str>,
        folder: &'b mut F,
    ) -> Result<&'a Self> {
        let (operation, index) = self.operation_with_index(operation_name)?;
        let folder_ctx = ctx.alloc(private::FolderContext::with_document(ctx, self));
        let mut info = VisitInfo::default();
        info.path.push(PathSegment::Index(index));
        let operation = private::FoldNode::fold_with_ctx(operation, &mut info, folder_ctx, folder)?;

        let mut borrowed_definitions = folder_ctx.definitions.clone().into_inner();

        borrowed_definitions.push(Definition::Operation(operation));
        Ok(ctx.alloc(Document {
            definitions: Vec::from_iter_in(borrowed_definitions.into_iter().rev(), &ctx.arena),
            size_hint: self.size_hint,
        }))
    }
}

#[cfg(test)]
mod tests {
    use bumpalo::collections::CollectIn;

    use super::{super::*, FoldNode, Folder, Result};
    use crate::{
        ast::*,
        visit::{folder::FoldDocument, folder_simple::SimpleFolder},
    };

    #[test]
    fn kitchen_sink() {
        #[derive(Default)]
        struct FoldNoop {}
        impl<'a> SimpleFolder<'a> for FoldNoop {}

        let ctx = ASTContext::new();
        let query = include_str!("../../fixture/kitchen_sink.graphql");
        let ast = Document::parse(&ctx, query).unwrap();

        let output = ast
            .fold_operation(&ctx, Some("queryName"), &mut FoldNoop::default())
            .unwrap();

        let actual = output.print();
        let expected = indoc::indoc! {r#"
            query queryName($foo: ComplexType, $site: Site = MOBILE) @onQuery {
              whoever123is: node(id: [123, 456]) {
                id
                ... on User @onInlineFragment {
                  field2 {
                    id
                    alias: field1(first: 10, after: $foo) @include(if: $foo) {
                      id
                      ...frag @onFragmentSpread
                    }
                  }
                }
                ... @skip(unless: $foo) {
                  id
                }
                ... {
                  id
                }
              }
            }

            fragment frag on Friend @onFragmentDefinition {
              foo(size: $site, bar: 12, obj: {key: "value", block: """
              block string uses \"""
              """})
            }"#};

        assert_eq!(actual, expected);
    }

    struct InfoFolder {}

    impl<'a> Folder<'a> for InfoFolder {
        fn enter_fragment_spread(
            &mut self,
            _ctx: &'a ASTContext,
            fragment_spread: FragmentSpread<'a>,
            info: &VisitInfo,
        ) -> Result<FragmentSpread<'a>> {
            // We run this folder on the kitchen sink query which contains
            // exactly one fragment spread at the following location
            let expected_path = Path::try_from(
                "0.selectionSet.0.selectionSet.1.selectionSet.0.selectionSet.1.selectionSet.1",
            )
            .unwrap();
            assert_eq!(info.path, expected_path);
            Ok(fragment_spread)
        }

        fn value(
            &mut self,
            _ctx: &'a ASTContext,
            value: Value<'a>,
            info: &VisitInfo,
        ) -> Result<Value<'a>> {
            if let Value::Object(_) = value {
                // We run this folder on the kitchen sink query which contains
                // exactly one object value at the following location
                let expected_path = Path::try_from("3.selectionSet.0.arguments.2.value").unwrap();
                assert_eq!(info.path, expected_path);
            }

            Ok(value)
        }
    }

    #[test]
    fn fold_info_path() {
        let ctx = ASTContext::new();
        let query = include_str!("../../fixture/kitchen_sink.graphql");
        let ast = Document::parse(&ctx, query).unwrap();

        let mut folder = InfoFolder {};
        let _ = ast.fold(&ctx, &mut folder).unwrap();
    }

    #[test]
    fn fold_operation_info_path() {
        let ctx = ASTContext::new();
        let query = include_str!("../../fixture/kitchen_sink.graphql");
        let ast = Document::parse(&ctx, query).unwrap();

        let mut folder = InfoFolder {};
        let _ = ast
            .fold_operation(&ctx, Some("queryName"), &mut folder)
            .unwrap();
    }

    struct AddTypenames {}

    use std::iter;

    impl<'arena> Folder<'arena> for AddTypenames {
        fn selection_set(
            &mut self,
            ctx: &'arena ASTContext,
            selection_set: SelectionSet<'arena>,
            _info: &VisitInfo,
        ) -> Result<SelectionSet<'arena>> {
            if selection_set.is_empty() {
                return Ok(selection_set);
            }

            let has_typename = selection_set.selections.iter().any(|selection| {
                selection
                    .field()
                    .map(|field| field.name == "__typename" && field.alias.is_none())
                    .unwrap_or(false)
            });

            if !has_typename {
                let typename_field = Selection::Field(Field {
                    alias: None,
                    name: "__typename",
                    arguments: Arguments::default_in(&ctx.arena),
                    directives: Directives::default_in(&ctx.arena),
                    selection_set: SelectionSet::default_in(&ctx.arena),
                });

                let new_selections =
                    selection_set
                        .into_iter()
                        .chain(iter::once(typename_field))
                        .collect_in::<bumpalo::collections::Vec<Selection>>(&ctx.arena);

                Ok(SelectionSet {
                    selections: new_selections,
                })
            } else {
                Ok(selection_set)
            }
        }
    }

    #[test]
    fn fold_typename() {
        let ctx = ASTContext::new();
        let query = "query { todo { id author { id } } }";
        let ast = Document::parse(&ctx, query).unwrap();

        let mut folder = AddTypenames {};
        let new_ast = ast.fold_operation(&ctx, None, &mut folder);
        assert_eq!(
            new_ast.unwrap().print(),
            "{\n  todo {\n    id\n    author {\n      id\n      __typename\n    }\n    __typename\n  }\n  __typename\n}"
        );
    }
}