ruby-rbs 0.3.0

Rust bindings for RBS -- the type signature language for Ruby programs
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
use serde::Deserialize;
use std::{env, error::Error, fs::File, io::Write, path::Path};

// This config-driven code generation approach is inspired by Prism's ruby-prism crate.
// See: https://github.com/ruby/prism/blob/main/rust/ruby-prism/build.rs

#[derive(Debug, Deserialize)]
struct Config {
    nodes: Vec<Node>,
    #[serde(default)]
    enums: std::collections::HashMap<String, EnumDef>,
}

#[derive(Debug, Deserialize)]
struct EnumDef {
    #[serde(default)]
    #[allow(dead_code)]
    optional: bool,
    symbols: Vec<String>,
}

#[derive(Debug, Deserialize)]
struct NodeField {
    name: String,
    c_type: String,
    c_name: Option<String>,
    #[serde(default)]
    optional: bool,
}

impl NodeField {
    fn c_name(&self) -> &str {
        let name = self.c_name.as_ref().unwrap_or(&self.name);
        if name == "type" { "type_" } else { name }
    }
}

#[derive(Debug, Deserialize)]
struct LocationField {
    #[serde(default)]
    required: Option<String>,
    #[serde(default)]
    optional: Option<String>,
}

impl LocationField {
    fn name(&self) -> &str {
        self.required.as_ref().or(self.optional.as_ref()).unwrap()
    }

    fn is_required(&self) -> bool {
        self.required.is_some()
    }
}

#[derive(Debug, Deserialize)]
struct Node {
    name: String,
    rust_name: String,
    fields: Option<Vec<NodeField>>,
    locations: Option<Vec<LocationField>>,
}

impl Node {
    fn variant_name(&self) -> &str {
        self.rust_name
            .strip_suffix("Node")
            .unwrap_or(&self.rust_name)
    }
}

fn main() -> Result<(), Box<dyn Error>> {
    let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let config_path = manifest_dir.join("vendor/rbs/config.yml");

    let config_path = config_path
        .canonicalize()
        .map_err(|e| format!("Failed to find config.yml at {:?}: {}", config_path, e))?;

    println!("cargo:rerun-if-changed={}", config_path.display());

    let config_file = File::open(&config_path)?;
    let mut config: Config = serde_yaml::from_reader(config_file)?;

    // Symbol represents identifiers (interned strings), not traditional AST nodes.
    // However, the C parser defines it in `rbs_node_type` (RBS_AST_SYMBOL) and
    // treats it as a node (rbs_node_t*) in many contexts (lists, hashes).
    // We inject it into the config so it is generated as a struct matching the Node pattern,
    // allowing it to be wrapped in the Node enum and handled uniformly in Rust.
    config.nodes.push(Node {
        name: "RBS::AST::Symbol".to_string(),
        rust_name: "SymbolNode".to_string(),
        fields: None,
        locations: None,
    });

    config.nodes.sort_by(|a, b| a.name.cmp(&b.name));
    generate(&config)?;

    Ok(())
}

enum CIdentifier {
    Type,     // foo_bar_t
    Constant, // FOO_BAR
    Method,   // visit_foo_bar
}

fn convert_name(name: &str, identifier: CIdentifier) -> String {
    let type_name = name.replace("::", "_");
    let lowercase = matches!(identifier, CIdentifier::Type | CIdentifier::Method);
    let mut out = String::new();
    let mut prev_is_lower = false;

    for ch in type_name.chars() {
        if ch.is_ascii_uppercase() {
            if prev_is_lower {
                out.push('_');
            }
            out.push(if lowercase {
                ch.to_ascii_lowercase()
            } else {
                ch
            });
            prev_is_lower = false;
        } else if ch == '_' {
            out.push(ch);
            prev_is_lower = false;
        } else {
            out.push(if lowercase {
                ch
            } else {
                ch.to_ascii_uppercase()
            });
            prev_is_lower = ch.is_ascii_lowercase() || ch.is_ascii_digit();
        }
    }

    if matches!(identifier, CIdentifier::Type) {
        out.push_str("_t");
    }
    out
}

