mortar_compiler 0.3.0

Mortar language compiler core library
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
use crate::Language;
use crate::parser::{
    Arg, ChoiceDest, ChoiceItem, Condition, EventAction, FuncCall, FunctionDecl,
    InterpolatedString, NodeDef, NodeJump, NodeStmt, Program, StringPart, TopLevel,
};
use owo_colors::OwoColorize;
use std::collections::{HashMap, HashSet};

fn get_text(key: &str, language: Language) -> &'static str {
    match (key, language) {
        ("checking_file", Language::English) => "Checking file:",
        ("checking_file", Language::Chinese) => "检查文件:",
        ("error", Language::English) => "error",
        ("error", Language::Chinese) => "错误",
        ("warning", Language::English) => "warning",
        ("warning", Language::Chinese) => "警告",

        // Function naming warnings
        ("function_should_use_snake_case", Language::English) => {
            "Function '{}' should use snake_case naming."
        }
        ("function_should_use_snake_case", Language::Chinese) => {
            "函数 '{}' 应该使用 snake_case 命名。"
        }

        // Node naming warnings
        ("node_should_use_pascal_case", Language::English) => {
            "Node '{}' should use PascalCase naming."
        }
        ("node_should_use_pascal_case", Language::Chinese) => {
            "节点 '{}' 应该使用 PascalCase 命名。"
        }

        // Unused function warnings
        ("function_declared_but_never_used", Language::English) => {
            "Function '{}' is declared but never used."
        }
        ("function_declared_but_never_used", Language::Chinese) => "函数 '{}' 已声明但从未使用。",

        // Node not found errors
        ("node_not_defined", Language::English) => "Node '{}' is not defined.",
        ("node_not_defined", Language::Chinese) => "节点 '{}' 未定义",

        // Function not found errors
        ("function_not_declared", Language::English) => "Function '{}' is not declared.",
        ("function_not_declared", Language::Chinese) => "函数 '{}' 未声明。",

        // Argument count mismatch errors
        ("function_expects_args", Language::English) => {
            "Function '{}' expects {} arguments, but {} were provided."
        }
        ("function_expects_args", Language::Chinese) => {
            "函数 '{}' 期望 {} 个参数,但提供了 {} 个。"
        }

        // Argument type mismatch errors
        ("function_parameter_type_mismatch", Language::English) => {
            "Function '{}' parameter '{}' expects type '{}', but '{}' was provided."
        }
        ("function_parameter_type_mismatch", Language::Chinese) => {
            "函数 '{}' 的参数 '{}' 期望类型 '{}',但提供了 '{}'。"
        }

        // Condition type mismatch errors
        ("condition_must_return_boolean", Language::English) => {
            "Condition function '{}' must return a boolean type, but returns '{}'."
        }
        ("condition_must_return_boolean", Language::Chinese) => {
            "条件函数 '{}' 必须返回布尔类型,但返回了 '{}'。"
        }

        _ => "",
    }
}

fn format_message(template: &str, args: &[&str]) -> String {
    let mut result = template.to_string();
    for arg in args {
        if let Some(pos) = result.find("{}") {
            result.replace_range(pos..pos + 2, arg);
        }
    }
    result
}

fn get_line_col(source: &str, pos: usize) -> (usize, usize) {
    let mut line = 1;
    let mut col = 1;

    for (i, ch) in source.char_indices() {
        if i >= pos {
            break;
        }
        if ch == '\n' {
            line += 1;
            col = 1;
        } else {
            col += 1;
        }
    }

    (line, col)
}

#[derive(Debug, Clone)]
pub enum Severity {
    Error,
    Warning,
}

#[derive(Debug, Clone)]
pub enum DiagnosticKind {
    // Errors
    NodeNotFound {
        node_name: String,
    },
    FunctionNotFound {
        function_name: String,
    },
    SyntaxError {
        message: String,
    },
    TypeError {
        message: String,
    },
    ArgumentCountMismatch {
        function_name: String,
        expected: usize,
        actual: usize,
    },
    ArgumentTypeMismatch {
        function_name: String,
        parameter: String,
        expected: String,
        actual: String,
    },
    ConditionTypeMismatch {
        expected: String,
        actual: String,
    },

