caraspace_export_macros 0.0.1

Procedural macros for the caraspace crate (SpytialDecorators derive).
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
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput, Attribute, Data, Fields, Type, PathArguments, GenericArgument};

/// Collect decorators from field types at compile time
/// This walks the type tree and generates calls to collect decorators from nested types
fn collect_field_type_decorators(data: &Data, self_type_name: &str) -> Vec<proc_macro2::TokenStream> {
    let mut field_decorators = Vec::new();
    let mut seen_types = std::collections::HashSet::new();
    
    // Add the self type to seen_types to prevent self-referential includes
    seen_types.insert(self_type_name.to_string());
    
    if let Data::Struct(data_struct) = data {
        match &data_struct.fields {
            Fields::Named(fields) => {
                for field in &fields.named {
                    field_decorators.extend(analyze_field_type(&field.ty, &mut seen_types));
                }
            }
            Fields::Unnamed(fields) => {
                for field in &fields.unnamed {
                    field_decorators.extend(analyze_field_type(&field.ty, &mut seen_types));
                }
            }
            Fields::Unit => {}
        }
    }
    
    field_decorators
}

/// Analyze a field type and generate decorator-collection calls for nested types.
///
/// Containers (`Vec`, `Option`, `Box`) are unwrapped to reach the inner type.
/// Primitives and standard collections are skipped (they can never carry
/// decorators).  Everything else gets a probe call via [`DecoProbe`] — if the
/// type implements `HasSpytialDecorators` the real decorators are returned;
/// otherwise the probe safely returns an empty set.
fn analyze_field_type(ty: &Type, seen_types: &mut std::collections::HashSet<String>) -> Vec<proc_macro2::TokenStream> {
    match ty {
        Type::Path(type_path) => {
            if let Some(segment) = type_path.path.segments.last() {
                let name = segment.ident.to_string();
                match name.as_str() {
                    // Containers: unwrap to reach the inner type
                    "Vec" | "Option" | "Box" => {
                        if let PathArguments::AngleBracketed(args) = &segment.arguments {
                            if let Some(GenericArgument::Type(inner)) = args.args.first() {
                                return analyze_inner_type(inner, seen_types);
                            }
                        }
                    }
                    // Primitives and std collections: can never have decorators
                    "i8" | "i16" | "i32" | "i64" | "i128"
                    | "u8" | "u16" | "u32" | "u64" | "u128"
                    | "f32" | "f64" | "bool" | "char"
                    | "String" | "str"
                    | "Result" | "HashMap" | "HashSet" | "BTreeMap" | "BTreeSet" => {}
                    // Everything else: safe to probe
                    _ => {
                        if !seen_types.contains(&name) {
                            seen_types.insert(name.clone());
                            return vec![generate_probe_call(&name)];
                        }
                    }
                }
            }
        }
        _ => {}
    }
    Vec::new()
}

/// Recursively unwrap container generics (`Option<Box<T>>` → `T`), then
/// probe the inner type.
fn analyze_inner_type(ty: &Type, seen_types: &mut std::collections::HashSet<String>) -> Vec<proc_macro2::TokenStream> {
    if let Type::Path(type_path) = ty {
        if let Some(segment) = type_path.path.segments.last() {
            let name = segment.ident.to_string();
            match name.as_str() {
                "Vec" | "Option" | "Box" => {
                    if let PathArguments::AngleBracketed(args) = &segment.arguments {
                        if let Some(GenericArgument::Type(inner)) = args.args.first() {
                            return analyze_inner_type(inner, seen_types);
                        }
                    }
                }
                "i8" | "i16" | "i32" | "i64" | "i128"
                | "u8" | "u16" | "u32" | "u64" | "u128"
                | "f32" | "f64" | "bool" | "char"
                | "String" | "str"
                | "Result" | "HashMap" | "HashSet" | "BTreeMap" | "BTreeSet" => {}
                _ => {
                    if !seen_types.contains(&name) {
                        seen_types.insert(name.clone());
                        return vec![generate_probe_call(&name)];
                    }
                }
            }
        }
    }
    Vec::new()
}

