luallaby 0.1.0

**Work in progress** A pure-Rust Lua interpreter/compiler
Documentation
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
use std::{
    cell::RefCell,
    fmt,
    hash::{Hash, Hasher},
    io::Write,
    rc::Rc,
};

mod function;
mod numeric;
mod table;
mod thread;
mod userdata;

pub use function::{CallResult, FuncBuiltin, FuncBuiltinRaw, FuncClosure, FuncDef};
pub use numeric::{from_str_radix_wrapping, parse_f64_hex, LuaFloat, LuaInt, Numeric};
pub use table::Table;
pub use thread::{
    ProtectedHandler, Thread, ThreadState, HOOK_CALL, HOOK_COUNT, HOOK_LINE, HOOK_RET,
};
pub use userdata::{ChildMode, FileBufMode, FileDesc, FileHandle, FileMode, UserData};

use crate::{vm::Literal, LuaError, Result};

#[derive(Clone)]
pub enum Value {
    Nil,
    Bool(bool),
    Number(Numeric),
    String(Rc<Vec<u8>>),
    Func(Rc<FuncDef>),
    Table(Rc<RefCell<Table>>),
    Thread(Rc<RefCell<Thread>>),
    UserData(UserData),
    // TODO: Get rid of this variant, to optimize calls
    Mult(Vec<Value>), // Used for varargs
}

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub enum ValueType {
    Nil,
    Bool,
    Number,
    String,
    Func,
    Table,
    UData,
    Thread,
    Custom(String),
}

impl Default for Value {
    fn default() -> Self {
        Value::Nil
    }
}

// TODO: Use proper naming conventions for this
impl Value {
    pub fn empty() -> Self {
        Self::Mult(Vec::new())
    }

    pub fn empty_cap(cap: usize) -> Self {
        Self::Mult(Vec::with_capacity(cap))
    }

    pub fn int(n: i64) -> Self {
        Self::Number(Numeric::Integer(n))
    }

    pub fn float(f: f64) -> Self {
        Self::Number(Numeric::Float(f))
    }

    pub fn string(s: String) -> Self {
        Self::String(Rc::new(s.into_bytes()))
    }

    pub fn str(s: &str) -> Self {
        Self::String(Rc::new(s.to_string().into_bytes()))
    }

    pub fn str_bytes(s: Vec<u8>) -> Self {
        Self::String(Rc::new(s))
    }

    pub fn is_falsy(&self) -> bool {
        match self {
            Value::Nil | Value::Bool(false) => true,
            Value::Mult(vec) => vec.first().map(Value::is_falsy).unwrap_or(true),
            _ => false,
        }
    }

    pub fn is_truthy(&self) -> bool {
        !self.is_falsy()
    }

    pub fn value_type_basic(&self) -> ValueType {
        match self {
            Value::Nil => ValueType::Nil,
            Value::Bool(..) => ValueType::Bool,
            Value::Number(..) => ValueType::Number,
            Value::String(..) => ValueType::String,
            Value::Func(..) => ValueType::Func,
            Value::Table(..) => ValueType::Table,
            Value::Thread(..) => ValueType::Thread,
            Value::UserData(..) => ValueType::UData,
            Value::Mult(vec) => match vec.first() {
                Some(val) => val.value_type(),
                None => panic!("empty multi-value"),
            },
        }
    }

    pub fn value_type(&self) -> ValueType {
        match self {
            Value::Nil => ValueType::Nil,
            Value::Bool(..) => ValueType::Bool,
            Value::Number(..) => ValueType::Number,
            Value::String(..) => ValueType::String,
            Value::Func(..) => ValueType::Func,
            Value::Table(tbl) => match tbl
                .borrow()
                .get_meta()
                .clone()
                .map(|meta| meta.borrow().get(&Value::str("__name")))
            {
                Some(Value::String(str)) => {
                    ValueType::Custom(String::from_utf8_lossy(&str).into_owned())
                }
                _ => ValueType::Table,
            },
            Value::Thread(..) => ValueType::Thread,
            Value::UserData(ud) => match ud
                .get_meta()
                .map(|meta| meta.borrow().get(&Value::str("__name")))
            {
                Some(Value::String(str)) => {
                    ValueType::Custom(String::from_utf8_lossy(&str).into_owned())
                }
                _ => ValueType::UData,
            },
            Value::Mult(vec) => match vec.first() {
                Some(val) => val.value_type(),
                None => panic!("empty multi-value"),
            },
        }
    }

