stak_vm/
memory.rs

1use crate::{
2    Error,
3    cons::{Cons, NEVER, Tag},
4    number::Number,
5    r#type::Type,
6    value::Value,
7};
8use core::fmt::{self, Display, Formatter};
9
10const CONS_FIELD_COUNT: usize = 2;
11
12macro_rules! assert_heap_access {
13    ($self:expr, $index:expr) => {
14        assert_heap_cons!(
15            $self,
16            Cons::new(($index / CONS_FIELD_COUNT * CONS_FIELD_COUNT) as u64)
17        );
18    };
19}
20
21macro_rules! assert_heap_cons {
22    ($self:expr, $cons:expr) => {
23        if $cons.raw_eq(NEVER) {
24            debug_assert!($self.allocation_start() <= $cons.index());
25            debug_assert!($cons.index() < $self.allocation_end());
26        }
27    };
28}
29
30macro_rules! assert_heap_value {
31    ($self:expr, $cons:expr) => {
32        if let Some(cons) = $cons.to_cons() {
33            assert_heap_cons!($self, cons);
34        }
35    };
36}
37
38/// A memory on a virtual machine.
39pub struct Memory<'a> {
40    code: Cons,
41    stack: Cons,
42    r#false: Cons,
43    register: Cons,
44    allocation_index: usize,
45    space: bool,
46    heap: &'a mut [Value],
47}
48
49impl<'a> Memory<'a> {
50    /// Creates a memory.
51    pub fn new(heap: &'a mut [Value]) -> Result<Self, Error> {
52        let mut memory = Self {
53            code: NEVER,
54            stack: NEVER,
55            r#false: NEVER,
56            register: NEVER,
57            allocation_index: 0,
58            space: false,
59            heap,
60        };
61
62        // Initialize a fake false value.
63        let cons = memory.allocate_unchecked(Default::default(), Default::default())?;
64        memory.r#false = memory.allocate_unchecked(cons.into(), cons.into())?;
65
66        Ok(memory)
67    }
68
69    /// Returns a code.
70    #[inline]
71    pub const fn code(&self) -> Cons {
72        self.code
73    }
74
75    /// Sets a code.
76    #[inline]
77    pub fn set_code(&mut self, value: Cons) {
78        self.code = value;
79    }
80
81    /// Returns a register.
82    #[inline]
83    pub const fn register(&self) -> Cons {
84        self.register
85    }
86
87    /// Sets a register.
88    #[inline]
89    pub fn set_register(&mut self, value: Cons) {
90        self.register = value;
91    }
92
93    /// Returns a stack.
94    #[inline]
95    pub const fn stack(&self) -> Cons {
96        self.stack
97    }
98
99    /// Sets a stack.
100    #[inline]
101    pub fn set_stack(&mut self, value: Cons) {
102        self.stack = value;
103    }
104
105    /// Returns a boolean value.
106    #[inline]
107    pub const fn boolean(&self, value: bool) -> Cons {
108        if value {
109            self.cdr(self.r#false).assume_cons()
110        } else {
111            self.r#false
112        }
113    }
114
115    /// Returns a null value.
116    #[inline]
117    pub const fn null(&self) -> Cons {
118        self.car(self.r#false).assume_cons()
119    }
120
121    /// Sets a false value.
122    #[inline]
123    pub(crate) fn set_false(&mut self, cons: Cons) {
124        self.r#false = cons;
125    }
126
127    /// Pushes a value to a stack.
128    #[inline]
129    pub fn push(&mut self, value: Value) -> Result<(), Error> {
130        self.stack = self.cons(value, self.stack)?;
131
132        Ok(())
133    }
134
135    /// Pops a value from a stack.
136    #[inline]
137    pub fn pop(&mut self) -> Value {
138        debug_assert_ne!(self.stack, self.null());
139
140        let value = self.car(self.stack);
141        self.stack = self.cdr(self.stack).assume_cons();
142        value
143    }
144
145    /// Pops values from a stack.
146    pub fn pop_many<const M: usize>(&mut self) -> [Value; M] {
147        let mut values = [Default::default(); M];
148
149        for index in 0..=M - 1 {
150            values[M - 1 - index] = self.pop();
151        }
152
153        values
154    }
155
156    /// Pops numbers from a stack.
157    pub fn pop_numbers<const M: usize>(&mut self) -> [Number; M] {
158        let mut numbers = [Default::default(); M];
159
160        for (index, value) in self.pop_many::<M>().into_iter().enumerate() {
161            numbers[index] = value.assume_number();
162        }
163
164        numbers
165    }
166
167    /// Peeks a value at the top of a stack.
168    #[inline]
169    pub fn top(&mut self) -> Value {
170        debug_assert_ne!(self.stack, self.null());
171
172        self.car(self.stack)
173    }
174
175    /// Allocates a cons with a default tag of [`Type::Pair`].
176    #[inline]
177    pub fn cons(&mut self, car: Value, cdr: Cons) -> Result<Cons, Error> {
178        self.allocate(car, cdr.set_tag(Type::Pair as Tag).into())
179    }
180
181    /// Allocates a cons.
182    #[inline]
183    pub fn allocate(&mut self, car: Value, cdr: Value) -> Result<Cons, Error> {
184        let mut cons = self.allocate_unchecked(car, cdr)?;
185
186        debug_assert_eq!(cons.tag(), Type::default() as Tag);
187        assert_heap_cons!(self, cons);
188        assert_heap_value!(self, car);
189        assert_heap_value!(self, cdr);
190
191        if self.is_out_of_memory() || cfg!(feature = "gc_always") {
192            self.collect_garbages(Some(&mut cons))?;
193        }
194
195        Ok(cons)
196    }
197
198    #[inline]
199    fn allocate_unchecked(&mut self, car: Value, cdr: Value) -> Result<Cons, Error> {
200        if self.is_out_of_memory() {
201            return Err(Error::OutOfMemory);
202        }
203
204        let cons = Cons::new(self.allocation_end() as u64);
205        self.allocation_index += CONS_FIELD_COUNT;
206
207        assert_heap_cons!(self, cons);
208
209        self.set_raw_car(cons, car);
210        self.set_raw_cdr(cons, cdr);
211
212        debug_assert!(self.allocation_index <= self.space_size());
213
214        Ok(cons)
215    }
216
217    #[inline]
218    const fn is_out_of_memory(&self) -> bool {
219        self.allocation_index >= self.space_size()
220    }
221
222    /// Returns a heap size.
223    #[inline]
224    pub const fn size(&self) -> usize {
225        self.heap.len()
226    }
227
228    #[inline]
229    const fn space_size(&self) -> usize {
230        self.size() / 2
231    }
232
233    /// Returns the current allocation index relative an allocation start index.
234    #[inline]
235    pub const fn allocation_index(&self) -> usize {
236        self.allocation_index
237    }
238
239    /// Returns an allocation start index.
240    #[inline]
241    pub const fn allocation_start(&self) -> usize {
242        if self.space { self.space_size() } else { 0 }
243    }
244
245    /// Returns an allocation end index.
246    #[inline]
247    pub const fn allocation_end(&self) -> usize {
248        self.allocation_start() + self.allocation_index
249    }
250
251    #[inline]
252    const fn get(&self, index: usize) -> Value {
253        assert_heap_access!(self, index);
254        self.heap[index]
255    }
256
257    #[inline]
258    fn set(&mut self, index: usize, value: Value) {
259        assert_heap_access!(self, index);
260        self.heap[index] = value
261    }
262
263    /// Returns a value of a `car` field in a cons.
264    #[inline]
265    pub const fn car(&self, cons: Cons) -> Value {
266        self.get(cons.index())
267    }
268
269    /// Returns a value of a `cdr` field in a cons.
270    #[inline]
271    pub const fn cdr(&self, cons: Cons) -> Value {
272        self.get(cons.index() + 1)
273    }
274
275    #[inline]
276    const fn unchecked_car(&self, cons: Cons) -> Value {
277        self.heap[cons.index()]
278    }
279
280    #[inline]
281    const fn unchecked_cdr(&self, cons: Cons) -> Value {
282        self.heap[cons.index() + 1]
283    }
284
285    /// Returns a value of a `car` field in a value assumed as a cons.
286    #[inline]
287    pub const fn car_value(&self, cons: Value) -> Value {
288        self.car(cons.assume_cons())
289    }
290
291    /// Returns a value of a `cdr` field in a value assumed as a cons.
292    #[inline]
293    pub const fn cdr_value(&self, cons: Value) -> Value {
294        self.cdr(cons.assume_cons())
295    }
296
297    #[inline]
298    fn set_raw_field(&mut self, cons: Cons, index: usize, value: Value) {
299        self.set(cons.index() + index, value);
300    }
301
302    #[inline]
303    fn set_raw_car(&mut self, cons: Cons, value: Value) {
304        self.set_raw_field(cons, 0, value)
305    }
306
307    #[inline]
308    fn set_raw_cdr(&mut self, cons: Cons, value: Value) {
309        self.set_raw_field(cons, 1, value)
310    }
311
312    #[inline]
313    fn set_field(&mut self, cons: Cons, index: usize, value: Value) {
314        self.set_raw_field(
315            cons,
316            index,
317            value.set_tag(self.get(cons.index() + index).tag()),
318        )
319    }
320
321    /// Sets a value to a `car` field in a cons.
322    #[inline]
323    pub fn set_car(&mut self, cons: Cons, value: Value) {
324        self.set_field(cons, 0, value)
325    }
326
327    /// Sets a value to a `cdr` field in a cons.
328    #[inline]
329    pub fn set_cdr(&mut self, cons: Cons, value: Value) {
330        self.set_field(cons, 1, value)
331    }
332
333    #[inline]
334    fn set_unchecked_car(&mut self, cons: Cons, value: Value) {
335        self.heap[cons.index()] = value
336    }
337
338    #[inline]
339    fn set_unchecked_cdr(&mut self, cons: Cons, value: Value) {
340        self.heap[cons.index() + 1] = value;
341    }
342
343    /// Sets a value to a `car` field in a value assumed as a cons.
344    #[inline]
345    pub fn set_car_value(&mut self, cons: Value, value: Value) {
346        self.set_car(cons.assume_cons(), value);
347    }
348
349    /// Sets a value to a `cdr` field in a value assumed as a cons.
350    #[inline]
351    pub fn set_cdr_value(&mut self, cons: Value, value: Value) {
352        self.set_cdr(cons.assume_cons(), value);
353    }
354
355    /// Returns a tail of a list.
356    pub const fn tail(&self, mut list: Cons, mut index: usize) -> Cons {
357        while index > 0 {
358            list = self.cdr(list).assume_cons();
359            index -= 1;
360        }
361
362        list
363    }
364
365    /// Executes an operation against a value at the top of a stack.
366    pub fn operate_top(&mut self, operate: impl Fn(&Self, Value) -> Value) -> Result<(), Error> {
367        let value = self.pop();
368        self.push(operate(self, value))?;
369        Ok(())
370    }
371
372    /// Executes an unary number operation.
373    pub fn operate_unary(&mut self, operate: fn(Number) -> Number) -> Result<(), Error> {
374        let [x] = self.pop_numbers();
375
376        self.push(operate(x).into())?;
377
378        Ok(())
379    }
380
381    /// Executes a binary number operation.
382    pub fn operate_binary(&mut self, operate: fn(Number, Number) -> Number) -> Result<(), Error> {
383        let [x, y] = self.pop_numbers();
384
385        self.push(operate(x, y).into())?;
386
387        Ok(())
388    }
389
390    /// Executes an operation that returns `Option<Value>`.
391    pub fn operate_option(
392        &mut self,
393        mut operate: impl FnMut(&mut Self) -> Option<Value>,
394    ) -> Result<(), Error> {
395        let value = operate(self).unwrap_or_else(|| self.boolean(false).into());
396        self.push(value)?;
397        Ok(())
398    }
399
400    // Garbage collection
401
402    fn collect_garbages(&mut self, cons: Option<&mut Cons>) -> Result<(), Error> {
403        self.allocation_index = 0;
404        self.space = !self.space;
405
406        self.code = self.copy_cons(self.code)?;
407        self.stack = self.copy_cons(self.stack)?;
408        self.r#false = self.copy_cons(self.r#false)?;
409        self.register = self.copy_cons(self.register)?;
410
411        if let Some(cons) = cons {
412            *cons = self.copy_cons(*cons)?;
413        }
414
415        let mut index = self.allocation_start();
416
417        while index < self.allocation_end() {
418            let value = self.copy_value(self.get(index))?;
419            self.set(index, value);
420            index += 1;
421        }
422
423        Ok(())
424    }
425
426    fn copy_value(&mut self, value: Value) -> Result<Value, Error> {
427        Ok(if let Some(cons) = value.to_cons() {
428            self.copy_cons(cons)?.into()
429        } else {
430            value
431        })
432    }
433
434    fn copy_cons(&mut self, cons: Cons) -> Result<Cons, Error> {
435        Ok(if cons.raw_eq(NEVER) {
436            NEVER
437        } else if self.unchecked_car(cons).raw_eq(NEVER.into()) {
438            // Get a forward pointer.
439            self.unchecked_cdr(cons).assume_cons()
440        } else {
441            let copy =
442                self.allocate_unchecked(self.unchecked_car(cons), self.unchecked_cdr(cons))?;
443
444            // Set a forward pointer.
445            self.set_unchecked_car(cons, NEVER.into());
446            self.set_unchecked_cdr(cons, copy.into());
447
448            copy
449        }
450        .set_tag(cons.tag()))
451    }
452}
453
454impl Display for Memory<'_> {
455    fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
456        writeln!(formatter, "code: {}", self.code)?;
457        writeln!(formatter, "stack: {}", self.stack)?;
458
459        for index in 0..self.allocation_index / 2 {
460            let index = self.allocation_start() + 2 * index;
461            let cons = Cons::new(index as u64);
462
463            write!(
464                formatter,
465                "{:02x}: {} {}",
466                index,
467                self.car(cons),
468                self.cdr(cons)
469            )?;
470
471            for (cons, name) in [
472                (self.code, "code"),
473                (self.register, "register"),
474                (self.stack, "stack"),
475            ] {
476                if index == cons.index() && !cons.raw_eq(NEVER) {
477                    write!(formatter, " <- {name}")?;
478                }
479            }
480
481            writeln!(formatter)?;
482        }
483
484        Ok(())
485    }
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491
492    const HEAP_SIZE: usize = 1 << 9;
493
494    fn create_heap() -> [Value; HEAP_SIZE] {
495        [Default::default(); HEAP_SIZE]
496    }
497
498    macro_rules! assert_snapshot {
499        ($memory:expr) => {
500            #[cfg(not(feature = "gc_always"))]
501            insta::assert_snapshot!($memory);
502
503            let _ = $memory;
504        };
505    }
506
507    #[test]
508    fn create() {
509        let mut heap = create_heap();
510        let memory = Memory::new(&mut heap).unwrap();
511
512        assert_snapshot!(memory);
513    }
514
515    #[test]
516    fn create_list() {
517        let mut heap = create_heap();
518        let mut memory = Memory::new(&mut heap).unwrap();
519
520        let list = memory
521            .cons(Number::from_i64(1).into(), memory.null())
522            .unwrap();
523
524        assert_eq!(memory.cdr(list).tag(), Type::Pair as Tag);
525        assert_snapshot!(memory);
526
527        let list = memory.cons(Number::from_i64(2).into(), list).unwrap();
528
529        assert_eq!(memory.cdr(list).tag(), Type::Pair as Tag);
530        assert_snapshot!(memory);
531
532        let list = memory.cons(Number::from_i64(3).into(), list).unwrap();
533
534        assert_eq!(memory.cdr(list).tag(), Type::Pair as Tag);
535        assert_snapshot!(memory);
536    }
537
538    #[test]
539    fn convert_false() {
540        let mut heap = create_heap();
541        let memory = Memory::new(&mut heap).unwrap();
542
543        assert_eq!(
544            Value::from(memory.boolean(false)).to_cons().unwrap(),
545            memory.boolean(false)
546        );
547    }
548
549    #[test]
550    fn convert_true() {
551        let mut heap = create_heap();
552        let memory = Memory::new(&mut heap).unwrap();
553
554        assert_eq!(
555            Value::from(memory.boolean(true)).to_cons().unwrap(),
556            memory.boolean(true)
557        );
558    }
559
560    #[test]
561    fn convert_null() {
562        let mut heap = create_heap();
563        let memory = Memory::new(&mut heap).unwrap();
564
565        assert_eq!(Value::from(memory.null()).to_cons().unwrap(), memory.null());
566    }
567
568    mod stack {
569        use super::*;
570
571        #[test]
572        fn push_and_pop() {
573            let mut heap = create_heap();
574            let mut memory = Memory::new(&mut heap).unwrap();
575
576            memory.stack = memory.null();
577            memory.push(Number::from_i64(42).into()).unwrap();
578
579            assert_eq!(memory.pop(), Number::from_i64(42).into());
580        }
581
582        #[test]
583        fn push_and_pop_twice() {
584            let mut heap = create_heap();
585            let mut memory = Memory::new(&mut heap).unwrap();
586
587            memory.stack = memory.null();
588            memory.push(Number::from_i64(1).into()).unwrap();
589            memory.push(Number::from_i64(2).into()).unwrap();
590
591            assert_eq!(memory.pop(), Number::from_i64(2).into());
592            assert_eq!(memory.pop(), Number::from_i64(1).into());
593        }
594    }
595
596    mod garbage_collection {
597        use super::*;
598
599        #[test]
600        fn collect_cons() {
601            let mut heap = create_heap();
602            let mut memory = Memory::new(&mut heap).unwrap();
603
604            memory
605                .allocate(Number::default().into(), Number::default().into())
606                .unwrap();
607            memory.collect_garbages(None).unwrap();
608
609            assert_snapshot!(memory);
610        }
611
612        #[test]
613        fn collect_stack() {
614            let mut heap = create_heap();
615            let mut memory = Memory::new(&mut heap).unwrap();
616
617            memory.stack = memory.null();
618            memory.push(Number::from_i64(42).into()).unwrap();
619            memory.collect_garbages(None).unwrap();
620
621            assert_snapshot!(memory);
622        }
623
624        #[test]
625        fn collect_deep_stack() {
626            let mut heap = create_heap();
627            let mut memory = Memory::new(&mut heap).unwrap();
628
629            memory.stack = memory.null();
630            memory.push(Number::from_i64(1).into()).unwrap();
631            memory.push(Number::from_i64(2).into()).unwrap();
632            memory.collect_garbages(None).unwrap();
633
634            assert_snapshot!(memory);
635        }
636
637        #[test]
638        fn collect_cycle() {
639            let mut heap = create_heap();
640            let mut memory = Memory::new(&mut heap).unwrap();
641
642            let cons = memory
643                .allocate(Number::default().into(), Number::default().into())
644                .unwrap();
645            memory.set_cdr(cons, cons.into());
646
647            memory.collect_garbages(None).unwrap();
648
649            assert_snapshot!(memory);
650        }
651    }
652}