tree-type-proc-macro 0.1.0

Procedural macros for tree-type crate
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
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
//! Code generation for `::tree_type` structures

use crate::core::{Attribute, Child, DefaultValue, TreeDef};
use quote::quote;
use syn::Ident;

/// Get parameter type and conversion for dynamic ID methods
fn get_param_type_and_conversion(
    _id_type: &syn::Type,
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    // Use Display since it works for all types (strings, numbers, custom types)
    (quote! { impl std::fmt::Display }, quote! { id })
}

/// Resolve a symlink target path by looking up identities in the tree structure
fn resolve_symlink_target_path(
    target_path: &str,
    root_children: &[Child],
    up_dirs: &str,
    _current_depth: usize,
) -> Option<proc_macro2::TokenStream> {
    // Handle absolute paths by stripping leading slash
    let path_to_resolve = target_path.strip_prefix('/').unwrap_or(target_path);

    // Split path into components
    let path_parts: Vec<&str> = path_to_resolve
        .split('/')
        .filter(|s| !s.is_empty())
        .collect();

    if path_parts.is_empty() {
        return None;
    }

    // Try to find the target identity in the root children
    if let Some(target_child) = find_child_by_identity(&path_parts, root_children) {
        // Check if the target has a custom filename
        let target_filename = match target_child {
            Child::File {
                custom_filename: Some(filename_lit),
                ..
            } => filename_lit.value(),
            Child::File {
                name,
                custom_filename: None,
                ..
            }
            | Child::Directory { name, .. } => {
                name.to_string() // Use identity name directly
            }
            Child::DynamicId { .. } => {
                // Dynamic IDs can't be resolved at compile time
                return None;
            }
        };

        // Build the relative path with the correct filename
        let path_prefix = if path_parts.len() > 1 {
            path_parts[..path_parts.len() - 1].join("/")
        } else {
            String::new()
        };

        let full_path = if path_prefix.is_empty() {
            format!("{up_dirs}{target_filename}")
        } else {
            format!("{up_dirs}{path_prefix}/{target_filename}")
        };

        return Some(quote! { #full_path });
    }

    None
}

/// Find a child by following the identity path
fn find_child_by_identity<'a>(path_parts: &[&str], children: &'a [Child]) -> Option<&'a Child> {
    if path_parts.is_empty() {
        return None;
    }

    let first_part = path_parts[0];
    let remaining_parts = &path_parts[1..];

    // Find the child with matching identity name
    for child in children {
        let child_name = match child {
            Child::File { name, .. } | Child::Directory { name, .. } => name.to_string(),
            Child::DynamicId { id_name, .. } => id_name.to_string(),
        };

        if child_name == first_part {
            if remaining_parts.is_empty() {
                // Found the target
                return Some(child);
            }
            // Continue searching in child's children
            if let Child::Directory {
                children: dir_children,
                ..
            } = child
            {
                return find_child_by_identity(remaining_parts, dir_children);
            }
        }
    }

    None
}

pub fn generate_code(tree: &TreeDef) -> proc_macro2::TokenStream {
    let root_name = &tree.name;
    let mut structs = Vec::new();

    // Generate root struct with full method set
    structs.push(generate_root_struct(root_name, &tree.children));

    // Generate child structs recursively
    generate_child_structs(root_name, &tree.children, &mut structs, 0, &tree.children);

    quote! {
        #(#structs)*
    }
}

