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::sync::Arc;
use crate::data::{
self,
function::Function,
object::{Object, ObjectFieldsMap, ObjectT},
string::StringT,
tuple::{Tuple, TupleT},
Data, Type,
};
use super::Config;
impl Config {
pub fn with_fs(self) -> Self {
self.add_var(
"fs_read_text",
Function::new_generic(
|a, i| {
if a.is_included_in_single(&StringT) {
Ok(Type::newm(vec![
Arc::new(StringT),
Arc::new(ObjectT::new(vec![(
i.global.object_fields.get_or_add_field("fs_read_error"),
Type::new(data::string::StringT),
)])),
]))
} else {
Err(format!(
"Called fs_read_text with argument type {}, but expected String",
a.with_info(i)
))?
}
},
|a, i| {
let a = a.get();
let a = a
.as_any()
.downcast_ref::<data::string::String>()
.expect("got non-string argument to fs_read_text");
Ok(match std::fs::read_to_string(&a.0) {
Ok(contents) => Data::new(data::string::String(contents)),
Err(e) => Data::new(Object::new(vec![(
i.global.object_fields.get_or_add_field("fs_read_error"),
Data::new(data::string::String(e.to_string())),
)])),
})
},
),
)
.add_var(
"fs_write",
Function::new_generic(
|a, i| {
if a.is_included_in_single(&TupleT(vec![
Type::new(StringT),
Type::new(StringT),
])) {
Ok(Type::newm(vec![
Arc::new(TupleT(vec![])),
Arc::new(ObjectT::new(vec![(
i.global.object_fields.get_or_add_field("fs_write_error"),
Type::new(data::string::StringT),
)])),
]))
} else {
Err(format!(
"Called fs_write with argument type {}, but expected (String, String)",
a.with_info(i)
))?
}
},
|a, i| {
let a = a.get();
let a = a
.as_any()
.downcast_ref::<Tuple>()
.expect("got non-tuple argument to fs_read_text");
let (a, b) = (a.0[0].read(), a.0[1].read());
let (a, b) = (a.get(), b.get());
let a = a
.as_any()
.downcast_ref::<data::string::String>()
.expect("file path was not a string in fs_write");
let b = b
.as_any()
.downcast_ref::<data::string::String>()
.expect("file content was not a string in fs_write");
Ok(match std::fs::write(&a.0, &b.0) {
Ok(()) => Data::empty_tuple(),
Err(e) => Data::new(Object::new(vec![(
i.global.object_fields.get_or_add_field("fs_write_error"),
Data::new(data::string::String(e.to_string())),
)])),
})
},
),
)
}
}