rumoca 0.7.28

Modelica compiler written in RUST
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
//! This module defines the `Visitor` and `MutVisitor` traits for implementing
//! the Visitor design pattern in the context of an intermediate representation (IR)
//! for an abstract syntax tree (AST).
//!
//! ## Overview
//!
//! Two visitor traits are provided:
//! - `Visitor` - For immutable traversal (analysis, code generation, LSP features)
//! - `MutVisitor` - For mutable traversal (transformations, optimizations)
//!
//! Each trait provides methods for entering and exiting various types of AST nodes.
//! These methods can be overridden to implement custom behavior when traversing the AST.
//!
//! ## Key Components
//!
//! - **`Visitor` Trait**: Immutable visitor for read-only traversal. Used for analysis,
//!   code generation, and LSP features like semantic tokens, references, etc.
//!
//! - **`MutVisitor` Trait**: Mutable visitor with `enter_*` and `exit_*` methods for each
//!   AST node type. Used for transformations that modify the AST.
use crate::ir;

// =============================================================================
// Immutable Visitor (for analysis, LSP features)
// =============================================================================

/// Immutable visitor trait for AST analysis.
///
/// Implement this trait for read-only traversal such as:
/// - Semantic token collection
/// - Reference finding
/// - Symbol collection
/// - Code analysis
pub trait Visitor {
    fn enter_stored_definition(&mut self, _node: &ir::ast::StoredDefinition) {}
    fn exit_stored_definition(&mut self, _node: &ir::ast::StoredDefinition) {}

    fn enter_class_definition(&mut self, _node: &ir::ast::ClassDefinition) {}
    fn exit_class_definition(&mut self, _node: &ir::ast::ClassDefinition) {}

    fn enter_equation(&mut self, _node: &ir::ast::Equation) {}
    fn exit_equation(&mut self, _node: &ir::ast::Equation) {}

    fn enter_statement(&mut self, _node: &ir::ast::Statement) {}
    fn exit_statement(&mut self, _node: &ir::ast::Statement) {}

    fn enter_expression(&mut self, _node: &ir::ast::Expression) {}
    fn exit_expression(&mut self, _node: &ir::ast::Expression) {}

    fn enter_component(&mut self, _node: &ir::ast::Component) {}
    fn exit_component(&mut self, _node: &ir::ast::Component) {}

    fn enter_component_reference(&mut self, _node: &ir::ast::ComponentReference) {}
    fn exit_component_reference(&mut self, _node: &ir::ast::ComponentReference) {}

    fn enter_for_index(&mut self, _node: &ir::ast::ForIndex) {}
    fn exit_for_index(&mut self, _node: &ir::ast::ForIndex) {}
}

/// Trait for AST nodes that can accept an immutable visitor.
pub trait Visitable {
    fn accept<V: Visitor>(&self, visitor: &mut V);
}

// =============================================================================
// Mutable Visitor (for transformations)
// =============================================================================

/// Mutable visitor trait for AST transformations.
///
/// Implement this trait to modify the AST during traversal.
pub trait MutVisitor {
    fn enter_stored_definition(&mut self, _node: &mut ir::ast::StoredDefinition) {}
    fn exit_stored_definition(&mut self, _node: &mut ir::ast::StoredDefinition) {}

    fn enter_class_definition(&mut self, _node: &mut ir::ast::ClassDefinition) {}
    fn exit_class_definition(&mut self, _node: &mut ir::ast::ClassDefinition) {}

    fn enter_equation(&mut self, _node: &mut ir::ast::Equation) {}
    fn exit_equation(&mut self, _node: &mut ir::ast::Equation) {}

    fn enter_statement(&mut self, _node: &mut ir::ast::Statement) {}
    fn exit_statement(&mut self, _node: &mut ir::ast::Statement) {}

    fn enter_expression(&mut self, _node: &mut ir::ast::Expression) {}
    fn exit_expression(&mut self, _node: &mut ir::ast::Expression) {}

    fn enter_component(&mut self, _node: &mut ir::ast::Component) {}
    fn exit_component(&mut self, _node: &mut ir::ast::Component) {}

    fn enter_component_reference(&mut self, _node: &mut ir::ast::ComponentReference) {}
    fn exit_component_reference(&mut self, _node: &mut ir::ast::ComponentReference) {}

    fn enter_for_index(&mut self, _node: &mut ir::ast::ForIndex) {}
    fn exit_for_index(&mut self, _node: &mut ir::ast::ForIndex) {}
}