fn generate_root_struct(name: &Ident, children: &[Child]) -> proc_macro2::TokenStream {
    let nav_methods = children
        .iter()
        .map(|child| generate_nav_method(name, child));

    let children_method = generate_children_method(children);
    let parent_method = generate_parent_method(None);

    let validate_impl = generate_validate_method(children);
    let setup_impl = generate_setup_method(children, 0, children); // Pass root children
    let ensure_impl = generate_ensure_method(children);

    // Skip From impl for GenericDir to avoid conflict with reflexive impl
    let from_impl = if name == "GenericDir" {
        quote! {}
    } else {
        quote! {
            pub fn from_generic(dir: ::tree_type::GenericDir) -> Self {
                Self(dir.as_path().to_path_buf())
            }
        }
    };

    let from_trait = if name == "GenericDir" {
        quote! {}
    } else {
        quote! {
            impl From<#name> for ::tree_type::GenericDir {
                fn from(dir: #name) -> Self {
                    Self::new(dir.0).expect("Path validation already performed")
                }
            }
        }
    };

    let serde_derives = if cfg!(feature = "serde") {
        quote! { #[derive(tree_type::deps::serde::Serialize, tree_type::deps::serde::Deserialize)] }
    } else {
        quote! {}
    };
    let walk_fns = build_walk_fns();

    let display_impl = generate_display_impl(name);
    let debug_impl = generate_debug_impl(name);

    quote! {
        #serde_derives
        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct #name(std::path::PathBuf);

        impl #name {
            pub fn new(path: impl Into<std::path::PathBuf>) -> std::io::Result<Self> {
                let path_buf = path.into();
                // For directories, allow root paths and paths with filename components
                // Only reject empty paths or invalid paths like ".."
                if path_buf.as_os_str().is_empty() {
                    return Err(std::io::Error::from(std::io::ErrorKind::InvalidFilename));
                }
                Ok(Self(path_buf))
            }

            pub fn as_path(&self) -> &std::path::Path {
                &self.0
            }

            pub fn exists(&self) -> bool {
                self.0.exists()
            }

            pub fn as_generic(&self) -> ::tree_type::GenericDir {
                ::tree_type::GenericDir::new(self.0.clone()).expect("Path validation already performed")
            }

            pub fn create(&self) -> std::io::Result<()> {
                ::tree_type::fs::create_dir(&self.0)
            }

            pub fn create_all(&self) -> std::io::Result<()> {
                ::tree_type::fs::create_dir_all(&self.0)
            }

            pub fn remove(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_dir(&self.0)
            }

            pub fn remove_all(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_dir_all(&self.0)
            }

            pub fn read_dir(&self) -> std::io::Result<impl Iterator<Item = std::io::Result<::tree_type::GenericPath>>> {
                ::tree_type::fs::read_dir(&self.0)
                    .map(|read_dir| read_dir.map(|result| result.and_then(::tree_type::GenericPath::try_from)))
            }

            pub fn fs_metadata(&self) -> std::io::Result<::tree_type::fs::Metadata> {
                ::tree_type::fs::metadata(&self.0)
            }

            /// Returns the final component of the path as a String.
            /// For root paths like "/", returns an empty string.
            /// See [`std::path::Path::file_name`] for more details.
            pub fn file_name(&self) -> String {
                self.0.file_name()
                    .map(|name| name.to_string_lossy().to_string())
                    .unwrap_or_default()
            }

            #walk_fns

            #validate_impl
            #setup_impl
            #ensure_impl

            #from_impl

            #(#nav_methods)*

            #children_method

            #parent_method
        }

        impl AsRef<std::path::Path> for #name {
            fn as_ref(&self) -> &std::path::Path {
                &self.0
            }
        }

        #display_impl

        #debug_impl

        #from_trait
    }
}

pub fn build_walk_fns() -> proc_macro2::TokenStream {
    if cfg!(feature = "walk") {
        quote! {
            /// Create a WalkDir iterator for the given path
            pub fn walk_dir(&self) -> ::tree_type::deps::walk::WalkDir {
                self.as_generic().walk_dir()
            }

            /// Walk directory and return iterator of paths
            pub fn walk(&self) -> impl Iterator<Item = std::io::Result<::tree_type::GenericPath>> {
                // can't use `as_generic` because the GenericDir would go out-of-scope when we
                // return the iterator it returned
                ::tree_type::deps::walk::WalkDir::new(&self.0)
                    .into_iter()
                    .map(|r| r.map_err(|e| e.into()).and_then(::tree_type::GenericPath::try_from))
            }

            /// Calculate total size in bytes of directory contents
            pub fn size_in_bytes(&self) -> std::io::Result<u64> {
                self.as_generic().size_in_bytes()
            }

            /// List directory contents with metadata
            pub fn lsl(
                &self
            ) -> std::io::Result<Vec<(std::path::PathBuf, std::fs::Metadata)>> {
                self.as_generic().lsl()
            }
        }
    } else {
        quote! {}
    }
}

fn generate_child_structs(
    parent_name: &Ident,
    children: &[Child],
    structs: &mut Vec<proc_macro2::TokenStream>,
    depth: usize,
    root_children: &[Child],
) {
    for child in children {
        match child {
            Child::File {
                name,
                custom_type,
                attributes,
                ..
            } => {
                let struct_name = get_child_type_name(parent_name, name, custom_type.as_ref());
                structs.push(generate_file_struct(
                    &struct_name,
                    attributes,
                    Some(parent_name),
                ));
            }
            Child::Directory {
                name,
                custom_type,
                children,
                ..
            } => {
                let struct_name = get_child_type_name(parent_name, name, custom_type.as_ref());
                structs.push(generate_dir_struct(
                    &struct_name,
                    children,
                    depth + 1,
                    root_children,
                    Some(parent_name),
                ));
                generate_child_structs(&struct_name, children, structs, depth + 1, root_children);
            }
            Child::DynamicId {
                child_type,
                children,
                attributes,
                is_directory,
                ..
            } => {
                if *is_directory {
                    structs.push(generate_dir_struct(
                        child_type,
                        children,
                        depth + 1,
                        root_children,
                        Some(parent_name),
                    ));
                    generate_child_structs(child_type, children, structs, depth + 1, root_children);
                } else {
                    structs.push(generate_file_struct(
                        child_type,
                        attributes,
                        Some(parent_name),
                    ));
                }
            }
        }
    }
}