/// Converts snake_case to PascalCase for Rust enum names
fn snake_to_pascal(s: &str) -> String {
    s.split('_')
        .map(|word| {
            let mut chars = word.chars();
            match chars.next() {
                None => String::new(),
                Some(first) => first.to_uppercase().chain(chars).collect(),
            }
        })
        .collect()
}

/// Generates Rust enum module constant name from snake_case (e.g., "unspecified" -> "RBS_ATTRIBUTE_VISIBILITY_UNSPECIFIED")
fn enum_constant_name(enum_name: &str, variant: &str) -> String {
    format!(
        "RBS_{}",
        format!("{}_{}", enum_name, variant).to_uppercase()
    )
}

fn write_enum_field_accessor(
    file: &mut File,
    field: &NodeField,
    enum_name: &str,
) -> std::io::Result<()> {
    let rust_enum_name = snake_to_pascal(enum_name);
    writeln!(file, "    #[must_use]")?;
    writeln!(
        file,
        "    pub fn {}(&self) -> {} {{",
        field.name, rust_enum_name
    )?;
    writeln!(
        file,
        "        {}::from_raw(unsafe {{ (*self.pointer).{} }})",
        rust_enum_name,
        field.c_name()
    )?;
    writeln!(file, "    }}")?;
    writeln!(file)?;
    Ok(())
}

fn write_node_field_accessor(
    file: &mut File,
    field: &NodeField,
    rust_type: &str,
) -> std::io::Result<()> {
    if field.optional {
        writeln!(file, "    #[must_use]")?;
        writeln!(
            file,
            "    pub fn {}(&self) -> Option<{rust_type}<'a>> {{",
            field.name,
        )?;
        writeln!(
            file,
            "        let ptr = unsafe {{ (*self.pointer).{} }};",
            field.c_name()
        )?;
        writeln!(file, "        if ptr.is_null() {{")?;
        writeln!(file, "            None")?;
        writeln!(file, "        }} else {{")?;
        writeln!(
            file,
            "            Some({rust_type} {{ parser: self.parser, pointer: ptr, marker: PhantomData }})"
        )?;
        writeln!(file, "        }}")?;
    } else {
        writeln!(file, "    #[must_use]")?;
        writeln!(
            file,
            "    pub fn {}(&self) -> {rust_type}<'a> {{",
            field.name
        )?;
        writeln!(
            file,
            "        {rust_type} {{ parser: self.parser, pointer: unsafe {{ (*self.pointer).{} }}, marker: PhantomData }}",
            field.c_name()
        )?;
    }
    writeln!(file, "    }}")?;
    writeln!(file)?;
    Ok(())
}

