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
//! Visitor-based type checking for Modelica classes.
//!
//! This module provides a unified visitor that performs multiple semantic checks
//! in a single AST traversal, improving efficiency over separate check functions.
//!
//! # Checks Performed
//!
//! - `cardinality_context`: Validates cardinality() is only used in if-conditions or asserts
//! - `class_member_access`: Validates member access on class-typed variables
//! - `scalar_subscripts`: Validates subscript expressions are scalar
//! - `array_bounds`: Validates array subscripts are within bounds
//!
//! # Example
//!
//! ```ignore
//! use rumoca::ir::analysis::check_visitor::{CheckConfig, CheckVisitor};
//!
//! let config = CheckConfig::all();
//! let mut visitor = CheckVisitor::new(config, &defined_symbols);
//! class.accept(&mut visitor);
//! let result = visitor.into_result();
//! ```

use std::collections::HashMap;

use crate::ir::ast::{ClassDefinition, Component, Equation, Expression, Location, Statement};
use crate::ir::visitor::Visitor;

use super::symbols::DefinedSymbol;
use super::type_checker::{TypeCheckResult, TypeError, TypeErrorSeverity};
use super::type_inference::SymbolType;

// =============================================================================
// Check Configuration
// =============================================================================

/// Configuration for which checks to perform during traversal.
///
/// Use `CheckConfig::all()` to enable all checks, or create a custom
/// configuration to run only specific checks.
#[derive(Debug, Clone, Default)]
pub struct CheckConfig {
    /// Check that cardinality() is only used in if-conditions or assert statements
    pub check_cardinality_context: bool,
    /// Check that class member access is valid (e.g., `x.y` where x is a class instance)
    pub check_class_member_access: bool,
    /// Check that subscript expressions are scalar (not arrays)
    pub check_scalar_subscripts: bool,
    /// Check that array subscripts are within bounds
    pub check_array_bounds: bool,
}

impl CheckConfig {
    /// Create a configuration with all checks enabled
    pub fn all() -> Self {
        Self {
            check_cardinality_context: true,
            check_class_member_access: true,
            check_scalar_subscripts: true,
            check_array_bounds: true,
        }
    }

    /// Create a configuration with no checks enabled
    pub fn none() -> Self {
        Self::default()
    }

    /// Create a configuration with only cardinality context check enabled
    pub fn cardinality_only() -> Self {
        Self {
            check_cardinality_context: true,
            ..Self::default()
        }
    }
}

// =============================================================================
// Check Context
// =============================================================================

/// Context tracking during traversal for semantic checks.
#[derive(Debug, Clone, Default)]
struct CheckContext {
    /// Whether we're inside an if-equation/statement condition
    in_condition: bool,
    /// Whether we're inside an assert statement
    in_assert: bool,
    /// Current component being checked (for bindings)
    current_component: Option<String>,
    /// Whether we're inside a for loop (for break/return checks)
    in_loop: bool,
    /// Whether we're inside a while loop
    in_while: bool,
    /// Whether we're inside a function (for return checks)
    #[allow(dead_code)]
    in_function: bool,
}

// =============================================================================
// Check Visitor
// =============================================================================

/// Unified visitor for performing multiple semantic checks in a single traversal.
///
/// This visitor collects all type errors found during traversal into a single
/// `TypeCheckResult`. The checks performed are controlled by the `CheckConfig`.
pub struct CheckVisitor<'a> {
    /// Configuration for which checks to perform
    config: CheckConfig,
    /// Accumulated type errors
    result: TypeCheckResult,
    /// Defined symbols for type lookups
    #[allow(dead_code)]
    defined: &'a HashMap<String, DefinedSymbol>,
    /// Component shapes for array bounds checking
    #[allow(dead_code)]
    component_shapes: HashMap<String, Vec<usize>>,
    /// Traversal context
    context: CheckContext,
}

impl<'a> CheckVisitor<'a> {
    /// Create a new check visitor with the given configuration and symbol table.
    pub fn new(config: CheckConfig, defined: &'a HashMap<String, DefinedSymbol>) -> Self {
        Self {
            config,
            result: TypeCheckResult::new(),
            defined,
            component_shapes: HashMap::new(),
            context: CheckContext::default(),
        }
    }