fn generate_nav_method(parent_name: &Ident, child: &Child) -> proc_macro2::TokenStream {
    match child {
        Child::File {
            name,
            custom_filename,
            custom_type,
            ..
        } => {
            let method_name = name;
            let filename = custom_filename
                .as_ref()
                .map_or_else(|| name.to_string(), syn::LitStr::value);
            let return_type = get_child_type_name(parent_name, name, custom_type.as_ref());

            quote! {
                pub fn #method_name(&self) -> #return_type {
                    #return_type(self.0.join(#filename))
                }
            }
        }
        Child::Directory {
            name,
            custom_filename,
            custom_type,
            ..
        } => {
            let method_name = name;
            let dirname = custom_filename
                .as_ref()
                .map_or_else(|| name.to_string(), syn::LitStr::value);
            let return_type = get_child_type_name(parent_name, name, custom_type.as_ref());

            quote! {
                pub fn #method_name(&self) -> #return_type {
                    #return_type(self.0.join(#dirname))
                }
            }
        }
        Child::DynamicId {
            id_name,
            id_type,
            child_type,
            ..
        } => {
            // Generate parameterized method for type-safe access
            let method_name = id_name;

            // Generate type-specific reference signature based on ID type
            let (param_type, conversion) = get_param_type_and_conversion(id_type);

            quote! {
                /// Access a dynamic ID instance by reference.
                ///
                /// This method takes a reference to avoid consuming the parameter,
                /// allowing for better ergonomics and parameter reuse.
                pub fn #method_name(&self, id: #param_type) -> #child_type {
                    #child_type(self.0.join(#conversion.to_string()))
                }
            }
        }
    }
}

fn generate_children_method(children: &[Child]) -> Option<proc_macro2::TokenStream> {
    // Find all dynamic ID children to determine the return type and validate consistency
    let dynamic_children: Vec<_> = children
        .iter()
        .filter_map(|child| {
            if let Child::DynamicId {
                child_type,
                is_directory,
                ..
            } = child
            {
                Some((child_type, *is_directory))
            } else {
                None
            }
        })
        .collect();

    if dynamic_children.is_empty() {
        return None;
    }

    // Use the first dynamic ID child for the return type
    let (dynamic_child, is_directory) = dynamic_children[0];

    // Validate that all dynamic ID children have the same is_directory value
    // This ensures consistent behavior when multiple dynamic ID types exist
    if dynamic_children.len() > 1 {
        let all_same_type = dynamic_children.iter().all(|(_, dir)| *dir == is_directory);
        // This is a compile-time validation - if mixed file/directory dynamic IDs exist,
        // the children() method behavior would be ambiguous
        assert!(
            all_same_type,
            "Mixed file and directory dynamic ID types in the same parent are not supported"
        );
    }

    // Generate the appropriate file type check based on whether it's a directory or file
    let file_type_check = if is_directory {
        quote! { entry_path.is_dir() }
    } else {
        quote! { entry_path.is_file() }
    };

    Some(quote! {
        /// Iterate over dynamic ID children in this directory.
        ///
        /// Performs `read_dir()` on the filesystem and converts directory entries
        /// into correctly typed dynamic ID instances, returning them via an Iterator.
        pub fn children(&self) -> std::io::Result<impl Iterator<Item = std::io::Result<#dynamic_child>>> {
            let path = self.0.clone();
            let read_dir = ::tree_type::fs::read_dir(&path)?;
            Ok(read_dir.filter_map(move |entry| {
                match entry {
                    Ok(entry) => {
                        let entry_path = entry.path();
                        if #file_type_check {
                            Some(#dynamic_child::new(entry_path).map_err(std::io::Error::from))
                        } else {
                            None
                        }
                    }
                    Err(e) => Some(Err(e))
                }
            }))
        }
    })
}

fn generate_parent_method(parent_type: Option<&Ident>) -> proc_macro2::TokenStream {
    match parent_type {
        Some(parent_type) => {
            // Type-safe parent method for non-root types
            quote! {
                /// Get the parent directory with type-safe return type.
                pub fn parent(&self) -> #parent_type {
                    let parent_path = self.0.parent().expect("Non-root type must have parent");
                    #parent_type::new(parent_path).expect("Parent path should be valid")
                }
            }
        }
        None => {
            // Root type returns Option<GenericDir>
            quote! {
                /// Get the parent directory as GenericDir.
                /// Returns None for root directories or if parent cannot be determined.
                pub fn parent(&self) -> Option<::tree_type::GenericDir> {
                    self.0.parent().and_then(|parent_path| {
                        ::tree_type::GenericDir::new(parent_path).ok()
                    })
                }
            }
        }
    }
}

