1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
// ShapeError carries location info for good diagnostics, making it larger than clippy's threshold.
#![allow(clippy::result_large_err)]
//! Runtime module for Shape execution
//!
//! This module contains the pattern matching engine, query executor,
//! and evaluation logic for the Shape language.
//!
//! Shape is a general-purpose scientific computing language for high-speed
//! time-series analysis. The runtime is domain-agnostic - all domain-specific
//! logic (finance, IoT, sensors, etc.) belongs in stdlib modules.
// Import from shape-value (moved there to break circular dependency)
pub use shape_value::AlignedVec;
pub mod alerts;
pub mod annotation_context;
pub mod arrow_c;
pub mod ast_extensions;
pub mod binary_reader;
pub mod blob_prefetch;
pub mod blob_store;
pub mod blob_wire_format;
pub mod builtin_metadata;
pub mod chart_detect;
pub mod closure;
pub mod code_search;
pub mod columnar_aggregations;
pub mod const_eval;
pub mod content_builders;
pub mod content_dispatch;
pub mod content_methods;
pub mod content_renderer;
pub mod context;
pub mod crypto;
pub mod data;
pub mod dependency_resolver;
pub mod distributed_gc;
pub mod doc_extract;
pub mod engine;
pub mod event_queue;
pub mod execution_proof;
pub mod extension_context;
pub mod extensions;
pub mod extensions_config;
pub mod frontmatter;
pub mod fuzzy;
pub mod fuzzy_property;
pub mod hashing;
pub mod intrinsics;
pub mod json_value;
pub mod marshal;
pub mod leakage;
pub mod lookahead_guard;
pub mod metadata;
pub mod module_bindings;
pub mod module_exports;
pub mod typed_module_exports;
pub mod module_loader;
pub mod module_manifest;
pub mod multi_table;
pub mod multiple_testing;
pub mod native_resolution;
pub mod output_adapter;
pub mod print_result;
pub mod package_bundle;
pub mod package_lock;
pub mod pattern_library;
pub mod plugins;
pub mod progress;
pub mod project;
#[cfg(all(test, feature = "deep-tests"))]
mod project_deep_tests;
pub mod provider_registry;
pub mod query_builder;
pub mod query_executor;
pub mod query_result;
pub mod renderers;
pub mod schema_cache;
pub mod schema_inference;
pub mod simd_comparisons;
pub mod simd_forward_fill;
pub mod simd_i64;
pub mod simd_rolling;
pub mod simd_statistics;
pub mod snapshot;
// state_diff.rs was deleted in Phase 2b — its 1486 LoC of ValueWord-typed
// value-diff/patch logic depends on the deleted ValueWord type and tag_bits.
// The replacement (kind-threaded slot diff/patch) is part of the strict-typed
// snapshot rebuild that follows Phase 2b's wire/snapshot foundation.
pub mod statistics;
pub mod stdlib;
pub mod stdlib_io;
pub mod stdlib_metadata;
pub mod stdlib_time;
pub mod sync_bridge;
pub mod time_window;
pub mod timeframe_utils;
pub mod type_mapping;
pub mod type_methods;
pub mod type_schema;
pub mod type_system;
pub mod visitor;
pub mod window_manager;
pub mod wire_conversion;
// Export commonly used types
pub use alerts::{Alert, AlertRouter, AlertSeverity, AlertSink};
pub use context::{DataLoadMode, ExecutionContext as Context};
pub use data::DataFrame;
pub use data::OwnedDataRow as RowValue;
pub use event_queue::{
EventQueue, MemoryEventQueue, QueuedEvent, SharedEventQueue, SuspensionState, WaitCondition,
create_event_queue,
};
pub use extensions::{
ExtensionCapability, ExtensionDataSource, ExtensionLoader, ExtensionOutputSink,
LoadedExtension, ParsedOutputField, ParsedOutputSchema, ParsedQueryParam, ParsedQuerySchema,
};
pub use extensions_config::{
ExtensionEntry as GlobalExtensionEntry, ExtensionsConfig as GlobalExtensionsConfig,
load_extensions_config, load_extensions_config_from,
};
pub use hashing::{HashDigest, combine_hashes, hash_bytes, hash_file, hash_string};
pub use intrinsics::{IntrinsicFn, IntrinsicsRegistry};
pub use leakage::{LeakageDetector, LeakageReport, LeakageSeverity, LeakageType, LeakageWarning};
pub use module_bindings::ModuleBindingRegistry;
pub use module_exports::{
FrameInfo, ModuleContext, ModuleExportRegistry, ModuleExports, ModuleFn, VmStateAccessor,
};
pub use multiple_testing::{MultipleTestingGuard, MultipleTestingStats, WarningLevel};
pub use progress::{
LoadPhase, ProgressEvent, ProgressGranularity, ProgressHandle, ProgressRegistry,
};
pub use query_result::{AlertResult, QueryResult, QueryType};
pub use sync_bridge::{
SyncDataProvider, block_on_shared, get_runtime_handle, initialize_shared_runtime,
};
pub use type_schema::{
FieldDef, FieldType, SchemaId, TypeSchema, TypeSchemaBuilder, TypeSchemaRegistry,
};
pub use wire_conversion::{
slot_extract_content, slot_to_envelope, slot_to_wire, wire_to_slot,
};
use self::type_methods::TypeMethodRegistry;
pub use error::{Result, ShapeError, SourceLocation};
use shape_ast::ast::Program;
pub use shape_ast::error;
use shape_wire::WireValue;
use std::any::Any;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::OnceLock;
use std::sync::RwLock;
use std::time::Duration;
/// The main runtime engine for Shape
pub struct Runtime {
/// Module loader for .shape files
module_loader: module_loader::ModuleLoader,
/// Persistent execution context for REPL
persistent_context: Option<context::ExecutionContext>,
/// Shared type method registry for user-defined methods
type_method_registry: Arc<TypeMethodRegistry>,
/// Registry for annotation definitions (`annotation warmup() { ... }`, etc.)
annotation_registry: Arc<RwLock<annotation_context::AnnotationRegistry>>,
/// Module binding registry shared with VM/JIT execution pipelines.
module_binding_registry: Arc<RwLock<module_bindings::ModuleBindingRegistry>>,
/// Per-runtime type schema registry.
///
/// Owns its own schema-ID counter + stdlib schemas; replaces the
/// process-global `STDLIB_SCHEMA_REGISTRY` + `NEXT_SCHEMA_ID` statics
/// that were retired in B1.7. Stored as `Arc<_>` so execution entry
/// points can cheaply install it as the task-local / thread-local
/// ambient registry ([`type_schema::current`]); mutations through
/// [`Runtime::schema_registry_mut`] use `Arc::make_mut` (copy-on-write
/// when the registry has already been scoped elsewhere).
pub schema_registry: Arc<type_schema::TypeSchemaRegistry>,
/// Debug mode flag — enables verbose logging/tracing when true
debug_mode: bool,
/// Execution timeout — the executor can check elapsed time against this
execution_timeout: Option<Duration>,
/// Memory limit in bytes — allocation tracking can reference this
memory_limit: Option<usize>,
/// Last structured runtime error payload produced by execution.
///
/// Hosts can consume this to render AnyError with target-specific
/// renderers (ANSI/HTML/plain) without parsing flat strings.
last_runtime_error: Option<WireValue>,
/// Optional blob store for content-addressed function blobs.
blob_store: Option<Arc<dyn crate::blob_store::BlobStore>>,
/// Optional keychain for module signature verification.
keychain: Option<crate::crypto::keychain::Keychain>,
/// Per-runtime cache of parsed extension module schemas.
///
/// Replaces the former process-global extension-schema static. Shared
/// through an `Arc` so execution entry points that load extensions can
/// hand the same cache to
/// [`extension_context::extension_module_schema_for_spec`] /
/// [`extension_context::register_declared_extensions_in_loader`].
extension_module_schemas: Arc<extension_context::ExtensionModuleSchemaCache>,
/// Per-runtime cache for the compiled core stdlib `BytecodeProgram`.
///
/// Replaces the legacy process-global `CORE_STDLIB_CACHE` static in
/// `shape-vm`. Populated lazily by `shape_vm::stdlib::get_core_stdlib`
/// on first use. Held as `OnceLock<Arc<dyn Any + Send + Sync>>` because
/// `shape-runtime` does not depend on `shape-vm` and therefore cannot
/// name `BytecodeProgram` directly; `shape-vm` wraps the compiled
/// result in `Arc<Result<BytecodeProgram>>` and downcasts on read.
core_stdlib_cache: OnceLock<Arc<dyn Any + Send + Sync>>,
}
impl Default for Runtime {
fn default() -> Self {
Self::new()
}
}
impl Runtime {
/// Create a new runtime instance
pub fn new() -> Self {
Self::new_internal(true)
}
pub(crate) fn new_without_stdlib() -> Self {
Self::new_internal(false)
}
fn new_internal(_load_stdlib: bool) -> Self {
let module_loader = module_loader::ModuleLoader::new();
let module_binding_registry =
Arc::new(RwLock::new(module_bindings::ModuleBindingRegistry::new()));
Self {
module_loader,
persistent_context: None,
type_method_registry: Arc::new(TypeMethodRegistry::new()),
annotation_registry: Arc::new(RwLock::new(
annotation_context::AnnotationRegistry::new(),
)),
module_binding_registry,
schema_registry: Arc::new(type_schema::TypeSchemaRegistry::new_with_stdlib()),
debug_mode: false,
execution_timeout: None,
memory_limit: None,
last_runtime_error: None,
blob_store: None,
keychain: None,
extension_module_schemas: Arc::new(
extension_context::ExtensionModuleSchemaCache::new(),
),
core_stdlib_cache: OnceLock::new(),
}
}
/// Borrow this runtime's extension module schema cache.
pub fn extension_module_schemas(
&self,
) -> &Arc<extension_context::ExtensionModuleSchemaCache> {
&self.extension_module_schemas
}
pub fn annotation_registry(&self) -> Arc<RwLock<annotation_context::AnnotationRegistry>> {
self.annotation_registry.clone()
}
pub fn enable_persistent_context(&mut self, data: &DataFrame) {
self.persistent_context = Some(context::ExecutionContext::new_with_registry(
data,
self.type_method_registry.clone(),
));
}
pub fn enable_persistent_context_without_data(&mut self) {
self.persistent_context = Some(context::ExecutionContext::new_empty_with_registry(
self.type_method_registry.clone(),
));
}
pub fn set_persistent_context(&mut self, ctx: context::ExecutionContext) {
self.persistent_context = Some(ctx);
}
pub fn persistent_context(&self) -> Option<&context::ExecutionContext> {
self.persistent_context.as_ref()
}
pub fn persistent_context_mut(&mut self) -> Option<&mut context::ExecutionContext> {
self.persistent_context.as_mut()
}
/// Store the last structured runtime error payload.
pub fn set_last_runtime_error(&mut self, payload: Option<WireValue>) {
self.last_runtime_error = payload;
}
/// Clear any stored structured runtime error payload.
pub fn clear_last_runtime_error(&mut self) {
self.last_runtime_error = None;
}
/// Borrow the last structured runtime error payload.
pub fn last_runtime_error(&self) -> Option<&WireValue> {
self.last_runtime_error.as_ref()
}
/// Take the last structured runtime error payload.
pub fn take_last_runtime_error(&mut self) -> Option<WireValue> {
self.last_runtime_error.take()
}
pub fn type_method_registry(&self) -> &Arc<TypeMethodRegistry> {
&self.type_method_registry
}
/// Borrow the per-runtime type schema registry.
///
/// During the B1 migration window this accessor is informational — most
/// decode / wire / printing / executor call sites still consult the
/// process-global statics. Track B1 threads `&runtime.schema_registry`
/// through those call sites and deletes the statics in B1.6.
pub fn schema_registry(&self) -> &type_schema::TypeSchemaRegistry {
&self.schema_registry
}
/// Mutable access to the per-runtime type schema registry.
///
/// Uses `Arc::make_mut` — if the registry has been cloned elsewhere
/// (e.g. installed as the current async-scope ambient registry), this
/// performs a copy-on-write clone so the mutation is visible only on
/// this `Runtime`. Callers that want the mutation to be visible
/// through a live ambient handle must install the new Arc themselves.
pub fn schema_registry_mut(&mut self) -> &mut type_schema::TypeSchemaRegistry {
Arc::make_mut(&mut self.schema_registry)
}
/// Clone the `Arc<TypeSchemaRegistry>` for installation as the current
/// ambient registry (see [`type_schema::current`]).
pub fn schema_registry_arc(&self) -> Arc<type_schema::TypeSchemaRegistry> {
self.schema_registry.clone()
}
/// Install this runtime's schema registry as the current synchronous
/// ambient registry for the returned guard's lifetime.
///
/// Synchronous execution entry points (CLI scripts, tests, REPL
/// one-shots) should hold the guard for the duration of execution so
/// any code path that consults [`type_schema::current_registry`]
/// observes this runtime's registry instead of reaching for the legacy
/// process-global statics.
pub fn enter_schema_scope(&self) -> type_schema::SyncRegistryScope {
type_schema::SyncRegistryScope::enter(self.schema_registry_arc())
}
/// Get the module-binding registry shared with VM/JIT execution.
pub fn module_binding_registry(&self) -> Arc<RwLock<module_bindings::ModuleBindingRegistry>> {
self.module_binding_registry.clone()
}
/// Lazily initialize and return the core stdlib cache payload.
///
/// `shape-runtime` cannot name `BytecodeProgram`, so the payload is
/// stored type-erased. Callers in `shape-vm` pass a closure that
/// produces an `Arc<T>` (typically `Arc<Result<BytecodeProgram>>`);
/// on read the returned `Arc<dyn Any>` is downcast back to `Arc<T>`.
///
/// Panics if a subsequent call requests a different concrete `T` on
/// the same `Runtime` — the cache is single-typed per runtime.
pub fn get_or_init_core_stdlib_cache<T, F>(&self, init: F) -> Arc<T>
where
T: Any + Send + Sync + 'static,
F: FnOnce() -> Arc<T>,
{
let entry = self
.core_stdlib_cache
.get_or_init(|| init() as Arc<dyn Any + Send + Sync>);
entry
.clone()
.downcast::<T>()
.expect("core_stdlib_cache type mismatch: already initialized with a different type")
}
/// Add a module search path for imports
///
/// This is useful when executing scripts - add the script's directory
/// to the module search paths for resolution.
pub fn add_module_path(&mut self, path: PathBuf) {
self.module_loader.add_module_path(path);
}
/// Set the keychain for module signature verification.
///
/// Propagates to the module loader so it can verify module signatures
/// at load time.
pub fn set_keychain(&mut self, keychain: crate::crypto::keychain::Keychain) {
self.keychain = Some(keychain.clone());
self.module_loader.set_keychain(keychain);
}
/// Set the blob store for content-addressed function blobs.
///
/// Propagates to the module loader so it can lazily fetch blobs
/// not found in inline caches.
pub fn set_blob_store(&mut self, store: Arc<dyn crate::blob_store::BlobStore>) {
self.blob_store = Some(store.clone());
self.module_loader.set_blob_store(store);
}
/// Set the project root and prepend its configured module paths
pub fn set_project_root(&mut self, root: &std::path::Path, extra_paths: &[PathBuf]) {
self.module_loader.set_project_root(root, extra_paths);
}
/// Set resolved dependency paths for the module loader
pub fn set_dependency_paths(
&mut self,
deps: std::collections::HashMap<String, std::path::PathBuf>,
) {
self.module_loader.set_dependency_paths(deps);
}
/// Get the resolved dependency paths from the module loader.
pub fn get_dependency_paths(&self) -> &std::collections::HashMap<String, std::path::PathBuf> {
self.module_loader.get_dependency_paths()
}
/// Register extension-provided module artifacts into the unified module loader.
pub fn register_extension_module_artifacts(
&mut self,
modules: &[crate::extensions::ParsedModuleSchema],
) {
for module in modules {
for artifact in &module.artifacts {
let code = match (&artifact.source, &artifact.compiled) {
(Some(source), Some(compiled)) => module_loader::ModuleCode::Both {
source: Arc::from(source.as_str()),
compiled: Arc::from(compiled.clone()),
},
(Some(source), None) => {
module_loader::ModuleCode::Source(Arc::from(source.as_str()))
}
(None, Some(compiled)) => {
module_loader::ModuleCode::Compiled(Arc::from(compiled.clone()))
}
(None, None) => continue,
};
self.module_loader
.register_extension_module(artifact.module_path.clone(), code);
}
}
}
/// Build a fresh module loader with the same search/dependency settings.
///
/// This is used by external executors (VM/JIT) so import resolution stays
/// aligned with runtime configuration.
pub fn configured_module_loader(&self) -> module_loader::ModuleLoader {
let mut loader = self.module_loader.clone_without_cache();
if let Some(ref store) = self.blob_store {
loader.set_blob_store(store.clone());
}
if let Some(ref kc) = self.keychain {
loader.set_keychain(kc.clone());
}
loader
}
/// Load `std::core::*` modules via the unified module loader and register them in runtime context.
///
/// This is the canonical stdlib bootstrap path used by the engine and CLI.
pub fn load_core_stdlib_into_context(&mut self, data: &DataFrame) -> Result<()> {
let module_paths = self.module_loader.list_core_stdlib_module_imports()?;
for module_path in module_paths {
// Skip the prelude module — it contains re-export imports that reference
// non-exported symbols (traits, constants). Prelude injection is handled
// separately by the graph-based compilation pipeline in the bytecode executor.
if module_path == "std::core::prelude" {
continue;
}
let resolved = self.module_loader.resolve_module_path(&module_path).ok();
let context_dir = resolved
.as_ref()
.and_then(|path| path.parent().map(|p| p.to_path_buf()));
let module = self.module_loader.load_module(&module_path)?;
self.load_program_with_context(&module.ast, data, context_dir.as_ref())?;
}
Ok(())
}
pub fn load_program(&mut self, program: &Program, data: &DataFrame) -> Result<()> {
self.load_program_with_context(program, data, None)
}
pub(crate) fn load_program_with_context(
&mut self,
program: &Program,
data: &DataFrame,
context_dir: Option<&PathBuf>,
) -> Result<()> {
let mut persistent_ctx = self.persistent_context.take();
let result = if let Some(ref mut ctx) = persistent_ctx {
if data.row_count() > 0 {
ctx.update_data(data);
}
self.process_program_items(program, ctx, context_dir)
} else {
let mut ctx = context::ExecutionContext::new_with_registry(
data,
self.type_method_registry.clone(),
);
self.process_program_items(program, &mut ctx, context_dir)
};
self.persistent_context = persistent_ctx;
result
}
fn process_program_items(
&mut self,
program: &Program,
ctx: &mut context::ExecutionContext,
context_dir: Option<&PathBuf>,
) -> Result<()> {
for item in &program.items {
match item {
shape_ast::ast::Item::Import(import, _) => {
let module = self
.module_loader
.load_module_with_context(&import.from, context_dir)?;
match &import.items {
shape_ast::ast::ImportItems::Named(imports) => {
for import_spec in imports {
if let Some(export) = module.exports.get(&import_spec.name) {
if import_spec.is_annotation {
continue;
}
let var_name =
import_spec.alias.as_ref().unwrap_or(&import_spec.name);
match export {
module_loader::Export::Function(_) => {
// Function exports are registered by the VM
}
module_loader::Export::Value(value) => {
if ctx.get_variable(var_name)?.is_none() {
ctx.set_variable(var_name, value.clone())?;
}
self.module_binding_registry
.write()
.unwrap()
.register_const(var_name, value.clone())?;
}
_ => {}
}
} else {
return Err(ShapeError::ModuleError {
message: format!(
"Export '{}' not found in module '{}'",
import_spec.name, import.from
),
module_path: Some(import.from.clone().into()),
});
}
}
}
shape_ast::ast::ImportItems::Namespace { .. } => {
// Namespace imports for extension modules are handled by the VM
}
}
}
shape_ast::ast::Item::Export(export, _) => {
match &export.item {
shape_ast::ast::ExportItem::Function(_) => {
// Function exports are registered by the VM
}
shape_ast::ast::ExportItem::BuiltinFunction(_)
| shape_ast::ast::ExportItem::BuiltinType(_)
| shape_ast::ast::ExportItem::Annotation(_) => {}
shape_ast::ast::ExportItem::Named(specs) => {
// For `pub { name1, name2 }` re-exports of names
// defined earlier in the module, verify each name
// exists. For `pub const/let/var X = ...` (the
// ExportStmt carries the source VariableDecl), the
// bytecode compiler handles the initialization at
// a later pass; the runtime loader should NOT pre-
// check existence here.
if export.source_decl.is_none() {
for spec in specs {
if let Ok(value) = ctx.get_variable(&spec.name) {
if value.is_none() {
return Err(ShapeError::RuntimeError {
message: format!(
"Cannot export undefined variable '{}'",
spec.name
),
location: None,
});
}
}
}
}
}
shape_ast::ast::ExportItem::TypeAlias(alias_def) => {
let overrides = HashMap::new();
if let Some(ref overrides_ast) = alias_def.meta_param_overrides {
for (_key, _expr) in overrides_ast {
// TODO: Use const_eval for simple literal evaluation
}
}
let base_type = match &alias_def.type_annotation {
shape_ast::ast::TypeAnnotation::Basic(n) => n.clone(),
shape_ast::ast::TypeAnnotation::Reference(n) => n.to_string(),
_ => "any".to_string(),
};
ctx.register_type_alias(&alias_def.name, &base_type, Some(overrides));
}
shape_ast::ast::ExportItem::Enum(enum_def) => {
ctx.register_enum(enum_def.clone());
}
shape_ast::ast::ExportItem::Struct(struct_def) => {
ctx.register_struct_type(struct_def.clone());
}
shape_ast::ast::ExportItem::Trait(_) => {
// Type definitions handled at compile time
}
shape_ast::ast::ExportItem::ForeignFunction(_) => {
// Foreign function exports are registered by the VM
}
}
}
shape_ast::ast::Item::Function(_function, _) => {
// Functions are registered by the VM
}
shape_ast::ast::Item::TypeAlias(alias_def, _) => {
let overrides = HashMap::new();
if let Some(ref overrides_ast) = alias_def.meta_param_overrides {
for (_key, _expr) in overrides_ast {
// TODO: Use const_eval for simple literal evaluation
}
}
let base_type = match &alias_def.type_annotation {
shape_ast::ast::TypeAnnotation::Basic(n) => n.clone(),
shape_ast::ast::TypeAnnotation::Reference(n) => n.to_string(),
_ => "any".to_string(),
};
ctx.register_type_alias(&alias_def.name, &base_type, Some(overrides));
}
shape_ast::ast::Item::Trait(_, _) => {}
shape_ast::ast::Item::Impl(_, _) => {}
shape_ast::ast::Item::Enum(enum_def, _) => {
ctx.register_enum(enum_def.clone());
}
shape_ast::ast::Item::StructType(struct_def, _) => {
ctx.register_struct_type(struct_def.clone());
}
shape_ast::ast::Item::Extend(extend_stmt, _) => {
let registry = ctx.type_method_registry();
for method in &extend_stmt.methods {
registry.register_method(&extend_stmt.type_name, method.clone());
}
}
shape_ast::ast::Item::AnnotationDef(ann_def, _) => {
self.annotation_registry
.write()
.unwrap()
.register(ann_def.clone());
}
_ => {}
}
}
Ok(())
}
/// Execute a query item against a data frame.
///
/// In the strict-typed runtime the AST-walking query evaluator has been
/// removed (see `docs/defections.md` 2026-05-06: AST-evaluation runtime
/// executors deletion). The replacement is "compile to bytecode, execute
/// in VM", which is the responsibility of the rebuild workstream
/// `ast-walking-interpreter-strict-rebuild`. Until that lands this entry
/// point returns an empty `QueryResult` so existing callers keep linking.
pub fn execute_query(
&mut self,
query: &shape_ast::ast::Item,
data: &DataFrame,
) -> Result<QueryResult> {
let _ = (query, data);
let id = self
.persistent_context
.as_ref()
.and_then(|ctx| ctx.get_current_id().ok())
.unwrap_or_default();
let timeframe = self
.persistent_context
.as_ref()
.and_then(|ctx| ctx.get_current_timeframe().ok())
.map(|t| t.to_string())
.unwrap_or_default();
Ok(QueryResult::new(QueryType::Value, id, timeframe))
}
/// Format a value using Shape format definitions from stdlib
///
/// Currently a placeholder until VM-based format execution is implemented.
pub fn format_value(
&mut self,
_value: WireValue,
type_name: &str,
format_name: Option<&str>,
_param_overrides: std::collections::HashMap<String, WireValue>,
) -> Result<String> {
if let Some(name) = format_name {
Ok(format!("<formatted {} as {}>", type_name, name))
} else {
Ok(format!("<formatted {}>", type_name))
}
}
/// Enable or disable debug mode.
///
/// When enabled, the runtime produces verbose tracing output via `tracing`
/// and enables any debug-only code paths in the executor.
pub fn set_debug_mode(&mut self, enabled: bool) {
self.debug_mode = enabled;
if enabled {
tracing::debug!("Shape runtime debug mode enabled");
}
}
/// Query whether debug mode is active.
pub fn debug_mode(&self) -> bool {
self.debug_mode
}
/// Set the maximum wall-clock duration for a single execution.
///
/// The executor can periodically check elapsed time against this limit
/// and abort with a timeout error if exceeded.
pub fn set_execution_timeout(&mut self, timeout: Duration) {
self.execution_timeout = Some(timeout);
}
/// Query the configured execution timeout, if any.
pub fn execution_timeout(&self) -> Option<Duration> {
self.execution_timeout
}
/// Set a memory limit (in bytes) for the runtime.
///
/// Allocation tracking can reference this value to decide when to refuse
/// new allocations or trigger garbage collection.
pub fn set_memory_limit(&mut self, limit: usize) {
self.memory_limit = Some(limit);
}
/// Query the configured memory limit, if any.
pub fn memory_limit(&self) -> Option<usize> {
self.memory_limit
}
}
#[cfg(test)]
mod runtime_tests {
use super::*;
use crate::type_schema::FieldType;
// B1.2 parity: two freshly constructed Runtimes have independent
// schema_registry instances. Scoped registrations on one registry do not
// advance the other's ID counter.
#[test]
fn b1_2_runtime_schema_registries_are_independent() {
let mut r1 = Runtime::new();
let mut r2 = Runtime::new();
// Both registries expose the canonical stdlib schemas.
assert!(r1.schema_registry().has_type("Row"));
assert!(r2.schema_registry().has_type("Row"));
assert!(r1.schema_registry().has_type("Option"));
assert!(r2.schema_registry().has_type("Result"));
let id_a = r1
.schema_registry_mut()
.register_type_scoped("UserA", vec![("x".to_string(), FieldType::F64)]);
let id_b = r2
.schema_registry_mut()
.register_type_scoped("UserA", vec![("x".to_string(), FieldType::F64)]);
// Independent registries can hand out identical IDs for equivalently
// named user schemas without cross-runtime collision. Inside each
// runtime, the ID resolves to its own schema.
assert_eq!(r1.schema_registry().get("UserA").unwrap().id, id_a);
assert_eq!(r2.schema_registry().get("UserA").unwrap().id, id_b);
assert_eq!(id_a, id_b);
}
}