/// Trait for AST nodes that can accept a mutable visitor.
pub trait MutVisitable {
    fn accept_mut<V: MutVisitor>(&mut self, visitor: &mut V);
}

// =============================================================================
// Immutable Visitable Implementations
// =============================================================================

impl Visitable for ir::ast::StoredDefinition {
    fn accept<V: Visitor>(&self, visitor: &mut V) {
        visitor.enter_stored_definition(self);
        for (_name, class) in &self.class_list {
            class.accept(visitor);
        }
        visitor.exit_stored_definition(self);
    }
}

impl Visitable for ir::ast::ClassDefinition {
    fn accept<V: Visitor>(&self, visitor: &mut V) {
        visitor.enter_class_definition(self);

        // Visit components
        for comp in self.components.values() {
            comp.accept(visitor);
        }

        // Visit equations
        for eq in &self.equations {
            eq.accept(visitor);
        }
        for eq in &self.initial_equations {
            eq.accept(visitor);
        }

        // Visit algorithms (statements)
        for algo in &self.algorithms {
            for stmt in algo {
                stmt.accept(visitor);
            }
        }
        for algo in &self.initial_algorithms {
            for stmt in algo {
                stmt.accept(visitor);
            }
        }

        // Visit nested classes
        for nested in self.classes.values() {
            nested.accept(visitor);
        }

        visitor.exit_class_definition(self);
    }
}

impl Visitable for ir::ast::Equation {
    fn accept<V: Visitor>(&self, visitor: &mut V) {
        visitor.enter_equation(self);
        match self {
            ir::ast::Equation::Simple { lhs, rhs } => {
                lhs.accept(visitor);
                rhs.accept(visitor);
            }
            ir::ast::Equation::FunctionCall { comp, args } => {
                comp.accept(visitor);
                for arg in args {
                    arg.accept(visitor);
                }
            }
            ir::ast::Equation::For { indices, equations } => {
                for index in indices {
                    visitor.enter_for_index(index);
                    index.range.accept(visitor);
                    visitor.exit_for_index(index);
                }
                for eq in equations {
                    eq.accept(visitor);
                }
            }
            ir::ast::Equation::Connect { lhs, rhs } => {
                lhs.accept(visitor);
                rhs.accept(visitor);
            }
            ir::ast::Equation::When(blocks) => {
                for block in blocks {
                    block.cond.accept(visitor);
                    for eq in &block.eqs {
                        eq.accept(visitor);
                    }
                }
            }
            ir::ast::Equation::If {
                cond_blocks,
                else_block,
            } => {
                for block in cond_blocks {
                    block.cond.accept(visitor);
                    for eq in &block.eqs {
                        eq.accept(visitor);
                    }
                }
                if let Some(else_block) = else_block {
                    for eq in else_block {
                        eq.accept(visitor);
                    }
                }
            }
            ir::ast::Equation::Empty => {}
        }
        visitor.exit_equation(self);
    }
}

impl Visitable for ir::ast::Statement {
    fn accept<V: Visitor>(&self, visitor: &mut V) {
        visitor.enter_statement(self);
        match self {
            ir::ast::Statement::Empty => {}
            ir::ast::Statement::Assignment { comp, value } => {
                comp.accept(visitor);
                value.accept(visitor);
            }
            ir::ast::Statement::Return { .. } | ir::ast::Statement::Break { .. } => {}
            ir::ast::Statement::For { indices, equations } => {
                for index in indices {
                    visitor.enter_for_index(index);
                    index.range.accept(visitor);
                    visitor.exit_for_index(index);
                }
                for stmt in equations {
                    stmt.accept(visitor);
                }
            }
            ir::ast::Statement::While(block) => {
                block.cond.accept(visitor);
                for stmt in &block.stmts {
                    stmt.accept(visitor);
                }
            }
            ir::ast::Statement::If {
                cond_blocks,
                else_block,
            } => {
                for block in cond_blocks {
                    block.cond.accept(visitor);
                    for stmt in &block.stmts {
                        stmt.accept(visitor);
                    }
                }
                if let Some(else_stmts) = else_block {
                    for stmt in else_stmts {
                        stmt.accept(visitor);
                    }
                }
            }
            ir::ast::Statement::When(blocks) => {
                for block in blocks {
                    block.cond.accept(visitor);
                    for stmt in &block.stmts {
                        stmt.accept(visitor);
                    }
                }
            }
            ir::ast::Statement::FunctionCall {
                comp,
                args,
                outputs,
            } => {
                comp.accept(visitor);
                for arg in args {
                    arg.accept(visitor);
                }
                for output in outputs {
                    output.accept(visitor);
                }
            }
        }
        visitor.exit_statement(self);
    }
}

