Skip to main content

rustia/
extension_api.rs

1use crate::function::IntoHostFunction;
2use crate::{
3    Error, GuestSurface, HostSchema, OpCapability, Profile, Result, Rustia, Settings, VmError,
4    VmErrorKind,
5};
6use rustia_compiler::{compile_with_options, CompileOptions};
7use rustia_vm::{
8    ClockProvider, EntropyProvider, HostFunctionOp, ModuleResolver, Program, ResolvedModule,
9    StdoutSink, VmSettings,
10};
11#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
12use std::time::{Instant, SystemTime, UNIX_EPOCH};
13#[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "web-live"))]
14use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue};
15
16#[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "web-live"))]
17#[wasm_bindgen]
18extern "C" {
19    #[wasm_bindgen(js_namespace = console, js_name = log)]
20    fn web_console_log(text: &str);
21}
22
23/// Chooses a script environment, resource limits, and host services.
24///
25/// Start with [`Rustia::builder`] for reproducible defaults, or use
26/// [`live`](Self::live) for real clocks, entropy, and `loadstring`.
27/// [`deterministic`](Self::deterministic) rejects nondeterministic input providers
28/// and host capabilities. None of these presets sets a fuel or memory limit.
29///
30/// ```
31/// use rustia::Rustia;
32///
33/// let mut lua = Rustia::builder()
34///     .fuel(100_000)
35///     .memory_limit_bytes(4 * 1024 * 1024)
36///     .build()?;
37/// assert_eq!(lua.load("return 6 * 7").eval::<i64>()?, 42);
38/// # Ok::<(), rustia::Error>(())
39/// ```
40///
41/// Use [`build_for_host`](Self::build_for_host) when callbacks need borrowed
42/// per-invocation state. The more restricted
43/// [`deterministic_leaf`](Self::deterministic_leaf) preset is for stateless
44/// decisions and requires a typed host plus an explicit memory limit.
45pub struct RustiaBuilder {
46    profile: Profile,
47    settings: VmSettings,
48    extensions: Vec<RustiaExtension>,
49    live_requested: bool,
50}
51
52/// Stable, typed description of the core profile and guest surface selected by
53/// a builder.
54///
55/// The descriptor deliberately covers the core [`Profile`] and guest-visible
56/// [`GuestSurface`] together. Its canonical bytes are one component of an
57/// embedder's package or replay identity; settings, budgets, host ABI, and any
58/// permitted services must be bound separately. Unlike a caller-maintained
59/// label, the value can also be read back from the built [`Rustia`] VM.
60#[derive(Clone, Copy, Debug, Eq, PartialEq)]
61pub struct RustiaExecutionProfile {
62    profile: Profile,
63    guest_surface: GuestSurface,
64}
65
66impl RustiaExecutionProfile {
67    /// Ordinary sealed deterministic execution.
68    pub const DETERMINISTIC_STANDARD: Self =
69        Self::new(Profile::DeterministicSim, GuestSurface::Standard);
70
71    /// Stateless authoritative-leaf execution.
72    pub const DETERMINISTIC_HARDENED_LEAF: Self =
73        Self::new(Profile::DeterministicSim, GuestSurface::HardenedLeaf);
74
75    pub(crate) const fn new(profile: Profile, guest_surface: GuestSurface) -> Self {
76        Self {
77            profile,
78            guest_surface,
79        }
80    }
81
82    pub(crate) const fn from_vm(
83        profile: rustia_vm::Profile,
84        guest_surface: rustia_vm::GuestSurface,
85    ) -> Self {
86        Self::new(
87            Profile::from_core(profile),
88            GuestSurface::from_core(guest_surface),
89        )
90    }
91
92    /// Constructs a builder whose core VM semantics exactly match this
93    /// descriptor. Further builder methods may add budgets or services; the
94    /// final descriptor remains readable through
95    /// [`RustiaBuilder::execution_profile`].
96    pub fn builder(self) -> RustiaBuilder {
97        RustiaBuilder::from_execution_profile(self)
98    }
99
100    /// Stable compact code for fixed-width host protocol fields.
101    ///
102    /// Codes name the complete `(Profile, GuestSurface)` pair rather than
103    /// relying on Rust enum discriminants.
104    pub const fn compatibility_id(self) -> u32 {
105        match (self.profile, self.guest_surface) {
106            (Profile::DeterministicSim, GuestSurface::HardenedLeaf) => 1,
107            (Profile::LuauCompat, GuestSurface::Standard) => 2,
108            (Profile::ReproducibleStandard, GuestSurface::Standard) => 3,
109            (Profile::DeterministicSim, GuestSurface::Standard) => 4,
110            (Profile::LuauCompat, GuestSurface::HardenedLeaf) => 5,
111            (Profile::ReproducibleStandard, GuestSurface::HardenedLeaf) => 6,
112            (Profile::Puc51Compat, GuestSurface::Standard) => 7,
113            (Profile::Puc51Compat, GuestSurface::HardenedLeaf) => 8,
114        }
115    }
116
117    /// Canonical versioned bytes for package and replay identity components.
118    ///
119    /// Each field is an explicitly assigned little-endian `u32`: encoding
120    /// version, core-profile tag, then guest-surface tag.
121    pub const fn identity_bytes(self) -> [u8; 12] {
122        let encoding = 1u32.to_le_bytes();
123        let profile = match self.profile {
124            Profile::LuauCompat => 1u32,
125            Profile::ReproducibleStandard => 2,
126            Profile::DeterministicSim => 3,
127            Profile::Puc51Compat => 4,
128        }
129        .to_le_bytes();
130        let surface = match self.guest_surface {
131            GuestSurface::Standard => 1u32,
132            GuestSurface::HardenedLeaf => 2,
133        }
134        .to_le_bytes();
135        [
136            encoding[0],
137            encoding[1],
138            encoding[2],
139            encoding[3],
140            profile[0],
141            profile[1],
142            profile[2],
143            profile[3],
144            surface[0],
145            surface[1],
146            surface[2],
147            surface[3],
148        ]
149    }
150}
151
152impl RustiaBuilder {
153    pub(crate) fn new() -> Self {
154        Self {
155            profile: Profile::ReproducibleStandard,
156            settings: VmSettings::default(),
157            extensions: Vec::new(),
158            live_requested: false,
159        }
160    }
161
162    fn from_execution_profile(execution_profile: RustiaExecutionProfile) -> Self {
163        let mut builder = Self::new();
164        builder.profile = execution_profile.profile;
165        builder.settings.guest_surface = execution_profile.guest_surface.to_core();
166        builder
167    }
168
169    /// Returns the typed core execution semantics currently selected by this
170    /// builder.
171    pub const fn execution_profile(&self) -> RustiaExecutionProfile {
172        RustiaExecutionProfile::new(
173            self.profile,
174            GuestSurface::from_core(self.settings.guest_surface),
175        )
176    }
177
178    /// Returns the effective limits and service declarations selected so far.
179    ///
180    /// Use [`Settings::identity_bytes`] when configuration is part of a replay
181    /// or package identity. Provider data and application code remain separate
182    /// identity inputs.
183    pub fn settings(&self) -> Settings {
184        Settings::from_core(self.profile, &self.settings)
185    }
186
187    #[cfg(test)]
188    pub(crate) const fn vm_settings(&self) -> &VmSettings {
189        &self.settings
190    }
191
192    /// Starts with reproducible inputs and the standard script environment.
193    ///
194    /// This uses [`Profile::ReproducibleStandard`]: clocks use deterministic
195    /// defaults, the random seed is zero, and `loadstring` is disabled. Script
196    /// `print` writes to stdout on native/WASI targets and is silent on browser
197    /// Wasm until a sink is supplied. Real clocks and other nondeterministic
198    /// providers remain available when explicitly configured.
199    /// [`Rustia::builder`] starts with this preset.
200    pub fn standard() -> Self {
201        let builder = Self::new();
202        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
203        let builder = builder.stdout(|text| print!("{text}"));
204        builder
205    }
206
207    /// Starts with [`Profile::DeterministicSim`] and no host services.
208    ///
209    /// Nondeterministic input providers and host capabilities are rejected.
210    /// Replay-stable providers and a `print` sink can still be added explicitly.
211    pub fn deterministic() -> Self {
212        RustiaExecutionProfile::DETERMINISTIC_STANDARD.builder()
213    }
214
215    /// Starts a restricted environment for independent, stateless decisions.
216    ///
217    /// Uses [`GuestSurface::HardenedLeaf`] with [`Profile::DeterministicSim`].
218    /// Set an explicit [`memory_limit_bytes`](Self::memory_limit_bytes) and use
219    /// [`build_for_host`](Self::build_for_host). Execute host-owned decision
220    /// bodies with [`Rustia::compile_entry`] and [`Rustia::invoke_entry_into`].
221    pub fn deterministic_leaf() -> Self {
222        RustiaExecutionProfile::DETERMINISTIC_HARDENED_LEAF.builder()
223    }
224
225    /// Starts with real clocks, a fresh random seed, output, and `loadstring`.
226    ///
227    /// Uses [`Profile::ReproducibleStandard`] with nondeterministic services;
228    /// results are not guaranteed to repeat. `loadstring` lets scripts compile
229    /// additional code at runtime, so choose this preset deliberately for
230    /// untrusted scripts.
231    ///
232    /// Native and WASI targets use their system services. With the default `web-live` feature,
233    /// `wasm32-unknown-unknown` uses the JavaScript host (`console`, `Date`, `performance`, and
234    /// `crypto`). Bare-Wasm builds can disable default features and plug the three input
235    /// providers explicitly; [`build`](Self::build) then verifies that none are missing.
236    pub fn live() -> Self {
237        let builder = Self::standard();
238        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
239        let builder = builder
240            .wall_clock(ServiceClock::system())
241            .monotonic_clock(ServiceClock::monotonic())
242            .entropy(ServiceEntropy::system());
243        #[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "web-live"))]
244        let builder = builder
245            .stdout(web_console_log)
246            .wall_clock(ServiceClock::system())
247            .monotonic_clock(ServiceClock::monotonic())
248            .entropy(ServiceEntropy::system());
249        let mut builder = builder;
250        builder.live_requested = true;
251        builder.settings.loadstring_compiler = Some(stock_loadstring_compiler);
252        builder
253    }
254
255    /// Starts a Lua 5.1 compatibility environment with `loadstring` enabled.
256    ///
257    /// The profile alone reproduces PUC 5.1.5 table layout, number
258    /// formatting, and `table.sort`; this preset adds `loadstring` so PUC-era
259    /// code that compiles chunks at runtime works out of the box. Runtime
260    /// compilation is an extra capability for untrusted scripts; enable it
261    /// where Lua 5.1 source compatibility requires it. Host services otherwise
262    /// use the defaults from [`standard`](Self::standard).
263    pub fn puc51_compat() -> Self {
264        let mut builder = Self::standard().profile(Profile::Puc51Compat);
265        builder.settings.loadstring_compiler = Some(stock_loadstring_compiler);
266        builder
267    }
268
269    /// Selects the core compatibility and capability policy.
270    /// Existing settings and services are retained and checked when building.
271    pub fn profile(mut self, profile: Profile) -> Self {
272        self.profile = profile;
273        self
274    }
275
276    #[cfg(test)]
277    pub(crate) fn raw_settings(mut self, settings: VmSettings) -> Self {
278        self.settings = settings;
279        self
280    }
281
282    /// Configures host-side reports independently of guest heap and fuel limits.
283    pub fn diagnostic_limits(mut self, limits: crate::DiagnosticLimits) -> Self {
284        self.settings.diagnostic_limits = limits.to_core();
285        self
286    }
287
288    /// Limits the instruction work allowed during execution.
289    ///
290    /// Direct `Rustia<()>` entry points use this as their top-level budget. A
291    /// typed invocation uses the lower of this ceiling and its explicit
292    /// [`crate::InvocationLimits`] fuel, across every guest call in that
293    /// invocation. Fuel measures deterministic work rather than elapsed time;
294    /// script `pcall` cannot catch fuel exhaustion. The default is unlimited.
295    pub fn fuel(mut self, fuel: u64) -> Self {
296        self.settings.initial_fuel = Some(fuel);
297        self
298    }
299
300    /// Limits nested script calls. The default and maximum are 512.
301    ///
302    /// Larger values are clamped to the engine maximum. Exhaustion returns a
303    /// distinct error that script `pcall` cannot catch.
304    pub fn recursion_limit(mut self, limit: usize) -> Self {
305        self.settings.recursion_limit = limit.min(rustia_vm::MAX_RECURSION_LIMIT);
306        self
307    }
308
309    /// Limits the VM's accounted live memory. The default is unlimited.
310    ///
311    /// Accounting is deterministic across native and Wasm targets. It does not
312    /// bound total process memory, allocator capacity, or memory captured by
313    /// Rust callbacks. Allocations can fail once the limit is reached.
314    pub fn memory_limit_bytes(mut self, bytes: usize) -> Self {
315        self.settings.memory_limit_bytes = Some(bytes);
316        self
317    }
318
319    /// Enables tracking of live and reserved memory peaks at instruction boundaries.
320    pub fn memory_tracking(mut self, enabled: bool) -> Self {
321        self.settings.enable_memory_tracking = enabled;
322        self
323    }
324
325    /// Adds a group of Rust callbacks to install when the VM is built.
326    /// For a typed host, use [`crate::HostModule`] after building instead.
327    pub fn extension(mut self, extension: RustiaExtension) -> Self {
328        self.extensions.push(extension);
329        self
330    }
331
332    /// Chooses where script `print` output goes.
333    ///
334    /// Each call sends one string, with arguments joined by tabs and a trailing
335    /// newline. The closure cannot return an error. Output sinks are allowed in
336    /// every ordinary profile, including [`Profile::DeterministicSim`].
337    #[cfg(not(feature = "transferable"))]
338    pub fn stdout(mut self, sink: impl FnMut(&str) + 'static) -> Self {
339        self.settings.services.stdout = Some(StdoutSink::new(sink));
340        self
341    }
342
343    /// Chooses a transferable sink for script `print` output.
344    #[cfg(feature = "transferable")]
345    pub fn stdout(mut self, sink: impl FnMut(&str) + Send + 'static) -> Self {
346        self.settings.services.stdout = Some(StdoutSink::new(sink));
347        self
348    }
349
350    /// Discards script `print` output by removing the configured sink.
351    pub fn without_stdout(mut self) -> Self {
352        self.settings.services.stdout = None;
353        self
354    }
355
356    /// Installs the host-owned resolver behind script-visible `require`.
357    ///
358    /// The resolver chooses a canonical module identity and source for every
359    /// request. Successful results are cached by identity within the calling
360    /// function's module cohort: the cache shared by a module and its dependencies.
361    /// Each installation starts a fresh cohort; retained functions keep using
362    /// their original cohort. A module can therefore execute again in a new
363    /// installation before [`Rustia::reset_decision`] clears all guest state.
364    /// See [`ServiceModuleResolver`] for loading, failure, and suspension rules.
365    pub fn module_resolver(mut self, resolver: ServiceModuleResolver) -> Self {
366        self.settings.module_resolver = Some(resolver.into_provider());
367        self
368    }
369
370    /// Supplies the clock for no-argument `os.time()` and the default `os.date`
371    /// timestamp. A nondeterministic provider is rejected at [`build`](Self::build) on
372    /// `DeterministicSim`.
373    pub fn wall_clock(mut self, clock: ServiceClock) -> Self {
374        self.settings.services.wall_clock = Some(clock.into_provider());
375        self
376    }
377
378    /// Supplies the clock for `os.clock()`, overriding the VM's built-in
379    /// logical clock. Same `DeterministicSim` validation as [`wall_clock`](Self::wall_clock).
380    pub fn monotonic_clock(mut self, clock: ServiceClock) -> Self {
381        self.settings.services.monotonic_clock = Some(clock.into_provider());
382        self
383    }
384
385    /// Supplies the seed read once at VM construction for the initial `math.random`
386    /// sequence. Calling `math.randomseed` later still replaces that state. A nondeterministic
387    /// provider is rejected by [`deterministic`](Self::deterministic).
388    pub fn entropy(mut self, entropy: ServiceEntropy) -> Self {
389        self.settings.services.entropy = Some(entropy.into_provider());
390        self
391    }
392
393    /// Validates the configuration and builds a VM without a typed host context.
394    ///
395    /// Returns an error for incompatible services, invalid extensions, or a
396    /// hardened-leaf preset, which requires [`build_for_host`](Self::build_for_host).
397    pub fn build(self) -> Result<Rustia> {
398        self.validate()?;
399        if self.settings.guest_surface.is_hardened_leaf() {
400            return Err(Error::from(VmError::new(
401                VmErrorKind::HardenedLeafViolation {
402                    feature: "context-free facade",
403                },
404            )));
405        }
406        let mut rustia = Rustia::from_settings(self.profile, self.settings);
407        for extension in self.extensions {
408            rustia.install_extension(extension)?;
409        }
410        Ok(rustia)
411    }
412
413    /// Builds a typed VM while preserving this builder's profile, settings,
414    /// and host services.
415    ///
416    /// Legacy [`RustiaExtension`] values deliberately do not cross into the
417    /// typed capability surface; install a [`crate::HostModule<H>`] after
418    /// building instead.
419    pub fn build_for_host<H>(self) -> Result<Rustia<H>>
420    where
421        H: HostSchema,
422    {
423        self.validate()?;
424        if !self.extensions.is_empty() {
425            return Err(Error::embed(
426                "legacy RustiaExtension values cannot be installed into a typed VM; \
427                 use HostModule instead"
428                    .to_owned(),
429            ));
430        }
431        Ok(Rustia::<H>::from_settings(self.profile, self.settings))
432    }
433
434    fn validate(&self) -> Result<()> {
435        if self.live_requested
436            && (self.settings.services.wall_clock.is_none()
437                || self.settings.services.monotonic_clock.is_none()
438                || self.settings.services.entropy.is_none())
439        {
440            return Err(Error::from(VmError::new(VmErrorKind::Unsupported {
441                feature: "live() without a complete platform adapter (plug \
442                          .wall_clock/.monotonic_clock/.entropy providers, or enable the \
443                          default web-live feature for browser/JavaScript wasm hosts)",
444            })));
445        }
446        if self.profile.is_deterministic_sim() {
447            for (feature, clock) in [
448                (
449                    "non-deterministic wall clock provider",
450                    &self.settings.services.wall_clock,
451                ),
452                (
453                    "non-deterministic monotonic clock provider",
454                    &self.settings.services.monotonic_clock,
455                ),
456            ] {
457                if clock.as_ref().is_some_and(|clock| !clock.deterministic()) {
458                    return Err(Error::from(VmError::new(VmErrorKind::CapabilityRemoved {
459                        feature,
460                        operation: None,
461                        profile: self.profile,
462                    })));
463                }
464            }
465            if self
466                .settings
467                .services
468                .entropy
469                .as_ref()
470                .is_some_and(|entropy| !entropy.deterministic())
471            {
472                return Err(Error::from(VmError::new(VmErrorKind::CapabilityRemoved {
473                    feature: "non-deterministic entropy provider",
474                    operation: None,
475                    profile: self.profile,
476                })));
477            }
478            if self
479                .settings
480                .module_resolver
481                .as_ref()
482                .is_some_and(|resolver| !resolver.deterministic())
483            {
484                return Err(Error::from(VmError::new(VmErrorKind::CapabilityRemoved {
485                    feature: "non-deterministic module resolver",
486                    operation: Some("require".to_owned()),
487                    profile: self.profile,
488                })));
489            }
490        }
491        if self.settings.guest_surface.is_hardened_leaf() {
492            if !self.profile.is_deterministic_sim() {
493                return Err(Error::from(VmError::new(
494                    VmErrorKind::HardenedLeafViolation {
495                        feature: "non-DeterministicSim profile",
496                    },
497                )));
498            }
499            if self.settings.memory_limit_bytes.is_none() {
500                return Err(Error::from(VmError::new(
501                    VmErrorKind::HardenedLeafViolation {
502                        feature: "missing logical-live memory limit",
503                    },
504                )));
505            }
506            if self.settings.services.stdout.is_some()
507                || self.settings.services.wall_clock.is_some()
508                || self.settings.services.monotonic_clock.is_some()
509                || self.settings.services.entropy.is_some()
510            {
511                return Err(Error::from(VmError::new(
512                    VmErrorKind::HardenedLeafViolation {
513                        feature: "host output, clock, or entropy services",
514                    },
515                )));
516            }
517            if self.settings.loadstring_compiler.is_some()
518                || self.settings.module_resolver.is_some()
519                || self.settings.enable_conformance_coverage
520                || self.settings.enable_opcode_census
521                || self.settings.enable_conformance_top_level_yield
522                || self.settings.enable_conformance_int64_userdata
523                || self.settings.enable_conformance_native_userdata
524                || self.settings.enable_conformance_native_type_checks
525                || self.settings.enable_conformance_pcall_helpers
526            {
527                return Err(Error::from(VmError::new(
528                    VmErrorKind::HardenedLeafViolation {
529                        feature: "dynamic-code or conformance-only facilities",
530                    },
531                )));
532            }
533        }
534        Ok(())
535    }
536}
537
538/// Host-supplied source returned by a [`ServiceModuleResolver`].
539#[derive(Clone, Debug, Eq, PartialEq)]
540pub struct ModuleSource {
541    identity: String,
542    source_name: String,
543    source: Vec<u8>,
544}
545
546impl ModuleSource {
547    /// Creates a module whose diagnostic and resolver-referrer source name
548    /// matches its canonical cache identity.
549    pub fn new(identity: impl Into<String>, source: impl AsRef<[u8]>) -> Self {
550        let identity = identity.into();
551        Self {
552            source_name: identity.clone(),
553            identity,
554            source: source.as_ref().to_vec(),
555        }
556    }
557
558    /// Creates a module with a separate canonical cache identity and source
559    /// name. The source name is used for diagnostics and nested `require`
560    /// resolver referrers.
561    pub fn with_source_name(
562        identity: impl Into<String>,
563        source_name: impl Into<String>,
564        source: impl AsRef<[u8]>,
565    ) -> Self {
566        Self {
567            identity: identity.into(),
568            source_name: source_name.into(),
569            source: source.as_ref().to_vec(),
570        }
571    }
572
573    pub fn identity(&self) -> &str {
574        &self.identity
575    }
576
577    pub fn source_name(&self) -> &str {
578        &self.source_name
579    }
580
581    pub fn source(&self) -> &[u8] {
582        &self.source
583    }
584}
585
586/// Host-owned resolver for script-visible `require`.
587///
588/// Resolution is performed on demand with the requested path and the current
589/// chunk's source name. The host must return a stable canonical identity when
590/// it labels the resolver deterministic. Because the canonical identity is a
591/// resolver result, the resolver is called before every cache lookup; a host
592/// with expensive I/O or compilation should keep its own source cache. A cache
593/// hit skips module execution and discards the newly resolved program.
594///
595/// A module may return zero or one value. Successful results are cached within
596/// the calling function's module cohort; failures can be retried. Module code
597/// running in a guest coroutine may yield and resume before its result is
598/// cached. Recursive loading is an error, as is requesting an identity that a
599/// different coroutine is still loading.
600///
601/// Ordinary `require` keeps completed writes when a module fails. An enclosing
602/// [`Chunk::install`](crate::Chunk::install) still rolls back guest state when
603/// the installation fails; external Rust effects remain outside that rollback.
604///
605/// ```
606/// use rustia::{ModuleSource, RustiaBuilder, ServiceModuleResolver};
607///
608/// # fn main() -> rustia::Result<()> {
609/// let resolver = ServiceModuleResolver::from_fn(|name, _referrer| {
610///     match name {
611///         "answer" => Ok(ModuleSource::new("answer", "return 42")),
612///         _ => Err(rustia::Error::embed(format!("unknown module {name}"))),
613///     }
614/// });
615/// let mut lua = RustiaBuilder::deterministic().module_resolver(resolver).build()?;
616/// assert_eq!(lua.load("return require('answer')").eval::<i64>()?, 42);
617/// # Ok(())
618/// # }
619/// ```
620#[derive(Clone, Debug)]
621pub struct ServiceModuleResolver {
622    provider: ModuleResolver,
623}
624
625impl ServiceModuleResolver {
626    /// Host-supplied replay-stable resolver. The determinism assertion is
627    /// trusted, not verified.
628    #[cfg(not(feature = "transferable"))]
629    pub fn from_fn(
630        resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + 'static,
631    ) -> Self {
632        Self::from_fn_with_determinism(resolver, true)
633    }
634
635    /// Host-supplied replay-stable transferable resolver.
636    #[cfg(feature = "transferable")]
637    pub fn from_fn(
638        resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + Send + 'static,
639    ) -> Self {
640        Self::from_fn_with_determinism(resolver, true)
641    }
642
643    /// Host-supplied live resolver explicitly labeled nondeterministic.
644    #[cfg(not(feature = "transferable"))]
645    pub fn from_nondeterministic_fn(
646        resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + 'static,
647    ) -> Self {
648        Self::from_fn_with_determinism(resolver, false)
649    }
650
651    /// Host-supplied live transferable resolver.
652    #[cfg(feature = "transferable")]
653    pub fn from_nondeterministic_fn(
654        resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + Send + 'static,
655    ) -> Self {
656        Self::from_fn_with_determinism(resolver, false)
657    }
658
659    #[cfg(not(feature = "transferable"))]
660    fn from_fn_with_determinism(
661        mut resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + 'static,
662        deterministic: bool,
663    ) -> Self {
664        let provider = ModuleResolver::new_with_profile(
665            move |requested, referrer, profile| {
666                let module =
667                    resolver(requested, referrer).map_err(crate::value::embed_to_vm_error)?;
668                compile_module_source(module, profile)
669            },
670            deterministic,
671        );
672        Self { provider }
673    }
674
675    #[cfg(feature = "transferable")]
676    fn from_fn_with_determinism(
677        mut resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + Send + 'static,
678        deterministic: bool,
679    ) -> Self {
680        let provider = ModuleResolver::new_with_profile(
681            move |requested, referrer, profile| {
682                let module =
683                    resolver(requested, referrer).map_err(crate::value::embed_to_vm_error)?;
684                compile_module_source(module, profile)
685            },
686            deterministic,
687        );
688        Self { provider }
689    }
690
691    fn into_provider(self) -> ModuleResolver {
692        self.provider
693    }
694}
695
696fn compile_module_source(
697    module: ModuleSource,
698    profile: rustia_vm::Profile,
699) -> rustia_vm::Result<ResolvedModule> {
700    if module.identity.is_empty() {
701        return Err(crate::value::embed_to_vm_error(Error::embed(
702            "module identity must not be empty",
703        )));
704    }
705    let chunk = rustia_parser::parse_source_bytes(&module.source).map_err(|error| {
706        module_compile_error(
707            Error::from_engine(error),
708            &module.source_name,
709            &module.source,
710        )
711    })?;
712    let options = CompileOptions {
713        puc51_constructor_order: profile == rustia_vm::Profile::Puc51Compat,
714        ..CompileOptions::default()
715    }
716    .with_source_bytes(module.source_name.clone(), &module.source);
717    let mut program = compile_with_options(&chunk, options).map_err(|error| {
718        module_compile_error(
719            Error::from_engine(error),
720            &module.source_name,
721            &module.source,
722        )
723    })?;
724    program.diagnostic_source = rustia_vm::diagnostic::SourceSnapshot::copy_with_limit(
725        &module.source,
726        crate::DiagnosticLimits::default().source_bytes,
727    );
728    Ok(ResolvedModule::new(module.identity, program))
729}
730
731fn module_compile_error(error: Error, name: &str, source: &[u8]) -> rustia_vm::Error {
732    let message = format!("{name}:1: {error}");
733    let mut error = error.with_source(name, source, crate::DiagnosticLimits::default());
734    // Keep a single snapshot lease at the outer diagnostic, not an unbudgeted
735    // copy hidden in the typed cause chain.
736    let mut diagnostic = error.diagnostic.take();
737    let mut error = crate::value::embed_to_vm_error(error);
738    if let Some(diagnostic) = &mut diagnostic {
739        std::sync::Arc::make_mut(diagnostic).host_cause = error
740            .diagnostic
741            .as_ref()
742            .and_then(|diagnostic| diagnostic.host_cause.clone());
743    }
744    error.diagnostic = diagnostic.map(|diagnostic| std::sync::Arc::new(diagnostic.to_core()));
745    if let rustia_vm::ErrorKind::RuntimeError { message: raw } = &mut error.kind {
746        *raw = message;
747    }
748    error
749}
750
751/// A clock supplied to [`RustiaBuilder::wall_clock`] or
752/// [`RustiaBuilder::monotonic_clock`].
753///
754/// Every constructor declares whether readings repeat during replay.
755/// [`Profile::DeterministicSim`] rejects nondeterministic providers when built;
756/// other profiles accept either kind.
757/// Cloning shares the underlying provider.
758#[non_exhaustive]
759#[derive(Clone, Debug)]
760pub struct ServiceClock {
761    provider: ClockProvider,
762}
763
764impl ServiceClock {
765    /// Real system time in seconds since the Unix epoch, anchored to a monotonic instant at
766    /// construction so readings never move backwards. Labeled nondeterministic: usable on
767    /// `ReproducibleStandard`/`LuauCompat`, rejected on `DeterministicSim`.
768    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
769    pub fn system() -> Self {
770        let epoch = SystemTime::now()
771            .duration_since(UNIX_EPOCH)
772            .map_or(0.0, |duration| duration.as_secs_f64());
773        let start = Instant::now();
774        Self {
775            provider: ClockProvider::new(move || epoch + start.elapsed().as_secs_f64(), false),
776        }
777    }
778
779    /// Monotonic elapsed time in seconds. Labeled nondeterministic.
780    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
781    pub fn monotonic() -> Self {
782        let start = Instant::now();
783        Self {
784            provider: ClockProvider::new(move || start.elapsed().as_secs_f64(), false),
785        }
786    }
787
788    /// JavaScript host wall time in seconds since the Unix epoch. Labeled nondeterministic.
789    #[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "web-live"))]
790    pub fn system() -> Self {
791        Self {
792            provider: ClockProvider::new(|| js_sys::Date::now() / 1_000.0, false),
793        }
794    }
795
796    /// JavaScript host monotonic time in seconds. Uses `performance.now()` when available and
797    /// falls back to `Date.now()`. Labeled nondeterministic.
798    #[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "web-live"))]
799    pub fn monotonic() -> Self {
800        Self {
801            provider: ClockProvider::new(web_monotonic_seconds, false),
802        }
803    }
804
805    /// Constant clock that always reads `t` seconds. Labeled deterministic.
806    pub fn fixed(t: f64) -> Self {
807        Self {
808            provider: ClockProvider::new(move || t, true),
809        }
810    }
811
812    /// Supplies a clock whose readings the host promises to reproduce during replay.
813    /// Rustia trusts this declaration and does not verify it.
814    #[cfg(not(feature = "transferable"))]
815    pub fn from_fn(clock: impl FnMut() -> f64 + 'static) -> Self {
816        Self {
817            provider: ClockProvider::new(clock, true),
818        }
819    }
820
821    /// Supplies a transferable clock whose readings the host promises to reproduce.
822    #[cfg(feature = "transferable")]
823    pub fn from_fn(clock: impl FnMut() -> f64 + Send + 'static) -> Self {
824        Self {
825            provider: ClockProvider::new(clock, true),
826        }
827    }
828
829    /// Host-supplied live clock. The provider is explicitly labeled nondeterministic.
830    #[cfg(not(feature = "transferable"))]
831    pub fn from_nondeterministic_fn(clock: impl FnMut() -> f64 + 'static) -> Self {
832        Self {
833            provider: ClockProvider::new(clock, false),
834        }
835    }
836
837    /// Host-supplied transferable live clock.
838    #[cfg(feature = "transferable")]
839    pub fn from_nondeterministic_fn(clock: impl FnMut() -> f64 + Send + 'static) -> Self {
840        Self {
841            provider: ClockProvider::new(clock, false),
842        }
843    }
844
845    pub(crate) fn into_provider(self) -> ClockProvider {
846        self.provider
847    }
848}
849
850/// Host entropy used to select the VM's initial `math.random` sequence.
851///
852/// Like [`ServiceClock`], every constructor carries a determinism label. The provider is read
853/// once while the VM is built; `math.randomseed` remains available afterward.
854#[non_exhaustive]
855#[derive(Clone, Debug)]
856pub struct ServiceEntropy {
857    provider: EntropyProvider,
858}
859
860impl ServiceEntropy {
861    /// System entropy where Rustia has a default platform adapter. If the platform random
862    /// source is temporarily unavailable, a time-varying fallback still preserves `live()`'s
863    /// no-replay-guarantee contract. Labeled nondeterministic.
864    #[cfg(any(
865        not(all(target_arch = "wasm32", target_os = "unknown")),
866        all(target_arch = "wasm32", target_os = "unknown", feature = "web-live")
867    ))]
868    pub fn system() -> Self {
869        let fallback_counter = std::sync::atomic::AtomicU64::new(0);
870        Self {
871            provider: EntropyProvider::new(
872                move || {
873                    system_entropy().unwrap_or_else(|| {
874                        let counter = fallback_counter
875                            .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
876                            .wrapping_add(1);
877                        fallback_entropy(counter)
878                    })
879                },
880                false,
881            ),
882        }
883    }
884
885    /// Constant replay-stable seed.
886    pub fn fixed(seed: u64) -> Self {
887        Self {
888            provider: EntropyProvider::new(move || seed, true),
889        }
890    }
891
892    /// Host-supplied replay-stable seed provider.
893    #[cfg(not(feature = "transferable"))]
894    pub fn from_fn(entropy: impl FnMut() -> u64 + 'static) -> Self {
895        Self {
896            provider: EntropyProvider::new(entropy, true),
897        }
898    }
899
900    /// Host-supplied transferable replay-stable seed provider.
901    #[cfg(feature = "transferable")]
902    pub fn from_fn(entropy: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
903        Self {
904            provider: EntropyProvider::new(entropy, true),
905        }
906    }
907
908    /// Host-supplied live seed provider, explicitly labeled nondeterministic.
909    #[cfg(not(feature = "transferable"))]
910    pub fn from_nondeterministic_fn(entropy: impl FnMut() -> u64 + 'static) -> Self {
911        Self {
912            provider: EntropyProvider::new(entropy, false),
913        }
914    }
915
916    /// Host-supplied transferable live seed provider.
917    #[cfg(feature = "transferable")]
918    pub fn from_nondeterministic_fn(entropy: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
919        Self {
920            provider: EntropyProvider::new(entropy, false),
921        }
922    }
923
924    pub(crate) fn into_provider(self) -> EntropyProvider {
925        self.provider
926    }
927}
928
929#[cfg(feature = "web-live")]
930fn system_entropy() -> Option<u64> {
931    getrandom::u64().ok()
932}
933
934#[cfg(all(
935    not(feature = "web-live"),
936    not(all(target_arch = "wasm32", target_os = "unknown"))
937))]
938fn system_entropy() -> Option<u64> {
939    None
940}
941
942#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
943fn fallback_entropy(counter: u64) -> u64 {
944    let wall = SystemTime::now()
945        .duration_since(UNIX_EPOCH)
946        .map_or(0_u128, |duration| duration.as_nanos());
947    (wall as u64) ^ ((wall >> 64) as u64) ^ counter.rotate_left(29)
948}
949
950#[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "web-live"))]
951fn fallback_entropy(counter: u64) -> u64 {
952    js_sys::Date::now().to_bits() ^ web_monotonic_seconds().to_bits() ^ counter.rotate_left(29)
953}
954
955#[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "web-live"))]
956fn web_monotonic_seconds() -> f64 {
957    let global = js_sys::global();
958    let performance = js_sys::Reflect::get(&global, &JsValue::from_str("performance"));
959    let Ok(performance) = performance else {
960        return js_sys::Date::now() / 1_000.0;
961    };
962    let now = js_sys::Reflect::get(&performance, &JsValue::from_str("now"))
963        .ok()
964        .and_then(|value| value.dyn_into::<js_sys::Function>().ok())
965        .and_then(|now| now.call0(&performance).ok())
966        .and_then(|value| value.as_f64());
967    now.unwrap_or_else(js_sys::Date::now) / 1_000.0
968}
969
970/// Stock `loadstring` compiler installed by [`RustiaBuilder::live`]: the same parse + compile
971/// pipeline the facade uses for ahead-of-time source (public builtin environment), with
972/// Luau's `[string "..."]` chunk naming when the script passes no chunk name.
973///
974/// The VM supplies its active [`Profile`] so profile-dependent codegen stays
975/// consistent between ahead-of-time and runtime-compiled chunks (currently the
976/// PUC 5.1 table-constructor write order under `Profile::Puc51Compat`).
977fn stock_loadstring_compiler(
978    source: &[u8],
979    source_name: Option<&[u8]>,
980    profile: rustia_vm::Profile,
981) -> std::result::Result<Program, String> {
982    let source_name = source_name.map_or_else(
983        || loadstring_chunk_name(source),
984        |name| String::from_utf8_lossy(name).into_owned(),
985    );
986    let chunk = rustia_parser::parse_source_bytes(source)
987        .map_err(|error| format!("{source_name}:1: {error}"))?;
988    let options = CompileOptions {
989        puc51_constructor_order: profile == rustia_vm::Profile::Puc51Compat,
990        ..CompileOptions::default()
991    }
992    .with_source_bytes(source_name.clone(), source);
993    let mut program = compile_with_options(&chunk, options)
994        .map_err(|error| format!("{source_name}:1: {error}"))?;
995    program.diagnostic_source = rustia_vm::diagnostic::SourceSnapshot::copy_with_limit(
996        source,
997        crate::DiagnosticLimits::default().source_bytes,
998    );
999    Ok(program)
1000}
1001
1002fn loadstring_chunk_name(source: &[u8]) -> String {
1003    let mut preview = String::new();
1004    for byte in source.iter().copied().take(60) {
1005        match byte {
1006            b'\\' => preview.push_str("\\\\"),
1007            b'"' => preview.push_str("\\\""),
1008            b'\n' => break,
1009            0x20..=0x7e => preview.push(byte as char),
1010            _ => preview.push('?'),
1011        }
1012    }
1013    if source.len() > 60 {
1014        preview.push_str("...");
1015    }
1016    format!("[string \"{preview}\"]")
1017}
1018
1019/// A group of Rust callbacks installed together, optionally in a named table.
1020///
1021/// Add it with [`RustiaBuilder::extension`] or [`Rustia::install_extension`].
1022/// For callbacks that borrow per-invocation host state, use [`crate::HostModule`]
1023/// instead. The capability labels here describe captured host state; they do
1024/// not provide a borrowed host context or make captured mutations transactional.
1025#[derive(Clone, Debug)]
1026pub struct RustiaExtension {
1027    namespace: Option<String>,
1028    functions: Vec<HostFunctionOp>,
1029}
1030
1031/// Version for the public host-function fuel-cost schedule.
1032///
1033/// Bump this when a rustia release changes the meaning of declared host fuel costs.
1034pub const RUSTIA_HOST_FUEL_ABI_VERSION: u32 = 1;
1035
1036/// Default fuel cost assigned by capability-specific host-function helpers.
1037pub const RUSTIA_DEFAULT_HOST_FUNCTION_FUEL: u32 = 1;
1038
1039/// Minimum accepted host-function fuel cost.
1040pub const RUSTIA_MIN_HOST_FUNCTION_FUEL: u32 = 1;
1041
1042/// Public host-function fuel policy for extension metadata.
1043#[non_exhaustive]
1044#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1045pub struct RustiaHostFuelPolicy {
1046    /// ABI version for interpreting host-function fuel costs.
1047    pub abi_version: u32,
1048    /// Fuel cost used when the helper API does not take an explicit cost.
1049    pub default_function_fuel: u32,
1050    /// Smallest fuel cost accepted by VM registration.
1051    pub minimum_function_fuel: u32,
1052}
1053
1054/// The fuel policy used by extension registration helpers.
1055pub const RUSTIA_HOST_FUEL_POLICY: RustiaHostFuelPolicy = RustiaHostFuelPolicy {
1056    abi_version: RUSTIA_HOST_FUEL_ABI_VERSION,
1057    default_function_fuel: RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1058    minimum_function_fuel: RUSTIA_MIN_HOST_FUNCTION_FUEL,
1059};
1060
1061/// Public pre-install metadata for a registered host function.
1062#[non_exhaustive]
1063#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1064pub struct RustiaHostFunctionInfo<'a> {
1065    /// The binding name inside the extension's namespace, or a global name.
1066    pub name: &'a str,
1067    /// ABI version used to interpret `fuel_cost`.
1068    pub fuel_abi_version: u32,
1069    /// Fuel charged per call.
1070    pub fuel_cost: u32,
1071    /// The callback's declared access to host state and effects.
1072    pub capability: OpCapability,
1073    /// The number of typed Rust parameters.
1074    pub parameter_count: u8,
1075    /// Rust type names for the callback parameters.
1076    pub parameter_types: &'a [&'static str],
1077    /// Rust type names for the callback results.
1078    pub return_types: &'a [&'static str],
1079    /// Whether the callback returns a Rustia `Result`.
1080    pub fallible: bool,
1081}
1082
1083impl RustiaExtension {
1084    /// Creates callbacks to install under a named table. An empty name selects globals.
1085    pub fn new(namespace: impl Into<String>) -> Self {
1086        let namespace = namespace.into();
1087        Self {
1088            namespace: (!namespace.is_empty()).then_some(namespace),
1089            functions: Vec::new(),
1090        }
1091    }
1092
1093    /// Creates callbacks to install directly as globals.
1094    pub fn global() -> Self {
1095        Self {
1096            namespace: None,
1097            functions: Vec::new(),
1098        }
1099    }
1100
1101    /// Returns the table name, or `None` for global callbacks.
1102    pub fn namespace(&self) -> Option<&str> {
1103        self.namespace.as_deref()
1104    }
1105
1106    /// Returns the fuel policy used by these registration helpers.
1107    pub fn fuel_policy(&self) -> RustiaHostFuelPolicy {
1108        RUSTIA_HOST_FUEL_POLICY
1109    }
1110
1111    /// Describes the callbacks before installation.
1112    pub fn functions(&self) -> impl Iterator<Item = RustiaHostFunctionInfo<'_>> + '_ {
1113        self.functions
1114            .iter()
1115            .map(|function| RustiaHostFunctionInfo {
1116                name: &function.name,
1117                fuel_abi_version: RUSTIA_HOST_FUEL_ABI_VERSION,
1118                fuel_cost: function.fuel_cost,
1119                capability: OpCapability::from_core(function.capability),
1120                parameter_count: function.parameter_count,
1121                parameter_types: &function.parameter_types,
1122                return_types: &function.return_types,
1123                fallible: function.fallible,
1124            })
1125    }
1126
1127    /// Adds a callback declared free of external mutable state, at the default fuel cost.
1128    pub fn fn_pure<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1129    where
1130        Func: IntoHostFunction<Args, Return>,
1131    {
1132        self.fn_with(
1133            name,
1134            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1135            OpCapability::Pure,
1136            function,
1137        )
1138    }
1139
1140    /// Adds a callback declared to read deterministic input, at the default fuel cost.
1141    pub fn fn_input<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1142    where
1143        Func: IntoHostFunction<Args, Return>,
1144    {
1145        self.fn_with(
1146            name,
1147            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1148            OpCapability::ReadsDeterministicInput,
1149            function,
1150        )
1151    }
1152
1153    /// Adds a callback declared to read slot state, at the default fuel cost.
1154    pub fn fn_slot_read<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1155    where
1156        Func: IntoHostFunction<Args, Return>,
1157    {
1158        self.fn_with(
1159            name,
1160            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1161            OpCapability::ReadsSlotState,
1162            function,
1163        )
1164    }
1165
1166    /// Adds a callback declared to write slot effects, at the default fuel cost.
1167    pub fn fn_slot_write<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1168    where
1169        Func: IntoHostFunction<Args, Return>,
1170    {
1171        self.fn_with(
1172            name,
1173            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1174            OpCapability::WritesSlotEffect,
1175            function,
1176        )
1177    }
1178
1179    /// Adds a callback declared to emit deterministic effects, at the default fuel cost.
1180    pub fn fn_effect<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1181    where
1182        Func: IntoHostFunction<Args, Return>,
1183    {
1184        self.fn_with(
1185            name,
1186            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1187            OpCapability::EmitsDeterministicEffect,
1188            function,
1189        )
1190    }
1191
1192    /// Adds a callback that reads external mutable state. Deterministic profiles reject it.
1193    pub fn fn_external_state<Func, Args, Return>(
1194        self,
1195        name: impl Into<String>,
1196        function: Func,
1197    ) -> Self
1198    where
1199        Func: IntoHostFunction<Args, Return>,
1200    {
1201        self.fn_with(
1202            name,
1203            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1204            OpCapability::ReadsExternalMutableState,
1205            function,
1206        )
1207    }
1208
1209    /// Adds a nondeterministic callback. Deterministic profiles reject it.
1210    pub fn fn_nondeterministic<Func, Args, Return>(
1211        self,
1212        name: impl Into<String>,
1213        function: Func,
1214    ) -> Self
1215    where
1216        Func: IntoHostFunction<Args, Return>,
1217    {
1218        self.fn_with(
1219            name,
1220            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1221            OpCapability::NondeterministicEffect,
1222            function,
1223        )
1224    }
1225
1226    /// Adds a callback with an explicit capability and nonzero fuel cost.
1227    /// Invalid costs and disallowed capabilities are rejected during installation.
1228    pub fn fn_with<Func, Args, Return>(
1229        mut self,
1230        name: impl Into<String>,
1231        fuel_cost: u32,
1232        capability: OpCapability,
1233        function: Func,
1234    ) -> Self
1235    where
1236        Func: IntoHostFunction<Args, Return>,
1237    {
1238        self.functions.push(
1239            crate::HostFunction::<()>::with_capability(capability, function)
1240                .fuel_cost(fuel_cost)
1241                .into_op(name.into()),
1242        );
1243        self
1244    }
1245
1246    pub(crate) fn install(self, rustia: &mut Rustia) -> Result<()> {
1247        let Some(namespace) = self.namespace else {
1248            return rustia
1249                .vm_mut()
1250                .install_host_functions(self.functions)
1251                .map_err(Error::from_engine);
1252        };
1253
1254        rustia
1255            .vm_mut()
1256            .install_host_module(namespace, self.functions)
1257            .map_err(Error::from_engine)
1258    }
1259}