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(
14 target_arch = "wasm32",
15 target_os = "unknown",
16 feature = "platform-adapters"
17))]
18use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue};
19
20#[cfg(all(
21 target_arch = "wasm32",
22 target_os = "unknown",
23 feature = "platform-adapters"
24))]
25#[wasm_bindgen]
26extern "C" {
27 #[wasm_bindgen(js_namespace = console, js_name = log)]
28 fn web_console_log(text: &str);
29}
30
31pub struct RustiaBuilder {
54 profile: Profile,
55 settings: VmSettings,
56 extensions: Vec<RustiaExtension>,
57 live_requested: bool,
58}
59
60#[derive(Clone, Copy, Debug, Eq, PartialEq)]
69pub struct RustiaExecutionProfile {
70 profile: Profile,
71 guest_surface: GuestSurface,
72}
73
74impl RustiaExecutionProfile {
75 pub const DETERMINISTIC_STANDARD: Self =
77 Self::new(Profile::DeterministicSim, GuestSurface::Standard);
78
79 pub const DETERMINISTIC_HARDENED_LEAF: Self =
81 Self::new(Profile::DeterministicSim, GuestSurface::HardenedLeaf);
82
83 pub(crate) const fn new(profile: Profile, guest_surface: GuestSurface) -> Self {
84 Self {
85 profile,
86 guest_surface,
87 }
88 }
89
90 pub(crate) const fn from_vm(
91 profile: rustia_vm::Profile,
92 guest_surface: rustia_vm::GuestSurface,
93 ) -> Self {
94 Self::new(
95 Profile::from_core(profile),
96 GuestSurface::from_core(guest_surface),
97 )
98 }
99
100 pub fn builder(self) -> RustiaBuilder {
105 RustiaBuilder::from_execution_profile(self)
106 }
107
108 pub const fn compatibility_id(self) -> u32 {
113 match (self.profile, self.guest_surface) {
114 (Profile::DeterministicSim, GuestSurface::HardenedLeaf) => 1,
115 (Profile::LuauCompat, GuestSurface::Standard) => 2,
116 (Profile::ReproducibleStandard, GuestSurface::Standard) => 3,
117 (Profile::DeterministicSim, GuestSurface::Standard) => 4,
118 (Profile::LuauCompat, GuestSurface::HardenedLeaf) => 5,
119 (Profile::ReproducibleStandard, GuestSurface::HardenedLeaf) => 6,
120 (Profile::Puc51Compat, GuestSurface::Standard) => 7,
121 (Profile::Puc51Compat, GuestSurface::HardenedLeaf) => 8,
122 }
123 }
124
125 pub const fn identity_bytes(self) -> [u8; 12] {
130 let encoding = 1u32.to_le_bytes();
131 let profile = match self.profile {
132 Profile::LuauCompat => 1u32,
133 Profile::ReproducibleStandard => 2,
134 Profile::DeterministicSim => 3,
135 Profile::Puc51Compat => 4,
136 }
137 .to_le_bytes();
138 let surface = match self.guest_surface {
139 GuestSurface::Standard => 1u32,
140 GuestSurface::HardenedLeaf => 2,
141 }
142 .to_le_bytes();
143 [
144 encoding[0],
145 encoding[1],
146 encoding[2],
147 encoding[3],
148 profile[0],
149 profile[1],
150 profile[2],
151 profile[3],
152 surface[0],
153 surface[1],
154 surface[2],
155 surface[3],
156 ]
157 }
158}
159
160impl RustiaBuilder {
161 pub(crate) fn new() -> Self {
162 Self {
163 profile: Profile::ReproducibleStandard,
164 settings: VmSettings::default(),
165 extensions: Vec::new(),
166 live_requested: false,
167 }
168 }
169
170 fn from_execution_profile(execution_profile: RustiaExecutionProfile) -> Self {
171 let mut builder = Self::new();
172 builder.profile = execution_profile.profile;
173 builder.settings.guest_surface = execution_profile.guest_surface.to_core();
174 builder
175 }
176
177 pub const fn execution_profile(&self) -> RustiaExecutionProfile {
180 RustiaExecutionProfile::new(
181 self.profile,
182 GuestSurface::from_core(self.settings.guest_surface),
183 )
184 }
185
186 pub fn settings(&self) -> Settings {
192 Settings::from_core(self.profile, &self.settings)
193 }
194
195 #[cfg(test)]
196 pub(crate) const fn vm_settings(&self) -> &VmSettings {
197 &self.settings
198 }
199
200 pub fn standard() -> Self {
209 let builder = Self::new();
210 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
211 let builder = builder.stdout(|text| print!("{text}"));
212 builder
213 }
214
215 pub fn deterministic() -> Self {
220 RustiaExecutionProfile::DETERMINISTIC_STANDARD.builder()
221 }
222
223 pub fn deterministic_leaf() -> Self {
230 RustiaExecutionProfile::DETERMINISTIC_HARDENED_LEAF.builder()
231 }
232
233 pub fn live() -> Self {
246 let builder = Self::standard();
247 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
248 let builder = builder
249 .wall_clock(ServiceClock::system())
250 .monotonic_clock(ServiceClock::monotonic())
251 .entropy(ServiceEntropy::system());
252 #[cfg(all(
253 target_arch = "wasm32",
254 target_os = "unknown",
255 feature = "platform-adapters"
256 ))]
257 let builder = builder
258 .stdout(web_console_log)
259 .wall_clock(ServiceClock::system())
260 .monotonic_clock(ServiceClock::monotonic())
261 .entropy(ServiceEntropy::system());
262 let mut builder = builder;
263 builder.live_requested = true;
264 builder.settings.loadstring_compiler = Some(stock_loadstring_compiler);
265 builder
266 }
267
268 pub fn puc51_compat() -> Self {
277 let mut builder = Self::standard().profile(Profile::Puc51Compat);
278 builder.settings.loadstring_compiler = Some(stock_loadstring_compiler);
279 builder
280 }
281
282 pub fn profile(mut self, profile: Profile) -> Self {
285 self.profile = profile;
286 self
287 }
288
289 #[cfg(test)]
290 pub(crate) fn raw_settings(mut self, settings: VmSettings) -> Self {
291 self.settings = settings;
292 self
293 }
294
295 pub fn diagnostic_limits(mut self, limits: crate::DiagnosticLimits) -> Self {
297 self.settings.diagnostic_limits = limits.to_core();
298 self
299 }
300
301 pub fn fuel(mut self, fuel: u64) -> Self {
309 self.settings.initial_fuel = Some(fuel);
310 self
311 }
312
313 pub fn recursion_limit(mut self, limit: usize) -> Self {
318 self.settings.recursion_limit = limit.min(rustia_vm::MAX_RECURSION_LIMIT);
319 self
320 }
321
322 pub fn memory_limit_bytes(mut self, bytes: usize) -> Self {
329 self.settings.memory_limit_bytes = Some(bytes);
330 self
331 }
332
333 pub fn memory_tracking(mut self, enabled: bool) -> Self {
335 self.settings.enable_memory_tracking = enabled;
336 self
337 }
338
339 pub fn extension(mut self, extension: RustiaExtension) -> Self {
342 self.extensions.push(extension);
343 self
344 }
345
346 #[cfg(not(feature = "send"))]
352 pub fn stdout(mut self, sink: impl FnMut(&str) + 'static) -> Self {
353 self.settings.services.stdout = Some(StdoutSink::new(sink));
354 self
355 }
356
357 #[cfg(feature = "send")]
359 pub fn stdout(mut self, sink: impl FnMut(&str) + Send + 'static) -> Self {
360 self.settings.services.stdout = Some(StdoutSink::new(sink));
361 self
362 }
363
364 pub fn without_stdout(mut self) -> Self {
366 self.settings.services.stdout = None;
367 self
368 }
369
370 pub fn module_resolver(mut self, resolver: ServiceModuleResolver) -> Self {
380 self.settings.module_resolver = Some(resolver.into_provider());
381 self
382 }
383
384 pub fn wall_clock(mut self, clock: ServiceClock) -> Self {
388 self.settings.services.wall_clock = Some(clock.into_provider());
389 self
390 }
391
392 pub fn monotonic_clock(mut self, clock: ServiceClock) -> Self {
395 self.settings.services.monotonic_clock = Some(clock.into_provider());
396 self
397 }
398
399 pub fn entropy(mut self, entropy: ServiceEntropy) -> Self {
403 self.settings.services.entropy = Some(entropy.into_provider());
404 self
405 }
406
407 pub fn build(self) -> Result<Rustia> {
412 self.validate()?;
413 if self.settings.guest_surface.is_hardened_leaf() {
414 return Err(Error::from(VmError::new(
415 VmErrorKind::HardenedLeafViolation {
416 feature: "context-free facade",
417 },
418 )));
419 }
420 let mut rustia = Rustia::from_settings(self.profile, self.settings);
421 for extension in self.extensions {
422 rustia.install_extension(extension)?;
423 }
424 Ok(rustia)
425 }
426
427 pub fn build_for_host<H>(self) -> Result<Rustia<H>>
434 where
435 H: HostSchema,
436 {
437 self.validate()?;
438 if !self.extensions.is_empty() {
439 return Err(Error::embed(
440 "legacy RustiaExtension values cannot be installed into a typed VM; \
441 use HostModule instead"
442 .to_owned(),
443 ));
444 }
445 Ok(Rustia::<H>::from_settings(self.profile, self.settings))
446 }
447
448 fn validate(&self) -> Result<()> {
449 if self.live_requested
450 && (self.settings.services.wall_clock.is_none()
451 || self.settings.services.monotonic_clock.is_none()
452 || self.settings.services.entropy.is_none())
453 {
454 return Err(Error::from(VmError::new(VmErrorKind::Unsupported {
455 feature: "live() without a complete platform adapter (plug \
456 .wall_clock/.monotonic_clock/.entropy providers, or enable the \
457 default platform-adapters feature for browser/JavaScript wasm hosts)",
458 })));
459 }
460 if self.profile.is_deterministic_sim() {
461 for (feature, clock) in [
462 (
463 "non-deterministic wall clock provider",
464 &self.settings.services.wall_clock,
465 ),
466 (
467 "non-deterministic monotonic clock provider",
468 &self.settings.services.monotonic_clock,
469 ),
470 ] {
471 if clock.as_ref().is_some_and(|clock| !clock.deterministic()) {
472 return Err(Error::from(VmError::new(VmErrorKind::CapabilityRemoved {
473 feature,
474 operation: None,
475 profile: self.profile,
476 })));
477 }
478 }
479 if self
480 .settings
481 .services
482 .entropy
483 .as_ref()
484 .is_some_and(|entropy| !entropy.deterministic())
485 {
486 return Err(Error::from(VmError::new(VmErrorKind::CapabilityRemoved {
487 feature: "non-deterministic entropy provider",
488 operation: None,
489 profile: self.profile,
490 })));
491 }
492 if self
493 .settings
494 .module_resolver
495 .as_ref()
496 .is_some_and(|resolver| !resolver.deterministic())
497 {
498 return Err(Error::from(VmError::new(VmErrorKind::CapabilityRemoved {
499 feature: "non-deterministic module resolver",
500 operation: Some("require".to_owned()),
501 profile: self.profile,
502 })));
503 }
504 }
505 if self.settings.guest_surface.is_hardened_leaf() {
506 if !self.profile.is_deterministic_sim() {
507 return Err(Error::from(VmError::new(
508 VmErrorKind::HardenedLeafViolation {
509 feature: "non-DeterministicSim profile",
510 },
511 )));
512 }
513 if self.settings.memory_limit_bytes.is_none() {
514 return Err(Error::from(VmError::new(
515 VmErrorKind::HardenedLeafViolation {
516 feature: "missing logical-live memory limit",
517 },
518 )));
519 }
520 if self.settings.services.stdout.is_some()
521 || self.settings.services.wall_clock.is_some()
522 || self.settings.services.monotonic_clock.is_some()
523 || self.settings.services.entropy.is_some()
524 {
525 return Err(Error::from(VmError::new(
526 VmErrorKind::HardenedLeafViolation {
527 feature: "host output, clock, or entropy services",
528 },
529 )));
530 }
531 if self.settings.loadstring_compiler.is_some()
532 || self.settings.module_resolver.is_some()
533 || self.settings.enable_conformance_coverage
534 || self.settings.enable_opcode_census
535 || self.settings.enable_conformance_top_level_yield
536 || self.settings.enable_conformance_int64_userdata
537 || self.settings.enable_conformance_native_userdata
538 || self.settings.enable_conformance_native_type_checks
539 || self.settings.enable_conformance_pcall_helpers
540 {
541 return Err(Error::from(VmError::new(
542 VmErrorKind::HardenedLeafViolation {
543 feature: "dynamic-code or conformance-only facilities",
544 },
545 )));
546 }
547 }
548 Ok(())
549 }
550}
551
552#[derive(Clone, Debug, Eq, PartialEq)]
554pub struct ModuleSource {
555 identity: String,
556 source_name: String,
557 source: Vec<u8>,
558}
559
560impl ModuleSource {
561 pub fn new(identity: impl Into<String>, source: impl AsRef<[u8]>) -> Self {
564 let identity = identity.into();
565 Self {
566 source_name: identity.clone(),
567 identity,
568 source: source.as_ref().to_vec(),
569 }
570 }
571
572 pub fn with_source_name(
576 identity: impl Into<String>,
577 source_name: impl Into<String>,
578 source: impl AsRef<[u8]>,
579 ) -> Self {
580 Self {
581 identity: identity.into(),
582 source_name: source_name.into(),
583 source: source.as_ref().to_vec(),
584 }
585 }
586
587 pub fn identity(&self) -> &str {
588 &self.identity
589 }
590
591 pub fn source_name(&self) -> &str {
592 &self.source_name
593 }
594
595 pub fn source(&self) -> &[u8] {
596 &self.source
597 }
598}
599
600#[derive(Clone, Debug)]
635pub struct ServiceModuleResolver {
636 provider: ModuleResolver,
637}
638
639impl ServiceModuleResolver {
640 #[cfg(not(feature = "send"))]
643 pub fn from_fn(
644 resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + 'static,
645 ) -> Self {
646 Self::from_fn_with_determinism(resolver, true)
647 }
648
649 #[cfg(feature = "send")]
651 pub fn from_fn(
652 resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + Send + 'static,
653 ) -> Self {
654 Self::from_fn_with_determinism(resolver, true)
655 }
656
657 #[cfg(not(feature = "send"))]
659 pub fn from_nondeterministic_fn(
660 resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + 'static,
661 ) -> Self {
662 Self::from_fn_with_determinism(resolver, false)
663 }
664
665 #[cfg(feature = "send")]
667 pub fn from_nondeterministic_fn(
668 resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + Send + 'static,
669 ) -> Self {
670 Self::from_fn_with_determinism(resolver, false)
671 }
672
673 #[cfg(not(feature = "send"))]
674 fn from_fn_with_determinism(
675 mut resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + 'static,
676 deterministic: bool,
677 ) -> Self {
678 let provider = ModuleResolver::new_with_profile(
679 move |requested, referrer, profile| {
680 let module =
681 resolver(requested, referrer).map_err(crate::value::embed_to_vm_error)?;
682 compile_module_source(module, profile)
683 },
684 deterministic,
685 );
686 Self { provider }
687 }
688
689 #[cfg(feature = "send")]
690 fn from_fn_with_determinism(
691 mut resolver: impl FnMut(&str, Option<&str>) -> Result<ModuleSource> + Send + 'static,
692 deterministic: bool,
693 ) -> Self {
694 let provider = ModuleResolver::new_with_profile(
695 move |requested, referrer, profile| {
696 let module =
697 resolver(requested, referrer).map_err(crate::value::embed_to_vm_error)?;
698 compile_module_source(module, profile)
699 },
700 deterministic,
701 );
702 Self { provider }
703 }
704
705 fn into_provider(self) -> ModuleResolver {
706 self.provider
707 }
708}
709
710fn compile_module_source(
711 module: ModuleSource,
712 profile: rustia_vm::Profile,
713) -> rustia_vm::Result<ResolvedModule> {
714 if module.identity.is_empty() {
715 return Err(crate::value::embed_to_vm_error(Error::embed(
716 "module identity must not be empty",
717 )));
718 }
719 let chunk = rustia_parser::parse_source_bytes(&module.source).map_err(|error| {
720 module_compile_error(
721 Error::from_engine(error),
722 &module.source_name,
723 &module.source,
724 )
725 })?;
726 let options = CompileOptions {
727 puc51_constructor_order: profile == rustia_vm::Profile::Puc51Compat,
728 ..CompileOptions::default()
729 }
730 .with_source_bytes(module.source_name.clone(), &module.source);
731 let mut program = compile_with_options(&chunk, options).map_err(|error| {
732 module_compile_error(
733 Error::from_engine(error),
734 &module.source_name,
735 &module.source,
736 )
737 })?;
738 program.diagnostic_source = rustia_vm::diagnostic::SourceSnapshot::copy_with_limit(
739 &module.source,
740 crate::DiagnosticLimits::default().source_bytes,
741 );
742 Ok(ResolvedModule::new(module.identity, program))
743}
744
745fn module_compile_error(error: Error, name: &str, source: &[u8]) -> rustia_vm::Error {
746 let message = format!("{name}:1: {error}");
747 let mut error = error.with_source(name, source, crate::DiagnosticLimits::default());
748 let mut diagnostic = error.diagnostic.take();
751 let mut error = crate::value::embed_to_vm_error(error);
752 if let Some(diagnostic) = &mut diagnostic {
753 std::sync::Arc::make_mut(diagnostic).host_cause = error
754 .diagnostic
755 .as_ref()
756 .and_then(|diagnostic| diagnostic.host_cause.clone());
757 }
758 error.diagnostic = diagnostic.map(|diagnostic| std::sync::Arc::new(diagnostic.to_core()));
759 if let rustia_vm::ErrorKind::RuntimeError { message: raw } = &mut error.kind {
760 *raw = message;
761 }
762 error
763}
764
765#[non_exhaustive]
773#[derive(Clone, Debug)]
774pub struct ServiceClock {
775 provider: ClockProvider,
776}
777
778impl ServiceClock {
779 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
783 pub fn system() -> Self {
784 let epoch = SystemTime::now()
785 .duration_since(UNIX_EPOCH)
786 .map_or(0.0, |duration| duration.as_secs_f64());
787 let start = Instant::now();
788 Self {
789 provider: ClockProvider::new(move || epoch + start.elapsed().as_secs_f64(), false),
790 }
791 }
792
793 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
795 pub fn monotonic() -> Self {
796 let start = Instant::now();
797 Self {
798 provider: ClockProvider::new(move || start.elapsed().as_secs_f64(), false),
799 }
800 }
801
802 #[cfg(all(
804 target_arch = "wasm32",
805 target_os = "unknown",
806 feature = "platform-adapters"
807 ))]
808 pub fn system() -> Self {
809 Self {
810 provider: ClockProvider::new(|| js_sys::Date::now() / 1_000.0, false),
811 }
812 }
813
814 #[cfg(all(
817 target_arch = "wasm32",
818 target_os = "unknown",
819 feature = "platform-adapters"
820 ))]
821 pub fn monotonic() -> Self {
822 Self {
823 provider: ClockProvider::new(web_monotonic_seconds, false),
824 }
825 }
826
827 pub fn fixed(t: f64) -> Self {
829 Self {
830 provider: ClockProvider::new(move || t, true),
831 }
832 }
833
834 #[cfg(not(feature = "send"))]
837 pub fn from_fn(clock: impl FnMut() -> f64 + 'static) -> Self {
838 Self {
839 provider: ClockProvider::new(clock, true),
840 }
841 }
842
843 #[cfg(feature = "send")]
845 pub fn from_fn(clock: impl FnMut() -> f64 + Send + 'static) -> Self {
846 Self {
847 provider: ClockProvider::new(clock, true),
848 }
849 }
850
851 #[cfg(not(feature = "send"))]
853 pub fn from_nondeterministic_fn(clock: impl FnMut() -> f64 + 'static) -> Self {
854 Self {
855 provider: ClockProvider::new(clock, false),
856 }
857 }
858
859 #[cfg(feature = "send")]
861 pub fn from_nondeterministic_fn(clock: impl FnMut() -> f64 + Send + 'static) -> Self {
862 Self {
863 provider: ClockProvider::new(clock, false),
864 }
865 }
866
867 pub(crate) fn into_provider(self) -> ClockProvider {
868 self.provider
869 }
870}
871
872#[non_exhaustive]
877#[derive(Clone, Debug)]
878pub struct ServiceEntropy {
879 provider: EntropyProvider,
880}
881
882impl ServiceEntropy {
883 #[cfg(any(
887 not(all(target_arch = "wasm32", target_os = "unknown")),
888 all(
889 target_arch = "wasm32",
890 target_os = "unknown",
891 feature = "platform-adapters"
892 )
893 ))]
894 pub fn system() -> Self {
895 let fallback_counter = std::sync::atomic::AtomicU64::new(0);
896 Self {
897 provider: EntropyProvider::new(
898 move || {
899 system_entropy().unwrap_or_else(|| {
900 let counter = fallback_counter
901 .fetch_add(1, std::sync::atomic::Ordering::Relaxed)
902 .wrapping_add(1);
903 fallback_entropy(counter)
904 })
905 },
906 false,
907 ),
908 }
909 }
910
911 pub fn fixed(seed: u64) -> Self {
913 Self {
914 provider: EntropyProvider::new(move || seed, true),
915 }
916 }
917
918 #[cfg(not(feature = "send"))]
920 pub fn from_fn(entropy: impl FnMut() -> u64 + 'static) -> Self {
921 Self {
922 provider: EntropyProvider::new(entropy, true),
923 }
924 }
925
926 #[cfg(feature = "send")]
928 pub fn from_fn(entropy: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
929 Self {
930 provider: EntropyProvider::new(entropy, true),
931 }
932 }
933
934 #[cfg(not(feature = "send"))]
936 pub fn from_nondeterministic_fn(entropy: impl FnMut() -> u64 + 'static) -> Self {
937 Self {
938 provider: EntropyProvider::new(entropy, false),
939 }
940 }
941
942 #[cfg(feature = "send")]
944 pub fn from_nondeterministic_fn(entropy: impl Fn() -> u64 + Send + Sync + 'static) -> Self {
945 Self {
946 provider: EntropyProvider::new(entropy, false),
947 }
948 }
949
950 pub(crate) fn into_provider(self) -> EntropyProvider {
951 self.provider
952 }
953}
954
955#[cfg(feature = "platform-adapters")]
956fn system_entropy() -> Option<u64> {
957 getrandom::u64().ok()
958}
959
960#[cfg(all(
961 not(feature = "platform-adapters"),
962 not(all(target_arch = "wasm32", target_os = "unknown"))
963))]
964fn system_entropy() -> Option<u64> {
965 None
966}
967
968#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
969fn fallback_entropy(counter: u64) -> u64 {
970 let wall = SystemTime::now()
971 .duration_since(UNIX_EPOCH)
972 .map_or(0_u128, |duration| duration.as_nanos());
973 (wall as u64) ^ ((wall >> 64) as u64) ^ counter.rotate_left(29)
974}
975
976#[cfg(all(
977 target_arch = "wasm32",
978 target_os = "unknown",
979 feature = "platform-adapters"
980))]
981fn fallback_entropy(counter: u64) -> u64 {
982 js_sys::Date::now().to_bits() ^ web_monotonic_seconds().to_bits() ^ counter.rotate_left(29)
983}
984
985#[cfg(all(
986 target_arch = "wasm32",
987 target_os = "unknown",
988 feature = "platform-adapters"
989))]
990fn web_monotonic_seconds() -> f64 {
991 let global = js_sys::global();
992 let performance = js_sys::Reflect::get(&global, &JsValue::from_str("performance"));
993 let Ok(performance) = performance else {
994 return js_sys::Date::now() / 1_000.0;
995 };
996 let now = js_sys::Reflect::get(&performance, &JsValue::from_str("now"))
997 .ok()
998 .and_then(|value| value.dyn_into::<js_sys::Function>().ok())
999 .and_then(|now| now.call0(&performance).ok())
1000 .and_then(|value| value.as_f64());
1001 now.unwrap_or_else(js_sys::Date::now) / 1_000.0
1002}
1003
1004fn stock_loadstring_compiler(
1012 source: &[u8],
1013 source_name: Option<&[u8]>,
1014 profile: rustia_vm::Profile,
1015) -> std::result::Result<Program, String> {
1016 let source_name = source_name.map_or_else(
1017 || loadstring_chunk_name(source),
1018 |name| String::from_utf8_lossy(name).into_owned(),
1019 );
1020 let chunk = rustia_parser::parse_source_bytes(source)
1021 .map_err(|error| format!("{source_name}:1: {error}"))?;
1022 let options = CompileOptions {
1023 puc51_constructor_order: profile == rustia_vm::Profile::Puc51Compat,
1024 ..CompileOptions::default()
1025 }
1026 .with_source_bytes(source_name.clone(), source);
1027 let mut program = compile_with_options(&chunk, options)
1028 .map_err(|error| format!("{source_name}:1: {error}"))?;
1029 program.diagnostic_source = rustia_vm::diagnostic::SourceSnapshot::copy_with_limit(
1030 source,
1031 crate::DiagnosticLimits::default().source_bytes,
1032 );
1033 Ok(program)
1034}
1035
1036fn loadstring_chunk_name(source: &[u8]) -> String {
1037 let mut preview = String::new();
1038 for byte in source.iter().copied().take(60) {
1039 match byte {
1040 b'\\' => preview.push_str("\\\\"),
1041 b'"' => preview.push_str("\\\""),
1042 b'\n' => break,
1043 0x20..=0x7e => preview.push(byte as char),
1044 _ => preview.push('?'),
1045 }
1046 }
1047 if source.len() > 60 {
1048 preview.push_str("...");
1049 }
1050 format!("[string \"{preview}\"]")
1051}
1052
1053#[derive(Clone, Debug)]
1060pub struct RustiaExtension {
1061 namespace: Option<String>,
1062 functions: Vec<HostFunctionOp>,
1063}
1064
1065pub const RUSTIA_HOST_FUEL_ABI_VERSION: u32 = 1;
1069
1070pub const RUSTIA_DEFAULT_HOST_FUNCTION_FUEL: u32 = 1;
1072
1073pub const RUSTIA_MIN_HOST_FUNCTION_FUEL: u32 = 1;
1075
1076#[non_exhaustive]
1078#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1079pub struct RustiaHostFuelPolicy {
1080 pub abi_version: u32,
1082 pub default_function_fuel: u32,
1084 pub minimum_function_fuel: u32,
1086}
1087
1088pub const RUSTIA_HOST_FUEL_POLICY: RustiaHostFuelPolicy = RustiaHostFuelPolicy {
1090 abi_version: RUSTIA_HOST_FUEL_ABI_VERSION,
1091 default_function_fuel: RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1092 minimum_function_fuel: RUSTIA_MIN_HOST_FUNCTION_FUEL,
1093};
1094
1095#[non_exhaustive]
1097#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1098pub struct RustiaHostFunctionInfo<'a> {
1099 pub name: &'a str,
1101 pub fuel_abi_version: u32,
1103 pub fuel_cost: u32,
1105 pub capability: OpCapability,
1107 pub parameter_count: u8,
1109 pub parameter_types: &'a [&'static str],
1111 pub return_types: &'a [&'static str],
1113 pub fallible: bool,
1115}
1116
1117impl RustiaExtension {
1118 pub fn new(namespace: impl Into<String>) -> Self {
1120 let namespace = namespace.into();
1121 Self {
1122 namespace: (!namespace.is_empty()).then_some(namespace),
1123 functions: Vec::new(),
1124 }
1125 }
1126
1127 pub fn global() -> Self {
1129 Self {
1130 namespace: None,
1131 functions: Vec::new(),
1132 }
1133 }
1134
1135 pub fn namespace(&self) -> Option<&str> {
1137 self.namespace.as_deref()
1138 }
1139
1140 pub fn fuel_policy(&self) -> RustiaHostFuelPolicy {
1142 RUSTIA_HOST_FUEL_POLICY
1143 }
1144
1145 pub fn functions(&self) -> impl Iterator<Item = RustiaHostFunctionInfo<'_>> + '_ {
1147 self.functions
1148 .iter()
1149 .map(|function| RustiaHostFunctionInfo {
1150 name: &function.name,
1151 fuel_abi_version: RUSTIA_HOST_FUEL_ABI_VERSION,
1152 fuel_cost: function.fuel_cost,
1153 capability: OpCapability::from_core(function.capability),
1154 parameter_count: function.parameter_count,
1155 parameter_types: &function.parameter_types,
1156 return_types: &function.return_types,
1157 fallible: function.fallible,
1158 })
1159 }
1160
1161 pub fn fn_pure<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1163 where
1164 Func: IntoHostFunction<Args, Return>,
1165 {
1166 self.fn_with(
1167 name,
1168 RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1169 OpCapability::Pure,
1170 function,
1171 )
1172 }
1173
1174 pub fn fn_input<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1176 where
1177 Func: IntoHostFunction<Args, Return>,
1178 {
1179 self.fn_with(
1180 name,
1181 RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1182 OpCapability::ReadsDeterministicInput,
1183 function,
1184 )
1185 }
1186
1187 pub fn fn_slot_read<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1189 where
1190 Func: IntoHostFunction<Args, Return>,
1191 {
1192 self.fn_with(
1193 name,
1194 RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1195 OpCapability::ReadsSlotState,
1196 function,
1197 )
1198 }
1199
1200 pub fn fn_slot_write<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1202 where
1203 Func: IntoHostFunction<Args, Return>,
1204 {
1205 self.fn_with(
1206 name,
1207 RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1208 OpCapability::WritesSlotEffect,
1209 function,
1210 )
1211 }
1212
1213 pub fn fn_effect<Func, Args, Return>(self, name: impl Into<String>, function: Func) -> Self
1215 where
1216 Func: IntoHostFunction<Args, Return>,
1217 {
1218 self.fn_with(
1219 name,
1220 RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1221 OpCapability::EmitsDeterministicEffect,
1222 function,
1223 )
1224 }
1225
1226 pub fn fn_external_state<Func, Args, Return>(
1228 self,
1229 name: impl Into<String>,
1230 function: Func,
1231 ) -> Self
1232 where
1233 Func: IntoHostFunction<Args, Return>,
1234 {
1235 self.fn_with(
1236 name,
1237 RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1238 OpCapability::ReadsExternalMutableState,
1239 function,
1240 )
1241 }
1242
1243 pub fn fn_nondeterministic<Func, Args, Return>(
1245 self,
1246 name: impl Into<String>,
1247 function: Func,
1248 ) -> Self
1249 where
1250 Func: IntoHostFunction<Args, Return>,
1251 {
1252 self.fn_with(
1253 name,
1254 RUSTIA_DEFAULT_HOST_FUNCTION_FUEL,
1255 OpCapability::NondeterministicEffect,
1256 function,
1257 )
1258 }
1259
1260 pub fn fn_with<Func, Args, Return>(
1263 mut self,
1264 name: impl Into<String>,
1265 fuel_cost: u32,
1266 capability: OpCapability,
1267 function: Func,
1268 ) -> Self
1269 where
1270 Func: IntoHostFunction<Args, Return>,
1271 {
1272 self.functions.push(
1273 crate::HostFunction::<()>::with_capability(capability, function)
1274 .fuel_cost(fuel_cost)
1275 .into_op(name.into()),
1276 );
1277 self
1278 }
1279
1280 pub(crate) fn install(self, rustia: &mut Rustia) -> Result<()> {
1281 let Some(namespace) = self.namespace else {
1282 return rustia
1283 .vm_mut()
1284 .install_host_functions(self.functions)
1285 .map_err(Error::from_engine);
1286 };
1287
1288 rustia
1289 .vm_mut()
1290 .install_host_module(namespace, self.functions)
1291 .map_err(Error::from_engine)
1292 }
1293}