impl Visitable for ir::ast::Expression {
    fn accept<V: Visitor>(&self, visitor: &mut V) {
        visitor.enter_expression(self);
        match self {
            ir::ast::Expression::Unary { rhs, .. } => {
                rhs.accept(visitor);
            }
            ir::ast::Expression::Binary { lhs, rhs, .. } => {
                lhs.accept(visitor);
                rhs.accept(visitor);
            }
            ir::ast::Expression::ComponentReference(cref) => {
                cref.accept(visitor);
            }
            ir::ast::Expression::FunctionCall { comp, args } => {
                comp.accept(visitor);
                for arg in args {
                    arg.accept(visitor);
                }
            }
            ir::ast::Expression::Array { elements, .. } => {
                for element in elements {
                    element.accept(visitor);
                }
            }
            ir::ast::Expression::Range { start, step, end } => {
                start.accept(visitor);
                if let Some(step) = step {
                    step.accept(visitor);
                }
                end.accept(visitor);
            }
            ir::ast::Expression::Terminal { .. } => {}
            ir::ast::Expression::Empty => {}
            ir::ast::Expression::Tuple { elements } => {
                for element in elements {
                    element.accept(visitor);
                }
            }
            ir::ast::Expression::If {
                branches,
                else_branch,
            } => {
                for (cond, then_expr) in branches {
                    cond.accept(visitor);
                    then_expr.accept(visitor);
                }
                else_branch.accept(visitor);
            }
            ir::ast::Expression::Parenthesized { inner } => {
                inner.accept(visitor);
            }
            ir::ast::Expression::ArrayComprehension { expr, indices } => {
                expr.accept(visitor);
                for idx in indices {
                    visitor.enter_for_index(idx);
                    idx.range.accept(visitor);
                    visitor.exit_for_index(idx);
                }
            }
        }
        visitor.exit_expression(self);
    }
}

impl Visitable for ir::ast::Component {
    fn accept<V: Visitor>(&self, visitor: &mut V) {
        visitor.enter_component(self);
        self.start.accept(visitor);
        visitor.exit_component(self);
    }
}

impl Visitable for ir::ast::ComponentReference {
    fn accept<V: Visitor>(&self, visitor: &mut V) {
        visitor.enter_component_reference(self);
        visitor.exit_component_reference(self);
    }
}

// =============================================================================
// Mutable Visitable Implementations
// =============================================================================

impl MutVisitable for ir::ast::StoredDefinition {
    fn accept_mut<V: MutVisitor>(&mut self, visitor: &mut V) {
        visitor.enter_stored_definition(self);
        for (_name, class) in &mut self.class_list {
            class.accept_mut(visitor);
        }
        visitor.exit_stored_definition(self);
    }
}

impl MutVisitable for ir::ast::ClassDefinition {
    fn accept_mut<V: MutVisitor>(&mut self, visitor: &mut V) {
        visitor.enter_class_definition(self);

        // Visit components
        for comp in self.components.values_mut() {
            comp.accept_mut(visitor);
        }

        // Visit equations
        for eq in &mut self.equations {
            eq.accept_mut(visitor);
        }
        for eq in &mut self.initial_equations {
            eq.accept_mut(visitor);
        }

        // Visit algorithms (statements)
        for algo in &mut self.algorithms {
            for stmt in algo {
                stmt.accept_mut(visitor);
            }
        }
        for algo in &mut self.initial_algorithms {
            for stmt in algo {
                stmt.accept_mut(visitor);
            }
        }

        // Visit nested classes
        for nested in self.classes.values_mut() {
            nested.accept_mut(visitor);
        }

        visitor.exit_class_definition(self);
    }
}