    // Warnings
    NonSnakeCaseFunction {
        function_name: String,
    },
    NonPascalCaseNode {
        node_name: String,
    },
    UnusedFunction {
        function_name: String,
    },
}

#[derive(Debug, Clone)]
pub struct Diagnostic {
    pub kind: DiagnosticKind,
    pub severity: Severity,
    pub span: Option<(usize, usize)>, // (start, end) byte positions
    pub message: String,
}

pub struct DiagnosticCollector {
    diagnostics: Vec<Diagnostic>,
    file_name: String,
    language: Language,
}

impl DiagnosticCollector {
    pub fn new(file_name: String) -> Self {
        Self {
            diagnostics: Vec::new(),
            file_name,
            language: Language::English,
        }
    }

    pub fn new_with_language(file_name: String, language: Language) -> Self {
        Self {
            diagnostics: Vec::new(),
            file_name,
            language,
        }
    }

    pub fn add_diagnostic(&mut self, diagnostic: Diagnostic) {
        self.diagnostics.push(diagnostic);
    }

    pub fn has_errors(&self) -> bool {
        self.diagnostics
            .iter()
            .any(|d| matches!(d.severity, Severity::Error))
    }

    pub fn print_diagnostics(&self, source: &str) {
        if self.diagnostics.is_empty() {
            return;
        }

        println!(
            "{} {}",
            get_text("checking_file", self.language),
            self.file_name.cyan()
        );

        // Sort diagnostics: errors first, then warnings
        let mut sorted_diagnostics = self.diagnostics.clone();
        sorted_diagnostics.sort_by(|a, b| {
            use Severity::*;
            match (&a.severity, &b.severity) {
                (Error, Warning) => std::cmp::Ordering::Less,
                (Warning, Error) => std::cmp::Ordering::Greater,
                _ => std::cmp::Ordering::Equal,
            }
        });

        for diagnostic in &sorted_diagnostics {
            let severity_str = match diagnostic.severity {
                Severity::Error => get_text("error", self.language),
                Severity::Warning => get_text("warning", self.language),
            };

            if let Some((start, _end)) = diagnostic.span {
                // Calculate line and column numbers
                let (line, col) = get_line_col(source, start);

                // Print colored error header
                let header = format!(
                    "{}: {}:{}:{}: {}",
                    severity_str, self.file_name, line, col, diagnostic.message
                );

                match diagnostic.severity {
                    Severity::Error => println!("{}", header.red()),
                    Severity::Warning => println!("{}", header.yellow()),
                }

                // Show source code snippet
                let lines: Vec<&str> = source.lines().collect();
                if line > 0 && (line - 1) < lines.len() {
                    let source_line = lines[line - 1];
                    println!(
                        "{:3} {} {}",
                        line.to_string().bright_blue(),
                        "|".bright_blue(),
                        source_line
                    );

                    // Calculate character count within error range for equal-length indicators
                    let error_length = if let Some((span_start, span_end)) = diagnostic.span {
                        // Convert byte length to character length
                        let error_text = &source[span_start..std::cmp::min(span_end, source.len())];
                        std::cmp::max(1, error_text.chars().count())
                    } else {
                        1
                    };

                    // Create pointer indicators with equal-length ^ characters
                    let padding = " ".repeat(col - 1); // col is 1-based, subtract 1 for correct position
                    let pointer_str = "^".repeat(error_length);
                    let pointer = match diagnostic.severity {
                        Severity::Error => {
                            format!("    {} {}{}", "|".bright_blue(), padding, pointer_str.red())
                        }
                        Severity::Warning => format!(
                            "    {} {}{}",
                            "|".bright_blue(),
                            padding,
                            pointer_str.yellow()
                        ),
                    };
                    println!("{}", pointer);
                }
            } else {
                let header = format!(
                    "{}: {}: {}",
                    severity_str, self.file_name, diagnostic.message
                );
                match diagnostic.severity {
                    Severity::Error => println!("{}", header.red()),
                    Severity::Warning => println!("{}", header.yellow()),
                }
            }
            println!();
        }
    }

    pub fn get_diagnostics(&self) -> &Vec<Diagnostic> {
        &self.diagnostics
    }

