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
414
415
416
417
418
419
420
421
422
use std::{
    cell::RefCell,
    fmt,
    fs::{File, OpenOptions},
    hash::{Hash, Hasher},
    io::{
        stderr, stdin, stdout, BufReader, BufWriter, Cursor, LineWriter, Read, Seek, SeekFrom,
        Stderr, Stdin, Stdout, Write,
    },
    os::fd::AsRawFd,
    process::Child,
    rc::Rc,
};

use super::Table;

#[derive(Clone, Debug)]
pub enum UserData {
    C(*const u8),
    File(Rc<RefCell<FileHandle>>),
}

pub struct FileHandle {
    file: FileDesc,
    meta: Option<Rc<RefCell<Table>>>,
}

pub enum FileDesc {
    Buffer(Rc<RefCell<Cursor<Vec<u8>>>>),
    Child(Option<Child>, ChildMode),
    File(Option<LuaFile>, FileMode),
    StdIn,
    StdOut,
    StdErr,
}

pub enum FileBufMode {
    None,
    Full(Option<usize>),
    Line(Option<usize>),
}

pub struct LuaFile {
    file: File,
    read: Option<Box<dyn Read>>,
    write: Option<Box<dyn Write>>,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ChildMode {
    Read,
    Write,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FileMode {
    Read,
    Write,
    Append,
    ReadUpdate,
    WriteUpdate,
    AppendUpdate,
}

impl UserData {
    pub fn as_ptr(&self) -> *const u8 {
        match self {
            UserData::C(ptr) => *ptr,
            UserData::File(file) => file.borrow().file.as_ptr(),
        }
    }

    pub fn get_meta(&self) -> Option<Rc<RefCell<Table>>> {
        match self {
            UserData::C(..) => None,
            UserData::File(file) => file.borrow().get_meta().clone(),
        }
    }
}

impl fmt::Display for UserData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            UserData::C(ptr) => write!(f, "userdata: {:p}", ptr),
            UserData::File(file) => {
                if file.borrow().is_closed() {
                    write!(f, "file (closed)")
                } else {
                    write!(f, "file ({:p})", self.as_ptr())
                }
            }
        }
    }
}

impl PartialEq for UserData {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (UserData::C(p1), UserData::C(p2)) => p1 == p2,
            (UserData::File(f1), UserData::File(f2)) => Rc::as_ptr(f1) == Rc::as_ptr(f2),
            _ => false,
        }
    }
}

impl Hash for UserData {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            UserData::C(ptr) => ptr.hash(state),
            UserData::File(file) => file.borrow().file.hash(state),
        }
    }
}

impl FileHandle {
    pub fn new(file: FileDesc, meta: Option<Rc<RefCell<Table>>>) -> Self {
        Self { file, meta }
    }

    pub fn take_buffer(self) -> Option<Vec<u8>> {
        match self.file {
            FileDesc::Buffer(buf) => Rc::into_inner(buf)
                .map(RefCell::into_inner)
                .map(Cursor::into_inner),
            _ => None,
        }
    }

    pub fn desc(&self) -> &FileDesc {
        &self.file
    }

    pub fn desc_mut(&mut self) -> &mut FileDesc {
        &mut self.file
    }

    pub fn get_meta(&self) -> &Option<Rc<RefCell<Table>>> {
        &self.meta
    }

    pub fn set_meta(&mut self, meta: Option<Rc<RefCell<Table>>>) {
        self.meta = meta;
    }

    pub fn is_closed(&self) -> bool {
        matches!(self.file, FileDesc::File(None, _))
    }

    pub fn set_buffering(&mut self, mode: FileBufMode) -> bool {
        match &mut self.file {
            FileDesc::File(Some(file), _) => {
                file.read = match mode {
                    FileBufMode::None | FileBufMode::Line(_) => None,
                    FileBufMode::Full(cap) => match file.file.try_clone() {
                        Ok(file) => Some(Box::new(match cap {
                            Some(cap) => BufReader::with_capacity(cap, file),
                            None => BufReader::new(file),
                        })),
                        Err(_) => return false,
                    },
                };
                file.write = match mode {
                    FileBufMode::None => None,
                    FileBufMode::Full(cap) => match file.file.try_clone() {
                        Ok(file) => Some(Box::new(match cap {
                            Some(cap) => BufWriter::with_capacity(cap, file),
                            None => BufWriter::new(file),
                        })),
                        Err(_) => return false,
                    },
                    FileBufMode::Line(cap) => match file.file.try_clone() {
                        Ok(file) => Some(Box::new(match cap {
                            Some(cap) => LineWriter::with_capacity(cap, file),
                            None => LineWriter::new(file),
                        })),
                        Err(_) => return false,
                    },
                };
                true
            }
            _ => false,
        }
    }
}

impl fmt::Debug for FileHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.file)
    }
}

impl Read for FileHandle {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.file.read(buf)
    }
}

impl Seek for FileHandle {
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        self.file.seek(pos)
    }
}

impl Write for FileHandle {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.file.write(buf)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.file.flush()
    }
}

impl FileDesc {
    pub fn file(file: File, mode: FileMode) -> FileDesc {
        Self::File(
            Some(LuaFile {
                file,
                read: None,
                write: None,
            }),
            mode,
        )
    }

