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
|
use std::{collections::HashMap, sync::LazyLock};
use crate::{
ast,
eval::{Context, Error, Result, Value},
Wrap,
};
macro_rules! builtins {
($($f:ident),* $(,)?) => {
pub static BUILTINS: LazyLock<HashMap<&'static str, Box<dyn Fn(&mut Context, &[ast::Expr]) -> Result + Sync + Send>>> =
LazyLock::new(|| {
[
$((
stringify!($f),
Box::new($f) as Box<dyn Fn(&mut Context, &[ast::Expr]) -> Result + Sync + Send>,
)),*
]
.into_iter()
.collect()
});
}
}
builtins! {
print,
println,
// string
isupper,
islower,
substr,
// node
text,
parent,
children,
kind,
// list
length,
member,
push,
pop,
isempty,
}
fn print(ctx: &mut Context, args: &[ast::Expr]) -> Result {
for arg in args {
let val = ctx.eval_expr(arg)?;
let mut default_stream = Box::new(std::io::stdout()) as Box<dyn std::io::Write>;
let stream = ctx.output_stream.as_mut().unwrap_or(&mut default_stream);
write!(stream, "{val}").unwrap();
}
Ok(Value::Unit)
}
fn println(ctx: &mut Context, args: &[ast::Expr]) -> Result {
print(ctx, args)?;
print(ctx, &[ast::Expr::Lit(ast::Literal::Str("\n".to_owned()))])
}
fn isupper(ctx: &mut Context, args: &[ast::Expr]) -> Result {
Ok(ctx
.eval_expr(&get_args::<1>(args)?[0])?
.as_str()?
.chars()
.all(|c| c.is_ascii_uppercase())
.into())
}
fn islower(ctx: &mut Context, args: &[ast::Expr]) -> Result {
Ok(ctx
.eval_expr(&get_args::<1>(args)?[0])?
.as_str()?
.chars()
.all(|c| c.is_ascii_lowercase())
.into())
}
fn substr(ctx: &mut Context, args: &[ast::Expr]) -> Result {
if let Ok([string, start, end]) = get_args::<3>(args) {
let v = ctx.eval_expr(string)?;
let s = v.as_str()?;
let start = ctx.eval_expr(start)?.as_int()?;
let end = ctx.eval_expr(end)?.as_int()?;
if start < 0 || start >= s.len() as i128 || end >= s.len() as i128 || start > end {
return Err(Error::InvalidStringSlice {
length: s.len(),
start,
end,
});
}
Ok(s[start as usize..end as usize].into())
} else {
let [string, end] = get_args::<2>(args)?;
let v = ctx.eval_expr(string)?;
let s = v.as_str()?;
let end = ctx.eval_expr(end)?.as_int()?;
if end >= s.len() as i128 {
return Err(Error::InvalidStringSlice {
length: s.len(),
start: 0,
end,
});
}
Ok(s[..end as usize].into())
}
}
fn text(ctx: &mut Context, args: &[ast::Expr]) -> Result {
let v = ctx.eval_expr(&get_args::<1>(args)?[0])?;
let id = v.as_node()?;
let node = ctx.get_node_by_id(id).unwrap();
let text = node
.utf8_text(ctx.input_src.as_ref().unwrap().as_bytes())
.unwrap();
text.to_owned().wrap(Value::String).wrap(Ok)
}
fn parent(ctx: &mut Context, args: &[ast::Expr]) -> Result {
let v = ctx.eval_expr(&get_args::<1>(args)?[0])?;
let id = v.as_node()?;
let node = ctx.get_node_by_id(id).unwrap();
let parent = node.parent();
parent
.map(|n| Value::Node(n.id()))
.ok_or(Error::NoParentNode(node))
}
fn children(ctx: &mut Context, args: &[ast::Expr]) -> Result {
let v = ctx.eval_expr(&get_args::<1>(args)?[0])?;
let id = v.as_node()?;
let node = ctx.get_node_by_id(id).unwrap();
let children = node
.children(&mut node.walk())
.map(|c| Value::Node(c.id()))
.collect::<Vec<_>>();
Ok(Value::List(children))
}
fn length(ctx: &mut Context, args: &[ast::Expr]) -> Result {
let v = ctx.eval_expr(&get_args::<1>(args)?[0])?;
let l = v.as_list()?;
(l.len() as i128).wrap(Value::Integer).wrap(Ok)
}
fn kind(ctx: &mut Context, args: &[ast::Expr]) -> Result {
let v = ctx.eval_expr(&get_args::<1>(args)?[0])?;
let id = v.as_node()?;
let node = ctx.get_node_by_id(id).unwrap();
node.kind().to_owned().wrap(Value::String).wrap(Ok)
}
fn member(ctx: &mut Context, args: &[ast::Expr]) -> Result {
let [list_expr, element_expr] = get_args::<2>(args)?;
let list = ctx.eval_expr(list_expr)?;
let v = list.as_list()?;
let element = ctx.eval_expr(element_expr)?;
v.iter()
.any(|item| item == &element)
.wrap(Value::Boolean)
.wrap(Ok)
}
fn push(ctx: &mut Context, args: &[ast::Expr]) -> Result {
let [lhs, rhs] = get_args::<2>(args)?;
let ast::Expr::Ident(ident) = lhs else {
return Err(Error::MalformedExpr(format!(
"malformed assigment, lhs: {:?}",
lhs
)));
};
let element = ctx.eval_expr(rhs)?;
let variable = ctx.lookup_mut(ident)?;
variable.mutate(|v| match &mut v.value {
Value::List(l) => {
l.push(element);
Ok(Value::Unit)
}
_ => Err(v.ty().expected([ast::Type::List])),
})
}
fn pop(ctx: &mut Context, args: &[ast::Expr]) -> Result {
let [lhs] = get_args::<1>(args)?;
let ast::Expr::Ident(ident) = lhs else {
return Err(Error::MalformedExpr(format!(
"malformed assigment, lhs: {:?}",
lhs
)));
};
let variable = ctx.lookup_mut(ident)?;
variable.mutate(|v| match &mut v.value {
Value::List(l) => l.pop().ok_or(Error::ArrayOutOfBounds { idx: 0, len: 0 }),
_ => Err(v.ty().expected([ast::Type::List])),
})
}
fn isempty(ctx: &mut Context, args: &[ast::Expr]) -> Result {
let v = ctx.eval_expr(&get_args::<1>(args)?[0])?;
match v.ty() {
ast::Type::List => v
.as_list()
.unwrap()
.is_empty()
.wrap(Value::Boolean)
.wrap(Ok),
ast::Type::String => v.as_str().unwrap().is_empty().wrap(Value::Boolean).wrap(Ok),
_ => Err(v.ty().expected([ast::Type::List])),
}
}
fn get_args<const N: usize>(args: &[ast::Expr]) -> std::result::Result<&[ast::Expr; N], Error> {
args.try_into().map_err(|_| Error::IncorrectArgFormat {
wanted: N,
got: args.len(),
})
}
#[cfg(test)]
mod test {
use super::*;
use crate::{ast::*, eval::*};
#[test]
fn test_ts_builtins() {
let language = tree_sitter_python::language();
let mut ctx = Context::new(language).with_program(Program::new());
assert_eq!(
ctx.eval_block(&Block {
body: vec![Statement::decl(Type::List, "a", Expr::list([Expr::int(5)]),)]
}),
Ok(Value::Unit)
);
assert_eq!(
ctx.lookup(&String::from("a")).unwrap().clone(),
Variable {
ty: Type::List,
name: "a".to_owned(),
value: vec![5usize.into()].into(),
}
);
}
}
|