1use crate::heap::Heap;
13use crate::id::WaitKey;
14use crate::value::Value;
15
16#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
18pub struct EffectId {
19 pub domain: u64,
21 pub sequence: u64,
23}
24
25#[derive(Clone, PartialEq, Eq, Debug)]
27pub struct EffectRecord {
28 pub id: EffectId,
30 pub arg: i64,
32 pub outcome: i64,
34 pub bytes: Option<Vec<u8>>,
36 pub request: Option<Vec<u8>>,
38 pub module: Option<Vec<u8>>,
40}
41
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
44pub struct JournalError;
45
46impl std::fmt::Display for JournalError {
47 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48 f.write_str("journal payload mismatch")
49 }
50}
51impl std::error::Error for JournalError {}
52
53mod journal_payload {
54 pub trait Sealed {}
55 impl Sealed for i64 {}
56 impl Sealed for Vec<u8> {}
57}
58
59pub trait JournalPayload: journal_payload::Sealed + Sized {
62 #[doc(hidden)]
64 fn record(self, id: EffectId, arg: i64) -> EffectRecord;
65 #[doc(hidden)]
67 fn replay(record: &EffectRecord) -> Result<Self, JournalError>;
68}
69
70impl JournalPayload for i64 {
71 fn record(self, id: EffectId, arg: i64) -> EffectRecord {
72 EffectRecord {
73 id,
74 arg,
75 outcome: self,
76 bytes: None,
77 module: None,
78 request: None,
79 }
80 }
81 fn replay(record: &EffectRecord) -> Result<Self, JournalError> {
82 if record.bytes.is_none() {
83 Ok(record.outcome)
84 } else {
85 Err(JournalError)
86 }
87 }
88}
89
90impl JournalPayload for Vec<u8> {
91 fn record(self, id: EffectId, arg: i64) -> EffectRecord {
92 EffectRecord {
93 id,
94 arg,
95 outcome: 0,
96 bytes: Some(self),
97 module: None,
98 request: None,
99 }
100 }
101 fn replay(record: &EffectRecord) -> Result<Self, JournalError> {
102 record.bytes.clone().ok_or(JournalError)
103 }
104}
105
106#[derive(Clone, Debug, Default)]
110pub struct Journal {
111 entries: Vec<EffectRecord>,
112 index: std::collections::HashMap<EffectId, usize>,
114}
115
116impl PartialEq for Journal {
117 fn eq(&self, other: &Self) -> bool {
118 self.entries == other.entries
119 }
120}
121
122impl Eq for Journal {}
123
124impl Journal {
125 pub fn new() -> Self {
127 Self::default()
128 }
129
130 pub fn entries(&self) -> &[EffectRecord] {
132 &self.entries
133 }
134
135 pub fn commit<P: JournalPayload>(
137 &mut self,
138 id: EffectId,
139 arg: i64,
140 fresh: impl FnOnce() -> P,
141 ) -> Result<P, JournalError> {
142 if let Some(&position) = self.index.get(&id) {
143 if self.entries[position].request.is_some() {
146 return Err(JournalError);
147 }
148 return P::replay(&self.entries[position]);
149 }
150 let record = fresh().record(id, arg);
151 let outcome = P::replay(&record);
152 self.index.insert(id, self.entries.len());
153 self.entries.push(record);
154 outcome
155 }
156
157 pub fn seed(&mut self, id: EffectId, arg: i64, outcome: i64) {
159 let _ = self.seed_record(outcome.record(id, arg));
160 }
161
162 pub fn seed_record(&mut self, record: EffectRecord) -> Result<(), JournalError> {
165 if record.bytes.is_some() && record.outcome != 0
166 || record.module.is_some() && record.bytes.is_none()
167 || record.module.is_some() && record.request.is_some()
168 {
169 return Err(JournalError);
170 }
171 if !self.index.contains_key(&record.id) {
172 self.index.insert(record.id, self.entries.len());
173 self.entries.push(record);
174 }
175 Ok(())
176 }
177
178 pub fn replay_request<P: JournalPayload>(
181 &self,
182 id: EffectId,
183 arg: i64,
184 request: &[u8],
185 ) -> Result<Option<P>, JournalError> {
186 let Some(&position) = self.index.get(&id) else {
187 return Ok(None);
188 };
189 let record = &self.entries[position];
190 if record.arg != arg
191 || record.module.is_some()
192 || record.request.as_deref() != Some(request)
193 {
194 return Err(JournalError);
195 }
196 P::replay(record).map(Some)
197 }
198
199 pub fn commit_request<P: JournalPayload>(
202 &mut self,
203 id: EffectId,
204 arg: i64,
205 request: &[u8],
206 fresh: impl FnOnce() -> P,
207 ) -> Result<P, JournalError> {
208 if let Some(outcome) = self.replay_request(id, arg, request)? {
209 return Ok(outcome);
210 }
211 let mut record = fresh().record(id, arg);
212 record.request = Some(request.to_vec());
213 let outcome = P::replay(&record);
214 self.index.insert(id, self.entries.len());
215 self.entries.push(record);
216 outcome
217 }
218
219 pub(crate) fn module_result(&self, domain: u64, name: &[u8]) -> Option<(EffectId, &[u8])> {
220 self.entries.iter().find_map(|record| {
221 (record.id.domain == domain && record.module.as_deref() == Some(name))
222 .then(|| record.bytes.as_deref().map(|bytes| (record.id, bytes)))?
223 })
224 }
225
226 pub(crate) fn commit_module(
227 &mut self,
228 id: EffectId,
229 name: &[u8],
230 fresh: impl FnOnce() -> Vec<u8>,
231 ) -> Result<Vec<u8>, JournalError> {
232 if let Some(&position) = self.index.get(&id)
233 && (self.entries[position].module.as_deref() != Some(name)
234 || self.entries[position].request.is_some())
235 {
236 return Err(JournalError);
237 }
238 let outcome = self.commit(id, 0, fresh)?;
239 let position = self.index[&id];
240 let record = &mut self.entries[position];
241 record.module = Some(name.to_vec());
242 Ok(outcome)
243 }
244}
245
246pub struct HostCtx<'a> {
247 pub journal: &'a mut Journal,
248 pub effect: EffectId,
249}
250
251pub enum HostResult {
252 Ready(i64),
253 Pending(WaitKey),
254 Fault,
256}
257
258#[deprecated(note = "use HostRegistry::function or HostRegistry::typed")]
259pub type HostFn = fn(&mut HostCtx<'_>, i64) -> HostResult;
260
261#[derive(Clone, Copy, PartialEq, Eq, Debug)]
263pub enum NativePolicy {
264 VmLocal,
267 External,
271}
272
273#[derive(Clone, Copy, PartialEq, Eq, Debug)]
275pub enum NativeOutcome {
276 Ready,
278 Pending(WaitKey),
280 Fault,
282}
283
284pub type NativeFn = fn(&mut NativeCall<'_>) -> NativeOutcome;
286
287#[derive(Clone, Copy, PartialEq, Eq, Debug)]
289pub enum LuaType {
290 Nil,
292 Boolean,
294 Number,
296 String,
298 Table,
300 Function,
302 Thread,
304 Userdata,
307}
308
309#[derive(Clone, Copy)]
313pub struct NativeValue<'a> {
314 pub(crate) value: Value,
315 _call: std::marker::PhantomData<&'a ()>,
316}
317
318impl std::fmt::Debug for NativeValue<'_> {
319 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
320 let ty = match self.value {
321 Value::Nil => LuaType::Nil,
322 Value::Bool(_) => LuaType::Boolean,
323 Value::Integer(_) | Value::Float(_) => LuaType::Number,
324 Value::String(_) => LuaType::String,
325 Value::Table(_) => LuaType::Table,
326 Value::Closure(_) | Value::Native(_) | Value::NativeClosure(_) => LuaType::Function,
327 Value::Thread(_) => LuaType::Thread,
328 Value::Userdata(_) | Value::LightUserdata(..) => LuaType::Userdata,
329 };
330 f.debug_tuple("NativeValue").field(&ty).finish()
331 }
332}
333
334impl NativeValue<'_> {
335 pub(crate) fn wrap(value: Value) -> Self {
336 Self {
337 value,
338 _call: std::marker::PhantomData,
339 }
340 }
341}
342
343#[derive(Clone, Copy, PartialEq, Eq, Debug)]
345pub enum RawSetError {
346 NotATable,
348 InvalidKey,
350 Memory,
353}
354
355#[derive(Clone, Debug, PartialEq)]
360#[deprecated(note = "use Value and IntoLua/FromLua with rooted object values")]
361pub enum HostValue {
362 Nil,
364 Boolean(bool),
366 Integer(i64),
368 Number(f64),
370 String(Vec<u8>),
372 Object(crate::id::ObjectId),
374 Native(String),
376 LightUserdata(crate::userdata::LightUserdata),
378}
379
380#[derive(Clone, Copy, PartialEq, Eq, Debug)]
382pub enum UserdataError {
383 NotUserdata,
385 Unregistered,
387 Memory,
391}
392
393#[derive(Clone, Debug, PartialEq)]
396#[deprecated(note = "use Completion with rooted Value objects")]
397pub enum LegacyCompletion {
398 Return(Vec<HostValue>),
400 Error(HostValue),
402}
403
404#[deprecated(note = "use NativeContext with HostRegistry::function or typed")]
409pub type NativeCall<'a> = LegacyNativeCall<'a>;
410
411pub(crate) enum NativeError {
413 Argument(usize, Vec<u8>),
414 Message(Vec<u8>, bool),
415}
416
417#[doc(hidden)]
419pub struct LegacyNativeCall<'a> {
420 pub(crate) heap: &'a mut Heap,
421 pub(crate) args: &'a [Value],
422 pub(crate) results: &'a mut Vec<Value>,
423 pub(crate) effect: Option<EffectId>,
424 pub(crate) journal: Option<&'a mut Journal>,
425 pub(crate) out_of_memory: bool,
428 pub(crate) registry: &'a HostRegistry,
430 pub(crate) max_objects: u32,
433 pub(crate) error: Option<NativeError>,
436}
437
438impl<'a> LegacyNativeCall<'a> {
439 pub fn arg_count(&self) -> usize {
440 self.args.len()
441 }
442
443 pub fn arg(&self, index: usize) -> NativeValue<'a> {
445 NativeValue::wrap(self.args.get(index).copied().unwrap_or(Value::Nil))
446 }
447
448 pub fn type_of(&self, value: NativeValue<'a>) -> LuaType {
449 match value.value {
450 Value::Nil => LuaType::Nil,
451 Value::Bool(_) => LuaType::Boolean,
452 Value::Integer(_) | Value::Float(_) => LuaType::Number,
453 Value::String(_) => LuaType::String,
454 Value::Table(_) => LuaType::Table,
455 Value::Closure(_) | Value::Native(_) | Value::NativeClosure(_) => LuaType::Function,
456 Value::Thread(_) => LuaType::Thread,
457 Value::Userdata(_) | Value::LightUserdata(..) => LuaType::Userdata,
458 }
459 }
460
461 pub fn string_bytes(&self, value: NativeValue<'a>) -> Option<&[u8]> {
463 match value.value {
464 Value::String(handle) => self.heap.string_bytes(handle),
465 _ => None,
466 }
467 }
468
469 pub fn raw_get(&self, table: NativeValue<'a>, key: NativeValue<'a>) -> Option<NativeValue<'a>> {
472 let Value::Table(handle) = table.value else {
473 return None;
474 };
475 let value = match self.heap.key_view(key.value) {
476 Ok(key) => self.heap.table_get_view(handle, key)?,
477 Err(_) => Value::Nil,
478 };
479 Some(NativeValue::wrap(value))
480 }
481
482 pub fn raw_set(
485 &mut self,
486 table: NativeValue<'a>,
487 key: NativeValue<'a>,
488 value: NativeValue<'a>,
489 ) -> Result<(), RawSetError> {
490 let Value::Table(handle) = table.value else {
491 return Err(RawSetError::NotATable);
492 };
493 if self.heap.update_string_key(handle, key.value, value.value) {
494 return Ok(());
495 }
496 let normalized = self
497 .heap
498 .normalize_value(key.value)
499 .map_err(|_| RawSetError::InvalidKey)?;
500 match self
501 .heap
502 .table_insert(handle, normalized, key.value, value.value)
503 {
504 Ok(()) => Ok(()),
505 Err(crate::heap::InsertError::NoTable) => Err(RawSetError::NotATable),
506 Err(crate::heap::InsertError::Memory) => {
507 self.out_of_memory = true;
508 Err(RawSetError::Memory)
509 }
510 }
511 }
512
513 pub fn raw_equal(&self, a: NativeValue<'a>, b: NativeValue<'a>) -> bool {
517 crate::compare::equal(self.heap, a.value, b.value)
518 }
519
520 pub fn raw_len(&self, value: NativeValue<'a>) -> Option<i64> {
521 match value.value {
522 Value::String(handle) => i64::try_from(self.heap.string_bytes(handle)?.len()).ok(),
523 Value::Table(handle) => Some(self.heap.tables.get(handle)?.table.raw_border()),
524 _ => None,
525 }
526 }
527
528 pub fn metatable(&self, value: NativeValue<'a>) -> Option<NativeValue<'a>> {
531 let metatable = self.heap.metatable_of(value.value)?;
532 Some(NativeValue::wrap(Value::Table(metatable)))
533 }
534
535 pub fn set_metatable(
539 &mut self,
540 object: NativeValue<'a>,
541 metatable: Option<NativeValue<'a>>,
542 ) -> bool {
543 let metatable = match metatable.map(|value| value.value) {
544 None => None,
545 Some(Value::Table(metatable)) => Some(metatable),
546 Some(_) => return false,
547 };
548 self.heap.set_metatable(object.value, metatable)
551 }
552
553 pub fn new_userdata(
556 &mut self,
557 len: usize,
558 user_values: usize,
559 ) -> Result<NativeValue<'a>, UserdataError> {
560 if len > crate::userdata::MAX_USERDATA_BYTES {
561 self.out_of_memory = true;
562 return Err(UserdataError::Memory);
563 }
564 let made = self
565 .heap
566 .alloc_userdata(self.max_objects, user_values, len as u64, || {
567 crate::userdata::Payload::Bytes(vec![0; len].into_boxed_slice())
568 });
569 self.made(made)
570 }
571
572 pub fn new_host_userdata<T: crate::userdata::HostUserdata>(
576 &mut self,
577 value: T,
578 user_values: usize,
579 ) -> Result<NativeValue<'a>, UserdataError> {
580 if !self.registry.has_userdata_type::<T>() {
581 return Err(UserdataError::Unregistered);
582 }
583 let charge = value.logical_size();
584 let made = self
585 .heap
586 .alloc_userdata(self.max_objects, user_values, charge, || {
587 crate::userdata::Payload::Host {
588 symbol: T::SYMBOL,
589 value: Box::new(value),
590 }
591 });
592 self.made(made)
593 }
594
595 fn made(
596 &mut self,
597 made: Result<crate::id::Handle<crate::heap::UserdataObj>, crate::id::TerminationReason>,
598 ) -> Result<NativeValue<'a>, UserdataError> {
599 match made {
600 Ok(handle) => Ok(NativeValue::wrap(Value::Userdata(handle))),
601 Err(_) => {
602 self.out_of_memory = true;
603 Err(UserdataError::Memory)
604 }
605 }
606 }
607
608 pub fn light_userdata(&self, key: crate::userdata::HostLightKey) -> NativeValue<'a> {
610 NativeValue::wrap(Value::LightUserdata(crate::value::LightDomain::Host, key.0))
611 }
612
613 pub fn light(&self, value: NativeValue<'a>) -> Option<crate::userdata::LightUserdata> {
615 match value.value {
616 Value::LightUserdata(domain, bits) => {
617 Some(crate::userdata::LightUserdata { domain, bits })
618 }
619 _ => None,
620 }
621 }
622
623 pub fn is_full_userdata(&self, value: NativeValue<'a>) -> bool {
625 matches!(value.value, Value::Userdata(_))
626 }
627
628 fn userdata_object(&self, value: NativeValue<'a>) -> Option<&crate::heap::UserdataObj> {
629 match value.value {
630 Value::Userdata(handle) => self.heap.userdata.get(handle),
631 _ => None,
632 }
633 }
634
635 fn userdata_object_mut(
636 &mut self,
637 value: NativeValue<'a>,
638 ) -> Option<&mut crate::heap::UserdataObj> {
639 match value.value {
640 Value::Userdata(handle) => self.heap.userdata.get_mut(handle),
641 _ => None,
642 }
643 }
644
645 pub fn userdata_bytes(&self, value: NativeValue<'a>) -> Option<&[u8]> {
648 self.userdata_object(value)?.payload.bytes()
649 }
650
651 pub fn userdata_bytes_mut(&mut self, value: NativeValue<'a>) -> Option<&mut [u8]> {
652 self.userdata_object_mut(value)?.payload.bytes_mut()
653 }
654
655 pub fn userdata_ref<T: crate::userdata::HostUserdata>(
659 &self,
660 value: NativeValue<'a>,
661 ) -> Option<&T> {
662 self.userdata_object(value)?.payload.host::<T>()
663 }
664
665 pub fn userdata_mut<T: crate::userdata::HostUserdata>(
690 &mut self,
691 value: NativeValue<'a>,
692 ) -> Option<&mut T> {
693 self.userdata_object_mut(value)?.payload.host_mut::<T>()
694 }
695
696 pub fn user_value(&self, value: NativeValue<'a>, n: usize) -> Option<NativeValue<'a>> {
699 let object = self.userdata_object(value)?;
700 let held = *object.user_values.get(n.checked_sub(1)?)?;
701 Some(NativeValue::wrap(held))
702 }
703
704 pub fn set_user_value(
706 &mut self,
707 value: NativeValue<'a>,
708 n: usize,
709 held: NativeValue<'a>,
710 ) -> bool {
711 let Some(slot) = n
712 .checked_sub(1)
713 .and_then(|index| self.userdata_object_mut(value)?.user_values.get_mut(index))
714 else {
715 return false;
716 };
717 *slot = held.value;
718 true
719 }
720
721 pub fn set_userdata_charge(
725 &mut self,
726 value: NativeValue<'a>,
727 bytes: u64,
728 ) -> Result<(), UserdataError> {
729 let Value::Userdata(handle) = value.value else {
730 return Err(UserdataError::NotUserdata);
731 };
732 let object = self
733 .heap
734 .userdata
735 .get(handle)
736 .ok_or(UserdataError::NotUserdata)?;
737 if object.payload.symbol().is_none() {
738 return Err(UserdataError::NotUserdata);
739 }
740 let old = object.charge;
741 if bytes > old && !self.heap.gc.fits(bytes - old) {
742 self.out_of_memory = true;
743 return Err(UserdataError::Memory);
744 }
745 if bytes > old {
749 self.heap.gc.charge(bytes - old);
750 } else {
751 self.heap.give_back(old - bytes);
752 }
753 if let Some(object) = self.heap.userdata.get_mut(handle) {
754 object.charge = bytes;
755 }
756 Ok(())
757 }
758
759 pub fn arg_error(&mut self, index: usize, message: &str) -> NativeOutcome {
763 self.error = Some(NativeError::Argument(index, message.as_bytes().to_vec()));
764 NativeOutcome::Fault
765 }
766
767 pub fn error(&mut self, message: &str) -> NativeOutcome {
769 self.error = Some(NativeError::Message(message.as_bytes().to_vec(), true));
770 NativeOutcome::Fault
771 }
772
773 pub fn raw_error(&mut self, message: &str) -> NativeOutcome {
775 self.error = Some(NativeError::Message(message.as_bytes().to_vec(), false));
776 NativeOutcome::Fault
777 }
778
779 pub fn type_error(&mut self, index: usize, expected: &str) -> NativeOutcome {
783 let got: Vec<u8> = if index >= self.args.len() {
784 b"no value".to_vec()
785 } else {
786 let value = self.args[index];
787 match crate::index::metamethod(self.heap, value, b"__name") {
788 Some(Value::String(name)) => {
789 self.heap.string_bytes(name).unwrap_or_default().to_vec()
790 }
791 _ if matches!(value, Value::LightUserdata(..)) => b"light userdata".to_vec(),
792 _ => crate::heap::type_name(value).as_bytes().to_vec(),
793 }
794 };
795 let mut message = format!("{expected} expected, got ").into_bytes();
796 message.extend(got);
797 self.error = Some(NativeError::Argument(index, message));
798 NativeOutcome::Fault
799 }
800
801 pub fn push(&mut self, value: NativeValue<'a>) {
802 self.results.push(value.value);
803 }
804
805 pub fn integer(&self, index: usize) -> Option<i64> {
807 match self.args.get(index)? {
808 Value::Integer(integer) => Some(*integer),
809 _ => None,
810 }
811 }
812
813 pub fn number(&self, index: usize) -> Option<f64> {
815 match self.args.get(index)? {
816 Value::Integer(integer) => Some(*integer as f64),
817 Value::Float(float) => Some(*float),
818 _ => None,
819 }
820 }
821
822 pub fn boolean(&self, index: usize) -> Option<bool> {
823 match self.args.get(index)? {
824 Value::Bool(bit) => Some(*bit),
825 _ => None,
826 }
827 }
828
829 pub fn is_nil(&self, index: usize) -> bool {
831 matches!(self.args.get(index), None | Some(Value::Nil))
832 }
833
834 pub fn push_integer(&mut self, value: i64) {
835 self.results.push(Value::Integer(value));
836 }
837
838 pub fn push_number(&mut self, value: f64) {
839 self.results.push(Value::Float(value));
840 }
841
842 pub fn push_boolean(&mut self, value: bool) {
843 self.results.push(Value::Bool(value));
844 }
845
846 pub fn push_nil(&mut self) {
847 self.results.push(Value::Nil);
848 }
849
850 pub fn push_arg(&mut self, index: usize) {
852 self.results
853 .push(self.args.get(index).copied().unwrap_or(Value::Nil));
854 }
855
856 pub fn effect(&self) -> Option<EffectId> {
858 self.effect
859 }
860
861 pub fn journal(&mut self) -> Option<&mut Journal> {
863 self.journal.as_deref_mut()
864 }
865}
866
867#[derive(Clone)]
868pub(crate) struct NativeEntry {
869 pub(crate) policy: NativePolicy,
870 pub(crate) function: NativeFn,
871 pub(crate) callback: Option<std::rc::Rc<crate::api::native::Callback>>,
872 pub(crate) typed: Option<std::rc::Rc<crate::api::native::TypedCallback>>,
873 pub(crate) builtin: Option<Builtin>,
877}
878
879#[derive(Clone, Copy, Debug, PartialEq, Eq)]
883pub(crate) enum Builtin {
884 #[allow(dead_code)] Exit,
887 Os(crate::oslib::OsFn),
888 Io(crate::iolib::IoFn),
889 #[cfg(test)]
890 CapabilitySmoke,
891 Pcall,
892 Xpcall,
893 Error,
894 Assert,
895 Type,
896 ToString,
897 ToNumber,
898 Print,
899 Next,
900 Pairs,
901 Ipairs,
902 IpairsNext,
904 CollectGarbage,
905 Load,
906 LoadFile,
907 DoFile,
908 Math(crate::library::MathFn),
910 Table(crate::library::TableFn),
912 String(crate::strlib::StrFn),
914 Utf8(crate::utf8lib::Utf8Fn),
916 Package(crate::package::PkgFn),
918 Debug(crate::debuglib::DbgFn),
920 Coroutine(crate::corolib::CoFn),
922 Warn,
924}
925
926pub type Output = Box<dyn FnMut(&[u8])>;
932
933pub type Warnings = Box<dyn FnMut(&[u8], bool)>;
940
941pub type Entropy = Box<dyn FnMut() -> i64>;
945
946fn builtin_placeholder(_call: &mut NativeCall<'_>) -> NativeOutcome {
947 NativeOutcome::Fault
948}
949
950type HookEntries = Vec<(String, std::rc::Rc<crate::api::hooks::HookCallback>)>;
951
952#[derive(Clone)]
973pub struct HostRegistry {
974 entries: Vec<(String, HostFn)>,
975 natives: Vec<(String, NativeEntry)>,
976 userdata_types: Vec<crate::userdata::HostType>,
978 hooks: Option<Box<HookEntries>>,
979}
980
981impl HostRegistry {
982 pub fn new() -> Self {
984 Self {
985 entries: Vec::new(),
986 natives: Vec::new(),
987 userdata_types: Vec::new(),
988 hooks: None,
989 }
990 }
991
992 pub fn register_hook<F>(&mut self, symbol: impl Into<String>, callback: F)
995 where
996 F: Fn(&mut crate::HookContext<'_>) -> crate::Result<crate::HookAction> + 'static,
997 {
998 let symbol = symbol.into();
999 let hooks = self.hooks.get_or_insert_with(Box::default);
1000 let entry = (
1001 symbol.clone(),
1002 std::rc::Rc::new(callback) as std::rc::Rc<crate::api::hooks::HookCallback>,
1003 );
1004 if let Some(slot) = hooks.iter().position(|(name, _)| name == &symbol) {
1005 hooks[slot] = entry;
1006 } else {
1007 hooks.push(entry);
1008 }
1009 }
1010 pub(crate) fn hook_slot(&self, symbol: &str) -> Option<u32> {
1011 self.hooks
1012 .as_ref()?
1013 .iter()
1014 .position(|(name, _)| name == symbol)
1015 .and_then(|i| i.try_into().ok())
1016 }
1017 pub(crate) fn hook(
1018 &self,
1019 slot: u32,
1020 ) -> Option<(&str, &std::rc::Rc<crate::api::hooks::HookCallback>)> {
1021 self.hooks
1022 .as_ref()?
1023 .get(slot as usize)
1024 .map(|(name, callback)| (name.as_str(), callback))
1025 }
1026
1027 pub fn register_userdata<T: crate::userdata::HostUserdata>(&mut self) {
1033 self.insert_userdata_type(crate::userdata::HostType::of::<T>());
1034 }
1035
1036 pub fn register_portable_userdata<T: crate::userdata::PortableUserdata>(&mut self) {
1040 self.insert_userdata_type(crate::userdata::HostType::portable::<T>());
1041 }
1042
1043 pub fn register_rebind_userdata<T: crate::userdata::RebindUserdata>(&mut self) {
1046 self.insert_userdata_type(crate::userdata::HostType::rebind::<T>());
1047 }
1048
1049 pub fn userdata_policy(&self, symbol: &str) -> Option<crate::UserdataPolicy> {
1051 self.userdata_type(symbol).map(|entry| entry.policy.kind())
1052 }
1053
1054 fn insert_userdata_type(&mut self, entry: crate::userdata::HostType) {
1055 self.userdata_types
1056 .retain(|held| held.symbol != entry.symbol && held.type_id != entry.type_id);
1057 self.userdata_types.push(entry);
1058 }
1059
1060 pub(crate) fn has_userdata_type<T: 'static>(&self) -> bool {
1061 let type_id = std::any::TypeId::of::<T>();
1062 self.userdata_types
1063 .iter()
1064 .any(|entry| entry.type_id == type_id)
1065 }
1066
1067 pub(crate) fn userdata_type(&self, symbol: &str) -> Option<crate::userdata::HostType> {
1068 self.userdata_types
1069 .iter()
1070 .find(|entry| entry.symbol == symbol)
1071 .copied()
1072 }
1073
1074 pub fn register_native(
1078 &mut self,
1079 symbol: impl Into<String>,
1080 policy: NativePolicy,
1081 function: NativeFn,
1082 ) {
1083 self.insert_native(
1084 symbol.into(),
1085 NativeEntry {
1086 policy,
1087 function,
1088 callback: None,
1089 typed: None,
1090 builtin: None,
1091 },
1092 );
1093 }
1094
1095 pub fn function<F>(&mut self, symbol: impl Into<String>, policy: NativePolicy, f: F)
1098 where
1099 F: Fn(&mut crate::NativeContext<'_>) -> crate::Result<crate::NativeReturn> + 'static,
1100 {
1101 self.insert_native(
1102 symbol.into(),
1103 NativeEntry {
1104 policy,
1105 function: builtin_placeholder,
1106 callback: Some(std::rc::Rc::new(f)),
1107 typed: None,
1108 builtin: None,
1109 },
1110 );
1111 }
1112
1113 pub fn typed<A, R, F>(&mut self, symbol: impl Into<String>, policy: NativePolicy, f: F)
1116 where
1117 A: crate::FromLuaMulti,
1118 R: crate::IntoLuaMulti,
1119 F: Fn(&mut crate::NativeContext<'_>, A) -> crate::Result<R> + 'static,
1120 {
1121 let fast: std::rc::Rc<crate::api::native::TypedCallback> = std::rc::Rc::new(move |cx| {
1122 let args = cx
1123 .arguments::<A>()
1124 .map_err(|error| cx.argument_error(error))?;
1125 let result = f(cx, args)?;
1126 cx.write_results(result)
1127 });
1128 let callback = fast.clone();
1129 self.insert_native(
1130 symbol.into(),
1131 NativeEntry {
1132 policy,
1133 function: builtin_placeholder,
1134 builtin: None,
1135 typed: Some(fast),
1136 callback: Some(std::rc::Rc::new(move |cx| {
1137 callback(cx)?;
1138 Ok(crate::NativeReturn::Return(cx.take_results()?))
1139 })),
1140 },
1141 );
1142 }
1143
1144 pub(crate) fn register_builtin(&mut self, symbol: &str, builtin: Builtin) {
1145 self.insert_native(
1146 symbol.to_string(),
1147 NativeEntry {
1148 policy: NativePolicy::VmLocal,
1149 function: builtin_placeholder,
1150 callback: None,
1151 typed: None,
1152 builtin: Some(builtin),
1153 },
1154 );
1155 }
1156
1157 fn insert_native(&mut self, symbol: String, entry: NativeEntry) {
1158 if let Some(slot) = self.natives.iter().position(|(name, _)| name == &symbol) {
1159 self.natives[slot] = (symbol, entry);
1160 } else {
1161 self.natives.push((symbol, entry));
1162 }
1163 }
1164
1165 pub(crate) fn fill_missing_natives(&mut self, source: &Self) {
1166 for (symbol, entry) in &source.natives {
1167 if self.native_slot(symbol).is_none() {
1168 self.insert_native(symbol.clone(), entry.clone());
1169 }
1170 }
1171 }
1172
1173 pub(crate) fn native_slot(&self, symbol: &str) -> Option<usize> {
1174 self.natives.iter().position(|(name, _)| name == symbol)
1175 }
1176
1177 pub(crate) fn native(&self, slot: usize) -> Option<&NativeEntry> {
1178 self.natives.get(slot).map(|(_, entry)| entry)
1179 }
1180
1181 #[deprecated(note = "use HostRegistry::function or HostRegistry::typed")]
1183 pub(crate) fn register(&mut self, symbol: impl Into<String>, function: HostFn) {
1184 let symbol = symbol.into();
1185 if let Some(slot) = self.entries.iter().position(|(name, _)| name == &symbol) {
1186 self.entries[slot] = (symbol, function);
1187 } else {
1188 self.entries.push((symbol, function));
1189 }
1190 }
1191
1192 #[doc(hidden)] pub fn proof() -> Self {
1194 let mut registry = Self::new();
1195 registry.register("mark", mark);
1196 registry.register("park", park);
1197 registry.register_native("add", NativePolicy::VmLocal, native_add);
1198 registry.register_native("sub", NativePolicy::VmLocal, native_sub);
1199 registry.register_native("many", NativePolicy::VmLocal, native_many);
1200 registry.register_native("none", NativePolicy::VmLocal, native_none);
1201 registry.register_native("mark", NativePolicy::External, native_mark);
1202 registry.register_native("park", NativePolicy::VmLocal, native_park);
1203 registry.register_native("second", NativePolicy::VmLocal, native_second);
1204 registry.register_native("upto", NativePolicy::VmLocal, native_upto);
1205 register_userdata_proof(&mut registry);
1206 crate::library::register_standard(&mut registry);
1207 crate::debuglib::register_debug(&mut registry);
1208 registry
1209 }
1210
1211 pub(crate) fn contains(&self, symbol: &str) -> bool {
1212 self.entries.iter().any(|(name, _)| name == symbol)
1213 }
1214
1215 pub(crate) fn call(&self, symbol: &str, ctx: &mut HostCtx<'_>, arg: i64) -> Option<HostResult> {
1216 let function = self.entries.iter().find(|(name, _)| name == symbol)?.1;
1217 Some(function(ctx, arg))
1218 }
1219}
1220
1221impl Default for HostRegistry {
1222 fn default() -> Self {
1223 Self::new()
1224 }
1225}
1226
1227pub fn mark(ctx: &mut HostCtx<'_>, arg: i64) -> HostResult {
1230 let effect = ctx.effect;
1231 let outcome = ctx.journal.commit(effect, arg, || effect.sequence as i64);
1232 match outcome {
1233 Ok(outcome) => HostResult::Ready(outcome),
1234 Err(_) => HostResult::Fault,
1235 }
1236}
1237
1238pub fn park(_ctx: &mut HostCtx<'_>, _arg: i64) -> HostResult {
1240 HostResult::Pending(WaitKey(1))
1241}
1242
1243pub fn native_add(call: &mut NativeCall<'_>) -> NativeOutcome {
1245 match (call.integer(0), call.integer(1)) {
1246 (Some(a), Some(b)) => {
1247 call.push_integer(a.wrapping_add(b));
1248 NativeOutcome::Ready
1249 }
1250 _ => NativeOutcome::Fault,
1251 }
1252}
1253
1254pub fn native_sub(call: &mut NativeCall<'_>) -> NativeOutcome {
1256 match (call.integer(0), call.integer(1)) {
1257 (Some(a), Some(b)) => {
1258 call.push_integer(a.wrapping_sub(b));
1259 NativeOutcome::Ready
1260 }
1261 _ => NativeOutcome::Fault,
1262 }
1263}
1264
1265pub fn native_many(call: &mut NativeCall<'_>) -> NativeOutcome {
1267 call.push_integer(10);
1268 call.push_nil();
1269 call.push_integer(30);
1270 NativeOutcome::Ready
1271}
1272
1273pub fn native_none(_call: &mut NativeCall<'_>) -> NativeOutcome {
1275 NativeOutcome::Ready
1276}
1277
1278pub fn native_mark(call: &mut NativeCall<'_>) -> NativeOutcome {
1281 let (Some(effect), Some(arg)) = (call.effect(), call.integer(0)) else {
1282 return NativeOutcome::Fault;
1283 };
1284 let Some(journal) = call.journal() else {
1285 return NativeOutcome::Fault;
1286 };
1287 let Ok(outcome) = journal.commit(effect, arg, || effect.sequence as i64) else {
1288 return NativeOutcome::Fault;
1289 };
1290 call.push_integer(outcome);
1291 NativeOutcome::Ready
1292}
1293
1294pub fn native_park(_call: &mut NativeCall<'_>) -> NativeOutcome {
1296 NativeOutcome::Pending(WaitKey(1))
1297}
1298
1299pub fn native_second(call: &mut NativeCall<'_>) -> NativeOutcome {
1301 call.push_arg(1);
1302 NativeOutcome::Ready
1303}
1304
1305pub fn native_upto(call: &mut NativeCall<'_>) -> NativeOutcome {
1308 let last = if call.is_nil(1) {
1309 Some(0)
1310 } else {
1311 call.integer(1)
1312 };
1313 match (call.integer(0), last.and_then(|last| last.checked_add(1))) {
1314 (Some(n), Some(next)) => {
1315 if next <= n {
1316 call.push_integer(next);
1317 }
1318 NativeOutcome::Ready
1319 }
1320 _ => NativeOutcome::Fault,
1321 }
1322}
1323
1324#[doc(hidden)] pub const USERDATA_NATIVES: [(&str, NativeFn); 10] = [
1331 ("newud", native_newud),
1332 ("light", native_light),
1333 ("udpeek", native_udpeek),
1334 ("udpoke", native_udpoke),
1335 ("counter_new", native_counter_new),
1336 ("counter_get", native_counter_get),
1337 ("counter_add", native_counter_add),
1338 ("counter_grow", native_counter_grow),
1339 ("handle_new", native_handle_new),
1340 ("handle_get", native_handle_get),
1341];
1342
1343#[doc(hidden)] pub fn register_userdata_proof(registry: &mut HostRegistry) {
1347 for (symbol, function) in USERDATA_NATIVES {
1348 registry.register_native(symbol, NativePolicy::VmLocal, function);
1349 }
1350 registry.register_portable_userdata::<ProofCounter>();
1351 registry.register_userdata::<ProofHandle>();
1352}
1353
1354#[derive(Debug, PartialEq)]
1357#[doc(hidden)] pub struct ProofCounter {
1359 pub count: i64,
1360 pub size: u64,
1361}
1362
1363impl crate::userdata::HostUserdata for ProofCounter {
1364 const SYMBOL: &'static str = "moonseed.Counter";
1365 fn logical_size(&self) -> u64 {
1366 self.size
1367 }
1368}
1369
1370impl crate::userdata::PortableUserdata for ProofCounter {
1371 fn encode(&self) -> Vec<u8> {
1372 let mut bytes = self.count.to_le_bytes().to_vec();
1373 bytes.extend(self.size.to_le_bytes());
1374 bytes
1375 }
1376
1377 fn decode(bytes: &[u8]) -> Option<Self> {
1378 let (count, size) = bytes.split_at_checked(8)?;
1379 Some(Self {
1380 count: i64::from_le_bytes(count.try_into().ok()?),
1381 size: u64::from_le_bytes(size.try_into().ok()?),
1382 })
1383 }
1384}
1385
1386#[derive(Debug)]
1389#[doc(hidden)] pub struct ProofHandle(pub i64);
1391
1392impl crate::userdata::HostUserdata for ProofHandle {
1393 const SYMBOL: &'static str = "moonseed.Handle";
1394 fn logical_size(&self) -> u64 {
1395 8
1396 }
1397}
1398
1399fn native_newud(call: &mut NativeCall<'_>) -> NativeOutcome {
1400 let size = call.integer(0).and_then(|size| usize::try_from(size).ok());
1401 let user_values = if call.is_nil(1) {
1402 Some(0)
1403 } else {
1404 call.integer(1).and_then(|n| usize::try_from(n).ok())
1405 };
1406 let (Some(size), Some(user_values)) = (size, user_values) else {
1407 return NativeOutcome::Fault;
1408 };
1409 match call.new_userdata(size, user_values) {
1410 Ok(userdata) => {
1411 call.push(userdata);
1412 NativeOutcome::Ready
1413 }
1414 Err(_) => NativeOutcome::Fault,
1415 }
1416}
1417
1418fn native_light(call: &mut NativeCall<'_>) -> NativeOutcome {
1419 let Some(key) = call.integer(0) else {
1420 return NativeOutcome::Fault;
1421 };
1422 let light = call.light_userdata(crate::userdata::HostLightKey(key as u64));
1423 call.push(light);
1424 NativeOutcome::Ready
1425}
1426
1427fn native_udpeek(call: &mut NativeCall<'_>) -> NativeOutcome {
1428 let userdata = call.arg(0);
1429 let byte = call
1430 .integer(1)
1431 .and_then(|index| usize::try_from(index).ok())
1432 .and_then(|index| call.userdata_bytes(userdata)?.get(index).copied());
1433 match byte {
1434 Some(byte) => {
1435 call.push_integer(i64::from(byte));
1436 NativeOutcome::Ready
1437 }
1438 None => NativeOutcome::Fault,
1439 }
1440}
1441
1442fn native_udpoke(call: &mut NativeCall<'_>) -> NativeOutcome {
1443 let userdata = call.arg(0);
1444 let (Some(index), Some(byte)) = (call.integer(1), call.integer(2)) else {
1445 return NativeOutcome::Fault;
1446 };
1447 let slot = usize::try_from(index)
1448 .ok()
1449 .and_then(|index| call.userdata_bytes_mut(userdata)?.get_mut(index));
1450 match slot {
1451 Some(slot) => {
1452 *slot = byte as u8;
1453 NativeOutcome::Ready
1454 }
1455 None => NativeOutcome::Fault,
1456 }
1457}
1458
1459fn native_counter_new(call: &mut NativeCall<'_>) -> NativeOutcome {
1462 let Some(count) = call.integer(0) else {
1463 return call.type_error(0, "number");
1464 };
1465 let size = call.integer(2).map_or(16, |size| size.max(0) as u64);
1466 let metatable = call.arg(1);
1467 let counter = match call.new_host_userdata(ProofCounter { count, size }, 1) {
1468 Ok(counter) => counter,
1469 Err(_) => return NativeOutcome::Fault,
1470 };
1471 if !call.is_nil(1) && !call.set_metatable(counter, Some(metatable)) {
1472 return call.type_error(1, "table");
1473 }
1474 call.push(counter);
1475 NativeOutcome::Ready
1476}
1477
1478fn native_counter_get(call: &mut NativeCall<'_>) -> NativeOutcome {
1479 let this = call.arg(0);
1480 let Some(counter) = call.userdata_ref::<ProofCounter>(this) else {
1481 return call.type_error(0, ProofCounter::SYMBOL_NAME);
1482 };
1483 let count = counter.count;
1484 call.push_integer(count);
1485 NativeOutcome::Ready
1486}
1487
1488fn native_counter_add(call: &mut NativeCall<'_>) -> NativeOutcome {
1489 let this = call.arg(0);
1490 let Some(by) = call.integer(1) else {
1491 return call.type_error(1, "number");
1492 };
1493 let Some(counter) = call.userdata_mut::<ProofCounter>(this) else {
1494 return call.type_error(0, ProofCounter::SYMBOL_NAME);
1495 };
1496 counter.count = counter.count.wrapping_add(by);
1497 call.push_arg(0);
1498 NativeOutcome::Ready
1499}
1500
1501fn native_counter_grow(call: &mut NativeCall<'_>) -> NativeOutcome {
1504 let this = call.arg(0);
1505 let Some(size) = call.integer(1).and_then(|size| u64::try_from(size).ok()) else {
1506 return call.type_error(1, "number");
1507 };
1508 if call.userdata_ref::<ProofCounter>(this).is_none() {
1509 return call.type_error(0, ProofCounter::SYMBOL_NAME);
1510 }
1511 if call.set_userdata_charge(this, size).is_err() {
1512 return NativeOutcome::Fault;
1513 }
1514 if let Some(counter) = call.userdata_mut::<ProofCounter>(this) {
1515 counter.size = size;
1516 }
1517 NativeOutcome::Ready
1518}
1519
1520fn native_handle_new(call: &mut NativeCall<'_>) -> NativeOutcome {
1521 let Some(n) = call.integer(0) else {
1522 return call.type_error(0, "number");
1523 };
1524 match call.new_host_userdata(ProofHandle(n), 0) {
1525 Ok(handle) => {
1526 call.push(handle);
1527 NativeOutcome::Ready
1528 }
1529 Err(_) => NativeOutcome::Fault,
1530 }
1531}
1532
1533fn native_handle_get(call: &mut NativeCall<'_>) -> NativeOutcome {
1534 let this = call.arg(0);
1535 let Some(handle) = call.userdata_ref::<ProofHandle>(this) else {
1536 return call.type_error(0, ProofHandle::SYMBOL_NAME);
1537 };
1538 let n = handle.0;
1539 call.push_integer(n);
1540 NativeOutcome::Ready
1541}
1542
1543impl ProofCounter {
1544 const SYMBOL_NAME: &'static str = <Self as crate::userdata::HostUserdata>::SYMBOL;
1545}
1546
1547impl ProofHandle {
1548 const SYMBOL_NAME: &'static str = <Self as crate::userdata::HostUserdata>::SYMBOL;
1549}