    /// Create a new check visitor with component shape information for bounds checking.
    pub fn with_shapes(
        config: CheckConfig,
        defined: &'a HashMap<String, DefinedSymbol>,
        component_shapes: HashMap<String, Vec<usize>>,
    ) -> Self {
        Self {
            config,
            result: TypeCheckResult::new(),
            defined,
            component_shapes,
            context: CheckContext::default(),
        }
    }

    /// Consume the visitor and return the accumulated type check result.
    pub fn into_result(self) -> TypeCheckResult {
        self.result
    }

    /// Get a reference to the current result.
    pub fn result(&self) -> &TypeCheckResult {
        &self.result
    }

    /// Add a cardinality context error at the given location.
    fn add_cardinality_error(&mut self, location: Location) {
        self.result.add_error(TypeError::new(
            location,
            SymbolType::Unknown,
            SymbolType::Unknown,
            "cardinality may only be used in the condition of an if-statement/equation or an assert.".to_string(),
            TypeErrorSeverity::Error,
        ));
    }

    // =========================================================================
    // Cardinality Context Checking
    // =========================================================================

    /// Check if an expression contains a cardinality() call and report an error
    /// if we're not in a valid context (if-condition or assert).
    fn check_cardinality_in_expr(&mut self, expr: &Expression) {
        if !self.config.check_cardinality_context {
            return;
        }

        // If we're in a valid context, cardinality is allowed
        if self.context.in_condition || self.context.in_assert {
            return;
        }

        // Look for cardinality calls in this expression
        if let Some(loc) = find_cardinality_call(expr) {
            self.add_cardinality_error(loc);
        }
    }
}

// =============================================================================
// Visitor Implementation
// =============================================================================

impl Visitor for CheckVisitor<'_> {
    fn enter_component(&mut self, node: &Component) {
        // Check component bindings for cardinality context violations
        if self.config.check_cardinality_context && !matches!(node.start, Expression::Empty) {
            self.context.current_component = Some(node.name.clone());
            self.check_cardinality_in_expr(&node.start);
            self.context.current_component = None;
        }
    }

    fn enter_equation(&mut self, node: &Equation) {
        match node {
            Equation::Simple { lhs, rhs } => {
                // Check both sides for cardinality violations
                self.check_cardinality_in_expr(lhs);
                self.check_cardinality_in_expr(rhs);
            }
            Equation::If { cond_blocks, .. } => {
                // The conditions are valid contexts for cardinality
                // We'll check them with in_condition = true
                for block in cond_blocks {
                    self.context.in_condition = true;
                    // Note: The visitor will descend into the condition expression
                    // but we've set the flag, so cardinality is allowed there
                    // We need to check the condition here since Visitor doesn't
                    // have a separate hook for if-conditions
                    let _ = &block.cond; // Condition is checked with in_condition=true
                    self.context.in_condition = false;
                }
            }
            Equation::FunctionCall { comp, args, .. } => {
                // Check if this is an assert - cardinality IS allowed in assert
                let is_assert = comp.parts.len() == 1
                    && comp.parts.first().is_some_and(|p| p.ident.text == "assert");

                if is_assert {
                    self.context.in_assert = true;
                    // Args will be checked with in_assert=true
                } else {
                    // Check arguments for cardinality violations
                    for arg in args {
                        self.check_cardinality_in_expr(arg);
                    }
                }
            }
            _ => {}
        }
    }

    fn exit_equation(&mut self, node: &Equation) {
        // Reset context flags
        if let Equation::FunctionCall { comp, .. } = node {
            let is_assert = comp.parts.len() == 1
                && comp.parts.first().is_some_and(|p| p.ident.text == "assert");
            if is_assert {
                self.context.in_assert = false;
            }
        }
    }

    fn enter_statement(&mut self, node: &Statement) {
        match node {
            Statement::Assignment { value, .. } => {
                self.check_cardinality_in_expr(value);
            }
            Statement::If { cond_blocks, .. } => {
                // The conditions are valid contexts for cardinality
                for block in cond_blocks {
                    self.context.in_condition = true;
                    let _ = &block.cond;
                    self.context.in_condition = false;
                }
            }
            Statement::While(block) => {
                // While condition is a valid context for cardinality
                self.context.in_condition = true;
                let _ = &block.cond;
                self.context.in_condition = false;
                self.context.in_while = true;
            }
            Statement::For { .. } => {
                self.context.in_loop = true;
            }
            Statement::FunctionCall { comp, args, .. } => {
                let is_assert = comp.parts.len() == 1
                    && comp.parts.first().is_some_and(|p| p.ident.text == "assert");

                if is_assert {
                    self.context.in_assert = true;
                } else {
                    for arg in args {
                        self.check_cardinality_in_expr(arg);
                    }
                }
            }
            _ => {}
        }
    }

    fn exit_statement(&mut self, node: &Statement) {
        match node {
            Statement::While(_) => {
                self.context.in_while = false;
            }
            Statement::For { .. } => {
                self.context.in_loop = false;
            }
            Statement::FunctionCall { comp, .. } => {
                let is_assert = comp.parts.len() == 1
                    && comp.parts.first().is_some_and(|p| p.ident.text == "assert");
                if is_assert {
                    self.context.in_assert = false;
                }
            }
            _ => {}
        }
    }
}

