bevy_scene_macros 0.19.0

Derive implementations for bevy_scene
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
use crate::bsn::types::{
    Bsn, BsnConstructor, BsnEntry, BsnFields, BsnFnArg, BsnFnArgs, BsnListRoot,
    BsnRelatedSceneList, BsnRoot, BsnScene, BsnSceneFn, BsnSceneListItem, BsnSceneListItems,
    BsnType, BsnValue,
};
use bevy_macro_utils::{fq_std::FQDefault, path_to_string};
use proc_macro2::TokenStream;
use quote::{format_ident, quote, ToTokens};
use std::collections::{hash_map::Entry, HashMap, HashSet};
use syn::{parse::Parse, ExprTuple, Ident, Index, Lit, Member, Path};

/// Tracks named entity references and assigns them unique, sequential indices
/// during the code generation process.
#[derive(Default)]
pub(crate) struct EntityRefs {
    refs: HashMap<String, usize>,
    next: usize,
}

impl EntityRefs {
    /// Retrieves the index for a given entity name.
    /// Creates a new one if it hasn't been seen yet.
    fn get(&mut self, name: String) -> usize {
        match self.refs.entry(name) {
            Entry::Occupied(entry) => *entry.get(),
            Entry::Vacant(entry) => {
                let index = self.next;
                entry.insert(index);
                self.next += 1;
                index
            }
        }
    }
}

#[derive(Default)]
pub(crate) struct HoistedExpressions {
    expressions: Vec<TokenStream>,
    next: usize,
}

impl HoistedExpressions {
    fn next_ident(&mut self) -> Ident {
        let index = self.next;
        let ident = format_ident!("_expr{index}");
        self.next += 1;
        ident
    }

    pub fn hoist(&mut self, value: &BsnValue) -> Ident {
        let ident = self.next_ident();
        self.expressions.push(quote! {let #ident = #value;});
        ident
    }
}

/// Context used in the [`Bsn`] code generation pipeline.
/// Used to accumulate validation errors without short-circuiting.
pub(crate) struct BsnCodegenCtx<'a> {
    pub bevy_scene: &'a Path,
    pub bevy_ecs: &'a Path,
    pub invocation_index: ExprTuple,
    pub entity_refs: &'a mut EntityRefs,
    pub hoisted_expressions: &'a mut HoistedExpressions,
    /// Accumulated parsing and validation errors.
    pub errors: Vec<syn::Error>,
}
impl<'a> BsnCodegenCtx<'a> {
    fn fixed_entity_ref(&mut self, ident: &Ident) -> (String, usize) {
        let string = ident.to_string();
        (ident.to_string(), self.entity_refs.get(string))
    }
}

/// Represents the target path and whether it is a reference, e.g.,
/// when applying a template patch.
struct PatchTarget<'a> {
    /// The path to the field being patched.
    pub path: &'a [Member],
    /// Whether the target is a reference.
    /// - `true`: Requires dereferencing (`*`) to assign a value to the target.
    /// - `false`: Requires a mutable borrow (`&mut`) to create a temporary
    ///   reference.
    pub is_ref: bool,
}

pub trait BsnTokenStream: Parse {
    fn to_tokens(&self, ctx: &mut BsnCodegenCtx) -> TokenStream;
}

impl BsnTokenStream for BsnRoot {
    fn to_tokens(&self, ctx: &mut BsnCodegenCtx) -> TokenStream {
        let tokens = self.0.to_tokens(ctx);
        let errors = ctx.errors.iter().map(|e| e.to_compile_error());
        let bevy_scene = ctx.bevy_scene;
        let hoisted_exprs = ctx.hoisted_expressions.expressions.drain(..);
        let call_id = if !ctx.entity_refs.refs.is_empty() {
            quote! {
                static _CALL_ID: #bevy_scene::macro_utils::CallCounter = #bevy_scene::macro_utils::CallCounter::new();
                let _call_id = _CALL_ID.increment();
            }
        } else {
            quote! {}
        };

        // NOTE: Assigning the result to a variable first so that the LSP's
        // type inference can see assignments before it encounters
        // any compile errors. This keeps autocomplete working in broken states,
        // e.g. when typing the name of a field but no value yet.
        quote! {
            #bevy_scene::SceneScope({
                #call_id
                #(#hoisted_exprs)*
                let _res = #tokens;
                #(#errors)*
                _res
            })
        }
    }
}

