Skip to main content

runmat_core/session/
mod.rs

1use anyhow::Result;
2use runmat_builtins::{self, Type, Value};
3use runmat_gc::{gc_configure, gc_stats, GcConfig};
4use tracing::{debug, info, info_span, warn};
5
6use runmat_hir::{LoweringContext, LoweringResult, SourceId};
7use runmat_lexer::{tokenize_detailed, Token as LexToken};
8use runmat_parser::{parse_with_options, ParserOptions};
9use runmat_runtime::{build_runtime_error, gather_if_needed_async, RuntimeError};
10use runmat_runtime::{
11    runtime_export_workspace_state, runtime_import_workspace_state, WorkspaceReplayMode,
12};
13#[cfg(target_arch = "wasm32")]
14use runmat_snapshot::SnapshotBuilder;
15use runmat_snapshot::{Snapshot, SnapshotConfig, SnapshotLoader};
16use runmat_time::Instant;
17#[cfg(feature = "jit")]
18use runmat_turbine::TurbineEngine;
19use std::collections::{HashMap, HashSet};
20use std::future::Future;
21#[cfg(not(target_arch = "wasm32"))]
22use std::path::Path;
23use std::sync::{
24    atomic::{AtomicBool, Ordering},
25    Arc, Mutex,
26};
27use uuid::Uuid;
28
29use crate::execution::{
30    ExecutionResult, ExecutionStats, ExecutionStreamEntry, ExecutionStreamKind, InputRequest,
31    InputRequestKind, InputResponse, SharedAsyncInputHandler, StdinEvent, StdinEventKind,
32};
33use crate::fusion::{build_fusion_snapshot, FusionPlanSnapshot};
34use crate::profiling::{gather_profiling, reset_provider_telemetry};
35use crate::source_pool::{line_col_from_offset, SourcePool};
36use crate::telemetry::{TelemetryPlatformInfo, TelemetrySink};
37use crate::workspace::{
38    determine_display_label_from_context, format_type_info, gather_gpu_preview_values,
39    gpu_dtype_label, gpu_size_bytes, last_displayable_statement_emit_disposition,
40    last_emit_var_index, last_expr_emits_value, last_unsuppressed_assign_var,
41    slice_value_for_preview, workspace_entry, FinalStmtEmitDisposition, MaterializedVariable,
42    WorkspaceEntry, WorkspaceExportMode, WorkspaceMaterializeOptions, WorkspaceMaterializeTarget,
43    WorkspacePreview, WorkspaceResidency, WorkspaceSnapshot, MATERIALIZE_DEFAULT_LIMIT,
44};
45use crate::{
46    approximate_size_bytes, matlab_class_name, numeric_dtype_label, preview_numeric_values,
47    value_shape, CompatMode, RunError,
48};
49
50mod compile;
51mod config;
52mod run;
53mod snapshot;
54mod workspace;
55
56/// Host-agnostic RunMat execution session (parser + interpreter + optional JIT).
57pub struct RunMatSession {
58    /// JIT compiler engine (optional for fallback mode)
59    #[cfg(feature = "jit")]
60    jit_engine: Option<TurbineEngine>,
61    /// Verbose output for debugging
62    verbose: bool,
63    /// Execution statistics
64    stats: ExecutionStats,
65    /// Persistent variable context for session state
66    variables: HashMap<String, Value>,
67    /// Current variable array for bytecode execution
68    variable_array: Vec<Value>,
69    /// Mapping from variable names to VarId indices
70    variable_names: HashMap<String, usize>,
71    /// Persistent workspace values keyed by variable name
72    workspace_values: HashMap<String, Value>,
73    /// User-defined functions context for session state
74    function_definitions: HashMap<String, runmat_hir::HirStmt>,
75    /// Interned source pool for user-defined functions
76    source_pool: SourcePool,
77    /// Source IDs for user-defined functions keyed by name
78    function_source_ids: HashMap<String, SourceId>,
79    /// Loaded snapshot for standard library preloading
80    snapshot: Option<Arc<Snapshot>>,
81    /// Cooperative cancellation flag shared with the runtime.
82    interrupt_flag: Arc<AtomicBool>,
83    /// Tracks whether an execution is currently active.
84    is_executing: bool,
85    /// Optional async input handler (Phase 2). When set, stdin interactions are awaited
86    /// internally by `ExecuteFuture` rather than being surfaced as "pending requests".
87    async_input_handler: Option<SharedAsyncInputHandler>,
88    /// Maximum number of call stack frames to retain for diagnostics.
89    callstack_limit: usize,
90    /// Namespace prefix for runtime/semantic error identifiers.
91    error_namespace: String,
92    /// Default source name used for diagnostics.
93    default_source_name: String,
94    /// Override source name for the current execution.
95    source_name_override: Option<String>,
96    pub(crate) telemetry_consent: bool,
97    pub(crate) telemetry_client_id: Option<String>,
98    pub(crate) telemetry_platform: TelemetryPlatformInfo,
99    pub(crate) telemetry_sink: Option<Arc<dyn TelemetrySink>>,
100    workspace_preview_tokens: HashMap<Uuid, WorkspaceMaterializeTicket>,
101    workspace_version: u64,
102    emit_fusion_plan: bool,
103    compat_mode: CompatMode,
104}
105
106pub(crate) struct PreparedExecution {
107    ast: runmat_parser::Program,
108    lowering: LoweringResult,
109    bytecode: runmat_vm::Bytecode,
110}
111
112#[derive(Debug, Clone)]
113struct WorkspaceMaterializeTicket {
114    name: String,
115}
116
117struct ActiveExecutionGuard {
118    flag: *mut bool,
119}
120
121impl ActiveExecutionGuard {
122    fn new(session: &mut RunMatSession) -> Result<Self> {
123        if session.is_executing {
124            Err(anyhow::anyhow!(
125                "RunMatSession is already executing another script"
126            ))
127        } else {
128            session.is_executing = true;
129            Ok(Self {
130                flag: &mut session.is_executing,
131            })
132        }
133    }
134}
135
136impl Drop for ActiveExecutionGuard {
137    fn drop(&mut self) {
138        unsafe {
139            if let Some(flag) = self.flag.as_mut() {
140                *flag = false;
141            }
142        }
143    }
144}
145
146impl Default for RunMatSession {
147    fn default() -> Self {
148        Self::new().expect("Failed to create default RunMat session")
149    }
150}