-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbool.rs
More file actions
100 lines (78 loc) · 2.47 KB
/
Copy pathbool.rs
File metadata and controls
100 lines (78 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use std::any::Any;
use std::fmt;
use std::sync::{Arc, RwLock};
use once_cell::sync::Lazy;
use crate::vm::{RuntimeBoolResult, RuntimeErr};
use super::gen;
use super::new;
use super::base::{ObjectRef, ObjectTrait, TypeRef, TypeTrait};
use super::class::TYPE_TYPE;
use super::ns::Namespace;
// Bool Type -----------------------------------------------------------
gen::type_and_impls!(BoolType, Bool);
pub static BOOL_TYPE: Lazy<gen::obj_ref_t!(BoolType)> =
Lazy::new(|| gen::obj_ref!(BoolType::new()));
// Bool Object ---------------------------------------------------------
pub struct Bool {
ns: Namespace,
value: bool,
}
gen::standard_object_impls!(Bool);
impl Bool {
pub fn new(value: bool) -> Self {
Self { ns: Namespace::default(), value }
}
pub fn value(&self) -> &bool {
&self.value
}
}
impl ObjectTrait for Bool {
gen::object_trait_header!(BOOL_TYPE);
// Unary operations -----------------------------------------------
fn bool_val(&self) -> RuntimeBoolResult {
Ok(*self.value())
}
// Binary operations -----------------------------------------------
fn is_equal(&self, rhs: &dyn ObjectTrait) -> bool {
if self.is(rhs) || rhs.is_always() {
true
} else if let Some(rhs) = rhs.down_to_bool() {
self.value() == rhs.value()
} else {
false
}
}
fn and(&self, rhs: &dyn ObjectTrait) -> RuntimeBoolResult {
if let Some(rhs) = rhs.down_to_bool() {
Ok(*self.value() && *rhs.value())
} else {
Err(RuntimeErr::type_err(format!(
"{} && {} not implemented",
self.class().read().unwrap(),
rhs.class().read().unwrap(),
)))
}
}
fn or(&self, rhs: &dyn ObjectTrait) -> RuntimeBoolResult {
if let Some(rhs) = rhs.down_to_bool() {
Ok(*self.value() || *rhs.value())
} else {
Err(RuntimeErr::type_err(format!(
"{} || {} not implemented",
self.class().read().unwrap(),
rhs.class().read().unwrap(),
)))
}
}
}
// Display -------------------------------------------------------------
impl fmt::Display for Bool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.value)
}
}
impl fmt::Debug for Bool {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self}")
}
}