impl BsnTokenStream for BsnListRoot {
    fn to_tokens(&self, ctx: &mut BsnCodegenCtx) -> TokenStream {
        let tokens = self.0.to_tokens(ctx);
        let errors = ctx.errors.iter().map(|e| e.to_compile_error());
        let bevy_scene = ctx.bevy_scene;
        let hoisted_exprs = ctx.hoisted_expressions.expressions.drain(..);
        let call_id = if !ctx.entity_refs.refs.is_empty() {
            quote! {
                static _CALL_ID: #bevy_scene::macro_utils::CallCounter = #bevy_scene::macro_utils::CallCounter::new();
                let _call_id = _CALL_ID.increment();
            }
        } else {
            quote! {}
        };

        // NOTE: Assigning the result to a variable first so that the LSP's
        // type inference can see assignments before it encounters
        // any compile errors. This keeps autocomplete working in broken states,
        // e.g. when typing the name of a field but no value yet.
        quote! {
            {
                #call_id
                #(#hoisted_exprs)*
                let _res = #bevy_scene::SceneListScope(#tokens);
                #(#errors)*
                _res
            }
        }
    }
}

impl<const ALLOW_FLAT: bool> Bsn<ALLOW_FLAT> {
    /// Converts to tokens and performs validation checks.
    /// Accumulates errors in [`BsnCodegenCtx`].
    pub fn try_to_tokens(&self, ctx: &mut BsnCodegenCtx) -> syn::Result<TokenStream> {
        let bevy_scene = ctx.bevy_scene;
        let mut combined_patches = Vec::new();
        let mut scene_impls = Vec::new();
        for entry in &self.entries {
            match entry.try_to_tokens(ctx) {
                Ok(EntryResult::CombinedSceneFunction(patch)) => combined_patches.push(patch),
                Ok(EntryResult::NewSceneImpl(scene_impl)) => {
                    if !combined_patches.is_empty() {
                        let patches = combined_patches.drain(..);
                        scene_impls.push(quote! {
                            #bevy_scene::SceneFunction(move |_context, _scene| {
                                #(#patches)*
                            })
                        });
                    }
                    scene_impls.push(scene_impl)
                }
                Err(err) => scene_impls.push(err.to_compile_error()),
            }
        }
        if !combined_patches.is_empty() {
            let patches = combined_patches.drain(..);
            scene_impls.push(quote! {
                #bevy_scene::SceneFunction(move |_context, _scene| {
                    #(#patches)*
                })
            });
        }
        Ok(quote! { #bevy_scene::auto_nest_tuple!(#(#scene_impls),*) })
    }

    pub fn to_tokens(&self, ctx: &mut BsnCodegenCtx) -> TokenStream {
        self.try_to_tokens(ctx)
            .unwrap_or_else(|e| e.to_compile_error())
    }
}

enum EntryResult {
    CombinedSceneFunction(TokenStream),
    NewSceneImpl(TokenStream),
}

