aboutsummaryrefslogtreecommitdiff
path: root/crates/sloth_vm/src/sloth_std/file.rs
blob: b0b476a72204551070c8004695366ddd11c76d56 (plain)
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
use std::fs;

use crate::native::{self, NativeFunction, NativeFunctionResult};
use crate::value::{Object, ObjectType, Primitive};
use crate::VM;

fn file_read(vm: &mut VM, args: &[Primitive]) -> NativeFunctionResult {
    let Some(Primitive::Object(ptr)) = args.get(0).cloned() else {
        return Err(native::Error::InvalidArgument);
    };

    let object = vm
        .objects()
        .get(ptr as usize)
        .ok_or(native::Error::InvalidArgument)?;

    let ObjectType::String(str) = &object.typ else {
        return Err(native::Error::InvalidArgument);
    };

    let contents = fs::read_to_string(str).expect("IO Error: Failed to read file!");

    let object = Object::new(ObjectType::String(contents));
    let ptr = vm.objects_mut().allocate(object);

    Ok(Primitive::Object(ptr as u32))
}

pub const FILE_READ: NativeFunction = NativeFunction {
    name: "file$read",
    function: file_read,
    arity: 1,
    returns_value: true,
    doc: Some(
        "NativeFunction file$read: \n\targs: path (str)\n\tdesc: Returns the contents of a file \
         at <path>\n\tExample: `var todo = file$read('/home/sloth/todo.txt'); # Assuming the \
         contents of todo.txt are 'Take a nap' then todo = 'Take a nap'`",
    ),
};

fn file_write(vm: &mut VM, args: &[Primitive]) -> NativeFunctionResult {
    let Some(Primitive::Object(path_ptr)) = args.get(0).cloned() else {
        return Err(native::Error::InvalidArgument);
    };

    let path_object = vm
        .objects()
        .get(path_ptr as usize)
        .ok_or(native::Error::InvalidArgument)?;

    let ObjectType::String(path) = &path_object.typ else {
        return Err(native::Error::InvalidArgument);
    };

    let Some(Primitive::Object(content_ptr)) = args.get(1).cloned() else {
        return Err(native::Error::InvalidArgument);
    };

    let content_object = vm
        .objects()
        .get(content_ptr as usize)
        .ok_or(native::Error::InvalidArgument)?;

    let ObjectType::String(content) = &content_object.typ else {
        return Err(native::Error::InvalidArgument);
    };

    let _ = fs::write(path, content);

    Ok(Primitive::Empty)
}

pub const FILE_WRITE: NativeFunction = NativeFunction {
    name: "file$write",
    function: file_write,
    arity: 2,
    returns_value: false,
    doc: Some(
        "NativeFunction file$write: \n\targs: path (str), content (str)\n\tdesc: Writes <content> \
         to file at <path>\n\tExample: `file$write('/home/sloth/todo.txt', 'Take a nap'); # \
         todo.txt now contains the string 'Take a nap'`",
    ),
};