// =============================================================================
// Helper Functions
// =============================================================================

/// Find a cardinality() call in an expression and return its location.
fn find_cardinality_call(expr: &Expression) -> Option<Location> {
    match expr {
        Expression::FunctionCall { comp, args, .. } => {
            // Check if this is a cardinality call
            if comp.parts.len() == 1
                && let Some(first) = comp.parts.first()
                && first.ident.text == "cardinality"
            {
                return Some(first.ident.location.clone());
            }
            // Recurse into arguments
            for arg in args {
                if let Some(loc) = find_cardinality_call(arg) {
                    return Some(loc);
                }
            }
            None
        }
        Expression::Binary { lhs, rhs, .. } => {
            find_cardinality_call(lhs).or_else(|| find_cardinality_call(rhs))
        }
        Expression::Unary { rhs, .. } => find_cardinality_call(rhs),
        Expression::If {
            branches,
            else_branch,
        } => {
            for (cond, then_expr) in branches {
                if let Some(loc) = find_cardinality_call(cond) {
                    return Some(loc);
                }
                if let Some(loc) = find_cardinality_call(then_expr) {
                    return Some(loc);
                }
            }
            find_cardinality_call(else_branch)
        }
        Expression::Array { elements, .. } => {
            for elem in elements {
                if let Some(loc) = find_cardinality_call(elem) {
                    return Some(loc);
                }
            }
            None
        }
        Expression::Range { start, step, end } => {
            if let Some(loc) = find_cardinality_call(start) {
                return Some(loc);
            }
            if let Some(loc) = step.as_ref().and_then(|s| find_cardinality_call(s)) {
                return Some(loc);
            }
            find_cardinality_call(end)
        }
        Expression::Tuple { elements } => {
            for elem in elements {
                if let Some(loc) = find_cardinality_call(elem) {
                    return Some(loc);
                }
            }
            None
        }
        Expression::ArrayComprehension { expr, indices } => {
            if let Some(loc) = find_cardinality_call(expr) {
                return Some(loc);
            }
            for idx in indices {
                if let Some(loc) = find_cardinality_call(&idx.range) {
                    return Some(loc);
                }
            }
            None
        }
        Expression::Parenthesized { inner } => find_cardinality_call(inner),
        Expression::ComponentReference(_) | Expression::Terminal { .. } | Expression::Empty => None,
    }
}

// =============================================================================
// Public API
// =============================================================================

/// Perform all configured checks on a class definition using the visitor pattern.
///
/// This is more efficient than calling individual check functions as it
/// performs all checks in a single AST traversal.
pub fn check_class(
    class: &ClassDefinition,
    config: CheckConfig,
    defined: &HashMap<String, DefinedSymbol>,
) -> TypeCheckResult {
    use crate::ir::visitor::Visitable;

    let mut visitor = CheckVisitor::new(config, defined);
    class.accept(&mut visitor);
    visitor.into_result()
}

/// Perform all checks on a class definition.
pub fn check_all(
    class: &ClassDefinition,
    defined: &HashMap<String, DefinedSymbol>,
) -> TypeCheckResult {
    check_class(class, CheckConfig::all(), defined)
}