impl BsnEntry {
    fn try_to_tokens(&self, ctx: &mut BsnCodegenCtx) -> syn::Result<EntryResult> {
        let (bevy_scene, bevy_ecs) = (ctx.bevy_scene, ctx.bevy_ecs);

        Ok(match self {
            BsnEntry::TemplatePatch(ty) => {
                let mut assigns = Vec::new();
                let target = PatchTarget {
                    path: &[Member::Named(Ident::new(
                        "__value",
                        proc_macro2::Span::call_site(),
                    ))],
                    is_ref: true,
                };
                ty.to_patch_tokens(ctx, &mut assigns, true, false, true, target)?;
                let path = &ty.path;
                EntryResult::CombinedSceneFunction(if assigns.is_empty() {
                    quote! {
                        let _ = _scene.get_or_insert_template::<#path>(_context);
                    }
                } else {
                    quote! {
                        let __value = _scene.get_or_insert_template::<#path>(_context);
                        #(#assigns)*
                    }
                })
            }
            BsnEntry::FromTemplatePatch(ty) => {
                let mut assigns = Vec::new();
                let target = PatchTarget {
                    path: &[Member::Named(Ident::new(
                        "__value",
                        proc_macro2::Span::call_site(),
                    ))],
                    is_ref: true,
                };
                ty.to_patch_tokens(ctx, &mut assigns, true, false, false, target)?;
                let path = &ty.path;
                EntryResult::CombinedSceneFunction(if assigns.is_empty() {
                    quote! {
                        let _ = _scene.get_or_insert_template::<<#path as #bevy_ecs::template::FromTemplate>::Template>(_context);
                    }
                } else {
                    quote! {
                        let __value = _scene.get_or_insert_template::<<#path as #bevy_ecs::template::FromTemplate>::Template>(_context);
                        #(#assigns)*
                    }
                })
            }
            BsnEntry::TemplateConst {
                type_path,
                const_ident,
            } => EntryResult::CombinedSceneFunction(quote! {
                let __value = _scene.get_or_insert_template::<#type_path>(_context);
                *__value = #type_path::#const_ident;
            }),
            BsnEntry::TemplateConstructor(BsnConstructor {
                type_path,
                function,
                args,
            }) => EntryResult::CombinedSceneFunction({
                let args = args.to_tokens(ctx);
                quote! {
                    let __value = _scene.get_or_insert_template::<#type_path>(_context);
                    *__value = #type_path::#function #args;
                }
            }),
            BsnEntry::FromTemplateConstructor(BsnConstructor {
                type_path,
                function,
                args,
            }) => EntryResult::CombinedSceneFunction({
                let args = args.to_tokens(ctx);
                quote! {
                    let __value = _scene.get_or_insert_template::<<#type_path as #bevy_ecs::template::FromTemplate>::Template>(_context);
                    *__value = <#type_path as #bevy_ecs::template::FromTemplate>::Template::#function #args;
                }
            }),
            BsnEntry::RelatedSceneList(BsnRelatedSceneList {
                scene_list,
                relationship_path,
            }) => {
                let scenes = scene_list.0.to_tokens(ctx);
                EntryResult::NewSceneImpl(quote! {
                    #bevy_scene::RelatedScenes::<<#relationship_path as #bevy_ecs::relationship::RelationshipTarget>
                    ::Relationship, _>::new(#scenes)
                })
            }
            BsnEntry::UncachedScene(s) => EntryResult::NewSceneImpl(s.to_tokens(ctx)?),
            BsnEntry::CachedScene(s) => EntryResult::NewSceneImpl(s.to_tokens(ctx)?),
            BsnEntry::Name(ident) => {
                let (name, index) = ctx.fixed_entity_ref(ident);
                let invocation = ctx.invocation_index.clone();
                EntryResult::CombinedSceneFunction(quote! {
                    #bevy_scene::NameEntityReference { name: #bevy_ecs::name::Name(#name.into()), reference: #bevy_ecs::template::SceneEntityReference::new(#invocation, #index, _call_id,) }.resolve_inline(_context, _scene);
                })
            }
        })
    }
}

impl BsnScene {
    fn to_tokens(&self, ctx: &mut BsnCodegenCtx) -> syn::Result<TokenStream> {
        let bevy_scene = ctx.bevy_scene;
        match self {
            BsnScene::Asset(lit) => Ok(quote! {
                #bevy_scene::CachedSceneAsset::from(#lit)
            }),
            BsnScene::Fn(func) => Ok(func.to_tokens(ctx)),
            BsnScene::SceneComponent(bsn_type) => {
                // TODO: this can and should use a simpler codegen path than BsnType::to_patch_tokens,
                // which imposes constraints like requiring the type to impl FromTemplate, and requiring
                // enums to have VariantDefault.
                let mut assignments = Vec::new();
                let props = format_ident!("__props");
                let props_ref = format_ident!("__props_ref");
                let target = PatchTarget {
                    path: &[Member::Named(props_ref.clone())],
                    is_ref: true,
                };
                bsn_type.to_patch_tokens(ctx, &mut assignments, false, true, true, target)?;
                let mut assigns = Vec::new();
                let target = PatchTarget {
                    path: &[Member::Named(Ident::new(
                        "__value",
                        proc_macro2::Span::call_site(),
                    ))],
                    is_ref: true,
                };
                bsn_type.to_patch_tokens(ctx, &mut assigns, true, false, true, target)?;
                let path = &bsn_type.path;
                let bevy_scene = ctx.bevy_scene;
                let from_template_patch = quote! {
                    <#path as #bevy_scene::PatchFromTemplate>::patch(move |__value, _context| {
                        #(#assigns)*
                    })
                };
                Ok(quote! {{
                    let mut #props = <<#path as #bevy_scene::SceneComponent>::Props as #FQDefault>::default();
                    let #props_ref = &mut #props;
                    #(#assignments)*
                    (<#path as #bevy_scene::SceneComponent>::scene(#props), #from_template_patch)
                }})
            }
            BsnScene::Expression(tokens) => Ok(quote! {
                #tokens
            }),
        }
    }
}