    pub fn analyze_program(&mut self, program: &Program) {
        // Collect all function declarations and nodes
        let mut declared_functions = HashMap::new();
        let mut declared_nodes = HashMap::new();
        let mut used_functions = HashSet::new();
        let mut used_nodes = HashSet::new();

        // First pass: collect declarations
        for item in &program.body {
            match item {
                TopLevel::FunctionDecl(func) => {
                    // Check function naming convention
                    if !is_snake_case(&func.name) {
                        self.add_diagnostic(Diagnostic {
                            kind: DiagnosticKind::NonSnakeCaseFunction {
                                function_name: func.name.clone(),
                            },
                            severity: Severity::Warning,
                            span: func.name_span,
                            message: format_message(
                                get_text("function_should_use_snake_case", self.language),
                                &[&func.name],
                            ),
                        });
                    }

                    declared_functions.insert(func.name.clone(), func);
                }
                TopLevel::NodeDef(node) => {
                    // Check node naming convention
                    if !is_pascal_case(&node.name) {
                        self.add_diagnostic(Diagnostic {
                            kind: DiagnosticKind::NonPascalCaseNode {
                                node_name: node.name.clone(),
                            },
                            severity: Severity::Warning,
                            span: node.name_span,
                            message: format_message(
                                get_text("node_should_use_pascal_case", self.language),
                                &[&node.name],
                            ),
                        });
                    }

                    declared_nodes.insert(node.name.clone(), node);
                }
            }
        }

        // Second pass: check usages
        for item in &program.body {
            if let TopLevel::NodeDef(node) = item {
                self.analyze_node_usage(
                    node,
                    &declared_functions,
                    &declared_nodes,
                    &mut used_functions,
                    &mut used_nodes,
                );
            }
        }

        // Check for unused functions
        for func_name in declared_functions.keys() {
            if !used_functions.contains(func_name) {
                self.add_diagnostic(Diagnostic {
                    kind: DiagnosticKind::UnusedFunction {
                        function_name: func_name.clone(),
                    },
                    severity: Severity::Warning,
                    span: declared_functions[func_name].name_span,
                    message: format_message(
                        get_text("function_declared_but_never_used", self.language),
                        &[func_name],
                    ),
                });
            }
        }
    }

    fn analyze_node_usage(
        &mut self,
        node: &NodeDef,
        declared_functions: &HashMap<String, &FunctionDecl>,
        declared_nodes: &HashMap<String, &NodeDef>,
        used_functions: &mut HashSet<String>,
        used_nodes: &mut HashSet<String>,
    ) {
        // Analyze node jump
        if let Some(jump) = &node.jump {
            self.analyze_node_jump(jump, declared_nodes, used_nodes);
        }

        // Analyze statements
        for stmt in &node.body {
            match stmt {
                NodeStmt::Events(events) => {
                    for event in events {
                        self.analyze_event_action(
                            &event.action,
                            declared_functions,
                            used_functions,
                        );
                    }
                }
                NodeStmt::Choice(choices) => {
                    self.analyze_choices(
                        choices,
                        declared_functions,
                        declared_nodes,
                        used_functions,
                        used_nodes,
                    );
                }
                NodeStmt::Text(text) => {
                    // Check for function calls in text interpolation (old format)
                    self.analyze_text_interpolation(text, declared_functions, used_functions);
                }
                NodeStmt::InterpolatedText(interpolated) => {
                    // Check function calls in interpolated string
                    self.analyze_interpolated_string(
                        interpolated,
                        declared_functions,
                        used_functions,
                    );
                }
            }
        }
    }

    fn analyze_node_jump(
        &mut self,
        jump: &NodeJump,
        declared_nodes: &HashMap<String, &NodeDef>,
        used_nodes: &mut HashSet<String>,
    ) {
        match jump {
            NodeJump::Identifier(node_name, span) => {
                used_nodes.insert(node_name.clone());
                if !declared_nodes.contains_key(node_name) {
                    self.add_diagnostic(Diagnostic {
                        kind: DiagnosticKind::NodeNotFound {
                            node_name: node_name.clone(),
                        },
                        severity: Severity::Error,
                        span: *span,
                        message: format_message(
                            get_text("node_not_defined", self.language),
                            &[node_name],
                        ),
                    });
                }
            }
            NodeJump::Return | NodeJump::Break => {
                // These are always valid
            }
        }
    }