fn write_visit_trait(file: &mut File, config: &Config) -> Result<(), Box<dyn std::error::Error>> {
    writeln!(file, "/// A trait for traversing the AST using a visitor")?;
    writeln!(file, "pub trait Visit {{")?;
    writeln!(
        file,
        "   /// Visit any node of the AST. Generally used to continue traversal"
    )?;
    writeln!(file, "   fn visit(&mut self, node: &Node) {{")?;
    writeln!(file, "       match node {{")?;

    for node in &config.nodes {
        let node_variant_name = node.variant_name();
        let method_name = convert_name(node_variant_name, CIdentifier::Method);

        writeln!(file, "           Node::{node_variant_name}(it) => {{")?;
        writeln!(file, "               self.visit_{method_name}_node(it);")?;
        writeln!(file, "           }}")?;
    }

    writeln!(file, "       }}")?;
    writeln!(file, "   }}")?;

    for node in &config.nodes {
        let node_variant_name = node.variant_name();
        let method_name = convert_name(node_variant_name, CIdentifier::Method);

        writeln!(file)?;
        writeln!(
            file,
            "    fn visit_{method_name}_node(&mut self, node: &{node_variant_name}Node) {{"
        )?;
        writeln!(file, "        visit_{method_name}_node(self, node);")?;
        writeln!(file, "    }}")?;
    }
    writeln!(file, "}}")?;
    writeln!(file)?;

    // Map C field types (e.g. `rbs_type_name`) to the corresponding
    // visitor method name (e.g. `type_name` -> `visit_type_name_node`).
    let visitor_method_names: std::collections::HashMap<String, String> = config
        .nodes
        .iter()
        .map(|node| {
            let c_type = convert_name(&node.name, CIdentifier::Type);
            let c_type = c_type.strip_suffix("_t").unwrap_or(&c_type).to_string();
            let method = convert_name(node.variant_name(), CIdentifier::Method);
            (c_type, method)
        })
        .collect();

    let is_visitable = |c_type: &str| -> bool {
        matches!(c_type, "rbs_node" | "rbs_node_list" | "rbs_hash")
            || visitor_method_names.contains_key(c_type)
    };

    for node in &config.nodes {
        let node_variant_name = node.variant_name();
        let method_name = convert_name(node_variant_name, CIdentifier::Method);

        let has_visitable_fields = node
            .fields
            .iter()
            .flatten()
            .any(|field| is_visitable(&field.c_type));

        if !has_visitable_fields {
            // If there's nothing to visit in this node, write the empty method with
            // underscored parameters, and skip to the next iteration
            writeln!(
                file,
                "pub fn visit_{method_name}_node<V: Visit + ?Sized>(_visitor: &mut V, _node: &{node_variant_name}Node) {{}}"
            )?;

            continue;
        }

        writeln!(
            file,
            "pub fn visit_{method_name}_node<V: Visit + ?Sized>(visitor: &mut V, node: &{node_variant_name}Node) {{"
        )?;

        if let Some(fields) = &node.fields {
            for field in fields {
                let field_method_name = if field.name == "type" {
                    "type_"
                } else {
                    field.name.as_str()
                };

                match field.c_type.as_str() {
                    "rbs_node" => {
                        if field.optional {
                            writeln!(
                                file,
                                "    if let Some(item) = node.{field_method_name}() {{"
                            )?;
                            writeln!(file, "        visitor.visit(&item);")?;
                            writeln!(file, "    }}")?;
                        } else {
                            writeln!(file, "    visitor.visit(&node.{field_method_name}());")?;
                        }
                    }

                    "rbs_node_list" => {
                        if field.optional {
                            writeln!(
                                file,
                                "    if let Some(list) = node.{field_method_name}() {{"
                            )?;
                            writeln!(file, "        for item in list.iter() {{")?;
                            writeln!(file, "            visitor.visit(&item);")?;
                            writeln!(file, "        }}")?;
                            writeln!(file, "    }}")?;
                        } else {
                            writeln!(file, "    for item in node.{field_method_name}().iter() {{")?;
                            writeln!(file, "        visitor.visit(&item);")?;
                            writeln!(file, "    }}")?;
                        }
                    }

                    "rbs_hash" => {
                        if field.optional {
                            writeln!(
                                file,
                                "    if let Some(hash) = node.{field_method_name}() {{"
                            )?;
                            writeln!(file, "        for (key, value) in hash.iter() {{")?;
                            writeln!(file, "            visitor.visit(&key);")?;
                            writeln!(file, "            visitor.visit(&value);")?;
                            writeln!(file, "        }}")?;
                            writeln!(file, "    }}")?;
                        } else {
                            writeln!(
                                file,
                                "    for (key, value) in node.{field_method_name}().iter() {{"
                            )?;
                            writeln!(file, "        visitor.visit(&key);")?;
                            writeln!(file, "        visitor.visit(&value);")?;
                            writeln!(file, "    }}")?;
                        }
                    }

                    _ => {
                        if let Some(visit_method_name) = visitor_method_names.get(&field.c_type) {
                            if field.optional {
                                writeln!(
                                    file,
                                    "    if let Some(item) = node.{field_method_name}() {{"
                                )?;
                                writeln!(
                                    file,
                                    "        visitor.visit_{visit_method_name}_node(&item);"
                                )?;
                                writeln!(file, "    }}")?;
                            } else {
                                writeln!(
                                    file,
                                    "    visitor.visit_{visit_method_name}_node(&node.{field_method_name}());"
                                )?;
                            }
                        }
                    }
                }
            }
        }
        writeln!(file, "}}")?;
        writeln!(file)?;
    }

    Ok(())
}