fn get_child_type_name(
    parent_name: &Ident,
    child_name: &Ident,
    custom_type: Option<&Ident>,
) -> Ident {
    custom_type.cloned().unwrap_or_else(|| {
        Ident::new(
            &format!("{}{}", parent_name, capitalize(&child_name.to_string())),
            child_name.span(),
        )
    })
}

fn generate_create_default_method(default_val: &DefaultValue) -> proc_macro2::TokenStream {
    match default_val {
        DefaultValue::DefaultTrait => {
            quote! {
                pub fn create_default<E>(&self) -> std::result::Result<::tree_type::CreateDefaultOutcome, E>
                where
                    E: From<std::io::Error>,
                {
                    if self.exists() {
                        return Ok(tree_type::CreateDefaultOutcome::AlreadyExists);
                    }
                    self.write(&String::default())?;
                    Ok(tree_type::CreateDefaultOutcome::Created)
                }
            }
        }
        DefaultValue::Literal(lit) => {
            quote! {
                pub fn create_default<E>(&self) -> std::result::Result<::tree_type::CreateDefaultOutcome, E>
                where
                    E: From<std::io::Error>,
                {
                    if self.exists() {
                        return Ok(tree_type::CreateDefaultOutcome::AlreadyExists);
                    }
                    self.write(&#lit.to_string())?;
                    Ok(tree_type::CreateDefaultOutcome::Created)
                }
            }
        }
        DefaultValue::Function(expr) => {
            quote! {
                pub fn create_default<E>(&self) -> std::result::Result<::tree_type::CreateDefaultOutcome, E>
                where
                    E: From<std::io::Error>,
                {
                    if self.exists() {
                        return Ok(tree_type::CreateDefaultOutcome::AlreadyExists);
                    }
                    let content = (#expr)(self)?;
                    self.write(&content)?;
                    Ok(tree_type::CreateDefaultOutcome::Created)
                }
            }
        }
    }
}

fn generate_file_struct(
    name: &Ident,
    attributes: &[Attribute],
    parent_type: Option<&Ident>,
) -> proc_macro2::TokenStream {
    // Find default attribute if present
    let default_method = attributes.iter().find_map(|attr| {
        if let Attribute::Default(val) = attr {
            Some(generate_create_default_method(val))
        } else {
            None
        }
    });

    let parent_method = generate_parent_method(parent_type);

    let serde_derives = if cfg!(feature = "serde") {
        quote! { #[derive(tree_type::deps::serde::Serialize, tree_type::deps::serde::Deserialize)] }
    } else {
        quote! {}
    };

    let display_impl = generate_display_impl(name);
    let debug_impl = generate_debug_impl(name);

    quote! {
        #serde_derives
        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct #name(std::path::PathBuf);

        impl #name {
            pub fn new(path: impl Into<std::path::PathBuf>) -> std::io::Result<Self> {
                let path_buf = path.into();
                // For directories, allow root paths and paths with filename components
                // Only reject empty paths or invalid paths like ".."
                if path_buf.as_os_str().is_empty() {
                    return Err(std::io::Error::from(std::io::ErrorKind::InvalidFilename));
                }
                Ok(Self(path_buf))
            }

            pub fn as_path(&self) -> &std::path::Path {
                &self.0
            }

            pub fn exists(&self) -> bool {
                self.0.exists()
            }

            pub fn as_generic(&self) -> ::tree_type::GenericFile {
                ::tree_type::GenericFile::new(self.0.clone()).expect("Path validation already performed")
            }

            pub fn read(&self) -> std::io::Result<Vec<u8>> {
                ::tree_type::fs::read(&self.0)
            }

            pub fn read_to_string(&self) -> std::io::Result<String> {
                ::tree_type::fs::read_to_string(&self.0)
            }

            pub fn write<C: AsRef<[u8]>>(&self, contents: C) -> std::io::Result<()> {
                if let Some(parent) = self.0.parent() {
                    if !parent.exists() {
                        ::tree_type::fs::create_dir_all(parent)?;
                    }
                }
                ::tree_type::fs::write(&self.0, contents)
            }

            pub fn remove(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_file(&self.0)
            }

            pub fn fs_metadata(&self) -> std::io::Result<::tree_type::fs::Metadata> {
                ::tree_type::fs::metadata(&self.0)
            }

            /// Returns the final component of the path as a String.
            /// See [`std::path::Path::file_name`] for more details.
            pub fn file_name(&self) -> String {
                self.0.file_name()
                    .expect("validated in new")
                    .to_string_lossy()
                    .to_string()
            }

            /// Set file permissions to 0o600 (read/write for owner only).
            ///
            /// This method is only available on Unix systems.
            #[cfg(unix)]
            pub fn secure(&self) -> std::io::Result<()> {
                self.as_generic().secure()
            }

            pub fn from_generic(file: ::tree_type::GenericFile) -> Self {
                Self(file.as_path().to_path_buf())
            }

            #default_method

            #parent_method
        }

        impl AsRef<std::path::Path> for #name {
            fn as_ref(&self) -> &std::path::Path {
                &self.0
            }
        }

        #display_impl

        #debug_impl

        impl From<#name> for ::tree_type::GenericFile {
            fn from(file: #name) -> Self {
                Self::new(file.0).expect("Path validation already performed")
            }
        }
    }
}