/// Perform all semantic checks on a class definition.
///
/// This is the recommended entry point for semantic validation. It combines
/// multiple semantic checks into a single result:
///
/// - Cardinality context validation
/// - Class member access validation
/// - Scalar subscript validation
/// - Array bounds validation
/// - Component binding validation
/// - Assert argument validation
/// - Break/return context validation
///
/// # Arguments
///
/// * `class` - The class definition to check
/// * `defined` - Symbol table with defined symbols (optional, empty HashMap if not available)
///
/// # Returns
///
/// A `TypeCheckResult` containing all errors found during semantic checking.
pub fn check_semantic(
    class: &ClassDefinition,
    defined: &HashMap<String, DefinedSymbol>,
) -> TypeCheckResult {
    use super::type_checker;

    let mut result = TypeCheckResult::new();

    // Cardinality checks
    result.merge(type_checker::check_cardinality_context(class));
    result.merge(type_checker::check_cardinality_arguments(class));

    // Class and member access checks
    result.merge(type_checker::check_class_member_access(class));

    // Array and subscript checks
    result.merge(type_checker::check_scalar_subscripts(class));
    result.merge(type_checker::check_array_bounds(class));

    // Component and binding checks
    result.merge(type_checker::check_component_bindings(class));
    result.merge(type_checker::check_assert_arguments(class));
    result.merge(type_checker::check_builtin_attribute_modifiers(class));

    // Control flow checks
    result.merge(type_checker::check_break_return_context(class));

    // Start modification dimension checks
    result.merge(type_checker::check_start_modification_dimensions(class));

    // Visitor-based checks (for future expansion)
    let visitor_result = check_all(class, defined);
    result.merge(visitor_result);

    result
}

/// Perform semantic checks with equation type checking.
///
/// This extends `check_semantic` by also performing type checking on equations
/// using the provided symbol table.
///
/// # Arguments
///
/// * `class` - The class definition to check
/// * `defined` - Symbol table with defined symbols for type inference
///
/// # Returns
///
/// A `TypeCheckResult` containing all errors found during semantic and type checking.
pub fn check_semantic_with_types(
    class: &ClassDefinition,
    defined: &HashMap<String, DefinedSymbol>,
) -> TypeCheckResult {
    use super::type_checker;

    let mut result = check_semantic(class, defined);

    // Type check equations
    result.merge(type_checker::check_equations(&class.equations, defined));

    // Type check algorithm sections
    for algorithm_block in &class.algorithms {
        result.merge(type_checker::check_statements(algorithm_block, defined));
    }

    result
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_check_config_all() {
        let config = CheckConfig::all();
        assert!(config.check_cardinality_context);
        assert!(config.check_class_member_access);
        assert!(config.check_scalar_subscripts);
        assert!(config.check_array_bounds);
    }

    #[test]
    fn test_check_config_none() {
        let config = CheckConfig::none();
        assert!(!config.check_cardinality_context);
        assert!(!config.check_class_member_access);
        assert!(!config.check_scalar_subscripts);
        assert!(!config.check_array_bounds);
    }

    #[test]
    fn test_check_config_cardinality_only() {
        let config = CheckConfig::cardinality_only();
        assert!(config.check_cardinality_context);
        assert!(!config.check_class_member_access);
        assert!(!config.check_scalar_subscripts);
        assert!(!config.check_array_bounds);
    }

    #[test]
    fn test_find_cardinality_call_not_found() {
        // Test that find_cardinality_call returns None for non-cardinality expressions
        let expr = Expression::Empty;
        assert!(find_cardinality_call(&expr).is_none());
    }

    #[test]
    fn test_find_cardinality_call_in_array() {
        // Test that find_cardinality_call returns None for array without cardinality
        let expr = Expression::Array {
            elements: vec![Expression::Empty, Expression::Empty],
            is_matrix: false,
        };
        assert!(find_cardinality_call(&expr).is_none());
    }

    #[test]
    fn test_find_cardinality_call_in_parenthesized() {
        // Test that find_cardinality_call descends into parenthesized expressions
        let expr = Expression::Parenthesized {
            inner: Box::new(Expression::Empty),
        };
        assert!(find_cardinality_call(&expr).is_none());
    }
}