oak-rust 0.0.11

High-performance incremental Rust parser for the oak ecosystem with flexible configuration, emphasizing memory safety and zero-cost abstractions.
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
use crate::RustParser;

use crate::{ast::*, language::RustLanguage, lexer::RustTokenType, parser::RustElementType};
use core::range::Range;
use oak_core::{Builder, BuilderCache, GreenNode, OakDiagnostics, OakError, Parser, RedNode, RedTree, SourceText, TextEdit, builder::BuildOutput, source::Source};
use std::sync::Arc;

mod build_generics;

pub use build_generics::*;

/// AST builder for the Rust language.
///
/// `RustBuilder` is responsible for parsing Rust source code and constructing
/// an Abstract Syntax Tree (AST). It uses a Pratt parser to handle operator
/// precedence in expressions and supports all Rust syntax features.
#[derive(Clone, Copy)]
pub struct RustBuilder<'config> {
    /// Language configuration
    config: &'config RustLanguage,
}

impl<'config> RustBuilder<'config> {
    /// Creates a new `RustBuilder` with the given configuration.
    pub const fn new(config: &'config RustLanguage) -> Self {
        Self { config }
    }
}

impl<'config> Builder<RustLanguage> for RustBuilder<'config> {
    fn build<'a, S: Source + ?Sized>(&self, source: &S, edits: &[TextEdit], _cache: &'a mut impl BuilderCache<RustLanguage>) -> BuildOutput<RustLanguage> {
        let parser = RustParser::new(self.config);
        let mut session = oak_core::parser::session::ParseSession::<RustLanguage>::default();
        let OakDiagnostics { result, diagnostics } = parser.parse(source, edits, &mut session);

        match result {
            Ok(green) => {
                let source_text = SourceText::new(source.get_text_in((0..source.length()).into()).into_owned());
                match self.build_root(green, &source_text) {
                    Ok(root) => OakDiagnostics { result: Ok(root), diagnostics },
                    Err(e) => {
                        let mut diagnostics = diagnostics;
                        diagnostics.push(e.clone());
                        OakDiagnostics { result: Err(e), diagnostics }
                    }
                }
            }
            Err(e) => OakDiagnostics { result: Err(e), diagnostics },
        }
    }
}

impl<'config> RustBuilder<'config> {
    /// Builds the root of the AST (the entire source file).
    pub(crate) fn build_root<'a>(&self, green_tree: &'a GreenNode<'a, RustLanguage>, source: &SourceText) -> Result<RustRoot, OakError> {
        let red_root = RedNode::new(green_tree, 0);
        let mut items = Vec::new();