fn generate_dir_struct(
    name: &Ident,
    children: &[Child],
    depth: usize,
    root_children: &[Child],
    parent_type: Option<&Ident>,
) -> proc_macro2::TokenStream {
    let nav_methods = children
        .iter()
        .map(|child| generate_nav_method(name, child));

    let children_method = generate_children_method(children);
    let parent_method = generate_parent_method(parent_type);

    let validate_impl = generate_validate_method(children);
    let setup_impl = generate_setup_method(children, depth, root_children);
    let ensure_impl = generate_ensure_method(children);

    let serde_derives = if cfg!(feature = "serde") {
        quote! { #[derive(tree_type::deps::serde::Serialize, tree_type::deps::serde::Deserialize)] }
    } else {
        quote! {}
    };
    let walk_fns = build_walk_fns();

    let display_impl = generate_display_impl(name);
    let debug_impl = generate_debug_impl(name);

    quote! {
        #serde_derives
        #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
        pub struct #name(std::path::PathBuf);

        impl #name {
            pub fn new(path: impl Into<std::path::PathBuf>) -> std::io::Result<Self> {
                let path_buf = path.into();
                // For directories, allow root paths and paths with filename components
                // Only reject empty paths or invalid paths like ".."
                if path_buf.as_os_str().is_empty() {
                    return Err(std::io::Error::from(std::io::ErrorKind::InvalidFilename));
                }
                Ok(Self(path_buf))
            }

            pub fn as_path(&self) -> &std::path::Path {
                &self.0
            }

            pub fn exists(&self) -> bool {
                self.0.exists()
            }

            pub fn as_generic(&self) -> ::tree_type::GenericDir {
                ::tree_type::GenericDir::new(self.0.clone()).expect("Path validation already performed")
            }

            pub fn create(&self) -> std::io::Result<()> {
                ::tree_type::fs::create_dir(&self.0)
            }

            pub fn create_all(&self) -> std::io::Result<()> {
                ::tree_type::fs::create_dir_all(&self.0)
            }

            pub fn remove(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_dir(&self.0)
            }

            pub fn remove_all(&self) -> std::io::Result<()> {
                ::tree_type::fs::remove_dir_all(&self.0)
            }

            pub fn read_dir(&self) -> std::io::Result<impl Iterator<Item = std::io::Result<::tree_type::GenericPath>>> {
                ::tree_type::fs::read_dir(&self.0)
                    .map(|read_dir| read_dir.map(|result| result.and_then(::tree_type::GenericPath::try_from)))
            }

            pub fn fs_metadata(&self) -> std::io::Result<::tree_type::fs::Metadata> {
                ::tree_type::fs::metadata(&self.0)
            }

            /// Set directory permissions to 0o700 (read/write/execute for owner only).
            ///
            /// This method is only available on Unix systems.
            #[cfg(unix)]
            pub fn secure(&self) -> std::io::Result<()> {
                self.as_generic().secure()
            }

            #walk_fns

            #validate_impl
            #setup_impl
            #ensure_impl

            /// Returns the final component of the path as a String.
            /// For root paths like "/", returns an empty string.
            /// See [`std::path::Path::file_name`] for more details.
            pub fn file_name(&self) -> String {
                self.0.file_name()
                    .map(|name| name.to_string_lossy().to_string())
                    .unwrap_or_default()
            }

            pub fn from_generic(dir: ::tree_type::GenericDir) -> Self {
                Self(dir.as_path().to_path_buf())
            }

            #(#nav_methods)*

            #children_method

            #parent_method
        }

        impl AsRef<std::path::Path> for #name {
            fn as_ref(&self) -> &std::path::Path {
                &self.0
            }
        }

        #display_impl

        #debug_impl

        impl From<#name> for ::tree_type::GenericDir {
            fn from(dir: #name) -> Self {
                Self::new(dir.0).expect("Path validation already performed")
            }
        }
    }
}

fn capitalize(s: &str) -> String {
    // Convert snake_case to PascalCase
    s.split('_')
        .filter(|part| !part.is_empty())
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
            }
        })
        .collect()
}