impl MutVisitable for ir::ast::Equation {
    fn accept_mut<V: MutVisitor>(&mut self, visitor: &mut V) {
        visitor.enter_equation(self);
        match self {
            ir::ast::Equation::Simple { lhs, rhs } => {
                lhs.accept_mut(visitor);
                rhs.accept_mut(visitor);
            }
            ir::ast::Equation::FunctionCall { comp, args } => {
                comp.accept_mut(visitor);
                for arg in args {
                    arg.accept_mut(visitor);
                }
            }
            ir::ast::Equation::For { indices, equations } => {
                for index in indices {
                    visitor.enter_for_index(index);
                    index.range.accept_mut(visitor);
                    visitor.exit_for_index(index);
                }
                for eq in equations {
                    eq.accept_mut(visitor);
                }
            }
            ir::ast::Equation::Connect { lhs, rhs } => {
                lhs.accept_mut(visitor);
                rhs.accept_mut(visitor);
            }
            ir::ast::Equation::When(blocks) => {
                for block in blocks {
                    block.cond.accept_mut(visitor);
                    for eq in &mut block.eqs {
                        eq.accept_mut(visitor);
                    }
                }
            }
            ir::ast::Equation::If {
                cond_blocks,
                else_block,
            } => {
                for block in cond_blocks {
                    block.cond.accept_mut(visitor);
                    for eq in &mut block.eqs {
                        eq.accept_mut(visitor);
                    }
                }
                if let Some(else_block) = else_block {
                    for eq in else_block {
                        eq.accept_mut(visitor);
                    }
                }
            }
            ir::ast::Equation::Empty => {}
        }
        visitor.exit_equation(self);
    }
}

impl MutVisitable for ir::ast::Statement {
    fn accept_mut<V: MutVisitor>(&mut self, visitor: &mut V) {
        visitor.enter_statement(self);
        match self {
            ir::ast::Statement::Empty => {}
            ir::ast::Statement::Assignment { comp, value } => {
                comp.accept_mut(visitor);
                value.accept_mut(visitor);
            }
            ir::ast::Statement::Return { .. } | ir::ast::Statement::Break { .. } => {}
            ir::ast::Statement::For { indices, equations } => {
                for index in indices {
                    visitor.enter_for_index(index);
                    index.range.accept_mut(visitor);
                    visitor.exit_for_index(index);
                }
                for stmt in equations {
                    stmt.accept_mut(visitor);
                }
            }
            ir::ast::Statement::While(block) => {
                block.cond.accept_mut(visitor);
                for stmt in &mut block.stmts {
                    stmt.accept_mut(visitor);
                }
            }
            ir::ast::Statement::If {
                cond_blocks,
                else_block,
            } => {
                for block in cond_blocks {
                    block.cond.accept_mut(visitor);
                    for stmt in &mut block.stmts {
                        stmt.accept_mut(visitor);
                    }
                }
                if let Some(else_stmts) = else_block {
                    for stmt in else_stmts {
                        stmt.accept_mut(visitor);
                    }
                }
            }
            ir::ast::Statement::When(blocks) => {
                for block in blocks {
                    block.cond.accept_mut(visitor);
                    for stmt in &mut block.stmts {
                        stmt.accept_mut(visitor);
                    }
                }
            }
            ir::ast::Statement::FunctionCall {
                comp,
                args,
                outputs,
            } => {
                comp.accept_mut(visitor);
                for arg in args {
                    arg.accept_mut(visitor);
                }
                for output in outputs {
                    output.accept_mut(visitor);
                }
            }
        }
        visitor.exit_statement(self);
    }
}

impl MutVisitable for ir::ast::Expression {
    fn accept_mut<V: MutVisitor>(&mut self, visitor: &mut V) {
        visitor.enter_expression(self);
        match self {
            ir::ast::Expression::Unary { rhs, .. } => {
                rhs.accept_mut(visitor);
            }
            ir::ast::Expression::Binary { op, lhs, rhs } => {
                // For Assign expressions (named arguments like `actual=expr`),
                // skip the LHS since it's an argument name, not a component reference.
                // The LHS should not be renamed during flattening.
                if !matches!(op, ir::ast::OpBinary::Assign(_)) {
                    lhs.accept_mut(visitor);
                }
                rhs.accept_mut(visitor);
            }
            ir::ast::Expression::ComponentReference(cref) => {
                cref.accept_mut(visitor);
            }
            ir::ast::Expression::FunctionCall { comp, args } => {
                comp.accept_mut(visitor);
                for arg in args {
                    arg.accept_mut(visitor);
                }
            }
            ir::ast::Expression::Array { elements, .. } => {
                for element in elements {
                    element.accept_mut(visitor);
                }
            }
            ir::ast::Expression::Range { start, step, end } => {
                start.accept_mut(visitor);
                if let Some(step) = step {
                    step.accept_mut(visitor);
                }
                end.accept_mut(visitor);
            }
            ir::ast::Expression::Terminal { .. } => {}
            ir::ast::Expression::Empty => {}
            ir::ast::Expression::Tuple { elements } => {
                for element in elements {
                    element.accept_mut(visitor);
                }
            }
            ir::ast::Expression::If {
                branches,
                else_branch,
            } => {
                for (cond, then_expr) in branches {
                    cond.accept_mut(visitor);
                    then_expr.accept_mut(visitor);
                }
                else_branch.accept_mut(visitor);
            }
            ir::ast::Expression::Parenthesized { inner } => {
                inner.accept_mut(visitor);
            }
            ir::ast::Expression::ArrayComprehension { expr, indices } => {
                expr.accept_mut(visitor);
                for idx in indices {
                    visitor.enter_for_index(idx);
                    idx.range.accept_mut(visitor);
                    visitor.exit_for_index(idx);
                }
            }
        }
        visitor.exit_expression(self);
    }
}

