1#[cfg(all(feature = "no_std", not(feature = "std")))]
46use alloc::{
47 format,
48 rc::Rc,
49 string::{String, ToString},
50 sync::Arc,
51 vec,
52 vec::Vec,
53};
54
55#[cfg(any(feature = "std", not(feature = "no_std")))]
56use std::{rc::Rc, sync::Arc};
57
58use core::cell::{Cell, RefCell};
59
60#[cfg(all(feature = "no_std", not(feature = "std")))]
61use alloc::collections::{BTreeMap, BTreeSet};
62#[cfg(any(feature = "std", not(feature = "no_std")))]
63use std::collections::{BTreeMap, BTreeSet};
64
65use nybl::builtins::{self, error, error_fatal_with_hint, error_with_hint};
66use nybl::error::NyblError;
67use nybl::import_scope::{ImportScope, ImportedName};
68use nybl::methods;
69use nybl::ops;
70use nybl::parser::{ParamMode, Visibility};
71use nybl::value::{FnBody, NyblFn, NyblFnOrigin, Value};
72use nybl::{EntryPoint, NyblHost, NyblLimits};
73
74use crate::chunk::{
75 CallSiteIdx, CaptureSource, Chunk, CodeOffset, Constant, EnumConstructShape, EnumIdx,
76 EnumVariantShape, FnDef, FnIdx, Instr, InterpPart, LoopStateKind, NameIdx, NamespaceRef,
77 PatternIdx, PlaceIdx, PlaceProjectionRecipe, RefArgTarget, SlotIdx, StructIdx,
78};
79
80const MAX_CALL_DEPTH: usize = 64;
82
83const STEP_SCALE: u64 = 8;
89
90const TICK_MEMCHECK_MASK: u64 = 0xFF;
97
98const SLOTS_FREELIST_CAP: usize = 128;
104
105enum Slot {
108 Value(Value),
109 Iter(Vec<Value>),
112 IterObject(Value),
118 Repeat(i64),
120}
121
122struct FrameScopeBases {
125 types: usize,
126 aliases: usize,
127}
128
129struct FunctionFrameContext {
130 scope_bases: FrameScopeBases,
131 function_module: Option<String>,
132 lexical_context: Rc<ModuleLexicalContext>,
133}
134
135struct Frame {
136 chunk: Arc<Chunk>,
137 ip: usize,
138 slots: Vec<Value>,
145 scopes: Vec<BTreeMap<String, Value>>,
151 scope_base: usize,
156 has_declaration_overlay: bool,
160 type_scope_base: usize,
165 alias_scope_base: usize,
168 stack_base: usize,
169 is_function: bool,
170 function_module: Option<String>,
173 lexical_context: Rc<ModuleLexicalContext>,
177 wrap: FrameWrap,
180 defining_environment_module: Option<String>,
181 captured_names: BTreeSet<String>,
184 prepared_calls: Vec<PreparedCall>,
187 pending_write_backs: Vec<PendingWriteBack>,
190 current_function_entry: Option<Rc<FnEntry>>,
193 nesting_total: u32,
197}
198
199impl Frame {
200 fn top(chunk: Arc<Chunk>, lexical_context: Rc<ModuleLexicalContext>) -> Self {
201 let scopes = vec![BTreeMap::new()];
202 Self {
203 chunk,
204 ip: 0,
205 slots: Vec::new(),
206 scope_base: scopes.len(),
207 has_declaration_overlay: false,
208 scopes,
209 type_scope_base: 1,
211 alias_scope_base: 1,
212 stack_base: 0,
213 is_function: false,
214 function_module: None,
215 lexical_context,
216 wrap: FrameWrap::None,
217 defining_environment_module: None,
218 captured_names: BTreeSet::new(),
219 prepared_calls: Vec::new(),
220 pending_write_backs: Vec::new(),
221 current_function_entry: None,
222 nesting_total: 0,
223 }
224 }
225
226 fn function(
227 chunk: Arc<Chunk>,
228 slots: Vec<Value>,
229 scopes: Vec<BTreeMap<String, Value>>,
230 stack_base: usize,
231 context: FunctionFrameContext,
232 wrap: FrameWrap,
233 ) -> Self {
234 Self {
235 chunk,
236 ip: 0,
237 slots,
238 scope_base: scopes.len(),
239 has_declaration_overlay: false,
240 scopes,
241 type_scope_base: context.scope_bases.types,
242 alias_scope_base: context.scope_bases.aliases,
243 stack_base,
244 is_function: true,
245 function_module: context.function_module,
246 lexical_context: context.lexical_context,
247 wrap,
248 defining_environment_module: None,
249 captured_names: BTreeSet::new(),
250 prepared_calls: Vec::new(),
251 pending_write_backs: Vec::new(),
252 current_function_entry: None,
253 nesting_total: 0,
254 }
255 }
256
257 fn caller_type_scope_depth(&self) -> usize {
258 if self.is_function {
259 self.type_scope_base.saturating_sub(1)
260 } else {
261 self.type_scope_base
262 }
263 }
264}
265
266#[derive(Debug, Clone, Copy, PartialEq, Eq)]
272enum FrameWrap {
273 None,
275 TryCall { line: u32 },
281 ResultOk { line: u32 },
284 ResultErr { line: u32 },
287 IterStart,
292 IterAdvance(crate::chunk::CodeOffset),
298}
299
300enum IterStep {
304 Next(Value),
305 Done,
306 Malformed,
307}
308
309fn unwrap_iter_step(v: &Value) -> IterStep {
310 let e = match v {
311 Value::EnumVariant(e) => e,
312 _ => return IterStep::Malformed,
313 };
314 if e.type_name() != "Iter" {
315 return IterStep::Malformed;
316 }
317 match (e.variant(), e.payload()) {
318 ("Next", nybl::value::EnumPayload::Tuple(items)) if items.len() == 1 => {
319 IterStep::Next(items[0].clone())
320 }
321 ("Done", nybl::value::EnumPayload::Unit) => IterStep::Done,
322 _ => IterStep::Malformed,
323 }
324}
325
326struct FnEntry {
327 exact_self_name: Option<String>,
328 params: Vec<String>,
329 param_modes: Vec<ParamMode>,
330 chunk: Arc<Chunk>,
331 module_path: String,
332 declaration_alias_names: BTreeSet<String>,
333}
334
335enum PreparedCallable {
336 User(Rc<FnEntry>),
337 HostThenUser {
341 name: String,
342 entry: Rc<FnEntry>,
343 },
344 Closure(Rc<NyblFn>),
345 UserMethod {
346 entry: Rc<FnEntry>,
347 receiver: Value,
348 receiver_target: Option<NamespaceRef>,
349 receiver_place: Option<ResolvedPlace>,
350 },
351 DeferredMethod {
352 receiver: Value,
353 method: String,
354 nested_place: bool,
355 },
356 NamedMethodInPlace {
357 target: NamespaceRef,
358 method: String,
359 },
360 PlaceMethodInPlace {
361 place: ResolvedPlace,
362 method: String,
363 },
364 NamedFallback(String),
367}
368
369impl PreparedCallable {
370 fn named_user(name: &str, entry: Rc<FnEntry>) -> Self {
371 if entry.param_modes.iter().all(|mode| *mode != ParamMode::Ref) {
372 Self::HostThenUser {
373 name: name.to_string(),
374 entry,
375 }
376 } else {
377 Self::User(entry)
378 }
379 }
380}
381
382#[derive(Clone, PartialEq, Eq)]
383enum ResolvedRefTarget {
384 Slot {
385 frame: usize,
386 slot: SlotIdx,
387 },
388 Scope {
389 frame: usize,
390 scope: usize,
391 name: String,
392 },
393}
394
395#[derive(Clone)]
396enum ResolvedPlaceProjection {
397 Index(Value),
398 Field(String),
399}
400
401#[derive(Clone)]
402struct ResolvedPlace {
403 target: ResolvedRefTarget,
404 root_recipe: NamespaceRef,
405 root_name: String,
406 root: Value,
407 projections: Vec<ResolvedPlaceProjection>,
408}
409
410struct PreparedRef {
411 param: usize,
412 recipe: RefArgTarget,
413 index_count: usize,
414}
415
416enum PreparedReceiverRef {
417 Binding(NamespaceRef),
418 Place(ResolvedPlace),
419}
420
421struct PreparedCall {
422 site: CallSiteIdx,
423 callable: PreparedCallable,
424 display_name: String,
425 refs: Vec<PreparedRef>,
426 receiver_ref: Option<PreparedReceiverRef>,
427 value_count: usize,
428 ref_index_count: usize,
429}
430
431struct PendingWriteBack {
432 parameter: usize,
433 place: ResolvedPlace,
434}
435
436fn shapes_match(a: &[(String, EnumVariantShape)], b: &[(String, EnumVariantShape)]) -> bool {
446 if a.len() != b.len() {
447 return false;
448 }
449 a.iter().zip(b.iter()).all(|((an, av), (bn, bv))| {
450 if an != bn {
451 return false;
452 }
453 match (av, bv) {
454 (EnumVariantShape::Unit, EnumVariantShape::Unit) => true,
455 (EnumVariantShape::Tuple(fa), EnumVariantShape::Tuple(fb)) => fa.len() == fb.len(),
456 (EnumVariantShape::Struct(fa), EnumVariantShape::Struct(fb)) => fa == fb,
457 _ => false,
458 }
459 })
460}
461
462type TypeKey = (String, String);
463type RuntimeEnumVariants = Vec<(String, EnumVariantShape)>;
464type StructTypeTable = BTreeMap<TypeKey, Vec<String>>;
465type EnumTypeTable = BTreeMap<TypeKey, RuntimeEnumVariants>;
466type BuiltinTypeTables = (StructTypeTable, EnumTypeTable, BTreeMap<String, String>);
467type ModuleStructDef = (TypeKey, Vec<String>);
468type ModuleEnumDef = (TypeKey, RuntimeEnumVariants);
469type ModuleMethodDef = (TypeKey, String, Rc<FnEntry>);
470
471fn seed_builtin_types() -> BuiltinTypeTables {
484 use nybl::parser::VariantKind;
485 let builtin_mp = nybl::value::BUILTIN_MODULE_PATH.to_string();
486 let mut struct_defs: BTreeMap<(String, String), Vec<String>> = BTreeMap::new();
487 let mut enum_defs: BTreeMap<(String, String), Vec<(String, EnumVariantShape)>> =
488 BTreeMap::new();
489 let mut bindings: BTreeMap<String, String> = BTreeMap::new();
490 struct_defs.insert(
491 (builtin_mp.clone(), String::from("RuntimeError")),
492 nybl::builtins::builtin_runtime_error_fields(),
493 );
494 bindings.insert(String::from("RuntimeError"), builtin_mp.clone());
495 let variants: Vec<(String, EnumVariantShape)> = nybl::builtins::builtin_result_variants()
496 .into_iter()
497 .map(|v| {
498 let shape = match v.kind {
499 VariantKind::Unit => EnumVariantShape::Unit,
500 VariantKind::Tuple(fs) => EnumVariantShape::Tuple(fs),
501 VariantKind::Struct(fs) => EnumVariantShape::Struct(fs),
502 };
503 (v.name, shape)
504 })
505 .collect();
506 enum_defs.insert((builtin_mp.clone(), String::from("Result")), variants);
507 bindings.insert(String::from("Result"), builtin_mp.clone());
508 let iter_variants: Vec<(String, EnumVariantShape)> = nybl::builtins::builtin_iter_variants()
509 .into_iter()
510 .map(|v| {
511 let shape = match v.kind {
512 VariantKind::Unit => EnumVariantShape::Unit,
513 VariantKind::Tuple(fs) => EnumVariantShape::Tuple(fs),
514 VariantKind::Struct(fs) => EnumVariantShape::Struct(fs),
515 };
516 (v.name, shape)
517 })
518 .collect();
519 enum_defs.insert((builtin_mp.clone(), String::from("Iter")), iter_variants);
520 bindings.insert(String::from("Iter"), builtin_mp);
521 (struct_defs, enum_defs, bindings)
522}
523
524#[allow(clippy::large_enum_variant)]
530enum ImportSlot {
531 Loading,
532 Loaded(ModuleArtifacts),
533}
534
535#[derive(Clone)]
536struct ModuleArtifacts {
537 explicit_surface: bool,
540 bindings: Vec<(String, Value)>,
544 binding_origins: BTreeMap<String, BindingOrigin>,
548 fn_decls: Vec<(String, Rc<FnEntry>)>,
553 struct_defs: Vec<ModuleStructDef>,
556 enum_defs: Vec<ModuleEnumDef>,
559 methods: Vec<ModuleMethodDef>,
562 type_exports: BTreeMap<String, String>,
564 module_exports: BTreeMap<String, Rc<nybl::value::NyblModule>>,
567 lexical_context: Rc<ModuleLexicalContext>,
570}
571
572#[derive(Clone, Default)]
573struct ModuleLexicalContext {
574 type_bindings: Rc<BTreeMap<String, String>>,
575 module_aliases: Rc<BTreeMap<String, Rc<nybl::value::NyblModule>>>,
576 imported_functions: Rc<BTreeMap<String, Rc<FnEntry>>>,
577}
578
579type ImportCache = Rc<RefCell<BTreeMap<String, ImportSlot>>>;
582type LiveValueEnvironments = Rc<RefCell<BTreeMap<String, BTreeMap<String, Value>>>>;
583type BindingOrigin = (String, String);
584
585#[derive(Clone)]
589struct CompiledModule {
590 chunk: Arc<Chunk>,
591 source: Arc<str>,
592 builtin_usage: Arc<BTreeMap<String, u32>>,
593 load_steps: u64,
596}
597
598type CompiledModuleGraph = Arc<BTreeMap<String, CompiledModule>>;
599
600fn snapshot_module_bindings(
601 top_scope: &BTreeMap<String, Value>,
602 binding_origins: &BTreeMap<String, BindingOrigin>,
603 module_path: &str,
604 imports: &ImportCache,
605 line: u32,
606) -> Result<Vec<(String, Value)>, NyblError> {
607 let forwarded: BTreeMap<String, Value> = {
612 let imports = imports.borrow();
613 top_scope
614 .keys()
615 .filter_map(|name| {
616 let origin = binding_origins.get(name)?;
617 if origin.0 == module_path && origin.1 == *name {
618 return None;
619 }
620 let ImportSlot::Loaded(origin_module) = imports.get(&origin.0)? else {
621 return None;
622 };
623 origin_module
624 .bindings
625 .iter()
626 .find(|(origin_name, _)| origin_name == &origin.1)
627 .map(|(_, value)| (name.clone(), value.clone()))
628 })
629 .collect()
630 };
631 let local: BTreeMap<String, Value> = top_scope
632 .iter()
633 .filter(|(name, _)| !forwarded.contains_key(*name))
634 .map(|(name, value)| (name.clone(), value.clone()))
635 .collect();
636 let mut local_snapshots: BTreeMap<String, Value> =
637 Value::__compatibility_snapshot_bindings(&local, line)?
638 .into_iter()
639 .collect();
640
641 top_scope
642 .keys()
643 .map(|name| {
644 let value = forwarded
645 .get(name)
646 .cloned()
647 .or_else(|| local_snapshots.remove(name))
648 .ok_or_else(|| {
649 error(line, format!("Missing compatibility snapshot for `{name}`"))
650 })?;
651 Ok((name.clone(), value))
652 })
653 .collect()
654}
655type LiveBindingOrigins = Rc<RefCell<BTreeMap<String, BTreeMap<String, BindingOrigin>>>>;
656
657#[derive(Clone)]
658struct ModuleRuntime {
659 imports: ImportCache,
660 environments: LiveValueEnvironments,
661 origins: LiveBindingOrigins,
662}
663
664impl ModuleRuntime {
665 fn empty() -> Self {
666 Self {
667 imports: Rc::new(RefCell::new(BTreeMap::new())),
668 environments: Rc::new(RefCell::new(BTreeMap::new())),
669 origins: Rc::new(RefCell::new(BTreeMap::new())),
670 }
671 }
672}
673
674fn take_live_environment(
675 environments: &LiveValueEnvironments,
676 module_path: &str,
677 origins: &BTreeMap<String, BindingOrigin>,
678) -> BTreeMap<String, Value> {
679 let mut environments = environments.borrow_mut();
680 let mut environment = environments.remove(module_path).unwrap_or_default();
681 for (binding, (origin_module, origin_binding)) in origins {
682 if origin_module == module_path && origin_binding == binding {
683 continue;
684 }
685 if let Some(value) = environments
686 .get_mut(origin_module)
687 .and_then(|origin| origin.remove(origin_binding))
688 {
689 environment.insert(binding.clone(), value);
690 }
691 }
692 environment
693}
694
695fn put_live_environment(
696 environments: &LiveValueEnvironments,
697 module_path: &str,
698 mut environment: BTreeMap<String, Value>,
699 origins: &BTreeMap<String, BindingOrigin>,
700) {
701 let mut environments = environments.borrow_mut();
702 for (binding, (origin_module, origin_binding)) in origins {
703 if origin_module == module_path && origin_binding == binding {
704 continue;
705 }
706 if let Some(value) = environment.remove(binding) {
707 environments
708 .entry(origin_module.clone())
709 .or_default()
710 .insert(origin_binding.clone(), value);
711 }
712 }
713 environments.insert(module_path.to_string(), environment);
714}
715
716enum Next {
719 Continue,
721 Halt,
723}
724
725pub struct Vm<'h, H: NyblHost + ?Sized> {
729 frames: Vec<Frame>,
730 stack: Vec<Slot>,
731 functions: BTreeMap<String, Rc<FnEntry>>,
737 host: &'h mut H,
738 steps: u64,
739 step_budget: u64,
740 call_depth_base: usize,
743 rand_state: u64,
744 imports: ImportCache,
745 compiled_modules: Option<CompiledModuleGraph>,
749 import_scopes: Vec<ImportScope>,
750 limits: NyblLimits,
751 current_module: String,
757 struct_defs: BTreeMap<(String, String), Vec<String>>,
762 enum_defs: BTreeMap<(String, String), Vec<(String, EnumVariantShape)>>,
765 user_methods: BTreeMap<(String, String), BTreeMap<String, Rc<FnEntry>>>,
770 type_exports: BTreeMap<String, String>,
772 type_bindings: Vec<BTreeMap<String, String>>,
778 module_aliases: Vec<BTreeMap<String, Rc<nybl::value::NyblModule>>>,
783 imported_functions: Vec<BTreeMap<String, Rc<FnEntry>>>,
785 root_lexical_context: Rc<ModuleLexicalContext>,
788 slots_freelist: Vec<Vec<Value>>,
794 root_function_visibility: BTreeMap<u32, Visibility>,
795 abi_declarations: Vec<(String, Rc<FnEntry>)>,
796 function_origin: NyblFnOrigin,
797 memory: nybl::memory::MemoryContext,
798 live_value_environments: LiveValueEnvironments,
799 binding_origins: BTreeMap<String, BindingOrigin>,
800 live_binding_origins: LiveBindingOrigins,
801}
802
803struct VmState {
804 frames: Vec<Frame>,
805 stack: Vec<Slot>,
806 functions: BTreeMap<String, Rc<FnEntry>>,
807 rand_state: u64,
808 imports: ImportCache,
809 compiled_modules: Option<CompiledModuleGraph>,
810 import_scopes: Vec<ImportScope>,
811 current_module: String,
812 struct_defs: BTreeMap<(String, String), Vec<String>>,
813 enum_defs: BTreeMap<(String, String), Vec<(String, EnumVariantShape)>>,
814 user_methods: BTreeMap<(String, String), BTreeMap<String, Rc<FnEntry>>>,
815 type_exports: BTreeMap<String, String>,
816 type_bindings: Vec<BTreeMap<String, String>>,
817 module_aliases: Vec<BTreeMap<String, Rc<nybl::value::NyblModule>>>,
818 imported_functions: Vec<BTreeMap<String, Rc<FnEntry>>>,
819 root_lexical_context: Rc<ModuleLexicalContext>,
820 slots_freelist: Vec<Vec<Value>>,
821 root_function_visibility: BTreeMap<u32, Visibility>,
822 abi_declarations: Vec<(String, Rc<FnEntry>)>,
823 function_origin: NyblFnOrigin,
824 live_value_environments: LiveValueEnvironments,
825 binding_origins: BTreeMap<String, BindingOrigin>,
826 live_binding_origins: LiveBindingOrigins,
827}
828
829pub struct NyblInstance {
831 state: Option<VmState>,
832 entries: Vec<EntryPoint>,
833 limits: NyblLimits,
834 in_operation: Cell<bool>,
835 memory: nybl::memory::MemoryContext,
836 identity: Rc<()>,
837}
838
839#[derive(Clone)]
843pub struct PreparedEntry {
844 name: String,
845 arity: usize,
846 variadic: bool,
847 target: Rc<FnEntry>,
848 instance_identity: Rc<()>,
849}
850
851impl PreparedEntry {
852 pub fn name(&self) -> &str {
853 &self.name
854 }
855
856 pub const fn arity(&self) -> usize {
857 self.arity
858 }
859
860 pub const fn is_variadic(&self) -> bool {
861 self.variadic
862 }
863
864 pub const fn accepts_arity(&self, count: usize) -> bool {
865 if self.variadic {
866 count >= self.arity
867 } else {
868 count == self.arity
869 }
870 }
871}
872
873impl core::fmt::Debug for PreparedEntry {
874 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
875 f.debug_struct("PreparedEntry")
876 .field("name", &self.name)
877 .field("arity", &self.arity)
878 .field("variadic", &self.variadic)
879 .finish_non_exhaustive()
880 }
881}
882
883impl<'h, H: NyblHost + ?Sized> Vm<'h, H> {
884 pub fn new(chunk: Chunk, host: &'h mut H, limits: NyblLimits) -> Self {
889 let memory = nybl::memory::MemoryContext::__new(limits.max_memory);
890 Self::new_internal(
891 Arc::new(chunk),
892 host,
893 limits,
894 ModuleRuntime::empty(),
895 None,
896 String::from(nybl::value::ROOT_MODULE_PATH),
897 BTreeMap::new(),
898 NyblFnOrigin::__instance("vm"),
899 memory,
900 )
901 }
902
903 #[allow(clippy::too_many_arguments)]
904 fn new_internal(
905 chunk: Arc<Chunk>,
906 host: &'h mut H,
907 limits: NyblLimits,
908 module_runtime: ModuleRuntime,
909 compiled_modules: Option<CompiledModuleGraph>,
910 current_module: String,
911 root_function_visibility: BTreeMap<u32, Visibility>,
912 function_origin: NyblFnOrigin,
913 memory: nybl::memory::MemoryContext,
914 ) -> Self {
915 let step_budget = limits.max_steps.saturating_mul(STEP_SCALE);
916 let (struct_defs, enum_defs, builtin_bindings) = seed_builtin_types();
917 let root_lexical_context = Rc::new(ModuleLexicalContext {
918 type_bindings: Rc::new(builtin_bindings.clone()),
919 module_aliases: Rc::new(BTreeMap::new()),
920 imported_functions: Rc::new(BTreeMap::new()),
921 });
922 let mut top = Frame::top(chunk, Rc::new(ModuleLexicalContext::default()));
926 top.nesting_total = top.chunk.nesting_depth;
929 Self {
930 frames: vec![top],
931 stack: Vec::new(),
932 functions: BTreeMap::new(),
933 host,
934 steps: 0,
935 step_budget,
936 call_depth_base: 0,
937 rand_state: 0,
938 imports: module_runtime.imports,
939 compiled_modules,
940 import_scopes: vec![ImportScope::default()],
941 limits,
942 current_module,
943 struct_defs,
944 enum_defs,
945 user_methods: BTreeMap::new(),
946 type_exports: BTreeMap::new(),
947 type_bindings: vec![builtin_bindings],
948 module_aliases: vec![BTreeMap::new()],
949 imported_functions: vec![BTreeMap::new()],
950 root_lexical_context,
951 slots_freelist: Vec::new(),
952 root_function_visibility,
953 abi_declarations: Vec::new(),
954 function_origin,
955 memory,
956 live_value_environments: module_runtime.environments,
957 binding_origins: BTreeMap::new(),
958 live_binding_origins: module_runtime.origins,
959 }
960 }
961
962 fn into_state(self) -> VmState {
963 VmState {
964 frames: self.frames,
965 stack: self.stack,
966 functions: self.functions,
967 rand_state: self.rand_state,
968 imports: self.imports,
969 compiled_modules: self.compiled_modules,
970 import_scopes: self.import_scopes,
971 current_module: self.current_module,
972 struct_defs: self.struct_defs,
973 enum_defs: self.enum_defs,
974 user_methods: self.user_methods,
975 type_exports: self.type_exports,
976 type_bindings: self.type_bindings,
977 module_aliases: self.module_aliases,
978 imported_functions: self.imported_functions,
979 root_lexical_context: self.root_lexical_context,
980 slots_freelist: self.slots_freelist,
981 root_function_visibility: self.root_function_visibility,
982 abi_declarations: self.abi_declarations,
983 function_origin: self.function_origin,
984 live_value_environments: self.live_value_environments,
985 binding_origins: self.binding_origins,
986 live_binding_origins: self.live_binding_origins,
987 }
988 }
989
990 fn from_state(
991 state: VmState,
992 host: &'h mut H,
993 limits: NyblLimits,
994 memory: nybl::memory::MemoryContext,
995 ) -> Self {
996 let mut frames = state.frames;
997 if let Some(root) = frames.first_mut() {
1000 root.nesting_total = 0;
1001 }
1002 Self {
1003 frames,
1004 stack: state.stack,
1005 functions: state.functions,
1006 host,
1007 steps: 0,
1008 step_budget: limits.max_steps.saturating_mul(STEP_SCALE),
1009 call_depth_base: 0,
1010 rand_state: state.rand_state,
1011 imports: state.imports,
1012 compiled_modules: state.compiled_modules,
1013 import_scopes: state.import_scopes,
1014 limits,
1015 current_module: state.current_module,
1016 struct_defs: state.struct_defs,
1017 enum_defs: state.enum_defs,
1018 user_methods: state.user_methods,
1019 type_exports: state.type_exports,
1020 type_bindings: state.type_bindings,
1021 module_aliases: state.module_aliases,
1022 imported_functions: state.imported_functions,
1023 root_lexical_context: state.root_lexical_context,
1024 slots_freelist: state.slots_freelist,
1025 root_function_visibility: state.root_function_visibility,
1026 abi_declarations: state.abi_declarations,
1027 function_origin: state.function_origin,
1028 memory,
1029 live_value_environments: state.live_value_environments,
1030 binding_origins: state.binding_origins,
1031 live_binding_origins: state.live_binding_origins,
1032 }
1033 }
1034
1035 fn restore_instance_baseline(&mut self) {
1036 while self.frames.len() > 1 {
1037 let mut frame = self.frames.pop().expect("frame present");
1038 self.store_frame_defining_environment(&mut frame);
1039 if !frame.slots.is_empty() {
1040 self.return_slots(frame.slots);
1041 }
1042 }
1043 self.restore_active_defining_environment();
1044 self.stack.clear();
1045 if let Some(root) = self.frames.first_mut() {
1046 root.scopes.truncate(root.scope_base);
1047 }
1048 self.type_bindings.truncate(1);
1049 self.module_aliases.truncate(1);
1050 self.imported_functions.truncate(1);
1051 self.import_scopes.truncate(1);
1052 }
1053
1054 fn take_slots(&mut self, len: usize) -> Vec<Value> {
1059 let mut v = self.slots_freelist.pop().unwrap_or_default();
1060 if v.capacity() < len {
1061 v.reserve(len - v.capacity());
1062 }
1063 v.resize(len, Value::None);
1064 v
1065 }
1066
1067 fn return_slots(&mut self, mut slots: Vec<Value>) {
1072 if self.slots_freelist.len() >= SLOTS_FREELIST_CAP {
1073 return;
1074 }
1075 slots.clear();
1076 self.slots_freelist.push(slots);
1077 }
1078
1079 pub fn run(mut self) -> Result<(), NyblError> {
1080 self.check_root_nesting()?;
1081 let mut last_line: u32 = 0;
1082 while let Some((instr, line)) = self.fetch() {
1083 last_line = line;
1084 if let Err(err) = self.tick(line) {
1089 let err = self.attach_frame_module_context(err);
1090 self.unwind_to_try_call(err)?;
1091 continue;
1092 }
1093 match self.dispatch(instr, line) {
1094 Ok(Next::Continue) => {}
1095 Ok(Next::Halt) => break,
1096 Err(err) => {
1097 let err = self.attach_frame_module_context(err);
1098 self.unwind_to_try_call(err)?;
1099 }
1100 }
1101 }
1102 if self.memory.__exceeded() {
1108 return Err(error_fatal_with_hint(
1109 last_line,
1110 "Memory limit exceeded",
1111 "Your code is using too much memory. Check for large strings or arrays growing in loops.",
1112 ));
1113 }
1114 Ok(())
1115 }
1116
1117 fn check_root_nesting(&self) -> Result<(), NyblError> {
1120 if self.nesting_used() > self.limits.max_nesting {
1121 return Err(nybl::error_messages::nesting_error(0));
1122 }
1123 Ok(())
1124 }
1125
1126 #[inline]
1129 fn fetch(&mut self) -> Option<(Instr, u32)> {
1130 let frame = self.frames.last_mut()?;
1131 if frame.ip >= frame.chunk.code.len() {
1132 return None;
1133 }
1134 let instr = frame.chunk.code[frame.ip];
1135 let line = frame.chunk.lines[frame.ip];
1136 frame.ip += 1;
1137 Some((instr, line))
1138 }
1139
1140 fn jump(&mut self, target: CodeOffset) {
1141 if let Some(frame) = self.frames.last_mut() {
1142 frame.ip = target.0 as usize;
1143 }
1144 }
1145
1146 #[inline]
1149 fn tick(&mut self, line: u32) -> Result<(), NyblError> {
1150 self.steps += 1;
1151 if self.steps > self.step_budget {
1152 return Err(error_fatal_with_hint(
1162 self.active_loop_line().unwrap_or(line),
1163 "Your code took too many steps (possible infinite loop)",
1164 "Check your loops — make sure they have a condition that eventually stops them.",
1165 ));
1166 }
1167 if self.steps & TICK_MEMCHECK_MASK == 0 && self.memory.__exceeded() {
1177 return Err(error_fatal_with_hint(
1178 line,
1179 "Memory limit exceeded",
1180 "Your code is using too much memory. Check for large strings or arrays growing in loops.",
1181 ));
1182 }
1183 self.host.on_tick()?;
1184 Ok(())
1185 }
1186
1187 fn active_loop_line(&self) -> Option<u32> {
1196 self.frames.iter().find_map(|frame| {
1197 let offset = CodeOffset(frame.ip.saturating_sub(1) as u32);
1198 frame.chunk.outermost_loop_line(offset)
1199 })
1200 }
1201
1202 #[inline]
1205 fn push_value(&mut self, v: Value) {
1206 self.stack.push(Slot::Value(v));
1207 }
1208
1209 #[inline]
1210 fn pop_value(&mut self, line: u32) -> Result<Value, NyblError> {
1211 match self.stack.pop() {
1212 Some(Slot::Value(v)) => Ok(v),
1213 Some(_) => Err(error(line, "VM: expected value on stack")),
1214 None => Err(error(line, "VM: stack underflow")),
1215 }
1216 }
1217
1218 #[inline]
1219 fn peek_value(&self, line: u32) -> Result<&Value, NyblError> {
1220 match self.stack.last() {
1221 Some(Slot::Value(v)) => Ok(v),
1222 Some(_) => Err(error(line, "VM: expected value on stack")),
1223 None => Err(error(line, "VM: stack underflow")),
1224 }
1225 }
1226
1227 fn pop_n_values(&mut self, n: usize, line: u32) -> Result<Vec<Value>, NyblError> {
1228 if self.stack.len() < n {
1229 return Err(error(line, "VM: stack underflow"));
1230 }
1231 let start = self.stack.len() - n;
1232 let mut out = Vec::with_capacity(n);
1233 for slot in self.stack.drain(start..) {
1234 match slot {
1235 Slot::Value(v) => out.push(v),
1236 _ => return Err(error(line, "VM: expected value on stack")),
1237 }
1238 }
1239 Ok(out)
1240 }
1241
1242 fn current_scopes_mut(&mut self) -> &mut Vec<BTreeMap<String, Value>> {
1245 &mut self.frames.last_mut().expect("frame present").scopes
1246 }
1247
1248 fn current_scopes(&self) -> &Vec<BTreeMap<String, Value>> {
1249 &self.frames.last().expect("frame present").scopes
1250 }
1251
1252 fn push_scope(&mut self) {
1253 self.current_scopes_mut().push(BTreeMap::new());
1254 self.type_bindings.push(BTreeMap::new());
1258 self.module_aliases.push(BTreeMap::new());
1259 self.imported_functions.push(BTreeMap::new());
1260 self.import_scopes.push(ImportScope::default());
1261 }
1262
1263 fn pop_scope(&mut self) {
1264 let popped = {
1265 let frame = self.frames.last_mut().expect("frame present");
1266 if frame.scopes.len() > frame.scope_base {
1267 frame.scopes.pop();
1268 true
1269 } else {
1270 false
1271 }
1272 };
1273 if popped {
1274 let type_scope_base = self.frames.last().expect("frame present").type_scope_base;
1275 debug_assert!(
1276 self.type_bindings.len() > type_scope_base,
1277 "value and type scope stacks must stay paired"
1278 );
1279 if self.type_bindings.len() > type_scope_base {
1280 self.type_bindings.pop();
1281 self.module_aliases.pop();
1282 self.imported_functions.pop();
1283 self.import_scopes.pop();
1284 }
1285 }
1286 }
1287
1288 fn push_function_frame(
1292 &mut self,
1293 chunk: Arc<Chunk>,
1294 slots: Vec<Value>,
1295 scopes: Vec<BTreeMap<String, Value>>,
1296 stack_base: usize,
1297 function_module: Option<String>,
1298 wrap: FrameWrap,
1299 ) {
1300 self.park_active_defining_environment();
1301 let defining_environment = function_module.as_ref().map(|module| {
1302 let origins = self.binding_origins_for(module);
1303 take_live_environment(&self.live_value_environments, module, &origins)
1304 });
1305 let mut scopes = scopes;
1306 if let Some(environment) = defining_environment {
1307 scopes.insert(0, environment);
1308 scopes.push(BTreeMap::new());
1311 }
1312 let lexical_context = function_module
1313 .as_deref()
1314 .map(|module| self.module_lexical_context(module))
1315 .unwrap_or_else(|| Rc::clone(&self.root_lexical_context));
1316 let type_scope_base = self.type_bindings.len() + 1;
1317 let alias_scope_base = self.module_aliases.len();
1318 self.module_aliases.push(BTreeMap::new());
1319 self.imported_functions.push(BTreeMap::new());
1320 self.import_scopes.push(ImportScope::default());
1321 let mut frame = Frame::function(
1322 chunk,
1323 slots,
1324 scopes,
1325 stack_base,
1326 FunctionFrameContext {
1327 scope_bases: FrameScopeBases {
1328 types: type_scope_base,
1329 aliases: alias_scope_base,
1330 },
1331 function_module,
1332 lexical_context,
1333 },
1334 wrap,
1335 );
1336 frame.defining_environment_module = frame.function_module.clone();
1337 frame.nesting_total = self
1338 .nesting_used()
1339 .saturating_add(frame.chunk.nesting_depth);
1340 self.frames.push(frame);
1341 self.type_bindings.push(BTreeMap::new());
1342 }
1343
1344 fn nesting_used(&self) -> u32 {
1346 self.frames.last().map_or(0, |frame| frame.nesting_total)
1347 }
1348
1349 fn check_nesting(&self, depth: u32, line: u32) -> Result<(), NyblError> {
1352 if self.nesting_used().saturating_add(depth) > self.limits.max_nesting {
1353 return Err(nybl::error_messages::nesting_error(line));
1354 }
1355 Ok(())
1356 }
1357
1358 fn active_call_depth(&self) -> usize {
1360 self.call_depth_base + self.frames.len().saturating_sub(1)
1361 }
1362
1363 fn charge_steps(&mut self, steps: u64, line: u32) -> Result<(), NyblError> {
1365 self.steps = self.steps.saturating_add(steps.saturating_mul(STEP_SCALE));
1366 if self.steps > self.step_budget {
1367 return Err(nybl::error_messages::step_limit_error(line));
1368 }
1369 Ok(())
1370 }
1371
1372 fn bind_function_self_name(&mut self, name: Option<&str>, params: &[String], module: &str) {
1376 if let Some(name) = name
1377 && !params.iter().any(|param| param == name)
1378 && let Some(scope) = self.import_scopes.last_mut()
1379 {
1380 scope.self_binding = Some((module.to_string(), name.to_string()));
1381 }
1382 }
1383
1384 fn apply_entry_alias_context(&mut self, entry: &FnEntry) {
1385 let frame = self.frames.last_mut().expect("callee frame");
1386 let mut context = (*frame.lexical_context).clone();
1387 Rc::make_mut(&mut context.module_aliases)
1388 .retain(|name, _| entry.declaration_alias_names.contains(name));
1389 frame.lexical_context = Rc::new(context);
1390 }
1391
1392 fn park_active_defining_environment(&mut self) {
1393 let active_module = self.frames.last().and_then(|frame| {
1394 frame
1395 .defining_environment_module
1396 .clone()
1397 .or_else(|| (!frame.is_function).then(|| self.current_module.clone()))
1398 });
1399 let Some(module) = active_module else {
1400 return;
1401 };
1402 let environment = self
1403 .frames
1404 .last_mut()
1405 .and_then(|frame| frame.scopes.first_mut())
1406 .map(core::mem::take)
1407 .unwrap_or_default();
1408 let origins = self.binding_origins_for(&module);
1409 put_live_environment(
1410 &self.live_value_environments,
1411 &module,
1412 environment,
1413 &origins,
1414 );
1415 self.live_binding_origins
1416 .borrow_mut()
1417 .insert(module, origins);
1418 }
1419
1420 fn store_frame_defining_environment(&mut self, frame: &mut Frame) {
1421 let Some(module) = frame.defining_environment_module.as_ref() else {
1422 return;
1423 };
1424 let origins = self.binding_origins_for(module);
1425 if !self.live_value_environments.borrow().contains_key(module) {
1426 let environment = frame
1427 .scopes
1428 .first_mut()
1429 .map(core::mem::take)
1430 .unwrap_or_default();
1431 put_live_environment(&self.live_value_environments, module, environment, &origins);
1432 }
1433 self.live_binding_origins
1434 .borrow_mut()
1435 .insert(module.clone(), origins);
1436 }
1437
1438 fn restore_active_defining_environment(&mut self) {
1439 let active_module = self.frames.last().and_then(|frame| {
1440 frame
1441 .defining_environment_module
1442 .clone()
1443 .or_else(|| (!frame.is_function).then(|| self.current_module.clone()))
1444 });
1445 let Some(module) = active_module else {
1446 return;
1447 };
1448 if !self.live_value_environments.borrow().contains_key(&module) {
1449 return;
1450 }
1451 let origins = self.binding_origins_for(&module);
1452 let environment = take_live_environment(&self.live_value_environments, &module, &origins);
1453 if let Some(scope) = self
1454 .frames
1455 .last_mut()
1456 .and_then(|frame| frame.scopes.first_mut())
1457 {
1458 *scope = environment;
1459 }
1460 }
1461
1462 fn module_alias(&self, name: &str) -> Option<&Rc<nybl::value::NyblModule>> {
1463 let floor = self
1464 .frames
1465 .last()
1466 .filter(|frame| frame.is_function)
1467 .map(|frame| frame.alias_scope_base);
1468 self.module_aliases
1469 .iter()
1470 .enumerate()
1471 .rev()
1472 .filter(|(index, _)| floor.is_none_or(|floor| *index >= floor))
1473 .find_map(|(_, frame)| frame.get(name))
1474 .or_else(|| {
1475 self.frames
1476 .last()
1477 .and_then(|frame| frame.lexical_context.module_aliases.get(name))
1478 })
1479 }
1480
1481 fn module_binding(&self, module: &nybl::value::NyblModule, name: &str) -> Option<Value> {
1482 if !module.bindings.iter().any(|(binding, _)| binding == name) {
1486 return None;
1487 }
1488 if let Some((active_module, environment)) = self.frames.last().and_then(|frame| {
1489 let active_module = frame
1490 .defining_environment_module
1491 .as_deref()
1492 .or_else(|| (!frame.is_function).then_some(self.current_module.as_str()))?;
1493 Some((active_module, frame.scopes.first()?))
1494 }) {
1495 if module.path == active_module
1496 && let Some(value) = environment.get(name)
1497 {
1498 return Some(value.clone());
1499 }
1500 let (origin_module, origin_binding) = module.__binding_origin(name);
1501 if origin_module == active_module
1502 && let Some(value) = environment.get(&origin_binding)
1503 {
1504 return Some(value.clone());
1505 }
1506 let active_origins = self.binding_origins_for(active_module);
1507 if let Some(active_binding) =
1508 active_origins
1509 .iter()
1510 .find_map(|(active_binding, active_origin)| {
1511 (active_origin.0 == origin_module && active_origin.1 == origin_binding)
1512 .then_some(active_binding)
1513 })
1514 && let Some(value) = environment.get(active_binding)
1515 {
1516 return Some(value.clone());
1517 }
1518 }
1519 module.__binding(name)
1520 }
1521
1522 fn binding_origins_for(&self, module: &str) -> BTreeMap<String, BindingOrigin> {
1523 if module == self.current_module {
1524 return self.binding_origins.clone();
1525 }
1526 self.live_binding_origins
1527 .borrow()
1528 .get(module)
1529 .cloned()
1530 .unwrap_or_default()
1531 }
1532
1533 fn live_origin_value(&self, origin: &BindingOrigin) -> Option<Value> {
1534 if let Some((active_module, environment)) = self.frames.last().and_then(|frame| {
1535 let active_module = frame
1536 .defining_environment_module
1537 .as_deref()
1538 .or_else(|| (!frame.is_function).then_some(self.current_module.as_str()))?;
1539 Some((active_module, frame.scopes.first()?))
1540 }) {
1541 if active_module == origin.0
1542 && let Some(value) = environment.get(&origin.1)
1543 {
1544 return Some(value.clone());
1545 }
1546 let active_origins = self.binding_origins_for(active_module);
1547 if let Some(binding) = active_origins
1548 .iter()
1549 .find_map(|(binding, candidate)| (candidate == origin).then_some(binding))
1550 && let Some(value) = environment.get(binding)
1551 {
1552 return Some(value.clone());
1553 }
1554 }
1555 self.live_value_environments
1556 .borrow()
1557 .get(&origin.0)
1558 .and_then(|environment| environment.get(&origin.1))
1559 .cloned()
1560 }
1561
1562 fn imported_function(&self, name: &str) -> Option<&Rc<FnEntry>> {
1563 let floor = self
1564 .frames
1565 .last()
1566 .filter(|frame| frame.is_function)
1567 .map(|frame| frame.alias_scope_base);
1568 self.imported_functions
1569 .iter()
1570 .enumerate()
1571 .rev()
1572 .filter(|(index, _)| floor.is_none_or(|floor| *index >= floor))
1573 .find_map(|(_, frame)| frame.get(name))
1574 .or_else(|| {
1575 self.frames
1576 .last()
1577 .and_then(|frame| frame.lexical_context.imported_functions.get(name))
1578 })
1579 }
1580
1581 fn is_module_top_scope(&self) -> bool {
1582 self.frames
1583 .last()
1584 .is_some_and(|frame| !frame.is_function && frame.scopes.len() == frame.scope_base)
1585 }
1586
1587 fn define_local(&mut self, name: String, value: Value) {
1588 if self.current_scopes().is_empty() {
1589 self.current_scopes_mut().push(BTreeMap::new());
1590 }
1591 if let Some(scope) = self.current_scopes_mut().last_mut() {
1592 scope.insert(name, value);
1593 }
1594 }
1595
1596 fn sync_top_level_module_alias(
1597 &mut self,
1598 name: String,
1599 module: Option<Rc<nybl::value::NyblModule>>,
1600 ) {
1601 if !self.is_module_top_scope() {
1602 return;
1603 }
1604 let aliases = self.module_aliases.last_mut().expect("module alias scope");
1605 if let Some(module) = module {
1606 aliases.insert(name.clone(), Rc::clone(&module));
1607 self.publish_root_module_alias(name, Some(module));
1608 } else {
1609 aliases.remove(&name);
1610 self.publish_root_module_alias(name, None);
1611 }
1612 }
1613
1614 fn lookup_var_by_idx(&self, idx: NameIdx) -> Option<&Value> {
1618 let frame = self.frames.last()?;
1619 let name = frame.chunk.name(idx);
1620 for scope in frame.scopes.iter().rev() {
1621 if let Some(v) = scope.get(name) {
1622 return Some(v);
1623 }
1624 }
1625 if frame.is_function
1626 && frame.function_module.as_deref() == Some(nybl::value::ROOT_MODULE_PATH)
1627 {
1628 return self
1629 .frames
1630 .first()
1631 .and_then(|root| root.scopes.iter().rev().find_map(|scope| scope.get(name)));
1632 }
1633 None
1634 }
1635
1636 fn lookup_var_mut_by_idx(&mut self, idx: NameIdx) -> Option<&mut Value> {
1637 let (name, uses_root) = {
1638 let frame = self.frames.last()?;
1639 (
1640 frame.chunk.name(idx).to_string(),
1641 frame.is_function
1642 && frame.function_module.as_deref() == Some(nybl::value::ROOT_MODULE_PATH),
1643 )
1644 };
1645 let current_index = self.frames.len().checked_sub(1)?;
1646 if current_index == 0 {
1647 return self.frames[0]
1648 .scopes
1649 .iter_mut()
1650 .rev()
1651 .find_map(|scope| scope.get_mut(&name));
1652 }
1653 let (earlier, current) = self.frames.split_at_mut(current_index);
1654 for scope in current[0].scopes.iter_mut().rev() {
1655 if let Some(value) = scope.get_mut(&name) {
1656 return Some(value);
1657 }
1658 }
1659 if uses_root {
1660 return earlier.first_mut().and_then(|root| {
1661 root.scopes
1662 .iter_mut()
1663 .rev()
1664 .find_map(|scope| scope.get_mut(&name))
1665 });
1666 }
1667 None
1668 }
1669
1670 fn set_existing(&mut self, name: &str, value: Value) -> bool {
1671 for scope in self.current_scopes_mut().iter_mut().rev() {
1672 if let Some(slot) = scope.get_mut(name) {
1677 *slot = value;
1678 return true;
1679 }
1680 }
1681 if self.frames.last().is_some_and(|frame| {
1682 frame.is_function
1683 && frame.function_module.as_deref() == Some(nybl::value::ROOT_MODULE_PATH)
1684 }) && let Some(slot) = self.frames.first_mut().and_then(|root| {
1685 root.scopes
1686 .iter_mut()
1687 .rev()
1688 .find_map(|scope| scope.get_mut(name))
1689 }) {
1690 *slot = value;
1691 return true;
1692 }
1693 false
1694 }
1695
1696 fn set_existing_by_idx(&mut self, idx: NameIdx, value: Value) -> bool {
1701 let current_index = self.frames.len() - 1;
1702 let name = self.frames[current_index].chunk.name(idx).to_string();
1703 for scope in self.frames[current_index].scopes.iter_mut().rev() {
1704 if let Some(slot) = scope.get_mut(&name) {
1705 *slot = value;
1706 return true;
1707 }
1708 }
1709 let uses_root = self.frames[current_index].is_function
1710 && self.frames[current_index].function_module.as_deref()
1711 == Some(nybl::value::ROOT_MODULE_PATH);
1712 if self.frames[current_index].is_function
1713 && self.frames[current_index]
1714 .lexical_context
1715 .module_aliases
1716 .contains_key(&name)
1717 {
1718 let frame = &mut self.frames[current_index];
1719 let overlay_scope = if frame.has_declaration_overlay {
1720 frame.scope_base - 1
1721 } else {
1722 let scope = frame.scope_base;
1723 frame.scopes.insert(scope, BTreeMap::new());
1724 frame.scope_base += 1;
1725 frame.has_declaration_overlay = true;
1726 scope
1727 };
1728 frame
1729 .scopes
1730 .get_mut(overlay_scope)
1731 .expect("alias overlay scope")
1732 .insert(name, value);
1733 return true;
1734 }
1735 if uses_root
1736 && let Some(slot) = self.frames[0]
1737 .scopes
1738 .iter_mut()
1739 .rev()
1740 .find_map(|scope| scope.get_mut(&name))
1741 {
1742 *slot = value;
1743 return true;
1744 }
1745 false
1746 }
1747
1748 fn value_candidates_hint(&self, target: &str) -> Option<String> {
1759 let mut candidates: Vec<String> = Vec::new();
1760 for scope in self.current_scopes() {
1761 for k in scope.keys() {
1762 candidates.push(k.clone());
1763 }
1764 }
1765 for name in self.functions.keys() {
1766 candidates.push(name.clone());
1767 }
1768 nybl::suggest::did_you_mean(target, candidates)
1769 }
1770
1771 fn callable_candidates_hint(&self, target: &str) -> Option<String> {
1776 let mut candidates: Vec<String> = self.functions.keys().cloned().collect();
1777 for b in nybl::suggest::CORE_CALLABLE_BUILTINS {
1778 candidates.push((*b).to_string());
1779 }
1780 nybl::suggest::did_you_mean(target, candidates)
1781 }
1782
1783 fn active_module_path(&self) -> &str {
1784 self.frames
1785 .last()
1786 .and_then(|frame| frame.function_module.as_deref())
1787 .unwrap_or(&self.current_module)
1788 }
1789
1790 fn module_lexical_context(&self, module_path: &str) -> Rc<ModuleLexicalContext> {
1791 if module_path == self.current_module {
1792 return Rc::clone(&self.root_lexical_context);
1793 }
1794 let cache = self.imports.borrow();
1795 match cache.get(module_path) {
1796 Some(ImportSlot::Loaded(artifacts)) => Rc::clone(&artifacts.lexical_context),
1797 _ => Rc::new(ModuleLexicalContext::default()),
1798 }
1799 }
1800
1801 fn publish_root_type_binding(&mut self, name: String, origin: String) {
1802 let context = Rc::make_mut(&mut self.root_lexical_context);
1803 Rc::make_mut(&mut context.type_bindings).insert(name, origin);
1804 }
1805
1806 fn publish_root_module_alias(
1807 &mut self,
1808 name: String,
1809 module: Option<Rc<nybl::value::NyblModule>>,
1810 ) {
1811 let context = Rc::make_mut(&mut self.root_lexical_context);
1812 let aliases = Rc::make_mut(&mut context.module_aliases);
1813 if let Some(module) = module {
1814 aliases.insert(name, module);
1815 } else {
1816 aliases.remove(&name);
1817 }
1818 }
1819
1820 fn publish_root_imported_function(&mut self, name: String, function: Rc<FnEntry>) {
1821 let context = Rc::make_mut(&mut self.root_lexical_context);
1822 Rc::make_mut(&mut context.imported_functions).insert(name, function);
1823 }
1824
1825 #[inline]
1829 fn lookup_function_entry(&self, name: &str) -> Option<Rc<FnEntry>> {
1830 let frame = self.frames.last()?;
1831 let defining_module = frame.function_module.as_deref();
1832 if let Some(module_path) = defining_module
1833 && module_path != nybl::value::ROOT_MODULE_PATH
1834 {
1835 let cache = self.imports.borrow();
1836 if let Some(ImportSlot::Loaded(artifacts)) = cache.get(module_path)
1837 && let Some((_, entry)) = artifacts
1838 .fn_decls
1839 .iter()
1840 .find(|(candidate, _)| candidate == name)
1841 {
1842 return Some(entry.clone());
1843 }
1844 }
1845
1846 let import_floor = if frame.is_function {
1852 frame.alias_scope_base
1853 } else {
1854 0
1855 };
1856 let runtime_imports_empty = self.imported_functions[import_floor..]
1857 .iter()
1858 .all(BTreeMap::is_empty);
1859 if runtime_imports_empty && frame.lexical_context.imported_functions.is_empty() {
1860 if let Some(module_path) = defining_module {
1861 return self
1862 .functions
1863 .get(name)
1864 .filter(|entry| entry.module_path == module_path)
1865 .cloned();
1866 }
1867 return self.functions.get(name).cloned();
1868 }
1869
1870 if let Some(entry) = self.imported_function(name) {
1871 return Some(entry.clone());
1872 }
1873 if let Some(module_path) = defining_module
1874 && let Some(entry) = self
1875 .functions
1876 .get(name)
1877 .filter(|entry| entry.module_path == module_path)
1878 {
1879 return Some(entry.clone());
1880 }
1881 if defining_module.is_none_or(|path| path == self.current_module) {
1882 self.functions.get(name).cloned()
1883 } else {
1884 None
1885 }
1886 }
1887
1888 #[inline]
1891 fn dispatch(&mut self, instr: Instr, line: u32) -> Result<Next, NyblError> {
1892 match instr {
1893 Instr::LoadConst(idx) => {
1895 let value = match self.current_chunk().constant(idx) {
1896 Constant::Int(n) => Value::Int(*n),
1897 Constant::Number(n) => Value::Number(*n),
1898 Constant::Str(s) => Value::__new_str_in(s.clone(), &self.memory),
1899 };
1900 self.push_value(value);
1901 }
1902 Instr::LoadNone => self.push_value(Value::None),
1903 Instr::LoadTrue => self.push_value(Value::Bool(true)),
1904 Instr::LoadFalse => self.push_value(Value::Bool(false)),
1905
1906 Instr::LoadVar(n) => {
1908 if let Some(v) = self.lookup_var_by_idx(n).cloned() {
1915 self.push_value(v);
1916 } else {
1917 let chunk = Arc::clone(&self.frames.last().expect("frame present").chunk);
1922 let name = chunk.name(n);
1923 if let Some(module) = self.module_alias(name).cloned() {
1924 self.push_value(Value::Module(module));
1925 return Ok(Next::Continue);
1926 }
1927 let fn_entry = self.lookup_function_entry(name);
1928 if let Some(entry) = fn_entry {
1929 let params = entry.params.clone();
1930 let body: Rc<dyn core::any::Any + 'static> = Rc::new(entry.chunk.clone());
1931 let v = NyblFn::try_new_compiled_in_module_with_origin_and_modes(
1932 params,
1933 entry.param_modes.clone(),
1934 Vec::new(),
1935 body,
1936 Some(name.to_string()),
1937 Some(entry.module_path.clone()),
1938 self.function_origin.clone(),
1939 0,
1940 line,
1941 )
1942 .map(Value::Fn)?;
1943 self.push_value(v);
1944 } else {
1945 let hint = self.value_candidates_hint(name).unwrap_or_else(|| {
1949 "Did you forget to create it with `let`?".to_string()
1950 });
1951 return Err(error_with_hint(
1952 line,
1953 nybl::error_messages::variable_not_found(name),
1954 hint,
1955 ));
1956 }
1957 }
1958 }
1959 Instr::DefineLocal(n) => {
1960 let name = self.current_chunk().name(n).to_string();
1964 let v = self.pop_value(line)?;
1965 let module = match &v {
1966 Value::Module(module) => Some(Rc::clone(module)),
1967 _ => None,
1968 };
1969 if self.is_module_top_scope()
1970 && let Some(origin) = self.binding_origins.get(&name).cloned()
1971 && (origin.0 != self.current_module || origin.1 != name)
1972 && let Some(previous) = self
1973 .current_scopes_mut()
1974 .last_mut()
1975 .and_then(|scope| scope.remove(&name))
1976 {
1977 self.live_value_environments
1978 .borrow_mut()
1979 .entry(origin.0)
1980 .or_default()
1981 .insert(origin.1, previous);
1982 }
1983 self.define_local(name.clone(), v);
1984 if let Some(imports) = self.import_scopes.last_mut() {
1985 imports.forget(&name);
1986 }
1987 if self.is_module_top_scope() {
1988 self.binding_origins
1989 .insert(name.clone(), (self.current_module.clone(), name.clone()));
1990 }
1991 self.sync_top_level_module_alias(name, module);
1992 }
1993 Instr::StoreVar(n) => {
1994 let v = self.pop_value(line)?;
1997 let module = match &v {
1998 Value::Module(module) => Some(Rc::clone(module)),
1999 _ => None,
2000 };
2001 let top_level_name = self
2002 .is_module_top_scope()
2003 .then(|| self.current_chunk().name(n).to_string());
2004 let runtime_alias_without_value_binding = {
2005 let chunk = Arc::clone(&self.frames.last().expect("frame present").chunk);
2006 let name = chunk.name(n);
2007 self.lookup_var_by_idx(n).is_none() && self.module_alias(name).is_some()
2008 };
2009 if runtime_alias_without_value_binding {
2010 let name = self.current_chunk().name(n).to_string();
2011 self.define_local(name, v);
2012 return Ok(Next::Continue);
2013 }
2014 if !self.set_existing_by_idx(n, v) {
2015 let chunk = Arc::clone(&self.frames.last().expect("frame present").chunk);
2018 let name = chunk.name(n);
2019 return Err(error_with_hint(
2020 line,
2021 format!("Variable `{name}` doesn't exist yet"),
2022 format!("Use `let` to create a new variable: let {name} = ..."),
2023 ));
2024 }
2025 if let Some(name) = top_level_name {
2026 self.sync_top_level_module_alias(name, module);
2027 }
2028 }
2029 Instr::CompoundAssign { target, op } => {
2030 let rhs = self.pop_value(line)?;
2031 let runtime_alias_without_value_binding = match target {
2032 crate::chunk::AssignBack::Name(name_idx) => {
2033 let chunk = Arc::clone(&self.frames.last().expect("frame present").chunk);
2034 self.lookup_var_by_idx(name_idx).is_none()
2035 && self.module_alias(chunk.name(name_idx)).is_some()
2036 }
2037 crate::chunk::AssignBack::Slot(_) => false,
2038 };
2039 let current = match target {
2040 crate::chunk::AssignBack::Slot(slot) => self
2041 .frames
2042 .last()
2043 .and_then(|frame| frame.slots.get(slot.0 as usize))
2044 .cloned()
2045 .ok_or_else(|| error(line, "VM: local slot out of range"))?,
2046 crate::chunk::AssignBack::Name(name_idx) => {
2047 if let Some(value) = self.lookup_var_by_idx(name_idx).cloned() {
2048 value
2049 } else {
2050 let chunk =
2051 Arc::clone(&self.frames.last().expect("frame present").chunk);
2052 let name = chunk.name(name_idx);
2053 if let Some(module) = self.module_alias(name).cloned() {
2054 Value::Module(module)
2055 } else {
2056 return Err(error(
2057 line,
2058 nybl::error_messages::variable_not_found(name),
2059 ));
2060 }
2061 }
2062 }
2063 };
2064 let value = apply_in_place_assign(op, rhs, line, &self.memory, || Ok(current))?;
2065 match target {
2066 crate::chunk::AssignBack::Slot(slot) => {
2067 let target = self
2068 .frames
2069 .last_mut()
2070 .expect("frame present")
2071 .slots
2072 .get_mut(slot.0 as usize)
2073 .ok_or_else(|| error(line, "VM: local slot out of range"))?;
2074 *target = value;
2075 }
2076 crate::chunk::AssignBack::Name(name) => {
2077 if runtime_alias_without_value_binding {
2078 let name = self.current_chunk().name(name).to_string();
2079 self.define_local(name, value);
2080 return Ok(Next::Continue);
2081 }
2082 if !self.set_existing_by_idx(name, value) {
2083 let chunk =
2084 Arc::clone(&self.frames.last().expect("frame present").chunk);
2085 return Err(error(
2086 line,
2087 nybl::error_messages::variable_not_found(chunk.name(name)),
2088 ));
2089 }
2090 }
2091 }
2092 }
2093
2094 Instr::LoadLocal(slot) => {
2096 let frame = self.frames.last().expect("frame present");
2101 let v = frame
2102 .slots
2103 .get(slot.0 as usize)
2104 .cloned()
2105 .ok_or_else(|| error(line, "VM: local slot out of range"))?;
2106 self.push_value(v);
2107 }
2108 Instr::StoreLocal(slot) => {
2109 let v = self.pop_value(line)?;
2110 let frame = self.frames.last_mut().expect("frame present");
2111 let i = slot.0 as usize;
2112 if i < frame.slots.len() {
2113 frame.slots[i] = v;
2114 } else {
2115 return Err(error(line, "VM: local slot out of range"));
2116 }
2117 }
2118
2119 Instr::AddLocals(a, b) => {
2121 let frame = self.frames.last().expect("frame present");
2126 let av = frame
2127 .slots
2128 .get(a.0 as usize)
2129 .ok_or_else(|| error(line, "VM: local slot out of range"))?;
2130 let bv = frame
2131 .slots
2132 .get(b.0 as usize)
2133 .ok_or_else(|| error(line, "VM: local slot out of range"))?;
2134 let result = match (av, bv) {
2135 (Value::Int(x), Value::Int(y)) => x
2136 .checked_add(*y)
2137 .map(Value::Int)
2138 .map_or_else(|| ops::add_in(av, bv, line, &self.memory), Ok)?,
2139 _ => ops::add_in(av, bv, line, &self.memory)?,
2143 };
2144 self.push_value(result);
2145 }
2146 Instr::LtLocals(a, b) => {
2147 let frame = self.frames.last().expect("frame present");
2148 let av = frame
2149 .slots
2150 .get(a.0 as usize)
2151 .ok_or_else(|| error(line, "VM: local slot out of range"))?;
2152 let bv = frame
2153 .slots
2154 .get(b.0 as usize)
2155 .ok_or_else(|| error(line, "VM: local slot out of range"))?;
2156 let result = match (av, bv) {
2157 (Value::Int(x), Value::Int(y)) => Value::Bool(x < y),
2158 _ => ops::lt_in(av, bv, line, &self.memory)?,
2159 };
2160 self.push_value(result);
2161 }
2162 Instr::IncLocalInt(slot, k) => {
2163 let memory = &self.memory;
2169 let frame = self.frames.last_mut().expect("frame present");
2170 let i = slot.0 as usize;
2171 let current = frame
2172 .slots
2173 .get(i)
2174 .ok_or_else(|| error(line, "VM: local slot out of range"))?;
2175 let new = match current {
2176 Value::Int(x) => x.checked_add(k as i64).map(Value::Int).map_or_else(
2177 || ops::add_in(current, &Value::Int(k as i64), line, memory),
2178 Ok,
2179 )?,
2180 _ => ops::add_in(current, &Value::Int(k as i64), line, memory)?,
2181 };
2182 frame.slots[i] = new;
2183 }
2184 Instr::LoadLocalAddInt(slot, k) => {
2185 let frame = self.frames.last().expect("frame present");
2188 let v = frame
2189 .slots
2190 .get(slot.0 as usize)
2191 .ok_or_else(|| error(line, "VM: local slot out of range"))?;
2192 let result = match v {
2193 Value::Int(x) => x.checked_add(k as i64).map(Value::Int).map_or_else(
2194 || ops::add_in(v, &Value::Int(k as i64), line, &self.memory),
2195 Ok,
2196 )?,
2197 _ => ops::add_in(v, &Value::Int(k as i64), line, &self.memory)?,
2198 };
2199 self.push_value(result);
2200 }
2201 Instr::LtLocalInt(slot, k) => {
2202 let frame = self.frames.last().expect("frame present");
2206 let v = frame
2207 .slots
2208 .get(slot.0 as usize)
2209 .ok_or_else(|| error(line, "VM: local slot out of range"))?;
2210 let result = match v {
2211 Value::Int(x) => Value::Bool(*x < k as i64),
2212 _ => ops::lt_in(v, &Value::Int(k as i64), line, &self.memory)?,
2213 };
2214 self.push_value(result);
2215 }
2216
2217 Instr::PushScope => self.push_scope(),
2219 Instr::PopScope => self.pop_scope(),
2220
2221 Instr::Pop => {
2223 if self.stack.pop().is_none() {
2224 return Err(error(line, "VM: stack underflow"));
2225 }
2226 }
2227 Instr::Dup => {
2228 let v = self.peek_value(line)?.clone();
2229 self.push_value(v);
2230 }
2231 Instr::Dup2 => {
2232 let len = self.stack.len();
2233 if len < 2 {
2234 return Err(error(line, "VM: stack underflow"));
2235 }
2236 let b = match &self.stack[len - 1] {
2237 Slot::Value(v) => v.clone(),
2238 _ => return Err(error(line, "VM: expected value on stack")),
2239 };
2240 let a = match &self.stack[len - 2] {
2241 Slot::Value(v) => v.clone(),
2242 _ => return Err(error(line, "VM: expected value on stack")),
2243 };
2244 self.push_value(a);
2245 self.push_value(b);
2246 }
2247
2248 Instr::Add => self.binary_tracked(line, ops::add_in)?,
2250 Instr::Sub => self.binary(line, ops::sub)?,
2251 Instr::Mul => self.binary_tracked(line, ops::mul_in)?,
2252 Instr::Div => self.binary(line, ops::div)?,
2253 Instr::Rem => self.binary(line, ops::rem)?,
2254 Instr::Eq => self.binary_infallible(line, |a, b, _| Ok(ops::eq(a, b)))?,
2255 Instr::NotEq => self.binary_infallible(line, |a, b, _| Ok(ops::not_eq(a, b)))?,
2256 Instr::Lt => self.binary(line, ops::lt)?,
2257 Instr::Gt => self.binary(line, ops::gt)?,
2258 Instr::LtEq => self.binary(line, ops::lt_eq)?,
2259 Instr::GtEq => self.binary(line, ops::gt_eq)?,
2260
2261 Instr::Neg => {
2263 let v = self.pop_value(line)?;
2264 self.push_value(ops::neg(&v, line)?);
2265 }
2266 Instr::Not => {
2267 let v = self.pop_value(line)?;
2268 self.push_value(ops::not(&v));
2269 }
2270
2271 Instr::TruthyToBool => {
2272 let v = self.pop_value(line)?;
2273 self.push_value(Value::Bool(v.is_truthy()));
2274 }
2275
2276 Instr::GetIndex => {
2278 let idx = self.pop_value(line)?;
2279 let obj = self.pop_value(line)?;
2280 self.push_value(ops::index_get_in(&obj, &idx, line, &self.memory)?);
2281 }
2282 Instr::SetIndex => {
2283 let val = self.pop_value(line)?;
2284 let idx = self.pop_value(line)?;
2285 let mut obj = self.pop_value(line)?;
2286 ops::index_set_in(&mut obj, &idx, val, line, &self.memory)?;
2287 self.push_value(obj);
2288 }
2289 Instr::SetIndexInPlace { target, op } => {
2290 let idx = self.pop_value(line)?;
2291 let rhs = self.pop_value(line)?;
2292 let memory = self.memory.clone();
2293 match target {
2294 crate::chunk::AssignBack::Slot(slot) => {
2295 let value = self
2296 .frames
2297 .last_mut()
2298 .expect("frame present")
2299 .slots
2300 .get_mut(slot.0 as usize)
2301 .ok_or_else(|| error(line, "VM: local slot out of range"))?;
2302 let val = apply_in_place_assign(op, rhs, line, &memory, || {
2303 ops::index_get_in(value, &idx, line, &memory)
2304 })?;
2305 ops::index_set_in(value, &idx, val, line, &memory)?;
2306 }
2307 crate::chunk::AssignBack::Name(name_idx) => {
2308 let name = self.current_chunk().name(name_idx).to_string();
2309 if self.lookup_var_mut_by_idx(name_idx).is_none() {
2310 if let Some(module) = self.module_alias(&name).cloned() {
2311 let mut value = Value::Module(module);
2312 let val = apply_in_place_assign(op, rhs, line, &memory, || {
2313 ops::index_get_in(&value, &idx, line, &memory)
2314 })?;
2315 ops::index_set_in(&mut value, &idx, val, line, &memory)?;
2316 return Ok(Next::Continue);
2317 }
2318 let hint = self.value_candidates_hint(&name).unwrap_or_else(|| {
2319 "Did you forget to create it with `let`?".to_string()
2320 });
2321 return Err(error_with_hint(
2322 line,
2323 nybl::error_messages::variable_not_found(&name),
2324 hint,
2325 ));
2326 }
2327 let value = self
2328 .lookup_var_mut_by_idx(name_idx)
2329 .expect("binding checked above");
2330 let val = apply_in_place_assign(op, rhs, line, &memory, || {
2331 ops::index_get_in(value, &idx, line, &memory)
2332 })?;
2333 ops::index_set_in(value, &idx, val, line, &memory)?;
2334 }
2335 }
2336 }
2337 Instr::AssignPlace { place, op } => {
2338 let index_count = self
2339 .current_chunk()
2340 .place(place)
2341 .projections
2342 .iter()
2343 .filter(|projection| matches!(projection, PlaceProjectionRecipe::Index))
2344 .count();
2345 let indices = self.pop_n_values(index_count, line)?;
2346 let rhs = self.pop_value(line)?;
2347 let resolved =
2348 self.resolve_place_internal(place, indices, 0, line, false, false)?;
2349 if nybl::naming::is_constant_name(&resolved.root_name) {
2350 return Err(nybl::error_messages::constant_mutation_error(
2351 &resolved.root_name,
2352 line,
2353 ));
2354 }
2355 let value = apply_in_place_assign(op, rhs, line, &self.memory, || {
2356 self.place_value_from(&resolved.root, &resolved.projections, line)
2357 })?;
2358 let mut root = resolved.root.clone();
2359 self.write_place_value(&mut root, &resolved.projections, value, line)?;
2360 self.store_resolved_target(&resolved.target, root, line)?;
2361 }
2362
2363 Instr::StringInterp(idx) => {
2365 let recipe_parts = Arc::clone(&self.current_chunk().interp(idx).parts);
2366 self.push_value(self.build_interp(&recipe_parts, line)?);
2367 }
2368
2369 Instr::MakeArray(n) => {
2371 let items = self.pop_n_values(n as usize, line)?;
2372 self.push_value(Value::__try_new_array_in(items, line, &self.memory)?);
2373 }
2374 Instr::MakeDict(n) => {
2375 let flat = self.pop_n_values((n as usize) * 2, line)?;
2376 let mut entries: Vec<(String, Value)> = Vec::with_capacity(n as usize);
2377 let mut iter = flat.into_iter();
2378 while let (Some(key), Some(val)) = (iter.next(), iter.next()) {
2379 let key_str = match &key {
2380 Value::Str(s) => s.as_str().to_string(),
2381 other => {
2382 return Err(error(
2383 line,
2384 format!("Dict keys must be strings, got {}", other.type_name()),
2385 ));
2386 }
2387 };
2388 drop(key);
2389 entries.push((key_str, val));
2390 }
2391 self.push_value(Value::__try_new_dict_in(entries, line, &self.memory)?);
2392 }
2393
2394 Instr::Call { name, argc } => {
2396 return self.call(name, argc as usize, line);
2397 }
2398 Instr::CallValue { argc } => {
2399 return self.call_value(argc as usize, line);
2400 }
2401 Instr::PrepareCall { name, site } => {
2402 self.prepare_named_call(name, site, line)?;
2403 }
2404 Instr::PrepareCallValue { site } => {
2405 let callee = self.pop_value(line)?;
2406 self.prepare_value_call(callee, site, line)?;
2407 }
2408 Instr::PrepareMethodValue {
2409 method,
2410 site,
2411 nested_place,
2412 } => {
2413 let receiver = self.pop_value(line)?;
2414 self.prepare_method_call(receiver, None, None, method, site, nested_place, line)?;
2415 }
2416 Instr::PrepareMethodNamed {
2417 target,
2418 method,
2419 site,
2420 } => {
2421 self.prepare_named_method_call(target, method, site, line)?;
2422 }
2423 Instr::PrepareMethodPlace {
2424 place,
2425 method,
2426 site,
2427 } => {
2428 let index_count = self
2429 .current_chunk()
2430 .place(place)
2431 .projections
2432 .iter()
2433 .filter(|projection| matches!(projection, PlaceProjectionRecipe::Index))
2434 .count();
2435 let indices = self.pop_n_values(index_count, line)?;
2436 let resolved = self.resolve_place(place, indices, 0, line)?;
2437 let receiver =
2438 self.place_value_from(&resolved.root, &resolved.projections, line)?;
2439 self.prepare_method_call(receiver, None, Some(resolved), method, site, true, line)?;
2440 }
2441 Instr::CallPrepared { site } => {
2442 return self.call_prepared(site, line);
2443 }
2444 Instr::CallMethod {
2445 method,
2446 argc,
2447 assign_back_to,
2448 nested_place,
2449 } => {
2450 return self.call_method(method, argc as usize, assign_back_to, nested_place, line);
2451 }
2452 Instr::CallMethodInPlace {
2453 target,
2454 method,
2455 argc,
2456 } => {
2457 return self.call_method_in_place(target, method, argc as usize, line);
2458 }
2459
2460 Instr::DefineFn(idx) => {
2462 self.define_fn(idx, line)?;
2463 }
2464 Instr::MakeLambda(idx) => {
2465 self.make_lambda(idx, line)?;
2466 }
2467 Instr::Return => {
2468 let v = self.pop_value(line)?;
2469 return self.do_return(v, line);
2470 }
2471 Instr::ReturnNone => {
2472 return self.do_return(Value::None, line);
2473 }
2474
2475 Instr::MakeIter => {
2477 let mut v = self.pop_value(line)?;
2478 match &mut v {
2485 Value::Array(arr) => {
2486 let mut items = arr.__take_in(&self.memory);
2487 drop(v);
2488 items.reverse();
2489 self.stack.push(Slot::Iter(items));
2490 }
2491 Value::Str(s) => {
2492 let mut items: Vec<Value> = s
2493 .chars()
2494 .map(|c| Value::__new_str_in(c.to_string(), &self.memory))
2495 .collect();
2496 drop(v);
2497 items.reverse();
2498 self.stack.push(Slot::Iter(items));
2499 }
2500 Value::Dict(d) => {
2501 let mut items: Vec<Value> = d
2502 .iter()
2503 .map(|(k, _)| Value::__new_str_in(k.clone(), &self.memory))
2504 .collect();
2505 drop(v);
2506 items.reverse();
2507 self.stack.push(Slot::Iter(items));
2508 }
2509 Value::Iter(_) => {
2510 self.stack.push(Slot::IterObject(v));
2512 }
2513 Value::Struct(_) | Value::EnumVariant(_) => {
2514 let iterable = v;
2518 self.dispatch_iter_method(
2519 iterable,
2520 "iter",
2521 Vec::new(),
2522 FrameWrap::IterStart,
2523 line,
2524 )?;
2525 }
2526 _ => {
2527 return Err(error(
2528 line,
2529 nybl::error_messages::cant_iterate_over(v.type_name()),
2530 ));
2531 }
2532 }
2533 }
2534 Instr::IterNext { target } => {
2535 match self.stack.last_mut() {
2536 Some(Slot::Iter(items)) => {
2537 let next = items.pop();
2538 match next {
2539 Some(item) => self.push_value(item),
2540 None => {
2541 self.stack.pop();
2542 self.jump(target);
2543 }
2544 }
2545 }
2546 Some(Slot::IterObject(iter_val)) => {
2547 if matches!(iter_val, Value::Iter(_)) {
2551 let iter_clone = iter_val.clone();
2552 let (result, _) = methods::iter_method_in(
2553 &iter_clone,
2554 "next",
2555 &[],
2556 line,
2557 &self.memory,
2558 )?;
2559 match unwrap_iter_step(&result) {
2560 IterStep::Next(v) => self.push_value(v),
2561 IterStep::Done => {
2562 self.stack.pop();
2563 self.jump(target);
2564 }
2565 IterStep::Malformed => {
2566 return Err(error(
2567 line,
2568 format!(
2569 "`.next()` on a `for` iterator must return `Iter::Next(v)` or `Iter::Done`, got {}",
2570 result.inspect()
2571 ),
2572 ));
2573 }
2574 }
2575 } else {
2576 let iter_clone = iter_val.clone();
2581 self.dispatch_iter_method(
2582 iter_clone,
2583 "next",
2584 Vec::new(),
2585 FrameWrap::IterAdvance(target),
2586 line,
2587 )?;
2588 }
2589 }
2590 _ => return Err(error(line, "VM: expected iterator on stack")),
2591 }
2592 }
2593 Instr::MakeRepeatCount => {
2594 let v = self.pop_value(line)?;
2595 let n = match v {
2596 Value::Int(n) => n,
2597 Value::Number(n) => n as i64,
2598 other => {
2599 return Err(error(
2600 line,
2601 format!("repeat needs a number, but got {}", other.type_name()),
2602 ));
2603 }
2604 };
2605 self.stack.push(Slot::Repeat(n.max(0)));
2606 }
2607 Instr::RepeatNext { target } => {
2608 let done = match self.stack.last_mut() {
2609 Some(Slot::Repeat(n)) => {
2610 if *n > 0 {
2611 *n -= 1;
2612 false
2613 } else {
2614 true
2615 }
2616 }
2617 _ => return Err(error(line, "VM: expected repeat counter on stack")),
2618 };
2619 if done {
2620 self.stack.pop();
2621 self.jump(target);
2622 }
2623 }
2624 Instr::PopLoopState(kind) => {
2625 let matches_kind = matches!(
2626 (kind, self.stack.last()),
2627 (
2628 LoopStateKind::Iterator,
2629 Some(Slot::Iter(_) | Slot::IterObject(_)),
2630 ) | (LoopStateKind::Repeat, Some(Slot::Repeat(_)))
2631 );
2632 if !matches_kind {
2633 let expected = match kind {
2634 LoopStateKind::Iterator => "iterator",
2635 LoopStateKind::Repeat => "repeat counter",
2636 };
2637 return Err(error(
2638 line,
2639 format!("VM: expected {expected} loop state on stack"),
2640 ));
2641 }
2642 self.stack.pop();
2643 }
2644
2645 Instr::Jump(t) => self.jump(t),
2647 Instr::JumpIfFalse(t) => {
2648 let v = self.pop_value(line)?;
2649 if !v.is_truthy() {
2650 self.jump(t);
2651 }
2652 }
2653 Instr::JumpIfFalsePeek(t) => {
2654 let truthy = self.peek_value(line)?.is_truthy();
2655 if !truthy {
2656 self.jump(t);
2657 }
2658 }
2659 Instr::JumpIfTruePeek(t) => {
2660 let truthy = self.peek_value(line)?.is_truthy();
2661 if truthy {
2662 self.jump(t);
2663 }
2664 }
2665
2666 Instr::Use(idx) => {
2668 let spec = self.current_chunk().use_spec(idx).clone();
2669 self.exec_use(&spec, line)?;
2670 }
2671
2672 Instr::DefineStruct(idx) => self.define_struct(idx, line)?,
2674 Instr::DefineEnum(idx) => self.define_enum(idx, line)?,
2675 Instr::DefineMethod {
2676 type_name,
2677 method_name,
2678 fn_idx,
2679 } => self.define_method(type_name, method_name, fn_idx),
2680 Instr::ValidateStructConstruct {
2681 namespace,
2682 type_name,
2683 fields,
2684 } => {
2685 let chunk = Arc::clone(&self.frames.last().expect("frame present").chunk);
2686 self.validate_struct_construct(
2687 namespace.map(|namespace| chunk.namespace_ref(namespace)),
2688 chunk.name(type_name),
2689 chunk.construct_fields(fields),
2690 line,
2691 )?;
2692 }
2693 Instr::ValidateEnumConstruct {
2694 namespace,
2695 type_name,
2696 variant,
2697 shape,
2698 fields,
2699 } => {
2700 let chunk = Arc::clone(&self.frames.last().expect("frame present").chunk);
2701 self.validate_enum_construct(
2702 namespace.map(|namespace| chunk.namespace_ref(namespace)),
2703 chunk.name(type_name),
2704 chunk.name(variant),
2705 shape,
2706 chunk.construct_fields(fields),
2707 line,
2708 )?;
2709 }
2710 Instr::ConstructStruct {
2711 namespace,
2712 type_name,
2713 count,
2714 } => {
2715 let namespace =
2716 namespace.map(|namespace| self.current_chunk().namespace_ref(namespace));
2717 self.construct_struct(namespace, type_name, count as usize, line)?;
2718 }
2719 Instr::ConstructEnum {
2720 namespace,
2721 type_name,
2722 variant,
2723 shape,
2724 } => {
2725 let namespace =
2726 namespace.map(|namespace| self.current_chunk().namespace_ref(namespace));
2727 self.construct_enum(namespace, type_name, variant, shape, line)?;
2728 }
2729 Instr::FieldGet(n) => {
2730 let field = self.current_chunk().name(n).to_string();
2731 let obj = self.pop_value(line)?;
2732 self.push_value(self.field_get(&obj, &field, line)?);
2733 }
2734 Instr::FieldSet(n) => {
2735 let field = self.current_chunk().name(n).to_string();
2736 let val = self.pop_value(line)?;
2737 let obj = self.pop_value(line)?;
2738 self.push_value(self.field_set(obj, &field, val, line)?);
2739 }
2740 Instr::FieldSetInPlace { target, field, op } => {
2741 let field = self.current_chunk().name(field).to_string();
2742 let rhs = self.pop_value(line)?;
2743 let memory = self.memory.clone();
2744
2745 let value = match target {
2746 crate::chunk::AssignBack::Slot(slot) => self
2747 .frames
2748 .last_mut()
2749 .expect("frame present")
2750 .slots
2751 .get_mut(slot.0 as usize)
2752 .ok_or_else(|| error(line, "VM: local slot out of range"))?,
2753 crate::chunk::AssignBack::Name(name_idx) => {
2754 let name = self.current_chunk().name(name_idx).to_string();
2755 if self.lookup_var_mut_by_idx(name_idx).is_none() {
2756 if let Some(module) = self.module_alias(&name).cloned() {
2757 let value = Value::Module(module);
2758 let val = apply_in_place_assign(op, rhs, line, &memory, || {
2759 self.field_get(&value, &field, line)
2760 })?;
2761 self.field_set(value, &field, val, line)?;
2762 return Ok(Next::Continue);
2763 }
2764 let hint = self.value_candidates_hint(&name).unwrap_or_else(|| {
2765 "Did you forget to create it with `let`?".to_string()
2766 });
2767 return Err(error_with_hint(
2768 line,
2769 nybl::error_messages::variable_not_found(&name),
2770 hint,
2771 ));
2772 }
2773 self.lookup_var_mut_by_idx(name_idx)
2774 .expect("binding checked above")
2775 }
2776 };
2777 match value {
2778 Value::Struct(structure) => {
2779 let type_name = structure.type_name().to_string();
2780 let val = apply_in_place_assign(op, rhs, line, &memory, || {
2781 structure.field(&field).cloned().ok_or_else(|| {
2782 error(
2783 line,
2784 nybl::error_messages::struct_has_no_field(&type_name, &field),
2785 )
2786 })
2787 })?;
2788 if !structure.__try_set_field_in(&field, val, line, &memory)? {
2789 return Err(error(
2790 line,
2791 nybl::error_messages::struct_has_no_field(&type_name, &field),
2792 ));
2793 }
2794 }
2795 other => {
2796 return Err(error(
2797 line,
2798 nybl::error_messages::cant_assign_field(&field, other.type_name()),
2799 ));
2800 }
2801 }
2802 }
2803
2804 Instr::MatchFail { pattern, on_fail } => {
2806 self.match_fail(pattern, on_fail, line)?;
2807 }
2808 Instr::MatchExhausted => {
2809 return Err(error(line, "No match arm matched the scrutinee"));
2810 }
2811
2812 Instr::TryUnwrap => {
2814 return self.try_unwrap(line);
2815 }
2816
2817 Instr::Halt => return Ok(Next::Halt),
2819 }
2820
2821 Ok(Next::Continue)
2822 }
2823
2824 fn binary(
2827 &mut self,
2828 line: u32,
2829 op: fn(&Value, &Value, u32) -> Result<Value, NyblError>,
2830 ) -> Result<(), NyblError> {
2831 let b = self.pop_value(line)?;
2832 let a = self.pop_value(line)?;
2833 self.push_value(op(&a, &b, line)?);
2834 Ok(())
2835 }
2836
2837 fn binary_tracked(
2838 &mut self,
2839 line: u32,
2840 op: fn(&Value, &Value, u32, &nybl::memory::MemoryContext) -> Result<Value, NyblError>,
2841 ) -> Result<(), NyblError> {
2842 let b = self.pop_value(line)?;
2843 let a = self.pop_value(line)?;
2844 self.push_value(op(&a, &b, line, &self.memory)?);
2845 Ok(())
2846 }
2847
2848 fn binary_infallible(
2849 &mut self,
2850 line: u32,
2851 op: fn(&Value, &Value, u32) -> Result<Value, NyblError>,
2852 ) -> Result<(), NyblError> {
2853 let b = self.pop_value(line)?;
2854 let a = self.pop_value(line)?;
2855 self.push_value(op(&a, &b, line)?);
2856 Ok(())
2857 }
2858
2859 fn build_interp(&self, parts: &[InterpPart], line: u32) -> Result<Value, NyblError> {
2862 let mut result = String::new();
2863 for part in parts {
2864 match part {
2865 InterpPart::Literal(s) => result.push_str(s),
2866 InterpPart::Local(slot) => {
2867 let v = self
2868 .frames
2869 .last()
2870 .and_then(|frame| frame.slots.get(slot.0 as usize))
2871 .ok_or_else(|| error(line, "VM: local slot out of range"))?;
2872 result.push_str(&format!("{v}"));
2873 }
2874 InterpPart::Name(name_idx) => {
2875 let name = self.current_chunk().name(*name_idx);
2876 if let Some(value) = self.lookup_var_by_idx(*name_idx) {
2877 result.push_str(&format!("{value}"));
2878 } else if let Some(module) = self.module_alias(name) {
2879 result.push_str(&format!("{}", Value::Module(Rc::clone(module))));
2880 } else {
2881 return Err(error(line, nybl::error_messages::variable_not_found(name)));
2882 }
2883 }
2884 }
2885 }
2886 Ok(Value::__new_str_in(result, &self.memory))
2887 }
2888
2889 fn current_chunk(&self) -> &Chunk {
2892 &self.frames.last().expect("frame present").chunk
2893 }
2894
2895 fn prepare_named_call(
2898 &mut self,
2899 name_idx: NameIdx,
2900 site: CallSiteIdx,
2901 line: u32,
2902 ) -> Result<(), NyblError> {
2903 let chunk = Arc::clone(&self.frames.last().expect("frame present").chunk);
2904 let name = chunk.name(name_idx).to_string();
2905
2906 let scoped = self
2907 .current_scopes()
2908 .iter()
2909 .rev()
2910 .find_map(|scope| scope.get(&name))
2911 .cloned();
2912 let callable = if let Some(value) = scoped {
2913 match value {
2914 Value::Fn(function) => PreparedCallable::Closure(function),
2915 other => {
2916 return Err(error(
2917 line,
2918 format!("`{name}` is a {}, not a function", other.type_name()),
2919 ));
2920 }
2921 }
2922 } else if let Some(entry) = self
2923 .frames
2924 .last()
2925 .and_then(|frame| frame.current_function_entry.as_ref())
2926 .filter(|entry| entry.exact_self_name.as_deref() == Some(name.as_str()))
2927 .cloned()
2928 {
2929 PreparedCallable::User(entry)
2930 } else if let Some(module) = self
2931 .frames
2932 .last()
2933 .and_then(|frame| frame.lexical_context.module_aliases.get(&name).cloned())
2934 {
2935 return Err(error(
2936 line,
2937 format!(
2938 "`{name}` is a {}, not a function",
2939 Value::Module(module).type_name()
2940 ),
2941 ));
2942 } else if let Some(entry) = self.imported_function(&name).cloned() {
2943 PreparedCallable::User(entry)
2944 } else if self.frames.last().is_some_and(|frame| {
2945 frame.is_function
2946 && frame.function_module.as_deref() == Some(nybl::value::ROOT_MODULE_PATH)
2947 }) {
2948 match self
2949 .frames
2950 .first()
2951 .and_then(|root| root.scopes.iter().rev().find_map(|scope| scope.get(&name)))
2952 .cloned()
2953 {
2954 Some(Value::Fn(function)) => PreparedCallable::Closure(function),
2955 Some(other) => {
2956 return Err(error(
2957 line,
2958 format!("`{name}` is a {}, not a function", other.type_name()),
2959 ));
2960 }
2961 None => self
2962 .lookup_function_entry(&name)
2963 .map(|entry| PreparedCallable::named_user(&name, entry))
2964 .unwrap_or_else(|| PreparedCallable::NamedFallback(name.clone())),
2965 }
2966 } else {
2967 self.lookup_function_entry(&name)
2968 .map(|entry| PreparedCallable::named_user(&name, entry))
2969 .unwrap_or_else(|| PreparedCallable::NamedFallback(name.clone()))
2970 };
2971 self.preflight_call(callable, name, site, line)
2972 }
2973
2974 fn prepare_value_call(
2975 &mut self,
2976 callee: Value,
2977 site: CallSiteIdx,
2978 line: u32,
2979 ) -> Result<(), NyblError> {
2980 match callee {
2981 Value::Fn(function) => {
2982 let display = function.self_name.as_deref().unwrap_or("fn").to_string();
2983 self.preflight_call(PreparedCallable::Closure(function), display, site, line)
2984 }
2985 other => Err(error(
2986 line,
2987 nybl::error_messages::cant_call_a(other.type_name()),
2988 )),
2989 }
2990 }
2991
2992 #[allow(clippy::too_many_arguments)]
2993 fn prepare_method_call(
2994 &mut self,
2995 receiver: Value,
2996 receiver_target: Option<NamespaceRef>,
2997 receiver_place: Option<ResolvedPlace>,
2998 method_idx: NameIdx,
2999 site: CallSiteIdx,
3000 nested_place: bool,
3001 line: u32,
3002 ) -> Result<(), NyblError> {
3003 let method = self.current_chunk().name(method_idx).to_string();
3004 if let Value::Module(module) = &receiver {
3005 if matches!(method.as_str(), "type" | "to_str" | "inspect") {
3007 return self.preflight_call(
3008 PreparedCallable::DeferredMethod {
3009 receiver,
3010 method: method.clone(),
3011 nested_place,
3012 },
3013 method,
3014 site,
3015 line,
3016 );
3017 }
3018 let callee = self.module_binding(module, &method).ok_or_else(|| {
3019 error(
3020 line,
3021 format!("`{method}` isn't exported from `{}`", module.path),
3022 )
3023 })?;
3024 return self.prepare_value_call(callee, site, line);
3025 }
3026
3027 let type_key = match &receiver {
3028 Value::Struct(value) => Some((
3029 value.module_path().to_string(),
3030 value.type_name().to_string(),
3031 )),
3032 Value::EnumVariant(value) => Some((
3033 value.module_path().to_string(),
3034 value.type_name().to_string(),
3035 )),
3036 _ => None,
3037 };
3038 if let Some(type_key) = type_key
3039 && let Some(entry) = self
3040 .user_methods
3041 .get(&type_key)
3042 .and_then(|methods| methods.get(&method))
3043 .cloned()
3044 {
3045 return self.preflight_call(
3046 PreparedCallable::UserMethod {
3047 entry,
3048 receiver,
3049 receiver_target,
3050 receiver_place,
3051 },
3052 format!("{}.{}", type_key.1, method),
3053 site,
3054 line,
3055 );
3056 }
3057 if methods::is_mutating_collection_receiver(&receiver, &method)
3058 && let Some(place) = receiver_place
3059 {
3060 return self.preflight_call(
3061 PreparedCallable::PlaceMethodInPlace {
3062 place,
3063 method: method.clone(),
3064 },
3065 method,
3066 site,
3067 line,
3068 );
3069 }
3070 if nested_place && receiver_place.is_none() {
3071 methods::reject_nested_array_mutation(&receiver, &method, line)?;
3072 }
3073 self.preflight_call(
3074 PreparedCallable::DeferredMethod {
3075 receiver,
3076 method: method.clone(),
3077 nested_place,
3078 },
3079 method,
3080 site,
3081 line,
3082 )
3083 }
3084
3085 fn prepare_named_method_call(
3086 &mut self,
3087 target: NamespaceRef,
3088 method_idx: NameIdx,
3089 site: CallSiteIdx,
3090 line: u32,
3091 ) -> Result<(), NyblError> {
3092 let method = self.current_chunk().name(method_idx).to_string();
3093 let receiver_name = self.current_chunk().name(target.name_idx()).to_string();
3094 let receiver = match target.slot_idx() {
3095 Some(slot) => self
3096 .frames
3097 .last()
3098 .and_then(|frame| frame.slots.get(slot.0 as usize))
3099 .cloned()
3100 .ok_or_else(|| error(line, "VM: local slot out of range"))?,
3101 None => {
3102 let value = self
3103 .current_scopes()
3104 .iter()
3105 .rev()
3106 .find_map(|scope| scope.get(&receiver_name))
3107 .cloned();
3108 match value {
3109 Some(value) => value,
3110 None => {
3111 if let Some(entry) = self.lookup_function_entry(&receiver_name) {
3112 let body: Rc<dyn core::any::Any + 'static> =
3113 Rc::new(entry.chunk.clone());
3114 let function =
3115 NyblFn::try_new_compiled_in_module_with_origin_and_modes(
3116 entry.params.clone(),
3117 entry.param_modes.clone(),
3118 Vec::new(),
3119 body,
3120 Some(receiver_name.clone()),
3121 Some(entry.module_path.clone()),
3122 self.function_origin.clone(),
3123 0,
3124 line,
3125 )?;
3126 return self.prepare_method_call(
3127 Value::Fn(function),
3128 None,
3129 None,
3130 method_idx,
3131 site,
3132 false,
3133 line,
3134 );
3135 }
3136 if let Some(module) = self.module_alias(&receiver_name).cloned() {
3137 return self.prepare_method_call(
3138 Value::Module(module),
3139 None,
3140 None,
3141 method_idx,
3142 site,
3143 false,
3144 line,
3145 );
3146 }
3147 let hint =
3148 self.value_candidates_hint(&receiver_name)
3149 .unwrap_or_else(|| {
3150 "Did you forget to create it with `let`?".to_string()
3151 });
3152 return Err(error_with_hint(
3153 line,
3154 nybl::error_messages::variable_not_found(&receiver_name),
3155 hint,
3156 ));
3157 }
3158 }
3159 }
3160 };
3161
3162 if methods::is_mutating_collection_receiver(&receiver, &method) {
3163 return self.preflight_call(
3164 PreparedCallable::NamedMethodInPlace {
3165 target,
3166 method: method.clone(),
3167 },
3168 method,
3169 site,
3170 line,
3171 );
3172 }
3173 self.prepare_method_call(receiver, Some(target), None, method_idx, site, false, line)
3174 }
3175
3176 fn preflight_call(
3177 &mut self,
3178 callable: PreparedCallable,
3179 display_name: String,
3180 site_idx: CallSiteIdx,
3181 line: u32,
3182 ) -> Result<(), NyblError> {
3183 let site = self.current_chunk().call_site(site_idx).clone();
3184 if let PreparedCallable::NamedFallback(name) = &callable {
3185 validate_named_builtin_arity(name, site.arg_modes.len(), line)?;
3186 }
3187 let expected_modes: Option<&[ParamMode]> = match &callable {
3188 PreparedCallable::User(entry) | PreparedCallable::HostThenUser { entry, .. } => {
3189 Some(&entry.param_modes)
3190 }
3191 PreparedCallable::Closure(function) => Some(&function.param_modes),
3192 PreparedCallable::UserMethod {
3193 entry,
3194 receiver_target,
3195 receiver_place,
3196 ..
3197 } => {
3198 validate_user_arity(
3199 &display_name,
3200 &entry.param_modes,
3201 site.arg_modes.len() + 1,
3202 true,
3203 line,
3204 )?;
3205 if entry.param_modes.first() == Some(&ParamMode::Ref)
3206 && receiver_target.is_none()
3207 && receiver_place.is_none()
3208 {
3209 let mut error =
3210 NyblError::runtime("a `ref` method receiver must be a mutable place", line);
3211 error.friendly_hint = Some(
3212 "Store the value in a `let` binding, or call through one of its fields or indexes."
3213 .to_string(),
3214 );
3215 return Err(error);
3216 }
3217 Some(&entry.param_modes[1..])
3218 }
3219 PreparedCallable::NamedFallback(_)
3220 | PreparedCallable::DeferredMethod { .. }
3221 | PreparedCallable::NamedMethodInPlace { .. }
3222 | PreparedCallable::PlaceMethodInPlace { .. } => None,
3223 };
3224 if let Some(expected) = expected_modes {
3225 validate_user_call_modes(&display_name, expected, &site.arg_modes, line)?;
3226 } else if let Some((index, _)) = site
3227 .arg_modes
3228 .iter()
3229 .enumerate()
3230 .find(|(_, mode)| **mode == ParamMode::Ref)
3231 {
3232 return Err(call_mode_error(
3233 line,
3234 &display_name,
3235 index,
3236 ParamMode::Value,
3237 ));
3238 }
3239
3240 if matches!(
3241 &callable,
3242 PreparedCallable::NamedMethodInPlace { .. }
3243 | PreparedCallable::PlaceMethodInPlace { .. }
3244 ) || matches!(
3245 &callable,
3246 PreparedCallable::DeferredMethod { receiver, .. }
3247 if !matches!(receiver, Value::Host(_))
3248 ) {
3249 validate_builtin_method_arity(&display_name, site.arg_modes.len(), line)?;
3250 }
3251 if let PreparedCallable::NamedMethodInPlace { target, method } = &callable {
3252 let receiver_name = self.current_chunk().name(target.name_idx());
3253 methods::reject_constant_array_mutation(receiver_name, method, line)?;
3254 if target.slot_idx().is_none()
3255 && self
3256 .frames
3257 .last()
3258 .is_some_and(|frame| frame.captured_names.contains(receiver_name))
3259 {
3260 return Err(nybl::ref_params::captured_ref_target(1, line));
3261 }
3262 }
3263 if let PreparedCallable::PlaceMethodInPlace { place, method } = &callable {
3264 methods::reject_constant_array_mutation(&place.root_name, method, line)?;
3265 self.validate_mutable_resolved_target(&place.target, &place.root_name, 0, line)?;
3266 }
3267
3268 let receiver_ref = match &callable {
3269 PreparedCallable::UserMethod {
3270 entry,
3271 receiver_target,
3272 receiver_place,
3273 ..
3274 } if entry.param_modes.first() == Some(&ParamMode::Ref) => {
3275 if let Some(place) = receiver_place {
3276 self.validate_mutable_resolved_target(
3277 &place.target,
3278 &place.root_name,
3279 0,
3280 line,
3281 )?;
3282 Some(PreparedReceiverRef::Place(place.clone()))
3283 } else {
3284 let recipe = receiver_target.expect("mutable receiver target was preflighted");
3285 let name = self.current_chunk().name(recipe.name_idx());
3286 if nybl::naming::is_constant_name(name) {
3287 return Err(nybl::error_messages::constant_mutation_error(name, line));
3288 }
3289 if recipe.slot_idx().is_none()
3290 && self
3291 .frames
3292 .last()
3293 .is_some_and(|frame| frame.captured_names.contains(name))
3294 {
3295 return Err(nybl::ref_params::captured_ref_target(1, line));
3296 }
3297 Some(PreparedReceiverRef::Binding(recipe))
3298 }
3299 }
3300 _ => None,
3301 };
3302 let mut seen = BTreeSet::new();
3303 if let Some(receiver) = &receiver_ref {
3304 let identity = match receiver {
3305 PreparedReceiverRef::Binding(recipe) => match recipe.slot_idx() {
3306 Some(slot) => (0_u8, slot.0),
3307 None => (1_u8, recipe.name_idx().0),
3308 },
3309 PreparedReceiverRef::Place(place) => match place.root_recipe.slot_idx() {
3310 Some(slot) => (0_u8, slot.0),
3311 None => (1_u8, place.root_recipe.name_idx().0),
3312 },
3313 };
3314 seen.insert(identity);
3315 }
3316 let mut refs = Vec::new();
3317 for (index, (mode, target)) in site
3318 .arg_modes
3319 .iter()
3320 .zip(site.ref_targets.iter())
3321 .enumerate()
3322 {
3323 if *mode != ParamMode::Ref {
3324 continue;
3325 }
3326 let recipe = match target {
3327 Some(RefArgTarget::Binding(recipe)) => RefArgTarget::Binding(*recipe),
3328 Some(RefArgTarget::Place(place)) => RefArgTarget::Place(*place),
3329 Some(RefArgTarget::Invalid) | None => {
3330 return Err(invalid_ref_target_error(line, index));
3331 }
3332 };
3333 let root = match recipe {
3334 RefArgTarget::Binding(root) => root,
3335 RefArgTarget::Place(place) => self.current_chunk().place(place).root,
3336 RefArgTarget::Invalid => unreachable!(),
3337 };
3338 let name = self.current_chunk().name(root.name_idx());
3339 if nybl::naming::is_constant_name(name) {
3340 return Err(nybl::error_messages::constant_mutation_error(name, line));
3341 }
3342 if root.slot_idx().is_none()
3343 && self
3344 .frames
3345 .last()
3346 .is_some_and(|frame| frame.captured_names.contains(name))
3347 {
3348 return Err(nybl::ref_params::captured_ref_target(index + 1, line));
3349 }
3350 let root_exists = match root.slot_idx() {
3351 Some(slot) => self
3352 .frames
3353 .last()
3354 .is_some_and(|frame| frame.slots.get(slot.0 as usize).is_some()),
3355 None => self
3356 .current_scopes()
3357 .iter()
3358 .rev()
3359 .any(|scope| scope.contains_key(name)),
3360 };
3361 if !root_exists {
3362 return Err(invalid_ref_target_error(line, index));
3363 }
3364 let identity = match root.slot_idx() {
3365 Some(slot) => (0_u8, slot.0),
3366 None => (1_u8, root.name_idx().0),
3367 };
3368 if !seen.insert(identity) {
3369 return Err(duplicate_ref_target_error(line));
3370 }
3371 refs.push(PreparedRef {
3372 param: index,
3373 recipe,
3374 index_count: match recipe {
3375 RefArgTarget::Place(place) => self
3376 .current_chunk()
3377 .place(place)
3378 .projections
3379 .iter()
3380 .filter(|projection| matches!(projection, PlaceProjectionRecipe::Index))
3381 .count(),
3382 RefArgTarget::Binding(_) | RefArgTarget::Invalid => 0,
3383 },
3384 });
3385 }
3386 let value_count = site
3387 .arg_modes
3388 .iter()
3389 .filter(|mode| **mode == ParamMode::Value)
3390 .count();
3391 let ref_index_count = refs.iter().map(|prepared| prepared.index_count).sum();
3392 self.frames
3393 .last_mut()
3394 .expect("frame present")
3395 .prepared_calls
3396 .push(PreparedCall {
3397 site: site_idx,
3398 callable,
3399 display_name,
3400 refs,
3401 receiver_ref,
3402 value_count,
3403 ref_index_count,
3404 });
3405 Ok(())
3406 }
3407
3408 fn call_prepared(&mut self, site: CallSiteIdx, line: u32) -> Result<Next, NyblError> {
3409 let prepared = self
3410 .frames
3411 .last_mut()
3412 .expect("frame present")
3413 .prepared_calls
3414 .pop()
3415 .ok_or_else(|| error(line, "VM: missing prepared call"))?;
3416 if prepared.site != site {
3417 return Err(error(line, "VM: prepared call-site mismatch"));
3418 }
3419 let stacked = self.pop_n_values(prepared.value_count + prepared.ref_index_count, line)?;
3420 let (ordinary, ref_indices) = stacked.split_at(prepared.value_count);
3421 let modes = self.current_chunk().call_site(site).arg_modes.clone();
3422 let param_offset = usize::from(matches!(
3423 &prepared.callable,
3424 PreparedCallable::UserMethod { .. }
3425 ));
3426 let mut ordinary = ordinary.iter().cloned();
3427 let mut full_args: Vec<Option<Value>> =
3428 core::iter::repeat_with(|| None).take(modes.len()).collect();
3429 for (index, mode) in modes.iter().enumerate() {
3430 if *mode == ParamMode::Value {
3431 full_args[index] = ordinary.next();
3432 }
3433 }
3434
3435 let mut pending =
3436 Vec::with_capacity(prepared.refs.len() + usize::from(prepared.receiver_ref.is_some()));
3437 let receiver_snapshot = if let Some(recipe) = prepared.receiver_ref {
3438 let place = match recipe {
3439 PreparedReceiverRef::Binding(recipe) => {
3440 let (target, root) = self.resolve_ref_target(recipe, 0, line)?;
3441 ResolvedPlace {
3442 target,
3443 root_recipe: recipe,
3444 root_name: self.current_chunk().name(recipe.name_idx()).to_string(),
3445 root,
3446 projections: Vec::new(),
3447 }
3448 }
3449 PreparedReceiverRef::Place(place) => self.refresh_resolved_place(place, line)?,
3450 };
3451 let snapshot = self.place_value_from(&place.root, &place.projections, line)?;
3452 pending.push(PendingWriteBack {
3453 parameter: 0,
3454 place,
3455 });
3456 Some(snapshot)
3457 } else {
3458 None
3459 };
3460 let mut ref_index_offset = 0;
3461 for prepared_ref in prepared.refs {
3462 let next_offset = ref_index_offset + prepared_ref.index_count;
3463 let indices = ref_indices[ref_index_offset..next_offset].to_vec();
3464 ref_index_offset = next_offset;
3465 let place =
3466 self.resolve_ref_recipe(prepared_ref.recipe, indices, prepared_ref.param, line)?;
3467 let snapshot = self.place_value_from(&place.root, &place.projections, line)?;
3468 if pending
3469 .iter()
3470 .any(|write_back: &PendingWriteBack| write_back.place.target == place.target)
3471 {
3472 return Err(duplicate_ref_target_error(line));
3473 }
3474 full_args[prepared_ref.param] = Some(snapshot);
3475 pending.push(PendingWriteBack {
3476 parameter: prepared_ref.param + param_offset,
3477 place,
3478 });
3479 }
3480 let args = full_args
3481 .into_iter()
3482 .map(|value| value.ok_or_else(|| error(line, "VM: incomplete prepared arguments")))
3483 .collect::<Result<Vec<_>, _>>()?;
3484
3485 let before = self.frames.len();
3486 let next = match prepared.callable {
3487 PreparedCallable::User(entry) => self.enter_user_fn_args(entry, args, line)?,
3488 PreparedCallable::HostThenUser { name, entry } => {
3489 if let Some(result) = self.host.call(&name, &args, line) {
3490 self.push_value(result?);
3491 return Ok(Next::Continue);
3492 }
3493 self.enter_user_fn_args(entry, args, line)?
3494 }
3495 PreparedCallable::Closure(function) => self.call_closure(&function, args, line)?,
3496 PreparedCallable::UserMethod {
3497 entry, receiver, ..
3498 } => {
3499 let mut method_args = Vec::with_capacity(args.len() + 1);
3500 method_args.push(receiver_snapshot.unwrap_or(receiver));
3501 method_args.extend(args);
3502 self.enter_user_fn_args(entry, method_args, line)?
3503 }
3504 PreparedCallable::DeferredMethod {
3505 receiver,
3506 method,
3507 nested_place,
3508 } => {
3509 debug_assert!(pending.is_empty());
3510 return self.dispatch_method(receiver, &method, args, None, nested_place, line);
3511 }
3512 PreparedCallable::NamedMethodInPlace { target, method } => {
3513 debug_assert!(pending.is_empty());
3514 return self.call_method_in_place_args(target, &method, args, line);
3515 }
3516 PreparedCallable::PlaceMethodInPlace { place, method } => {
3517 debug_assert!(pending.is_empty());
3518 return self.call_method_at_place(place, &method, args, line);
3519 }
3520 PreparedCallable::NamedFallback(name) => {
3521 debug_assert!(pending.is_empty());
3522 return self.invoke_named_fallback(&name, args, line);
3523 }
3524 };
3525 if !pending.is_empty() {
3526 if self.frames.len() != before + 1 {
3527 return Err(error(
3528 line,
3529 format!(
3530 "VM: `{}` did not enter a function frame",
3531 prepared.display_name
3532 ),
3533 ));
3534 }
3535 self.frames
3536 .last_mut()
3537 .expect("callee frame")
3538 .pending_write_backs = pending;
3539 }
3540 Ok(next)
3541 }
3542
3543 fn resolve_ref_target(
3544 &self,
3545 recipe: NamespaceRef,
3546 position: usize,
3547 line: u32,
3548 ) -> Result<(ResolvedRefTarget, Value), NyblError> {
3549 self.resolve_target(recipe, position, line, true)
3550 }
3551
3552 fn resolve_target(
3553 &self,
3554 recipe: NamespaceRef,
3555 position: usize,
3556 line: u32,
3557 reject_capture: bool,
3558 ) -> Result<(ResolvedRefTarget, Value), NyblError> {
3559 let frame_index = self.frames.len().saturating_sub(1);
3560 let frame = self.frames.last().expect("frame present");
3561 if let Some(slot) = recipe.slot_idx() {
3562 let value = frame
3563 .slots
3564 .get(slot.0 as usize)
3565 .cloned()
3566 .ok_or_else(|| error(line, "VM: local slot out of range"))?;
3567 return Ok((
3568 ResolvedRefTarget::Slot {
3569 frame: frame_index,
3570 slot,
3571 },
3572 value,
3573 ));
3574 }
3575 let name = frame.chunk.name(recipe.name_idx()).to_string();
3576 if reject_capture && frame.captured_names.contains(&name) {
3577 return Err(nybl::ref_params::captured_ref_target(position + 1, line));
3578 }
3579 for (scope_index, scope) in frame.scopes.iter().enumerate().rev() {
3580 if let Some(value) = scope.get(&name) {
3581 return Ok((
3582 ResolvedRefTarget::Scope {
3583 frame: frame_index,
3584 scope: scope_index,
3585 name,
3586 },
3587 value.clone(),
3588 ));
3589 }
3590 }
3591 Err(error_with_hint(
3592 line,
3593 nybl::error_messages::variable_not_found(&name),
3594 "Did you forget to create it with `let`?",
3595 ))
3596 }
3597
3598 fn validate_mutable_resolved_target(
3599 &self,
3600 target: &ResolvedRefTarget,
3601 root_name: &str,
3602 position: usize,
3603 line: u32,
3604 ) -> Result<(), NyblError> {
3605 if nybl::naming::is_constant_name(root_name) {
3606 return Err(nybl::error_messages::constant_mutation_error(
3607 root_name, line,
3608 ));
3609 }
3610 if let ResolvedRefTarget::Scope { frame, name, .. } = target
3611 && self
3612 .frames
3613 .get(*frame)
3614 .is_some_and(|frame| frame.captured_names.contains(name))
3615 {
3616 return Err(nybl::ref_params::captured_ref_target(position + 1, line));
3617 }
3618 Ok(())
3619 }
3620
3621 fn resolved_target_value(
3622 &self,
3623 target: &ResolvedRefTarget,
3624 line: u32,
3625 ) -> Result<Value, NyblError> {
3626 match target {
3627 ResolvedRefTarget::Slot { frame, slot } => self
3628 .frames
3629 .get(*frame)
3630 .and_then(|frame| frame.slots.get(slot.0 as usize))
3631 .cloned()
3632 .ok_or_else(|| error(line, "VM: mutable place slot is no longer live")),
3633 ResolvedRefTarget::Scope { frame, scope, name } => self
3634 .frames
3635 .get(*frame)
3636 .and_then(|frame| frame.scopes.get(*scope))
3637 .and_then(|scope| scope.get(name))
3638 .cloned()
3639 .ok_or_else(|| error(line, "VM: mutable place binding is no longer live")),
3640 }
3641 }
3642
3643 fn store_resolved_target(
3644 &mut self,
3645 target: &ResolvedRefTarget,
3646 value: Value,
3647 line: u32,
3648 ) -> Result<(), NyblError> {
3649 match target {
3650 ResolvedRefTarget::Slot { frame, slot } => {
3651 let target = self
3652 .frames
3653 .get_mut(*frame)
3654 .and_then(|frame| frame.slots.get_mut(slot.0 as usize))
3655 .ok_or_else(|| error(line, "VM: mutable place slot is no longer live"))?;
3656 *target = value;
3657 }
3658 ResolvedRefTarget::Scope { frame, scope, name } => {
3659 let target = self
3660 .frames
3661 .get_mut(*frame)
3662 .and_then(|frame| frame.scopes.get_mut(*scope))
3663 .and_then(|scope| scope.get_mut(name))
3664 .ok_or_else(|| error(line, "VM: mutable place binding is no longer live"))?;
3665 *target = value;
3666 }
3667 }
3668 Ok(())
3669 }
3670
3671 fn resolve_ref_recipe(
3672 &self,
3673 recipe: RefArgTarget,
3674 indices: Vec<Value>,
3675 position: usize,
3676 line: u32,
3677 ) -> Result<ResolvedPlace, NyblError> {
3678 match recipe {
3679 RefArgTarget::Binding(root) => {
3680 let (target, value) = self.resolve_ref_target(root, position, line)?;
3681 Ok(ResolvedPlace {
3682 target,
3683 root_recipe: root,
3684 root_name: self.current_chunk().name(root.name_idx()).to_string(),
3685 root: value,
3686 projections: Vec::new(),
3687 })
3688 }
3689 RefArgTarget::Place(place) => self.resolve_place(place, indices, position, line),
3690 RefArgTarget::Invalid => Err(invalid_ref_target_error(line, position)),
3691 }
3692 }
3693
3694 fn resolve_place(
3695 &self,
3696 place: PlaceIdx,
3697 indices: Vec<Value>,
3698 position: usize,
3699 line: u32,
3700 ) -> Result<ResolvedPlace, NyblError> {
3701 self.resolve_place_internal(place, indices, position, line, true, true)
3702 }
3703
3704 fn resolve_place_internal(
3705 &self,
3706 place: PlaceIdx,
3707 indices: Vec<Value>,
3708 position: usize,
3709 line: u32,
3710 reject_capture: bool,
3711 validate_path: bool,
3712 ) -> Result<ResolvedPlace, NyblError> {
3713 let recipe = self.current_chunk().place(place);
3714 let root_recipe = recipe.root;
3715 let root_name = self
3716 .current_chunk()
3717 .name(root_recipe.name_idx())
3718 .to_string();
3719 let (target, root) = self.resolve_target(root_recipe, position, line, reject_capture)?;
3720 let mut indices = indices.into_iter();
3721 let mut projections = Vec::with_capacity(recipe.projections.len());
3722 for projection in &recipe.projections {
3723 projections.push(match projection {
3724 PlaceProjectionRecipe::Index => ResolvedPlaceProjection::Index(
3725 indices
3726 .next()
3727 .ok_or_else(|| error(line, "VM: missing mutable-place index"))?,
3728 ),
3729 PlaceProjectionRecipe::Field(field) => {
3730 ResolvedPlaceProjection::Field(self.current_chunk().name(*field).to_string())
3731 }
3732 });
3733 }
3734 if indices.next().is_some() {
3735 return Err(error(line, "VM: too many mutable-place indices"));
3736 }
3737 let resolved = ResolvedPlace {
3738 target,
3739 root_recipe,
3740 root_name,
3741 root,
3742 projections,
3743 };
3744 if validate_path {
3745 let _ = self.place_value_from(&resolved.root, &resolved.projections, line)?;
3746 }
3747 Ok(resolved)
3748 }
3749
3750 fn refresh_resolved_place(
3751 &self,
3752 mut place: ResolvedPlace,
3753 line: u32,
3754 ) -> Result<ResolvedPlace, NyblError> {
3755 place.root = self.resolved_target_value(&place.target, line)?;
3756 let _ = self.place_value_from(&place.root, &place.projections, line)?;
3757 Ok(place)
3758 }
3759
3760 fn place_value_from(
3761 &self,
3762 root: &Value,
3763 projections: &[ResolvedPlaceProjection],
3764 line: u32,
3765 ) -> Result<Value, NyblError> {
3766 let mut value = root.clone();
3767 for projection in projections {
3768 value = match projection {
3769 ResolvedPlaceProjection::Index(index) => {
3770 ops::index_get_in(&value, index, line, &self.memory)?
3771 }
3772 ResolvedPlaceProjection::Field(field) => match &value {
3773 Value::Struct(structure) => {
3774 structure.field(field).cloned().ok_or_else(|| {
3775 error(
3776 line,
3777 nybl::error_messages::struct_has_no_field(
3778 structure.type_name(),
3779 field,
3780 ),
3781 )
3782 })?
3783 }
3784 other => {
3785 return Err(error(
3786 line,
3787 nybl::error_messages::cant_assign_field(field, other.type_name()),
3788 ));
3789 }
3790 },
3791 };
3792 }
3793 Ok(value)
3794 }
3795
3796 fn write_place_value(
3797 &self,
3798 root: &mut Value,
3799 projections: &[ResolvedPlaceProjection],
3800 value: Value,
3801 line: u32,
3802 ) -> Result<(), NyblError> {
3803 let Some((projection, tail)) = projections.split_first() else {
3804 *root = value;
3805 return Ok(());
3806 };
3807 if tail.is_empty() {
3808 return match projection {
3809 ResolvedPlaceProjection::Index(index) => {
3810 ops::index_set_in(root, index, value, line, &self.memory)
3811 }
3812 ResolvedPlaceProjection::Field(field) => {
3813 self.set_place_field(root, field, value, line)
3814 }
3815 };
3816 }
3817 let mut child = match projection {
3818 ResolvedPlaceProjection::Index(index) => {
3819 ops::index_get_in(root, index, line, &self.memory)?
3820 }
3821 ResolvedPlaceProjection::Field(_) => {
3822 self.place_value_from(root, core::slice::from_ref(projection), line)?
3823 }
3824 };
3825 self.write_place_value(&mut child, tail, value, line)?;
3826 match projection {
3827 ResolvedPlaceProjection::Index(index) => {
3828 ops::index_set_in(root, index, child, line, &self.memory)
3829 }
3830 ResolvedPlaceProjection::Field(field) => self.set_place_field(root, field, child, line),
3831 }
3832 }
3833
3834 fn set_place_field(
3835 &self,
3836 root: &mut Value,
3837 field: &str,
3838 value: Value,
3839 line: u32,
3840 ) -> Result<(), NyblError> {
3841 match root {
3842 Value::Struct(structure) => {
3843 let type_name = structure.type_name().to_string();
3844 if structure.__try_set_field_in(field, value, line, &self.memory)? {
3845 Ok(())
3846 } else {
3847 Err(error(
3848 line,
3849 nybl::error_messages::struct_has_no_field(&type_name, field),
3850 ))
3851 }
3852 }
3853 other => Err(error(
3854 line,
3855 nybl::error_messages::cant_assign_field(field, other.type_name()),
3856 )),
3857 }
3858 }
3859
3860 fn enter_user_fn_args(
3861 &mut self,
3862 entry: Rc<FnEntry>,
3863 args: Vec<Value>,
3864 line: u32,
3865 ) -> Result<Next, NyblError> {
3866 if self.active_call_depth() >= MAX_CALL_DEPTH {
3867 return Err(nybl::error_messages::call_depth_error(line));
3868 }
3869 self.check_nesting(entry.chunk.nesting_depth, line)?;
3870 let args = self.pack_rest_arguments(args, &entry.param_modes, line)?;
3871 let slot_count = entry.chunk.slot_count as usize;
3872 let mut slots = self.take_slots(slot_count);
3873 for (index, arg) in args.into_iter().enumerate() {
3874 let slot = entry
3875 .chunk
3876 .parameter_slots
3877 .get(index)
3878 .ok_or_else(|| error(line, "VM: parameter slot metadata is incomplete"))?;
3879 slots[slot.0 as usize] = arg;
3880 }
3881 self.push_function_frame(
3882 entry.chunk.clone(),
3883 slots,
3884 Vec::new(),
3885 self.stack.len(),
3886 Some(entry.module_path.clone()),
3887 FrameWrap::None,
3888 );
3889 self.frames
3890 .last_mut()
3891 .expect("callee frame")
3892 .current_function_entry = Some(Rc::clone(&entry));
3893 self.bind_function_self_name(
3894 entry.exact_self_name.as_deref(),
3895 &entry.params,
3896 &entry.module_path,
3897 );
3898 self.apply_entry_alias_context(&entry);
3899 Ok(Next::Continue)
3900 }
3901
3902 fn pack_rest_arguments(
3903 &self,
3904 mut args: Vec<Value>,
3905 modes: &[ParamMode],
3906 line: u32,
3907 ) -> Result<Vec<Value>, NyblError> {
3908 if modes.last() != Some(&ParamMode::Rest) {
3909 return Ok(args);
3910 }
3911 let fixed = modes.len().saturating_sub(1);
3912 let extras = args.split_off(fixed);
3913 let rest = Value::__try_new_array_in(extras, line, &self.memory)?;
3914 if self.memory.__exceeded() {
3915 return Err(error_fatal_with_hint(
3916 line,
3917 "Memory limit exceeded",
3918 "Your code is using too much memory. Check for large strings or arrays growing in loops.",
3919 ));
3920 }
3921 args.push(rest);
3922 Ok(args)
3923 }
3924
3925 fn invoke_named_fallback(
3926 &mut self,
3927 name: &str,
3928 args: Vec<Value>,
3929 line: u32,
3930 ) -> Result<Next, NyblError> {
3931 match name {
3932 "range" | "rand" | "print" | "try_call" | "panic"
3936 if !self.limits.disabled_builtins.is_empty()
3937 && self.limits.disabled_builtins.contains(name) =>
3938 {
3939 return Err(nybl::check::disabled_builtin_error(name, line));
3940 }
3941 "range" => {
3942 let value =
3943 builtins::builtin_range_in(&args, line, &mut self.rand_state, &self.memory)?;
3944 self.push_value(value);
3945 return Ok(Next::Continue);
3946 }
3947 "rand" => {
3948 let value = builtins::builtin_rand(&args, line, &mut self.rand_state)?;
3949 self.push_value(value);
3950 return Ok(Next::Continue);
3951 }
3952 "print" => {
3953 let message = nybl::formatting::__format_values_in(&args, " ", line, &self.memory)?;
3954 self.host.on_print(&message);
3955 if let Some(error) = self.host.print_error(line) {
3956 return Err(error);
3957 }
3958 self.push_value(Value::None);
3959 return Ok(Next::Continue);
3960 }
3961 "try_call" => return self.builtin_try_call(args, line),
3962 "panic" => {
3963 let value = builtins::builtin_panic(&args, line)?;
3964 self.push_value(value);
3965 return Ok(Next::Continue);
3966 }
3967 _ => {}
3968 }
3969 let host_result = self.host.call(name, &args, line);
3970 if let Some(result) = host_result {
3971 self.push_value(result?);
3972 return Ok(Next::Continue);
3973 }
3974 if let Some(hint) = self.callable_candidates_hint(name) {
3975 return Err(error_with_hint(
3976 line,
3977 nybl::error_messages::function_not_found(name),
3978 hint,
3979 ));
3980 }
3981 let host_hint = self.host.function_hint().to_string();
3982 Err(if host_hint.is_empty() {
3983 error(line, nybl::error_messages::function_not_found(name))
3984 } else {
3985 error_with_hint(
3986 line,
3987 nybl::error_messages::function_not_found(name),
3988 host_hint,
3989 )
3990 })
3991 }
3992
3993 fn call(&mut self, name_idx: NameIdx, argc: usize, line: u32) -> Result<Next, NyblError> {
3994 let chunk = Arc::clone(&self.frames.last().expect("frame present").chunk);
4000 let name: &str = chunk.name(name_idx);
4001
4002 let current_value = self
4007 .current_scopes()
4008 .iter()
4009 .rev()
4010 .find_map(|scope| scope.get(name))
4011 .cloned();
4012 if let Some(value) = current_value {
4013 let args = self.pop_n_values(argc, line)?;
4014 return match &value {
4015 Value::Fn(f) => {
4016 let f = Rc::clone(f);
4017 drop(value);
4018 self.call_closure(&f, args, line)
4019 }
4020 other => Err(error(
4021 line,
4022 format!("`{}` is a {}, not a function", name, other.type_name()),
4023 )),
4024 };
4025 }
4026
4027 let declaration_alias = self.frames.last().and_then(|frame| {
4032 if frame.lexical_context.module_aliases.is_empty() {
4033 None
4034 } else {
4035 frame.lexical_context.module_aliases.get(name).cloned()
4036 }
4037 });
4038 if let Some(module) = declaration_alias {
4039 let _args = self.pop_n_values(argc, line)?;
4040 return Err(error(
4041 line,
4042 format!(
4043 "`{}` is a {}, not a function",
4044 name,
4045 Value::Module(module).type_name()
4046 ),
4047 ));
4048 }
4049
4050 if let Some(entry) = self.imported_function(name).cloned() {
4051 validate_user_arity(name, &entry.param_modes, argc, false, line)?;
4052 drop(chunk);
4053 return self.enter_user_fn(entry, argc, line);
4054 }
4055
4056 if self.frames.last().is_some_and(|frame| {
4057 frame.is_function
4058 && frame.function_module.as_deref() == Some(nybl::value::ROOT_MODULE_PATH)
4059 }) {
4060 let root_value = self
4061 .frames
4062 .first()
4063 .and_then(|root| root.scopes.iter().rev().find_map(|scope| scope.get(name)))
4064 .cloned();
4065 if let Some(value) = root_value {
4066 let args = self.pop_n_values(argc, line)?;
4067 return match &value {
4068 Value::Fn(function) => {
4069 let function = Rc::clone(function);
4070 self.call_closure(&function, args, line)
4071 }
4072 other => Err(error(
4073 line,
4074 format!("`{}` is a {}, not a function", name, other.type_name()),
4075 )),
4076 };
4077 }
4078 }
4079
4080 if let Some(entry) = self.lookup_function_entry(name) {
4093 validate_user_arity(name, &entry.param_modes, argc, false, line)?;
4096 drop(chunk);
4097 return self.enter_user_fn(entry, argc, line);
4098 }
4099
4100 let args = self.pop_n_values(argc, line)?;
4103
4104 match name {
4111 "range" | "rand" | "print" | "try_call" | "panic"
4116 if !self.limits.disabled_builtins.is_empty()
4117 && self.limits.disabled_builtins.contains(name) =>
4118 {
4119 return Err(nybl::check::disabled_builtin_error(name, line));
4120 }
4121 "range" => {
4122 let v =
4123 builtins::builtin_range_in(&args, line, &mut self.rand_state, &self.memory)?;
4124 self.push_value(v);
4125 return Ok(Next::Continue);
4126 }
4127 "rand" => {
4128 let v = builtins::builtin_rand(&args, line, &mut self.rand_state)?;
4129 self.push_value(v);
4130 return Ok(Next::Continue);
4131 }
4132 "print" => {
4133 let message = nybl::formatting::__format_values_in(&args, " ", line, &self.memory)?;
4134 self.host.on_print(&message);
4135 if let Some(error) = self.host.print_error(line) {
4136 return Err(error);
4137 }
4138 self.push_value(Value::None);
4139 return Ok(Next::Continue);
4140 }
4141 "try_call" => return self.builtin_try_call(args, line),
4142 "panic" => {
4143 let v = builtins::builtin_panic(&args, line)?;
4148 self.push_value(v);
4149 return Ok(Next::Continue);
4150 }
4151 _ => {}
4152 }
4153
4154 let host_result = self.host.call(name, &args, line);
4156 if let Some(result) = host_result {
4157 let v = result?;
4158 self.push_value(v);
4159 return Ok(Next::Continue);
4160 }
4161
4162 if let Some(hint) = self.callable_candidates_hint(name) {
4168 return Err(error_with_hint(
4169 line,
4170 nybl::error_messages::function_not_found(name),
4171 hint,
4172 ));
4173 }
4174 let host_hint = self.host.function_hint().to_string();
4175 Err(if host_hint.is_empty() {
4176 error(line, nybl::error_messages::function_not_found(name))
4177 } else {
4178 error_with_hint(
4179 line,
4180 nybl::error_messages::function_not_found(name),
4181 host_hint,
4182 )
4183 })
4184 }
4185
4186 fn enter_user_fn(
4193 &mut self,
4194 entry: Rc<FnEntry>,
4195 argc: usize,
4196 line: u32,
4197 ) -> Result<Next, NyblError> {
4198 if entry.param_modes.last() == Some(&ParamMode::Rest) {
4199 let args = self.pop_n_values(argc, line)?;
4200 return self.enter_user_fn_args(entry, args, line);
4201 }
4202 if self.active_call_depth() >= MAX_CALL_DEPTH {
4203 return Err(nybl::error_messages::call_depth_error(line));
4204 }
4205 self.check_nesting(entry.chunk.nesting_depth, line)?;
4206
4207 if self.stack.len() < argc {
4208 return Err(error(line, "VM: stack underflow"));
4209 }
4210
4211 let slot_count = entry.chunk.slot_count as usize;
4218 let mut slots = self.take_slots(slot_count);
4219 let start = self.stack.len() - argc;
4220 for i in 0..argc {
4221 let slot = core::mem::replace(&mut self.stack[start + i], Slot::Value(Value::None));
4222 match slot {
4223 Slot::Value(v) => {
4224 let parameter_slot =
4225 entry.chunk.parameter_slots.get(i).ok_or_else(|| {
4226 error(line, "VM: parameter slot metadata is incomplete")
4227 })?;
4228 slots[parameter_slot.0 as usize] = v;
4229 }
4230 _ => {
4231 self.stack.truncate(start);
4232 self.return_slots(slots);
4233 return Err(error(line, "VM: expected value on stack"));
4234 }
4235 }
4236 }
4237 self.stack.truncate(start);
4238
4239 self.push_function_frame(
4240 entry.chunk.clone(),
4241 slots,
4242 Vec::new(),
4250 self.stack.len(),
4251 Some(entry.module_path.clone()),
4252 FrameWrap::None,
4253 );
4254 self.frames
4255 .last_mut()
4256 .expect("callee frame")
4257 .current_function_entry = Some(Rc::clone(&entry));
4258 self.bind_function_self_name(
4259 entry.exact_self_name.as_deref(),
4260 &entry.params,
4261 &entry.module_path,
4262 );
4263 self.apply_entry_alias_context(&entry);
4264 Ok(Next::Continue)
4269 }
4270
4271 fn call_value(&mut self, argc: usize, line: u32) -> Result<Next, NyblError> {
4276 let callee = self.pop_value(line)?;
4277 let args = self.pop_n_values(argc, line)?;
4278 self.invoke_value(callee, args, line)
4279 }
4280
4281 fn invoke_value(
4287 &mut self,
4288 callee: Value,
4289 args: Vec<Value>,
4290 line: u32,
4291 ) -> Result<Next, NyblError> {
4292 match &callee {
4293 Value::Fn(f) => {
4294 let f = Rc::clone(f);
4295 drop(callee);
4296 self.call_closure(&f, args, line)
4297 }
4298 other => Err(error(
4299 line,
4300 nybl::error_messages::cant_call_a(other.type_name()),
4301 )),
4302 }
4303 }
4304
4305 fn call_method(
4306 &mut self,
4307 method_idx: NameIdx,
4308 argc: usize,
4309 assign_back_to: Option<crate::chunk::AssignBack>,
4310 nested_place: bool,
4311 line: u32,
4312 ) -> Result<Next, NyblError> {
4313 let chunk = Arc::clone(&self.frames.last().expect("frame present").chunk);
4314 let method = chunk.name(method_idx);
4315
4316 let obj = self.pop_value(line)?;
4317 let args = self.pop_n_values(argc, line)?;
4318
4319 self.dispatch_method(obj, method, args, assign_back_to, nested_place, line)
4320 }
4321
4322 fn call_method_in_place(
4323 &mut self,
4324 target: crate::chunk::NamespaceRef,
4325 method_idx: NameIdx,
4326 argc: usize,
4327 line: u32,
4328 ) -> Result<Next, NyblError> {
4329 let chunk = Arc::clone(&self.frames.last().expect("frame present").chunk);
4330 let method = chunk.name(method_idx);
4331 let args = self.pop_n_values(argc, line)?;
4332 self.call_method_in_place_args(target, method, args, line)
4333 }
4334
4335 fn call_method_in_place_args(
4336 &mut self,
4337 target: crate::chunk::NamespaceRef,
4338 method: &str,
4339 args: Vec<Value>,
4340 line: u32,
4341 ) -> Result<Next, NyblError> {
4342 let chunk = Arc::clone(&self.frames.last().expect("frame present").chunk);
4343 let memory = self.memory.clone();
4344 let receiver_idx = target.name_idx();
4345 let receiver_name = chunk.name(receiver_idx);
4346 let (fallback, assign_back) = match target.slot_idx() {
4353 Some(slot) => {
4354 let value = self
4355 .frames
4356 .last_mut()
4357 .expect("frame present")
4358 .slots
4359 .get_mut(slot.0 as usize)
4360 .ok_or_else(|| error(line, "VM: local slot out of range"))?;
4361 if methods::is_mutating_collection_receiver(value, method) {
4362 methods::reject_constant_array_mutation(receiver_name, method, line)?;
4363 let result = methods::transactional_collection_method_in(
4364 value, method, args, line, &memory,
4365 )?;
4366 self.push_value(result);
4367 return Ok(Next::Continue);
4368 }
4369 (value.clone(), crate::chunk::AssignBack::Slot(slot))
4370 }
4371 None => {
4372 if self.lookup_var_mut_by_idx(receiver_idx).is_none() {
4373 if let Some(module) = self.module_alias(receiver_name).cloned() {
4374 return self.dispatch_method(
4375 Value::Module(module),
4376 method,
4377 args,
4378 None,
4379 false,
4380 line,
4381 );
4382 }
4383 let hint = self
4384 .value_candidates_hint(receiver_name)
4385 .unwrap_or_else(|| "Did you forget to create it with `let`?".to_string());
4386 return Err(error_with_hint(
4387 line,
4388 nybl::error_messages::variable_not_found(receiver_name),
4389 hint,
4390 ));
4391 }
4392 let value = self
4393 .lookup_var_mut_by_idx(receiver_idx)
4394 .expect("binding checked above");
4395 if methods::is_mutating_collection_receiver(value, method) {
4396 methods::reject_constant_array_mutation(receiver_name, method, line)?;
4397 let result = methods::transactional_collection_method_in(
4398 value, method, args, line, &memory,
4399 )?;
4400 self.push_value(result);
4401 return Ok(Next::Continue);
4402 }
4403 (value.clone(), crate::chunk::AssignBack::Name(receiver_idx))
4404 }
4405 };
4406
4407 self.dispatch_method(fallback, method, args, Some(assign_back), false, line)
4408 }
4409
4410 fn call_method_at_place(
4411 &mut self,
4412 place: ResolvedPlace,
4413 method: &str,
4414 args: Vec<Value>,
4415 line: u32,
4416 ) -> Result<Next, NyblError> {
4417 let place = self.refresh_resolved_place(place, line)?;
4418 let mut receiver = self.place_value_from(&place.root, &place.projections, line)?;
4419 methods::reject_constant_array_mutation(&place.root_name, method, line)?;
4420 let result = methods::transactional_collection_method_in(
4421 &mut receiver,
4422 method,
4423 args,
4424 line,
4425 &self.memory,
4426 )?;
4427 let mut root = place.root.clone();
4428 self.write_place_value(&mut root, &place.projections, receiver, line)?;
4429 self.store_resolved_target(&place.target, root, line)?;
4430 self.push_value(result);
4431 Ok(Next::Continue)
4432 }
4433
4434 fn dispatch_method(
4435 &mut self,
4436 obj: Value,
4437 method: &str,
4438 args: Vec<Value>,
4439 assign_back_to: Option<crate::chunk::AssignBack>,
4440 nested_place: bool,
4441 line: u32,
4442 ) -> Result<Next, NyblError> {
4443 if let Value::Module(ref m) = obj {
4455 if let Some(result) =
4456 methods::common_method_in(&obj, method, &args, line, &self.memory)?
4457 {
4458 self.push_value(result.0);
4459 return Ok(Next::Continue);
4460 }
4461 if let Some(callee) = self.module_binding(m, method) {
4462 drop(obj);
4463 return self.invoke_value(callee, args, line);
4464 }
4465 return Err(error(
4466 line,
4467 format!("`{}` isn't exported from `{}`", method, m.path),
4468 ));
4469 }
4470
4471 let user_type_key: Option<(String, String)> = match &obj {
4478 Value::Struct(s) => Some((s.module_path().to_string(), s.type_name().to_string())),
4479 Value::EnumVariant(e) => Some((e.module_path().to_string(), e.type_name().to_string())),
4480 _ => None,
4481 };
4482 if let Some(type_key) = user_type_key {
4483 let entry = self
4484 .user_methods
4485 .get(&type_key)
4486 .and_then(|m| m.get(method))
4487 .cloned();
4488 if let Some(entry) = entry {
4489 validate_user_arity(
4490 &format!("{}.{}", type_key.1, method),
4491 &entry.param_modes,
4492 args.len() + 1,
4493 true,
4494 line,
4495 )?;
4496 let mut method_args = Vec::with_capacity(args.len() + 1);
4497 method_args.push(obj);
4498 method_args.extend(args);
4499 self.enter_user_fn_args(entry, method_args, line)?;
4500 let _ = assign_back_to;
4505 return Ok(Next::Continue);
4506 }
4507 }
4508
4509 if nested_place {
4510 methods::reject_nested_array_mutation(&obj, method, line)?;
4511 }
4512
4513 if let Some((ret, _)) = methods::common_method_in(&obj, method, &args, line, &self.memory)?
4517 {
4518 self.push_value(ret);
4519 return Ok(Next::Continue);
4520 }
4521
4522 if methods::is_builtin_result(&obj) {
4528 if let Some(v) = methods::result_method(&obj, method, &args, line)? {
4529 self.push_value(v);
4530 return Ok(Next::Continue);
4531 }
4532 if let Some(kind) = methods::is_result_callable_method(method) {
4533 return self.call_result_callable_method(obj, kind, method, args, line);
4534 }
4535 }
4536
4537 let (ret, mutated) = match &obj {
4538 Value::Array(arr) => methods::array_method_in(arr, method, &args, line, &self.memory)?,
4539 Value::Str(s) => {
4540 methods::string_method_in(s.as_str(), method, &args, line, &self.memory)?
4541 }
4542 Value::Dict(entries) => {
4543 methods::dict_method_in(entries, method, &args, line, &self.memory)?
4544 }
4545 Value::Int(_) | Value::Number(_) => methods::numeric_method(&obj, method, &args, line)?,
4546 Value::Bool(_) => methods::bool_method(&obj, method, &args, line)?,
4547 Value::Iter(_) => methods::iter_method_in(&obj, method, &args, line, &self.memory)?,
4548 Value::Host(value) => {
4549 let result = self.host.call_method(value, method, &args, line);
4550 match result {
4551 Some(result) => (result?, None),
4552 None => {
4553 return Err(error(
4554 line,
4555 nybl::error_messages::no_such_method(obj.type_name(), method),
4556 ));
4557 }
4558 }
4559 }
4560 _ => {
4561 return Err(error(
4562 line,
4563 nybl::error_messages::no_such_method(obj.type_name(), method),
4564 ));
4565 }
4566 };
4567
4568 if methods::is_mutating_method(method)
4569 && let (Some(target), Some(new_obj)) = (assign_back_to, mutated)
4570 {
4571 match target {
4572 crate::chunk::AssignBack::Slot(slot) => {
4573 let frame = self.frames.last_mut().expect("frame present");
4574 let i = slot.0 as usize;
4575 if i < frame.slots.len() {
4576 frame.slots[i] = new_obj;
4577 }
4578 }
4584 crate::chunk::AssignBack::Name(var_idx) => {
4585 let var_name = self.current_chunk().name(var_idx).to_string();
4586 self.set_existing(&var_name, new_obj);
4587 }
4588 }
4589 }
4590 self.push_value(ret);
4591 Ok(Next::Continue)
4592 }
4593
4594 fn define_struct(&mut self, idx: StructIdx, line: u32) -> Result<(), NyblError> {
4595 let def = self.current_chunk().struct_def(idx).clone();
4596 let mut seen = BTreeSet::new();
4597 for field in &def.fields {
4598 if !seen.insert(field.clone()) {
4599 return Err(error(
4600 line,
4601 format!("Struct `{}` has duplicate field `{}`", def.name, field),
4602 ));
4603 }
4604 }
4605 let key = (self.current_module.clone(), def.name.clone());
4610 if let Some(existing) = self.struct_defs.get(&key) {
4611 if existing == &def.fields {
4612 self.bind_local_type(&def.name);
4613 return Ok(());
4614 }
4615 return Err(error(
4616 line,
4617 format!("Struct `{}` is already declared", def.name),
4618 ));
4619 }
4620 self.struct_defs.insert(key, def.fields);
4621 self.bind_local_type(&def.name);
4622 Ok(())
4623 }
4624
4625 fn define_enum(&mut self, idx: EnumIdx, line: u32) -> Result<(), NyblError> {
4626 let def = self.current_chunk().enum_def(idx).clone();
4627 let variants: Vec<(String, EnumVariantShape)> = def
4628 .variants
4629 .into_iter()
4630 .map(|v| (v.name, v.shape))
4631 .collect();
4632 let key = (self.current_module.clone(), def.name.clone());
4633 if let Some(existing) = self.enum_defs.get(&key) {
4634 if shapes_match(existing, &variants) {
4635 self.bind_local_type(&def.name);
4636 return Ok(());
4637 }
4638 return Err(error(
4639 line,
4640 format!("Enum `{}` is already declared", def.name),
4641 ));
4642 }
4643 let mut seen_variants = BTreeSet::new();
4644 for (variant, shape) in &variants {
4645 if !seen_variants.insert(variant.clone()) {
4646 return Err(error(
4647 line,
4648 format!("Enum `{}` has duplicate variant `{}`", def.name, variant),
4649 ));
4650 }
4651 let fields = match shape {
4652 EnumVariantShape::Unit => continue,
4653 EnumVariantShape::Tuple(fields) | EnumVariantShape::Struct(fields) => fields,
4654 };
4655 let mut seen_fields = BTreeSet::new();
4656 for field in fields {
4657 if !seen_fields.insert(field.clone()) {
4658 return Err(error(
4659 line,
4660 format!(
4661 "Enum variant `{}::{}` has duplicate field `{}`",
4662 def.name, variant, field
4663 ),
4664 ));
4665 }
4666 }
4667 }
4668 self.enum_defs.insert(key, variants);
4669 self.bind_local_type(&def.name);
4670 Ok(())
4671 }
4672
4673 fn bind_local_type(&mut self, name: &str) {
4677 if let Some(scope) = self.type_bindings.last_mut() {
4678 scope.insert(name.to_string(), self.current_module.clone());
4679 }
4680 if self.is_module_top_scope() {
4681 self.type_exports
4682 .insert(name.to_string(), self.current_module.clone());
4683 self.publish_root_type_binding(name.to_string(), self.current_module.clone());
4684 }
4685 }
4686
4687 fn define_method(&mut self, type_name: NameIdx, method_name: NameIdx, fn_idx: FnIdx) {
4688 let chunk = Arc::clone(&self.frames.last().expect("frame present").chunk);
4689 let type_name_s = chunk.name(type_name).to_string();
4690 let method_name_s = chunk.name(method_name).to_string();
4691 let fn_def = chunk.function(fn_idx);
4692 let entry = Rc::new(FnEntry {
4693 exact_self_name: None,
4694 params: fn_def.params.clone(),
4695 param_modes: fn_def.param_modes.clone(),
4696 chunk: Arc::clone(&fn_def.chunk),
4697 module_path: self.current_module.clone(),
4698 declaration_alias_names: self
4699 .frames
4700 .last()
4701 .expect("defining frame")
4702 .lexical_context
4703 .module_aliases
4704 .keys()
4705 .cloned()
4706 .collect(),
4707 });
4708 let key = (self.current_module.clone(), type_name_s);
4713 self.user_methods
4714 .entry(key)
4715 .or_default()
4716 .insert(method_name_s, entry);
4717 }
4718
4719 fn construct_struct(
4720 &mut self,
4721 namespace: Option<crate::chunk::NamespaceRef>,
4722 type_name: NameIdx,
4723 count: usize,
4724 line: u32,
4725 ) -> Result<(), NyblError> {
4726 let type_name_s = self.current_chunk().name(type_name).to_string();
4727 let module_path = match namespace {
4732 Some(namespace) => self.resolve_namespaced_type(namespace, &type_name_s, line)?,
4733 None => self.resolve_type_ref(None, &type_name_s).ok_or_else(|| {
4734 error(
4735 line,
4736 nybl::error_messages::struct_not_declared(&type_name_s),
4737 )
4738 })?,
4739 };
4740 let key = (module_path.clone(), type_name_s.clone());
4741 let decl = self
4742 .struct_defs
4743 .get(&key)
4744 .ok_or_else(|| {
4745 error(
4746 line,
4747 nybl::error_messages::struct_not_declared(&type_name_s),
4748 )
4749 })?
4750 .clone();
4751 let flat = self.pop_n_values(count * 2, line)?;
4752 let mut provided: BTreeMap<String, Value> = BTreeMap::new();
4753 let mut iter = flat.into_iter();
4754 while let (Some(key), Some(val)) = (iter.next(), iter.next()) {
4755 let key_str = match &key {
4756 Value::Str(s) => s.as_str().to_string(),
4757 other => {
4758 return Err(error(
4759 line,
4760 format!(
4761 "Struct field names must be strings, got {}",
4762 other.type_name()
4763 ),
4764 ));
4765 }
4766 };
4767 drop(key);
4768 if provided.contains_key(&key_str) {
4769 return Err(error(
4770 line,
4771 format!("Field `{key_str}` specified twice in `{type_name_s}` construction"),
4772 ));
4773 }
4774 if !decl.iter().any(|d| d == &key_str) {
4775 let msg = nybl::error_messages::struct_has_no_field(&type_name_s, &key_str);
4776 let err =
4777 match nybl::suggest::did_you_mean(&key_str, decl.iter().map(|s| s.as_str())) {
4778 Some(hint) => error_with_hint(line, msg, hint),
4779 None => error(line, msg),
4780 };
4781 return Err(err);
4782 }
4783 provided.insert(key_str, val);
4784 }
4785 let mut fields: Vec<(String, Value)> = Vec::with_capacity(decl.len());
4786 for d in &decl {
4787 match provided.remove(d) {
4788 Some(v) => fields.push((d.clone(), v)),
4789 None => {
4790 return Err(error(
4791 line,
4792 format!("Missing field `{d}` in `{type_name_s}` construction"),
4793 ));
4794 }
4795 }
4796 }
4797 self.push_value(Value::__try_new_struct_in(
4798 module_path,
4799 type_name_s,
4800 fields,
4801 line,
4802 &self.memory,
4803 )?);
4804 Ok(())
4805 }
4806
4807 fn validate_struct_construct(
4808 &self,
4809 namespace: Option<crate::chunk::NamespaceRef>,
4810 type_name: &str,
4811 provided: &[String],
4812 line: u32,
4813 ) -> Result<(), NyblError> {
4814 let module_path = match namespace {
4815 Some(namespace) => self.resolve_namespaced_type(namespace, type_name, line)?,
4816 None => self
4817 .resolve_type_ref(None, type_name)
4818 .ok_or_else(|| error(line, nybl::error_messages::struct_not_declared(type_name)))?,
4819 };
4820 let declared = self
4821 .struct_defs
4822 .get(&(module_path, type_name.to_string()))
4823 .ok_or_else(|| error(line, nybl::error_messages::struct_not_declared(type_name)))?;
4824 for (index, field) in provided.iter().enumerate() {
4825 if provided[..index].contains(field) {
4826 return Err(error(
4827 line,
4828 format!("Field `{field}` specified twice in `{type_name}` construction"),
4829 ));
4830 }
4831 if !declared.contains(field) {
4832 let message = nybl::error_messages::struct_has_no_field(type_name, field);
4833 return match nybl::suggest::did_you_mean(
4834 field,
4835 declared.iter().map(|name| name.as_str()),
4836 ) {
4837 Some(hint) => Err(error_with_hint(line, message, hint)),
4838 None => Err(error(line, message)),
4839 };
4840 }
4841 }
4842 for field in declared {
4843 if !provided.contains(field) {
4844 return Err(error(
4845 line,
4846 format!("Missing field `{field}` in `{type_name}` construction"),
4847 ));
4848 }
4849 }
4850 Ok(())
4851 }
4852
4853 fn validate_enum_construct(
4854 &self,
4855 namespace: Option<crate::chunk::NamespaceRef>,
4856 type_name: &str,
4857 variant: &str,
4858 shape: EnumConstructShape,
4859 provided: &[String],
4860 line: u32,
4861 ) -> Result<(), NyblError> {
4862 let module_path = match namespace {
4863 Some(namespace) => self.resolve_namespaced_type(namespace, type_name, line)?,
4864 None => self
4865 .resolve_type_ref(None, type_name)
4866 .ok_or_else(|| error(line, nybl::error_messages::enum_not_declared(type_name)))?,
4867 };
4868 let variants = self
4869 .enum_defs
4870 .get(&(module_path, type_name.to_string()))
4871 .ok_or_else(|| error(line, nybl::error_messages::enum_not_declared(type_name)))?;
4872 let declared = variants
4873 .iter()
4874 .find(|(name, _)| name == variant)
4875 .map(|(_, shape)| shape)
4876 .ok_or_else(|| {
4877 let message = nybl::error_messages::enum_has_no_variant(type_name, variant);
4878 match nybl::suggest::did_you_mean(
4879 variant,
4880 variants.iter().map(|(name, _)| name.as_str()),
4881 ) {
4882 Some(hint) => error_with_hint(line, message, hint),
4883 None => error(line, message),
4884 }
4885 })?;
4886 match (declared, shape) {
4887 (EnumVariantShape::Unit, EnumConstructShape::Unit) => Ok(()),
4888 (EnumVariantShape::Tuple(fields), EnumConstructShape::Tuple(argc)) => {
4889 if fields.len() == argc as usize {
4890 Ok(())
4891 } else {
4892 Err(error(
4893 line,
4894 format!(
4895 "`{}::{}` expects {} argument{}, but got {}",
4896 type_name,
4897 variant,
4898 fields.len(),
4899 if fields.len() == 1 { "" } else { "s" },
4900 argc
4901 ),
4902 ))
4903 }
4904 }
4905 (EnumVariantShape::Struct(fields), EnumConstructShape::Struct(_)) => {
4906 for (index, field) in provided.iter().enumerate() {
4907 if provided[..index].contains(field) {
4908 return Err(error(
4909 line,
4910 format!("Field `{field}` specified twice in `{type_name}::{variant}`"),
4911 ));
4912 }
4913 if !fields.contains(field) {
4914 return Err(error(
4915 line,
4916 nybl::error_messages::variant_has_no_field(type_name, variant, field),
4917 ));
4918 }
4919 }
4920 for field in fields {
4921 if !provided.contains(field) {
4922 return Err(error(
4923 line,
4924 format!(
4925 "Missing field `{field}` in `{type_name}::{variant}` construction"
4926 ),
4927 ));
4928 }
4929 }
4930 Ok(())
4931 }
4932 (EnumVariantShape::Unit, _) => Err(error(
4933 line,
4934 format!("Variant `{type_name}::{variant}` takes no payload"),
4935 )),
4936 (EnumVariantShape::Tuple(_), _) => Err(error(
4937 line,
4938 format!("Variant `{type_name}::{variant}` expects positional arguments `(…)`"),
4939 )),
4940 (EnumVariantShape::Struct(_), _) => Err(error(
4941 line,
4942 format!("Variant `{type_name}::{variant}` expects named fields `{{ … }}`"),
4943 )),
4944 }
4945 }
4946
4947 fn construct_enum(
4948 &mut self,
4949 namespace: Option<crate::chunk::NamespaceRef>,
4950 type_name: NameIdx,
4951 variant: NameIdx,
4952 shape: EnumConstructShape,
4953 line: u32,
4954 ) -> Result<(), NyblError> {
4955 let type_name_s = self.current_chunk().name(type_name).to_string();
4956 let variant_s = self.current_chunk().name(variant).to_string();
4957 let module_path = match namespace {
4958 Some(namespace) => self.resolve_namespaced_type(namespace, &type_name_s, line)?,
4959 None => self.resolve_type_ref(None, &type_name_s).ok_or_else(|| {
4960 error(line, nybl::error_messages::enum_not_declared(&type_name_s))
4961 })?,
4962 };
4963 let key = (module_path.clone(), type_name_s.clone());
4964 let decl = self
4965 .enum_defs
4966 .get(&key)
4967 .ok_or_else(|| error(line, nybl::error_messages::enum_not_declared(&type_name_s)))?
4968 .clone();
4969 let variant_decl = decl
4970 .iter()
4971 .find(|(n, _)| n == &variant_s)
4972 .cloned()
4973 .ok_or_else(|| {
4974 let msg = nybl::error_messages::enum_has_no_variant(&type_name_s, &variant_s);
4975 match nybl::suggest::did_you_mean(&variant_s, decl.iter().map(|(n, _)| n.as_str()))
4976 {
4977 Some(hint) => error_with_hint(line, msg, hint),
4978 None => error(line, msg),
4979 }
4980 })?;
4981 match (&variant_decl.1, shape) {
4982 (EnumVariantShape::Unit, EnumConstructShape::Unit) => {
4983 self.push_value(Value::__new_enum_unit_in(
4984 module_path,
4985 type_name_s,
4986 variant_s,
4987 &self.memory,
4988 ));
4989 }
4990 (EnumVariantShape::Tuple(fields), EnumConstructShape::Tuple(argc)) => {
4991 if fields.len() as u32 != argc {
4992 return Err(error(
4993 line,
4994 format!(
4995 "`{}::{}` expects {} argument{}, but got {}",
4996 type_name_s,
4997 variant_s,
4998 fields.len(),
4999 if fields.len() == 1 { "" } else { "s" },
5000 argc
5001 ),
5002 ));
5003 }
5004 let items = self.pop_n_values(argc as usize, line)?;
5005 self.push_value(Value::__try_new_enum_tuple_in(
5006 module_path,
5007 type_name_s,
5008 variant_s,
5009 items,
5010 line,
5011 &self.memory,
5012 )?);
5013 }
5014 (EnumVariantShape::Struct(decl_fields), EnumConstructShape::Struct(count)) => {
5015 let flat = self.pop_n_values(count as usize * 2, line)?;
5016 let mut provided: BTreeMap<String, Value> = BTreeMap::new();
5017 let mut iter = flat.into_iter();
5018 while let (Some(key), Some(val)) = (iter.next(), iter.next()) {
5019 let key_str = match &key {
5020 Value::Str(s) => s.as_str().to_string(),
5021 _ => {
5022 return Err(error(
5023 line,
5024 "Enum struct-variant field names must be strings",
5025 ));
5026 }
5027 };
5028 drop(key);
5029 if provided.contains_key(&key_str) {
5030 return Err(error(
5031 line,
5032 format!(
5033 "Field `{key_str}` specified twice in `{type_name_s}::{variant_s}`"
5034 ),
5035 ));
5036 }
5037 if !decl_fields.iter().any(|d| d == &key_str) {
5038 return Err(error(
5039 line,
5040 nybl::error_messages::variant_has_no_field(
5041 &type_name_s,
5042 &variant_s,
5043 &key_str,
5044 ),
5045 ));
5046 }
5047 provided.insert(key_str, val);
5048 }
5049 let mut fields: Vec<(String, Value)> = Vec::with_capacity(decl_fields.len());
5050 for d in decl_fields {
5051 match provided.remove(d) {
5052 Some(v) => fields.push((d.clone(), v)),
5053 None => {
5054 return Err(error(
5055 line,
5056 format!(
5057 "Missing field `{d}` in `{type_name_s}::{variant_s}` construction"
5058 ),
5059 ));
5060 }
5061 }
5062 }
5063 self.push_value(Value::__try_new_enum_struct_in(
5064 module_path,
5065 type_name_s,
5066 variant_s,
5067 fields,
5068 line,
5069 &self.memory,
5070 )?);
5071 }
5072 (EnumVariantShape::Unit, _) => {
5073 return Err(error(
5074 line,
5075 format!("Variant `{type_name_s}::{variant_s}` takes no payload"),
5076 ));
5077 }
5078 (EnumVariantShape::Tuple(_), _) => {
5079 return Err(error(
5080 line,
5081 format!(
5082 "Variant `{type_name_s}::{variant_s}` expects positional arguments `(…)`"
5083 ),
5084 ));
5085 }
5086 (EnumVariantShape::Struct(_), _) => {
5087 return Err(error(
5088 line,
5089 format!("Variant `{type_name_s}::{variant_s}` expects named fields `{{ … }}`"),
5090 ));
5091 }
5092 }
5093 Ok(())
5094 }
5095
5096 fn field_get(&self, obj: &Value, field: &str, line: u32) -> Result<Value, NyblError> {
5097 match obj {
5098 Value::Struct(s) => s.field(field).cloned().ok_or_else(|| {
5099 let msg = nybl::error_messages::struct_has_no_field(s.type_name(), field);
5100 let names = s.fields().iter().map(|(k, _)| k.as_str());
5101 match nybl::suggest::did_you_mean(field, names) {
5102 Some(hint) => error_with_hint(line, msg, hint),
5103 None => error(line, msg),
5104 }
5105 }),
5106 Value::EnumVariant(e) => e.field(field).cloned().ok_or_else(|| {
5107 error(
5108 line,
5109 nybl::error_messages::variant_has_no_field(e.type_name(), e.variant(), field),
5110 )
5111 }),
5112 Value::Module(m) => {
5113 if let Some(v) = self.module_binding(m, field) {
5114 return Ok(v);
5115 }
5116 if m.has_type(field) {
5117 return Err(error(
5118 line,
5119 format!("`{}` in `{}` is a type, not a value", field, m.path),
5120 ));
5121 }
5122 Err(error(
5123 line,
5124 format!("`{}` isn't exported from `{}`", field, m.path),
5125 ))
5126 }
5127 other => Err(error(
5128 line,
5129 nybl::error_messages::cant_read_field(field, other.type_name()),
5130 )),
5131 }
5132 }
5133
5134 fn field_set(
5135 &self,
5136 mut obj: Value,
5137 field: &str,
5138 value: Value,
5139 line: u32,
5140 ) -> Result<Value, NyblError> {
5141 match &mut obj {
5145 Value::Struct(boxed) => {
5146 let type_name = boxed.type_name().to_string();
5147 if !boxed.__try_set_field_in(field, value, line, &self.memory)? {
5148 return Err(error(
5149 line,
5150 nybl::error_messages::struct_has_no_field(&type_name, field),
5151 ));
5152 }
5153 Ok(obj)
5154 }
5155 other => Err(error(
5156 line,
5157 nybl::error_messages::cant_assign_field(field, other.type_name()),
5158 )),
5159 }
5160 }
5161
5162 fn match_fail(
5170 &mut self,
5171 pattern: PatternIdx,
5172 on_fail: CodeOffset,
5173 line: u32,
5174 ) -> Result<(), NyblError> {
5175 let value = self.pop_value(line)?;
5176 let recipe = self.current_chunk().pattern(pattern).clone();
5180 let mut bindings: Vec<(String, Value)> = Vec::new();
5181 let frame = self.frames.last().expect("frame present");
5187 let frame_scopes = &frame.scopes;
5188 let type_bindings = &self.type_bindings;
5189 let module_aliases = &self.module_aliases;
5190 let resolver = |ns: Option<&str>, tn: &str| -> Option<String> {
5191 if let Some(ns) = ns
5192 && let Some(slot) = recipe
5193 .namespaces
5194 .iter()
5195 .find(|(name, _)| name == ns)
5196 .map(|(_, namespace)| namespace)
5197 .and_then(|namespace| namespace.slot_idx())
5198 {
5199 return match frame.slots.get(slot.0 as usize) {
5200 Some(Value::Module(module)) => module.type_origin(tn).map(str::to_string),
5201 _ => None,
5202 };
5203 }
5204 resolve_type_in_frame(frame, frame_scopes, type_bindings, module_aliases, ns, tn)
5205 };
5206 let matched = nybl::pattern_matches_in(
5207 &recipe.pattern,
5208 &value,
5209 &mut bindings,
5210 &resolver,
5211 &self.memory,
5212 );
5213 if matched {
5214 for (name, v) in bindings {
5215 self.define_local(name, v);
5216 }
5217 } else {
5218 self.jump(on_fail);
5219 }
5220 Ok(())
5221 }
5222
5223 fn try_unwrap(&mut self, line: u32) -> Result<Next, NyblError> {
5237 let value = self.pop_value(line)?;
5238 match &value {
5239 Value::EnumVariant(ev) if ev.variant() == "Ok" => {
5240 use nybl::value::EnumPayload;
5241 let payload = match ev.payload() {
5242 EnumPayload::Tuple(items) if items.len() == 1 => items[0].clone(),
5243 EnumPayload::Unit => Value::None,
5244 EnumPayload::Tuple(items) => {
5245 return Err(error(
5246 line,
5247 format!(
5248 "try: Ok variant must carry exactly one value, got {}",
5249 items.len()
5250 ),
5251 ));
5252 }
5253 EnumPayload::Struct(_) => {
5254 return Err(error(
5255 line,
5256 "try: Ok variant must carry a single positional value, not named fields",
5257 ));
5258 }
5259 };
5260 self.push_value(payload);
5261 Ok(Next::Continue)
5262 }
5263 Value::EnumVariant(ev) if ev.variant() == "Err" => {
5264 let current_is_fn = self.frames.last().map(|f| f.is_function).unwrap_or(false);
5265 if !current_is_fn {
5266 return Err(nybl::error_messages::top_level_try_error(line));
5267 }
5268 self.do_return(value, line)
5271 }
5272 other => Err(error(
5273 line,
5274 format!(
5275 "try expected a Result-shaped value (Ok/Err variant), got {}",
5276 other.type_name()
5277 ),
5278 )),
5279 }
5280 }
5281
5282 fn define_fn(&mut self, idx: FnIdx, line: u32) -> Result<(), NyblError> {
5283 let chunk = Arc::clone(&self.frames.last().expect("frame present").chunk);
5284 let fn_def = chunk.function(idx);
5285 let name = fn_def.name.clone();
5286 if fn_def.checks_import_clash {
5290 if let Some(imported) = self
5291 .import_scopes
5292 .last()
5293 .and_then(|scope| scope.names.get(&name))
5294 {
5295 return Err(nybl::error_messages::function_replaces_import_error(
5296 &name,
5297 &imported.path,
5298 line,
5299 ));
5300 }
5301 if let Some(imports) = self.import_scopes.last_mut() {
5303 imports.functions.insert(name.clone());
5304 }
5305 }
5306 let entry = Rc::new(FnEntry {
5307 exact_self_name: Some(name.clone()),
5308 params: fn_def.params.clone(),
5309 param_modes: fn_def.param_modes.clone(),
5310 chunk: Arc::clone(&fn_def.chunk),
5311 module_path: self.active_module_path().to_string(),
5312 declaration_alias_names: self
5313 .frames
5314 .last()
5315 .expect("defining frame")
5316 .lexical_context
5317 .module_aliases
5318 .keys()
5319 .cloned()
5320 .collect(),
5321 });
5322 self.functions.insert(name.clone(), Rc::clone(&entry));
5323 if self.is_module_top_scope()
5324 && self.current_module == nybl::value::ROOT_MODULE_PATH
5325 && let Some(visibility) = self.root_function_visibility.get(&idx.0).copied()
5326 {
5327 self.abi_declarations
5328 .retain(|(existing, _)| existing != &name);
5329 if visibility == Visibility::Public {
5330 self.abi_declarations.push((name, entry));
5331 }
5332 }
5333 Ok(())
5334 }
5335
5336 fn make_lambda(&mut self, idx: FnIdx, line: u32) -> Result<(), NyblError> {
5342 let chunk = Arc::clone(&self.frames.last().expect("frame present").chunk);
5343 let fn_def = chunk.function(idx);
5344 let captures = self.snapshot_captures_for(fn_def);
5345 let body: Rc<dyn core::any::Any + 'static> = Rc::new(Arc::clone(&fn_def.chunk));
5346 let value = NyblFn::try_new_compiled_in_module_with_origin_and_modes(
5347 fn_def.params.clone(),
5348 fn_def.param_modes.clone(),
5349 captures,
5350 body,
5351 None,
5352 Some(self.active_module_path().to_string()),
5353 self.function_origin.clone(),
5354 0,
5355 line,
5356 )
5357 .map(Value::Fn)?;
5358 self.push_value(value);
5359 Ok(())
5360 }
5361
5362 fn snapshot_captures_for(&self, fn_def: &FnDef) -> Vec<(String, Value)> {
5375 let frame = self.frames.last().expect("frame present");
5376 let mut out = Vec::with_capacity(fn_def.capture_names.len());
5377 for (name, source) in fn_def
5378 .capture_names
5379 .iter()
5380 .zip(fn_def.capture_sources.iter())
5381 {
5382 match source {
5383 CaptureSource::ParentSlot(slot) => {
5384 let v = frame
5385 .slots
5386 .get(slot.0 as usize)
5387 .cloned()
5388 .unwrap_or(Value::None);
5389 out.push((name.clone(), v));
5390 }
5391 CaptureSource::ParentScope(look_name) => {
5392 let mut found = None;
5393 let defining_environment_floor =
5394 usize::from(frame.defining_environment_module.is_some());
5395 for scope in frame.scopes.iter().skip(defining_environment_floor).rev() {
5396 if let Some(v) = scope.get(look_name.as_str()) {
5397 found = Some(v.clone());
5398 break;
5399 }
5400 }
5401 if let Some(v) = found {
5402 out.push((name.clone(), v));
5403 }
5404 }
5405 };
5406 }
5407 out
5408 }
5409
5410 fn call_closure(
5415 &mut self,
5416 func: &Rc<NyblFn>,
5417 args: Vec<Value>,
5418 line: u32,
5419 ) -> Result<Next, NyblError> {
5420 if !func.__is_allowed_by(&self.function_origin, "vm") {
5421 return Err(error(
5422 line,
5423 "This function belongs to a different Nybl engine instance",
5424 ));
5425 }
5426 let chunk: Arc<Chunk> = match &func.body {
5430 FnBody::Compiled(any) => match any.downcast_ref::<Arc<Chunk>>() {
5431 Some(c) => Arc::clone(c),
5432 None => {
5433 return Err(error(
5434 line,
5435 "Closure body wasn't compiled by the bytecode VM",
5436 ));
5437 }
5438 },
5439 FnBody::Ast(_) => {
5440 return Err(error(
5441 line,
5442 "Closure body wasn't compiled for the VM — use `nybl::run` to execute tree-walker closures",
5443 ));
5444 }
5445 };
5446
5447 let display_name = func.self_name.as_deref().unwrap_or("fn");
5448 validate_user_arity(display_name, &func.param_modes, args.len(), false, line)?;
5449 let args = self.pack_rest_arguments(args, &func.param_modes, line)?;
5450
5451 if self.active_call_depth() >= MAX_CALL_DEPTH {
5452 return Err(nybl::error_messages::call_depth_error(line));
5453 }
5454 self.check_nesting(chunk.nesting_depth, line)?;
5455
5456 let slot_count = chunk.slot_count as usize;
5463 let mut slots = self.take_slots(slot_count);
5464 for (i, arg) in args.into_iter().enumerate() {
5465 let slot = chunk
5466 .parameter_slots
5467 .get(i)
5468 .ok_or_else(|| error(line, "VM: parameter slot metadata is incomplete"))?;
5469 slots[slot.0 as usize] = arg;
5470 }
5471
5472 let mut scope = BTreeMap::new();
5473 for (name, value) in &func.captures {
5474 scope.insert(name.clone(), value.clone());
5475 }
5476 if let Some(self_name) = &func.self_name {
5477 scope.insert(self_name.clone(), Value::Fn(Rc::clone(func)));
5478 }
5479
5480 self.push_function_frame(
5481 chunk,
5482 slots,
5483 vec![scope],
5484 self.stack.len(),
5485 func.module_path.clone(),
5486 FrameWrap::None,
5487 );
5488 let module = func
5489 .module_path
5490 .as_deref()
5491 .unwrap_or(nybl::value::ROOT_MODULE_PATH);
5492 self.bind_function_self_name(func.self_name.as_deref(), &func.params, module);
5493 if let Some(frame) = self.frames.last_mut() {
5494 frame.captured_names = func.captures.iter().map(|(name, _)| name.clone()).collect();
5495 }
5496 Ok(Next::Continue)
5497 }
5498
5499 fn exec_use(&mut self, spec: &crate::chunk::UseSpec, line: u32) -> Result<(), NyblError> {
5506 let refresh_root_context = self.is_module_top_scope();
5507 let path = spec.path.as_str();
5508 let items = spec.items.as_deref();
5509 let alias = spec.alias.as_deref();
5510
5511 let is_plain_glob = items.is_none() && alias.is_none();
5512 if is_plain_glob
5513 && self
5514 .import_scopes
5515 .last()
5516 .is_some_and(|imports| imports.paths.contains(path))
5517 {
5518 return Ok(());
5519 }
5520 self.park_active_defining_environment();
5525 let loaded = self.load_module(path, line);
5526 self.restore_active_defining_environment();
5527 let artifacts = loaded?;
5528
5529 for (key, fields) in &artifacts.struct_defs {
5536 if let Some(existing) = self.struct_defs.get(key) {
5537 if existing == fields {
5538 continue;
5539 }
5540 return Err(error(
5541 line,
5542 format!(
5543 "Type `{}` from `{}` reloaded with different fields",
5544 key.1, key.0
5545 ),
5546 ));
5547 }
5548 self.struct_defs.insert(key.clone(), fields.clone());
5549 }
5550 for (key, variants) in &artifacts.enum_defs {
5551 if let Some(existing) = self.enum_defs.get(key) {
5552 if shapes_match(existing, variants) {
5553 continue;
5554 }
5555 return Err(error(
5556 line,
5557 format!(
5558 "Type `{}` from `{}` reloaded with different variants",
5559 key.1, key.0
5560 ),
5561 ));
5562 }
5563 self.enum_defs.insert(key.clone(), variants.clone());
5564 }
5565 for (type_key, method_name, entry) in &artifacts.methods {
5566 self.user_methods
5567 .entry(type_key.clone())
5568 .or_default()
5569 .insert(method_name.clone(), entry.clone());
5570 }
5571
5572 let mut exports: Vec<(String, Value)> =
5577 Vec::with_capacity(artifacts.fn_decls.len() + artifacts.bindings.len());
5578 let mut fn_entries: BTreeMap<String, Rc<FnEntry>> = BTreeMap::new();
5579 for (name, entry) in &artifacts.fn_decls {
5580 if artifacts
5581 .bindings
5582 .iter()
5583 .any(|(binding, _)| binding == name)
5584 {
5585 continue;
5586 }
5587 let body: Rc<dyn core::any::Any + 'static> = Rc::new(entry.chunk.clone());
5588 let value = NyblFn::try_new_compiled_in_module_with_origin_and_modes(
5589 entry.params.clone(),
5590 entry.param_modes.clone(),
5591 Vec::new(),
5592 body,
5593 Some(name.clone()),
5594 Some(entry.module_path.clone()),
5595 self.function_origin.clone(),
5596 0,
5597 line,
5598 )
5599 .map(Value::Fn)?;
5600 exports.push((name.clone(), value));
5601 fn_entries.insert(name.clone(), entry.clone());
5602 }
5603 for (name, value) in &artifacts.bindings {
5604 exports.push((name.clone(), value.clone()));
5605 }
5606 exports.sort_by(|(left, _), (right, _)| left.cmp(right));
5610
5611 if let Some(list) = items {
5614 let available: BTreeSet<&str> = exports.iter().map(|(k, _)| k.as_str()).collect();
5615 for wanted in list {
5616 if !available.contains(wanted.as_str())
5617 && !artifacts.type_exports.contains_key(wanted)
5618 {
5619 return Err(error(
5620 line,
5621 format!("`{wanted}` isn't exported from `{path}` (selective import)"),
5622 ));
5623 }
5624 }
5625 let listed: BTreeSet<String> = list.iter().cloned().collect();
5626 exports.retain(|(k, _)| listed.contains(k));
5627 fn_entries.retain(|name, _| listed.contains(name));
5628 }
5629
5630 let exposed_types: BTreeMap<String, String> = match items {
5636 Some(list) => artifacts
5637 .type_exports
5638 .iter()
5639 .filter(|(name, _)| list.iter().any(|item| item == *name))
5640 .map(|(name, origin)| (name.clone(), origin.clone()))
5641 .collect(),
5642 None => artifacts
5643 .type_exports
5644 .iter()
5645 .filter(|(name, _)| {
5646 artifacts.explicit_surface || alias.is_some() || !nybl::naming::is_private(name)
5647 })
5648 .map(|(name, origin)| (name.clone(), origin.clone()))
5649 .collect(),
5650 };
5651
5652 if let Some(alias_name) = alias {
5653 let frame_has = self
5660 .frames
5661 .last()
5662 .and_then(|f| f.scopes.last())
5663 .map(|s| s.contains_key(alias_name))
5664 .unwrap_or(false);
5665 let imported_function_has = self
5666 .imported_functions
5667 .last()
5668 .is_some_and(|functions| functions.contains_key(alias_name));
5669 if frame_has || self.functions.contains_key(alias_name) || imported_function_has {
5670 return Err(error(
5671 line,
5672 format!("`{alias_name}` is already bound — can't use it as a module alias"),
5673 ));
5674 }
5675 let live_bindings = exports
5676 .iter()
5677 .map(|(name, _)| {
5678 let origin = artifacts
5679 .binding_origins
5680 .get(name)
5681 .cloned()
5682 .unwrap_or_else(|| (path.to_string(), name.clone()));
5683 (name.clone(), origin)
5684 })
5685 .collect();
5686 let module_rc = nybl::value::NyblModule::__try_new_live_with_type_exports(
5687 path.to_string(),
5688 exports,
5689 nybl::value::NyblTypeExports::from_origins(exposed_types),
5690 live_bindings,
5691 Rc::clone(&self.live_value_environments),
5692 line,
5693 )?;
5694 let module_value = Value::Module(Rc::clone(&module_rc));
5702 if let Some(frame) = self.frames.last_mut()
5703 && let Some(scope) = frame.scopes.last_mut()
5704 {
5705 scope.insert(alias_name.to_string(), module_value);
5706 }
5707 self.module_aliases
5708 .last_mut()
5709 .expect("module alias scope")
5710 .insert(alias_name.to_string(), Rc::clone(&module_rc));
5711 if let Some(scope) = self.type_bindings.last_mut() {
5712 scope.insert(alias_name.to_string(), path.to_string());
5713 }
5714 if refresh_root_context {
5715 self.publish_root_module_alias(alias_name.to_string(), Some(Rc::clone(&module_rc)));
5716 self.publish_root_type_binding(alias_name.to_string(), path.to_string());
5717 }
5718 } else {
5719 let skip_private = items.is_none() && !artifacts.explicit_surface;
5723 let module_top_scope = self.is_module_top_scope();
5724 let incoming_origin = |name: &str| {
5725 artifacts
5726 .binding_origins
5727 .get(name)
5728 .cloned()
5729 .unwrap_or_else(|| (path.to_string(), name.to_string()))
5730 };
5731 let mut already_bound = BTreeSet::new();
5736 for (name, _) in &exports {
5737 if skip_private && nybl::naming::is_private(name) {
5738 continue;
5739 }
5740 match self.flat_binding_origin(name, module_top_scope, spec.local_scope) {
5741 None => {}
5742 Some(Some(existing)) if existing == incoming_origin(name) => {
5743 already_bound.insert(name.clone());
5744 }
5745 Some(_) => {
5746 return Err(nybl::error_messages::import_clash_error(name, path, line));
5747 }
5748 }
5749 }
5750 for (type_name, origin) in &exposed_types {
5751 if let Some(existing) = self
5752 .type_bindings
5753 .last()
5754 .and_then(|scope| scope.get(type_name))
5755 && existing != origin
5756 {
5757 return Err(nybl::error_messages::import_clash_error(
5758 type_name, path, line,
5759 ));
5760 }
5761 }
5762 for (name, mut value) in exports {
5763 if skip_private && nybl::naming::is_private(&name) {
5764 continue;
5765 }
5766 if already_bound.contains(&name) {
5767 continue;
5768 }
5769 self.import_scopes
5770 .last_mut()
5771 .expect("import scope")
5772 .names
5773 .insert(
5774 name.clone(),
5775 ImportedName {
5776 origin: incoming_origin(&name),
5777 path: path.to_string(),
5778 },
5779 );
5780 if let Some(entry) = fn_entries.remove(&name) {
5781 self.imported_functions
5782 .last_mut()
5783 .expect("imported function scope")
5784 .insert(name.clone(), Rc::clone(&entry));
5785 if module_top_scope {
5786 self.publish_root_imported_function(name.clone(), entry);
5787 }
5788 }
5789 let module = artifacts.module_exports.get(&name).cloned();
5790 let origin = artifacts
5791 .binding_origins
5792 .get(&name)
5793 .cloned()
5794 .unwrap_or_else(|| (path.to_string(), name.clone()));
5795 if module_top_scope {
5796 self.binding_origins.insert(name.clone(), origin.clone());
5797 if (origin.0 != self.current_module || origin.1 != name)
5798 && let Some(authoritative) = self
5799 .live_value_environments
5800 .borrow_mut()
5801 .get_mut(&origin.0)
5802 .and_then(|environment| environment.remove(&origin.1))
5803 {
5804 value = authoritative;
5805 }
5806 } else if let Some(current) = self.live_origin_value(&origin) {
5807 value = current;
5808 }
5809 if let Some(frame) = self.frames.last_mut()
5810 && let Some(scope) = frame.scopes.last_mut()
5811 {
5812 scope.insert(name.clone(), value);
5813 }
5814 if let Some(module) = module {
5815 self.module_aliases
5816 .last_mut()
5817 .expect("module alias scope")
5818 .insert(name.clone(), Rc::clone(&module));
5819 if module_top_scope {
5820 self.publish_root_module_alias(name, Some(module));
5821 }
5822 }
5823 }
5824 for (type_name, origin) in &exposed_types {
5829 let already_bound = self
5830 .type_bindings
5831 .last()
5832 .map(|s| s.contains_key(type_name))
5833 .unwrap_or(false);
5834 if already_bound {
5835 continue;
5836 }
5837 if let Some(scope) = self.type_bindings.last_mut() {
5838 scope.insert(type_name.clone(), origin.clone());
5839 }
5840 if module_top_scope {
5841 self.type_exports
5842 .entry(type_name.clone())
5843 .or_insert_with(|| origin.clone());
5844 self.publish_root_type_binding(type_name.clone(), origin.clone());
5845 }
5846 }
5847 }
5848
5849 if is_plain_glob {
5850 self.import_scopes
5851 .last_mut()
5852 .expect("import scope")
5853 .paths
5854 .insert(path.to_string());
5855 }
5856 Ok(())
5857 }
5858
5859 fn flat_binding_origin(
5865 &self,
5866 name: &str,
5867 module_top_scope: bool,
5868 local_scope: Option<crate::chunk::LocalScopeSnapshot>,
5869 ) -> Option<Option<nybl::import_scope::BindingOrigin>> {
5870 if self.local_scope_shadows(local_scope, name) {
5876 return Some(None);
5877 }
5878 if let Some(origin) = self
5879 .import_scopes
5880 .last()
5881 .and_then(|scope| scope.known_origin(name))
5882 {
5883 return Some(Some(origin.clone()));
5884 }
5885 let bound = self
5886 .frames
5887 .last()
5888 .and_then(|frame| frame.scopes.last())
5889 .is_some_and(|scope| scope.contains_key(name))
5890 || self
5891 .import_scopes
5892 .last()
5893 .is_some_and(|scope| scope.functions.contains(name))
5894 || (module_top_scope && self.functions.contains_key(name));
5895 bound.then_some(None)
5896 }
5897
5898 fn local_scope_shadows(
5899 &self,
5900 snapshot: Option<crate::chunk::LocalScopeSnapshot>,
5901 name: &str,
5902 ) -> bool {
5903 let Some(snapshot) = snapshot else {
5904 return false;
5905 };
5906 let chunk = self.current_chunk();
5907 let scope = &chunk.local_scopes[snapshot.scope.0 as usize];
5908 scope
5909 .entries
5910 .binary_search_by(|entry| chunk.name(entry.name).cmp(name))
5911 .is_ok_and(|index| scope.entries[index].first_binding < snapshot.binding_count)
5912 }
5913
5914 fn resolve_namespaced_type(
5918 &self,
5919 namespace: crate::chunk::NamespaceRef,
5920 type_name: &str,
5921 line: u32,
5922 ) -> Result<String, NyblError> {
5923 let name = self.current_chunk().name(namespace.name_idx());
5924 let Some(slot) = namespace.slot_idx() else {
5925 self.validate_namespaced_type(name, type_name, line)?;
5926 return self.resolve_type_ref(Some(name), type_name).ok_or_else(|| {
5927 error(
5928 line,
5929 format!("`{type_name}` isn't a type exported from `{name}`"),
5930 )
5931 });
5932 };
5933 let value = self
5934 .frames
5935 .last()
5936 .and_then(|frame| frame.slots.get(slot.0 as usize))
5937 .ok_or_else(|| error(line, "VM: local slot out of range"))?;
5938 let module = match value {
5939 Value::Module(module) => module,
5940 other => {
5941 return Err(error(
5942 line,
5943 format!(
5944 "`{name}` is a {}, not a module alias — can't reach `{type_name}` through it",
5945 other.type_name()
5946 ),
5947 ));
5948 }
5949 };
5950 module
5951 .type_origin(type_name)
5952 .map(str::to_string)
5953 .ok_or_else(|| {
5954 error(
5955 line,
5956 format!("`{type_name}` isn't a type exported from `{}`", module.path),
5957 )
5958 })
5959 }
5960
5961 fn validate_namespaced_type(
5962 &self,
5963 ns: &str,
5964 type_name: &str,
5965 line: u32,
5966 ) -> Result<(), NyblError> {
5967 let frame = self
5973 .frames
5974 .last()
5975 .ok_or_else(|| error(line, "VM: no frame for namespaced type access"))?;
5976 for scope in frame.scopes.iter().rev() {
5977 if let Some(v) = scope.get(ns) {
5978 let module = match v {
5979 Value::Module(m) => m,
5980 other => {
5981 return Err(error(
5982 line,
5983 format!(
5984 "`{}` is a {}, not a module alias — can't reach `{}` through it",
5985 ns,
5986 other.type_name(),
5987 type_name
5988 ),
5989 ));
5990 }
5991 };
5992 if !module.has_type(type_name) {
5993 return Err(error(
5994 line,
5995 format!(
5996 "`{}` isn't a type exported from `{}`",
5997 type_name, module.path
5998 ),
5999 ));
6000 }
6001 return Ok(());
6002 }
6003 }
6004 if let Some(module) = self.module_alias(ns) {
6005 if !module.has_type(type_name) {
6006 return Err(error(
6007 line,
6008 format!(
6009 "`{}` isn't a type exported from `{}`",
6010 type_name, module.path
6011 ),
6012 ));
6013 }
6014 return Ok(());
6015 }
6016 Err(error(line, format!("`{ns}` isn't a module alias in scope")))
6017 }
6018
6019 fn resolve_type_ref(&self, namespace: Option<&str>, type_name: &str) -> Option<String> {
6024 let frame = self.frames.last()?;
6025 resolve_type_in_frame(
6026 frame,
6027 &frame.scopes,
6028 &self.type_bindings,
6029 &self.module_aliases,
6030 namespace,
6031 type_name,
6032 )
6033 }
6034
6035 fn load_module(&mut self, path: &str, line: u32) -> Result<ModuleArtifacts, NyblError> {
6036 {
6037 let cache = self.imports.borrow();
6038 if let Some(ImportSlot::Loaded(bindings)) = cache.get(path) {
6039 return Ok(bindings.clone());
6040 }
6041 if let Some(ImportSlot::Loading) = cache.get(path) {
6042 return Err(error(
6043 line,
6044 format!("Circular import: module `{path}` is still loading"),
6045 ));
6046 }
6047 }
6048
6049 if self.active_call_depth() >= MAX_CALL_DEPTH {
6051 return Err(nybl::error_messages::call_depth_error(line));
6052 }
6053
6054 let compiled = self
6055 .compiled_modules
6056 .as_ref()
6057 .and_then(|modules| modules.get(path))
6058 .cloned();
6059
6060 let (chunk, source): (Arc<Chunk>, Arc<str>) = match compiled {
6061 Some(module) => {
6062 self.charge_steps(module.load_steps, line)?;
6064 nybl::check::check_disabled_builtins(
6065 &module.builtin_usage,
6066 &self.limits.disabled_builtins,
6067 )
6068 .map_err(|error| error.with_module_source(path, module.source.as_ref()))?;
6069 (module.chunk, module.source)
6070 }
6071 None if self.compiled_modules.is_some() => {
6072 return Err(error(
6077 line,
6078 format!("Module `{path}` is missing from the compiled module graph"),
6079 ));
6080 }
6081 None => {
6082 let source = match self.host.resolve_module(path) {
6083 Some(Ok(source)) => source,
6084 Some(Err(error)) => return Err(error),
6085 None => return Err(error(line, format!("Module `{path}` not found"))),
6086 };
6087 let chunk = self.compile_module_source(path, &source, line)?;
6088 (Arc::new(chunk), Arc::from(source))
6089 }
6090 };
6091 self.check_nesting(chunk.nesting_depth, line)?;
6092
6093 self.imports
6094 .borrow_mut()
6095 .insert(path.to_string(), ImportSlot::Loading);
6096
6097 let result = self
6098 .evaluate_module_chunk(path, chunk)
6099 .map_err(|error| error.with_module_source(path, source.as_ref()));
6100
6101 match result {
6102 Ok(bindings) => {
6103 self.imports
6104 .borrow_mut()
6105 .insert(path.to_string(), ImportSlot::Loaded(bindings.clone()));
6106 Ok(bindings)
6107 }
6108 Err(e) => {
6109 self.imports.borrow_mut().remove(path);
6110 Err(e)
6111 }
6112 }
6113 }
6114
6115 fn compile_module_source(
6119 &mut self,
6120 path: &str,
6121 source: &str,
6122 line: u32,
6123 ) -> Result<Chunk, NyblError> {
6124 let tokens =
6125 nybl::lexer::lex(source).map_err(|error| error.with_module_source(path, source))?;
6126 self.charge_steps(nybl::lexer::module_load_steps(&tokens), line)?;
6127 (|| {
6128 let stmts = nybl::parser::parse(tokens)?;
6129 nybl::check::enforce_disabled_builtins(&stmts, &self.limits.disabled_builtins)?;
6134 crate::compile(&stmts)
6135 })()
6136 .map_err(|error| error.with_module_source(path, source))
6137 }
6138
6139 fn evaluate_module_chunk(
6143 &mut self,
6144 module_path: &str,
6145 chunk: Arc<Chunk>,
6146 ) -> Result<ModuleArtifacts, NyblError> {
6147 let public_surface = chunk.public_surface.clone();
6148 let module_runtime = ModuleRuntime {
6149 imports: Rc::clone(&self.imports),
6150 environments: Rc::clone(&self.live_value_environments),
6151 origins: Rc::clone(&self.live_binding_origins),
6152 };
6153 let limits = self.limits.clone();
6154 let call_depth_base = self.active_call_depth() + 1;
6155 let nesting_base = self.nesting_used();
6156 let steps = self.steps;
6157 let mut sub = Vm::new_internal(
6158 chunk,
6159 self.host,
6160 limits,
6161 module_runtime,
6162 self.compiled_modules.clone(),
6163 module_path.to_string(),
6164 BTreeMap::new(),
6165 self.function_origin.clone(),
6166 self.memory.clone(),
6167 );
6168 sub.steps = steps;
6171 sub.call_depth_base = call_depth_base;
6172 if let Some(top) = sub.frames.first_mut() {
6173 top.nesting_total = nesting_base.saturating_add(top.chunk.nesting_depth);
6174 }
6175 let module_result = sub.run_internal();
6176 self.steps = sub.steps;
6177 if let Err(module_error) = module_result {
6178 sub.restore_instance_baseline();
6179 let failed_environment = sub
6180 .frames
6181 .first_mut()
6182 .and_then(|frame| frame.scopes.first_mut())
6183 .map(core::mem::take)
6184 .unwrap_or_default();
6185 put_live_environment(
6186 &sub.live_value_environments,
6187 module_path,
6188 failed_environment,
6189 &sub.binding_origins,
6190 );
6191 sub.live_value_environments.borrow_mut().remove(module_path);
6194 sub.live_binding_origins.borrow_mut().remove(module_path);
6195 return Err(module_error);
6196 }
6197 let mut bindings = match sub
6200 .frames
6201 .first()
6202 .and_then(|frame| frame.scopes.first())
6203 .map(|scope| {
6204 snapshot_module_bindings(scope, &sub.binding_origins, module_path, &sub.imports, 0)
6205 })
6206 .transpose()
6207 {
6208 Ok(bindings) => bindings.unwrap_or_default(),
6209 Err(snapshot_error) => {
6210 let failed_environment = sub
6211 .frames
6212 .first_mut()
6213 .and_then(|frame| frame.scopes.first_mut())
6214 .map(core::mem::take)
6215 .unwrap_or_default();
6216 put_live_environment(
6217 &sub.live_value_environments,
6218 module_path,
6219 failed_environment,
6220 &sub.binding_origins,
6221 );
6222 sub.live_value_environments.borrow_mut().remove(module_path);
6223 sub.live_binding_origins.borrow_mut().remove(module_path);
6224 return Err(snapshot_error);
6225 }
6226 };
6227 let live_environment = sub
6228 .frames
6229 .first_mut()
6230 .and_then(|frame| frame.scopes.first_mut())
6231 .map(core::mem::take)
6232 .unwrap_or_default();
6233 let binding_origins = sub.binding_origins.clone();
6234 put_live_environment(
6235 &sub.live_value_environments,
6236 module_path,
6237 live_environment,
6238 &binding_origins,
6239 );
6240 sub.live_binding_origins
6241 .borrow_mut()
6242 .insert(module_path.to_string(), binding_origins.clone());
6243 let mut fn_decls: Vec<(String, Rc<FnEntry>)> = sub.functions.into_iter().collect();
6249 let builtin_mp = nybl::value::BUILTIN_MODULE_PATH;
6256 let struct_defs: Vec<ModuleStructDef> = sub
6257 .struct_defs
6258 .into_iter()
6259 .filter(|((mp, _), _)| mp != builtin_mp)
6260 .collect();
6261 let enum_defs: Vec<ModuleEnumDef> = sub
6262 .enum_defs
6263 .into_iter()
6264 .filter(|((mp, _), _)| mp != builtin_mp)
6265 .collect();
6266 let mut methods: Vec<ModuleMethodDef> = Vec::new();
6267 for (type_key, by_method) in sub.user_methods {
6268 for (method_name, entry) in by_method {
6269 methods.push((type_key.clone(), method_name, entry));
6270 }
6271 }
6272 let all_module_exports: BTreeMap<String, Rc<nybl::value::NyblModule>> = bindings
6273 .iter()
6274 .filter_map(|(name, value)| match value {
6275 Value::Module(module) => Some((name.clone(), Rc::clone(module))),
6276 _ => None,
6277 })
6278 .collect();
6279 let mut lexical_context = Rc::try_unwrap(core::mem::take(&mut sub.root_lexical_context))
6280 .unwrap_or_else(|context| (*context).clone());
6281 lexical_context.module_aliases = Rc::new(all_module_exports.clone());
6282 let lexical_context = Rc::new(lexical_context);
6283 let mut type_exports = sub.type_exports;
6284 let explicit_surface = public_surface.is_some();
6285 if let Some(names) = public_surface {
6286 let names: BTreeSet<String> = names.into_iter().collect();
6287 bindings.retain(|(name, _)| names.contains(name));
6288 fn_decls.retain(|(name, _)| names.contains(name));
6289 type_exports.retain(|name, _| names.contains(name));
6290 }
6291 let module_exports: BTreeMap<String, Rc<nybl::value::NyblModule>> = bindings
6292 .iter()
6293 .filter_map(|(name, value)| match value {
6294 Value::Module(module) => Some((name.clone(), Rc::clone(module))),
6295 _ => None,
6296 })
6297 .collect();
6298 Ok(ModuleArtifacts {
6299 explicit_surface,
6300 bindings,
6301 binding_origins,
6302 fn_decls,
6303 struct_defs,
6304 enum_defs,
6305 methods,
6306 type_exports,
6307 module_exports,
6308 lexical_context,
6309 })
6310 }
6311
6312 fn run_internal(&mut self) -> Result<(), NyblError> {
6316 while let Some((instr, line)) = self.fetch() {
6317 if let Err(err) = self.tick(line) {
6318 let err = self.attach_frame_module_context(err);
6319 self.unwind_to_try_call(err)?;
6320 continue;
6321 }
6322 match self.dispatch(instr, line) {
6323 Ok(Next::Continue) => {}
6324 Ok(Next::Halt) => break,
6325 Err(err) => {
6326 let err = self.attach_frame_module_context(err);
6327 self.unwind_to_try_call(err)?;
6328 }
6329 }
6330 }
6331 Ok(())
6332 }
6333
6334 fn do_return(&mut self, value: Value, line: u32) -> Result<Next, NyblError> {
6335 if self.memory.__exceeded() {
6336 return Err(error_fatal_with_hint(
6337 line,
6338 "Memory limit exceeded",
6339 "Your code is using too much memory. Check for large strings or arrays growing in loops.",
6340 ));
6341 }
6342 if self.frames.last().is_some_and(|frame| !frame.is_function) {
6343 drop(value);
6344 let frame = self.frames.last_mut().expect("frame present");
6345 frame.ip = frame.chunk.code.len();
6346 frame.scopes.truncate(frame.scope_base);
6347 self.stack.clear();
6348 self.type_bindings.truncate(frame.type_scope_base);
6349 self.module_aliases.truncate(frame.alias_scope_base);
6350 self.imported_functions.truncate(frame.alias_scope_base);
6351 self.import_scopes.truncate(frame.alias_scope_base);
6352 return Ok(Next::Halt);
6353 }
6354 let mut frame = self.frames.pop().expect("frame present");
6357 self.store_frame_defining_environment(&mut frame);
6358 self.restore_active_defining_environment();
6359 self.stack.truncate(frame.stack_base);
6360 self.type_bindings.truncate(frame.caller_type_scope_depth());
6364 self.module_aliases.truncate(frame.alias_scope_base);
6365 self.imported_functions.truncate(frame.alias_scope_base);
6366 self.import_scopes.truncate(frame.alias_scope_base);
6367 match frame.wrap {
6372 FrameWrap::IterStart => {
6373 self.stack.push(Slot::IterObject(value));
6377 return Ok(Next::Continue);
6378 }
6379 FrameWrap::IterAdvance(target) => {
6380 match unwrap_iter_step(&value) {
6387 IterStep::Next(x) => {
6388 drop(value);
6389 self.push_value(x);
6390 return Ok(Next::Continue);
6391 }
6392 IterStep::Done => {
6393 drop(value);
6394 self.stack.pop();
6395 self.jump(target);
6396 return Ok(Next::Continue);
6397 }
6398 IterStep::Malformed => {
6399 let msg = format!(
6400 "`.next()` on a `for` iterator must return `Iter::Next(v)` or `Iter::Done`, got {}",
6401 value.inspect()
6402 );
6403 let caller_line = self
6409 .frames
6410 .last()
6411 .and_then(|f| {
6412 let idx = f.ip.saturating_sub(1);
6413 f.chunk.lines.get(idx).copied()
6414 })
6415 .unwrap_or(0);
6416 return Err(error(caller_line, msg));
6417 }
6418 }
6419 }
6420 _ => {}
6421 }
6422 let final_value = match frame.wrap {
6427 FrameWrap::None => value,
6428 FrameWrap::TryCall { line } => {
6429 builtins::make_try_call_ok_in(value, line, &self.memory)?
6430 }
6431 FrameWrap::ResultOk { line } => methods::make_result_ok_in(value, line, &self.memory)?,
6432 FrameWrap::ResultErr { line } => {
6433 methods::make_result_err_in(value, line, &self.memory)?
6434 }
6435 FrameWrap::IterStart | FrameWrap::IterAdvance(_) => {
6436 unreachable!("handled above")
6437 }
6438 };
6439 if self.memory.__exceeded() {
6440 return Err(error_fatal_with_hint(
6441 line,
6442 "Memory limit exceeded",
6443 "Your code is using too much memory. Check for large strings or arrays growing in loops.",
6444 ));
6445 }
6446 self.commit_frame_write_backs(&frame, line)?;
6450
6451 if !frame.slots.is_empty() {
6454 self.return_slots(core::mem::take(&mut frame.slots));
6455 }
6456 if frame.is_function {
6457 self.push_value(final_value);
6458 Ok(Next::Continue)
6459 } else {
6460 drop(final_value);
6463 Ok(Next::Halt)
6464 }
6465 }
6466
6467 fn commit_frame_write_backs(&mut self, frame: &Frame, line: u32) -> Result<(), NyblError> {
6468 if frame.pending_write_backs.is_empty() {
6469 return Ok(());
6470 }
6471 let mut values = Vec::with_capacity(frame.pending_write_backs.len());
6472 for pending in &frame.pending_write_backs {
6473 let parameter_slot = frame
6474 .chunk
6475 .parameter_slots
6476 .get(pending.parameter)
6477 .ok_or_else(|| error(line, "VM: ref parameter metadata is incomplete"))?;
6478 let value = frame
6479 .slots
6480 .get(parameter_slot.0 as usize)
6481 .cloned()
6482 .ok_or_else(|| error(line, "VM: ref parameter slot out of range"))?;
6483 let mut root = self.resolved_target_value(&pending.place.target, line)?;
6484 self.write_place_value(&mut root, &pending.place.projections, value, line)?;
6485 values.push(root);
6486 }
6487 for (pending, value) in frame.pending_write_backs.iter().zip(values) {
6488 self.store_resolved_target(&pending.place.target, value, line)?;
6489 }
6490 Ok(())
6491 }
6492
6493 fn builtin_try_call(&mut self, args: Vec<Value>, line: u32) -> Result<Next, NyblError> {
6500 if args.len() != 1 {
6501 return Err(error(
6502 line,
6503 format!("`try_call` expects 1 argument, but got {}", args.len()),
6504 ));
6505 }
6506 let mut iter = args.into_iter();
6507 let callable = iter.next().unwrap();
6508 let func = match &callable {
6509 Value::Fn(f) => Rc::clone(f),
6510 other => {
6511 return Err(error(
6512 line,
6513 format!("`try_call` expects a function, got {}", other.type_name()),
6514 ));
6515 }
6516 };
6517 drop(callable);
6518 if let Err(err) = self.call_closure(&func, Vec::new(), line) {
6519 if err.is_fatal {
6520 return Err(err);
6521 }
6522 self.push_value(builtins::make_try_call_err_in(&err, &self.memory));
6523 if self.memory.__exceeded() {
6524 return Err(error_fatal_with_hint(
6525 line,
6526 "Memory limit exceeded",
6527 "Your code is using too much memory. Check for large strings or arrays growing in loops.",
6528 ));
6529 }
6530 return Ok(Next::Continue);
6531 }
6532 if let Some(frame) = self.frames.last_mut() {
6535 frame.wrap = FrameWrap::TryCall { line };
6536 }
6537 Ok(Next::Continue)
6538 }
6539
6540 fn dispatch_iter_method(
6547 &mut self,
6548 receiver: Value,
6549 method: &str,
6550 extra_args: Vec<Value>,
6551 wrap: FrameWrap,
6552 line: u32,
6553 ) -> Result<(), NyblError> {
6554 let type_key: Option<(String, String)> = match &receiver {
6555 Value::Struct(s) => Some((s.module_path().to_string(), s.type_name().to_string())),
6556 Value::EnumVariant(e) => Some((e.module_path().to_string(), e.type_name().to_string())),
6557 _ => None,
6558 };
6559 let key = type_key.ok_or_else(|| {
6560 error(
6561 line,
6562 nybl::error_messages::cant_iterate_over(receiver.type_name()),
6563 )
6564 })?;
6565 let entry = self
6566 .user_methods
6567 .get(&key)
6568 .and_then(|m| m.get(method))
6569 .cloned()
6570 .ok_or_else(|| {
6571 error(
6572 line,
6573 format!(
6574 "`{}` doesn't have a `.{}()` method — can't iterate",
6575 key.1, method
6576 ),
6577 )
6578 })?;
6579 validate_user_arity(
6580 &format!("{}.{}", key.1, method),
6581 &entry.param_modes,
6582 extra_args.len() + 1,
6583 true,
6584 line,
6585 )?;
6586 let mut args = Vec::with_capacity(extra_args.len() + 1);
6587 args.push(receiver);
6588 args.extend(extra_args);
6589 self.enter_user_fn_args(Rc::clone(&entry), args, line)?;
6590 self.frames.last_mut().expect("callee frame").wrap = wrap;
6591 self.apply_entry_alias_context(&entry);
6592 Ok(())
6593 }
6594
6595 fn call_result_callable_method(
6603 &mut self,
6604 obj: Value,
6605 kind: methods::ResultCallableKind,
6606 method: &str,
6607 args: Vec<Value>,
6608 line: u32,
6609 ) -> Result<Next, NyblError> {
6610 use methods::{ResultCallableKind, make_result_err_in, make_result_ok_in};
6611 if args.len() != 1 {
6612 return Err(error(
6613 line,
6614 format!("`{}` expects 1 argument, but got {}", method, args.len()),
6615 ));
6616 }
6617 let mut args_iter = args.into_iter();
6618 let callable = args_iter.next().unwrap();
6619
6620 let (is_ok, payload) = match &obj {
6621 Value::EnumVariant(e) => {
6622 let payload = match e.payload() {
6623 nybl::value::EnumPayload::Tuple(items) if items.len() == 1 => items[0].clone(),
6624 _ => {
6625 return Err(error(
6626 line,
6627 format!("malformed Result::{} payload", e.variant()),
6628 ));
6629 }
6630 };
6631 (e.variant() == "Ok", payload)
6632 }
6633 _ => return Err(error(line, "Result method called on non-Result")),
6634 };
6635 drop(obj);
6636
6637 match kind {
6638 ResultCallableKind::Map => {
6639 if !is_ok {
6640 let value = make_result_err_in(payload, line, &self.memory)?;
6642 if self.memory.__exceeded() {
6643 return Err(error_fatal_with_hint(
6644 line,
6645 "Memory limit exceeded",
6646 "Your code is using too much memory. Check for large strings or arrays growing in loops.",
6647 ));
6648 }
6649 self.push_value(value);
6650 return Ok(Next::Continue);
6651 }
6652 let func = match &callable {
6653 Value::Fn(f) => Rc::clone(f),
6654 other => {
6655 return Err(error(
6656 line,
6657 format!("`map` expects a function, got {}", other.type_name()),
6658 ));
6659 }
6660 };
6661 drop(callable);
6662 self.call_closure(&func, vec![payload], line)?;
6663 if let Some(frame) = self.frames.last_mut() {
6664 frame.wrap = FrameWrap::ResultOk { line };
6665 }
6666 Ok(Next::Continue)
6667 }
6668 ResultCallableKind::MapErr => {
6669 if is_ok {
6670 let value = make_result_ok_in(payload, line, &self.memory)?;
6671 if self.memory.__exceeded() {
6672 return Err(error_fatal_with_hint(
6673 line,
6674 "Memory limit exceeded",
6675 "Your code is using too much memory. Check for large strings or arrays growing in loops.",
6676 ));
6677 }
6678 self.push_value(value);
6679 return Ok(Next::Continue);
6680 }
6681 let func = match &callable {
6682 Value::Fn(f) => Rc::clone(f),
6683 other => {
6684 return Err(error(
6685 line,
6686 format!("`map_err` expects a function, got {}", other.type_name()),
6687 ));
6688 }
6689 };
6690 drop(callable);
6691 self.call_closure(&func, vec![payload], line)?;
6692 if let Some(frame) = self.frames.last_mut() {
6693 frame.wrap = FrameWrap::ResultErr { line };
6694 }
6695 Ok(Next::Continue)
6696 }
6697 ResultCallableKind::AndThen => {
6698 if !is_ok {
6699 let value = make_result_err_in(payload, line, &self.memory)?;
6700 if self.memory.__exceeded() {
6701 return Err(error_fatal_with_hint(
6702 line,
6703 "Memory limit exceeded",
6704 "Your code is using too much memory. Check for large strings or arrays growing in loops.",
6705 ));
6706 }
6707 self.push_value(value);
6708 return Ok(Next::Continue);
6709 }
6710 let func = match &callable {
6711 Value::Fn(f) => Rc::clone(f),
6712 other => {
6713 return Err(error(
6714 line,
6715 format!("`and_then` expects a function, got {}", other.type_name()),
6716 ));
6717 }
6718 };
6719 drop(callable);
6720 self.call_closure(&func, vec![payload], line)
6724 }
6725 }
6726 }
6727
6728 fn attach_frame_module_context(&self, err: NyblError) -> NyblError {
6746 if err.source_context.is_some() || err.is_try_return {
6747 return err;
6748 }
6749 match self
6750 .frames
6751 .last()
6752 .and_then(|frame| frame.function_module.as_deref())
6753 {
6754 Some(module) => {
6755 if let Some(compiled) = self
6756 .compiled_modules
6757 .as_ref()
6758 .and_then(|modules| modules.get(module))
6759 {
6760 err.with_module_source(module, compiled.source.as_ref())
6761 } else {
6762 err.with_module(module)
6763 }
6764 }
6765 None => err,
6766 }
6767 }
6768
6769 fn unwind_to_try_call(&mut self, err: NyblError) -> Result<(), NyblError> {
6780 if err.is_fatal {
6781 return Err(err);
6782 }
6783 let wrap_idx = match self
6784 .frames
6785 .iter()
6786 .rposition(|f| matches!(f.wrap, FrameWrap::TryCall { .. }))
6787 {
6788 Some(i) => i,
6789 None => return Err(err),
6790 };
6791 let wrapper_stack_base = self.frames[wrap_idx].stack_base;
6792 let wrapper_line = match self.frames[wrap_idx].wrap {
6793 FrameWrap::TryCall { line } => line,
6794 _ => unreachable!("try_call frame selected by wrapper kind"),
6795 };
6796 while self.frames.len() > wrap_idx {
6799 let mut frame = self.frames.pop().expect("frame present");
6800 self.store_frame_defining_environment(&mut frame);
6801 self.type_bindings.truncate(frame.caller_type_scope_depth());
6802 self.module_aliases.truncate(frame.alias_scope_base);
6803 self.imported_functions.truncate(frame.alias_scope_base);
6804 self.import_scopes.truncate(frame.alias_scope_base);
6805 if !frame.slots.is_empty() {
6806 self.return_slots(frame.slots);
6807 }
6808 }
6809 self.restore_active_defining_environment();
6810 self.stack.truncate(wrapper_stack_base);
6811 self.push_value(builtins::make_try_call_err_in(&err, &self.memory));
6812 if self.memory.__exceeded() {
6813 Err(error_fatal_with_hint(
6814 wrapper_line,
6815 "Memory limit exceeded",
6816 "Your code is using too much memory. Check for large strings or arrays growing in loops.",
6817 ))
6818 } else {
6819 Ok(())
6820 }
6821 }
6822}
6823
6824fn resolve_type_in_frame(
6825 frame: &Frame,
6826 value_scopes: &[BTreeMap<String, Value>],
6827 type_scopes: &[BTreeMap<String, String>],
6828 module_aliases: &[BTreeMap<String, Rc<nybl::value::NyblModule>>],
6829 namespace: Option<&str>,
6830 type_name: &str,
6831) -> Option<String> {
6832 if let Some(namespace) = namespace {
6833 for scope in value_scopes.iter().rev() {
6834 if let Some(value) = scope.get(namespace) {
6835 return match value {
6836 Value::Module(module) => module.type_origin(type_name).map(str::to_string),
6837 _ => None,
6838 };
6839 }
6840 }
6841 let floor = frame.is_function.then_some(frame.alias_scope_base);
6842 for (index, aliases) in module_aliases.iter().enumerate().rev() {
6843 if floor.is_some_and(|floor| index < floor) {
6844 continue;
6845 }
6846 if let Some(module) = aliases.get(namespace) {
6847 return module.type_origin(type_name).map(str::to_string);
6848 }
6849 }
6850 return frame
6851 .lexical_context
6852 .module_aliases
6853 .get(namespace)
6854 .and_then(|module| module.type_origin(type_name).map(str::to_string));
6855 }
6856
6857 let floor = frame
6858 .is_function
6859 .then_some(frame.type_scope_base.saturating_sub(1));
6860 for (index, bindings) in type_scopes.iter().enumerate().rev() {
6861 if floor.is_some_and(|floor| index < floor) {
6862 continue;
6863 }
6864 if let Some(module_path) = bindings.get(type_name) {
6865 return Some(module_path.clone());
6866 }
6867 }
6868 frame.lexical_context.type_bindings.get(type_name).cloned()
6869}
6870
6871fn apply_in_place_assign<F>(
6872 op: crate::chunk::InPlaceAssignOp,
6873 rhs: Value,
6874 line: u32,
6875 memory: &nybl::memory::MemoryContext,
6876 current: F,
6877) -> Result<Value, NyblError>
6878where
6879 F: FnOnce() -> Result<Value, NyblError>,
6880{
6881 use crate::chunk::InPlaceAssignOp;
6882
6883 if op == InPlaceAssignOp::Eq {
6884 return Ok(rhs);
6885 }
6886 let left = current()?;
6887 match op {
6888 InPlaceAssignOp::Eq => unreachable!(),
6889 InPlaceAssignOp::Add => ops::add_in(&left, &rhs, line, memory),
6890 InPlaceAssignOp::Sub => ops::sub_in(&left, &rhs, line, memory),
6891 InPlaceAssignOp::Mul => ops::mul_in(&left, &rhs, line, memory),
6892 InPlaceAssignOp::Div => ops::div_in(&left, &rhs, line, memory),
6893 InPlaceAssignOp::Rem => ops::rem_in(&left, &rhs, line, memory),
6894 }
6895}
6896
6897#[derive(Clone)]
6912pub struct CompiledScript {
6913 chunk: Arc<Chunk>,
6914 root_function_visibility: Arc<BTreeMap<u32, Visibility>>,
6915 builtin_usage: Arc<BTreeMap<String, u32>>,
6919 compiled_modules: Option<CompiledModuleGraph>,
6922}
6923
6924impl core::fmt::Debug for CompiledScript {
6925 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
6926 f.debug_struct("CompiledScript")
6927 .field("instructions", &self.chunk.code.len())
6928 .field("functions", &self.chunk.functions.len())
6929 .field(
6930 "precompiled_modules",
6931 &self
6932 .compiled_modules
6933 .as_ref()
6934 .map_or(0, |modules| modules.len()),
6935 )
6936 .finish_non_exhaustive()
6937 }
6938}
6939
6940const _: () = {
6943 const fn assert_send_sync<T: Send + Sync>() {}
6944 assert_send_sync::<CompiledScript>();
6945};
6946
6947impl CompiledScript {
6948 pub fn compile(source: &str) -> Result<Self, NyblError> {
6953 let statements = nybl::parse(source)?;
6954 let builtin_usage = nybl::check::collect_builtin_usage(&statements);
6955 let compiled = crate::compiler::compile_program(&statements)?;
6956 crate::validate_chunk(&compiled.chunk)?;
6957 Ok(Self {
6958 chunk: Arc::new(compiled.chunk),
6959 root_function_visibility: Arc::new(compiled.root_function_visibility),
6960 builtin_usage: Arc::new(builtin_usage),
6961 compiled_modules: None,
6962 })
6963 }
6964
6965 pub fn compile_with_modules<F>(source: &str, mut resolver: F) -> Result<Self, NyblError>
6979 where
6980 F: FnMut(&str) -> Option<Result<String, NyblError>>,
6981 {
6982 let mut program = Self::compile(source)?;
6983 let mut modules = BTreeMap::new();
6984 let mut root_uses = BTreeMap::new();
6985 collect_chunk_use_sites(&program.chunk, &mut root_uses);
6986 for (path, line) in root_uses {
6987 compile_reachable_module(&path, line, None, &mut resolver, &mut modules)?;
6988 }
6989 program.compiled_modules = Some(Arc::new(modules));
6990 Ok(program)
6991 }
6992
6993 #[doc(hidden)]
6996 pub fn __root_chunk_ptr(&self) -> *const u8 {
6997 Arc::as_ptr(&self.chunk).cast()
6998 }
6999
7000 #[doc(hidden)]
7003 pub fn __module_chunk_ptr(&self, path: &str) -> Option<*const u8> {
7004 self.compiled_modules
7005 .as_ref()?
7006 .get(path)
7007 .map(|module| Arc::as_ptr(&module.chunk).cast())
7008 }
7009}
7010
7011fn collect_chunk_use_sites(chunk: &Chunk, uses: &mut BTreeMap<String, u32>) {
7015 for (offset, instruction) in chunk.code.iter().enumerate() {
7016 if let Instr::Use(index) = instruction {
7017 let spec = chunk.use_spec(*index);
7018 uses.entry(spec.path.clone()).or_insert(chunk.lines[offset]);
7019 }
7020 }
7021 for function in &chunk.functions {
7022 collect_chunk_use_sites(&function.chunk, uses);
7023 }
7024}
7025
7026fn compile_reachable_module<F>(
7027 path: &str,
7028 use_line: u32,
7029 importer: Option<(&str, &str)>,
7030 resolver: &mut F,
7031 modules: &mut BTreeMap<String, CompiledModule>,
7032) -> Result<(), NyblError>
7033where
7034 F: FnMut(&str) -> Option<Result<String, NyblError>>,
7035{
7036 if modules.contains_key(path) {
7039 return Ok(());
7040 }
7041
7042 let source = match resolver(path) {
7043 Some(Ok(source)) => source,
7044 Some(Err(error)) => return Err(attach_importer_source(error, importer)),
7045 None => {
7046 return Err(attach_importer_source(
7047 error(use_line, format!("Module `{path}` not found")),
7048 importer,
7049 ));
7050 }
7051 };
7052 let tokens = nybl::lexer::lex(&source)
7053 .map_err(|error| error.with_module_source(path, source.as_str()))?;
7054 let load_steps = nybl::lexer::module_load_steps(&tokens);
7055 let statements = nybl::parser::parse(tokens)
7056 .map_err(|error| error.with_module_source(path, source.as_str()))?;
7057 let builtin_usage = nybl::check::collect_builtin_usage(&statements);
7058 let compiled = crate::compiler::compile_program(&statements)
7059 .map_err(|error| error.with_module_source(path, source.as_str()))?;
7060 crate::validate_chunk(&compiled.chunk)
7061 .map_err(|error| error.with_module_source(path, source.as_str()))?;
7062
7063 let mut uses = BTreeMap::new();
7064 collect_chunk_use_sites(&compiled.chunk, &mut uses);
7065 let module = CompiledModule {
7066 chunk: Arc::new(compiled.chunk),
7067 source: Arc::from(source),
7068 builtin_usage: Arc::new(builtin_usage),
7069 load_steps,
7070 };
7071 modules.insert(path.to_string(), module);
7072
7073 let importer_source = Arc::clone(&modules[path].source);
7076 for (dependency, line) in uses {
7077 compile_reachable_module(
7078 &dependency,
7079 line,
7080 Some((path, importer_source.as_ref())),
7081 resolver,
7082 modules,
7083 )?;
7084 }
7085 Ok(())
7086}
7087
7088fn attach_importer_source(error: NyblError, importer: Option<(&str, &str)>) -> NyblError {
7089 match importer {
7090 Some((path, source)) => error.with_module_source(path, source),
7091 None => error,
7092 }
7093}
7094
7095impl NyblInstance {
7096 pub fn load(
7102 source: &str,
7103 host: &mut dyn NyblHost,
7104 limits: &NyblLimits,
7105 ) -> Result<Self, NyblError> {
7106 let program = CompiledScript::compile(source)?;
7107 Self::from_compiled(&program, host, limits)
7108 }
7109
7110 pub fn from_compiled(
7120 program: &CompiledScript,
7121 host: &mut dyn NyblHost,
7122 limits: &NyblLimits,
7123 ) -> Result<Self, NyblError> {
7124 nybl::check::check_disabled_builtins(&program.builtin_usage, &limits.disabled_builtins)?;
7125 let memory = nybl::memory::MemoryContext::__new(limits.max_memory);
7126 let mut vm = Vm::new_internal(
7127 Arc::clone(&program.chunk),
7128 host,
7129 limits.clone(),
7130 ModuleRuntime::empty(),
7131 program.compiled_modules.clone(),
7132 nybl::value::ROOT_MODULE_PATH.to_string(),
7133 (*program.root_function_visibility).clone(),
7134 NyblFnOrigin::__instance("vm"),
7135 memory.clone(),
7136 );
7137 vm.check_root_nesting()?;
7138 vm.run_internal()?;
7139 if memory.__exceeded() {
7140 return Err(instance_memory_error());
7141 }
7142 let entries = vm
7143 .abi_declarations
7144 .iter()
7145 .map(|(name, target)| {
7146 let required = nybl::ref_params::required_arity(&target.param_modes);
7147 if target.param_modes.last() == Some(&ParamMode::Rest) {
7148 EntryPoint::__new_variadic(name.clone(), required)
7149 } else {
7150 EntryPoint::__new(name.clone(), required)
7151 }
7152 })
7153 .collect();
7154 Ok(Self {
7155 state: Some(vm.into_state()),
7156 entries,
7157 limits: limits.clone(),
7158 in_operation: Cell::new(false),
7159 memory,
7160 identity: Rc::new(()),
7161 })
7162 }
7163
7164 #[doc(hidden)]
7167 pub fn __root_chunk_ptr(&self) -> *const u8 {
7168 let state = self.state.as_ref().expect("instance state present");
7169 let frame = state.frames.first().expect("root frame present");
7170 Arc::as_ptr(&frame.chunk).cast()
7171 }
7172
7173 #[doc(hidden)]
7175 pub fn __module_chunk_ptr(&self, path: &str) -> Option<*const u8> {
7176 let state = self.state.as_ref().expect("instance state present");
7177 state
7178 .compiled_modules
7179 .as_ref()?
7180 .get(path)
7181 .map(|module| Arc::as_ptr(&module.chunk).cast())
7182 }
7183
7184 pub fn entry_points(&self) -> &[EntryPoint] {
7185 &self.entries
7186 }
7187
7188 pub fn prepare_entry(&self, name: &str) -> Result<PreparedEntry, NyblError> {
7190 let state = self.state.as_ref().expect("instance state present");
7191 let target = state
7192 .abi_declarations
7193 .iter()
7194 .find(|(entry_name, _)| entry_name == name)
7195 .map(|(_, target)| Rc::clone(target))
7196 .ok_or_else(|| error(0, format!("Public entry point `{name}` was not found")))?;
7197 if target.param_modes.contains(&ParamMode::Ref) {
7198 return Err(error(
7199 0,
7200 format!(
7201 "Public entry point `{name}` has `ref` parameters and cannot be called from the host"
7202 ),
7203 ));
7204 }
7205 let arity = nybl::ref_params::required_arity(&target.param_modes);
7206 let variadic = target.param_modes.last() == Some(&ParamMode::Rest);
7207 Ok(PreparedEntry {
7208 name: name.to_string(),
7209 arity,
7210 variadic,
7211 target,
7212 instance_identity: Rc::clone(&self.identity),
7213 })
7214 }
7215
7216 pub fn call_prepared(
7218 &mut self,
7219 entry: &PreparedEntry,
7220 args: &[Value],
7221 host: &mut dyn NyblHost,
7222 ) -> Result<Value, NyblError> {
7223 let _operation = VmOperationGuard::begin(&self.in_operation)?;
7224 self.validate_prepared_entry(entry)?;
7225 validate_prepared_arity(entry, args.len())?;
7226 if self.memory.__exceeded() {
7227 return Err(instance_memory_error());
7228 }
7229 let state = self.state.take().expect("instance state present");
7230 let mut vm = Vm::from_state(state, host, self.limits.clone(), self.memory.clone());
7231 let result = {
7232 for argument in args {
7233 vm.push_value(argument.clone());
7234 }
7235 let execution = vm
7236 .enter_user_fn(Rc::clone(&entry.target), args.len(), 0)
7237 .and_then(|_| vm.run_internal());
7238 let value = execution.and_then(|_| vm.pop_value(0));
7239 vm.restore_instance_baseline();
7240 if self.memory.__exceeded() {
7241 Err(instance_memory_error())
7242 } else {
7243 value
7244 }
7245 };
7246 self.state = Some(vm.into_state());
7247 result
7248 }
7249
7250 pub fn call_batch<A: AsRef<[Value]>>(
7256 &mut self,
7257 entry: &PreparedEntry,
7258 calls: &[A],
7259 host: &mut dyn NyblHost,
7260 ) -> Result<Vec<Value>, NyblError> {
7261 let _operation = VmOperationGuard::begin(&self.in_operation)?;
7262 self.validate_prepared_entry(entry)?;
7263 if self.memory.__exceeded() {
7264 return Err(instance_memory_error());
7265 }
7266 let state = self.state.take().expect("instance state present");
7267 let mut vm = Vm::from_state(state, host, self.limits.clone(), self.memory.clone());
7268 let mut values = Vec::with_capacity(calls.len());
7269 let result = (|| {
7270 for call in calls {
7271 let args = call.as_ref();
7272 validate_prepared_arity(entry, args.len())?;
7273 vm.steps = 0;
7274 for argument in args {
7275 vm.push_value(argument.clone());
7276 }
7277 let execution = vm
7278 .enter_user_fn(Rc::clone(&entry.target), args.len(), 0)
7279 .and_then(|_| vm.run_internal());
7280 let value = execution.and_then(|_| vm.pop_value(0));
7281 vm.restore_instance_baseline();
7282 if self.memory.__exceeded() {
7283 return Err(instance_memory_error());
7284 }
7285 values.push(value?);
7286 }
7287 Ok(values)
7288 })();
7289 self.state = Some(vm.into_state());
7290 result
7291 }
7292
7293 fn validate_prepared_entry(&self, entry: &PreparedEntry) -> Result<(), NyblError> {
7294 if Rc::ptr_eq(&self.identity, &entry.instance_identity) {
7295 Ok(())
7296 } else {
7297 Err(error(
7298 0,
7299 "This prepared entry belongs to a different Nybl engine instance",
7300 ))
7301 }
7302 }
7303
7304 pub fn call(
7305 &mut self,
7306 name: &str,
7307 args: &[Value],
7308 host: &mut dyn NyblHost,
7309 ) -> Result<Value, NyblError> {
7310 let _operation = VmOperationGuard::begin(&self.in_operation)?;
7311 let state = self.state.as_ref().expect("instance state present");
7312 let target = state
7313 .abi_declarations
7314 .iter()
7315 .find(|(entry_name, _)| entry_name == name)
7316 .map(|(_, target)| Rc::clone(target))
7317 .ok_or_else(|| error(0, format!("Public entry point `{name}` was not found")))?;
7318 validate_user_arity(name, &target.param_modes, args.len(), false, 0)?;
7319 nybl::ref_params::validate_call_modes(
7320 name,
7321 &target.param_modes,
7322 &vec![ParamMode::Value; args.len()],
7323 0,
7324 )?;
7325 if self.memory.__exceeded() {
7326 return Err(instance_memory_error());
7327 }
7328 let state = self.state.take().expect("instance state present");
7329 let mut vm = Vm::from_state(state, host, self.limits.clone(), self.memory.clone());
7330 let result = {
7331 for argument in args {
7332 vm.push_value(argument.clone());
7333 }
7334 let execution = vm
7335 .enter_user_fn(target, args.len(), 0)
7336 .and_then(|_| vm.run_internal());
7337 let value = execution.and_then(|_| vm.pop_value(0));
7338 vm.restore_instance_baseline();
7339 if self.memory.__exceeded() {
7340 Err(instance_memory_error())
7341 } else {
7342 value
7343 }
7344 };
7345 self.state = Some(vm.into_state());
7346 result
7347 }
7348
7349 pub fn call_value(
7350 &mut self,
7351 callable: &Value,
7352 args: &[Value],
7353 host: &mut dyn NyblHost,
7354 ) -> Result<Value, NyblError> {
7355 let _operation = VmOperationGuard::begin(&self.in_operation)?;
7356 let function = match callable {
7357 Value::Fn(function) => Rc::clone(function),
7358 other => {
7359 return Err(error(
7360 0,
7361 format!("expected function, got {}", other.type_name()),
7362 ));
7363 }
7364 };
7365 let state = self.state.as_ref().expect("instance state present");
7366 if !function.__is_allowed_by(&state.function_origin, "vm") {
7367 return Err(error(
7368 0,
7369 "This function belongs to a different Nybl engine instance",
7370 ));
7371 }
7372 let display_name = function.self_name.as_deref().unwrap_or("fn");
7373 validate_user_arity(display_name, &function.param_modes, args.len(), false, 0)?;
7374 nybl::ref_params::validate_call_modes(
7375 display_name,
7376 &function.param_modes,
7377 &vec![ParamMode::Value; args.len()],
7378 0,
7379 )?;
7380 if self.memory.__exceeded() {
7381 return Err(instance_memory_error());
7382 }
7383 let state = self.state.take().expect("instance state present");
7384 let mut vm = Vm::from_state(state, host, self.limits.clone(), self.memory.clone());
7385 let result = {
7386 let execution = vm
7387 .call_closure(&function, args.to_vec(), 0)
7388 .and_then(|_| vm.run_internal());
7389 let value = execution.and_then(|_| vm.pop_value(0));
7390 vm.restore_instance_baseline();
7391 if self.memory.__exceeded() {
7392 Err(instance_memory_error())
7393 } else {
7394 value
7395 }
7396 };
7397 self.state = Some(vm.into_state());
7398 result
7399 }
7400}
7401
7402fn validate_prepared_arity(entry: &PreparedEntry, actual: usize) -> Result<(), NyblError> {
7403 if entry.accepts_arity(actual) {
7404 return Ok(());
7405 }
7406 Err(error(
7407 0,
7408 if entry.variadic {
7409 format!(
7410 "`{}` expects at least {} arguments, but got {actual}",
7411 entry.name, entry.arity
7412 )
7413 } else {
7414 format!(
7415 "`{}` expects {} argument{}, but got {actual}",
7416 entry.name,
7417 entry.arity,
7418 if entry.arity == 1 { "" } else { "s" }
7419 )
7420 },
7421 ))
7422}
7423
7424fn instance_memory_error() -> NyblError {
7425 NyblError::fatal("Memory limit exceeded", 0)
7426}
7427
7428fn call_mode_error(
7429 line: u32,
7430 callable: &str,
7431 zero_based_position: usize,
7432 expected: ParamMode,
7433) -> NyblError {
7434 let position = zero_based_position + 1;
7435 match expected {
7436 ParamMode::Ref => error_with_hint(
7437 line,
7438 format!("argument {position} to `{callable}` must be passed with `ref`"),
7439 format!("Write `ref` before argument {position}."),
7440 ),
7441 ParamMode::Value => error_with_hint(
7442 line,
7443 format!("argument {position} to `{callable}` is a value parameter and can't use `ref`"),
7444 format!("Remove `ref` from argument {position}."),
7445 ),
7446 ParamMode::Rest => error_with_hint(
7447 line,
7448 format!("argument {position} to `{callable}` is a value parameter and can't use `ref`"),
7449 format!("Remove `ref` from argument {position}."),
7450 ),
7451 }
7452}
7453
7454fn validate_user_arity(
7455 callable: &str,
7456 expected: &[ParamMode],
7457 actual: usize,
7458 including_self: bool,
7459 line: u32,
7460) -> Result<(), NyblError> {
7461 let has_rest = expected.last() == Some(&ParamMode::Rest);
7462 let minimum = expected.len().saturating_sub(usize::from(has_rest));
7463 if (has_rest && actual >= minimum) || (!has_rest && actual == minimum) {
7464 return Ok(());
7465 }
7466 let self_suffix = if including_self {
7467 " (including `self`)"
7468 } else {
7469 ""
7470 };
7471 let expectation = if has_rest {
7472 format!(
7473 "at least {minimum} argument{}",
7474 if minimum == 1 { "" } else { "s" }
7475 )
7476 } else {
7477 format!("{minimum} argument{}", if minimum == 1 { "" } else { "s" })
7478 };
7479 Err(error(
7480 line,
7481 format!("`{callable}` expects {expectation}{self_suffix}, but got {actual}"),
7482 ))
7483}
7484
7485fn validate_user_call_modes(
7486 callable: &str,
7487 expected: &[ParamMode],
7488 actual: &[ParamMode],
7489 line: u32,
7490) -> Result<(), NyblError> {
7491 validate_user_arity(callable, expected, actual.len(), false, line)?;
7492 let fixed = expected
7493 .len()
7494 .saturating_sub(usize::from(expected.last() == Some(&ParamMode::Rest)));
7495 for (index, mode) in actual.iter().enumerate() {
7496 let expected_mode = expected.get(index).copied().unwrap_or(ParamMode::Value);
7497 let expected_mode = if index >= fixed || expected_mode == ParamMode::Rest {
7498 ParamMode::Value
7499 } else {
7500 expected_mode
7501 };
7502 if *mode != expected_mode {
7503 return Err(call_mode_error(line, callable, index, expected_mode));
7504 }
7505 }
7506 Ok(())
7507}
7508
7509fn invalid_ref_target_error(line: u32, zero_based_position: usize) -> NyblError {
7510 error_with_hint(
7511 line,
7512 format!(
7513 "`ref` argument {} must name a mutable variable",
7514 zero_based_position + 1
7515 ),
7516 "Assign the value to a `let` variable, then pass that variable with `ref`.",
7517 )
7518}
7519
7520fn duplicate_ref_target_error(line: u32) -> NyblError {
7521 error_with_hint(
7522 line,
7523 "the same variable can't be passed to more than one `ref` parameter",
7524 "Use a distinct variable for each `ref` argument.",
7525 )
7526}
7527
7528fn validate_named_builtin_arity(name: &str, count: usize, line: u32) -> Result<(), NyblError> {
7529 let expected = match name {
7530 "rand" | "try_call" | "panic" => Some((1, 1)),
7531 "range" => Some((1, 3)),
7532 "print" => None,
7533 _ => return Ok(()),
7534 };
7535 if let Some((min, max)) = expected
7536 && (count < min || count > max)
7537 {
7538 let expectation = if min == max {
7539 format!("{} argument{}", min, if min == 1 { "" } else { "s" })
7540 } else {
7541 format!("{min} to {max} arguments")
7542 };
7543 return Err(error(
7544 line,
7545 format!("`{name}` expects {expectation}, but got {count}"),
7546 ));
7547 }
7548 Ok(())
7549}
7550
7551fn validate_builtin_method_arity(method: &str, count: usize, line: u32) -> Result<(), NyblError> {
7552 let Some(expected) = methods::builtin_method_arity(method) else {
7553 return Ok(());
7554 };
7555 if count != expected {
7556 return Err(error(
7557 line,
7558 format!(
7559 "`.{method}()` needs {expected} argument{}",
7560 if expected == 1 { "" } else { "s" }
7561 ),
7562 ));
7563 }
7564 Ok(())
7565}
7566
7567struct VmOperationGuard<'a>(&'a Cell<bool>);
7568
7569impl<'a> VmOperationGuard<'a> {
7570 fn begin(flag: &'a Cell<bool>) -> Result<Self, NyblError> {
7571 if flag.replace(true) {
7572 return Err(error(0, "A Nybl instance cannot be re-entered"));
7573 }
7574 Ok(Self(flag))
7575 }
7576}
7577
7578impl Drop for VmOperationGuard<'_> {
7579 fn drop(&mut self) {
7580 self.0.set(false);
7581 }
7582}
7583
7584pub fn execute<H: NyblHost>(
7592 chunk: Chunk,
7593 host: &mut H,
7594 limits: &NyblLimits,
7595) -> Result<(), NyblError> {
7596 crate::validate_chunk(&chunk)?;
7597 let vm = Vm::new(chunk, host, limits.clone());
7598 vm.run()
7599}
7600
7601pub fn run<H: NyblHost>(source: &str, host: &mut H, limits: &NyblLimits) -> Result<(), NyblError> {
7605 let stmts = nybl::parse(source)?;
7606 nybl::check::enforce_disabled_builtins(&stmts, &limits.disabled_builtins)?;
7607 let chunk = crate::compile(&stmts)?;
7608 execute(chunk, host, limits)
7609}
7610
7611#[cfg(test)]
7612mod tests {
7613 use super::*;
7614 use std::cell::RefCell;
7615
7616 struct SilentHost;
7617
7618 impl NyblHost for SilentHost {
7619 fn call(
7620 &mut self,
7621 _name: &str,
7622 _args: &[Value],
7623 _line: u32,
7624 ) -> Option<Result<Value, NyblError>> {
7625 None
7626 }
7627 }
7628
7629 #[test]
7630 fn named_call_uses_host_once_then_exact_self_recursion_bypasses_it() {
7631 struct Host {
7632 calls: usize,
7633 prints: Vec<String>,
7634 }
7635
7636 impl NyblHost for Host {
7637 fn call(
7638 &mut self,
7639 name: &str,
7640 _args: &[Value],
7641 _line: u32,
7642 ) -> Option<Result<Value, NyblError>> {
7643 if name != "f" {
7644 return None;
7645 }
7646 self.calls += 1;
7647 (self.calls > 1).then_some(Ok(Value::Int(99)))
7648 }
7649
7650 fn on_print(&mut self, message: &str) {
7651 self.prints.push(message.to_string());
7652 }
7653 }
7654
7655 let mut host = Host {
7656 calls: 0,
7657 prints: Vec::new(),
7658 };
7659 run(
7660 "fn f(n) { if n == 0 { return 1 } return f(n - 1) }\nprint(f(2))",
7661 &mut host,
7662 &NyblLimits::standard(),
7663 )
7664 .unwrap();
7665 assert_eq!(host.calls, 1);
7666 assert_eq!(host.prints, ["1"]);
7667 }
7668
7669 #[test]
7670 fn method_bare_name_resolves_named_function_not_method_self() {
7671 struct PrintHost(Vec<String>);
7672
7673 impl NyblHost for PrintHost {
7674 fn call(
7675 &mut self,
7676 _name: &str,
7677 _args: &[Value],
7678 _line: u32,
7679 ) -> Option<Result<Value, NyblError>> {
7680 None
7681 }
7682
7683 fn on_print(&mut self, message: &str) {
7684 self.0.push(message.to_string());
7685 }
7686 }
7687
7688 let mut host = PrintHost(Vec::new());
7689 run(
7690 "struct S {}\nfn m() { return 7 }\nfn S.m(self) { return m() }\nlet value = S {}\nprint(value.m())",
7691 &mut host,
7692 &NyblLimits::standard(),
7693 )
7694 .unwrap();
7695 assert_eq!(host.0, ["7"]);
7696 }
7697
7698 #[test]
7699 fn sequential_broken_loops_leave_the_value_stack_balanced() {
7700 let mut source = String::new();
7701 for _ in 0..128 {
7702 source.push_str("for item in [1, 2, 3] { break }\n");
7703 source.push_str("repeat 3 { break }\n");
7704 }
7705 let program = nybl::parse(&source).expect("parse");
7706 let chunk = crate::compile(&program).expect("compile");
7707 let mut host = SilentHost;
7708 let mut vm = Vm::new(chunk, &mut host, NyblLimits::standard());
7709
7710 vm.run_internal().expect("execute");
7711
7712 assert!(
7713 vm.stack.is_empty(),
7714 "clean completion left {} loop sidecars on the value stack",
7715 vm.stack.len()
7716 );
7717 }
7718
7719 #[test]
7720 fn loop_control_leaves_value_and_type_scope_stacks_balanced() {
7721 let source = r#"repeat 2048 {
7722 if true { continue }
7723}
7724for outer in [1, 2] {
7725 repeat 3 {
7726 while true {
7727 if true { break }
7728 }
7729 let label = match outer {
7730 n if n < 0 => "negative",
7731 _ => "positive",
7732 }
7733 if outer == 1 { continue }
7734 break
7735 }
7736}"#;
7737 let program = nybl::parse(source).expect("parse");
7738 let chunk = crate::compile(&program).expect("compile");
7739 let mut host = SilentHost;
7740 let mut vm = Vm::new(chunk, &mut host, NyblLimits::standard());
7741
7742 vm.run_internal().expect("execute");
7743
7744 let frame = vm.frames.last().expect("top frame");
7745 assert_eq!(frame.scopes.len(), frame.scope_base);
7746 assert_eq!(vm.type_bindings.len(), frame.type_scope_base);
7747 assert!(
7748 vm.stack.is_empty(),
7749 "clean completion left {} values or loop sidecars",
7750 vm.stack.len()
7751 );
7752 }
7753
7754 #[test]
7755 fn frame_scope_floors_preserve_base_scopes_and_pair_type_scopes() {
7756 let mut host = SilentHost;
7757 let mut vm = Vm::new(Chunk::new(), &mut host, NyblLimits::standard());
7758
7759 vm.pop_scope();
7761 assert_eq!(vm.frames.last().unwrap().scopes.len(), 1);
7762 assert_eq!(vm.type_bindings.len(), 1);
7763 vm.push_scope();
7764 vm.pop_scope();
7765 assert_eq!(vm.frames.last().unwrap().scopes.len(), 1);
7766 assert_eq!(vm.type_bindings.len(), 1);
7767
7768 vm.push_function_frame(
7772 Arc::new(Chunk::new()),
7773 Vec::new(),
7774 Vec::new(),
7775 0,
7776 None,
7777 FrameWrap::None,
7778 );
7779 vm.pop_scope();
7780 assert_eq!(vm.frames.last().unwrap().scopes.len(), 0);
7781 assert_eq!(vm.type_bindings.len(), 2);
7782 vm.push_scope();
7783 vm.pop_scope();
7784 assert_eq!(vm.frames.last().unwrap().scopes.len(), 0);
7785 assert_eq!(vm.type_bindings.len(), 2);
7786 vm.push_scope();
7787 vm.push_scope();
7788 vm.do_return(Value::None, 0).expect("return");
7789 assert_eq!(vm.frames.len(), 1);
7790 assert_eq!(vm.type_bindings.len(), 1);
7791
7792 let mut captures = BTreeMap::new();
7795 captures.insert(String::from("captured"), Value::Int(10));
7796 vm.push_function_frame(
7797 Arc::new(Chunk::new()),
7798 Vec::new(),
7799 vec![captures],
7800 vm.stack.len(),
7801 None,
7802 FrameWrap::None,
7803 );
7804 vm.push_scope();
7805 vm.pop_scope();
7806 let frame = vm.frames.last().unwrap();
7807 assert_eq!(frame.scopes.len(), 1);
7808 assert!(matches!(
7809 frame.scopes[0].get("captured"),
7810 Some(Value::Int(10))
7811 ));
7812 assert_eq!(vm.type_bindings.len(), 2);
7813
7814 vm.do_return(Value::None, 0).expect("closure return");
7818 vm.push_function_frame(
7819 Arc::new(Chunk::new()),
7820 Vec::new(),
7821 Vec::new(),
7822 vm.stack.len(),
7823 None,
7824 FrameWrap::TryCall { line: 1 },
7825 );
7826 vm.push_scope();
7827 vm.push_function_frame(
7828 Arc::new(Chunk::new()),
7829 Vec::new(),
7830 Vec::new(),
7831 vm.stack.len(),
7832 None,
7833 FrameWrap::None,
7834 );
7835 vm.push_scope();
7836 vm.unwind_to_try_call(error(1, "boom")).expect("unwind");
7837 assert_eq!(vm.frames.len(), 1);
7838 assert_eq!(vm.type_bindings.len(), 1);
7839 }
7840
7841 #[test]
7842 fn named_call_frames_share_one_module_context() {
7843 let mut host = SilentHost;
7844 let mut vm = Vm::new(Chunk::new(), &mut host, NyblLimits::standard());
7845 let root_context = Rc::clone(&vm.root_lexical_context);
7846
7847 vm.push_function_frame(
7848 Arc::new(Chunk::new()),
7849 Vec::new(),
7850 Vec::new(),
7851 0,
7852 Some(nybl::value::ROOT_MODULE_PATH.to_string()),
7853 FrameWrap::None,
7854 );
7855
7856 assert!(Rc::ptr_eq(
7857 &vm.frames.last().unwrap().lexical_context,
7858 &root_context
7859 ));
7860 assert_eq!(vm.type_bindings.len(), 2);
7861 assert_eq!(vm.module_aliases.len(), 2);
7862 assert_eq!(vm.imported_functions.len(), 2);
7863 assert!(vm.type_bindings[1].is_empty());
7864 assert!(vm.module_aliases[1].is_empty());
7865 assert!(vm.imported_functions[1].is_empty());
7866 }
7867
7868 #[test]
7869 fn root_type_publication_reuses_unique_context_storage() {
7870 const DECLARATIONS: usize = 1_024;
7871 let mut host = SilentHost;
7872 let mut vm = Vm::new(Chunk::new(), &mut host, NyblLimits::standard());
7873 let context = Rc::as_ptr(&vm.root_lexical_context);
7874 let bindings = Rc::as_ptr(&vm.root_lexical_context.type_bindings);
7875
7876 for index in 0..DECLARATIONS {
7877 vm.bind_local_type(&format!("Type{index}"));
7878 }
7879
7880 assert_eq!(Rc::as_ptr(&vm.root_lexical_context), context);
7881 assert_eq!(Rc::as_ptr(&vm.root_lexical_context.type_bindings), bindings);
7882 assert_eq!(
7883 vm.root_lexical_context.type_bindings.len(),
7884 DECLARATIONS + 3
7885 );
7886 }
7887
7888 #[test]
7889 fn restored_lexical_snapshot_forks_without_leaking_abandoned_changes() {
7890 let mut host = SilentHost;
7891 let mut vm = Vm::new(Chunk::new(), &mut host, NyblLimits::standard());
7892 vm.publish_root_type_binding("A".to_string(), "root".to_string());
7893 let snapshot = Rc::clone(&vm.root_lexical_context);
7894 vm.publish_root_type_binding("B".to_string(), "leaked".to_string());
7895
7896 vm.root_lexical_context = Rc::clone(&snapshot);
7897 vm.publish_root_type_binding("C".to_string(), "root".to_string());
7898
7899 assert_eq!(
7900 vm.root_lexical_context.type_bindings.get("A"),
7901 Some(&"root".to_string())
7902 );
7903 assert!(!vm.root_lexical_context.type_bindings.contains_key("B"));
7904 assert_eq!(
7905 vm.root_lexical_context.type_bindings.get("C"),
7906 Some(&"root".to_string())
7907 );
7908 }
7909
7910 #[test]
7911 fn repeated_publication_replaces_in_place_without_retaining_history() {
7912 let mut host = SilentHost;
7913 let mut vm = Vm::new(Chunk::new(), &mut host, NyblLimits::standard());
7914 let bindings = Rc::as_ptr(&vm.root_lexical_context.type_bindings);
7915
7916 for index in 0..1_000 {
7917 vm.publish_root_type_binding("Repeated".to_string(), index.to_string());
7918 }
7919
7920 assert_eq!(Rc::as_ptr(&vm.root_lexical_context.type_bindings), bindings);
7921 assert_eq!(vm.root_lexical_context.type_bindings.len(), 4);
7922 assert_eq!(
7923 vm.root_lexical_context.type_bindings.get("Repeated"),
7924 Some(&"999".to_string())
7925 );
7926 }
7927
7928 #[test]
7929 fn capture_snapshot_distinguishes_missing_from_bound_none() {
7930 let program = nybl::parse(
7931 r#"let present = none
7932let read = fn() { return [missing, present] }"#,
7933 )
7934 .expect("parse");
7935 let chunk = crate::compile(&program).expect("compile");
7936 let lambda = chunk.functions[0].clone();
7937 let mut host = SilentHost;
7938 let mut vm = Vm::new(chunk, &mut host, NyblLimits::standard());
7939 vm.define_local("present".to_string(), Value::None);
7940
7941 let captures = vm.snapshot_captures_for(&lambda);
7942
7943 assert_eq!(captures.len(), 1, "missing bindings must not be invented");
7944 assert_eq!(captures[0].0, "present");
7945 assert!(matches!(captures[0].1, Value::None));
7946 }
7947
7948 struct RetainingHost {
7949 retained: Option<Value>,
7950 }
7951
7952 impl NyblHost for RetainingHost {
7953 fn call(
7954 &mut self,
7955 name: &str,
7956 _args: &[Value],
7957 _line: u32,
7958 ) -> Option<Result<Value, NyblError>> {
7959 if name != "retain_large" {
7960 return None;
7961 }
7962 self.retained = Some(Value::new_str("x".repeat(16 * 1024)));
7963 Some(Ok(Value::None))
7964 }
7965 }
7966
7967 #[test]
7968 fn instance_leaves_host_allocations_untracked_and_checks_final_returns() {
7969 let limits = NyblLimits {
7970 max_steps: 100,
7971 max_memory: 32,
7972 ..NyblLimits::standard()
7973 };
7974 let mut host = RetainingHost { retained: None };
7975 let mut instance = NyblInstance::load(
7976 "pub fn host_only() { retain_large() }\npub fn too_large() { return \"abcdefghijklmnopqrstuvwxyz0123456789\" }",
7977 &mut host,
7978 &limits,
7979 )
7980 .unwrap();
7981 instance.call("host_only", &[], &mut host).unwrap();
7982 assert!(host.retained.is_some());
7983 assert_eq!(instance.memory.__used(), 0);
7984 let error = instance.call("too_large", &[], &mut host).unwrap_err();
7985 assert!(error.is_fatal);
7986 assert!(error.message.contains("Memory limit"));
7987 assert_eq!(instance.memory.__used(), 0);
7988 instance.call("host_only", &[], &mut host).unwrap();
7989 }
7990
7991 struct ExternalValueHost {
7992 value: Option<Value>,
7993 }
7994
7995 impl NyblHost for ExternalValueHost {
7996 fn call(
7997 &mut self,
7998 name: &str,
7999 _args: &[Value],
8000 _line: u32,
8001 ) -> Option<Result<Value, NyblError>> {
8002 (name == "take_external").then(|| Ok(self.value.take().unwrap_or(Value::None)))
8003 }
8004 }
8005
8006 #[test]
8007 fn external_values_are_free_until_detach_and_memory_poison_is_fail_fast() {
8008 let external = Value::new_array((0..256).map(Value::Int).collect());
8009 let limits = NyblLimits {
8010 max_steps: 100,
8011 max_memory: 64,
8012 ..NyblLimits::standard()
8013 };
8014 let mut host = ExternalValueHost {
8015 value: Some(external),
8016 };
8017 let mut instance = NyblInstance::load(
8018 "let stored = none\npub fn keep() { stored = take_external() }\npub fn mutate() { stored.push(256) }\npub fn harmless() { return 1 }",
8019 &mut host,
8020 &limits,
8021 )
8022 .unwrap();
8023
8024 instance.call("keep", &[], &mut host).unwrap();
8025 assert_eq!(instance.memory.__used(), 0);
8026 let mutation_error = instance.call("mutate", &[], &mut host).unwrap_err();
8027 assert!(mutation_error.is_fatal);
8028 assert!(instance.memory.__used() > limits.max_memory);
8029 let poisoned = instance.call("harmless", &[], &mut host).unwrap_err();
8030 assert!(poisoned.is_fatal);
8031 assert!(poisoned.message.contains("Memory limit"));
8032 }
8033
8034 #[test]
8035 fn returned_receipts_release_on_last_drop_and_instances_do_not_cross_charge() {
8036 let mut host = SilentHost;
8037 let source = "pub fn make(x) { return [x, x, x, x] }\npub fn harmless() { return none }";
8038 let limits = NyblLimits::standard();
8039 let mut first = NyblInstance::load(source, &mut host, &limits).unwrap();
8040 let mut second = NyblInstance::load(source, &mut host, &limits).unwrap();
8041
8042 let first_value = first.call("make", &[Value::Int(1)], &mut host).unwrap();
8043 let first_bytes = first.memory.__used();
8044 assert!(first_bytes > 0);
8045 assert_eq!(second.memory.__used(), 0);
8046 first.call("harmless", &[], &mut host).unwrap();
8047 assert_eq!(first.memory.__used(), first_bytes);
8048
8049 let first_clone = first_value.clone();
8050 drop(first_value);
8051 assert_eq!(first.memory.__used(), first_bytes);
8052 let second_value = second.call("make", &[Value::Int(2)], &mut host).unwrap();
8053 let second_bytes = second.memory.__used();
8054 assert!(second_bytes > 0);
8055 assert_eq!(first.memory.__used(), first_bytes);
8056 drop(first_clone);
8057 assert_eq!(first.memory.__used(), 0);
8058 assert_eq!(second.memory.__used(), second_bytes);
8059 drop(second_value);
8060 assert_eq!(second.memory.__used(), 0);
8061 }
8062
8063 struct HookAllocatingHost {
8064 retained: RefCell<Vec<Value>>,
8065 }
8066
8067 impl HookAllocatingHost {
8068 fn retain_large(&self) {
8069 self.retained
8070 .borrow_mut()
8071 .push(Value::new_str("x".repeat(16 * 1024)));
8072 }
8073 }
8074
8075 impl NyblHost for HookAllocatingHost {
8076 fn call(
8077 &mut self,
8078 name: &str,
8079 _args: &[Value],
8080 _line: u32,
8081 ) -> Option<Result<Value, NyblError>> {
8082 self.retain_large();
8083 (name == "host_value").then_some(Ok(Value::None))
8084 }
8085
8086 fn on_print(&mut self, _message: &str) {
8087 self.retain_large();
8088 }
8089
8090 fn function_hint(&self) -> &str {
8091 self.retain_large();
8092 "host hint"
8093 }
8094
8095 fn on_tick(&mut self) -> Result<(), NyblError> {
8096 self.retain_large();
8097 Ok(())
8098 }
8099
8100 fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
8101 self.retain_large();
8102 (name == "hook").then(|| Ok(String::new()))
8103 }
8104 }
8105
8106 #[test]
8107 fn every_instance_host_hook_leaves_accounting_unchanged() {
8108 let limits = NyblLimits {
8109 max_steps: 100,
8110 max_memory: 64,
8111 ..NyblLimits::standard()
8112 };
8113 let mut host = HookAllocatingHost {
8114 retained: RefCell::new(Vec::new()),
8115 };
8116 let mut instance = NyblInstance::load(
8117 "use hook\npub fn print_it() { print(\"ok\") }\npub fn host_it() { host_value() }\npub fn hint_it() { missing() }",
8118 &mut host,
8119 &limits,
8120 )
8121 .unwrap();
8122 assert_eq!(instance.memory.__used(), 0);
8123 instance.call("print_it", &[], &mut host).unwrap();
8124 instance.call("host_it", &[], &mut host).unwrap();
8125 let error = instance.call("hint_it", &[], &mut host).unwrap_err();
8126 assert!(!error.is_fatal);
8127 assert!(
8128 error
8129 .friendly_hint
8130 .as_deref()
8131 .is_some_and(|hint| hint.contains("host hint"))
8132 );
8133 assert_eq!(instance.memory.__used(), 0);
8134 assert!(host.retained.borrow().len() >= 8);
8135 }
8136
8137 #[test]
8138 fn same_instance_reentry_rejection_precedes_target_and_arity_checks() {
8139 let mut host = SilentHost;
8140 let mut instance =
8141 NyblInstance::load("pub fn entry() {}", &mut host, &NyblLimits::standard()).unwrap();
8142 instance.in_operation.set(true);
8143 let error = instance
8144 .call("missing", &[Value::None], &mut host)
8145 .unwrap_err();
8146 instance.in_operation.set(false);
8147 assert_eq!(error.line, Some(0));
8148 assert!(error.message.contains("cannot be re-entered"));
8149 }
8150
8151 #[test]
8152 fn batch_reentry_rejection_precedes_prepared_validation() {
8153 let mut host = SilentHost;
8154 let mut instance =
8155 NyblInstance::load("pub fn entry() {}", &mut host, &NyblLimits::standard()).unwrap();
8156 let entry = instance.prepare_entry("entry").unwrap();
8157 instance.in_operation.set(true);
8158 let error = instance
8159 .call_batch(&entry, &[Vec::<Value>::new()], &mut host)
8160 .unwrap_err();
8161 instance.in_operation.set(false);
8162 assert_eq!(error.line, Some(0));
8163 assert!(error.message.contains("cannot be re-entered"));
8164 }
8165
8166 struct MapModuleHost {
8167 modules: BTreeMap<String, String>,
8168 }
8169
8170 impl NyblHost for MapModuleHost {
8171 fn call(
8172 &mut self,
8173 _name: &str,
8174 _args: &[Value],
8175 _line: u32,
8176 ) -> Option<Result<Value, NyblError>> {
8177 None
8178 }
8179
8180 fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
8181 self.modules.get(name).cloned().map(Ok)
8182 }
8183 }
8184
8185 #[test]
8186 fn vm_module_compilation_error_retains_transitive_source_context() {
8187 let root_source = "use outer";
8188 let inner_source = "let okay = 1\nlet broken =";
8189 let mut host = MapModuleHost {
8190 modules: BTreeMap::from([
8191 ("outer".to_string(), "use inner\nlet outer = 1".to_string()),
8192 ("inner".to_string(), inner_source.to_string()),
8193 ]),
8194 };
8195
8196 let error = crate::run(root_source, &mut host, &NyblLimits::standard()).unwrap_err();
8197 let context = error.source_context.as_ref().expect("module context");
8198
8199 assert_eq!(context.module_path, "inner");
8200 assert_eq!(context.source.as_deref(), Some(inner_source));
8201 let rendered = error.render(root_source);
8202 assert!(rendered.contains("in module `inner` at line 2"));
8203 assert!(rendered.contains("let broken ="));
8204 assert!(!rendered.contains("1 | use outer"));
8205 }
8206
8207 #[test]
8208 fn module_compatibility_snapshots_do_not_force_named_cow_detaches() {
8209 let mut host = MapModuleHost {
8210 modules: BTreeMap::from([
8211 (
8212 "leaf".to_string(),
8213 "let items = [1, 2, 3]\nfn pop() { items.pop() }".to_string(),
8214 ),
8215 (
8216 "facade".to_string(),
8217 "use leaf.{items}\nfn pop() { items.pop() }".to_string(),
8218 ),
8219 ]),
8220 };
8221 let mut instance = NyblInstance::load(
8222 "use leaf as leaf\nuse facade as facade\npub fn facade_pop() { facade.pop() }\npub fn direct_pop() { leaf.pop() }",
8223 &mut host,
8224 &NyblLimits::standard(),
8225 )
8226 .unwrap();
8227 let loaded_bytes = instance.memory.__used();
8228 assert!(loaded_bytes > 0);
8229
8230 instance.call("facade_pop", &[], &mut host).unwrap();
8231 assert_eq!(instance.memory.__used(), loaded_bytes);
8232 instance.call("direct_pop", &[], &mut host).unwrap();
8233 assert_eq!(instance.memory.__used(), loaded_bytes);
8234 }
8235
8236 #[test]
8237 fn facade_fanout_reuses_the_origin_compatibility_snapshot() {
8238 const FACADES: usize = 8;
8239 let items = (0..256)
8240 .map(|value| value.to_string())
8241 .collect::<Vec<_>>()
8242 .join(", ");
8243 let mut modules = BTreeMap::from([(
8244 "leaf".to_string(),
8245 format!("let items = [{items}]\nfn size() {{ return items.len() }}"),
8246 )]);
8247 let mut source = String::new();
8248 for index in 0..FACADES {
8249 modules.insert(format!("facade{index}"), "use leaf".to_string());
8250 source.push_str(&format!("use facade{index} as f{index}\n"));
8251 source.push_str(&format!("let size{index} = f{index}.size()\n"));
8252 }
8253 let mut host = MapModuleHost { modules };
8254 let instance = NyblInstance::load(&source, &mut host, &NyblLimits::standard()).unwrap();
8255
8256 let imports = instance.state.as_ref().unwrap().imports.borrow();
8257 let ImportSlot::Loaded(leaf) = imports.get("leaf").unwrap() else {
8258 panic!("leaf should be loaded")
8259 };
8260 let leaf_items = &leaf
8261 .bindings
8262 .iter()
8263 .find(|(name, _)| name == "items")
8264 .unwrap()
8265 .1;
8266 for index in 0..FACADES {
8267 let ImportSlot::Loaded(facade) = imports.get(&format!("facade{index}")).unwrap() else {
8268 panic!("facade should be loaded")
8269 };
8270 let facade_items = &facade
8271 .bindings
8272 .iter()
8273 .find(|(name, _)| name == "items")
8274 .unwrap()
8275 .1;
8276 assert!(leaf_items.__shares_backing_with(facade_items));
8277 }
8278 }
8279
8280 #[test]
8281 fn recursive_module_snapshots_do_not_retain_replaced_instance_receipts() {
8282 let mut host = MapModuleHost {
8283 modules: BTreeMap::from([(
8284 "leaf".to_string(),
8285 "let items = [[\"abcdefghijklmnopqrstuvwxyz0123456789\"]]\nlet captured = \"zyxwvutsrqponmlkjihgfedcba9876543210\"\nlet callback = fn() { return captured }\nfn clear() { items = []; captured = none; callback = none }"
8286 .to_string(),
8287 )]),
8288 };
8289 let mut instance = NyblInstance::load(
8290 "use leaf as leaf\npub fn clear() { leaf.clear() }",
8291 &mut host,
8292 &NyblLimits::standard(),
8293 )
8294 .unwrap();
8295 let loaded_bytes = instance.memory.__used();
8296 assert!(loaded_bytes > 0);
8297
8298 instance.call("clear", &[], &mut host).unwrap();
8299 let cleared_bytes = instance.memory.__used();
8300 assert!(cleared_bytes < loaded_bytes);
8301
8302 let mut empty_host = MapModuleHost {
8303 modules: BTreeMap::from([(
8304 "leaf".to_string(),
8305 "let items = []\nlet captured = none\nlet callback = none\nfn clear() { items = []; captured = none; callback = none }"
8306 .to_string(),
8307 )]),
8308 };
8309 let empty = NyblInstance::load(
8310 "use leaf as leaf\npub fn clear() { leaf.clear() }",
8311 &mut empty_host,
8312 &NyblLimits::standard(),
8313 )
8314 .unwrap();
8315 assert_eq!(cleared_bytes, empty.memory.__used());
8316 }
8317
8318 struct WrappingModuleHost {
8319 modules: BTreeMap<String, String>,
8320 }
8321
8322 impl NyblHost for WrappingModuleHost {
8323 fn call(
8324 &mut self,
8325 name: &str,
8326 args: &[Value],
8327 line: u32,
8328 ) -> Option<Result<Value, NyblError>> {
8329 if name != "wrap" {
8330 return None;
8331 }
8332 Some(
8333 nybl::value::NyblModule::try_new(
8334 "host.wrapper".to_string(),
8335 vec![("child".to_string(), args[0].clone())],
8336 Vec::new(),
8337 line,
8338 )
8339 .map(Value::Module),
8340 )
8341 }
8342
8343 fn resolve_module(&mut self, name: &str) -> Option<Result<String, NyblError>> {
8344 self.modules.get(name).cloned().map(Ok)
8345 }
8346 }
8347
8348 #[test]
8349 fn module_snapshots_externalize_host_module_binding_graphs() {
8350 let root = "use leaf as leaf\npub fn clear() { leaf.clear() }";
8351 let mut host = WrappingModuleHost {
8352 modules: BTreeMap::from([(
8353 "leaf".to_string(),
8354 "let child = [\"abcdefghijklmnopqrstuvwxyz0123456789\"]\nlet wrapped = wrap(child)\nfn clear() { child = none; wrapped = none }"
8355 .to_string(),
8356 )]),
8357 };
8358 let mut instance = NyblInstance::load(root, &mut host, &NyblLimits::standard()).unwrap();
8359 let loaded_bytes = instance.memory.__used();
8360 assert!(loaded_bytes > 0);
8361 instance.call("clear", &[], &mut host).unwrap();
8362 let cleared_bytes = instance.memory.__used();
8363 assert!(cleared_bytes < loaded_bytes);
8364
8365 let mut empty_host = WrappingModuleHost {
8366 modules: BTreeMap::from([(
8367 "leaf".to_string(),
8368 "let child = none\nlet wrapped = none\nfn clear() { child = none; wrapped = none }"
8369 .to_string(),
8370 )]),
8371 };
8372 let empty = NyblInstance::load(root, &mut empty_host, &NyblLimits::standard()).unwrap();
8373 assert_eq!(cleared_bytes, empty.memory.__used());
8374 }
8375}