#[expect(clippy::too_many_lines)]
fn generate_validate_method(children: &[Child]) -> proc_macro2::TokenStream {
    let validations = children.iter().map(|child| {
        if let Child::DynamicId { child_type, attributes, is_directory, .. } = child {
            // Check for pattern validation
            let pattern = attributes.iter().find_map(|attr| {
                if let Attribute::Pattern(lit) = attr {
                    Some(lit)
                } else {
                    None
                }
            });

            // Check for custom validator
            let custom_validator = attributes.iter().find_map(|attr| {
                if let Attribute::Validate(expr) = attr {
                    Some(expr)
                } else {
                    None
                }
            });

            // Generate validation for dynamic IDs - always recurse into instances
            let pattern_validation = pattern.map(|pattern_lit| {
                quote! {
                    {
                        let dir_name = entry.file_name();
                        let name_str = dir_name.to_string_lossy();
                        match ::tree_type::deps::pattern_validation::Regex::new(#pattern_lit) {
                            Ok(re) => {
                                if !re.is_match(&name_str) {
                                    report.errors.push(tree_type::ValidationError {
                                        path: entry_path.clone(),
                                        message: format!("Directory name '{}' does not match pattern: {}", name_str, #pattern_lit),
                                    });
                                    continue;
                                }
                            }
                            Err(e) => {
                                report.errors.push(tree_type::ValidationError {
                                    path: entry_path.clone(),
                                    message: format!("Invalid regex pattern: {}", e),
                                });
                                continue;
                            }
                        }
                    }
                }
            });

            let validator_call = custom_validator.map(|_validator| {
                quote! {
                    let result = (#_validator)(&child_instance);
                    for error in result.errors {
                        report.errors.push(tree_type::ValidationError {
                            path: entry_path.clone(),
                            message: error,
                        });
                    }
                    for warning in result.warnings {
                        report.warnings.push(tree_type::ValidationWarning {
                            path: entry_path.clone(),
                            message: warning,
                        });
                    }
                }
            });

            let recursive_validation = if *is_directory {
                quote! {
                    let child_report = child_instance.validate();
                    report.merge(child_report);
                }
            } else {
                quote! {
                    // File types don't have validate() method
                }
            };

            quote! {
                // Validate dynamic ID instances in current directory
                if self.exists() {
                    let read_result = ::tree_type::fs::read_dir(&self.0);

                    match read_result {
                        Ok(entries) => {
                            for entry in entries {
                                match entry {
                                    Ok(entry) => {
                                        let entry_path = entry.path();

                                        // Check if entry matches expected type (file or directory)
                                        let is_expected_type = if #is_directory {
                                            entry_path.is_dir()
                                        } else {
                                            entry_path.is_file()
                                        };

                                        if !is_expected_type {
                                            continue;
                                        }

                                        #pattern_validation

                                        // Create child instance once for both validator and recursive validation
                                        let child_instance = #child_type(entry_path.clone());

                                        #validator_call

                                        // Only recursively validate if it's a directory
                                        #recursive_validation
                                    }
                                    Err(e) => {
                                        report.errors.push(tree_type::ValidationError {
                                            path: self.0.clone(),
                                            message: format!("Failed to read directory entry: {}", e),
                                        });
                                    }
                                }
                            }
                        }
                        Err(e) => {
                            report.errors.push(tree_type::ValidationError {
                                path: self.0.clone(),
                                message: format!("Failed to read directory: {}", e),
                            });
                        }
                    }
                }
            }
        } else {
                        let name = child.name();

                        // Check for pattern validation
                        let pattern = child.attributes().iter().find_map(|attr| {
                            if let Attribute::Pattern(lit) = attr {
                                Some(lit)
                            } else {
                                None
                            }
                        });

                        // Check for custom validator
                        let custom_validator = child.attributes().iter().find_map(|attr| {
                            if let Attribute::Validate(expr) = attr {
                                Some(expr)
                            } else {
                                None
                            }
                        });

                        if let Some(pattern_lit) = pattern {
                            // Pattern validation
                            quote! {
                                {
                                    if self.#name().exists() {
                                        match self.#name().read_to_string() {
                                            Ok(content) => {
                                                match ::tree_type::deps::pattern_validation::Regex::new(#pattern_lit) {
                                                    Ok(re) => {
                                                        if !re.is_match(&content) {
                                                            report.errors.push(tree_type::ValidationError {
                                                                path: self.#name().as_path().to_path_buf(),
                                                                message: format!("File content does not match pattern: {}", #pattern_lit),
                                                            });
                                                        }
                                                    }
                                                    Err(e) => {
                                                        report.errors.push(tree_type::ValidationError {
                                                            path: self.#name().as_path().to_path_buf(),
                                                            message: format!("Invalid regex pattern: {}", e),
                                                        });
                                                    }
                                                }
                                            }
                                            Err(e) => {
                                                report.errors.push(tree_type::ValidationError {
                                                    path: self.#name().as_path().to_path_buf(),
                                                    message: format!("Failed to read file: {}", e),
                                                });
                                            }
                                        }
                                    }
                                }
                            }
                        } else if let Some(validator) = custom_validator {
                            // Call custom validation function
                            quote! {
                                let result = (#validator)(&self.#name());
                                for error in result.errors {
                                    report.errors.push(tree_type::ValidationError {
                                        path: self.#name().as_path().to_path_buf(),
                                        message: error,
                                    });
                                }
                                for warning in result.warnings {
                                    report.warnings.push(tree_type::ValidationWarning {
                                        path: self.#name().as_path().to_path_buf(),
                                        message: warning,
                                    });
                                }
                            }
                        } else if child.is_required() {
                            // Standard required validation
                            quote! {
                                if !self.#name().exists() {
                                    report.errors.push(tree_type::ValidationError {
                                        path: self.#name().as_path().to_path_buf(),
                                        message: "Required path does not exist".to_string(),
                                    });
                                }
                            }
                        } else {
                            quote! {}
                        }
                    }
    });

    // Add recursive validation for child directories
    let recursive_validations = children.iter().filter_map(|child| match child {
        Child::Directory { name, .. } => Some(quote! {
            if self.#name().exists() {
                let child_report = self.#name().validate();
                report.merge(child_report);
            }
        }),
        _ => None,
    });

    quote! {
        #[allow(clippy::regex_creation_in_loops)]
        pub fn validate(&self) -> ::tree_type::ValidationReport {
            let mut report = ::tree_type::ValidationReport::new();

            // Validate root directory exists
            if !self.exists() {
                report.errors.push(tree_type::ValidationError {
                    path: self.0.clone(),
                    message: "Directory does not exist".to_string(),
                });
            }

            #(#validations)*
            #(#recursive_validations)*

            report
        }
    }
}