fn write_enum_types(
    file: &mut File,
    enums: &std::collections::HashMap<String, EnumDef>,
) -> Result<(), Box<dyn Error>> {
    for (enum_name, enum_def) in enums {
        let rust_enum_name = snake_to_pascal(enum_name);
        let c_enum_module = format!("rbs_{}", enum_name);

        // Write enum definition
        writeln!(file, "/// Generated from config.yml enums.{}", enum_name)?;
        writeln!(file, "#[derive(Debug, Clone, Copy, PartialEq, Eq)]")?;
        writeln!(file, "pub enum {} {{", rust_enum_name)?;

        for symbol in &enum_def.symbols {
            let variant_name = snake_to_pascal(symbol);
            writeln!(file, "    /// {} (:{}) ", variant_name, symbol)?;
            writeln!(file, "    {},", variant_name)?;
        }

        writeln!(file, "}}")?;
        writeln!(file)?;

        // Write impl block with from_raw
        writeln!(file, "impl {} {{", rust_enum_name)?;
        writeln!(
            file,
            "    /// Converts the raw C enum value to the Rust enum."
        )?;
        writeln!(file, "    #[must_use]")?;
        writeln!(
            file,
            "    pub fn from_raw(raw: {}::Type) -> Self {{",
            c_enum_module
        )?;
        writeln!(file, "        match raw {{")?;

        for symbol in &enum_def.symbols {
            let variant_name = snake_to_pascal(symbol);
            let constant_name = enum_constant_name(enum_name, symbol);
            writeln!(
                file,
                "            {}::{} => Self::{},",
                c_enum_module, constant_name, variant_name
            )?;
        }

        writeln!(
            file,
            "            _ => panic!(\"Unknown {}: {{}}\", raw),",
            c_enum_module
        )?;
        writeln!(file, "        }}")?;
        writeln!(file, "    }}")?;
        writeln!(file, "}}")?;
        writeln!(file)?;
    }

    Ok(())
}

