1#![allow(unused_macros)]
2use crate::{
3 function,
4 lang::{
5 ast::Chunk,
6 value::{FunctionKind, Object, UserObject, UserObjectError, Value, META_NEXT},
7 },
8 object, option, run_str, set_field, typed, userobject, ExpectedType, ExpectedTypes,
9};
10use std::{
11 cell::RefCell,
12 collections::HashMap,
13 env,
14 error::Error,
15 fmt::{Debug, Display},
16 fs::{self, File},
17 io::{self, Read, Stderr, Stdin, Stdout, Write},
18 net::{TcpListener, TcpStream},
19 path::Path,
20 process::Command,
21 rc::Rc,
22 thread,
23 time::Duration,
24};
25
26use super::{
27 interpreter::{Interpreter, RunTimeError},
28 position::Located,
29};
30
31pub const FOR_FUNC: &str = "next";
32
33pub const INT_MODULE: &str = "int";
34pub const FLOAT_MODULE: &str = "float";
35pub const BOOL_MODULE: &str = "bool";
36pub const CHAR_MODULE: &str = "char";
37pub const STRING_MODULE: &str = "string";
38pub const VECTOR_MODULE: &str = "vector";
39pub const OBJECT_MODULE: &str = "object";
40pub const TYPED_MODULE: &str = "typed";
41
42pub fn globals() -> HashMap<String, Rc<RefCell<Value>>> {
43 let mut globals = HashMap::new();
44 set_field!(globals."print" = function!(_print));
45 set_field!(globals."input" = function!(_input));
46 set_field!(globals."assert" = function!(_assert));
47 set_field!(globals."error" = function!(_error));
48 set_field!(globals."exit" = function!(_exit));
49 set_field!(globals."safe_call" = function!(_safe_call));
50 set_field!(globals."type" = function!(_type));
51 set_field!(globals."require" = function!(_require));
52 set_field!(globals."raw_type" = function!(_raw_type));
53 set_field!(globals."raw_get" = function!(_raw_get));
54 set_field!(globals."raw_set" = function!(_raw_set));
55 set_field!(globals."iter" = function!(_iter));
56 set_field!(globals."next" = function!(_next));
57 set_field!(
58 globals.INT_MODULE = object! {
59 "from" = function!(_int_from),
60 "from_bin" = function!(_int_from_bin),
61 "from_hex" = function!(_int_from_hex),
62 "bytes" = function!(_int_bytes)
63 }
64 );
65 set_field!(
66 globals.FLOAT_MODULE = object! {
67 "from" = function!(_float_from),
68 "floor" = function!(_float_floor),
69 "ceil" = function!(_float_ceil),
70 "round" = function!(_float_round)
71 }
72 );
73 set_field!(
74 globals.BOOL_MODULE = object! {
75 "from" = function!(_bool_from)
76 }
77 );
78 set_field!(
79 globals.CHAR_MODULE = object! {
80 "from" = function!(_char_from),
81 "byte" = function!(_char_byte),
82 "is_whitespace" = function!(_char_is_whitespace),
83 "is_alphabetic" = function!(_char_is_alphabetic),
84 "is_alphanumeric" = function!(_char_is_alphanumeric),
85 "is_control" = function!(_char_is_control),
86 "is_digit" = function!(_char_is_digit),
87 "is_graphic" = function!(_char_is_graphic),
88 "is_hex" = function!(_char_is_hex),
89 "is_lower" = function!(_char_is_lower),
90 "is_upper" = function!(_char_is_upper)
91 }
92 );
93 set_field!(globals."str" = function!(_string_from));
94 set_field!(
95 globals.STRING_MODULE = object! {
96 "lowercase" = ('a'..='z').collect::<Vec<char>>(),
97 "uppercase" = ('A'..='Z').collect::<Vec<char>>(),
98 "letters" = ('a'..='z').chain('A'..='Z').collect::<Vec<char>>(),
99 "from" = globals["str"].borrow().clone(),
100 "len" = function!(_string_len),
101 "iter" = function!(_string_iter),
102 "get" = function!(_string_get),
103 "sub" = function!(_string_sub),
104 "sep" = function!(_string_sep),
105 "rep" = function!(_string_rep),
106 "rev" = function!(_string_rev),
107 "find" = function!(_string_find),
108 "format" = function!(_string_format),
109 "bin" = function!(_int_from_bin),
110 "hex" = function!(_int_from_hex)
111 }
112 );
113 set_field!(
114 globals.VECTOR_MODULE = object! {
115 "iter" = function!(_vector_iter),
116 "len" = function!(_vector_len),
117 "get" = function!(_vector_get),
118 "contains" = function!(_vector_contains),
119 "push" = function!(_vector_push),
120 "pop" = function!(_vector_pop),
121 "insert" = function!(_vector_insert),
122 "join" = function!(_vector_join),
123 "swap" = function!(_vector_swap),
124 "copy" = function!(_vector_copy),
125 "clear" = function!(_vector_clear)
126 }
127 );
128 set_field!(globals."keys" = function!(_object_keys));
129 set_field!(globals."values" = function!(_object_values));
130 set_field!(globals."setmeta" = function!(_object_setmeta));
131 set_field!(globals."getmeta" = function!(_object_getmeta));
132 set_field!(
133 globals.OBJECT_MODULE = object! {
134 "len" = function!(_object_len),
135 "keys" = globals["keys"].borrow().clone(),
136 "values" = globals["values"].borrow().clone(),
137 "setmeta" = globals["setmeta"].borrow().clone(),
138 "getmeta" = globals["getmeta"].borrow().clone(),
139 "clear" = function!(_object_clear)
140 }
141 );
142 set_field!(globals."range" = function!(_range));
143 set_field!(globals."math" = object! {
144 "pi" = Value::Float(std::f64::consts::PI),
145 "nan" = Value::Float(f64::NAN),
146 "inf" = Value::Float(f64::INFINITY),
147 "e" = Value::Float(f64::EPSILON),
148 "abs" = function!(_math_abs),
149 "sqrt" = function!(_math_sqrt),
150 "exp" = function!(_math_exp),
151 "exp2" = function!(_math_exp2),
152 "exp_m1" = function!(_math_exp_m1),
153 "signum" = function!(_math_signum),
154 "fract" = function!(_math_fract),
155 "cos" = function!(_math_cos),
156 "sin" = function!(_math_sin),
157 "tan" = function!(_math_tan),
158 "cosh" = function!(_math_cosh),
159 "sinh" = function!(_math_sinh),
160 "tanh" = function!(_math_tanh),
161 "acos" = function!(_math_acos),
162 "asin" = function!(_math_asin),
163 "atan" = function!(_math_atan),
164 "acosh" = function!(_math_acosh),
165 "asinh" = function!(_math_asinh),
166 "atanh" = function!(_math_atanh),
167 "deg" = function!(_math_deg),
168 "rad" = function!(_math_rad),
169 "random" = function!(_math_random)
170 });
171 set_field!(globals."io" = object! {
172 "write" = function!(_io_write),
173 "flush" = function!(_io_flush),
174 "stdin" = function!(_io_stdin),
175 "stdout" = function!(_io_stdout),
176 "stderr" = function!(_io_stderr)
177 });
178 set_field!(globals."fs" = object! {
179 "open" = function!(_fs_open),
180 "list" = function!(_fs_list),
181 "type" = function!(_fs_type)
182 });
183 set_field!(globals."env" = object! {
184 "var" = function!(_env_var),
185 "set_var" = function!(_env_set_var),
186 "remove_var" = function!(_env_remove_var),
187 "vars" = function!(_env_vars),
188 "current_dir" = function!(_env_current_dir),
189 "current_exe" = function!(_env_current_exe),
190 "set_current_dir" = function!(_env_set_current_dir),
191 "args" = function!(_env_args)
192 });
193 set_field!(globals."net" = object! {
194 "bind" = function!(_net_bind),
195 "connect" = function!(_net_connect)
196 });
197 set_field!(globals."os" = object! {
198 "exec" = function!(_os_exec),
199 "time" = function!(_os_time),
200 "sleep" = function!(_os_sleep)
201 });
202 set_field!(globals."options" = function!(_typed_options));
203 set_field!(globals."some" = function!(_typed_some));
204 set_field!(globals."typed" = object! {
205 "type" = globals["type"].borrow().clone(),
206 "check" = function!(_typed_check),
207 "check_raw" = function!(_typed_check_raw),
208 "int" = function!(_typed_int),
209 "float" = function!(_typed_float),
210 "bool" = function!(_typed_bool),
211 "char" = function!(_typed_char),
212 "string" = function!(_typed_string),
213 "vector" = function!(_typed_vector),
214 "object" = function!(_typed_object),
215 "object_raw" = function!(_typed_object_raw),
216 "function" = function!(_typed_function),
217 "numeric" = function!(_typed_numeric),
218 "iterable" = function!(_typed_iterable),
219 "options" = globals["options"].borrow().clone(),
220 "some" = globals["some"].borrow().clone()
221 });
222 globals
223}
224
225pub fn _print(interpreter: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
226 let args = args.into_iter().enumerate();
227 let mut strings = vec![String::default(); args.len()];
228 for (i, value) in args {
229 strings.insert(
230 i,
231 value
232 .call_tostring(interpreter)
233 .map_err(|err| Into::<Box<dyn Error>>::into(err.to_string()))?,
234 )
235 }
236 println!("{}", strings.join(" "));
237 Ok(Value::default())
238}
239pub fn _input(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
240 let mut args = args.into_iter().enumerate();
241 let perfix = typed!(args: String?);
242
243 let mut input = String::new();
244 if let Some(prefix) = perfix {
245 print!("{prefix}");
246 std::io::stdout().flush()?;
247 }
248 std::io::stdin().read_line(&mut input)?;
249 let input = input.trim_end();
250 Ok(Value::String(input.to_string()))
251}
252#[derive(Debug, Clone, Copy, PartialEq, Eq)]
253pub struct AssertError;
254impl Display for AssertError {
255 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
256 write!(f, "assertion failed")
257 }
258}
259impl Error for AssertError {}
260pub fn _assert(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
261 let mut args = args.into_iter().enumerate();
262 let cond = bool::from(args.next().unwrap_or_default().1);
263 if cond {
264 Ok(Value::default())
265 } else {
266 Err(Box::new(AssertError))
267 }
268}
269#[derive(Debug, Clone, PartialEq)]
270pub struct CustomError(String);
271impl Display for CustomError {
272 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
273 write!(f, "{}", self.0)
274 }
275}
276impl Error for CustomError {}
277pub fn _error(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
278 let mut args = args.into_iter().enumerate();
279 let msg = args.next().unwrap_or_default().1.to_string();
280 Err(Box::new(CustomError(msg)))
281}
282pub fn _exit(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
283 let mut args = args.into_iter().enumerate();
284 let code = typed!(args: Int?).unwrap_or_default() as i32;
285 std::process::exit(code)
286}
287pub fn _safe_call(
288 interpreter: &mut Interpreter,
289 args: Vec<Value>,
290) -> Result<Value, Box<dyn Error>> {
291 let mut args = args.into_iter().enumerate();
292 let func = typed!(args: Function);
293 Ok(match func {
294 FunctionKind::Function(func) => {
295 interpreter.call(&func, args.map(|(_, v)| v).collect(), None);
296 let res = interpreter.run();
297 match res {
298 Ok(value) => object! {
299 "ok" = value.unwrap_or_default()
300 },
301 Err(err) => object! {
302 "err" = Value::String(err.value.to_string())
303 },
304 }
305 }
306 FunctionKind::UserFunction(func) => match func(interpreter, args.map(|(_, v)| v).collect())
307 {
308 Ok(value) => object! {
309 "ok" = value
310 },
311 Err(err) => object! {
312 "err" = Value::String(err.to_string())
313 },
314 },
315 })
316}
317pub fn _type(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
318 let mut args = args.into_iter().enumerate();
319 let value = args.next().unwrap_or_default().1;
320 Ok(Value::String(value.dynamic_typ()))
321}
322#[derive(Debug, Clone, PartialEq)]
323pub struct RequireError {
324 path: String,
325 global_path: Option<String>,
326}
327impl Display for RequireError {
328 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
329 write!(
330 f,
331 "couldn't find any of these modules:\n\t{0}.luna\n\t{0}/mod.luna\n\t{1}/{0}.luna\n\t{1}/{0}/mod.luna",
332 self.path, self.global_path.as_ref().unwrap_or(&"$LUNA_PATH".into())
333 )
334 }
335}
336impl Error for RequireError {}
337pub fn _require(interpreter: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
338 let mut args = args.into_iter().enumerate();
339 let path = typed!(args: String path => path.split('.').collect::<Vec<&str>>().join("/"));
340 let (text, full_path) = if let Ok(text) = fs::read_to_string(format!("{path}.luna")) {
341 (text, format!("{path}.luna"))
342 } else if let Ok(text) = fs::read_to_string(format!("{path}/mod.luna")) {
343 (text, format!("{path}/mod.luna"))
344 } else if fs::File::open(format!("{path}.so")).is_ok() {
345 unsafe {
346 let lib = libloading::Library::new(format!("{path}.so"))?;
347 let func: libloading::Symbol<
348 unsafe extern "C" fn(&mut Interpreter, Vec<Value>) -> Result<Value, Box<dyn Error>>,
349 > = lib.get(b"require")?;
350 return func(interpreter, Vec::from_iter(args.map(|(_, v)| v)));
351 }
352 } else if let Some(global_path) = &interpreter.global_path {
353 let current_path = env::current_dir().map_err(|_| "couldn't resolve current directory")?;
354 let root_path = "/";
355 let root_path = Path::new(&root_path);
356 env::set_current_dir(root_path).map_err(|_| "couldn't change directory to root")?;
357 if let Ok(text) = fs::read_to_string(format!("{global_path}/{path}.luna")) {
358 env::set_current_dir(current_path).map_err(|_| "couldn't change directory")?;
359 (text, format!("{global_path}/{path}.luna"))
360 } else if let Ok(text) = fs::read_to_string(format!("{global_path}/{path}/mod.luna")) {
361 env::set_current_dir(current_path).map_err(|_| "couldn't change directory")?;
362 (text, format!("{global_path}/{path}/mod.luna"))
363 } else if fs::File::open(format!("{global_path}/{path}.so")).is_ok() {
364 unsafe {
365 let lib = libloading::Library::new(format!("{global_path}/{path}.so"))?;
366 let func: libloading::Symbol<
367 unsafe extern "C" fn(
368 &mut Interpreter,
369 Vec<Value>,
370 ) -> Result<Value, Box<dyn Error>>,
371 > = lib.get(b"require")?;
372 return func(interpreter, Vec::from_iter(args.map(|(_, v)| v)));
373 }
374 } else {
375 env::set_current_dir(current_path).map_err(|_| "couldn't change directory")?;
376 return Err(Box::new(RequireError {
377 path,
378 global_path: Some(global_path.clone()),
379 }));
380 }
381 } else {
382 return Err(Box::new(RequireError {
383 path,
384 global_path: None,
385 }));
386 };
387 Ok(run_str::<Chunk>(&text, Some(&full_path))
388 .map_err(|err| {
389 format!(
390 "{full_path}:{}:{}: {}",
391 err.pos.ln.start + 1,
392 err.pos.col.start + 1,
393 err.value
394 )
395 })?
396 .unwrap_or_default())
397}
398
399pub fn _raw_type(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
400 let mut args = args.into_iter();
401 let v = args.next().unwrap_or_default();
402 Ok(Value::String(v.typ().to_string()))
403}
404pub fn _raw_get(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
405 let mut args = args.into_iter().enumerate();
406 let object = typed!(args: Object);
407 let object = object.borrow();
408 let key = typed!(args: String);
409 Ok(object.get(&key).unwrap_or_default())
410}
411pub fn _raw_set(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
412 let mut args = args.into_iter().enumerate();
413 let object = typed!(args: Object);
414 let mut object = object.borrow_mut();
415 let key = typed!(args: String);
416 let value = args.next().unwrap_or_default().1;
417 object.set(key, value);
418 Ok(Value::default())
419}
420
421pub fn _int_from(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
422 let mut args = args.into_iter().enumerate();
423 let (_, value) = args.next().unwrap_or_default();
424 Ok(Value::Int(match value {
425 Value::Int(v) => v,
426 Value::Float(v) => v as i64,
427 Value::Bool(v) => {
428 if v {
429 1
430 } else {
431 0
432 }
433 }
434 Value::Char(v) => v as i64,
435 Value::String(v) => {
436 if let Ok(v) = v.parse() {
437 v
438 } else {
439 return Ok(Value::default());
440 }
441 }
442 _ => return Ok(Value::default()),
443 }))
444}
445pub fn _int_from_bin(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
446 let mut args = args.into_iter().enumerate();
447 let string = typed!(args: String);
448 Ok(i64::from_str_radix(&string, 2)
449 .map(Value::Int)
450 .unwrap_or_default())
451}
452pub fn _int_from_hex(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
453 let mut args = args.into_iter().enumerate();
454 let string = typed!(args: String);
455 Ok(i64::from_str_radix(&string, 16)
456 .map(Value::Int)
457 .unwrap_or_default())
458}
459pub fn _int_bytes(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
460 let mut args = args.into_iter().enumerate();
461 let value = typed!(args: Int);
462 Ok(Value::Vector(Rc::new(RefCell::new(
463 value.to_be_bytes().into_iter().map(Value::from).collect(),
464 ))))
465}
466
467pub fn _float_from(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
468 let mut args = args.into_iter().enumerate();
469 let (_, value) = args.next().unwrap_or_default();
470 Ok(Value::Float(match value {
471 Value::Int(v) => v as f64,
472 Value::Float(v) => v,
473 Value::Bool(v) => {
474 if v {
475 1.
476 } else {
477 0.
478 }
479 }
480 Value::String(v) => {
481 if let Ok(v) = v.parse() {
482 v
483 } else {
484 return Ok(Value::default());
485 }
486 }
487 _ => return Ok(Value::default()),
488 }))
489}
490pub fn _float_floor(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
491 let mut args = args.into_iter().enumerate();
492 let value = typed!(args: Float);
493 Ok(Value::Float(value.floor()))
494}
495pub fn _float_ceil(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
496 let mut args = args.into_iter().enumerate();
497 let value = typed!(args: Float);
498 Ok(Value::Float(value.ceil()))
499}
500pub fn _float_round(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
501 let mut args = args.into_iter().enumerate();
502 let value = typed!(args: Float);
503 Ok(Value::Float(value.round()))
504}
505
506pub fn _bool_from(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
507 let mut args = args.into_iter().enumerate();
508 let (_, value) = args.next().unwrap_or_default();
509 Ok(Value::Bool(value.into()))
510}
511
512pub fn _char_from(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
513 let mut args = args.into_iter().enumerate();
514 let value = typed!(args: Int);
515 Ok(if let Ok(v) = u8::try_from(value) {
516 Value::Char(v as char)
517 } else {
518 Value::default()
519 })
520}
521pub fn _char_byte(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
522 let mut args = args.into_iter().enumerate();
523 let value = typed!(args: Char);
524 Ok(Value::Int(value as u8 as i64))
525}
526pub fn _char_is_whitespace(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
527 let mut args = args.into_iter().enumerate();
528 let value = typed!(args: Char);
529 Ok(Value::Bool(value.is_ascii_whitespace()))
530}
531pub fn _char_is_alphabetic(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
532 let mut args = args.into_iter().enumerate();
533 let value = typed!(args: Char);
534 Ok(Value::Bool(value.is_ascii_alphabetic()))
535}
536pub fn _char_is_alphanumeric(
537 _: &mut Interpreter,
538 args: Vec<Value>,
539) -> Result<Value, Box<dyn Error>> {
540 let mut args = args.into_iter().enumerate();
541 let value = typed!(args: Char);
542 Ok(Value::Bool(value.is_ascii_alphanumeric()))
543}
544pub fn _char_is_digit(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
545 let mut args = args.into_iter().enumerate();
546 let value = typed!(args: Char);
547 let radix = typed!(args: Int?).and_then(|v| u32::try_from(v).ok());
548 Ok(Value::Bool(value.is_digit(radix.unwrap_or(10))))
549}
550pub fn _char_is_control(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
551 let mut args = args.into_iter().enumerate();
552 let value = typed!(args: Char);
553 Ok(Value::Bool(value.is_ascii_control()))
554}
555pub fn _char_is_graphic(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
556 let mut args = args.into_iter().enumerate();
557 let value = typed!(args: Char);
558 Ok(Value::Bool(value.is_ascii_graphic()))
559}
560pub fn _char_is_hex(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
561 let mut args = args.into_iter().enumerate();
562 let value = typed!(args: Char);
563 Ok(Value::Bool(value.is_ascii_hexdigit()))
564}
565pub fn _char_is_lower(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
566 let mut args = args.into_iter().enumerate();
567 let value = typed!(args: Char);
568 Ok(Value::Bool(value.is_ascii_lowercase()))
569}
570pub fn _char_is_upper(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
571 let mut args = args.into_iter().enumerate();
572 let value = typed!(args: Char);
573 Ok(Value::Bool(value.is_ascii_uppercase()))
574}
575
576pub fn _string_from(
577 interpreter: &mut Interpreter,
578 args: Vec<Value>,
579) -> Result<Value, Box<dyn Error>> {
580 let args = args.into_iter().enumerate();
581 let mut string = String::new();
582 for (_, value) in args {
583 string.push_str(
584 &value
585 .call_tostring(interpreter)
586 .map_err(|err| Into::<Box<dyn Error>>::into(err.to_string()))?,
587 );
588 }
589 Ok(Value::String(string))
590}
591pub fn _string_iter(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
592 let mut args = args.into_iter().enumerate();
593 let string = typed!(args: String);
594
595 Ok(Value::UserObject(Rc::new(RefCell::new(Box::new(
596 IteratorObject(Box::new(
597 string
598 .chars()
599 .map(Value::Char)
600 .collect::<Vec<Value>>()
601 .into_iter(),
602 )),
603 )))))
604}
605pub fn _string_len(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
606 let mut args = args.into_iter().enumerate();
607 let string = typed!(args: String);
608
609 Ok(Value::Int(string.len() as i64))
610}
611pub fn _string_get(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
612 let mut args: std::iter::Enumerate<std::vec::IntoIter<Value>> = args.into_iter().enumerate();
613 let string = typed!(args: String);
614 let index = typed!(args: Int);
615 let default = typed!(args: Char?);
616
617 Ok(string
618 .chars()
619 .nth(index.unsigned_abs() as usize)
620 .map(Value::Char)
621 .or(default.map(Value::Char))
622 .unwrap_or_default())
623}
624pub fn _string_sub(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
625 let mut args = args.into_iter().enumerate();
626 let string = typed!(args: String);
627 let start = typed!(args: Int).unsigned_abs() as usize;
628 let stop = typed!(args: Int?)
629 .map(|idx| idx.unsigned_abs() as usize)
630 .unwrap_or(string.len() - 1);
631 let default = typed!(args: String?);
632
633 Ok(string
634 .get(start..=stop)
635 .map(|slice| Value::String(slice.to_string()))
636 .unwrap_or(default.map(Value::String).unwrap_or_default()))
637}
638pub fn _string_sep(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
639 let mut args = args.into_iter().enumerate();
640 let string = typed!(args: String);
641 let sep = typed!(args: String);
642
643 Ok(string
644 .split(&sep)
645 .map(|s| s.to_string())
646 .collect::<Vec<String>>()
647 .into())
648}
649pub fn _string_rep(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
650 let mut args = args.into_iter().enumerate();
651 let string = typed!(args: String);
652 let n = typed!(args: Int);
653
654 Ok(string.repeat(n as usize).into())
655}
656pub fn _string_rev(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
657 let mut args = args.into_iter().enumerate();
658 let string = typed!(args: String);
659
660 Ok(string.chars().rev().collect::<String>().into())
661}
662pub fn _string_find(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
663 let mut args = args.into_iter().enumerate();
664 let string = typed!(args: String);
665 let pattern = typed!(args: String);
666
667 Ok(string
668 .find(&pattern)
669 .map(|i| Value::Int(i as i64))
670 .unwrap_or_default())
671}
672#[derive(Debug, Clone, PartialEq)]
673pub enum FormatErrorKind {
674 NoFormatOption,
675 InvalidFormatOption(char),
676}
677#[derive(Debug, Clone, PartialEq)]
678pub struct FormatError {
679 kind: FormatErrorKind,
680 pos: usize,
681}
682impl Display for FormatErrorKind {
683 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
684 match self {
685 FormatErrorKind::NoFormatOption => write!(f, "no format option"),
686 FormatErrorKind::InvalidFormatOption(c) => write!(f, "invalid format option {c:?}"),
687 }
688 }
689}
690impl Display for FormatError {
691 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
692 write!(f, "{} (at idx {})", self.kind, self.pos)
693 }
694}
695impl Error for FormatError {}
696pub fn _string_format(
697 interpreter: &mut Interpreter,
698 args: Vec<Value>,
699) -> Result<Value, Box<dyn Error>> {
700 let mut args = args.into_iter().enumerate();
701 let string = typed!(args: String);
702 let mut formatted = String::new();
703 let mut chars = string.chars().enumerate();
704 while let Some((i, c)) = chars.next() {
705 match c {
706 '%' => {
707 let Some((i, c)) = chars.next() else {
708 return Err(Box::new(FormatError {
709 kind: FormatErrorKind::NoFormatOption,
710 pos: i,
711 }));
712 };
713 formatted.push_str(&match c {
714 '%' => "%".to_string(),
715 's' => args
716 .next()
717 .map(|(_, v)| v)
718 .unwrap_or_default()
719 .call_tostring(interpreter)
720 .map_err(|err| Into::<Box<dyn Error>>::into(err.to_string()))?,
721 'q' => match args.next().map(|(_, v)| v).unwrap_or_default() {
722 Value::String(v) => format!("{v:?}"),
723 value => value
724 .call_tostring(interpreter)
725 .map_err(|err| Into::<Box<dyn Error>>::into(err.to_string()))?,
726 },
727 'x' => match args.next().map(|(_, v)| v).unwrap_or_default() {
728 Value::Int(v) => format!("{v:x?}"),
729 value => value
730 .call_tostring(interpreter)
731 .map_err(|err| Into::<Box<dyn Error>>::into(err.to_string()))?,
732 },
733 c => {
734 return Err(Box::new(FormatError {
735 kind: FormatErrorKind::InvalidFormatOption(c),
736 pos: i,
737 }))
738 }
739 })
740 }
741 c => formatted.push(c),
742 }
743 }
744 Ok(formatted.into())
745}
746
747pub fn _vector_iter(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
748 let mut args = args.into_iter().enumerate();
749 let vector = typed!(args: Vector);
750 let vector = vector.borrow();
751
752 Ok(Value::UserObject(Rc::new(RefCell::new(Box::new(
753 IteratorObject(Box::new(vector.clone().into_iter())),
754 )))))
755}
756pub fn _vector_len(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
757 let mut args = args.into_iter().enumerate();
758 let vector = typed!(args: Vector);
759 let vector = vector.borrow();
760
761 Ok(Value::Int(vector.len() as i64))
762}
763pub fn _vector_get(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
764 let mut args = args.into_iter().enumerate();
765 let vector = typed!(args: Vector);
766 let vector = vector.borrow();
767 let index = typed!(args: Int);
768 let default = args.next().map(|(_, v)| v);
769
770 Ok(vector
771 .get(index.unsigned_abs() as usize)
772 .cloned()
773 .unwrap_or(default.unwrap_or_default()))
774}
775pub fn _vector_contains(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
776 let mut args = args.into_iter().enumerate();
777 let vector = typed!(args: Vector);
778 let vector = vector.borrow();
779 let value = args.next().map(|(_, v)| v).unwrap_or_default();
780
781 Ok(vector.contains(&value).into())
782}
783pub fn _vector_push(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
784 let mut args = args.into_iter().enumerate();
785 let vector = typed!(args: Vector);
786 let mut vector = vector.borrow_mut();
787 let value = args.next().map(|(_, v)| v).unwrap_or_default();
788
789 vector.push(value);
790 Ok(Value::default())
791}
792pub fn _vector_pop(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
793 let mut args = args.into_iter().enumerate();
794 let vector = typed!(args: Vector);
795 let mut vector = vector.borrow_mut();
796 let index = typed!(args: Int?);
797
798 if let Some(index) = index {
799 let index = index.unsigned_abs() as usize;
800 if vector.get(index).is_some() {
801 Ok(vector.remove(index))
802 } else {
803 Ok(Value::default())
804 }
805 } else {
806 Ok(vector.pop().unwrap_or_default())
807 }
808}
809pub fn _vector_insert(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
810 let mut args = args.into_iter().enumerate();
811 let vector = typed!(args: Vector);
812 let mut vector = vector.borrow_mut();
813 let index = typed!(args: Int int => int.unsigned_abs() as usize);
814 let value = args.next().map(|(_, v)| v).unwrap_or_default();
815 if index <= vector.len() {
816 vector.insert(index, value);
817 }
818 Ok(Value::default())
819}
820pub fn _vector_join(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
821 let mut args = args.into_iter().enumerate();
822 let vector = typed!(args: Vector);
823 let vector = vector.borrow();
824 let sep = typed!(args: String);
825
826 Ok(Value::String(
827 vector
828 .iter()
829 .map(|v| v.to_string())
830 .collect::<Vec<String>>()
831 .join(&sep),
832 ))
833}
834pub fn _vector_swap(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
835 let mut args = args.into_iter().enumerate();
836 let vector = typed!(args: Vector);
837 let mut vector = vector.borrow_mut();
838 let index1 = typed!(args: Int int => int.unsigned_abs() as usize);
839 let index2 = typed!(args: Int int => int.unsigned_abs() as usize);
840 if vector.get(index1).is_some() && vector.get(index2).is_some() {
841 vector.swap(index1, index2);
842 }
843 Ok(Value::default())
844}
845pub fn _vector_copy(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
846 let mut args = args.into_iter().enumerate();
847 let vector = typed!(args: Vector);
848 let vector = vector.borrow();
849
850 Ok(vector.clone().into())
851}
852pub fn _vector_clear(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
853 let mut args = args.into_iter().enumerate();
854 let vector = typed!(args: Vector);
855 let mut vector = vector.borrow_mut();
856 vector.clear();
857 Ok(Value::default())
858}
859
860pub fn _object_len(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
861 let mut args = args.into_iter().enumerate();
862 let object = typed!(args: Object);
863 let object = object.borrow();
864
865 Ok(Value::Int(object.fields.len() as i64))
866}
867pub fn _object_keys(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
868 let mut args = args.into_iter().enumerate();
869 let object = typed!(args: Object);
870 let object = object.borrow();
871
872 Ok(Value::UserObject(Rc::new(RefCell::new(Box::new(
873 IteratorObject(Box::new(
874 object
875 .fields
876 .keys()
877 .cloned()
878 .map(Value::String)
879 .collect::<Vec<Value>>()
880 .into_iter(),
881 )),
882 )))))
883}
884pub fn _object_values(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
885 let mut args = args.into_iter().enumerate();
886 let object = typed!(args: Object);
887 let object = object.borrow();
888
889 Ok(Value::UserObject(Rc::new(RefCell::new(Box::new(
890 IteratorObject(Box::new(
891 object
892 .fields
893 .values()
894 .cloned()
895 .collect::<Vec<Value>>()
896 .into_iter(),
897 )),
898 )))))
899}
900pub fn _object_setmeta(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
901 let mut args = args.into_iter().enumerate();
902 let object = typed!(args: Object);
903 {
904 let mut object = object.borrow_mut();
905 let meta = typed!(args: Object?);
906
907 object.meta = meta;
908 }
909 Ok(Value::Object(object))
910}
911pub fn _object_getmeta(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
912 let mut args = args.into_iter().enumerate();
913 let object = typed!(args: Object);
914 let object = object.borrow();
915 Ok(object
916 .meta
917 .as_ref()
918 .map(|o| Value::Object(Rc::clone(o)))
919 .unwrap_or_default())
920}
921pub fn _object_clear(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
922 let mut args = args.into_iter().enumerate();
923 let object = typed!(args: Object);
924 let mut object = object.borrow_mut();
925 object.fields.clear();
926 Ok(Value::default())
927}
928pub fn _range(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
929 let mut args = args.into_iter().enumerate();
930 let start = typed!(args: Int);
931 let end = typed!(args: Int?);
932
933 Ok(Value::UserObject(Rc::new(RefCell::new(Box::new(
934 IteratorObject(Box::new(
935 if let Some(end) = end {
936 start..end
937 } else {
938 0..start
939 }
940 .map(Value::Int)
941 .collect::<Vec<Value>>()
942 .into_iter(),
943 )),
944 )))))
945}
946
947pub fn _typed_check(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
948 let mut args = args.into_iter().enumerate();
949 let value = typed!(args);
950 for (_, arg) in args {
951 if let Value::String(typ) = arg {
952 if value.dynamic_typ() == typ {
953 return Ok(value);
954 }
955 }
956 }
957 Ok(Value::default())
958}
959pub fn _typed_check_raw(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
960 let mut args = args.into_iter().enumerate();
961 let value = typed!(args);
962 for (_, arg) in args {
963 if let Value::String(typ) = arg {
964 if value.typ() == typ {
965 return Ok(value);
966 }
967 }
968 }
969 Ok(Value::default())
970}
971pub fn _typed_int(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
972 let mut args = args.into_iter().enumerate();
973 let value: Value = typed!(args);
974 Ok(if value.typ() == "int" {
975 value
976 } else {
977 Value::default()
978 })
979}
980pub fn _typed_float(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
981 let mut args = args.into_iter().enumerate();
982 let value = typed!(args);
983 Ok(if value.typ() == "float" {
984 value
985 } else {
986 Value::default()
987 })
988}
989pub fn _typed_bool(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
990 let mut args = args.into_iter().enumerate();
991 let value = typed!(args);
992 Ok(if value.typ() == "bool" {
993 value
994 } else {
995 Value::default()
996 })
997}
998pub fn _typed_char(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
999 let mut args = args.into_iter().enumerate();
1000 let value = typed!(args);
1001 Ok(if value.typ() == "char" {
1002 value
1003 } else {
1004 Value::default()
1005 })
1006}
1007pub fn _typed_string(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1008 let mut args = args.into_iter().enumerate();
1009 let value = typed!(args);
1010 Ok(if value.typ() == "string" {
1011 value
1012 } else {
1013 Value::default()
1014 })
1015}
1016pub fn _typed_vector(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1017 let mut args = args.into_iter().enumerate();
1018 let value = typed!(args);
1019 Ok(if value.typ() == "vector" {
1020 value
1021 } else {
1022 Value::default()
1023 })
1024}
1025pub fn _typed_object(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1026 let mut args = args.into_iter().enumerate();
1027 let value = typed!(args);
1028 Ok(if value.dynamic_typ() == "object" {
1029 value
1030 } else {
1031 Value::default()
1032 })
1033}
1034pub fn _typed_object_raw(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1035 let mut args = args.into_iter().enumerate();
1036 let value = typed!(args);
1037 Ok(if value.typ() == "object" {
1038 value
1039 } else {
1040 Value::default()
1041 })
1042}
1043pub fn _typed_function(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1044 let mut args = args.into_iter().enumerate();
1045 let value = typed!(args);
1046 Ok(if value.typ() == "function" {
1047 value
1048 } else {
1049 Value::default()
1050 })
1051}
1052pub fn _typed_numeric(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1053 let mut args = args.into_iter().enumerate();
1054 let value = typed!(args);
1055 Ok(if value.typ() == "int" || value.typ() == "float" {
1056 value
1057 } else {
1058 Value::default()
1059 })
1060}
1061pub fn _typed_iterable(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1062 let mut args = args.into_iter().enumerate();
1063 let value = typed!(args);
1064 Ok(
1065 if value.typ() == "string" || value.typ() == "vector" || value.typ() == "object" {
1066 value
1067 } else {
1068 Value::default()
1069 },
1070 )
1071}
1072pub fn _typed_options(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1073 let mut args = args.into_iter().enumerate();
1074 let value = typed!(args);
1075 for (_, arg) in args {
1076 if value == arg {
1077 return Ok(value);
1078 }
1079 }
1080 Ok(Value::default())
1081}
1082pub fn _typed_some(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1083 let mut args = args.into_iter().enumerate();
1084 let value = typed!(args);
1085 Ok(if value.typ() != "null" { value } else { Value::default() })
1086}
1087
1088pub fn _math_abs(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1089 let mut args = args.into_iter().enumerate();
1090 option!(args:
1091 Int => value {
1092 Ok(Value::Int(value.abs()))
1093 },
1094 Float => value {
1095 Ok(Value::Float(value.abs()))
1096 }
1097 )
1098}
1099pub fn _math_sqrt(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1100 let mut args = args.into_iter().enumerate();
1101 option!(args:
1102 Int => value {
1103 Ok(Value::Float((value as f64).sqrt()))
1104 },
1105 Float => value {
1106 Ok(Value::Float(value.sqrt()))
1107 }
1108 )
1109}
1110pub fn _math_exp(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1111 let mut args = args.into_iter().enumerate();
1112 option!(args:
1113 Int => value {
1114 Ok(Value::Float((value as f64).exp()))
1115 },
1116 Float => value {
1117 Ok(Value::Float(value.exp()))
1118 }
1119 )
1120}
1121pub fn _math_exp2(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1122 let mut args = args.into_iter().enumerate();
1123 option!(args:
1124 Int => value {
1125 Ok(Value::Float((value as f64).exp2()))
1126 },
1127 Float => value {
1128 Ok(Value::Float(value.exp2()))
1129 }
1130 )
1131}
1132pub fn _math_exp_m1(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1133 let mut args = args.into_iter().enumerate();
1134 option!(args:
1135 Int => value {
1136 Ok(Value::Float((value as f64).exp_m1()))
1137 },
1138 Float => value {
1139 Ok(Value::Float(value.exp_m1()))
1140 }
1141 )
1142}
1143pub fn _math_signum(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1144 let mut args = args.into_iter().enumerate();
1145 option!(args:
1146 Int => value {
1147 Ok(Value::Float((value as f64).signum()))
1148 },
1149 Float => value {
1150 Ok(Value::Float(value.signum()))
1151 }
1152 )
1153}
1154pub fn _math_fract(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1155 let mut args = args.into_iter().enumerate();
1156 option!(args:
1157 Int => value {
1158 Ok(Value::Float((value as f64).fract()))
1159 },
1160 Float => value {
1161 Ok(Value::Float(value.fract()))
1162 }
1163 )
1164}
1165pub fn _math_sin(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1166 let mut args = args.into_iter().enumerate();
1167 option!(args:
1168 Int => value {
1169 Ok(Value::Float((value as f64).sin()))
1170 },
1171 Float => value {
1172 Ok(Value::Float(value.sin()))
1173 }
1174 )
1175}
1176pub fn _math_cos(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1177 let mut args = args.into_iter().enumerate();
1178 option!(args:
1179 Int => value {
1180 Ok(Value::Float((value as f64).cos()))
1181 },
1182 Float => value {
1183 Ok(Value::Float(value.cos()))
1184 }
1185 )
1186}
1187pub fn _math_tan(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1188 let mut args = args.into_iter().enumerate();
1189 option!(args:
1190 Int => value {
1191 Ok(Value::Float((value as f64).tan()))
1192 },
1193 Float => value {
1194 Ok(Value::Float(value.tan()))
1195 }
1196 )
1197}
1198pub fn _math_sinh(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1199 let mut args = args.into_iter().enumerate();
1200 option!(args:
1201 Int => value {
1202 Ok(Value::Float((value as f64).sinh()))
1203 },
1204 Float => value {
1205 Ok(Value::Float(value.sinh()))
1206 }
1207 )
1208}
1209pub fn _math_cosh(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1210 let mut args = args.into_iter().enumerate();
1211 option!(args:
1212 Int => value {
1213 Ok(Value::Float((value as f64).cosh()))
1214 },
1215 Float => value {
1216 Ok(Value::Float(value.cosh()))
1217 }
1218 )
1219}
1220pub fn _math_tanh(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1221 let mut args = args.into_iter().enumerate();
1222 option!(args:
1223 Int => value {
1224 Ok(Value::Float((value as f64).tanh()))
1225 },
1226 Float => value {
1227 Ok(Value::Float(value.tanh()))
1228 }
1229 )
1230}
1231pub fn _math_asin(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1232 let mut args = args.into_iter().enumerate();
1233 option!(args:
1234 Int => value {
1235 Ok(Value::Float((value as f64).asin()))
1236 },
1237 Float => value {
1238 Ok(Value::Float(value.asin()))
1239 }
1240 )
1241}
1242pub fn _math_acos(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1243 let mut args = args.into_iter().enumerate();
1244 option!(args:
1245 Int => value {
1246 Ok(Value::Float((value as f64).acos()))
1247 },
1248 Float => value {
1249 Ok(Value::Float(value.acos()))
1250 }
1251 )
1252}
1253pub fn _math_atan(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1254 let mut args = args.into_iter().enumerate();
1255 option!(args:
1256 Int => value {
1257 Ok(Value::Float((value as f64).atan()))
1258 },
1259 Float => value {
1260 Ok(Value::Float(value.atan()))
1261 }
1262 )
1263}
1264pub fn _math_asinh(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1265 let mut args = args.into_iter().enumerate();
1266 option!(args:
1267 Int => value {
1268 Ok(Value::Float((value as f64).asinh()))
1269 },
1270 Float => value {
1271 Ok(Value::Float(value.asinh()))
1272 }
1273 )
1274}
1275pub fn _math_acosh(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1276 let mut args = args.into_iter().enumerate();
1277 option!(args:
1278 Int => value {
1279 Ok(Value::Float((value as f64).acosh()))
1280 },
1281 Float => value {
1282 Ok(Value::Float(value.acosh()))
1283 }
1284 )
1285}
1286pub fn _math_atanh(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1287 let mut args = args.into_iter().enumerate();
1288 option!(args:
1289 Int => value {
1290 Ok(Value::Float((value as f64).atanh()))
1291 },
1292 Float => value {
1293 Ok(Value::Float(value.atanh()))
1294 }
1295 )
1296}
1297pub fn _math_deg(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1298 let mut args = args.into_iter().enumerate();
1299 option!(args:
1300 Int => value {
1301 Ok(Value::Float((value as f64).to_degrees()))
1302 },
1303 Float => value {
1304 Ok(Value::Float(value.to_degrees()))
1305 }
1306 )
1307}
1308pub fn _math_rad(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1309 let mut args = args.into_iter().enumerate();
1310 option!(args:
1311 Int => value {
1312 Ok(Value::Float((value as f64).to_radians()))
1313 },
1314 Float => value {
1315 Ok(Value::Float(value.to_radians()))
1316 }
1317 )
1318}
1319pub fn _math_random(_: &mut Interpreter, _: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1320 Ok(Value::Float(rand::random()))
1321}
1322
1323pub fn _io_write(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1324 let mut args = args.into_iter().enumerate();
1325 let text = typed!(args: String);
1326 write!(io::stdout(), "{}", text)?;
1327 Ok(Value::default())
1328}
1329pub fn _io_flush(_: &mut Interpreter, _: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1330 io::stdout().flush()?;
1331 Ok(Value::default())
1332}
1333pub fn _io_stdin(_: &mut Interpreter, _: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1334 Ok(Value::UserObject(Rc::new(RefCell::new(Box::new(
1335 StdinObject(io::stdin()),
1336 )))))
1337}
1338pub fn _io_stdout(_: &mut Interpreter, _: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1339 Ok(Value::UserObject(Rc::new(RefCell::new(Box::new(
1340 StdoutObject(io::stdout()),
1341 )))))
1342}
1343pub fn _io_stderr(_: &mut Interpreter, _: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1344 Ok(Value::UserObject(Rc::new(RefCell::new(Box::new(
1345 StderrObject(io::stderr()),
1346 )))))
1347}
1348
1349#[derive(Debug, Clone, PartialEq)]
1350pub struct InvalidOptionError(String);
1351impl Display for InvalidOptionError {
1352 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1353 write!(f, "invalid option {:?}", self.0)
1354 }
1355}
1356impl Error for InvalidOptionError {}
1357pub fn _fs_open(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1358 let mut args = args.into_iter().enumerate();
1359 let path = typed!(args: String);
1360 let (read, write, append) = typed!(args: String options => match options.as_str() {
1361 "w" => (true, true, false),
1362 "r" => (true, false, false),
1363 "a" => (true, false, true),
1364 _ => return Err(InvalidOptionError(options).into())
1365 });
1366 Ok(File::options()
1367 .read(read)
1368 .write(write)
1369 .create(write)
1370 .append(append)
1371 .open(path)
1372 .map(|file| Value::UserObject(Rc::new(RefCell::new(Box::new(FileObject(file))))))
1373 .unwrap_or_default())
1374}
1375pub fn _fs_list(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1376 let mut args = args.into_iter().enumerate();
1377 let path = typed!(args: String);
1378 Ok(fs::read_dir(path)?
1379 .flatten()
1380 .filter_map(|entry| entry.file_name().to_str().map(|s| s.to_string()))
1381 .collect::<Vec<String>>()
1382 .into())
1383}
1384pub fn _fs_type(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1385 let mut args = args.into_iter().enumerate();
1386 let path = typed!(args: String);
1387 if fs::metadata(&path)?.is_dir() {
1388 Ok(Value::String("dir".to_string()))
1389 } else if fs::metadata(&path)?.is_file() {
1390 Ok(Value::String("file".to_string()))
1391 } else {
1392 Ok(Value::default())
1393 }
1394}
1395
1396pub fn _env_set_var(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1397 let mut args = args.into_iter().enumerate();
1398 let var = typed!(args: String);
1399 let value = args.next().unwrap_or_default().1.to_string();
1400 env::set_var(var, value);
1401 Ok(Value::default())
1402}
1403pub fn _env_var(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1404 let mut args = args.into_iter().enumerate();
1405 let var = typed!(args: String);
1406 Ok(env::var(var).map(Value::String).unwrap_or_default())
1407}
1408pub fn _env_remove_var(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1409 let mut args = args.into_iter().enumerate();
1410 let var = typed!(args: String);
1411 env::remove_var(var);
1412 Ok(Value::default())
1413}
1414pub fn _env_vars(_: &mut Interpreter, _: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1415 Ok(Value::Object(Rc::new(RefCell::new(Object::new(
1416 env::vars().map(|(k, v)| (k, Value::String(v))).collect(),
1417 )))))
1418}
1419pub fn _env_current_dir(_: &mut Interpreter, _: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1420 Ok(env::current_dir()?
1421 .to_str()
1422 .map(|s| Value::String(s.to_string()))
1423 .unwrap_or_default())
1424}
1425pub fn _env_current_exe(_: &mut Interpreter, _: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1426 Ok(env::current_exe()?
1427 .to_str()
1428 .map(|s| Value::String(s.to_string()))
1429 .unwrap_or_default())
1430}
1431pub fn _env_set_current_dir(_: &mut Interpreter, _: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1432 Ok(Value::Object(Rc::new(RefCell::new(Object::new(
1433 env::vars().map(|(k, v)| (k, Value::String(v))).collect(),
1434 )))))
1435}
1436pub fn _env_args(_: &mut Interpreter, _: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1437 Ok(env::args().collect::<Vec<String>>().into())
1438}
1439
1440pub fn _net_bind(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1441 let mut args = args.into_iter().enumerate();
1442 let addr = typed!(args: String);
1443 let port = typed!(args: Int port => u16::try_from(port))
1444 .map_err(|_| Into::<Box<dyn Error>>::into("invalid port"))?;
1445 Ok(TcpListener::bind((addr, port))
1446 .map(|listener| {
1447 Value::UserObject(Rc::new(RefCell::new(Box::new(TcpListenerObject(listener)))))
1448 })
1449 .unwrap_or_default())
1450}
1451pub fn _net_connect(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1452 let mut args = args.into_iter().enumerate();
1453 let addr = typed!(args: String);
1454 let port = typed!(args: Int port => u16::try_from(port))
1455 .map_err(|_| Into::<Box<dyn Error>>::into("invalid port"))?;
1456 Ok(TcpStream::connect((addr, port))
1457 .map(|stream| Value::UserObject(Rc::new(RefCell::new(Box::new(TcpStreamObject(stream))))))
1458 .unwrap_or_default())
1459}
1460
1461pub fn _os_exec(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1462 let mut args = args.into_iter().enumerate();
1463 let command = typed!(args: String);
1464 let args = args.map(|(_, v)| v.to_string()).collect::<Vec<String>>();
1465 let output = Command::new(command).args(args).output()?;
1466 Ok(object!(
1467 "ok" = output
1468 .stdout
1469 .into_iter()
1470 .map(|b| b as char)
1471 .collect::<String>(),
1472 "err" = output
1473 .stderr
1474 .into_iter()
1475 .map(|b| b as char)
1476 .collect::<String>()
1477 ))
1478}
1479pub fn _os_time(_: &mut Interpreter, _: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1480 Ok(Value::Float(
1481 chrono::Utc::now().timestamp_micros() as f64 / 1_000_000.,
1482 ))
1483}
1484pub fn _os_sleep(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1485 let mut args = args.into_iter().enumerate();
1486 let secs = option!(args: Float => secs { secs }, Int => secs { secs as f64 });
1487 thread::sleep(Duration::from_secs_f64(secs));
1488 Ok(Value::default())
1489}
1490
1491fn _iter(_: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1492 let mut args = args.into_iter().enumerate();
1493 let value = typed!(args);
1494 match value {
1495 Value::Vector(vector) => {
1496 let vector = vector.borrow();
1497 Ok(Value::UserObject(Rc::new(RefCell::new(Box::new(
1498 IteratorObject(Box::new(vector.clone().into_iter())),
1499 )))))
1500 }
1501 Value::String(string) => Ok(Value::UserObject(Rc::new(RefCell::new(Box::new(
1502 IteratorObject(Box::new(
1503 string
1504 .chars()
1505 .map(Value::Char)
1506 .collect::<Vec<Value>>()
1507 .into_iter(),
1508 )),
1509 ))))),
1510 Value::Object(object) => {
1511 let object = object.borrow();
1512 Ok(Value::UserObject(Rc::new(RefCell::new(Box::new(
1513 IteratorObject(Box::new(
1514 object
1515 .fields
1516 .keys()
1517 .cloned()
1518 .map(Value::String)
1519 .collect::<Vec<Value>>()
1520 .into_iter(),
1521 )),
1522 )))))
1523 }
1524 value => Err(format!("cannot iterate over {}", value.dynamic_typ()).into()),
1525 }
1526}
1527fn _next(interpreter: &mut Interpreter, args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1528 let mut args = args.into_iter().enumerate();
1529 let iter = typed!(args);
1530 Ok(match &iter {
1531 Value::UserObject(object) => {
1532 let object = Rc::clone(object);
1533 let mut object = object.borrow_mut();
1534 object.call_mut("next", vec![iter])?
1535 }
1536 Value::Object(object) => {
1537 let object: Rc<RefCell<Object>> = Rc::clone(object);
1538 let object = object.borrow();
1539 let value = object.get_meta(META_NEXT).unwrap_or_default();
1540 match value {
1541 Value::Function(kind) => match kind {
1542 FunctionKind::Function(function) => {
1543 interpreter.call(&function, vec![], None);
1544 return Ok(interpreter
1545 .run()
1546 .map_err(|Located { value: err, pos: _ }| err)?
1547 .unwrap_or_default());
1548 }
1549 FunctionKind::UserFunction(func) => func(interpreter, vec![])
1550 .map_err(|err| RunTimeError::Custom(err.to_string()))?,
1551 },
1552 _ => Value::default(),
1553 }
1554 }
1555 Value::Function(kind) => match kind {
1556 FunctionKind::Function(function) => {
1557 interpreter.call(&function, vec![], None);
1558 return Ok(interpreter
1559 .run()
1560 .map_err(|Located { value: err, pos: _ }| err)?
1561 .unwrap_or_default());
1562 }
1563 FunctionKind::UserFunction(func) => {
1564 func(interpreter, vec![]).map_err(|err| RunTimeError::Custom(err.to_string()))?
1565 }
1566 },
1567 iter => return Err(format!("cannot iterate over {}", iter.dynamic_typ()).into()),
1568 })
1569}
1570fn _iter_next(_: &mut Interpreter, mut args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1571 let Some(_self) = args.first().cloned() else {
1572 return Err(Box::new(UserObjectError::ExpectedSelf("null")));
1573 };
1574 args.remove(0);
1575 if let Value::UserObject(_self) = _self {
1576 let mut _self = _self.borrow_mut();
1577 _self.call_mut("next", args)
1578 } else {
1579 Err(Box::new(UserObjectError::ExpectedSelf(_self.typ())))
1580 }
1581}
1582fn _iter_collect(_: &mut Interpreter, mut args: Vec<Value>) -> Result<Value, Box<dyn Error>> {
1583 let Some(_self) = args.first().cloned() else {
1584 return Err(Box::new(UserObjectError::ExpectedSelf("null")));
1585 };
1586 args.remove(0);
1587 if let Value::UserObject(_self) = _self {
1588 let mut _self = _self.borrow_mut();
1589 _self.call_mut("collect", args)
1590 } else {
1591 Err(Box::new(UserObjectError::ExpectedSelf(_self.typ())))
1592 }
1593}
1594pub trait CanBeIterator: Iterator<Item = Value> + Debug {
1595 fn call_next(&mut self) -> Result<Value, Box<dyn Error>> {
1596 Ok(self.next().unwrap_or_default())
1597 }
1598 fn call_collect(&mut self) -> Result<Value, Box<dyn Error>> {
1599 Ok(Value::Vector(Rc::new(RefCell::new(
1600 self.collect::<Vec<Value>>(),
1601 ))))
1602 }
1603}
1604impl CanBeIterator for std::vec::IntoIter<Value> {}
1605#[derive(Debug)]
1606pub struct IteratorObject(pub Box<dyn CanBeIterator>);
1607userobject! {
1608 IteratorObject: "iterator";
1609 self
1610 mut (self, args) {
1611 next : "next" {
1612 self.0.call_next()
1613 }
1614 collect : "collect" {
1615 self.0.call_collect()
1616 }
1617 }
1618}
1619
1620#[derive(Debug)]
1621pub struct StdinObject(Stdin);
1622userobject! {
1623 StdinObject: "stdin";
1624 self
1625 mut (self, args) {
1626 read : "read" {
1627 let mut args = args.into_iter().enumerate();
1628 let mode = typed!(args: String);
1629 let mut string = String::new();
1630 match mode.as_str() {
1631 "a" => self.0.read_to_string(&mut string)?,
1632 "l" => self.0.read_line(&mut string)?,
1633 _ => return Err(format!("invalid mode {mode:?} (expected: 'a'/'l')").into())
1634 };
1635 Ok(Value::String(string))
1636 }
1637 }
1638}
1639#[derive(Debug)]
1640pub struct StdoutObject(Stdout);
1641userobject! {
1642 StdoutObject: "stdout";
1643 self
1644 mut (self, args) {
1645 write : "write" {
1646 let mut args = args.into_iter().enumerate();
1647 let buf = typed!(args: String);
1648 Ok(Value::Int(self.0.write(&buf.into_bytes())? as i64))
1649 }
1650 flush : "flush" {
1651 self.0.flush()?;
1652 Ok(Value::default())
1653 }
1654 }
1655}
1656#[derive(Debug)]
1657pub struct StderrObject(Stderr);
1658userobject! {
1659 StderrObject: "stderr";
1660 self
1661 mut (self, args) {
1662 write : "write" {
1663 let mut args = args.into_iter().enumerate();
1664 let buf = typed!(args: String);
1665 Ok(Value::Int(self.0.write(&buf.into_bytes())? as i64))
1666 }
1667 }
1668}
1669
1670#[derive(Debug)]
1671pub struct FileObject(File);
1672userobject! {
1673 FileObject: "file";
1674 self
1675 mut (self, args) {
1676 read : "read" {
1677 let mut string = String::new();
1678 self.0.read_to_string(&mut string)?;
1679 Ok(Value::String(string))
1680 }
1681 write : "write" {
1682 let mut args = args.into_iter().enumerate();
1683 let buf = typed!(args: String);
1684 Ok(Value::Int(self.0.write(&buf.into_bytes())? as i64))
1685 }
1686 }
1687}
1688
1689#[derive(Debug)]
1690pub struct TcpListenerObject(TcpListener);
1691userobject! {
1692 TcpListenerObject: "tcp-listener";
1693 self
1694 static (self, args) {
1695 addr : "addr" {
1696 Ok(self
1697 .0
1698 .local_addr()
1699 .map(|addr| Value::String(addr.to_string()))
1700 .unwrap_or_default())
1701 }
1702 }
1703 mut (self, args) {
1704 accept : "accept" {
1705 Ok(self
1706 .0
1707 .accept()
1708 .map(|(stream, _)| {
1709 Value::UserObject(Rc::new(RefCell::new(Box::new(TcpStreamObject(stream)))))
1710 })
1711 .unwrap_or_default())
1712 }
1713 }
1714}
1715#[derive(Debug)]
1716pub struct TcpStreamObject(TcpStream);
1717userobject! {
1718 TcpStreamObject: "tcp-stream";
1719 self
1720 static (self, _args) {
1721 local_addr : "local_addr" {
1722 Ok(self
1723 .0
1724 .local_addr()
1725 .map(|addr| Value::String(addr.to_string()))
1726 .unwrap_or_default())
1727 }
1728 peer_addr : "peer_addr" {
1729 Ok(self
1730 .0
1731 .peer_addr()
1732 .map(|addr| Value::String(addr.to_string()))
1733 .unwrap_or_default())
1734 }
1735 }
1736 mut (self, args) {
1737 read : "read" {
1738 let mut buf = String::new();
1739 let Ok(_) = self.0.read_to_string(&mut buf) else {
1740 return Ok(Value::default());
1741 };
1742 Ok(Value::String(buf))
1743 }
1744 write : "write" {
1745 let mut args = args.into_iter().enumerate();
1746 let message = typed!(args: String);
1747 Ok(self.0.write(message.as_bytes()).unwrap_or_default().into())
1748 }
1749 flush : "flush" {
1750 self.0.flush()?;
1751 Ok(Value::default())
1752 }
1753 }
1754}