ctb_formats_pan/
runtime.rs

1/* SPDX-License-Identifier: MIT */
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7Permission is hereby granted, free of charge, to any person obtaining a copy of
8this software and associated documentation files (the “Software”), to deal in
9the Software without restriction, including without limitation the rights to
10use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11the Software, and to permit persons to whom the Software is furnished to do so,
12subject to the following conditions:
13
14The above copyright notice and this permission notice shall be included in all
15copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23SOFTWARE.
24*/
25
26//! Runtime state for Panorama databases and partial startup execution.
27
28#[allow(
29    unused_imports,
30    clippy::wildcard_imports,
31    reason = "Standard workspace module prelude"
32)]
33use crate::utilities::*;
34
35use std::collections::BTreeMap;
36
37use serde::{Deserialize, Serialize};
38
39use crate::parser::{PanDataRecord, PanDataValue, PanDocument};
40use crate::procedure_parser::{
41    PanExpr, PanProcedureAst, PanStatement, PanVariableScope,
42};
43
44/// Runtime representation of a Panorama value.
45#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
46pub enum PanRuntimeValue {
47    #[default]
48    Empty,
49    String(String),
50    Integer(i64),
51    Float(f64),
52    Boolean(bool),
53    UnresolvedExpression(String),
54}
55
56impl PanRuntimeValue {
57    #[must_use]
58    pub fn as_string(&self) -> String {
59        match self {
60            Self::String(s) => s.clone(),
61            Self::Integer(n) => n.to_string(),
62            Self::Float(f) => f.to_string(),
63            Self::Boolean(b) => {
64                if *b {
65                    "true".to_string()
66                } else {
67                    "false".to_string()
68                }
69            }
70            Self::Empty => String::new(),
71            Self::UnresolvedExpression(s) => s.clone(),
72        }
73    }
74
75    #[must_use]
76    pub fn as_i64(&self) -> i64 {
77        match self {
78            Self::Integer(n) => *n,
79            // Reason for fallback: non-convertible floats coerce to 0 in Panorama runtime
80            Self::Float(f) => {
81                math::approx_float::f64_to_i64_approx(*f).unwrap_or(0)
82            }
83            Self::Boolean(b) => i64::from(*b),
84            // Reason for fallback: unparseable numeric strings coerce to 0 in Panorama runtime
85            Self::String(s) => s.trim().parse::<i64>().unwrap_or(0),
86            Self::Empty | Self::UnresolvedExpression(_) => 0,
87        }
88    }
89
90    #[must_use]
91    pub fn as_f64(&self) -> f64 {
92        match self {
93            Self::Float(f) => *f,
94            // Reason for fallback: integer overflow during float conversion coerces to 0.0 in Panorama runtime
95            Self::Integer(n) => {
96                math::approx_float::i64_to_f64_approx(*n).unwrap_or(0.0)
97            }
98            Self::Boolean(b) => {
99                if *b {
100                    1.0
101                } else {
102                    0.0
103                }
104            }
105            // Reason for fallback: unparseable numeric strings coerce to 0.0 in Panorama runtime
106            Self::String(s) => s.trim().parse::<f64>().unwrap_or(0.0),
107            Self::Empty | Self::UnresolvedExpression(_) => 0.0,
108        }
109    }
110
111    #[must_use]
112    pub fn is_truthy(&self) -> bool {
113        match self {
114            Self::Boolean(b) => *b,
115            Self::Integer(n) => *n != 0,
116            Self::Float(f) => *f != 0.0,
117            Self::String(s) => {
118                let trimmed = s.trim();
119                !trimmed.is_empty()
120                    && trimmed != "0"
121                    && !trimmed.eq_ignore_ascii_case("false")
122            }
123            Self::Empty | Self::UnresolvedExpression(_) => false,
124        }
125    }
126}
127
128/// Data-oriented runtime state derived from the parsed PAN document.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
130pub struct PanRuntimeDataState {
131    pub field_names: Vec<String>,
132    pub record_count: usize,
133    pub current_record_index: Option<usize>,
134}
135
136/// Mutable runtime state for a Panorama database.
137#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
138pub struct PanRuntimeState {
139    pub document: PanDocument,
140    pub data_state: PanRuntimeDataState,
141    pub current_form: Option<String>,
142    pub window_name: Option<String>,
143    pub startup_procedure_name: Option<String>,
144    pub globals: BTreeMap<String, PanRuntimeValue>,
145    pub file_globals: BTreeMap<String, PanRuntimeValue>,
146    pub window_globals: BTreeMap<String, PanRuntimeValue>,
147    pub permanents: BTreeMap<String, PanRuntimeValue>,
148    pub locals: BTreeMap<String, PanRuntimeValue>,
149    pub resources: Vec<String>,
150    pub menu_bar_needs_redraw: bool,
151    pub menu_bar_definition: Option<String>,
152    pub ui_events: Vec<String>,
153}
154
155/// Summary of what happened during startup procedure execution.
156#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
157pub struct PanRuntimeExecutionReport {
158    pub startup_procedure_name: Option<String>,
159    pub executed_procedures: Vec<String>,
160    pub opened_forms: Vec<String>,
161    pub declared_variables: Vec<String>,
162    pub assignments: Vec<String>,
163    pub pending_operations: Vec<String>,
164}
165
166impl PanRuntimeState {
167    /// Parse a PAN file and initialize runtime state from it.
168    pub fn from_pan_bytes(pan_file: &[u8]) -> Result<Self> {
169        let document = crate::parser::parse_pan(pan_file)?;
170        Ok(Self::from_document(document))
171    }
172
173    /// Initialize runtime state from a parsed PAN document.
174    #[must_use]
175    pub fn from_document(document: PanDocument) -> Self {
176        let field_names = match document.schema.as_ref() {
177            Some(schema) => schema
178                .fields
179                .iter()
180                .map(|field| field.name.clone())
181                .collect::<Vec<_>>(),
182            None => Vec::new(),
183        };
184        let record_count = match document.record_count {
185            Some(rc) => rc,
186            None => match document.data.as_ref() {
187                Some(data) => data.records.len(),
188                None => 0,
189            },
190        };
191        let current_record_index =
192            if record_count > 0 { Some(0) } else { None };
193        let startup_procedure_name = find_startup_procedure_name(&document);
194        let current_form = document.launch_form.clone();
195
196        Self {
197            document,
198            data_state: PanRuntimeDataState {
199                field_names,
200                record_count,
201                current_record_index,
202            },
203            current_form,
204            window_name: None,
205            startup_procedure_name,
206            globals: BTreeMap::new(),
207            file_globals: BTreeMap::new(),
208            window_globals: BTreeMap::new(),
209            permanents: BTreeMap::new(),
210            locals: BTreeMap::new(),
211            resources: Vec::new(),
212            menu_bar_needs_redraw: false,
213            menu_bar_definition: None,
214            ui_events: Vec::new(),
215        }
216    }
217
218    /// Returns the parsed startup procedure AST when one is available.
219    #[must_use]
220    pub fn startup_procedure_ast(&self) -> Option<PanProcedureAst> {
221        let procedure_name = self.startup_procedure_name.as_deref()?;
222        self.load_procedure_ast(procedure_name).ok().flatten()
223    }
224
225    /// Execute the startup procedure if the database declares one.
226    pub fn run_startup_procedure(
227        &mut self,
228    ) -> Result<PanRuntimeExecutionReport> {
229        let mut report = PanRuntimeExecutionReport {
230            startup_procedure_name: self.startup_procedure_name.clone(),
231            ..PanRuntimeExecutionReport::default()
232        };
233
234        if let Some(procedure_name) = self.startup_procedure_name.clone() {
235            self.execute_procedure(&procedure_name, &mut report)?;
236        }
237
238        Ok(report)
239    }
240
241    pub fn execute_procedure(
242        &mut self,
243        procedure_name: &str,
244        report: &mut PanRuntimeExecutionReport,
245    ) -> Result<()> {
246        if report
247            .executed_procedures
248            .iter()
249            .any(|existing| existing == procedure_name)
250        {
251            report.pending_operations.push(format!(
252                "Skipping recursive or repeated startup call to procedure {procedure_name}"
253            ));
254            return Ok(());
255        }
256
257        let Some(ast) = self.load_procedure_ast(procedure_name)? else {
258            report.pending_operations.push(format!(
259                "Procedure {procedure_name} has no parsable AST yet"
260            ));
261            return Ok(());
262        };
263
264        report.executed_procedures.push(procedure_name.to_string());
265        self.execute_statements(&ast.statements, report)
266    }
267
268    fn execute_statements(
269        &mut self,
270        statements: &[PanStatement],
271        report: &mut PanRuntimeExecutionReport,
272    ) -> Result<()> {
273        for statement in statements {
274            match statement {
275                PanStatement::VariableDeclaration { scope, names } => {
276                    let scope_vars = self.scope_map_mut(*scope);
277                    for name in names {
278                        scope_vars.entry(name.clone()).or_default();
279                        report
280                            .declared_variables
281                            .push(format!("{scope:?}:{name}"));
282                    }
283                }
284                PanStatement::Assignment { target, value } => {
285                    let evaluated = self.evaluate_expr(value, report);
286                    self.set_variable(target, evaluated);
287                    report.assignments.push(target.clone());
288                }
289                PanStatement::Call {
290                    procedure_name,
291                    arguments: _,
292                } => {
293                    self.execute_procedure(procedure_name, report)?;
294                }
295                PanStatement::Command { name, arguments } => {
296                    self.execute_command(name, arguments, report);
297                }
298                PanStatement::Comment(_) => {}
299                PanStatement::If {
300                    condition,
301                    then_branch,
302                    else_branch,
303                } => {
304                    let cond_val = self.evaluate_expr(condition, report);
305                    if cond_val.is_truthy() {
306                        self.execute_statements(then_branch, report)?;
307                    } else if let Some(else_stmts) = else_branch {
308                        self.execute_statements(else_stmts, report)?;
309                    }
310                }
311                PanStatement::Case {
312                    cases,
313                    default_branch,
314                } => {
315                    let mut matched = false;
316                    for (case_expr, case_body) in cases {
317                        let branch_val = self.evaluate_expr(case_expr, report);
318                        if branch_val.is_truthy() {
319                            self.execute_statements(case_body, report)?;
320                            matched = true;
321                            break;
322                        }
323                    }
324                    if !matched {
325                        if let Some(def_stmts) = default_branch {
326                            self.execute_statements(def_stmts, report)?;
327                        }
328                    }
329                }
330                PanStatement::Loop { kind, body } => {
331                    // Execute loop body with safety limit of 10,000 iterations
332                    let mut iterations = 0usize;
333                    while iterations < 10_000 {
334                        iterations = iterations.saturating_add(1);
335                        self.execute_statements(body, report)?;
336                        match kind {
337                            crate::procedure_parser::PanLoopKind::Infinite => {
338                                break;
339                            }
340                            crate::procedure_parser::PanLoopKind::While(
341                                expr,
342                            ) => {
343                                if !self.evaluate_expr(expr, report).is_truthy()
344                                {
345                                    break;
346                                }
347                            }
348                            crate::procedure_parser::PanLoopKind::Until(
349                                expr,
350                            ) => {
351                                if self.evaluate_expr(expr, report).is_truthy()
352                                {
353                                    break;
354                                }
355                            }
356                            crate::procedure_parser::PanLoopKind::Repeat(
357                                expr,
358                            ) => {
359                                let count = match usize::try_from(
360                                    self.evaluate_expr(expr, report).as_i64(),
361                                ) {
362                                    Ok(c) => c,
363                                    Err(_) => 0,
364                                };
365                                if iterations >= count {
366                                    break;
367                                }
368                            }
369                        }
370                    }
371                }
372            }
373        }
374
375        Ok(())
376    }
377
378    fn execute_command(
379        &mut self,
380        name: &str,
381        arguments: &[PanExpr],
382        report: &mut PanRuntimeExecutionReport,
383    ) {
384        let lower_name = name.to_ascii_lowercase();
385        match lower_name.as_str() {
386            "openform" => {
387                if let Some(first_arg) = arguments.first() {
388                    let form_val = self.evaluate_expr(first_arg, report);
389                    let form_name = form_val.as_string();
390                    if !form_name.is_empty() {
391                        self.current_form = Some(form_name.clone());
392                        report.opened_forms.push(form_name);
393                    }
394                }
395            }
396            "windowname" => {
397                if let Some(first_arg) = arguments.first() {
398                    let val = self.evaluate_expr(first_arg, report);
399                    self.window_name = Some(val.as_string());
400                }
401            }
402            "openresource" => {
403                if let Some(first_arg) = arguments.first() {
404                    let val = self.evaluate_expr(first_arg, report);
405                    self.resources.push(val.as_string());
406                }
407            }
408            "drawmenus" => {
409                self.menu_bar_needs_redraw = true;
410            }
411            "filemenubar" => {
412                if let Some(second_arg) =
413                    arguments.get(1).or_else(|| arguments.first())
414                {
415                    let val = self.evaluate_expr(second_arg, report);
416                    self.menu_bar_definition = Some(val.as_string());
417                    self.menu_bar_needs_redraw = true;
418                }
419            }
420            "showvariables" => {
421                for arg in arguments {
422                    if let PanExpr::Identifier(var_name) = arg {
423                        self.ui_events.push(format!("showvariable:{var_name}"));
424                    }
425                }
426            }
427            "superobject" => {
428                let action = arguments
429                    .iter()
430                    .map(|a| self.evaluate_expr(a, report).as_string())
431                    .collect::<Vec<_>>()
432                    .join(" ");
433                self.ui_events.push(format!("superobject:{action}"));
434            }
435            "object" | "selectobjects" | "changeobjects"
436            | "selectnoobjects" => {
437                let action = arguments
438                    .iter()
439                    .map(|a| self.evaluate_expr(a, report).as_string())
440                    .collect::<Vec<_>>()
441                    .join(" ");
442                self.ui_events.push(format!("{lower_name}:{action}"));
443            }
444            "define" => {
445                if let Some(PanExpr::Identifier(target)) = arguments.first() {
446                    if self.lookup_variable(target).is_none()
447                        || self.lookup_variable(target)
448                            == Some(PanRuntimeValue::Empty)
449                    {
450                        if let Some(val_expr) = arguments.get(1) {
451                            let val = self.evaluate_expr(val_expr, report);
452                            self.set_variable(target, val);
453                        }
454                    }
455                }
456            }
457            "arraybuild" => {
458                if let Some(PanExpr::Identifier(target_var)) = arguments.first()
459                {
460                    let delim = match arguments.get(1) {
461                        Some(e) => self.evaluate_expr(e, report).as_string(),
462                        None => "\n".to_string(),
463                    };
464                    let field_name = match arguments.get(3) {
465                        Some(PanExpr::Identifier(s)) => s.clone(),
466                        Some(other) => {
467                            self.evaluate_expr(other, report).as_string()
468                        }
469                        None => String::new(),
470                    };
471
472                    let mut items = Vec::new();
473                    if let Some(data) = self.document.data.as_ref() {
474                        for record in &data.records {
475                            if let Some(field) =
476                                record.fields.iter().find(|f| {
477                                    f.field_name
478                                        .eq_ignore_ascii_case(&field_name)
479                                })
480                            {
481                                items.push(field.value.to_display_string());
482                            }
483                        }
484                    }
485                    let joined = items.join(&delim);
486                    self.set_variable(
487                        target_var,
488                        PanRuntimeValue::String(joined),
489                    );
490                }
491            }
492            "downrecord" => {
493                if let Some(cur) = self.data_state.current_record_index {
494                    let max = self.data_state.record_count.saturating_sub(1);
495                    self.data_state.current_record_index =
496                        Some(cur.saturating_add(1).min(max));
497                }
498            }
499            "uprecord" => {
500                if let Some(cur) = self.data_state.current_record_index {
501                    self.data_state.current_record_index =
502                        Some(cur.saturating_sub(1));
503                }
504            }
505            "firstrecord" | "toprecord" => {
506                if self.data_state.record_count > 0 {
507                    self.data_state.current_record_index = Some(0);
508                }
509            }
510            "lastrecord" | "bottomrecord" => {
511                if self.data_state.record_count > 0 {
512                    self.data_state.current_record_index =
513                        Some(self.data_state.record_count.saturating_sub(1));
514                }
515            }
516            "gotorecord" => {
517                if let Some(arg) = arguments.first() {
518                    // Reason for fallback: invalid or negative record numbers default to 1st record in Panorama gotorecord command
519                    let rec_num = usize::try_from(
520                        self.evaluate_expr(arg, report).as_i64(),
521                    )
522                    .unwrap_or(1);
523                    if rec_num > 0 && rec_num <= self.data_state.record_count {
524                        self.data_state.current_record_index =
525                            Some(rec_num.saturating_sub(1));
526                    }
527                }
528            }
529            "message" | "statusmessage" | "beep" | "stop" | "rtn" => {
530                let msg = arguments
531                    .iter()
532                    .map(|a| self.evaluate_expr(a, report).as_string())
533                    .collect::<Vec<_>>()
534                    .join(" ");
535                self.ui_events.push(format!("{lower_name}:{msg}"));
536            }
537            _ => {
538                report
539                    .pending_operations
540                    .push(format!("Command {name} logged"));
541            }
542        }
543    }
544
545    pub fn evaluate_expr(
546        &self,
547        expr: &PanExpr,
548        report: &mut PanRuntimeExecutionReport,
549    ) -> PanRuntimeValue {
550        match expr {
551            PanExpr::Pilcrow => PanRuntimeValue::String("\n".to_string()),
552            PanExpr::StringLiteral(value) => {
553                PanRuntimeValue::String(value.clone())
554            }
555            PanExpr::IntegerLiteral(value) => PanRuntimeValue::Integer(*value),
556            PanExpr::FloatLiteral(value) => PanRuntimeValue::Float(*value),
557            PanExpr::Identifier(name) => {
558                if let Some(val) = self.lookup_variable(name) {
559                    val
560                } else if let Some(val) = self.lookup_current_record_field(name)
561                {
562                    val
563                } else {
564                    PanRuntimeValue::String(String::new())
565                }
566            }
567            PanExpr::UnaryOp { op, operand } => {
568                let val = self.evaluate_expr(operand, report);
569                match op {
570                    crate::procedure_parser::PanUnaryOp::Not => {
571                        PanRuntimeValue::Boolean(!val.is_truthy())
572                    }
573                    crate::procedure_parser::PanUnaryOp::Negate => match val {
574                        PanRuntimeValue::Integer(n) => {
575                            PanRuntimeValue::Integer(n.saturating_neg())
576                        }
577                        PanRuntimeValue::Float(f) => PanRuntimeValue::Float(-f),
578                        other => PanRuntimeValue::Float(-other.as_f64()),
579                    },
580                }
581            }
582            PanExpr::BinaryOp { op, left, right } => {
583                let l_val = self.evaluate_expr(left, report);
584                let r_val = self.evaluate_expr(right, report);
585                match op {
586                    crate::procedure_parser::PanBinaryOp::Add => {
587                        if matches!(l_val, PanRuntimeValue::String(_)) || matches!(r_val, PanRuntimeValue::String(_)) {
588                            PanRuntimeValue::String(format!("{}{}", l_val.as_string(), r_val.as_string()))
589                        } else if matches!(l_val, PanRuntimeValue::Float(_)) || matches!(r_val, PanRuntimeValue::Float(_)) {
590                            PanRuntimeValue::Float(l_val.as_f64() + r_val.as_f64())
591                        } else {
592                            PanRuntimeValue::Integer(l_val.as_i64().saturating_add(r_val.as_i64()))
593                        }
594                    }
595                    crate::procedure_parser::PanBinaryOp::Subtract => {
596                        if matches!(l_val, PanRuntimeValue::Float(_)) || matches!(r_val, PanRuntimeValue::Float(_)) {
597                            PanRuntimeValue::Float(l_val.as_f64() - r_val.as_f64())
598                        } else {
599                            PanRuntimeValue::Integer(l_val.as_i64().saturating_sub(r_val.as_i64()))
600                        }
601                    }
602                    crate::procedure_parser::PanBinaryOp::Multiply => {
603                        if matches!(l_val, PanRuntimeValue::Float(_)) || matches!(r_val, PanRuntimeValue::Float(_)) {
604                            PanRuntimeValue::Float(l_val.as_f64() * r_val.as_f64())
605                        } else {
606                            PanRuntimeValue::Integer(l_val.as_i64().saturating_mul(r_val.as_i64()))
607                        }
608                    }
609                    crate::procedure_parser::PanBinaryOp::Divide => {
610                        let r_f = r_val.as_f64();
611                        if r_f == 0.0 {
612                            PanRuntimeValue::Float(0.0)
613                        } else {
614                            PanRuntimeValue::Float(l_val.as_f64() / r_f)
615                        }
616                    }
617                    crate::procedure_parser::PanBinaryOp::Equal => {
618                        PanRuntimeValue::Boolean(l_val.as_string().eq_ignore_ascii_case(&r_val.as_string()))
619                    }
620                    crate::procedure_parser::PanBinaryOp::NotEqual => {
621                        PanRuntimeValue::Boolean(!l_val.as_string().eq_ignore_ascii_case(&r_val.as_string()))
622                    }
623                    crate::procedure_parser::PanBinaryOp::LessThan => {
624                        PanRuntimeValue::Boolean(l_val.as_f64() < r_val.as_f64())
625                    }
626                    crate::procedure_parser::PanBinaryOp::GreaterThan => {
627                        PanRuntimeValue::Boolean(l_val.as_f64() > r_val.as_f64())
628                    }
629                    crate::procedure_parser::PanBinaryOp::LessThanOrEqual => {
630                        PanRuntimeValue::Boolean(l_val.as_f64() <= r_val.as_f64())
631                    }
632                    crate::procedure_parser::PanBinaryOp::GreaterThanOrEqual => {
633                        PanRuntimeValue::Boolean(l_val.as_f64() >= r_val.as_f64())
634                    }
635                    crate::procedure_parser::PanBinaryOp::Contains => {
636                        PanRuntimeValue::Boolean(l_val.as_string().to_ascii_lowercase().contains(&r_val.as_string().to_ascii_lowercase()))
637                    }
638                    crate::procedure_parser::PanBinaryOp::BeginsWith => {
639                        PanRuntimeValue::Boolean(l_val.as_string().to_ascii_lowercase().starts_with(&r_val.as_string().to_ascii_lowercase()))
640                    }
641                    crate::procedure_parser::PanBinaryOp::EndsWith => {
642                        PanRuntimeValue::Boolean(l_val.as_string().to_ascii_lowercase().ends_with(&r_val.as_string().to_ascii_lowercase()))
643                    }
644                    crate::procedure_parser::PanBinaryOp::And => {
645                        PanRuntimeValue::Boolean(l_val.is_truthy() && r_val.is_truthy())
646                    }
647                    crate::procedure_parser::PanBinaryOp::Or => {
648                        PanRuntimeValue::Boolean(l_val.is_truthy() || r_val.is_truthy())
649                    }
650                    crate::procedure_parser::PanBinaryOp::Xor => {
651                        PanRuntimeValue::Boolean(l_val.is_truthy() ^ r_val.is_truthy())
652                    }
653                    _ => PanRuntimeValue::Boolean(false),
654                }
655            }
656            PanExpr::Conditional {
657                condition,
658                true_value,
659                false_value,
660            } => {
661                let cond_val = self.evaluate_expr(condition, report);
662                if cond_val.is_truthy() {
663                    self.evaluate_expr(true_value, report)
664                } else {
665                    self.evaluate_expr(false_value, report)
666                }
667            }
668            PanExpr::FunctionCall { name, arguments } => {
669                self.evaluate_function_call(name, arguments, report)
670            }
671        }
672    }
673
674    fn evaluate_function_call(
675        &self,
676        name: &str,
677        arguments: &[PanExpr],
678        report: &mut PanRuntimeExecutionReport,
679    ) -> PanRuntimeValue {
680        match crate::function_dispatch::dispatch_function_call(
681            self,
682            name,
683            arguments,
684            &mut |expr| self.evaluate_expr(expr, report),
685        ) {
686            Ok(val) => val,
687            Err(err) => {
688                warn_fmt!("Failed evaluating function '{name}': {err}");
689                PanRuntimeValue::Empty
690            }
691        }
692    }
693
694    fn load_procedure_ast(
695        &self,
696        procedure_name: &str,
697    ) -> Result<Option<PanProcedureAst>> {
698        let Some(macro_info) = self
699            .document
700            .macros
701            .iter()
702            .find(|macro_info| macro_info.name == procedure_name)
703        else {
704            return Ok(None);
705        };
706
707        if let Some(ast) = macro_info.ast.clone() {
708            return Ok(Some(ast));
709        }
710
711        if let Some(code) = macro_info.code.as_deref() {
712            let ast = crate::procedure_parser::parse_procedure(code)?;
713            return Ok(Some(ast));
714        }
715
716        Ok(None)
717    }
718
719    fn scope_map_mut(
720        &mut self,
721        scope: PanVariableScope,
722    ) -> &mut BTreeMap<String, PanRuntimeValue> {
723        match scope {
724            PanVariableScope::Local => &mut self.locals,
725            PanVariableScope::Global => &mut self.globals,
726            PanVariableScope::FileGlobal => &mut self.file_globals,
727            PanVariableScope::WindowGlobal => &mut self.window_globals,
728            PanVariableScope::Permanent => &mut self.permanents,
729        }
730    }
731
732    fn set_variable(&mut self, target: &str, value: PanRuntimeValue) {
733        if self.locals.contains_key(target) {
734            self.locals.insert(target.to_string(), value);
735        } else if self.globals.contains_key(target) {
736            self.globals.insert(target.to_string(), value);
737        } else if self.file_globals.contains_key(target) {
738            self.file_globals.insert(target.to_string(), value);
739        } else if self.window_globals.contains_key(target) {
740            self.window_globals.insert(target.to_string(), value);
741        } else if self.permanents.contains_key(target) {
742            self.permanents.insert(target.to_string(), value);
743        } else if self.set_current_record_field(target, &value) {
744            // Field was updated on the current record!
745        } else {
746            self.file_globals.insert(target.to_string(), value);
747        }
748    }
749
750    fn set_current_record_field(
751        &mut self,
752        field_name: &str,
753        value: &PanRuntimeValue,
754    ) -> bool {
755        let Some(idx) = self.data_state.current_record_index else {
756            return false;
757        };
758        let Some(data) = self.document.data.as_mut() else {
759            return false;
760        };
761        let Some(record) = data.records.get_mut(idx) else {
762            return false;
763        };
764        let Some(field) = record
765            .fields
766            .iter_mut()
767            .find(|f| f.field_name.eq_ignore_ascii_case(field_name))
768        else {
769            return false;
770        };
771        let str_val = value.as_string();
772        field.value = PanDataValue::Text(str_val.clone());
773        field.formatted_value = Some(str_val.clone());
774        if let Ok(encoded) = ctb_formats_encoding::encode(
775            ctb_formats_encoding::CharEncoding::mac_roman(),
776            &str_val,
777        ) {
778            field.raw_bytes = encoded;
779        } else {
780            field.raw_bytes = str_val.into_bytes();
781        }
782        true
783    }
784
785    fn lookup_variable(&self, name: &str) -> Option<PanRuntimeValue> {
786        self.locals
787            .get(name)
788            .cloned()
789            .or_else(|| self.globals.get(name).cloned())
790            .or_else(|| self.file_globals.get(name).cloned())
791            .or_else(|| self.window_globals.get(name).cloned())
792            .or_else(|| self.permanents.get(name).cloned())
793    }
794
795    fn lookup_current_record_field(
796        &self,
797        name: &str,
798    ) -> Option<PanRuntimeValue> {
799        let current_record = self.current_record()?;
800        let field = current_record
801            .fields
802            .iter()
803            .find(|field| field.field_name.eq_ignore_ascii_case(name))?;
804        Some(runtime_value_from_field(&field.value))
805    }
806
807    fn current_record(&self) -> Option<&PanDataRecord> {
808        let data = self.document.data.as_ref()?;
809        let index = self.data_state.current_record_index?;
810        data.records.get(index)
811    }
812}
813
814fn find_startup_procedure_name(document: &PanDocument) -> Option<String> {
815    document
816        .macros
817        .iter()
818        .find(|macro_info| {
819            macro_info.is_procedure
820                && macro_info.name.eq_ignore_ascii_case(".Initialize")
821        })
822        .map(|macro_info| macro_info.name.clone())
823}
824
825fn runtime_value_from_field(value: &PanDataValue) -> PanRuntimeValue {
826    match value {
827        PanDataValue::Text(text) => PanRuntimeValue::String(text.clone()),
828        PanDataValue::Integer(number) => match number.parse::<i64>() {
829            Ok(n) => PanRuntimeValue::Integer(n),
830            Err(_) => PanRuntimeValue::String(number.clone()),
831        },
832        PanDataValue::Fixed(number) | PanDataValue::Float(number) => {
833            match number.parse::<f64>() {
834                Ok(f) => PanRuntimeValue::Float(f),
835                Err(_) => PanRuntimeValue::String(number.clone()),
836            }
837        }
838        PanDataValue::Date { pan_date_mdy, .. } => match pan_date_mdy {
839            Some(value) => PanRuntimeValue::String(value.clone()),
840            None => PanRuntimeValue::String(String::new()),
841        },
842        PanDataValue::Unknown(text) => PanRuntimeValue::String(text.clone()),
843    }
844}
845
846#[cfg(test)]
847#[allow(
848    clippy::panic,
849    clippy::expect_used,
850    clippy::unwrap_used,
851    clippy::unwrap_in_result,
852    clippy::panic_in_result_fn,
853    clippy::indexing_slicing,
854    clippy::arithmetic_side_effects,
855    reason = "Standard repository test boilerplate"
856)]
857mod tests {
858    use super::*;
859
860    use crate::parser::{
861        PanCapitalization, PanData, PanDataFieldValue, PanDataRecord,
862        PanFieldType, PanJustification, PanMacroInfo, PanPrelude, PanSchema,
863        PanSchemaField, PanSection,
864    };
865
866    fn sample_document() -> PanDocument {
867        let setup_ast = PanProcedureAst {
868            statements: vec![
869                PanStatement::VariableDeclaration {
870                    scope: PanVariableScope::Global,
871                    names: vec!["currentTopic".to_string()],
872                },
873                PanStatement::Assignment {
874                    target: "currentTopic".to_string(),
875                    value: PanExpr::Identifier("Topic".to_string()),
876                },
877            ],
878        };
879        let initialize_ast = PanProcedureAst {
880            statements: vec![
881                PanStatement::VariableDeclaration {
882                    scope: PanVariableScope::Permanent,
883                    names: vec!["dbName".to_string()],
884                },
885                PanStatement::Assignment {
886                    target: "dbName".to_string(),
887                    value: PanExpr::StringLiteral(
888                        "Programming Reference".to_string(),
889                    ),
890                },
891                PanStatement::Call {
892                    procedure_name: ".Setup".to_string(),
893                    arguments: Vec::new(),
894                },
895                PanStatement::Command {
896                    name: "openform".to_string(),
897                    arguments: vec![PanExpr::StringLiteral(
898                        "Reference".to_string(),
899                    )],
900                },
901                PanStatement::Command {
902                    name: "drawmenus".to_string(),
903                    arguments: Vec::new(),
904                },
905            ],
906        };
907
908        PanDocument {
909            prelude: PanPrelude {
910                first_u32_le: 0,
911                entries: Vec::new(),
912                raw_bytes: Vec::new(),
913            },
914            sections: vec![PanSection {
915                offset: 0,
916                declared_size: 0,
917                kind: 0,
918                name_raw: b"LAUNCH".to_vec(),
919                name: "LAUNCH".to_string(),
920                payload: Vec::new(),
921            }],
922            schema: Some(PanSchema {
923                names_section_offset: 0,
924                widths_section_offset: 0,
925                types_section_offset: 0,
926                fields: vec![PanSchemaField {
927                    index: 0,
928                    name: "Topic".to_string(),
929                    width: 32,
930                    type_code: 0,
931                    type_label: "Text".to_string(),
932                    field_type: PanFieldType::Text,
933                    output_pattern: None,
934                    formula: None,
935                    default_value: None,
936                    prompt: None,
937                    link: None,
938                    range: None,
939                    digits: 0,
940                    justification: PanJustification::Left,
941                    clairvoyance: false,
942                    capitalization: PanCapitalization::None,
943                }],
944            }),
945            data: Some(PanData {
946                sections: Vec::new(),
947                records: vec![PanDataRecord {
948                    index: 0,
949                    section_offset: 0,
950                    declared_size: 0,
951                    fields: vec![PanDataFieldValue {
952                        field_index: 0,
953                        field_name: "Topic".to_string(),
954                        field_type: PanFieldType::Text,
955                        type_label: "Text".to_string(),
956                        output_pattern: None,
957                        formula: None,
958                        raw_bytes: b"Intro".to_vec(),
959                        value: PanDataValue::Text("Intro".to_string()),
960                        formatted_value: None,
961                    }],
962                    trailing_bytes: Vec::new(),
963                }],
964                parse_warnings: Vec::new(),
965            }),
966            launch_form: Some("Splash".to_string()),
967            record_count: Some(1),
968            macros: vec![
969                PanMacroInfo {
970                    name: ".Initialize".to_string(),
971                    size: 0,
972                    is_procedure: true,
973                    code: None,
974                    ast: Some(initialize_ast),
975                    payload: Vec::new(),
976                },
977                PanMacroInfo {
978                    name: ".Setup".to_string(),
979                    size: 0,
980                    is_procedure: true,
981                    code: None,
982                    ast: Some(setup_ast),
983                    payload: Vec::new(),
984                },
985            ],
986            trailing_bytes: Vec::new(),
987        }
988    }
989
990    #[crate::ctb_test]
991    fn runtime_initializes_from_document() -> Result<()> {
992        let runtime = PanRuntimeState::from_document(sample_document());
993
994        ensure!(runtime.current_form.as_deref() == Some("Splash"));
995        ensure!(
996            runtime.startup_procedure_name.as_deref() == Some(".Initialize")
997        );
998        ensure!(runtime.data_state.record_count == 1);
999        ensure!(runtime.data_state.field_names == vec!["Topic".to_string()]);
1000        ensure!(runtime.startup_procedure_ast().is_some());
1001        Ok(())
1002    }
1003
1004    #[crate::ctb_test]
1005    fn runtime_executes_supported_startup_flow() -> Result<()> {
1006        let mut runtime = PanRuntimeState::from_document(sample_document());
1007        let report = runtime.run_startup_procedure()?;
1008
1009        ensure!(
1010            report.executed_procedures
1011                == vec![".Initialize".to_string(), ".Setup".to_string(),]
1012        );
1013        ensure!(report.opened_forms == vec!["Reference".to_string()]);
1014        ensure!(report.pending_operations.is_empty());
1015        ensure!(runtime.current_form.as_deref() == Some("Reference"));
1016        ensure!(runtime.menu_bar_needs_redraw);
1017        ensure!(
1018            runtime.permanents.get("dbName")
1019                == Some(&PanRuntimeValue::String(
1020                    "Programming Reference".to_string()
1021                ))
1022        );
1023        ensure!(
1024            runtime.globals.get("currentTopic")
1025                == Some(&PanRuntimeValue::String("Intro".to_string()))
1026        );
1027        Ok(())
1028    }
1029}