#[expect(clippy::too_many_lines)]
fn generate_setup_method(
    children: &[Child],
    depth: usize,
    root_children: &[Child],
) -> proc_macro2::TokenStream {
    let setups = children.iter().filter_map(|child| {
        let name = child.name();

        // Check for symlink attribute
        if let Some(target_path) = child.get_symlink_target() {
            let target_str = target_path.value();

            // Check if this is a same-directory symlink (identifier-based, no path separators)
            if !target_str.contains('/') {
                // Same-directory symlink: use self.target().as_path()
                let target_ident = syn::Ident::new(&target_str, target_path.span());
                return Some(quote! {
                    if !self.#name().as_path().exists() {
                        // Use relative filename for symlink target
                        let target_filename = self.#target_ident().as_path().file_name().unwrap().to_string_lossy().to_string();

                        #[cfg(unix)]
                        if let Err(e) = std::os::unix::fs::symlink(&target_filename, self.#name().as_path()) {
                            errors.push(tree_type::BuildError::File(
                                self.#name().as_path().to_path_buf(),
                                Box::new(e)
                            ));
                        }
                        #[cfg(windows)]
                        {
                            let result = if self.#target_ident().as_path().is_dir() {
                                std::os::windows::fs::symlink_dir(&target_filename, self.#name().as_path())
                            } else {
                                std::os::windows::fs::symlink_file(&target_filename, self.#name().as_path())
                            };
                            if let Err(e) = result {
                                errors.push(tree_type::BuildError::File(
                                    self.#name().as_path().to_path_buf(),
                                    Box::new(e)
                                ));
                            }
                        }
                    }
                });
            }
            // Cross-directory symlink: resolve identities in path
            let up_dirs_str = "../".repeat(depth);

            // Try to resolve identities in the target path
            if let Some(resolved_code) = resolve_symlink_target_path(&target_str, root_children, &up_dirs_str, depth) {
                return Some(quote! {
                    if !self.#name().as_path().exists() {
                        let relative_target = #resolved_code;

                        #[cfg(unix)]
                        if let Err(e) = std::os::unix::fs::symlink(&relative_target, self.#name().as_path()) {
                            errors.push(tree_type::BuildError::File(
                                self.#name().as_path().to_path_buf(),
                                Box::new(e)
                            ));
                        }
                        #[cfg(windows)]
                        {
                            let result = std::os::windows::fs::symlink_file(&relative_target, self.#name().as_path());
                            if let Err(e) = result {
                                errors.push(tree_type::BuildError::File(
                                    self.#name().as_path().to_path_buf(),
                                    Box::new(e)
                                ));
                            }
                        }
                    }
                });
            }
            // Fallback to original behavior for paths that can't be resolved
            return Some(quote! {
                if !self.#name().as_path().exists() {
                    let target_str = #target_str;

                    let relative_target = if let Some(path_without_slash) = target_str.strip_prefix('/') {
                        // Absolute path (like "/config/main") - convert to relative
                        let up_dirs = #up_dirs_str;
                        format!("{}{}", up_dirs, path_without_slash)
                    } else if target_str.contains('.') {
                        // File path (like "config/config.toml") - needs relative path calculation
                        let up_dirs = #up_dirs_str;
                        format!("{}{}", up_dirs, target_str)
                    } else {
                        // Identity path - use as-is
                        let up_dirs = #up_dirs_str;
                        format!("{}{}", up_dirs, target_str)
                    };

                    #[cfg(unix)]
                    if let Err(e) = std::os::unix::fs::symlink(&relative_target, self.#name().as_path()) {
                        errors.push(tree_type::BuildError::File(
                            self.#name().as_path().to_path_buf(),
                            Box::new(e)
                        ));
                    }
                    #[cfg(windows)]
                    {
                        let result = std::os::windows::fs::symlink_file(&relative_target, self.#name().as_path());
                        if let Err(e) = result {
                            errors.push(tree_type::BuildError::File(
                                self.#name().as_path().to_path_buf(),
                                Box::new(e)
                            ));
                        }
                    }
                }
            });
        }

        match child {
            Child::Directory { .. } => {
                // Recursively call setup() on child directories (matches legacy behavior)
                Some(quote! {
                    if let Err(child_errors) = self.#name().setup() {
                        errors.extend(child_errors);
                    }
                })
            }
            Child::File { attributes, .. } => {
                // Find default attribute if present
                let has_default = attributes.iter().any(|attr| matches!(attr, Attribute::Default(_)));

                if has_default {
                    Some(quote! {
                        if let Err(e) = self.#name().create_default::<std::io::Error>() {
                            errors.push(tree_type::BuildError::File(
                                self.#name().as_path().to_path_buf(),
                                Box::new(e)
                            ));
                        }
                    })
                } else {
                    None
                }
            }
            Child::DynamicId { .. } => None
        }
    });

    // Generate identity symlinks for files with different actual filenames
    let identity_symlinks = children.iter().filter_map(|child| {
        match child {
            Child::File { name, custom_filename, attributes, .. } => {
                // Skip files that have symlink attributes - they handle their own symlinks
                let has_symlink = attributes.iter().any(|attr| matches!(attr, Attribute::Symlink(_)));
                if has_symlink {
                    return None;
                }

                if let Some(filename_lit) = custom_filename {
                    let filename_str = filename_lit.value();
                    let identity_name = name.to_string();

                    // Only create identity symlink if identity name differs from actual filename
                    if identity_name != filename_str {
                        return Some(quote! {
                            // Create identity symlink: identity_name -> actual_filename
                            let identity_path = self.as_path().join(#identity_name);
                            if !identity_path.exists() {
                                #[cfg(unix)]
                                if let Err(e) = std::os::unix::fs::symlink(#filename_str, &identity_path) {
                                    errors.push(tree_type::BuildError::File(
                                        identity_path,
                                        Box::new(e)
                                    ));
                                }
                                #[cfg(windows)]
                                {
                                    let result = std::os::windows::fs::symlink_file(#filename_str, &identity_path);
                                    if let Err(e) = result {
                                        errors.push(tree_type::BuildError::File(
                                            identity_path,
                                            Box::new(e)
                                        ));
                                    }
                                }
                            }
                        });
                    }
                }
                None
            }
            _ => None
        }
    });

    quote! {
        pub fn setup(&self) -> std::result::Result<Vec<::tree_type::BuildError>, Vec<::tree_type::BuildError>> {
            let mut errors = Vec::new();

            if !self.0.exists() {
                let create_result = ::tree_type::fs::create_dir_all(&self.0);

                if let Err(e) = create_result {
                    errors.push(tree_type::BuildError::Directory(
                        self.0.clone(),
                        e
                    ));
                    return Err(errors);
                }
            }

            #(#setups)*

            // Create identity symlinks for files
            #(#identity_symlinks)*

            if errors.is_empty() {
                Ok(Vec::new())
            } else {
                Err(errors)
            }
        }
    }
}

fn generate_ensure_method(_children: &[Child]) -> proc_macro2::TokenStream {
    quote! {
        pub fn ensure(&self) -> std::result::Result<::tree_type::ValidationReport, Vec<::tree_type::BuildError>> {
            self.setup()?;
            Ok(self.validate())
        }
    }
}

/// Generates a `std::fmt::Display` implementation for a generated type.
///
/// The Display implementation outputs the path as a clean string using `Path::display()`,
/// matching the behavior of `std::path::Path` for consistent user experience.
fn generate_display_impl(name: &syn::Ident) -> proc_macro2::TokenStream {
    quote! {
        impl std::fmt::Display for #name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", self.0.display())
            }
        }
    }
}

/// Generates a `std::fmt::Debug` implementation for a generated type.
///
/// The Debug implementation outputs the type name followed by the path in parentheses,
/// providing type information for debugging while showing the underlying path.
fn generate_debug_impl(name: &syn::Ident) -> proc_macro2::TokenStream {
    quote! {
        impl std::fmt::Debug for #name {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}({})", stringify!(#name), self.0.display())
            }
        }
    }
}