impl BsnType {
    /// Recursively generates token streams.
    fn to_patch_tokens(
        &self,
        ctx: &mut BsnCodegenCtx,
        assignments: &mut Vec<TokenStream>,
        is_root: bool,
        is_props: bool,
        is_scene_component: bool,
        target: PatchTarget,
    ) -> syn::Result<()> {
        if !is_root {
            let (path, bevy_scene) = (&self.path, ctx.bevy_scene);
            assignments.push(quote! {#bevy_scene::macro_utils::touch_type::<#path>();});
        }

        if let Some(variant) = &self.enum_variant {
            if is_props {
                self.push_struct_patch(ctx, assignments, true, is_scene_component, target)?;
            } else {
                self.push_enum_patch(ctx, variant, assignments, target)?;
            }
        } else {
            self.push_struct_patch(ctx, assignments, is_props, is_scene_component, target)?;
        }

        Ok(())
    }

    fn push_enum_patch(
        &self,
        ctx: &mut BsnCodegenCtx,
        variant: &Ident,
        assignments: &mut Vec<TokenStream>,
        target: PatchTarget,
    ) -> syn::Result<()> {
        let (bevy_scene, bevy_ecs, path) = (ctx.bevy_scene, ctx.bevy_ecs, &self.path);
        let variant_default = format_ident!("default_{}", variant.to_string().to_lowercase());
        let template_path = quote! { #bevy_scene::macro_utils::PathResolveHelper::<<#path as #bevy_ecs::template::FromTemplate>::Template> };

        let maybe_deref = target.is_ref.then(|| quote! {*});
        let maybe_borrow_mut = (!target.is_ref).then(|| quote! {&mut});
        let field_path = target.path;

        let (check_pattern, binding_pattern, field_updates) = match &self.fields {
            BsnFields::Named(fields) => {
                let mut seen = HashSet::with_capacity(fields.len());
                let mut names = Vec::new();
                let mut assigns = Vec::new();

                for field in fields {
                    let field_name = &field.name;
                    if !seen.insert(field_name.to_string()) {
                        ctx.errors.push(syn::Error::new_spanned(
                            field_name,
                            format!("Duplicate field `{}` found in BSN enum variant", field_name),
                        ));
                        continue;
                    }

                    names.push(field_name);

                    assigns.push(self.process_enum_field(ctx, field_name, field.value.as_ref())?);
                }

                (
                    quote! { #variant { .. } },
                    quote! { #variant { #(#names,)* .. } },
                    assigns,
                )
            }
            BsnFields::Tuple(fields) if fields.is_empty() => {
                (quote! { #variant }, quote! { #variant }, vec![])
            }
            BsnFields::Tuple(fields) => {
                let names: Vec<_> = (0..fields.len()).map(|i| format_ident!("t{}", i)).collect();
                let assigns = fields
                    .iter()
                    .enumerate()
                    .map(|(i, f)| self.process_enum_field(ctx, &names[i], Some(&f.value)))
                    .collect::<syn::Result<Vec<_>>>()?;

                (
                    quote! { #variant(..) },
                    quote! { #variant(#(#names,)* ..) },
                    assigns,
                )
            }
        };

        assignments.push(quote! {
            {
                let _node = #maybe_borrow_mut #(#field_path).*;
                if !::core::matches!(_node, #template_path::#check_pattern) {
                    #maybe_deref _node = #template_path::#variant_default();
                }
                if let #template_path::#binding_pattern = _node {
                    #(#field_updates)*
                }
            }
        });
        Ok(())
    }

    fn push_struct_patch(
        &self,
        ctx: &mut BsnCodegenCtx,
        assignments: &mut Vec<TokenStream>,
        is_props: bool,
        is_scene_component: bool,
        target: PatchTarget,
    ) -> syn::Result<()> {
        match &self.fields {
            BsnFields::Named(fields) => {
                let mut seen = HashSet::with_capacity(fields.len());

                for field in fields {
                    let field_name = &field.name;
                    if is_props != field.is_prop {
                        if !is_scene_component && field.is_prop {
                            let type_path = &self.path;
                            ctx.errors.push(syn::Error::new_spanned(
                                field_name,
                                format!(
                                    "Scene prop fields are not supported in normal component patches\
                                     . If you would like to set a component scene's prop field, it \
                                     should be set using \"scene component\" syntax: \
                                     bsn! {{ @{} {{ @{field_name}: VALUE }} }}",
                                     path_to_string(type_path)
                                ),
                            ));
                        }
                        continue;
                    }
                    if !seen.insert(field_name.to_string()) {
                        ctx.errors.push(syn::Error::new_spanned(
                            field_name,
                            format!("Duplicate field `{}` found in BSN struct", field_name),
                        ));
                        continue;
                    }

                    if field.value.is_none() && !field.is_name_shorthand {
                        ctx.errors.push(syn::Error::new_spanned(
                            field_name,
                            format!("Field `{}` is missing a value.", field_name),
                        ));
                    }

                    let path = if field.is_prop {
                        &[Member::Named(format_ident!("__props"))]
                    } else {
                        target.path
                    };

                    self.process_field(
                        ctx,
                        assignments,
                        path,
                        Member::Named(field_name.clone()),
                        field.value.as_ref(),
                        field.is_name_shorthand,
                    )?;
                }
            }
            BsnFields::Tuple(fields) => {
                // Tuple fields can't be props
                if is_props {
                    return Ok(());
                }
                for (i, field) in fields.iter().enumerate() {
                    if let Err(err) = self.process_field(
                        ctx,
                        assignments,
                        target.path,
                        Member::Unnamed(Index::from(i)),
                        Some(&field.value),
                        false,
                    ) {
                        ctx.errors.push(err);
                    }
                }
            }
        }
        Ok(())
    }

    fn process_field(
        &self,
        ctx: &mut BsnCodegenCtx,
        assignments: &mut Vec<TokenStream>,
        base_path: &[Member],
        member: Member,
        value: Option<&BsnValue>,
        is_name_shorthand: bool,
    ) -> syn::Result<()> {
        match value {
            // NOTE: It is very important to still produce outputs for None field values. This is what
            // enables field autocomplete in Rust Analyzer
            None => {
                if is_name_shorthand {
                    assignments.push(quote! {
                        #(#base_path.)*#member = #member.into();
                    });
                } else {
                    assignments.push(quote! {
                        #(#base_path.)*#member;
                    });
                }
            }
            // Enables field autocomplete in Rust Analyzer
            Some(
                value @ (BsnValue::Ident(_)
                | BsnValue::Expr(_)
                | BsnValue::Closure(_)
                | BsnValue::Tuple(_)),
            ) => {
                let ident = ctx.hoisted_expressions.hoist(value);
                assignments.push(quote! { #(#base_path.)*#member = #ident; });
            }
            Some(BsnValue::Lit(_)) => {
                // value is Some
                let value = value.unwrap();
                assignments.push(quote! { #(#base_path.)*#member = #value; });
            }
            Some(BsnValue::Name(ident)) => {
                let index = ctx.entity_refs.get(ident.to_string());
                let bevy_ecs = ctx.bevy_ecs;
                let invocation = ctx.invocation_index.clone();
                assignments.push(quote! {
                    #(#base_path.)*#member = #bevy_ecs::template::EntityTemplate::from_reference(#invocation, #index,  _call_id);
                });
            }
            Some(value @ BsnValue::Type(ty)) if ty.enum_variant.is_some() => {
                assignments.push(quote! {#(#base_path.)*#member = #value;});
            }
            Some(BsnValue::Type(ty)) => {
                let mut new_path = base_path.to_vec();
                new_path.push(member);
                ty.to_patch_tokens(
                    ctx,
                    assignments,
                    false,
                    false,
                    false,
                    PatchTarget {
                        path: &new_path,
                        is_ref: false,
                    },
                )?;
            }
        }
        Ok(())
    }

    fn process_enum_field(
        &self,
        ctx: &mut BsnCodegenCtx,
        bind_name: &Ident,
        value: Option<&BsnValue>,
    ) -> syn::Result<TokenStream> {
        if value.is_none() {
            ctx.errors.push(syn::Error::new_spanned(
                bind_name,
                format!("Enum field `{}` is missing a value", bind_name),
            ));
        }

        if let Some(BsnValue::Type(ty)) = value
            && ty.enum_variant.is_none()
        {
            let mut type_assigns = Vec::new();
            ty.to_patch_tokens(
                ctx,
                &mut type_assigns,
                false,
                false,
                false,
                PatchTarget {
                    path: &[Member::Named(bind_name.clone())],
                    is_ref: true,
                },
            )?;
            return Ok(quote! {#(#type_assigns)*});
        }

        // NOTE: It is very important to still produce outputs for None field values. This is what
        // enables field autocomplete in Rust Analyzer
        value
            .map(|v| Ok(quote! { *#bind_name = #v; }))
            .unwrap_or(Ok(quote! { #bind_name; }))
    }
}

impl BsnTokenStream for BsnSceneListItems {
    fn to_tokens(&self, ctx: &mut BsnCodegenCtx) -> TokenStream {
        let bevy_scene = ctx.bevy_scene;
        let scenes = self.0.iter().map(|s| match s {
            BsnSceneListItem::Scene(bsn) => {
                let tokens = bsn.to_tokens(ctx);
                quote! {#bevy_scene::EntityScene(#tokens)}
            }
            BsnSceneListItem::Expression(stmts) => quote! {#(#stmts)*},
        });

        quote! { #bevy_scene::auto_nest_tuple!(#(#scenes),*) }
    }
}

impl BsnSceneFn {
    fn to_tokens(&self, ctx: &mut BsnCodegenCtx) -> TokenStream {
        let bevy_scene = ctx.bevy_scene;
        let args = self.args.to_tokens(ctx);
        let path = &self.path;
        quote! {#bevy_scene::SceneScope(#path #args)}
    }
}

impl ToTokens for BsnType {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let (path, variant) = (
            &self.path,
            self.enum_variant.as_ref().map(|v| quote! {::#v}),
        );
        match &self.fields {
            BsnFields::Named(fields) => {
                let assigns = fields.iter().map(|f| {
                    let (name, value) = (&f.name, &f.value);
                    quote! {#name: #value}
                });
                quote! { #path #variant { #(#assigns,)* } }
            }
            BsnFields::Tuple(fields) => {
                let assigns = fields.iter().map(|f| &f.value);
                quote! { #path #variant ( #(#assigns,)* ) }
            }
        }
        .to_tokens(tokens);
    }
}

impl BsnTokenStream for BsnFnArgs {
    fn to_tokens(&self, ctx: &mut BsnCodegenCtx) -> TokenStream {
        let args = self.0.iter().map(|a| a.to_tokens(ctx));
        quote! { (#(#args),*) }
    }
}

impl BsnTokenStream for BsnFnArg {
    fn to_tokens(&self, ctx: &mut BsnCodegenCtx) -> TokenStream {
        let bevy_ecs = ctx.bevy_ecs;
        match self {
            BsnFnArg::EntityName(ident) => {
                let index = ctx.entity_refs.get(ident.to_string());
                let invocation = ctx.invocation_index.clone();
                quote! {
                    #bevy_ecs::template::EntityTemplate::SceneEntityReference(
                        #bevy_ecs::template::SceneEntityReference::new(#invocation, #index, _call_id)
                    )
                }
            }
            BsnFnArg::Tokens(token_stream) => token_stream.clone(),
        }
    }
}
impl ToTokens for BsnValue {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        match self {
            BsnValue::Expr(e) => quote! {{#e}.into()}.to_tokens(tokens),
            BsnValue::Closure(c) => quote! {(#c).into()}.to_tokens(tokens),
            BsnValue::Ident(i) => quote! {(#i).into()}.to_tokens(tokens),
            BsnValue::Lit(Lit::Str(s)) => quote! {#s.into()}.to_tokens(tokens),
            BsnValue::Lit(l) => {
                if l.suffix().is_empty() {
                    l.to_tokens(tokens)
                } else {
                    quote! {(#l).into()}.to_tokens(tokens)
                }
            }
            BsnValue::Tuple(t) => {
                let inner = t.0.iter();
                quote! {(#(#inner),*)}.to_tokens(tokens);
            }
            BsnValue::Type(ty) => quote! {(#ty).into()}.to_tokens(tokens),
            BsnValue::Name(_) => {
                // Name requires additional context to convert to tokens
                unreachable!()
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::bsn::types::*;
    use syn::parse_quote;

    struct TestPaths {
        bevy_scene: Path,
        bevy_ecs: Path,
    }

    impl TestPaths {
        fn new() -> Self {
            Self {
                bevy_scene: parse_quote!(bevy_scene),
                bevy_ecs: parse_quote!(bevy_ecs),
            }
        }

        fn ctx<'a>(
            &'a self,
            refs: &'a mut EntityRefs,
            hoisted_expressions: &'a mut HoistedExpressions,
        ) -> BsnCodegenCtx<'a> {
            BsnCodegenCtx {
                bevy_scene: &self.bevy_scene,
                bevy_ecs: &self.bevy_ecs,
                entity_refs: refs,
                invocation_index: parse_quote!(("", 0, 0)),
                hoisted_expressions,
                errors: Vec::new(),
            }
        }
    }

    #[test]
    fn duplicate_field() {
        let mut refs = EntityRefs::default();
        let paths = TestPaths::new();
        let mut exprs = HoistedExpressions::default();
        let mut ctx = paths.ctx(&mut refs, &mut exprs);
        let mut assignments = vec![];
        let duplicate = BsnType {
            path: parse_quote!(Transform),
            enum_variant: None,
            fields: BsnFields::Named(vec![
                BsnNamedField {
                    name: parse_quote!(x),
                    value: Some(BsnValue::Expr(quote!({}))),
                    is_prop: false,
                    is_name_shorthand: false,
                },
                BsnNamedField {
                    name: parse_quote!(x),
                    value: Some(BsnValue::Expr(quote!({}))),
                    is_prop: false,
                    is_name_shorthand: false,
                },
            ]),
        };

        let res = duplicate.push_struct_patch(
            &mut ctx,
            &mut assignments,
            false,
            false,
            PatchTarget {
                path: &[],
                is_ref: false,
            },
        );

        assert!(res.is_ok());
        assert_eq!(ctx.errors.len(), 1);
        assert!(ctx.errors[0]
            .to_string()
            .contains("Duplicate field `x` found in BSN struct"));
    }

    #[test]
    fn recursive_duplicate_field() {
        let mut refs = EntityRefs::default();
        let paths = TestPaths::new();
        let mut exprs = HoistedExpressions::default();
        let mut ctx = paths.ctx(&mut refs, &mut exprs);
        let mut assignments = vec![];
        let nested_duplicate = BsnType {
            path: parse_quote!(Parent),
            enum_variant: None,
            fields: BsnFields::Named(vec![BsnNamedField {
                is_prop: false,
                is_name_shorthand: false,
                name: parse_quote!(child_field),
                value: Some(BsnValue::Type(BsnType {
                    path: parse_quote!(Child),
                    enum_variant: None,
                    fields: BsnFields::Named(vec![
                        BsnNamedField {
                            name: parse_quote!(x),
                            value: Some(BsnValue::Expr(quote!({}))),
                            is_prop: false,
                            is_name_shorthand: false,
                        },
                        BsnNamedField {
                            name: parse_quote!(x),
                            value: Some(BsnValue::Expr(quote!({}))),
                            is_prop: false,
                            is_name_shorthand: false,
                        },
                    ]),
                })),
            }]),
        };

        let res = nested_duplicate.to_patch_tokens(
            &mut ctx,
            &mut assignments,
            true,
            false,
            false,
            PatchTarget {
                path: &[],
                is_ref: false,
            },
        );

        assert!(res.is_ok());
        assert_eq!(ctx.errors.len(), 1);
        assert!(ctx.errors[0]
            .to_string()
            .contains("Duplicate field `x` found in BSN struct"));
    }

    #[test]
    fn missing_struct_field() {
        let mut refs = EntityRefs::default();
        let paths = TestPaths::new();
        let mut exprs = HoistedExpressions::default();
        let mut ctx = paths.ctx(&mut refs, &mut exprs);
        let mut assignments = Vec::new();
        let missing = BsnType {
            path: parse_quote!(Transform),
            enum_variant: None,
            fields: BsnFields::Named(vec![BsnNamedField {
                is_prop: false,
                is_name_shorthand: false,
                name: parse_quote!(x),
                value: None,
            }]),
        };

        let res = missing.push_struct_patch(
            &mut ctx,
            &mut assignments,
            false,
            false,
            PatchTarget {
                path: &[Member::Named(parse_quote!(value))],
                is_ref: false,
            },
        );

        assert!(res.is_ok());
        assert_eq!(ctx.errors.len(), 1);
        assert!(ctx.errors[0]
            .to_string()
            .contains("Field `x` is missing a value"));
    }

    #[test]
    fn enum_variant_field_values_use_implicit_into() {
        let mut refs = EntityRefs::default();
        let paths = TestPaths::new();
        let mut exprs = HoistedExpressions::default();
        let mut ctx = paths.ctx(&mut refs, &mut exprs);
        let mut assignments = Vec::new();
        let font = BsnType {
            path: parse_quote!(TextFont),
            enum_variant: None,
            fields: BsnFields::Named(vec![BsnNamedField {
                is_prop: false,
                is_name_shorthand: false,
                name: parse_quote!(font_size),
                value: Some(BsnValue::Type(BsnType {
                    path: parse_quote!(TextSize),
                    enum_variant: Some(parse_quote!(Large)),
                    fields: BsnFields::Named(Vec::new()),
                })),
            }]),
        };

        let res = font.push_struct_patch(
            &mut ctx,
            &mut assignments,
            false,
            false,
            PatchTarget {
                path: &[Member::Named(parse_quote!(value))],
                is_ref: false,
            },
        );

        assert!(res.is_ok());
        assert!(ctx.errors.is_empty());
        assert_eq!(
            assignments[0].to_string(),
            "value . font_size = (TextSize :: Large { }) . into () ;"
        );
    }

    #[test]
    fn enum_duplicate_field() {
        // Arrange
        let mut refs = EntityRefs::default();
        let paths = TestPaths::new();
        let mut exprs = HoistedExpressions::default();
        let mut ctx = paths.ctx(&mut refs, &mut exprs);
        let mut assignments = vec![];
        let duplicate = BsnType {
            path: parse_quote!(MyEnum),
            enum_variant: Some(parse_quote!(Variant)),
            fields: BsnFields::Named(vec![
                BsnNamedField {
                    is_prop: false,
                    is_name_shorthand: false,
                    name: parse_quote!(x),
                    value: Some(BsnValue::Expr(quote!(1))),
                },
                BsnNamedField {
                    is_prop: false,
                    is_name_shorthand: false,
                    name: parse_quote!(x),
                    value: Some(BsnValue::Expr(quote!(2))),
                },
            ]),
        };

        // Act
        let res = duplicate.push_enum_patch(
            &mut ctx,
            &parse_quote!(Variant),
            &mut assignments,
            PatchTarget {
                path: &[],
                is_ref: false,
            },
        );

        // Assert
        assert!(res.is_ok());
        assert_eq!(ctx.errors.len(), 1);
        assert!(ctx.errors[0]
            .to_string()
            .contains("Duplicate field `x` found in BSN enum variant"));
    }

    #[test]
    fn bsn_root_preserves_inference_on_error() {
        // Arrange
        let expected = "bevy_scene :: SceneScope ({ let _res = bevy_scene :: auto_nest_tuple \
            ! () ; :: core :: compile_error ! { \"Test Error\" } _res })";

        let mut refs = EntityRefs::default();
        let paths = TestPaths::new();
        let mut exprs = HoistedExpressions::default();
        let mut ctx = paths.ctx(&mut refs, &mut exprs);
        ctx.errors.push(syn::Error::new(
            proc_macro2::Span::call_site(),
            "Test Error",
        ));
        let root = BsnRoot(Bsn::<true> { entries: vec![] });

        // Act
        let res = root.to_tokens(&mut ctx).to_string();

        // Assert
        assert_eq!(res, expected,);
    }

    #[test]
    fn bsn_list_root_preserves_inference_on_error() {
        // Arrange
        let expected =
            "{ let _res = bevy_scene :: SceneListScope (bevy_scene :: auto_nest_tuple ! ()) ;"
                .to_string()
                + " :: core :: compile_error ! { \"Test Error\" }"
                + " _res }";

        let mut refs = EntityRefs::default();
        let paths = TestPaths::new();
        let mut exprs = HoistedExpressions::default();
        let mut ctx = paths.ctx(&mut refs, &mut exprs);
        ctx.errors.push(syn::Error::new(
            proc_macro2::Span::call_site(),
            "Test Error",
        ));
        let root = BsnListRoot(BsnSceneListItems(vec![]));

        // Act
        let res = root.to_tokens(&mut ctx).to_string();

        // Assert
        assert_eq!(res, expected,);
    }
}