    pub fn to_bool(&self) -> Result<bool> {
        match self.to_single() {
            Value::Bool(b) => Ok(*b),
            v => err!(LuaError::ExpectedType(ValueType::Bool, v.value_type())),
        }
    }

    pub fn to_number(&self) -> Result<&Numeric> {
        match self.to_single() {
            Value::Number(n) => Ok(n),
            v => err!(LuaError::ExpectedType(ValueType::Number, v.value_type())),
        }
    }

    pub fn to_number_coerce(&self) -> Result<Numeric> {
        match self.to_single() {
            Value::Number(n) => Ok(n.clone()),
            Value::String(s) => match Numeric::from_str(s) {
                Ok(n) => Ok(n),
                Err(..) => err!(LuaError::ExpectedType(ValueType::Number, ValueType::String)),
            },
            v => err!(LuaError::ExpectedType(ValueType::Number, v.value_type())),
        }
    }

    pub fn to_int_coerce(&self) -> Result<i64> {
        self.to_number_coerce().and_then(|n| n.coerce_int())
    }

    pub fn to_float_coerce(&self) -> Result<f64> {
        self.to_number_coerce().map(|n| n.to_float())
    }

    // TODO: Make conversion functions for bytes and parsed strings
    pub fn to_string(&self) -> Result<&[u8]> {
        match self.to_single() {
            Value::String(s) => Ok(s.as_ref()),
            v => err!(LuaError::ExpectedType(ValueType::String, v.value_type())),
        }
    }

    pub fn into_string(self) -> Result<Vec<u8>> {
        match self.into_single() {
            Value::String(s) => Ok(s.to_vec()),
            v => err!(LuaError::ExpectedType(ValueType::String, v.value_type())),
        }
    }

    pub fn to_string_coerce(&self) -> Result<Vec<u8>> {
        match self.to_single() {
            Value::String(s) => Ok(s.to_vec()),
            Value::Number(n) => Ok(format!("{}", n).into_bytes()),
            v => err!(LuaError::ExpectedType(ValueType::String, v.value_type())),
        }
    }

    pub fn to_func(&self) -> Result<Rc<FuncDef>> {
        match self.to_single() {
            Value::Func(f) => Ok(f.clone()),
            v => err!(LuaError::ExpectedType(ValueType::Func, v.value_type())),
        }
    }

    pub fn to_table(&self) -> Result<Rc<RefCell<Table>>> {
        match self.to_single() {
            Value::Table(t) => Ok(t.clone()),
            v => err!(LuaError::ExpectedType(ValueType::Table, v.value_type())),
        }
    }

    pub fn to_thread(&self) -> Result<Rc<RefCell<Thread>>> {
        match self.to_single() {
            Value::Thread(t) => Ok(t.clone()),
            v => err!(LuaError::ExpectedType(ValueType::Thread, v.value_type())),
        }
    }

    pub fn to_file(&self) -> Result<Rc<RefCell<FileHandle>>> {
        match self.to_single() {
            Value::UserData(UserData::File(file)) => {
                if file.borrow().is_closed() {
                    err!(LuaError::FileUseClosed)
                } else {
                    Ok(file.clone())
                }
            }
            v => err!(LuaError::ExpectedType(
                ValueType::Custom("FILE*".to_string()),
                v.value_type()
            )),
        }
    }

    // TODO: Make private, conversion should be implicit
    pub fn to_single(&self) -> &Self {
        match self {
            Value::Mult(vec) => vec.first().unwrap_or(&Value::Nil),
            v => v,
        }
    }

    // TODO: Make private, conversion should be implicit
    pub fn into_single(self) -> Self {
        match self {
            Value::Mult(vec) => vec.into_iter().next().unwrap_or(Value::Nil),
            v => v,
        }
    }

    pub fn into_vec(self) -> Vec<Value> {
        match self {
            Value::Mult(vec) => vec,
            v => vec![v],
        }
    }

    pub fn write<W: Write + ?Sized>(&self, dst: &mut W) -> Result<()> {
        Ok(match self {
            Value::Nil => write!(dst, "nil")?,
            Value::Bool(bool) => write!(dst, "{}", bool)?,
            Value::Number(num) => write!(dst, "{}", num)?,
            Value::String(str) => dst.write_all(str)?,
            Value::Func(func) => write!(dst, "function: {:?}", Rc::as_ptr(func))?,
            Value::Table(tbl) => write!(dst, "table: {:?}", Rc::as_ptr(tbl))?,
            Value::Thread(thrd) => write!(dst, "thread: {:?}", Rc::as_ptr(thrd))?,
            Value::UserData(data) => write!(dst, "{}", data)?,
            Value::Mult(..) => unreachable!(),
        })
    }