impl MutVisitable for ir::ast::Component {
    fn accept_mut<V: MutVisitor>(&mut self, visitor: &mut V) {
        visitor.enter_component(self);
        self.start.accept_mut(visitor);
        visitor.exit_component(self);
    }
}

impl MutVisitable for ir::ast::ComponentReference {
    fn accept_mut<V: MutVisitor>(&mut self, visitor: &mut V) {
        visitor.enter_component_reference(self);
        visitor.exit_component_reference(self);
    }
}

// =============================================================================
// Generic Collector Visitors
// =============================================================================

/// A generic collector that extracts items from ComponentReferences.
///
/// This provides a reusable pattern for collecting data from the AST
/// using a closure-based API.
///
/// # Example
///
/// ```
/// use rumoca::ir::visitor::{Collector, Visitable};
/// use rumoca::ir::ast::ComponentReference;
///
/// // Collect all component reference names
/// let collector: Collector<String, _> = Collector::new(|cref: &ComponentReference| {
///     cref.parts.first().map(|p| p.ident.text.clone())
/// });
/// // Then call: class.accept(&mut collector);
/// // let names: Vec<String> = collector.into_collected();
/// ```
pub struct Collector<T, F>
where
    F: FnMut(&ir::ast::ComponentReference) -> Option<T>,
{
    extractor: F,
    collected: Vec<T>,
}

impl<T, F> Collector<T, F>
where
    F: FnMut(&ir::ast::ComponentReference) -> Option<T>,
{
    /// Create a new collector with the given extractor function.
    pub fn new(extractor: F) -> Self {
        Self {
            extractor,
            collected: Vec::new(),
        }
    }

    /// Get the collected items as a reference.
    pub fn collected(&self) -> &[T] {
        &self.collected
    }

    /// Consume the collector and return the collected items.
    pub fn into_collected(self) -> Vec<T> {
        self.collected
    }
}

impl<T, F> Visitor for Collector<T, F>
where
    F: FnMut(&ir::ast::ComponentReference) -> Option<T>,
{
    fn enter_component_reference(&mut self, node: &ir::ast::ComponentReference) {
        if let Some(item) = (self.extractor)(node) {
            self.collected.push(item);
        }
    }
}

/// A generic collector that extracts items from Expressions.
///
/// Useful for collecting data from function calls, literals, etc.
pub struct ExpressionCollector<T, F>
where
    F: FnMut(&ir::ast::Expression) -> Option<T>,
{
    extractor: F,
    collected: Vec<T>,
}

impl<T, F> ExpressionCollector<T, F>
where
    F: FnMut(&ir::ast::Expression) -> Option<T>,
{
    /// Create a new expression collector with the given extractor function.
    pub fn new(extractor: F) -> Self {
        Self {
            extractor,
            collected: Vec::new(),
        }
    }

    /// Get the collected items as a reference.
    pub fn collected(&self) -> &[T] {
        &self.collected
    }

    /// Consume the collector and return the collected items.
    pub fn into_collected(self) -> Vec<T> {
        self.collected
    }
}

impl<T, F> Visitor for ExpressionCollector<T, F>
where
    F: FnMut(&ir::ast::Expression) -> Option<T>,
{
    fn enter_expression(&mut self, node: &ir::ast::Expression) {
        if let Some(item) = (self.extractor)(node) {
            self.collected.push(item);
        }
    }
}