    pub fn as_ptr(&self) -> *const u8 {
        match self {
            FileDesc::Buffer(buf) => Rc::as_ptr(buf) as *const u8,
            FileDesc::Child(child, _) => match child {
                Some(child) => child as *const Child as *const u8,
                None => 0 as *const u8,
            },
            FileDesc::File(file, _) => match file {
                Some(file) => &file.file as *const File as *const u8,
                None => 0 as *const u8,
            },
            FileDesc::StdIn => &stdin() as *const Stdin as *const u8,
            FileDesc::StdOut => &stdout() as *const Stdout as *const u8,
            FileDesc::StdErr => &stderr() as *const Stderr as *const u8,
        }
    }
}

impl fmt::Debug for FileDesc {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FileDesc::Buffer(buf) => write!(f, "Write({:p})", Rc::as_ptr(buf)),
            FileDesc::Child(child, mode) => write!(
                f,
                "Child({}, {:?})",
                match child {
                    Some(child) => child.id().to_string(),
                    None => "closed".to_string(),
                },
                mode
            ),
            FileDesc::File(file, mode) => write!(
                f,
                "File({}, {:?})",
                match file {
                    Some(file) => file.as_raw_fd().to_string(),
                    None => "closed".to_string(),
                },
                mode
            ),
            FileDesc::StdIn => write!(f, "StdIn"),
            FileDesc::StdOut => write!(f, "StdOut"),
            FileDesc::StdErr => write!(f, "StdErr"),
        }
    }
}

impl Hash for FileDesc {
    fn hash<H: Hasher>(&self, state: &mut H) {
        core::mem::discriminant(self).hash(state);
        match self {
            FileDesc::Buffer(buf) => Rc::as_ptr(buf).hash(state),
            _ => {}
        }
    }
}

const BAD_FILE_DESCRIPTOR: &str = "bad file descriptor";

impl FileMode {
    pub fn from_str(str: &str) -> Option<FileMode> {
        match str {
            "r" | "rb" => Some(FileMode::Read),
            "w" | "wb" => Some(FileMode::Write),
            "a" | "ab" => Some(FileMode::Append),
            "r+" | "r+b" => Some(FileMode::ReadUpdate),
            "w+" | "w+b" => Some(FileMode::WriteUpdate),
            "a+" | "a+b" => Some(FileMode::AppendUpdate),
            _ => None,
        }
    }

    pub fn options(&self) -> OpenOptions {
        File::options()
            .read(self.can_read())
            .write(self.can_write())
            .append(self.is_append())
            .truncate(self.does_truncate())
            .create(self.can_write())
            .clone()
    }

    fn can_read(&self) -> bool {
        !matches!(self, FileMode::Write | FileMode::Append)
    }

    fn can_write(&self) -> bool {
        !matches!(self, FileMode::Read)
    }

    fn is_append(&self) -> bool {
        matches!(self, FileMode::Append | FileMode::AppendUpdate)
    }

    fn does_truncate(&self) -> bool {
        matches!(self, FileMode::Write | FileMode::WriteUpdate)
    }
}

impl Read for FileDesc {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        match self {
            FileDesc::Child(Some(child), ChildMode::Read) if child.stdout.is_some() => {
                child.stdout.as_mut().unwrap().read(buf)
            }
            FileDesc::File(Some(file), mode) if mode.can_read() => file.read(buf),
            FileDesc::StdIn => stdin().read(buf),
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                BAD_FILE_DESCRIPTOR,
            )),
        }
    }
}

impl Seek for FileDesc {
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        match self {
            FileDesc::File(Some(file), _) => file.seek(pos),
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                "illegal seek",
            )),
        }
    }
}

impl Write for FileDesc {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        match self {
            FileDesc::Buffer(rc) => rc.borrow_mut().write(buf),
            FileDesc::Child(Some(child), ChildMode::Write) if child.stdin.is_some() => {
                child.stdin.as_mut().unwrap().write(buf)
            }
            FileDesc::File(Some(file), mode) if mode.can_write() => file.write(buf),
            FileDesc::StdOut => stdout().write(buf),
            FileDesc::StdErr => stderr().write(buf),
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                BAD_FILE_DESCRIPTOR,
            )),
        }
    }

    fn flush(&mut self) -> std::io::Result<()> {
        match self {
            FileDesc::Buffer(rc) => rc.borrow_mut().flush(),
            FileDesc::Child(Some(child), ChildMode::Write) if child.stdin.is_some() => {
                child.stdin.as_mut().unwrap().flush()
            }
            FileDesc::File(Some(file), mode) if mode.can_write() => file.flush(),
            FileDesc::StdOut => stdout().flush(),
            FileDesc::StdErr => stderr().flush(),
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::Other,
                BAD_FILE_DESCRIPTOR,
            )),
        }
    }
}

impl AsRawFd for LuaFile {
    fn as_raw_fd(&self) -> std::os::unix::prelude::RawFd {
        self.file.as_raw_fd()
    }
}

impl Read for LuaFile {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        match &mut self.read {
            Some(read) => read.read(buf),
            None => self.file.read(buf),
        }
    }
}

impl Seek for LuaFile {
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        self.file.seek(pos)
    }
}

impl Write for LuaFile {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        match &mut self.write {
            Some(write) => write.write(buf),
            None => self.file.write(buf),
        }
    }

    fn flush(&mut self) -> std::io::Result<()> {
        if let Some(write) = &mut self.write {
            write.flush()?;
        }
        self.file.flush()
    }
}