fn generate(config: &Config) -> Result<(), Box<dyn Error>> {
    let out_dir = env::var("OUT_DIR")?;
    let dest_path = Path::new(&out_dir).join("bindings.rs");

    let mut file = File::create(&dest_path)?;

    writeln!(file, "// Generated by build.rs from config.yml")?;
    writeln!(file)?;

    // Generate enum types from config
    write_enum_types(&mut file, &config.enums)?;

    for node in &config.nodes {
        writeln!(file, "#[derive(Debug)]")?;
        writeln!(file, "pub struct {}<'a> {{", node.rust_name)?;
        writeln!(file, "    #[allow(dead_code)]")?;
        writeln!(file, "    parser: NonNull<rbs_parser_t>,")?;
        writeln!(
            file,
            "    pointer: *mut {},",
            convert_name(&node.name, CIdentifier::Type)
        )?;
        writeln!(
            file,
            "    marker: PhantomData<&'a mut {}>",
            convert_name(&node.name, CIdentifier::Type)
        )?;
        writeln!(file, "}}\n")?;

        writeln!(file, "impl<'a> {}<'a> {{", node.rust_name)?;
        writeln!(file, "    /// Converts this node to a generic node.")?;
        writeln!(file, "    #[must_use]")?;
        writeln!(file, "    pub fn as_node(self) -> Node<'a> {{")?;
        writeln!(file, "        Node::{}(self)", node.variant_name())?;
        writeln!(file, "    }}")?;
        writeln!(file)?;
        writeln!(file, "    /// Returns the location of this node.")?;
        writeln!(file, "    #[must_use]")?;
        writeln!(file, "    pub fn location(&self) -> RBSLocationRange {{")?;
        writeln!(
            file,
            "        RBSLocationRange::new(unsafe {{ (*self.pointer).base.location }})"
        )?;
        writeln!(file, "    }}")?;
        writeln!(file)?;

        // Generate location accessor methods
        if let Some(locations) = &node.locations {
            for location in locations {
                let location_name = location.name();
                let method_name = format!("{}_location", location_name);
                let field_name = format!("{}_range", location_name);

                if location.is_required() {
                    writeln!(
                        file,
                        "    /// Returns the `{}` sub-location of this node.",
                        location_name
                    )?;
                    writeln!(file, "    #[must_use]")?;
                    writeln!(
                        file,
                        "    pub fn {}(&self) -> RBSLocationRange {{",
                        method_name
                    )?;
                    writeln!(
                        file,
                        "        RBSLocationRange::new(unsafe {{ (*self.pointer).{} }})",
                        field_name
                    )?;
                    writeln!(file, "    }}")?;
                } else {
                    writeln!(
                        file,
                        "    /// Returns the `{}` sub-location of this node if present.",
                        location_name
                    )?;
                    writeln!(file, "    #[must_use]")?;
                    writeln!(
                        file,
                        "    pub fn {}(&self) -> Option<RBSLocationRange> {{",
                        method_name
                    )?;
                    writeln!(
                        file,
                        "        let range = unsafe {{ (*self.pointer).{} }};",
                        field_name
                    )?;
                    writeln!(file, "        if range.start_char == -1 {{")?;
                    writeln!(file, "            None")?;
                    writeln!(file, "        }} else {{")?;
                    writeln!(file, "            Some(RBSLocationRange::new(range))")?;
                    writeln!(file, "        }}")?;
                    writeln!(file, "    }}")?;
                }
                writeln!(file)?;
            }
        }

        if let Some(fields) = &node.fields {
            for field in fields {
                match field.c_type.as_str() {
                    "rbs_string" => {
                        writeln!(file, "    #[must_use]")?;
                        writeln!(file, "    pub fn {}(&self) -> RBSString<'a> {{", field.name)?;
                        writeln!(
                            file,
                            "        RBSString::new(unsafe {{ &(*self.pointer).{} }})",
                            field.c_name()
                        )?;
                        writeln!(file, "    }}")?;
                        writeln!(file)?;
                    }
                    "bool" => {
                        writeln!(file, "    #[must_use]")?;
                        writeln!(file, "    pub fn {}(&self) -> bool {{", field.name)?;
                        writeln!(file, "        unsafe {{ (*self.pointer).{} }}", field.name)?;
                        writeln!(file, "    }}")?;
                        writeln!(file)?;
                    }
                    "rbs_ast_comment" => {
                        write_node_field_accessor(&mut file, field, "CommentNode")?
                    }
                    "rbs_ast_declarations_class_super" => {
                        write_node_field_accessor(&mut file, field, "ClassSuperNode")?
                    }
                    "rbs_ast_symbol" => write_node_field_accessor(&mut file, field, "SymbolNode")?,
                    "rbs_hash" => {
                        write_node_field_accessor(&mut file, field, "RBSHash")?;
                    }
                    "rbs_namespace" => {
                        write_node_field_accessor(&mut file, field, "NamespaceNode")?;
                    }
                    "rbs_node" => {
                        let name = if field.name == "type" {
                            "type_"
                        } else {
                            field.name.as_str()
                        };
                        if field.optional {
                            writeln!(file, "    #[must_use]")?;
                            writeln!(file, "    pub fn {name}(&self) -> Option<Node<'a>> {{")?;
                            writeln!(
                                file,
                                "        let ptr = unsafe {{ (*self.pointer).{} }};",
                                field.c_name()
                            )?;
                            writeln!(
                                file,
                                "        if ptr.is_null() {{ None }} else {{ Some(Node::new(self.parser, ptr)) }}"
                            )?;
                        } else {
                            writeln!(file, "    #[must_use]")?;
                            writeln!(file, "    pub fn {name}(&self) -> Node<'a> {{")?;
                            writeln!(
                                file,
                                "        unsafe {{ Node::new(self.parser, (*self.pointer).{}) }}",
                                field.c_name()
                            )?;
                        }
                        writeln!(file, "    }}")?;
                        writeln!(file)?;
                    }
                    "rbs_node_list" => {
                        write_node_field_accessor(&mut file, field, "NodeList")?;
                    }
                    "rbs_type_name" => {
                        write_node_field_accessor(&mut file, field, "TypeNameNode")?;
                    }
                    "rbs_types_block" => {
                        write_node_field_accessor(&mut file, field, "BlockTypeNode")?
                    }
                    c_type if config.enums.contains_key(c_type) => {
                        write_enum_field_accessor(&mut file, field, c_type)?;
                    }
                    "rbs_attr_ivar_name" => {
                        writeln!(file, "    #[must_use]")?;
                        writeln!(file, "    pub fn {}(&self) -> AttrIvarName {{", field.name)?;
                        writeln!(
                            file,
                            "        AttrIvarName::from_raw(unsafe {{ (*self.pointer).{} }})",
                            field.c_name()
                        )?;
                        writeln!(file, "    }}")?;
                        writeln!(file)?;
                    }
                    "rbs_location_range" => {
                        if field.optional {
                            writeln!(file, "    #[must_use]")?;
                            writeln!(
                                file,
                                "    pub fn {}(&self) -> Option<RBSLocationRange> {{",
                                field.name
                            )?;
                            writeln!(
                                file,
                                "        let range = unsafe {{ (*self.pointer).{} }};",
                                field.c_name()
                            )?;
                            writeln!(file, "        if range.start_char == -1 {{")?;
                            writeln!(file, "            None")?;
                            writeln!(file, "        }} else {{")?;
                            writeln!(file, "            Some(RBSLocationRange::new(range))")?;
                            writeln!(file, "        }}")?;
                            writeln!(file, "    }}")?;
                        } else {
                            writeln!(file, "    #[must_use]")?;
                            writeln!(
                                file,
                                "    pub fn {}(&self) -> RBSLocationRange {{",
                                field.name
                            )?;
                            writeln!(
                                file,
                                "        RBSLocationRange::new(unsafe {{ (*self.pointer).{} }})",
                                field.c_name()
                            )?;
                            writeln!(file, "    }}")?;
                        }
                        writeln!(file)?;
                    }
                    "rbs_location_range_list" => {
                        writeln!(file, "    #[must_use]")?;
                        writeln!(
                            file,
                            "    pub fn {}(&self) -> RBSLocationRangeList<'a> {{",
                            field.name
                        )?;
                        writeln!(
                            file,
                            "        RBSLocationRangeList {{ parser: self.parser, pointer: unsafe {{ (*self.pointer).{} }}, marker: PhantomData }}",
                            field.c_name()
                        )?;
                        writeln!(file, "    }}")?;
                        writeln!(file)?;
                    }
                    _ => panic!("Unknown field type: {}", field.c_type),
                }
            }
        }
        writeln!(file, "}}\n")?;
    }

    // Generate the Node enum to wrap all of the structs
    writeln!(file, "#[derive(Debug)]")?;
    writeln!(file, "pub enum Node<'a> {{")?;
    for node in &config.nodes {
        let variant_name = node
            .rust_name
            .strip_suffix("Node")
            .unwrap_or(&node.rust_name);

        writeln!(file, "    {variant_name}({}<'a>),", node.rust_name)?;
    }
    writeln!(file, "}}")?;

    writeln!(file, "impl Node<'_> {{")?;
    writeln!(file, "    #[allow(clippy::missing_safety_doc)]")?;
    writeln!(
        file,
        "    fn new(parser: NonNull<rbs_parser_t>, node: *mut rbs_node_t) -> Self {{"
    )?;
    writeln!(file, "        match unsafe {{ (*node).type_ }} {{")?;
    for node in &config.nodes {
        let enum_name = convert_name(&node.name, CIdentifier::Constant);
        let c_type = convert_name(&node.name, CIdentifier::Type);

        writeln!(
            file,
            "            rbs_node_type::{enum_name} => Self::{}({} {{ parser, pointer: node.cast::<{c_type}>(), marker: PhantomData }}),",
            node.variant_name(),
            node.rust_name,
        )?;
    }
    writeln!(
        file,
        "            _ => panic!(\"Unknown node type: {{}}\", unsafe {{ (*node).type_ }})"
    )?;
    writeln!(file, "        }}")?;
    writeln!(file, "    }}")?;
    writeln!(file)?;
    writeln!(file, "    /// Returns the location of the entire node.")?;
    writeln!(file, "    #[must_use]")?;
    writeln!(file, "    pub fn location(&self) -> RBSLocationRange {{")?;
    writeln!(file, "        match self {{")?;
    for node in &config.nodes {
        writeln!(
            file,
            "            Node::{}(node) => node.location(),",
            node.variant_name()
        )?;
    }
    writeln!(file, "        }}")?;
    writeln!(file, "    }}")?;
    writeln!(file, "}}")?;
    writeln!(file)?;

    write_visit_trait(&mut file, config)?;

    Ok(())
}