/// Collect strings from component references in an AST node.
///
/// This is a convenience function for the common case of collecting
/// component reference names.
///
/// # Example
///
/// ```
/// use rumoca::ir::visitor::{collect_component_refs, Visitable};
/// use rumoca::ir::ast::ClassDefinition;
///
/// let class = ClassDefinition::default();
/// let names = collect_component_refs(&class, |cref| {
///     cref.parts.first().map(|p| p.ident.text.clone())
/// });
/// ```
pub fn collect_component_refs<V: Visitable>(
    node: &V,
    mut extractor: impl FnMut(&ir::ast::ComponentReference) -> Option<String>,
) -> std::collections::HashSet<String> {
    let mut collector = Collector::new(|cref| extractor(cref));
    node.accept(&mut collector);
    collector.into_collected().into_iter().collect()
}

/// Collect strings from expressions in an AST node.
///
/// This is a convenience function for collecting data from expressions.
pub fn collect_from_expressions<V: Visitable>(
    node: &V,
    mut extractor: impl FnMut(&ir::ast::Expression) -> Option<String>,
) -> std::collections::HashSet<String> {
    let mut collector = ExpressionCollector::new(|expr| extractor(expr));
    node.accept(&mut collector);
    collector.into_collected().into_iter().collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::ast::*;
    use crate::modelica_grammar::ModelicaGrammar;
    use crate::modelica_parser::parse;

    fn parse_test_code(code: &str) -> StoredDefinition {
        let mut grammar = ModelicaGrammar::new();
        parse(code, "test.mo", &mut grammar).expect("Failed to parse test code");
        grammar.modelica.expect("No AST produced")
    }

    /// Test visitor that counts classes, components, and expressions
    struct CountingVisitor {
        classes: usize,
        components: usize,
        expressions: usize,
        equations: usize,
    }

    impl Visitor for CountingVisitor {
        fn enter_class_definition(&mut self, _node: &ClassDefinition) {
            self.classes += 1;
        }

        fn enter_component(&mut self, _node: &Component) {
            self.components += 1;
        }

        fn enter_expression(&mut self, _node: &Expression) {
            self.expressions += 1;
        }

        fn enter_equation(&mut self, _node: &Equation) {
            self.equations += 1;
        }
    }

    #[test]
    fn test_visitor_counts() {
        let code = r#"
model Test
  Real x;
  Real y;
equation
  x = 1.0;
  y = x + 2.0;
end Test;
"#;
        let ast = parse_test_code(code);
        let mut visitor = CountingVisitor {
            classes: 0,
            components: 0,
            expressions: 0,
            equations: 0,
        };

        ast.accept(&mut visitor);

        assert_eq!(visitor.classes, 1, "Should have 1 class");
        assert_eq!(visitor.components, 2, "Should have 2 components (x, y)");
        assert_eq!(visitor.equations, 2, "Should have 2 equations");
        // Expressions: x, 1.0, y, x, 2.0, (x + 2.0)
        assert!(visitor.expressions >= 4, "Should have multiple expressions");
    }

    #[test]
    fn test_nested_classes() {
        let code = r#"
model Outer
  Real x;
  model Inner
    Real y;
  end Inner;
end Outer;
"#;
        let ast = parse_test_code(code);
        let mut visitor = CountingVisitor {
            classes: 0,
            components: 0,
            expressions: 0,
            equations: 0,
        };

        ast.accept(&mut visitor);

        assert_eq!(visitor.classes, 2, "Should have 2 classes (Outer, Inner)");
        assert_eq!(
            visitor.components, 2,
            "Should have 2 components (x in Outer, y in Inner)"
        );
    }

    #[test]
    fn test_generic_collector() {
        let code = r#"
model Test
  Real x;
  Real y;
equation
  x = y + 1.0;
end Test;
"#;
        let ast = parse_test_code(code);
        let class = ast.class_list.get("Test").expect("Test class not found");

        // Use the generic collector to collect component reference names
        let names = collect_component_refs(class, |cref| {
            cref.parts.first().map(|p| p.ident.text.clone())
        });

        assert!(names.contains("x"), "Should contain 'x'");
        assert!(names.contains("y"), "Should contain 'y'");
    }

    #[test]
    fn test_collector_struct_directly() {
        let code = r#"
model Test
  Real a;
  Real b;
equation
  a = b * 2.0;
end Test;
"#;
        let ast = parse_test_code(code);
        let class = ast.class_list.get("Test").expect("Test class not found");

        // Use the Collector struct directly
        let mut collector = Collector::new(|cref: &ComponentReference| {
            cref.parts.first().map(|p| p.ident.text.clone())
        });
        class.accept(&mut collector);

        let names: Vec<String> = collector.into_collected();
        assert!(names.contains(&"a".to_string()));
        assert!(names.contains(&"b".to_string()));
    }
}