    fn analyze_choices(
        &mut self,
        choices: &[ChoiceItem],
        declared_functions: &HashMap<String, &FunctionDecl>,
        declared_nodes: &HashMap<String, &NodeDef>,
        used_functions: &mut HashSet<String>,
        used_nodes: &mut HashSet<String>,
    ) {
        for choice in choices {
            // Analyze condition
            if let Some(condition) = &choice.condition {
                match condition {
                    Condition::Identifier(_) => {
                        // TODO: Check if identifier is valid in scope
                        // For now, we assume identifiers are boolean
                    }
                    Condition::FuncCall(func_call) => {
                        self.analyze_func_call(func_call, declared_functions, used_functions);

                        // Check that the function returns a boolean type
                        if let Some(func_decl) = declared_functions.get(&func_call.name)
                            && let Some(return_type) = &func_decl.return_type
                            && !self.is_boolean_type(return_type)
                        {
                            self.add_diagnostic(Diagnostic {
                                kind: DiagnosticKind::ConditionTypeMismatch {
                                    expected: "Boolean".to_string(),
                                    actual: return_type.clone(),
                                },
                                severity: Severity::Error,
                                span: func_call.name_span,
                                message: format_message(
                                    get_text("condition_must_return_boolean", self.language),
                                    &[&func_call.name, return_type],
                                ),
                            });
                        }
                    }
                }
            }

            // Analyze choice destination
            match &choice.target {
                ChoiceDest::Identifier(node_name, span) => {
                    used_nodes.insert(node_name.clone());
                    if !declared_nodes.contains_key(node_name) {
                        self.add_diagnostic(Diagnostic {
                            kind: DiagnosticKind::NodeNotFound {
                                node_name: node_name.clone(),
                            },
                            severity: Severity::Error,
                            span: *span,
                            message: format_message(
                                get_text("node_not_defined", self.language),
                                &[node_name],
                            ),
                        });
                    }
                }
                ChoiceDest::NestedChoices(nested) => {
                    self.analyze_choices(
                        nested,
                        declared_functions,
                        declared_nodes,
                        used_functions,
                        used_nodes,
                    );
                }
                ChoiceDest::Return | ChoiceDest::Break => {
                    // These are always valid
                }
            }
        }
    }

    fn analyze_event_action(
        &mut self,
        action: &EventAction,
        declared_functions: &HashMap<String, &FunctionDecl>,
        used_functions: &mut HashSet<String>,
    ) {
        self.analyze_func_call(&action.call, declared_functions, used_functions);

        for chain in &action.chains {
            self.analyze_func_call(chain, declared_functions, used_functions);
        }
    }

    fn analyze_func_call(
        &mut self,
        func_call: &FuncCall,
        declared_functions: &HashMap<String, &FunctionDecl>,
        used_functions: &mut HashSet<String>,
    ) {
        used_functions.insert(func_call.name.clone());

        // Check if function is declared
        if !declared_functions.contains_key(&func_call.name) {
            self.add_diagnostic(Diagnostic {
                kind: DiagnosticKind::FunctionNotFound {
                    function_name: func_call.name.clone(),
                },
                severity: Severity::Error,
                span: func_call.name_span,
                message: format_message(
                    get_text("function_not_declared", self.language),
                    &[&func_call.name],
                ),
            });
            return;
        }

        let func_decl = declared_functions[&func_call.name];

        // Check argument count
        if func_call.args.len() != func_decl.params.len() {
            self.add_diagnostic(Diagnostic {
                kind: DiagnosticKind::ArgumentCountMismatch {
                    function_name: func_call.name.clone(),
                    expected: func_decl.params.len(),
                    actual: func_call.args.len(),
                },
                severity: Severity::Error,
                span: func_call.name_span,
                message: format_message(
                    get_text("function_expects_args", self.language),
                    &[
                        &func_call.name,
                        &func_decl.params.len().to_string(),
                        &func_call.args.len().to_string(),
                    ],
                ),
            });
        } else {
            // Check argument types if count matches
            for (arg, param) in func_call.args.iter().zip(func_decl.params.iter()) {
                let arg_type = self.infer_argument_type(arg, declared_functions);
                if !self.is_type_compatible(&arg_type, &param.type_name) {
                    let arg_type_for_message = self.infer_argument_type(arg, declared_functions);
                    self.add_diagnostic(Diagnostic {
                        kind: DiagnosticKind::ArgumentTypeMismatch {
                            function_name: func_call.name.clone(),
                            parameter: param.name.clone(),
                            expected: param.type_name.clone(),
                            actual: arg_type,
                        },
                        severity: Severity::Error,
                        span: func_call.name_span,
                        message: format_message(
                            get_text("function_parameter_type_mismatch", self.language),
                            &[
                                &func_call.name,
                                &param.name,
                                &param.type_name,
                                &arg_type_for_message,
                            ],
                        ),
                    });
                }
            }
        }

        // Analyze nested function calls in arguments
        for arg in &func_call.args {
            if let Arg::FuncCall(nested_call) = arg {
                self.analyze_func_call(nested_call, declared_functions, used_functions);
            }
        }
    }