    #[inline]
    pub fn write_as_string(&self) -> Result<Vec<u8>> {
        let mut str = Vec::new();
        self.write(&mut str)?;
        Ok(str)
    }

    pub fn write_as_value(&self) -> Result<Value> {
        Ok(Value::str_bytes(self.write_as_string()?))
    }
}

impl From<&Literal> for Value {
    fn from(lit: &Literal) -> Self {
        match lit {
            Literal::Nil => Self::Nil,
            Literal::Empty => Self::empty(),
            Literal::EmptyCap(c) => Self::empty_cap(*c),
            Literal::Bool(b) => Self::Bool(*b),
            Literal::Int(i) => Self::int(*i),
            Literal::Float(f) => Self::float(*f),
            Literal::String(s) => Self::String(s.clone()),
        }
    }
}

impl fmt::Debug for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Value::Nil => write!(f, "nil"),
            Value::Bool(bool) => write!(f, "{}", bool),
            Value::Number(num) => write!(f, "{}", num),
            Value::String(str) => write!(f, "{}", String::from_utf8_lossy(str)),
            Value::Func(func) => write!(f, "function: {:?}", Rc::as_ptr(func)),
            Value::Table(tbl) => write!(f, "table: {:?}", Rc::as_ptr(tbl)),
            Value::Thread(thrd) => write!(f, "thread: {:?}", Rc::as_ptr(thrd)),
            Value::UserData(data) => write!(f, "{:?}", data),
            Value::Mult(vec) => {
                let mut vec = vec.iter();
                write!(f, "[")?;
                if let Some(next) = vec.next() {
                    write!(f, "{:?}", next)?;
                }
                for val in vec {
                    write!(f, ", {:?}", val)?;
                }
                write!(f, "]")
            }
        }
    }
}

impl Hash for Value {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            Value::Nil => state.write_u8(0),
            Value::Bool(bool) => {
                state.write_u8(1);
                bool.hash(state);
            }
            Value::Number(num) => {
                state.write_u8(2);
                num.hash(state);
            }
            Value::String(str) => {
                state.write_u8(3);
                str.hash(state);
            }
            Value::Func(func) => {
                state.write_u8(4);
                Rc::as_ptr(func).hash(state);
            }
            Value::Table(tbl) => {
                state.write_u8(5);
                Rc::as_ptr(tbl).hash(state);
            }
            Value::Thread(thrd) => {
                state.write_u8(6);
                Rc::as_ptr(thrd).hash(state);
            }
            Value::UserData(data) => {
                state.write_u8(7);
                data.hash(state);
            }
            Value::Mult(..) => unreachable!(),
        }
    }
}

impl PartialEq for Value {
    fn eq(&self, other: &Self) -> bool {
        match (&self, &other) {
            (&Value::Nil, &Value::Nil) => true,
            (&Value::Bool(b1), &Value::Bool(b2)) => b1 == b2,
            (&Value::Number(n1), &Value::Number(n2)) => n1 == n2,
            (&Value::String(s1), &Value::String(s2)) => s1 == s2,
            (&Value::Func(f1), &Value::Func(f2)) => Rc::as_ptr(f1) == Rc::as_ptr(f2),
            (&Value::Table(v1), &Value::Table(v2)) => Rc::as_ptr(v1) == Rc::as_ptr(v2),
            (&Value::Thread(t1), &Value::Thread(t2)) => Rc::as_ptr(t1) == Rc::as_ptr(t2),
            (&Value::UserData(d1), &Value::UserData(d2)) => d1 == d2,
            _ => false,
        }
    }
}

impl Eq for Value {}

impl From<std::io::Error> for Value {
    fn from(value: std::io::Error) -> Self {
        Value::Mult(vec![
            Value::Nil,
            Value::string(value.kind().to_string()),
            Value::int(value.raw_os_error().unwrap_or(1) as i64),
        ])
    }
}

impl fmt::Display for ValueType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ValueType::Nil => write!(f, "nil"),
            ValueType::Bool => write!(f, "boolean"),
            ValueType::Number => write!(f, "number"),
            ValueType::String => write!(f, "string"),
            ValueType::Func => write!(f, "function"),
            ValueType::Table => write!(f, "table"),
            ValueType::UData => write!(f, "userdata"),
            ValueType::Thread => write!(f, "thread"),
            ValueType::Custom(str) => write!(f, "{}", str),
        }
    }
}