/// Generate a probe call that safely collects decorators from `type_name`.
///
/// Uses the inherent-method-priority trick: if the type implements
/// `HasSpytialDecorators`, the inherent `DecoProbe::get` is chosen and
/// returns real decorators.  Otherwise the blanket `DefaultDecorators::get`
/// is chosen and returns an empty set.  No heuristic needed.
fn generate_probe_call(type_name: &str) -> proc_macro2::TokenStream {
    let type_ident = syn::Ident::new(type_name, proc_macro2::Span::call_site());
    quote! {
        .extend_with({
            use caraspace::spytial_annotations::DefaultDecorators as _;
            caraspace::spytial_annotations::DecoProbe::<#type_ident>(::std::marker::PhantomData).get()
        })
    }
}

/// Derive macro for implementing HasSpytialDecorators trait
/// 
/// This macro analyzes all spatial annotation attributes on a struct
/// and generates a single implementation of HasSpytialDecorators that includes
/// all the annotations.
/// 
/// # Supported Attributes
/// - `#[attribute(field = "field_name")]` - Adds attribute directive
/// - `#[flag(name = "flag_name")]` - Adds flag directive  
/// - `#[orientation(selector = "sel", directions = ["up", "down"], negated = true)]` - Adds orientation constraint (`negated` optional)
/// - `#[align(selector = "sel", direction = "horizontal", negated = true)]` - Adds align constraint (`negated` optional)
/// - `#[cyclic(selector = "sel", direction = "up", negated = true)]` - Adds cyclic constraint (`negated` optional)
/// - `#[group(selector = "sel", name = "group_name", negated = true)]` - Adds selector-based group constraint (`negated` optional)
/// - `#[group(field = "field", group_on = 1, add_to_group = 2, negated = true)]` - Adds field-based group constraint (`negated` optional)
/// - `#[atom_color(selector = "sel", value = "red")]` - Adds atom color directive
/// - `#[size(selector = "sel", height = 20, width = 30)]` - Adds size directive
/// - `#[icon(selector = "sel", path = "icon.png", show_labels = true)]` - Adds icon directive
/// - `#[edge_style(field = "field", value = "blue", style = "dashed", weight = 2.0, show_label = true, hidden = false, filter = "...", selector = "...")]` - Adds edge style directive (replaces edge_color)
/// - `#[projection(sig = "signature")]` - Adds projection directive
/// - `#[hide_field(field = "field")]` - Adds hide field directive
/// - `#[hide_atom(selector = "sel")]` - Adds hide atom directive
/// - `#[inferred_edge(name = "edge", selector = "sel")]` - Adds inferred edge directive
/// - `#[tag(to_tag = "sel", name = "attr", value = "n-ary selector")]` - Adds tag directive
///
/// # Example
/// ```rust
/// use serde::Serialize;
/// use caraspace::SpytialDecorators;
/// 
/// #[derive(Serialize, SpytialDecorators)]
/// #[attribute(field = "name")]
/// #[flag(name = "important")]
/// struct Person {
///     name: String,
///     age: u32,
/// }
/// ```
#[proc_macro_derive(SpytialDecorators, attributes(attribute, flag, orientation, align, cyclic, group, atom_color, size, icon, edge_style, projection, hide_field, hide_atom, inferred_edge, tag))]
pub fn derive_spytial_decorators(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    
    let name = &input.ident;
    let generics = &input.generics;
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    // Parse spatial annotation attributes for this type
    let mut decorator_calls = Vec::new();
    
    for attr in &input.attrs {
        match parse_spatial_attribute(attr) {
            Some(SpatialAttribute::Attribute { field }) => {
                decorator_calls.push(quote! {
                    .attribute(#field, None)
                });
            }
            Some(SpatialAttribute::Flag { name }) => {
                decorator_calls.push(quote! {
                    .flag(#name)
                });
            }
            Some(SpatialAttribute::Orientation { selector, directions, negated }) => {
                decorator_calls.push(quote! {
                    .orientation(#selector, vec![#(#directions),*], #negated)
                });
            }
            Some(SpatialAttribute::Align { selector, direction, negated }) => {
                decorator_calls.push(quote! {
                    .align(#selector, #direction, #negated)
                });
            }
            Some(SpatialAttribute::Cyclic { selector, direction, negated }) => {
                decorator_calls.push(quote! {
                    .cyclic(#selector, #direction, #negated)
                });
            }
            Some(SpatialAttribute::GroupSelector { selector, name, negated }) => {
                decorator_calls.push(quote! {
                    .group_selector_based(#selector, #name, #negated)
                });
            }
            Some(SpatialAttribute::GroupField { field, group_on, add_to_group, negated }) => {
                decorator_calls.push(quote! {
                    .group_field_based(#field, #group_on, #add_to_group, None, #negated)
                });
            }
            Some(SpatialAttribute::AtomColor { selector, value }) => {
                decorator_calls.push(quote! {
                    .atom_color(#selector, #value)
                });
            }
            Some(SpatialAttribute::Size { selector, height, width }) => {
                decorator_calls.push(quote! {
                    .size(#selector, #height, #width)
                });
            }
            Some(SpatialAttribute::Icon { selector, path, show_labels }) => {
                decorator_calls.push(quote! {
                    .icon(#selector, #path, #show_labels)
                });
            }
            Some(SpatialAttribute::EdgeStyle {
                field,
                value,
                selector,
                filter,
                style,
                weight,
                show_label,
                hidden,
            }) => {
                let opt_str = |v: Option<String>| match v {
                    Some(s) => quote! { Some(#s) },
                    None => quote! { None },
                };
                let opt_f64 = |v: Option<f64>| match v {
                    Some(n) => quote! { Some(#n) },
                    None => quote! { None },
                };
                let opt_bool = |v: Option<bool>| match v {
                    Some(b) => quote! { Some(#b) },
                    None => quote! { None },
                };
                let selector_arg = opt_str(selector);
                let filter_arg = opt_str(filter);
                let style_arg = opt_str(style);
                let weight_arg = opt_f64(weight);
                let show_label_arg = opt_bool(show_label);
                let hidden_arg = opt_bool(hidden);
                decorator_calls.push(quote! {
                    .edge_style(
                        #field,
                        #value,
                        #selector_arg,
                        #filter_arg,
                        #style_arg,
                        #weight_arg,
                        #show_label_arg,
                        #hidden_arg,
                    )
                });
            }
            Some(SpatialAttribute::Projection { sig }) => {
                decorator_calls.push(quote! {
                    .projection(#sig)
                });
            }
            Some(SpatialAttribute::HideField { field, selector }) => {
                let selector_arg = match selector {
                    Some(s) => quote! { Some(#s) },
                    None => quote! { None },
                };
                decorator_calls.push(quote! {
                    .hide_field(#field, #selector_arg)
                });
            }
            Some(SpatialAttribute::HideAtom { selector }) => {
                decorator_calls.push(quote! {
                    .hide_atom(#selector)
                });
            }
            Some(SpatialAttribute::InferredEdge { name, selector }) => {
                decorator_calls.push(quote! {
                    .inferred_edge(#name, #selector)
                });
            }
            Some(SpatialAttribute::Tag { to_tag, name, value }) => {
                decorator_calls.push(quote! {
                    .tag(#to_tag, #name, #value)
                });
            }
            None => {}
        }
    }
    
    // Second, analyze field types and collect their decorators at compile time
    // Only do this for structs - enums don't have fields to analyze
    let field_type_decorators = match &input.data {
        Data::Struct(_) => collect_field_type_decorators(&input.data, &name.to_string()),
        Data::Enum(_) | Data::Union(_) => Vec::new(), // Enums and unions just return empty decorators
    };
    
    // Combine own decorators with field type decorators
    decorator_calls.extend(field_type_decorators);

    // Generate the HasSpytialDecorators implementation
    let expanded = quote! {
        impl #impl_generics caraspace::spytial_annotations::HasSpytialDecorators for #name #ty_generics #where_clause {
            fn decorators() -> caraspace::spytial_annotations::SpytialDecorators {
                // Register this type automatically when decorators() is called
                static REGISTRATION: ::std::sync::Once = ::std::sync::Once::new();
                REGISTRATION.call_once(|| {
                    let decorators = caraspace::spytial_annotations::SpytialDecoratorsBuilder::new()
                        #(#decorator_calls)*
                        .build();
                    caraspace::spytial_annotations::register_type_decorators(
                        stringify!(#name), 
                        decorators.clone()
                    );
                });

                caraspace::spytial_annotations::SpytialDecoratorsBuilder::new()
                    #(#decorator_calls)*
                    .build()
            }
        }
    };

    TokenStream::from(expanded)
}

#[derive(Debug)]
enum SpatialAttribute {
    Attribute { field: String },
    Flag { name: String },
    Orientation { selector: String, directions: Vec<String>, negated: bool },
    Align { selector: String, direction: String, negated: bool },
    Cyclic { selector: String, direction: String, negated: bool },
    GroupSelector { selector: String, name: String, negated: bool },
    GroupField { field: String, group_on: u32, add_to_group: u32, negated: bool },
    AtomColor { selector: String, value: String },
    Size { selector: String, height: u32, width: u32 },
    Icon { selector: String, path: String, show_labels: bool },
    EdgeStyle {
        field: String,
        value: String,
        selector: Option<String>,
        filter: Option<String>,
        style: Option<String>,
        weight: Option<f64>,
        show_label: Option<bool>,
        hidden: Option<bool>,
    },
    Projection { sig: String },
    HideField { field: String, selector: Option<String> },
    HideAtom { selector: String },
    InferredEdge { name: String, selector: String },
    Tag { to_tag: String, name: String, value: String },
}

fn parse_spatial_attribute(attr: &Attribute) -> Option<SpatialAttribute> {
    let path = &attr.path();
    
    if path.is_ident("attribute") {
        parse_attribute_args(attr)
    } else if path.is_ident("flag") {
        parse_flag_args(attr)
    } else if path.is_ident("orientation") {
        parse_orientation_args(attr)
    } else if path.is_ident("align") {
        parse_align_args(attr)
    } else if path.is_ident("cyclic") {
        parse_cyclic_args(attr)
    } else if path.is_ident("group") {
        parse_group_args(attr)
    } else if path.is_ident("atom_color") {
        parse_atom_color_args(attr)
    } else if path.is_ident("size") {
        parse_size_args(attr)
    } else if path.is_ident("icon") {
        parse_icon_args(attr)
    } else if path.is_ident("edge_style") {
        parse_edge_style_args(attr)
    } else if path.is_ident("projection") {
        parse_projection_args(attr)
    } else if path.is_ident("hide_field") {
        parse_hide_field_args(attr)
    } else if path.is_ident("hide_atom") {
        parse_hide_atom_args(attr)
    } else if path.is_ident("inferred_edge") {
        parse_inferred_edge_args(attr)
    } else if path.is_ident("tag") {
        parse_tag_args(attr)
    } else {
        None
    }
}

fn parse_attribute_args(attr: &Attribute) -> Option<SpatialAttribute> {
    // Simple parsing - look for field = "value"
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = tokens.to_string();
        
        if let Some(field) = extract_string_from_tokens(&token_str, "field") {
            return Some(SpatialAttribute::Attribute { field });
        }
    }
    
    Some(SpatialAttribute::Attribute { field: "name".to_string() })
}

fn parse_flag_args(attr: &Attribute) -> Option<SpatialAttribute> {
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = tokens.to_string();
        
        if let Some(name) = extract_string_from_tokens(&token_str, "name") {
            return Some(SpatialAttribute::Flag { name });
        }
    }
    
    Some(SpatialAttribute::Flag { name: "important".to_string() })
}

fn parse_orientation_args(attr: &Attribute) -> Option<SpatialAttribute> {
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = normalize_whitespace(&tokens.to_string());

        let selector = extract_string_from_tokens(&token_str, "selector").unwrap_or_else(|| "".to_string());
        let directions = extract_array_from_tokens(&token_str, "directions")
            .unwrap_or_else(|| vec!["up".to_string(), "down".to_string()]);
        let negated = extract_bool_from_tokens(&token_str, "negated").unwrap_or(false);

        return Some(SpatialAttribute::Orientation { selector, directions, negated });
    }

    None
}

fn parse_group_args(attr: &Attribute) -> Option<SpatialAttribute> {
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = normalize_whitespace(&tokens.to_string());
        let negated = extract_bool_from_tokens(&token_str, "negated").unwrap_or(false);

        if token_str.contains("field =") {
            // Field-based grouping
            let field = extract_string_from_tokens(&token_str, "field").unwrap_or_else(|| "id".to_string());
            let group_on = extract_number_from_tokens(&token_str, "group_on").unwrap_or(1);
            let add_to_group = extract_number_from_tokens(&token_str, "add_to_group").unwrap_or(2);

            Some(SpatialAttribute::GroupField { field, group_on, add_to_group, negated })
        } else {
            // Selector-based grouping
            let selector = extract_string_from_tokens(&token_str, "selector").unwrap_or_else(|| "".to_string());
            let name = extract_string_from_tokens(&token_str, "name").unwrap_or_else(|| "default".to_string());

            Some(SpatialAttribute::GroupSelector { selector, name, negated })
        }
    } else {
        None
    }
}

fn parse_align_args(attr: &Attribute) -> Option<SpatialAttribute> {
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = normalize_whitespace(&tokens.to_string());

        let selector = extract_string_from_tokens(&token_str, "selector").unwrap_or_else(|| "".to_string());
        let direction = extract_string_from_tokens(&token_str, "direction").unwrap_or_else(|| "horizontal".to_string());
        let negated = extract_bool_from_tokens(&token_str, "negated").unwrap_or(false);

        Some(SpatialAttribute::Align { selector, direction, negated })
    } else {
        None
    }
}

fn parse_cyclic_args(attr: &Attribute) -> Option<SpatialAttribute> {
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = normalize_whitespace(&tokens.to_string());

        let selector = extract_string_from_tokens(&token_str, "selector").unwrap_or_else(|| "".to_string());
        let direction = extract_string_from_tokens(&token_str, "direction").unwrap_or_else(|| "up".to_string());
        let negated = extract_bool_from_tokens(&token_str, "negated").unwrap_or(false);

        Some(SpatialAttribute::Cyclic { selector, direction, negated })
    } else {
        None
    }
}

fn parse_atom_color_args(attr: &Attribute) -> Option<SpatialAttribute> {
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = tokens.to_string();
        
        let selector = extract_string_from_tokens(&token_str, "selector").unwrap_or_else(|| "".to_string());
        let value = extract_string_from_tokens(&token_str, "value").unwrap_or_else(|| "blue".to_string());
        
        Some(SpatialAttribute::AtomColor { selector, value })
    } else {
        None
    }
}

fn parse_size_args(attr: &Attribute) -> Option<SpatialAttribute> {
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = tokens.to_string();
        
        let selector = extract_string_from_tokens(&token_str, "selector").unwrap_or_else(|| "".to_string());
        let height = extract_number_from_tokens(&token_str, "height").unwrap_or(20);
        let width = extract_number_from_tokens(&token_str, "width").unwrap_or(30);
        
        Some(SpatialAttribute::Size { selector, height, width })
    } else {
        None
    }
}

fn parse_icon_args(attr: &Attribute) -> Option<SpatialAttribute> {
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = tokens.to_string();
        
        let selector = extract_string_from_tokens(&token_str, "selector").unwrap_or_else(|| "".to_string());
        let path = extract_string_from_tokens(&token_str, "path").unwrap_or_else(|| "icon.png".to_string());
        let show_labels = extract_bool_from_tokens(&token_str, "show_labels").unwrap_or(true);
        
        Some(SpatialAttribute::Icon { selector, path, show_labels })
    } else {
        None
    }
}

fn parse_edge_style_args(attr: &Attribute) -> Option<SpatialAttribute> {
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = normalize_whitespace(&tokens.to_string());

        let field = extract_string_from_tokens(&token_str, "field")
            .unwrap_or_else(|| "relation".to_string());
        let value = extract_string_from_tokens(&token_str, "value")
            .unwrap_or_else(|| "blue".to_string());
        let selector = extract_string_from_tokens(&token_str, "selector");
        let filter = extract_string_from_tokens(&token_str, "filter");
        let style = extract_string_from_tokens(&token_str, "style");
        let weight = extract_float_from_tokens(&token_str, "weight");
        let show_label = extract_bool_from_tokens(&token_str, "show_label");
        let hidden = extract_bool_from_tokens(&token_str, "hidden");

        Some(SpatialAttribute::EdgeStyle {
            field,
            value,
            selector,
            filter,
            style,
            weight,
            show_label,
            hidden,
        })
    } else {
        None
    }
}

fn parse_projection_args(attr: &Attribute) -> Option<SpatialAttribute> {
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = tokens.to_string();
        
        let sig = extract_string_from_tokens(&token_str, "sig").unwrap_or_else(|| "default".to_string());
        
        Some(SpatialAttribute::Projection { sig })
    } else {
        None
    }
}

fn parse_hide_field_args(attr: &Attribute) -> Option<SpatialAttribute> {
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = tokens.to_string();
        
        let field = extract_string_from_tokens(&token_str, "field").unwrap_or_else(|| "field".to_string());
        let selector = extract_string_from_tokens(&token_str, "selector");
        
        Some(SpatialAttribute::HideField { field, selector })
    } else {
        None
    }
}

fn parse_hide_atom_args(attr: &Attribute) -> Option<SpatialAttribute> {
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = tokens.to_string();
        
        let selector = extract_string_from_tokens(&token_str, "selector").unwrap_or_else(|| "".to_string());
        
        Some(SpatialAttribute::HideAtom { selector })
    } else {
        None
    }
}

fn parse_inferred_edge_args(attr: &Attribute) -> Option<SpatialAttribute> {
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = tokens.to_string();

        let name = extract_string_from_tokens(&token_str, "name").unwrap_or_else(|| "edge".to_string());
        let selector = extract_string_from_tokens(&token_str, "selector").unwrap_or_else(|| "".to_string());

        Some(SpatialAttribute::InferredEdge { name, selector })
    } else {
        None
    }
}

fn parse_tag_args(attr: &Attribute) -> Option<SpatialAttribute> {
    if let Ok(meta) = attr.meta.require_list() {
        let tokens = &meta.tokens;
        let token_str = tokens.to_string();

        let to_tag = extract_string_from_tokens(&token_str, "to_tag").unwrap_or_default();
        let name = extract_string_from_tokens(&token_str, "name").unwrap_or_default();
        let value = extract_string_from_tokens(&token_str, "value").unwrap_or_default();

        Some(SpatialAttribute::Tag { to_tag, name, value })
    } else {
        None
    }
}

/// Replace newlines/tabs with spaces so the `extract_*_from_tokens` helpers
/// (which match `key = ` / `key = "`) work even when proc-macro2 wraps long
/// attribute lists across multiple lines.
fn normalize_whitespace(tokens: &str) -> String {
    tokens.replace(['\n', '\r', '\t'], " ")
}

fn extract_string_from_tokens(tokens: &str, key: &str) -> Option<String> {
    // Try both with and without spaces around =
    let patterns = [
        format!("{} = \"", key),
        format!("{}=\"", key),
        format!("{} =\"", key),
        format!("{}= \"", key),
    ];
    
    for pattern in &patterns {
        if let Some(start) = tokens.find(pattern) {
            let start = start + pattern.len();
            if let Some(end) = tokens[start..].find('"') {
                return Some(tokens[start..start + end].to_string());
            }
        }
    }
    None
}

fn extract_number_from_tokens(tokens: &str, key: &str) -> Option<u32> {
    let pattern = format!("{} = ", key);
    if let Some(start) = tokens.find(&pattern) {
        let start = start + pattern.len();
        let rest = &tokens[start..];
        let end = rest.find([',', ' ', ')']).unwrap_or(rest.len());
        if let Ok(value) = rest[..end].trim().parse::<u32>() {
            return Some(value);
        }
    }
    None
}

fn extract_bool_from_tokens(tokens: &str, key: &str) -> Option<bool> {
    let pattern = format!("{} = ", key);
    if let Some(start) = tokens.find(&pattern) {
        let start = start + pattern.len();
        let rest = &tokens[start..];
        let end = rest.find([',', ' ', ')']).unwrap_or(rest.len());
        if let Ok(value) = rest[..end].trim().parse::<bool>() {
            return Some(value);
        }
    }
    None
}

fn extract_float_from_tokens(tokens: &str, key: &str) -> Option<f64> {
    let pattern = format!("{} = ", key);
    if let Some(start) = tokens.find(&pattern) {
        let start = start + pattern.len();
        let rest = &tokens[start..];
        let end = rest.find([',', ' ', ')']).unwrap_or(rest.len());
        if let Ok(value) = rest[..end].trim().parse::<f64>() {
            return Some(value);
        }
    }
    None
}

fn extract_array_from_tokens(tokens: &str, key: &str) -> Option<Vec<String>> {
    // Try different patterns since the tokenizer might have different spacing
    let patterns = [
        format!("{}=[", key),
        format!("{} = [", key),
        format!("{}= [", key),
        format!("{} =[", key),
    ];
    
    for pattern in &patterns {
        if let Some(start) = tokens.find(pattern) {
            let start = start + pattern.len();
            let rest = &tokens[start..];
            if let Some(end) = rest.find(']') {
                let array_content = &rest[..end];
                let items: Vec<String> = array_content
                    .split(',')
                    .map(|s| s.trim().trim_matches('"').to_string())
                    .filter(|s| !s.is_empty())
                    .collect();
                return Some(items);
            }
        }
    }
    None
}