    fn infer_argument_type(
        &self,
        arg: &Arg,
        declared_functions: &HashMap<String, &FunctionDecl>,
    ) -> String {
        match arg {
            Arg::String(_) => "String".to_string(),
            Arg::Number(_) => "Number".to_string(),
            Arg::Identifier(_) => "Unknown".to_string(), // Could be enhanced with variable tracking
            Arg::FuncCall(func_call) => {
                if let Some(func_decl) = declared_functions.get(&func_call.name) {
                    func_decl
                        .return_type
                        .clone()
                        .unwrap_or("Unknown".to_string())
                } else {
                    "Unknown".to_string()
                }
            }
        }
    }

    fn is_boolean_type(&self, type_name: &str) -> bool {
        matches!(type_name, "Boolean" | "Bool")
    }

    fn is_type_compatible(&self, actual: &str, expected: &str) -> bool {
        match (expected, actual) {
            // Exact matches
            ("String", "String") | ("Number", "Number") => true,
            // Boolean type aliases
            ("Boolean", "Bool")
            | ("Bool", "Boolean")
            | ("Boolean", "Boolean")
            | ("Bool", "Bool") => true,
            // Unknown types are compatible for now (could be enhanced)
            (_, "Unknown") => true,
            // Everything else is incompatible
            _ => false,
        }
    }

    fn analyze_interpolated_string(
        &mut self,
        interpolated: &InterpolatedString,
        declared_functions: &HashMap<String, &FunctionDecl>,
        used_functions: &mut HashSet<String>,
    ) {
        for part in &interpolated.parts {
            if let StringPart::Expression(func_call) = part {
                self.analyze_func_call(func_call, declared_functions, used_functions);

                // Also check that the function returns a type that can be converted to string
                // All types can be converted to string for interpolation, so no error needed
                // This is where we could add more specific checks if needed
            }
        }
    }

    fn analyze_text_interpolation(
        &mut self,
        text: &str,
        declared_functions: &HashMap<String, &FunctionDecl>,
        used_functions: &mut HashSet<String>,
    ) {
        // Simple regex-like parsing to find function calls in {function_name()} pattern
        let mut chars = text.chars().peekable();
        while let Some(ch) = chars.next() {
            if ch == '{' {
                // Found potential function call
                let mut func_call = String::new();
                while let Some(&next_ch) = chars.peek() {
                    if next_ch == '}' {
                        chars.next(); // consume '}'
                        break;
                    }
                    func_call.push(chars.next().unwrap());
                }

                // Check if it looks like a function call
                if let Some(paren_pos) = func_call.find('(') {
                    let func_name = func_call[..paren_pos].trim().to_string();
                    if declared_functions.contains_key(&func_name) {
                        used_functions.insert(func_name);
                    }
                }
            }
        }
    }
}

fn is_snake_case(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }

    // Should start with lowercase letter or underscore
    let first_char = s.chars().next().unwrap();
    if !first_char.is_ascii_lowercase() && first_char != '_' {
        return false;
    }

    // Should contain only lowercase letters, digits, and underscores
    s.chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
}

fn is_pascal_case(s: &str) -> bool {
    if s.is_empty() {
        return false;
    }

    // Should start with uppercase letter
    let first_char = s.chars().next().unwrap();
    if !first_char.is_ascii_uppercase() {
        return false;
    }

    // Should contain only letters and digits
    s.chars()
        .all(|c| c.is_ascii_alphabetic() || c.is_ascii_digit())
}