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, Write};
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
38pub 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 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 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 #[inline]
71 pub const fn code(&self) -> Cons {
72 self.code
73 }
74
75 #[inline]
77 pub const fn set_code(&mut self, value: Cons) {
78 self.code = value;
79 }
80
81 #[inline]
83 pub const fn register(&self) -> Cons {
84 self.register
85 }
86
87 #[inline]
89 pub const fn set_register(&mut self, value: Cons) {
90 self.register = value;
91 }
92
93 #[inline]
95 pub const fn stack(&self) -> Cons {
96 self.stack
97 }
98
99 #[inline]
101 pub const fn set_stack(&mut self, value: Cons) {
102 self.stack = value;
103 }
104
105 #[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 #[inline]
117 pub const fn null(&self) -> Cons {
118 self.car(self.r#false).assume_cons()
119 }
120
121 #[inline]
123 pub(crate) const fn set_false(&mut self, cons: Cons) {
124 self.r#false = cons;
125 }
126
127 #[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 #[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 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 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 #[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 #[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 #[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 #[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 #[inline]
235 pub const fn allocation_index(&self) -> usize {
236 self.allocation_index
237 }
238
239 #[inline]
241 pub const fn allocation_start(&self) -> usize {
242 if self.space { self.space_size() } else { 0 }
243 }
244
245 #[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 #[inline]
265 pub const fn car(&self, cons: Cons) -> Value {
266 self.get(cons.index())
267 }
268
269 #[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 #[inline]
287 pub const fn car_value(&self, cons: Value) -> Value {
288 self.car(cons.assume_cons())
289 }
290
291 #[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 #[inline]
323 pub fn set_car(&mut self, cons: Cons, value: Value) {
324 self.set_field(cons, 0, value)
325 }
326
327 #[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 #[inline]
345 pub fn set_car_value(&mut self, cons: Value, value: Value) {
346 self.set_car(cons.assume_cons(), value);
347 }
348
349 #[inline]
351 pub fn set_cdr_value(&mut self, cons: Value, value: Value) {
352 self.set_cdr(cons.assume_cons(), value);
353 }
354
355 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 pub fn build_string(&mut self, string: &str) -> Result<Cons, Error> {
367 let string = self.build_raw_string(string)?;
368 let length = Number::from_i64(self.list_length(string) as _).into();
369 self.allocate(length, string.set_tag(Type::String as _).into())
370 }
371
372 pub fn build_raw_string(&mut self, string: &str) -> Result<Cons, Error> {
374 let mut list = self.null();
375 self.build_intermediate_string(string, &mut list)?;
376 Ok(list)
377 }
378
379 fn build_intermediate_string(&mut self, string: &str, list: &mut Cons) -> Result<(), Error> {
380 for character in string.chars().rev() {
381 *list = self.cons(Number::from_i64(character as _).into(), *list)?;
382 }
383
384 Ok(())
385 }
386
387 pub fn operate_top(&mut self, operate: impl Fn(&Self, Value) -> Value) -> Result<(), Error> {
389 let value = self.pop();
390 self.push(operate(self, value))?;
391 Ok(())
392 }
393
394 pub fn list_length(&self, mut list: Cons) -> usize {
396 let mut length = 0;
397
398 while list != self.null() {
399 length += 1;
400 list = self.cdr(list).assume_cons();
401 }
402
403 length
404 }
405
406 pub fn operate_unary(&mut self, operate: fn(Number) -> Number) -> Result<(), Error> {
408 let [x] = self.pop_numbers();
409
410 self.push(operate(x).into())?;
411
412 Ok(())
413 }
414
415 pub fn operate_binary(&mut self, operate: fn(Number, Number) -> Number) -> Result<(), Error> {
417 let [x, y] = self.pop_numbers();
418
419 self.push(operate(x, y).into())?;
420
421 Ok(())
422 }
423
424 fn collect_garbages(&mut self, cons: Option<&mut Cons>) -> Result<(), Error> {
427 self.allocation_index = 0;
428 self.space = !self.space;
429
430 self.code = self.copy_cons(self.code)?;
431 self.stack = self.copy_cons(self.stack)?;
432 self.r#false = self.copy_cons(self.r#false)?;
433 self.register = self.copy_cons(self.register)?;
434
435 if let Some(cons) = cons {
436 *cons = self.copy_cons(*cons)?;
437 }
438
439 let mut index = self.allocation_start();
440
441 while index < self.allocation_end() {
442 let value = self.copy_value(self.get(index))?;
443 self.set(index, value);
444 index += 1;
445 }
446
447 Ok(())
448 }
449
450 fn copy_value(&mut self, value: Value) -> Result<Value, Error> {
451 Ok(if let Some(cons) = value.to_cons() {
452 self.copy_cons(cons)?.into()
453 } else {
454 value
455 })
456 }
457
458 fn copy_cons(&mut self, cons: Cons) -> Result<Cons, Error> {
459 Ok(if cons.raw_eq(NEVER) {
460 NEVER
461 } else if self.unchecked_car(cons).raw_eq(NEVER.into()) {
462 self.unchecked_cdr(cons).assume_cons()
464 } else {
465 let copy =
466 self.allocate_unchecked(self.unchecked_car(cons), self.unchecked_cdr(cons))?;
467
468 self.set_unchecked_car(cons, NEVER.into());
470 self.set_unchecked_cdr(cons, copy.into());
471
472 copy
473 }
474 .set_tag(cons.tag()))
475 }
476}
477
478impl Write for Memory<'_> {
479 fn write_str(&mut self, string: &str) -> fmt::Result {
480 let mut list = self.null();
481 self.build_intermediate_string(string, &mut list)
482 .map_err(|_| fmt::Error)?;
483
484 if self.register() == self.null() {
485 self.set_register(list);
486 } else {
487 let mut head = self.register();
488
489 while self.cdr(head) != self.null().into() {
490 head = self.cdr(head).assume_cons();
491 }
492
493 self.set_cdr(head, list.into());
494 }
495
496 Ok(())
497 }
498}
499
500impl Display for Memory<'_> {
501 fn fmt(&self, formatter: &mut Formatter) -> fmt::Result {
502 writeln!(formatter, "code: {}", self.code)?;
503 writeln!(formatter, "stack: {}", self.stack)?;
504
505 for index in 0..self.allocation_index / 2 {
506 let index = self.allocation_start() + 2 * index;
507 let cons = Cons::new(index as u64);
508
509 write!(
510 formatter,
511 "{:02x}: {} {}",
512 index,
513 self.car(cons),
514 self.cdr(cons)
515 )?;
516
517 for (cons, name) in [
518 (self.code, "code"),
519 (self.register, "register"),
520 (self.stack, "stack"),
521 ] {
522 if index == cons.index() && !cons.raw_eq(NEVER) {
523 write!(formatter, " <- {name}")?;
524 }
525 }
526
527 writeln!(formatter)?;
528 }
529
530 Ok(())
531 }
532}
533
534#[cfg(test)]
535mod tests {
536 use super::*;
537
538 const HEAP_SIZE: usize = 1 << 9;
539
540 fn create_heap() -> [Value; HEAP_SIZE] {
541 [Default::default(); HEAP_SIZE]
542 }
543
544 macro_rules! assert_snapshot {
545 ($memory:expr) => {
546 #[cfg(not(feature = "gc_always"))]
547 insta::assert_snapshot!($memory);
548
549 let _ = $memory;
550 };
551 }
552
553 #[test]
554 fn create() {
555 let mut heap = create_heap();
556 let memory = Memory::new(&mut heap).unwrap();
557
558 assert_snapshot!(memory);
559 }
560
561 #[test]
562 fn create_list() {
563 let mut heap = create_heap();
564 let mut memory = Memory::new(&mut heap).unwrap();
565
566 let list = memory
567 .cons(Number::from_i64(1).into(), memory.null())
568 .unwrap();
569
570 assert_eq!(memory.cdr(list).tag(), Type::Pair as Tag);
571 assert_snapshot!(memory);
572
573 let list = memory.cons(Number::from_i64(2).into(), list).unwrap();
574
575 assert_eq!(memory.cdr(list).tag(), Type::Pair as Tag);
576 assert_snapshot!(memory);
577
578 let list = memory.cons(Number::from_i64(3).into(), list).unwrap();
579
580 assert_eq!(memory.cdr(list).tag(), Type::Pair as Tag);
581 assert_snapshot!(memory);
582 }
583
584 #[test]
585 fn convert_false() {
586 let mut heap = create_heap();
587 let memory = Memory::new(&mut heap).unwrap();
588
589 assert_eq!(
590 Value::from(memory.boolean(false)).to_cons().unwrap(),
591 memory.boolean(false)
592 );
593 }
594
595 #[test]
596 fn convert_true() {
597 let mut heap = create_heap();
598 let memory = Memory::new(&mut heap).unwrap();
599
600 assert_eq!(
601 Value::from(memory.boolean(true)).to_cons().unwrap(),
602 memory.boolean(true)
603 );
604 }
605
606 #[test]
607 fn convert_null() {
608 let mut heap = create_heap();
609 let memory = Memory::new(&mut heap).unwrap();
610
611 assert_eq!(Value::from(memory.null()).to_cons().unwrap(), memory.null());
612 }
613
614 fn assert_raw_string(memory: &Memory, mut cons: Cons, string: &str) {
615 for character in string.chars() {
616 assert_eq!(memory.car(cons).assume_number().to_i64(), character as _);
617 cons = memory.cdr(cons).assume_cons();
618 }
619
620 assert_eq!(cons, memory.null());
621 }
622
623 #[test]
624 fn build_string() {
625 let mut heap = create_heap();
626 let mut memory = Memory::new(&mut heap).unwrap();
627
628 let string = memory.build_string("foo").unwrap();
629
630 assert_eq!(memory.car(string), Number::from_i64(3).into());
631 assert_eq!(memory.cdr(string).tag(), Type::String as _);
632 assert_raw_string(&memory, memory.cdr(string).assume_cons(), "foo");
633 }
634
635 #[test]
636 fn format_string() {
637 let mut heap = create_heap();
638 let mut memory = Memory::new(&mut heap).unwrap();
639
640 memory.set_register(memory.null());
641
642 memory.write_str("foo").unwrap();
643
644 assert_raw_string(&memory, memory.register(), "foo");
645 }
646
647 #[test]
648 fn format_two_strings() {
649 let mut heap = create_heap();
650 let mut memory = Memory::new(&mut heap).unwrap();
651
652 memory.set_register(memory.null());
653
654 memory.write_str("foo").unwrap();
655 memory.write_str("bar").unwrap();
656
657 assert_raw_string(&memory, memory.register(), "foobar");
658 }
659
660 #[test]
661 fn format_templated_string() {
662 const FOO: usize = 42;
663
664 let mut heap = create_heap();
665 let mut memory = Memory::new(&mut heap).unwrap();
666
667 memory.set_register(memory.null());
668
669 write!(&mut memory, "foo{FOO}bar").unwrap();
670
671 assert_raw_string(&memory, memory.register(), "foo42bar");
672 }
673
674 mod stack {
675 use super::*;
676
677 #[test]
678 fn push_and_pop() {
679 let mut heap = create_heap();
680 let mut memory = Memory::new(&mut heap).unwrap();
681
682 memory.stack = memory.null();
683 memory.push(Number::from_i64(42).into()).unwrap();
684
685 assert_eq!(memory.pop(), Number::from_i64(42).into());
686 }
687
688 #[test]
689 fn push_and_pop_twice() {
690 let mut heap = create_heap();
691 let mut memory = Memory::new(&mut heap).unwrap();
692
693 memory.stack = memory.null();
694 memory.push(Number::from_i64(1).into()).unwrap();
695 memory.push(Number::from_i64(2).into()).unwrap();
696
697 assert_eq!(memory.pop(), Number::from_i64(2).into());
698 assert_eq!(memory.pop(), Number::from_i64(1).into());
699 }
700 }
701
702 mod garbage_collection {
703 use super::*;
704
705 #[test]
706 fn collect_cons() {
707 let mut heap = create_heap();
708 let mut memory = Memory::new(&mut heap).unwrap();
709
710 memory
711 .allocate(Number::default().into(), Number::default().into())
712 .unwrap();
713 memory.collect_garbages(None).unwrap();
714
715 assert_snapshot!(memory);
716 }
717
718 #[test]
719 fn collect_stack() {
720 let mut heap = create_heap();
721 let mut memory = Memory::new(&mut heap).unwrap();
722
723 memory.stack = memory.null();
724 memory.push(Number::from_i64(42).into()).unwrap();
725 memory.collect_garbages(None).unwrap();
726
727 assert_snapshot!(memory);
728 }
729
730 #[test]
731 fn collect_deep_stack() {
732 let mut heap = create_heap();
733 let mut memory = Memory::new(&mut heap).unwrap();
734
735 memory.stack = memory.null();
736 memory.push(Number::from_i64(1).into()).unwrap();
737 memory.push(Number::from_i64(2).into()).unwrap();
738 memory.collect_garbages(None).unwrap();
739
740 assert_snapshot!(memory);
741 }
742
743 #[test]
744 fn collect_cycle() {
745 let mut heap = create_heap();
746 let mut memory = Memory::new(&mut heap).unwrap();
747
748 let cons = memory
749 .allocate(Number::default().into(), Number::default().into())
750 .unwrap();
751 memory.set_cdr(cons, cons.into());
752
753 memory.collect_garbages(None).unwrap();
754
755 assert_snapshot!(memory);
756 }
757 }
758}