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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
pub mod functio;

mod coercions;
mod ops;

pub use functio::Functio;

use std::{
    cell::{Ref, RefCell, RefMut},
    collections::HashMap,
    fmt::Display,
    hash::Hash,
    io::Write,
    mem::discriminant,
    rc::Rc,
};

pub type Cart = HashMap<Value, ValueRef>;

/// AbleScript Value
#[derive(Debug, Default, Clone)]
pub enum Value {
    #[default]
    Nul,
    Undefined,
    Str(String),
    Int(isize),
    Abool(Abool),
    Functio(Functio),
    Cart(Cart),
}

impl Hash for Value {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        discriminant(self).hash(state);
        match self {
            Value::Nul | Value::Undefined => (),
            Value::Str(v) => v.hash(state),
            Value::Int(v) => v.hash(state),
            Value::Abool(v) => v.to_string().hash(state),
            Value::Functio(statements) => statements.hash(state),
            Value::Cart(_) => self.to_string().hash(state),
        }
    }
}

impl Value {
    /// Write an AbleScript value to a Brainfuck input stream by
    /// coercing the value to an integer, then truncating that integer
    /// to a single byte, then writing that byte. This should only be
    /// called on `Write`rs that cannot fail, e.g., `Vec<u8>`, because
    /// any IO errors will cause a panic.
    pub fn bf_write(&self, stream: &mut impl Write) {
        stream
            .write_all(&[self.clone().into_isize() as u8])
            .expect("Failed to write to Brainfuck input");
    }
}

/// Three-state logic value
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)]
pub enum Abool {
    Never = -1,
    Sometimes = 0,
    Always = 1,
}

impl Abool {
    pub fn to_bool(&self) -> bool {
        match self {
            Self::Always => true,
            Self::Sometimes if rand::random() => true,
            _ => false,
        }
    }
}

impl Display for Abool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Abool::Never => write!(f, "never"),
            Abool::Sometimes => write!(f, "sometimes"),
            Abool::Always => write!(f, "always"),
        }
    }
}

impl From<bool> for Abool {
    fn from(b: bool) -> Self {
        if b {
            Abool::Always
        } else {
            Abool::Never
        }
    }
}

impl Display for Value {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Value::Nul => write!(f, "nul"),
            Value::Undefined => write!(f, "undefined"),
            Value::Str(v) => write!(f, "{}", v),
            Value::Int(v) => write!(f, "{}", v),
            Value::Abool(v) => write!(f, "{}", v),
            Value::Functio(v) => match v {
                Functio::Bf {
                    instructions,
                    tape_len,
                } => {
                    write!(
                        f,
                        "({}) {}",
                        tape_len,
                        String::from_utf8(instructions.to_owned())
                            .expect("Brainfuck functio source should be UTF-8")
                    )
                }
                Functio::Able { params, body } => {
                    write!(
                        f,
                        "({}) -> {:?}",
                        params.join(", "),
                        // Maybe we should have a pretty-printer for
                        // statement blocks at some point?
                        body,
                    )
                }
                Functio::Builtin(b) => write!(f, "builtin @ {}", b.fn_addr()),
                Functio::Chain { functios, kind } => {
                    let (a, b) = *functios.clone();
                    write!(
                        f,
                        "{} {} {} ",
                        Value::Functio(a),
                        match kind {
                            functio::FunctioChainKind::Equal => '+',
                            functio::FunctioChainKind::ByArity => '*',
                        },
                        Value::Functio(b)
                    )
                }
                Functio::Eval(s) => write!(f, "{}", s),
            },
            Value::Cart(c) => {
                write!(f, "[")?;
                let mut cart_vec = c.iter().collect::<Vec<_>>();
                cart_vec.sort_by(|x, y| x.0.partial_cmp(y.0).unwrap_or(std::cmp::Ordering::Less));

                for (idx, (key, value)) in cart_vec.into_iter().enumerate() {
                    write!(f, "{}", if idx != 0 { ", " } else { "" },)?;
                    match &*value.borrow() {
                        x if std::ptr::eq(x, self) => write!(f, "<cycle>"),
                        x => write!(f, "{x}"),
                    }?;
                    write!(f, " <= {key}")?;
                }

                write!(f, "]")
            }
        }
    }
}

/// Runtime borrow-checked, counted reference to a [Value]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValueRef(Rc<RefCell<Value>>);

impl ValueRef {
    pub fn new(v: Value) -> Self {
        Self(Rc::new(RefCell::new(v)))
    }

    pub fn borrow(&self) -> Ref<Value> {
        self.0.borrow()
    }

    pub fn borrow_mut(&self) -> RefMut<Value> {
        self.0.borrow_mut()
    }

    pub fn replace(&self, v: Value) -> Value {
        self.0.replace(v)
    }
}

/// AbleScript variable either holding a reference
/// or being banned
#[derive(Debug)]
pub enum Variable {
    /// Reference to a value
    Ref(ValueRef),

    /// Banned variable
    Melo,
}

impl Variable {
    pub fn from_value(value: Value) -> Self {
        Self::Ref(ValueRef::new(value))
    }
}