        for child in red_root.children() {
            match child {
                RedTree::Node(n) => match n.green.kind {
                    RustElementType::Function => {
                        let func = self.build_function(n, source)?;
                        items.push(Item::Function(func));
                    }
                    RustElementType::StructItem => {
                        let struct_def = self.build_struct(n, source)?;
                        items.push(Item::Struct(struct_def));
                    }
                    RustElementType::EnumItem => {
                        let enum_def = self.build_enum(n, source)?;
                        items.push(Item::Enum(enum_def));
                    }
                    RustElementType::Trait => {
                        let trait_def = self.build_trait(n, source)?;
                        items.push(Item::Trait(trait_def));
                    }
                    RustElementType::Impl => {
                        let impl_block = self.build_impl(n, source)?;
                        items.push(Item::Impl(impl_block));
                    }
                    RustElementType::ModuleItem => {
                        let module = self.build_module(n, source)?;
                        items.push(Item::Module(module));
                    }
                    RustElementType::UseItem => {
                        let use_decl = self.build_use(n, source)?;
                        items.push(Item::Use(use_decl));
                    }
                    RustElementType::Const => {
                        let const_def = self.build_const(n, source)?;
                        items.push(Item::Const(const_def));
                    }
                    RustElementType::Static => {
                        let static_def = self.build_static(n, source)?;
                        items.push(Item::Static(static_def));
                    }
                    RustElementType::TypeAlias => {
                        let type_alias = self.build_type_alias(n, source)?;
                        items.push(Item::TypeAlias(type_alias));
                    }
                    _ => {
                        // Ignore other node types
                    }
                },
                RedTree::Leaf(_) => {
                    // Ignore top-level tokens (whitespace, comments, etc.)
                }
            }
        }
        let root = RustRoot { items };
        Ok(root)
    }

    /// Builds a function definition.
    pub(crate) fn build_function(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Arc<Function>, OakError> {
        let span = node.span();
        let mut name = Identifier { name: String::new(), span: Range { start: 0, end: 0 } };
        let mut params = Vec::new();
        let mut return_type = None;
        let mut body = None;
        let generics = self.build_generics_and_where(node.clone(), source)?;
        let mut is_async = false;
        let mut is_unsafe = false;
        let mut is_extern = false;

        for child in node.children() {
            match child {
                RedTree::Leaf(t) => match t.kind {
                    RustTokenType::Async => is_async = true,
                    RustTokenType::Unsafe => is_unsafe = true,
                    RustTokenType::Extern => is_extern = true,
                    RustTokenType::Identifier => {
                        name.name = text(source, t.span.clone().into());
                        name.span = t.span.clone().into();
                    }
                    _ => {}
                },
                RedTree::Node(n) => match n.green.kind {
                    RustElementType::ParameterList => {
                        params = self.build_param_list(n, source)?;
                    }
                    RustElementType::ReturnType => {
                        return_type = Some(self.build_type(n, source)?);
                    }
                    RustElementType::BlockExpression => {
                        body = Some(self.build_block(n, source)?);
                    }
                    _ => {}
                },
            }
        }

        let function = Arc::new(Function {
            name,
            params,
            return_type,
            body: body.unwrap_or_else(|| Block { statements: Vec::new(), block_start: 0, block_end: 0, nested: 0, span: Range { start: 0, end: 0 } }),
            is_async,
            is_unsafe,
            generics,
            is_extern,
            span: span.into(),
        });

        Ok(function)
    }

    /// Builds a parameter list.
    fn build_param_list(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Vec<Param>, OakError> {
        let mut params = Vec::new();
        for child in node.children() {
            if let RedTree::Node(n) = child {
                if n.green.kind == RustElementType::Parameter {
                    params.push(self.build_param(n, source)?);
                }
            }
        }
        Ok(params)
    }

    /// Builds a parameter.
    fn build_param(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Param, OakError> {
        let span = node.span();
        let mut name = Identifier { name: String::new(), span: Range { start: 0, end: 0 } };
        let mut ty = Type::Path("_".to_string());

        for child in node.children() {
            match child {
                RedTree::Leaf(t) => {
                    if let RustTokenType::Identifier = t.kind {
                        name.name = text(source, t.span.clone().into());
                        name.span = t.span.clone().into();
                    }
                }
                RedTree::Node(n) => match n.green.kind {
                    RustElementType::Type => {
                        ty = self.build_type(n, source)?;
                    }
                    _ => {}
                },
            }
        }

        Ok(Param { name, ty, is_mut: false, span: span.into() })
    }

    /// Builds a code block.
    fn build_block(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Block, OakError> {
        let span = node.span();
        let mut statements = Vec::new();

        for child in node.children() {
            match child {
                RedTree::Node(n) => match n.green.kind {
                    RustElementType::LetStatement => {
                        statements.push(self.build_let_statement(n, source)?);
                    }
                    RustElementType::ExpressionStatement => {
                        statements.push(self.build_expr_statement(n, source)?);
                    }
                    RustElementType::ItemStatement => {
                        let item = self.build_item_statement(n, source)?;
                        statements.push(Statement::Item(item));
                    }
                    _ => {
                        // Could be a block expression, treat it as an expression statement
                        let span = n.span();
                        if let Ok(block_expr) = self.build_expr(n, source) {
                            statements.push(Statement::ExprStmt { expr: block_expr, semi: false, span: span.into() });
                        }
                    }
                },
                RedTree::Leaf(_) => {
                    // Ignore separators and whitespace
                }
            }
        }

        Ok(Block { statements, block_start: span.start, block_end: span.end, nested: 0, span: span.into() })
    }

    /// Builds a let statement.
    fn build_let_statement(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Statement, OakError> {
        let span = node.span();
        let mut name = Identifier { name: String::new(), span: Range { start: 0, end: 0 } };
        let mut ty = None;
        let mut init = None;
        let mut mutable = false;

        for child in node.children() {
            match child {
                RedTree::Node(n) => match n.green.kind {
                    RustElementType::Pattern => {
                        let pattern = self.build_pattern(n, source)?;
                        // Extract Identifier from Pattern
                        match pattern {
                            Pattern::Ident(ident) => name = ident,
                            _ => {
                                return Err(OakError::syntax_error("Expected identifier in let statement".to_string(), span.start, None));
                            }
                        }
                    }
                    RustElementType::Type => {
                        ty = Some(self.build_type(n, source)?);
                    }
                    RustElementType::Expression => {
                        init = Some(self.build_expr(n, source)?);
                    }
                    _ => {}
                },
                RedTree::Leaf(t) => {
                    // Check for mut keyword
                    if t.kind == RustTokenType::Mut {
                        mutable = true;
                    }
                }
            }
        }

        Ok(Statement::Let { name, ty, expr: init, mutable, span: span.into() })
    }

    /// Builds an expression statement.
    fn build_expr_statement(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Statement, OakError> {
        let span = node.span();
        let mut expr = Expr::Bool { value: false, span: span.clone().into() };
        let mut has_semicolon = false;

        for child in node.children() {
            match child {
                RedTree::Node(n) => {
                    if let Ok(expression) = self.build_expr(n, source) {
                        expr = expression;
                    }
                }
                RedTree::Leaf(t) => {
                    if t.kind == RustTokenType::Semicolon {
                        has_semicolon = true;
                    }
                }
            }
        }

        Ok(Statement::ExprStmt { expr, semi: has_semicolon, span: span.into() })
    }

    /// Builds an expression.
    pub(crate) fn build_expr(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Expr, OakError> {
        let span = node.span();

        match node.green.kind {
            RustElementType::IdentifierExpression => {
                for child in node.children() {
                    if let RedTree::Leaf(t) = child {
                        if t.kind == RustTokenType::Identifier {
                            let ident = Identifier { name: text(source, t.span.clone().into()), span: t.span.clone().into() };
                            return Ok(Expr::Ident(ident));
                        }
                    }
                }
                Err(OakError::syntax_error("Invalid identifier expression".to_string(), span.start, None))
            }
            RustElementType::LiteralExpression => {
                for child in node.children() {
                    if let RedTree::Leaf(t) = child {
                        // Infer literal type directly from token text
                        let text = source.get_text_in(t.span.clone().into());
                        if text == "true" {
                            return Ok(Expr::Bool { value: true, span: span.into() });
                        }
                        else if text == "false" {
                            return Ok(Expr::Bool { value: false, span: span.into() });
                        }
                        else {
                            // Other literal types (numbers, strings, characters, etc.)
                            return Ok(Expr::Literal { value: text.to_string(), span: span.into() });
                        }
                    }
                }
                Err(OakError::syntax_error("Invalid literal expression".to_string(), span.start, None))
            }
            RustElementType::BinaryExpression => {
                let mut left = None;
                let mut op = None;
                let mut right = None;

                for child in node.children() {
                    match child {
                        RedTree::Node(n) => {
                            if left.is_none() {
                                left = Some(Box::new(self.build_expr(n, source)?));
                            }
                            else if right.is_none() {
                                right = Some(Box::new(self.build_expr(n, source)?));
                            }
                        }
                        RedTree::Leaf(t) => {
                            if op.is_none() {
                                // Infer operator type from token text
                                let text = source.get_text_in(t.span.clone().into());
                                op = match text.as_ref() {
                                    "+" => Some(RustTokenType::Plus),
                                    "-" => Some(RustTokenType::Minus),
                                    "*" => Some(RustTokenType::Star),
                                    "/" => Some(RustTokenType::Slash),
                                    "%" => Some(RustTokenType::Percent),
                                    "==" => Some(RustTokenType::EqEq),
                                    "!=" => Some(RustTokenType::Ne),
                                    "<" => Some(RustTokenType::Lt),
                                    "<=" => Some(RustTokenType::Le),
                                    ">" => Some(RustTokenType::Gt),
                                    ">=" => Some(RustTokenType::Ge),
                                    "&&" => Some(RustTokenType::AndAnd),
                                    "||" => Some(RustTokenType::OrOr),
                                    "&" => Some(RustTokenType::Ampersand),
                                    _ => None,
                                };
                            }
                        }
                    }
                }

                if let (Some(left), Some(op), Some(right)) = (left, op, right) { Ok(Expr::Binary { left, op, right, span: span.into() }) } else { Err(OakError::syntax_error("Invalid binary expression".to_string(), span.start, None)) }
            }
            RustElementType::UnaryExpression => {
                let mut op = None;
                let mut operand = None;

                for child in node.children() {
                    match child {
                        RedTree::Node(n) => {
                            operand = Some(Box::new(self.build_expr(n, source)?));
                        }
                        RedTree::Leaf(t) => {
                            if op.is_none() {
                                // Try to infer from the token text if available
                                let token_text = source.get_text_in(t.span.clone().into());
                                match token_text.as_ref() {
                                    "!" => op = Some(RustTokenType::Bang),
                                    "-" => op = Some(RustTokenType::Minus),
                                    "+" => op = Some(RustTokenType::Plus),
                                    _ => {}
                                }
                            }
                        }
                    }
                }

                if let (Some(op), Some(operand)) = (op, operand) { Ok(Expr::Unary { op, expr: operand, span: span.into() }) } else { Err(OakError::syntax_error("Invalid unary expression".to_string(), span.start, None)) }
            }
            RustElementType::CallExpression => {
                let mut func = None;
                let mut args = Vec::new();

                for child in node.children() {
                    match child {
                        RedTree::Node(n) => {
                            if func.is_none() {
                                func = Some(Box::new(self.build_expr(n, source)?));
                            }
                            else if n.green.kind == RustElementType::ArgumentList {
                                args = self.build_argument_list(n, source)?;
                            }
                        }
                        _ => {}
                    }
                }

                if let Some(func) = func { Ok(Expr::Call { callee: func, args, span: span.into() }) } else { Err(OakError::syntax_error("Invalid call expression".to_string(), span.start, None)) }
            }
            RustElementType::FieldExpression => {
                let mut base = None;
                let mut field = Identifier { name: String::new(), span: Range { start: 0, end: 0 } };

                for child in node.children() {
                    match child {
                        RedTree::Node(n) => {
                            base = Some(Box::new(self.build_expr(n, source)?));
                        }
                        RedTree::Leaf(t) => {
                            if t.kind == RustTokenType::Identifier {
                                field.name = text(source, t.span.clone().into());
                                field.span = t.span.clone().into();
                            }
                        }
                    }
                }

                if let Some(receiver) = base { Ok(Expr::Field { receiver, field, span: span.into() }) } else { Err(OakError::syntax_error("Invalid field expression".to_string(), span.start, None)) }
            }
            RustElementType::IndexExpression => {
                let mut base = None;
                let mut index = None;

                for child in node.children() {
                    if let RedTree::Node(n) = child {
                        if base.is_none() {
                            base = Some(Box::new(self.build_expr(n, source)?));
                        }
                        else if index.is_none() {
                            index = Some(Box::new(self.build_expr(n, source)?));
                        }
                    }
                }

                if let (Some(receiver), Some(index)) = (base, index) { Ok(Expr::Index { receiver, index, span: span.into() }) } else { Err(OakError::syntax_error("Invalid index expression".to_string(), span.start, None)) }
            }
            RustElementType::ParenthesizedExpression => {
                for child in node.children() {
                    if let RedTree::Node(n) = child {
                        let inner_expr = self.build_expr(n, source)?;
                        return Ok(Expr::Paren { expr: Box::new(inner_expr), span: span.into() });
                    }
                }
                Err(OakError::syntax_error("Invalid parenthesized expression".to_string(), span.start, None))
            }
            RustElementType::BlockExpression => {
                let block = self.build_block(node, source)?;
                Ok(Expr::Block(block))
            }
            _ => Err(OakError::syntax_error(format!("Unsupported expression type: {:?}", node.green.kind), span.start, None)),
        }
    }

    /// Builds a struct definition.
    pub(crate) fn build_struct(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Arc<Struct>, OakError> {
        let span = node.span();
        let mut name = Identifier { name: String::new(), span: Range { start: 0, end: 0 } };
        let mut fields = Vec::new();
        let generics = self.build_generics_and_where(node.clone(), source)?;

        for child in node.children() {
            match child {
                RedTree::Leaf(t) if t.kind == RustTokenType::Identifier => {
                    name.name = text(source, t.span.clone().into());
                    name.span = t.span.clone().into();
                }
                RedTree::Node(n) if n.green.kind == RustElementType::StructBody => {
                    fields = self.build_fields(n, source)?;
                }
                _ => {}
            }
        }

        let struct_def = Arc::new(Struct { name, generics, fields, span: span.into() });
        Ok(struct_def)
    }

    /// Builds a list of fields (for structs or enums).
    fn build_fields(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Vec<Field>, OakError> {
        let mut fields = Vec::new();
        for child in node.children() {
            if let RedTree::Node(n) = child {
                if n.green.kind == RustElementType::Field {
                    fields.push(self.build_field(n, source)?);
                }
            }
        }
        Ok(fields)
    }

    /// Builds a single field.
    fn build_field(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Field, OakError> {
        let span = node.span();
        let mut name = Identifier { name: String::new(), span: Range { start: 0, end: 0 } };
        let mut ty = Type::Path("_".to_string());

        for child in node.children() {
            match child {
                RedTree::Leaf(t) if t.kind == RustTokenType::Identifier => {
                    name.name = text(source, t.span.clone().into());
                    name.span = t.span.clone().into();
                }
                RedTree::Node(n) if n.green.kind == RustElementType::Type => {
                    ty = self.build_type(n, source)?;
                }
                _ => {}
            }
        }

        Ok(Field { name, ty, span: span.into() })
    }

    /// Builds an enum definition.
    pub(crate) fn build_enum(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Arc<Enum>, OakError> {
        let span = node.span();
        let mut name = Identifier { name: String::new(), span: Range { start: 0, end: 0 } };
        let mut variants = Vec::new();
        let generics = self.build_generics_and_where(node.clone(), source)?;

        for child in node.children() {
            match child {
                RedTree::Leaf(t) if t.kind == RustTokenType::Identifier => {
                    name.name = text(source, t.span.clone().into());
                    name.span = t.span.clone().into();
                }
                RedTree::Node(n) if n.green.kind == RustElementType::EnumBody => {
                    variants = self.build_variants(n, source)?;
                }
                _ => {}
            }
        }

        let enum_def = Arc::new(Enum { name, generics, variants, span: span.into() });
        Ok(enum_def)
    }

    /// Builds a list of enum variants.
    fn build_variants(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Vec<Variant>, OakError> {
        let mut variants = Vec::new();
        for child in node.children() {
            if let RedTree::Node(n) = child {
                if n.green.kind == RustElementType::Variant {
                    variants.push(self.build_variant(n, source)?);
                }
            }
        }
        Ok(variants)
    }

    /// Builds a single enum variant.
    fn build_variant(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Variant, OakError> {
        let span = node.span();
        let mut name = Identifier { name: String::new(), span: Range { start: 0, end: 0 } };
        let mut fields = None;

        for child in node.children() {
            match child {
                RedTree::Leaf(t) if t.kind == RustTokenType::Identifier => {
                    name.name = text(source, t.span.clone().into());
                    name.span = t.span.clone().into();
                }
                RedTree::Node(n) if n.green.kind == RustElementType::TupleBody || n.green.kind == RustElementType::StructBody => {
                    fields = Some(self.build_fields(n, source)?);
                }
                _ => {}
            }
        }

        Ok(Variant { name, fields, span: span.into() })
    }

    /// Builds a trait definition.
    pub(crate) fn build_trait(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Arc<Trait>, OakError> {
        let span = node.span();
        let mut name = Identifier { name: String::new(), span: Range { start: 0, end: 0 } };
        let mut items = Vec::new();
        let generics = self.build_generics_and_where(node.clone(), source)?;

        for child in node.children() {
            match child {
                RedTree::Leaf(t) if t.kind == RustTokenType::Identifier => {
                    name.name = text(source, t.span.clone().into());
                    name.span = t.span.clone().into();
                }
                RedTree::Node(n) if n.green.kind == RustElementType::TraitBody => {
                    items = self.build_trait_items(n, source)?;
                }
                _ => {}
            }
        }

        let trait_def = Arc::new(Trait { name, generics, items, span: span.into() });
        Ok(trait_def)
    }

    /// Builds items within a trait.
    fn build_trait_items(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Vec<TraitItem>, OakError> {
        let mut items = Vec::new();
        for child in node.children() {
            if let RedTree::Node(n) = child {
                match n.green.kind {
                    RustElementType::Function => {
                        let func = self.build_function(n, source)?;
                        items.push(TraitItem::Method((*func).clone()));
                    }
                    RustElementType::TypeAlias => {
                        let alias = self.build_type_alias(n, source)?;
                        items.push(TraitItem::Type((*alias).clone()));
                    }
                    _ => {}
                }
            }
        }
        Ok(items)
    }

    /// Builds an impl block.
    pub(crate) fn build_impl(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Arc<Impl>, OakError> {
        let span = node.span();
        let mut ty = Type::Path("_".to_string());
        let mut trait_ = None;
        let mut items = Vec::new();
        let generics = self.build_generics_and_where(node.clone(), source)?;

        for child in node.children() {
            if let RedTree::Node(n) = child {
                match n.green.kind {
                    RustElementType::Type => {
                        // In Rust, `impl Trait for Type` or `impl Type`.
                        // The parser distinguishes these.
                        if trait_.is_none() {
                            ty = self.build_type(n, source)?;
                        }
                        else {
                            // This would be the type after 'for'
                            ty = self.build_type(n, source)?;
                        }
                    }
                    RustElementType::TraitRef => {
                        trait_ = Some(self.build_type(n, source)?);
                    }
                    RustElementType::ImplBody => {
                        items = self.build_impl_items(n, source)?;
                    }
                    _ => {}
                }
            }
        }

        let impl_block = Arc::new(Impl { generics, ty, trait_, items, span: span.into() });
        Ok(impl_block)
    }

    /// Builds items within an impl block.
    fn build_impl_items(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Vec<ImplItem>, OakError> {
        let mut items = Vec::new();
        for child in node.children() {
            if let RedTree::Node(n) = child {
                match n.green.kind {
                    RustElementType::Function => {
                        let func = self.build_function(n, source)?;
                        items.push(ImplItem::Method((*func).clone()));
                    }
                    RustElementType::TypeAlias => {
                        let alias = self.build_type_alias(n, source)?;
                        items.push(ImplItem::Type((*alias).clone()));
                    }
                    RustElementType::Const => {
                        let constant = self.build_const(n, source)?;
                        items.push(ImplItem::Const((*constant).clone()));
                    }
                    _ => {}
                }
            }
        }
        Ok(items)
    }

    /// Builds a module definition.
    pub(crate) fn build_module(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Arc<Module>, OakError> {
        let span = node.span();
        let mut name = Identifier { name: String::new(), span: Range { start: 0, end: 0 } };
        let mut items = Vec::new();

        for child in node.children() {
            match child {
                RedTree::Leaf(t) if t.kind == RustTokenType::Identifier => {
                    name.name = text(source, t.span.clone().into());
                    name.span = t.span.clone().into();
                }
                RedTree::Node(n) if n.green.kind == RustElementType::Block => {
                    // Reuse build_root logic for module items
                    let root = self.build_root(n.green, source)?;
                    items = root.items;
                }
                _ => {}
            }
        }

        let module = Arc::new(Module { name, items, span: span.into() });
        Ok(module)
    }

    /// Builds a use statement.
    pub(crate) fn build_use(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Arc<UseItem>, OakError> {
        let span = node.span();
        let mut path = String::new();

        for child in node.children() {
            if let RedTree::Leaf(t) = child {
                if t.kind == RustTokenType::Identifier {
                    path = text(source, t.span().into());
                }
            }
        }

        let use_item = Arc::new(UseItem { path, span: span.into() });
        Ok(use_item)
    }

    /// Builds a constant definition.
    pub(crate) fn build_const(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Arc<Const>, OakError> {
        let span = node.span();
        let mut name = Identifier { name: String::new(), span: Range { start: 0, end: 0 } };
        let mut ty = Type::Path("_".to_string());
        let mut expr = Expr::Bool { value: false, span: span.clone().into() };

        for child in node.children() {
            match child {
                RedTree::Leaf(t) if t.kind == RustTokenType::Identifier => {
                    name.name = text(source, t.span.clone().into());
                    name.span = t.span.clone().into();
                }
                RedTree::Node(n) => match n.green.kind {
                    RustElementType::Type => ty = self.build_type(n, source)?,
                    RustElementType::Expression => expr = self.build_expr(n, source)?,
                    _ => {}
                },
                _ => {}
            }
        }

        let constant = Arc::new(Const { name, ty, expr, span: span.into() });
        Ok(constant)
    }

    /// Builds a static definition.
    pub(crate) fn build_static(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Arc<Static>, OakError> {
        let span = node.span();
        let mut name = Identifier { name: String::new(), span: Range { start: 0, end: 0 } };
        let mut ty = Type::Path("_".to_string());
        let mut expr = Expr::Bool { value: false, span: span.clone().into() };
        let mut mutable = false;

        for child in node.children() {
            match child {
                RedTree::Leaf(t) => match t.kind {
                    RustTokenType::Identifier => {
                        name.name = text(source, t.span.clone().into());
                        name.span = t.span.clone().into();
                    }
                    RustTokenType::Mut => mutable = true,
                    _ => {}
                },
                RedTree::Node(n) => match n.green.kind {
                    RustElementType::Type => ty = self.build_type(n, source)?,
                    RustElementType::Expression => expr = self.build_expr(n, source)?,
                    _ => {}
                },
            }
        }

        let static_def = Arc::new(Static { name, ty, expr, mutable, span: span.into() });
        Ok(static_def)
    }

    /// Builds a type alias.
    pub(crate) fn build_type_alias(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Arc<TypeAlias>, OakError> {
        let span = node.span();
        let mut name = Identifier { name: String::new(), span: Range { start: 0, end: 0 } };
        let mut ty = Type::Path("_".to_string());
        let generics = self.build_generics_and_where(node.clone(), source)?;

        for child in node.children() {
            match child {
                RedTree::Leaf(t) if t.kind == RustTokenType::Identifier => {
                    name.name = text(source, t.span.clone().into());
                    name.span = t.span.clone().into();
                }
                RedTree::Node(n) if n.green.kind == RustElementType::Type => {
                    ty = self.build_type(n, source)?;
                }
                _ => {}
            }
        }

        let type_alias = Arc::new(TypeAlias { name, generics, ty, span: span.into() });
        Ok(type_alias)
    }

    fn build_item_statement(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Item, OakError> {
        for child in node.children() {
            if let RedTree::Node(n) = child {
                match n.green.kind {
                    RustElementType::Function => return Ok(Item::Function(self.build_function(n, source)?)),
                    RustElementType::StructItem => return Ok(Item::Struct(self.build_struct(n, source)?)),
                    RustElementType::EnumItem => return Ok(Item::Enum(self.build_enum(n, source)?)),
                    RustElementType::Trait => return Ok(Item::Trait(self.build_trait(n, source)?)),
                    RustElementType::Impl => return Ok(Item::Impl(self.build_impl(n, source)?)),
                    RustElementType::ModuleItem => return Ok(Item::Module(self.build_module(n, source)?)),
                    RustElementType::UseItem => return Ok(Item::Use(self.build_use(n, source)?)),
                    RustElementType::Const => return Ok(Item::Const(self.build_const(n, source)?)),
                    RustElementType::Static => return Ok(Item::Static(self.build_static(n, source)?)),
                    RustElementType::TypeAlias => return Ok(Item::TypeAlias(self.build_type_alias(n, source)?)),
                    _ => {}
                }
            }
        }
        Err(OakError::syntax_error("Invalid item statement".to_string(), node.offset, None))
    }

    fn build_type(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Type, OakError> {
        let span = node.span();
        match node.green.kind {
            _ => Ok(Type::Path(text(source, span.into()))),
        }
    }

    fn build_pattern(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Pattern, OakError> {
        for child in node.children() {
            match child {
                RedTree::Leaf(t) => match t.kind {
                    RustTokenType::Identifier => {
                        return Ok(Pattern::Ident(Identifier { name: text(source, t.span.clone().into()), span: t.span.clone().into() }));
                    }
                    RustTokenType::Underscore => {
                        return Ok(Pattern::Wildcard);
                    }
                    _ => {}
                },
                RedTree::Node(n) => {
                    // Recurse into nested patterns if necessary
                    if let Ok(pattern) = self.build_pattern(n, source) {
                        if !matches!(pattern, Pattern::Wildcard) {
                            return Ok(pattern);
                        }
                    }
                }
            }
        }
        Ok(Pattern::Wildcard)
    }

    fn build_argument_list(&self, node: RedNode<RustLanguage>, source: &SourceText) -> Result<Vec<Expr>, OakError> {
        let mut args = Vec::new();
        for child in node.children() {
            if let RedTree::Node(n) = child {
                args.push(self.build_expr(n, source)?);
            }
        }
        Ok(args)
    }
}

/// Helper function to extract text from source code.
#[inline]
pub(crate) fn text(source: &SourceText, span: Range<usize>) -> String {
    source.get_text_in(span.into()).to_string()
}