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
23pub struct RustiaBuilder {
46 profile: Profile,
47 settings: VmSettings,
48 extensions: Vec<RustiaExtension>,
49 live_requested: bool,
50}
51
52#[derive(Clone, Copy, Debug, Eq, PartialEq)]
61pub struct RustiaExecutionProfile {
62 profile: Profile,
63 guest_surface: GuestSurface,
64}
65
66impl RustiaExecutionProfile {
67 pub const DETERMINISTIC_STANDARD: Self =
69 Self::new(Profile::DeterministicSim, GuestSurface::Standard);
70
71 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 pub fn builder(self) -> RustiaBuilder {
97 RustiaBuilder::from_execution_profile(self)
98 }
99
100 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 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 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 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 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 pub fn deterministic() -> Self {
212 RustiaExecutionProfile::DETERMINISTIC_STANDARD.builder()
213 }
214
215 pub fn deterministic_leaf() -> Self {
222 RustiaExecutionProfile::DETERMINISTIC_HARDENED_LEAF.builder()
223 }
224
225 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 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 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 pub fn diagnostic_limits(mut self, limits: crate::DiagnosticLimits) -> Self {
284 self.settings.diagnostic_limits = limits.to_core();
285 self
286 }
287
288 pub fn fuel(mut self, fuel: u64) -> Self {
296 self.settings.initial_fuel = Some(fuel);
297 self
298 }
299
300 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 pub fn memory_limit_bytes(mut self, bytes: usize) -> Self {
315 self.settings.memory_limit_bytes = Some(bytes);
316 self
317 }
318
319 pub fn memory_tracking(mut self, enabled: bool) -> Self {
321 self.settings.enable_memory_tracking = enabled;
322 self
323 }
324
325 pub fn extension(mut self, extension: RustiaExtension) -> Self {
328 self.extensions.push(extension);
329 self
330 }
331
332 #[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 #[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 pub fn without_stdout(mut self) -> Self {
352 self.settings.services.stdout = None;
353 self
354 }
355
356 pub fn module_resolver(mut self, resolver: ServiceModuleResolver) -> Self {
366 self.settings.module_resolver = Some(resolver.into_provider());
367 self
368 }
369
370 pub fn wall_clock(mut self, clock: ServiceClock) -> Self {
374 self.settings.services.wall_clock = Some(clock.into_provider());
375 self
376 }
377
378 pub fn monotonic_clock(mut self, clock: ServiceClock) -> Self {
381 self.settings.services.monotonic_clock = Some(clock.into_provider());
382 self
383 }
384
385 pub fn entropy(mut self, entropy: ServiceEntropy) -> Self {
389 self.settings.services.entropy = Some(entropy.into_provider());
390 self
391 }
392
393 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 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#[derive(Clone, Debug, Eq, PartialEq)]
540pub struct ModuleSource {
541 identity: String,
542 source_name: String,
543 source: Vec<u8>,
544}
545
546impl ModuleSource {
547 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 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#[derive(Clone, Debug)]
621pub struct ServiceModuleResolver {
622 provider: ModuleResolver,
623}
624
625impl ServiceModuleResolver {
626 #[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 #[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 #[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 #[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 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#[non_exhaustive]
759#[derive(Clone, Debug)]
760pub struct ServiceClock {
761 provider: ClockProvider,
762}
763
764impl ServiceClock {
765 #[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 #[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 #[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 #[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 pub fn fixed(t: f64) -> Self {
807 Self {
808 provider: ClockProvider::new(move || t, true),
809 }
810 }
811
812 #[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 #[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 #[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 #[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#[non_exhaustive]
855#[derive(Clone, Debug)]
856pub struct ServiceEntropy {
857 provider: EntropyProvider,
858}
859
860impl ServiceEntropy {
861 #[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 pub fn fixed(seed: u64) -> Self {
887 Self {
888 provider: EntropyProvider::new(move || seed, true),
889 }
890 }
891
892 #[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 #[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 #[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 #[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
970fn 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#[derive(Clone, Debug)]
1026pub struct RustiaExtension {
1027 namespace: Option<String>,
1028 functions: Vec<HostFunctionOp>,
1029}
1030
1031pub const RUSTIA_HOST_FUEL_ABI_VERSION: u32 = 1;
1035
1036pub const RUSTIA_DEFAULT_HOST_FUNCTION_FUEL: u32 = 1;
1038
1039pub const RUSTIA_MIN_HOST_FUNCTION_FUEL: u32 = 1;
1041
1042#[non_exhaustive]
1044#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1045pub struct RustiaHostFuelPolicy {
1046 pub abi_version: u32,
1048 pub default_function_fuel: u32,
1050 pub minimum_function_fuel: u32,
1052}
1053
1054pub 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#[non_exhaustive]
1063#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1064pub struct RustiaHostFunctionInfo<'a> {
1065 pub name: &'a str,
1067 pub fuel_abi_version: u32,
1069 pub fuel_cost: u32,
1071 pub capability: OpCapability,
1073 pub parameter_count: u8,
1075 pub parameter_types: &'a [&'static str],
1077 pub return_types: &'a [&'static str],
1079 pub fallible: bool,
1081}
1082
1083impl RustiaExtension {
1084 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 pub fn global() -> Self {
1095 Self {
1096 namespace: None,
1097 functions: Vec::new(),
1098 }
1099 }
1100
1101 pub fn namespace(&self) -> Option<&str> {
1103 self.namespace.as_deref()
1104 }
1105
1106 pub fn fuel_policy(&self) -> RustiaHostFuelPolicy {
1108 RUSTIA_HOST_FUEL_POLICY
1109 }
1110
1111 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 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 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 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 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 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 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 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 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}