1#![allow(unused)]
2use std::borrow::Cow;
3use std::convert::{AsMut, AsRef};
4use std::fmt::{Debug, Display, Formatter};
5use std::iter::{Extend, FromIterator, IntoIterator};
6
7use unique_pointer::UniquePointer;
8
9pub mod integer;
10mod macros;
11pub use integer::{AsInteger, Integer};
12pub mod float;
13pub use float::{AsFloat, Float};
14pub mod unsigned_integer;
15use sexprs_util::{dbg, try_result};
16pub use unsigned_integer::{AsUnsignedInteger, UnsignedInteger};
17
18use crate::{AsCell, AsNumber, AsSymbol, Cell, ListIterator, Quotable, Symbol};
19
20pub trait ValueListIterator<'c>: IntoIterator<Item = Value<'c>> + Quotable {}
21pub trait AsValue<'c>: Quotable {
24 fn as_value(&self) -> Value<'c>;
25}
26
27#[derive(Clone, Ord, Default, Eq, Hash, PartialOrd, PartialEq)]
28pub enum Value<'c> {
29 #[default]
30 Nil,
31 T,
32 String(&'c str),
33 Symbol(Symbol<'c>),
34 QuotedSymbol(Symbol<'c>),
35 Byte(u8),
36 UnsignedInteger(UnsignedInteger),
37 Integer(Integer),
38 Float(Float),
39 List(Cell<'c>),
40 QuotedList(Cell<'c>),
41 EmptyList,
42 EmptyQuotedList,
43}
44impl<'c> Value<'c> {
45 pub fn nil() -> Value<'c> {
46 Value::Nil
47 }
48
49 pub fn t() -> Value<'c> {
50 Value::T
51 }
52
53 pub fn symbol<T: AsSymbol<'c>>(sym: T) -> Value<'c> {
54 Value::Symbol(sym.as_symbol().unquote())
55 }
56
57 pub fn quoted_symbol<T: AsSymbol<'c>>(sym: T) -> Value<'c> {
58 Value::QuotedSymbol(sym.as_symbol().quote())
59 }
60
61 pub fn string<T: ToString>(value: T) -> Value<'c> {
62 Value::String(value.to_string().leak())
63 }
64
65 pub fn byte<T: AsNumber<u8>>(byte: T) -> Value<'c> {
66 Value::Byte(byte.as_number())
67 }
68
69 pub fn unsigned_integer<T: AsUnsignedInteger>(value: T) -> Value<'c> {
70 Value::UnsignedInteger(value.as_unsigned_integer())
71 }
72
73 pub fn integer<T: AsInteger>(value: T) -> Value<'c> {
74 Value::Integer(value.as_integer())
75 }
76
77 pub fn float<T: AsFloat>(value: T) -> Value<'c> {
78 Value::Float(value.as_float())
79 }
80
81 pub fn list<T: AsCell<'c>>(item: T) -> Value<'c> {
82 if item.is_quoted() {
83 Value::QuotedList(item.as_cell().quote())
84 } else {
85 Value::List(item.as_cell().unquote())
86 }
87 }
88
89 pub fn quoted_list<T: AsCell<'c>>(item: T) -> Value<'c> {
90 Value::QuotedList(item.as_cell().quote())
91 }
92
93 pub fn is_nil(&self) -> bool {
94 if *self == Value::Nil {
95 true
96 } else {
97 false
98 }
99 }
100
101 pub fn is_empty(&self) -> bool {
102 match self {
103 Value::List(h) => h.is_nil(),
104 Value::QuotedList(h) => h.is_nil(),
105 Value::EmptyList => true,
106 Value::EmptyQuotedList => true,
107 Value::Nil => true,
108 _ => false,
109 }
110 }
111
112 pub fn len(&self) -> usize {
113 match self {
114 Value::List(h) => h.len(),
115 Value::QuotedList(h) => h.len(),
116 Value::EmptyList => 0,
117 Value::EmptyQuotedList => 0,
118 Value::Nil => 0,
119 _ => 0,
120 }
121 }
122
123 pub fn empty_list() -> Value<'c> {
124 Value::EmptyList
125 }
126
127 pub fn empty_quoted_list() -> Value<'c> {
128 Value::EmptyQuotedList
129 }
130
131 pub fn quote(&self) -> Value<'c> {
132 let value = match self {
133 Value::Symbol(h) => Value::QuotedSymbol(h.clone().unquote()),
134 Value::List(h) => Value::QuotedList(h.clone().unquote()),
135 Value::QuotedSymbol(h) => Value::QuotedSymbol(h.clone().quote()),
136 Value::QuotedList(h) => Value::QuotedList(h.clone().quote()),
137 _ => self.clone(),
138 };
139 value.clone()
140 }
141
142 pub fn values(&self) -> Vec<Value<'c>> {
143 match self {
144 Value::List(cell) | Value::QuotedList(cell) => cell.values(),
145 _ => Vec::new(),
146 }
147 }
148
149 pub fn head(&self) -> Value<'c> {
150 match self {
151 Value::List(cell) | Value::QuotedList(cell) => cell.head().unwrap_or_default(),
152 _ => Value::nil(),
153 }
154 }
155
156 pub fn tail(&self) -> Cell<'c> {
157 match self {
158 Value::List(cell) | Value::QuotedList(cell) => {
159 cell.tail().map(Clone::clone).unwrap_or_default()
160 }
161 _ => Cell::nil(),
162 }
163 }
164
165 pub fn wrap_in_list(&self) -> Value<'c> {
166 if self.is_quoted() {
167 Value::QuotedList(Cell::new(self.clone()))
168 } else {
169 Value::List(Cell::new(self.clone()))
170 }
171 }
172
173 pub fn unwrap_list(&self) -> Value<'c> {
174 match self {
175 Value::List(cell) | Value::QuotedList(cell) => {
176 if cell.tail.is_null() {
177 let value = cell.head().unwrap_or_default();
178 value.clone()
179 } else {
180 self.clone()
181 }
182 }
183 _ => self.clone(),
184 }
185 }
186
187 pub fn is_integer(&self) -> bool {
188 match self {
189 Value::Integer(_) => true,
190 _ => false,
191 }
192 }
193
194 pub fn is_unsigned_integer(&self) -> bool {
195 match self {
196 Value::UnsignedInteger(_) => true,
197 _ => false,
198 }
199 }
200
201 pub fn is_float(&self) -> bool {
202 match self {
203 Value::Float(_) => true,
204 _ => false,
205 }
206 }
207
208 pub fn is_string(&self) -> bool {
209 match self {
210 Value::String(_) => true,
211 _ => false,
212 }
213 }
214
215 pub fn is_symbol(&self) -> bool {
216 match self {
217 Value::Symbol(_) => true,
218 Value::QuotedList(_) => true,
219 _ => false,
220 }
221 }
222
223 pub fn is_list(&self) -> bool {
224 match self {
225 Value::List(_) => true,
226 Value::QuotedList(_) => true,
227 _ => false,
228 }
229 }
230}
231
232impl<'c> AsValue<'c> for Value<'c> {
233 fn as_value(&self) -> Value<'c> {
234 self.clone()
235 }
236}
237impl<'c> AsValue<'c> for &Value<'c> {
238 fn as_value(&self) -> Value<'c> {
239 UniquePointer::read_only(*self).read()
240 }
241}
242
243impl<'c> Drop for Value<'c> {
244 fn drop(&mut self) {}
245}
246
247impl Debug for Value<'_> {
248 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
249 write!(f, "{}", self)
250 }
251}
252impl Display for Value<'_> {
253 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
254 write!(
255 f,
256 "{}",
257 match self {
258 Value::T => "t".to_string(),
259 Value::Nil => "nil".to_string(),
260 Value::Byte(h) => format!("0x{:02x}", h),
261 Value::Float(h) => format!("{}", h),
262 Value::Integer(h) => format!("{}", h),
263 Value::String(h) => format!("{:#?}", h),
264 Value::Symbol(h) => format!("{}", h),
265 Value::QuotedSymbol(h) => format!("'{}", h),
266 Value::UnsignedInteger(h) => format!("{}", h),
267 Value::List(h) => {
268 if h.is_nil() {
269 format!("()")
270 } else {
271 format!("({})", h)
272 }
273 }
274 Value::QuotedList(h) => {
275 if h.is_nil() {
276 format!("'()")
277 } else {
278 format!("'({})", h)
279 }
280 }
281 Value::EmptyList => format!("()"),
282 Value::EmptyQuotedList => format!("'()"),
283 }
284 )
285 }
286}
287impl<'c> From<()> for Value<'c> {
288 fn from(_: ()) -> Value<'c> {
289 Value::Nil
290 }
291}
292impl<'c> Into<bool> for &Value<'c> {
293 fn into(self) -> bool {
294 !self.is_empty()
295 }
296}
297impl<'c> Into<bool> for Value<'c> {
298 fn into(self) -> bool {
299 !self.is_empty()
300 }
301}
302impl<'c> From<bool> for Value<'c> {
303 fn from(value: bool) -> Value<'c> {
304 if value {
305 Value::T
306 } else {
307 Value::Nil
308 }
309 }
310}
311impl<'c> From<u8> for Value<'c> {
312 fn from(value: u8) -> Value<'c> {
313 Value::Byte(value)
314 }
315}
316impl<'c> From<Symbol<'c>> for Value<'c> {
317 fn from(value: Symbol<'c>) -> Value<'c> {
318 if value.is_quoted() {
319 Value::quoted_symbol(value.quote())
320 } else {
321 Value::symbol(value.unquote())
322 }
323 }
324}
325impl<'c> From<&Symbol<'c>> for Value<'c> {
326 fn from(value: &Symbol<'c>) -> Value<'c> {
327 if value.is_quoted() {
328 Value::quoted_symbol(value.quote())
329 } else {
330 Value::symbol(value.unquote())
331 }
332 }
333}
334impl<'c> From<&'c str> for Value<'c> {
335 fn from(value: &'c str) -> Value<'c> {
336 Value::String(value.to_string().leak())
337 }
338}
339impl<'c> From<u64> for Value<'c> {
340 fn from(value: u64) -> Value<'c> {
341 if value < u8::MAX.into() {
342 Value::Byte(value as u8)
343 } else {
344 Value::UnsignedInteger(value.into())
345 }
346 }
347}
348impl<'c> From<i32> for Value<'c> {
349 fn from(value: i32) -> Value<'c> {
350 if let Ok(value) = TryInto::<u64>::try_into(value) {
351 Value::UnsignedInteger(value.into())
352 } else {
353 Value::Integer(value.into())
354 }
355 }
356}
357
358impl<'c> From<Cow<'c, str>> for Value<'c> {
359 fn from(value: Cow<'c, str>) -> Value<'c> {
360 Value::from(value.into_owned().to_string().leak())
361 }
362}
363impl<'c> From<&'c mut str> for Value<'c> {
364 fn from(value: &'c mut str) -> Value<'c> {
365 Value::String(value.to_string().leak())
366 }
367}
368impl<'c> From<String> for Value<'c> {
369 fn from(value: String) -> Value<'c> {
370 Value::String(value.leak())
371 }
372}
373impl<'c> From<Option<String>> for Value<'c> {
374 fn from(value: Option<String>) -> Value<'c> {
375 match value {
376 None => Value::Nil,
377 Some(value) => Value::from(value),
378 }
379 }
380}
381impl<'c> From<Cell<'c>> for Value<'c> {
382 fn from(cell: Cell<'c>) -> Value<'c> {
383 let is_quoted = cell.is_quoted();
384 let value = cell.as_value();
385 if is_quoted {
386 value.quote()
387 } else {
388 value
389 }
390 }
391}
392impl<'c> AsRef<Value<'c>> for Value<'c> {
399 fn as_ref(&self) -> &Value<'c> {
400 &*self
401 }
402}
403impl<'c> AsMut<Value<'c>> for Value<'c> {
404 fn as_mut(&mut self) -> &mut Value<'c> {
405 &mut *self
406 }
407}
408
409impl<'c> PartialEq<&Value<'c>> for Value<'c> {
410 fn eq(&self, other: &&Value<'c>) -> bool {
411 let other = &**other;
412 self == other
413 }
414}
415impl<'c> PartialEq<Option<Value<'c>>> for Value<'c> {
416 fn eq(&self, other: &Option<Value<'c>>) -> bool {
417 match other {
418 Some(value) => value.eq(self),
419 None => Value::Nil == self,
420 }
421 }
422}
423impl<'c> PartialEq<Cell<'c>> for Value<'c> {
424 fn eq(&self, other: &Cell<'c>) -> bool {
425 other.as_value() == self
426 }
427}
428impl<'c> PartialEq<&mut Value<'c>> for Value<'c> {
435 fn eq(&self, other: &&mut Value<'c>) -> bool {
436 let other = &**other;
437 self == other
438 }
439}
440
441impl<'c> AsValue<'c> for () {
442 fn as_value(&self) -> Value<'c> {
443 Value::Nil
444 }
445}
446impl<'c> AsValue<'c> for bool {
447 fn as_value(&self) -> Value<'c> {
448 if *self {
449 Value::T
450 } else {
451 Value::Nil
452 }
453 }
454}
455impl<'c> AsValue<'c> for u8 {
456 fn as_value(&self) -> Value<'c> {
457 Value::Byte(*self)
458 }
459}
460impl<'c> AsValue<'c> for &'c str {
466 fn as_value(&self) -> Value<'c> {
467 Value::String(self.to_string().leak())
468 }
469}
470impl<'c> AsValue<'c> for u64 {
471 fn as_value(&self) -> Value<'c> {
472 if *self < u8::MAX.into() {
473 Value::Byte(*self as u8)
474 } else {
475 Value::UnsignedInteger(self.as_unsigned_integer())
476 }
477 }
478}
479impl<'c> AsValue<'c> for i32 {
480 fn as_value(&self) -> Value<'c> {
481 if let Ok(value) = TryInto::<u64>::try_into(*self) {
482 Value::UnsignedInteger(value.as_unsigned_integer())
483 } else {
484 Value::Integer(self.as_integer())
485 }
486 }
487}
488
489impl<'c> AsValue<'c> for Cow<'c, str> {
490 fn as_value(&self) -> Value<'c> {
491 Value::from(self.clone().into_owned().to_string().leak())
492 }
493}
494impl<'c> AsValue<'c> for &'c mut str {
495 fn as_value(&self) -> Value<'c> {
496 Value::String(self.to_string().leak())
497 }
498}
499impl<'c> AsValue<'c> for String {
500 fn as_value(&self) -> Value<'c> {
501 Value::String(self.to_string().leak())
502 }
503}
504impl<'c> AsValue<'c> for Option<String> {
505 fn as_value(&self) -> Value<'c> {
506 match self.clone() {
507 None => Value::Nil,
508 Some(value) => Value::from(value),
509 }
510 }
511}
512
513impl<'c> AsCell<'c> for Value<'c> {
514 fn as_cell(&self) -> Cell<'c> {
515 match self {
516 Value::Symbol(h) => Cell::quoted(Some(h.unquote()), false),
517 Value::QuotedSymbol(h) => Cell::quoted(Some(h.quote()), true),
518 Value::List(h) => {
519 let mut cell = Cell::nil();
520 for item in h.clone().into_iter() {
521 cell.add(&Cell::new(item));
522 }
523 cell
524 }
525 Value::QuotedList(h) => {
526 let mut cell = Cell::nil();
527 for item in h.clone().into_iter() {
528 cell.add(&Cell::new(item));
529 }
530 cell.quote()
531 }
532 _ => Cell::new(self.clone()),
533 }
534 }
535}
536impl<'c> AsCell<'c> for &Value<'c> {
537 fn as_cell(&self) -> Cell<'c> {
538 let value = UniquePointer::read_only(*self).read();
539 value.as_cell()
540 }
541}
542
543impl<'c> ListIterator<'c, Value<'c>> for Value<'c> {
544 fn iter_cells(&self) -> Cell<'c> {
545 match self {
546 Value::List(cell) | Value::QuotedList(cell) => cell.clone(),
547 _ => Cell::from(self.clone()),
548 }
549 }
550}
551impl<'c> ListIterator<'c, Value<'c>> for &Value<'c> {
552 fn iter_cells(&self) -> Cell<'c> {
553 match self {
554 Value::List(cell) | Value::QuotedList(cell) => cell.clone(),
555 _ => Cell::from(*self),
556 }
557 }
558}
559
560#[derive(Debug, Clone)]
561pub struct ValueIterator<'c> {
562 cell: UniquePointer<Cell<'c>>,
563 quoted: bool,
564}
565
566impl<'c> ValueIterator<'c> {
567 pub fn new(cell: &Cell<'c>, quoted: bool) -> ValueIterator<'c> {
568 ValueIterator {
569 cell: UniquePointer::from_ref(cell),
570 quoted,
571 }
572 }
573
574 pub fn item(&self) -> Option<&Cell<'c>> {
575 self.cell.as_ref()
576 }
577
578 pub fn tail(&self) -> Option<&Cell<'c>> {
579 if let Some(cell) = self.cell.as_ref() {
580 cell.tail()
581 } else {
582 None
583 }
584 }
585}
586impl<'c> Iterator for ValueIterator<'c> {
587 type Item = Value<'c>;
588
589 fn next(&mut self) -> Option<Self::Item> {
590 if self.cell.is_not_null() {
591 let value = self.cell.inner_ref().head();
592 let next_tail = self.cell.inner_ref().tail.clone();
593 self.cell = next_tail;
594 value
595 } else {
596 None
597 }
598 }
599}
600impl<'c> Quotable for ValueIterator<'c> {
601 fn is_quoted(&self) -> bool {
602 self.quoted
603 }
604
605 fn set_quoted(&mut self, quoted: bool) {
606 self.quoted = quoted;
607 }
608}
609impl<'c> ValueListIterator<'c> for ValueIterator<'c> {}
610
611impl<'c> IntoIterator for &Value<'c> {
612 type IntoIter = ValueIterator<'c>;
613 type Item = Value<'c>;
614
615 fn into_iter(self) -> Self::IntoIter {
616 let cell = match self.clone() {
617 Value::List(ref cell) | Value::QuotedList(ref cell) => cell.clone(),
618 Value::EmptyList | Value::EmptyQuotedList => Cell::nil(),
619 ref value => Cell::from(value),
620 };
621 let cell = if self.is_quoted() { cell.quote() } else { cell };
622 ValueIterator::new(&cell, self.is_quoted())
623 }
624}
625impl<'c> IntoIterator for Value<'c> {
626 type IntoIter = ValueIterator<'c>;
627 type Item = Value<'c>;
628
629 fn into_iter(self) -> Self::IntoIter {
630 let cell = match &self {
631 Value::List(cell) | Value::QuotedList(cell) => cell.clone(),
632 Value::EmptyList | Value::EmptyQuotedList => Cell::nil(),
633 value => Cell::from(value),
634 };
635 let cell = if self.is_quoted() { cell.quote() } else { cell };
636 ValueIterator::new(&cell, self.is_quoted())
637 }
638}
639
640impl<'c> FromIterator<Value<'c>> for Value<'c> {
641 fn from_iter<I: IntoIterator<Item = Value<'c>>>(iter: I) -> Value<'c> {
642 let mut cell = Cell::nil();
643 for value in iter {
644 cell.push_value(value);
645 }
646 Value::list(cell)
647 }
648}
649impl<'c> Extend<Value<'c>> for Value<'c> {
650 fn extend<T: IntoIterator<Item = Value<'c>>>(&mut self, iter: T) {
651 if let Value::List(cell) = self {
652 for value in iter {
653 cell.push_value(value);
654 }
655 } else if let Value::QuotedList(cell) = self {
656 for value in iter {
657 cell.push_value(value);
658 }
659 } else {
660 match self.clone() {
661 Value::EmptyList => {
662 let mut cell = Cell::nil();
663 for value in iter {
664 cell.push_value(value)
665 }
666 *self = Value::List(cell)
667 }
668 Value::EmptyQuotedList => {
669 let mut cell = Cell::nil();
670 for value in iter {
671 cell.push_value(value)
672 }
673 *self = Value::QuotedList(cell)
674 }
675 value => {
676 let mut cell = Cell::nil();
677 for value in iter {
678 cell.push_value(value)
679 }
680 *self = Value::List(cell)
681 }
682 }
683 }
684 }
685}
686
687impl<'c> Quotable for Value<'c> {
700 fn set_quoted(&mut self, quoted: bool) {
701 match self {
702 Value::Symbol(h) => {
703 if quoted {
704 *self = Value::QuotedSymbol(h.clone())
705 }
706 }
707 Value::List(h) => {
708 if quoted {
709 *self = Value::QuotedList(h.clone())
710 }
711 }
712 Value::QuotedSymbol(h) => {
713 if !quoted {
714 *self = Value::Symbol(h.clone())
715 }
716 }
717 Value::QuotedList(h) => {
718 if !quoted {
719 *self = Value::List(h.clone())
720 }
721 }
722 Value::EmptyList => {
723 if quoted {
724 *self = Value::EmptyList
725 }
726 }
727 Value::EmptyQuotedList => {
728 if quoted {
729 *self = Value::EmptyQuotedList
730 }
731 }
732 _ => {}
733 }
734 }
735
736 fn is_quoted(&self) -> bool {
737 match self {
738 Value::Symbol(h) => false,
739 Value::List(h) => false,
740 Value::QuotedSymbol(h) => true,
741 Value::QuotedList(h) => true,
742 Value::EmptyQuotedList => true,
743 _ => false,
744 }
745 }
746}
747
748impl<'c> AsSymbol<'c> for &Value<'c> {
749 fn as_symbol(&self) -> Symbol<'c> {
750 match self {
751 Value::Symbol(symbol) => symbol.clone(),
752 Value::QuotedSymbol(symbol) => symbol.clone(),
753 value => {
754 panic!("cannot convert {:#?} to symbol", self)
755 }
756 }
757 }
758
759 fn is_symbol(&self) -> bool {
760 match self {
761 Value::Symbol(symbol) | Value::QuotedSymbol(symbol) => true,
762 _ => false,
763 }
764 }
765}
766
767impl<'c> AsSymbol<'c> for Value<'c> {
768 fn as_symbol(&self) -> Symbol<'c> {
769 match self {
770 Value::Symbol(symbol) => symbol.clone(),
771 Value::QuotedSymbol(symbol) => symbol.clone(),
772 value => {
773 panic!("cannot convert {:#?} to symbol", self)
774 }
775 }
776 }
777
778 fn is_symbol(&self) -> bool {
779 match self {
780 Value::Symbol(symbol) | Value::QuotedSymbol(symbol) => true,
781 _ => false,
782 }
783 }
784}
785
786impl<'c> AsFloat for Value<'c> {
787 fn as_float(&self) -> Float {
788 match self {
789 Value::Float(float) => *float,
790 value => {
791 panic!("cannot convert {:#?} to float", self)
792 }
793 }
794 }
795}
796
797impl<'c> AsInteger for Value<'c> {
798 fn as_integer(&self) -> Integer {
799 match self {
800 Value::Integer(integer) => *integer,
801 value => {
802 panic!("cannot convert {:#?} to integer", self)
803 }
804 }
805 }
806}
807
808impl<'c> AsUnsignedInteger for Value<'c> {
809 fn as_unsigned_integer(&self) -> UnsignedInteger {
810 match self {
811 Value::UnsignedInteger(unsigned_integer) => *unsigned_integer,
812 value => {
813 panic!("cannot convert {:#?} to unsigned integer", self)
814 }
815 }
816 }
817}
818
819impl<'c> AsNumber<f64> for Value<'c> {
820 fn as_number(&self) -> f64 {
821 *self.as_float()
822 }
823}
824
825impl<'c> AsNumber<i64> for Value<'c> {
826 fn as_number(&self) -> i64 {
827 *self.as_integer()
828 }
829}
830
831impl<'c> AsNumber<u32> for Value<'c> {
832 fn as_number(&self) -> u32 {
833 *self.as_unsigned_integer()
834 }
835}
836
837