maid-lang 1.1.0

Maid Programming Language
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
use crate::{
    errors::standard_error::StandardError,
    interpreting::{
        context::Context, interpreter::Interpreter, runtime_result::RuntimeResult,
        symbol_table::SymbolTable,
    },
    lexing::{lexer::Lexer, position::Position},
    parsing::parser::Parser,
    values::{number::Number, string::Str, value::Value},
};
use std::{
    cell::RefCell,
    env, fs,
    io::{Write, stdin, stdout},
    thread,
    time::Duration,
    rc::Rc,
};

#[derive(Debug, Clone)]
pub struct BuiltInFunction {
    pub name: String,
    pub context: Option<Rc<RefCell<Context>>>,
    pub pos_start: Option<Position>,
    pub pos_end: Option<Position>,
}

impl BuiltInFunction {
    pub fn new(name: &str) -> Self {
        BuiltInFunction {
            name: name.to_string(),
            context: None,
            pos_start: None,
            pos_end: None,
        }
    }

    pub fn generate_new_context(&self) -> Rc<RefCell<Context>> {
        let mut new_context = Context::new(
            self.name.clone(),
            Some(self.context.as_ref().unwrap().clone()),
            self.pos_start.clone(),
        );
        let parent_st = self
            .context
            .as_ref()
            .unwrap()
            .borrow()
            .symbol_table
            .as_ref()
            .unwrap()
            .clone();
        new_context.symbol_table = Some(Rc::new(RefCell::new(SymbolTable::new(Some(parent_st)))));

        Rc::new(RefCell::new(new_context))
    }

    pub fn check_args(&self, arg_names: &[String], args: &[Value]) -> RuntimeResult {
        let mut result = RuntimeResult::new();

        if args.len() > arg_names.len() || args.len() < arg_names.len() {
            return result.failure(Some(StandardError::new(
                "invalid function call",
                self.pos_start.as_ref().unwrap().clone(),
                self.pos_end.as_ref().unwrap().clone(),
                Some(
                    format!(
                        "{} takes {} positional argument(s) but the program gave {}",
                        self.name,
                        arg_names.len(),
                        args.len()
                    )
                    .as_str(),
                ),
            )));
        }

        result.success(None)
    }

    pub fn populate_args(
        &self,
        arg_names: &[String],
        args: &[Value],
        exec_ctx: Rc<RefCell<Context>>,
    ) {
        for i in 0..args.len() {
            let arg_name = arg_names[i].clone();
            let mut arg_value = args[i].clone();
            arg_value.set_context(Some(exec_ctx.clone()));

            exec_ctx
                .borrow_mut()
                .symbol_table
                .as_mut()
                .unwrap()
                .borrow_mut()
                .set(arg_name, Some(arg_value));
        }
    }

    pub fn check_and_populate_args(
        &self,
        arg_names: &[String],
        args: &[Value],
        exec_ctx: Rc<RefCell<Context>>,
    ) -> RuntimeResult {
        let mut result = RuntimeResult::new();
        result.register(self.check_args(arg_names, args));

        if result.should_return() {
            return result;
        }

        self.populate_args(arg_names, args, exec_ctx);

        result.success(None)
    }

    pub fn execute(&self, args: &[Value]) -> RuntimeResult {
        let exec_context = self.generate_new_context();

        match self.name.as_str() {
            "serve" => self.execute_print(args, exec_context),
            "process" => self.execute_input(args, exec_context),
            "sweep" => self.execute_read(args, exec_context),
            "stash" => self.execute_write(args, exec_context),
            "tostring" => self.execute_tostring(args, exec_context),
            "tonumber" => self.execute_tonumber(args, exec_context),
            "length" => self.execute_length(args, exec_context),
            "uhoh" => self.execute_error(args, exec_context),
            "type" => self.execute_type(args, exec_context),
            "run" => self.execute_exec(args, exec_context),
            "_env" => self.execute_env(args, exec_context),
            "inline"  => self.execute_inline(args, exec_context),
            "rest"   => self.execute_rest(args, exec_context),
            _ => panic!("CRITICAL ERROR: BUILT IN NAME IS NOT DEFINED"),
        }
    }

    pub fn execute_print(&self, args: &[Value], exec_ctx: Rc<RefCell<Context>>) -> RuntimeResult {
        let mut result = RuntimeResult::new();
        result.register(self.check_and_populate_args(&["value".to_string()], args, exec_ctx));

        if result.should_return() {
            return result;
        }

        println!("{}", args[0].as_string());

        result.success(Some(Number::null_value()))
    }

    pub fn execute_input(&self, args: &[Value], exec_ctx: Rc<RefCell<Context>>) -> RuntimeResult {
        let mut result = RuntimeResult::new();
        result.register(self.check_and_populate_args(&["msg".to_string()], args, exec_ctx));

        if result.should_return() {
            return result;
        }

        let message_arg = args[0].clone();

        let message = match &message_arg {
            Value::StringValue(string) => string.as_string(),
            _ => {
                return result.failure(Some(StandardError::new(
                    "expected type string",
                    message_arg.position_start().unwrap().clone(),
                    message_arg.position_end().unwrap().clone(),
                    Some("add a message like 'Enter a number:' to get user input"),
                )));
            }
        };

        print!("{message}");

        let mut input = String::new();

        let _ = stdout().flush();

        stdin()
            .read_line(&mut input)
            .expect("did not enter a valid string");

        result.success(Some(Str::from(input.trim())))
    }

    pub fn execute_inline(&self, args: &[Value], exec_ctx: Rc<RefCell<Context>>) -> RuntimeResult {
        let mut result = RuntimeResult::new();
        result.register(self.check_and_populate_args(&["text".to_string()], args, exec_ctx));
        if result.should_return() { return result; }

        let text_arg = args[0].clone();
        let s = match &text_arg {
            Value::StringValue(string) => string.as_string(),
            _ => {
                return result.failure(Some(StandardError::new(
                    "expected type string",
                    text_arg.position_start().unwrap().clone(),
                    text_arg.position_end().unwrap().clone(),
                    Some("add the text to print without a newline"),
                )));
            }
        };

        print!("{}", s);
        let _ = stdout().flush();
        result.success(Some(Number::null_value()))
    }

    pub fn execute_rest(&self, args: &[Value], exec_ctx: Rc<RefCell<Context>>) -> RuntimeResult {
        let mut result = RuntimeResult::new();
        result.register(self.check_and_populate_args(&["seconds".to_string()], args, exec_ctx));
        if result.should_return() { return result; }

        let secs_arg = args[0].clone();
        let secs = match &secs_arg {
            Value::NumberValue(n) => n.value,
            _ => {
                return result.failure(Some(StandardError::new(
                    "expected type number",
                    secs_arg.position_start().unwrap().clone(),
                    secs_arg.position_end().unwrap().clone(),
                    Some("pass the number of seconds, e.g., rest(0.05)"),
                )));
            }
        };

        let dur = Duration::from_micros((secs * 1_000_000.0) as u64);
        thread::sleep(dur);
        result.success(Some(Number::null_value()))
    }

    pub fn execute_read(&self, args: &[Value], exec_ctx: Rc<RefCell<Context>>) -> RuntimeResult {
        let mut result = RuntimeResult::new();
        result.register(self.check_and_populate_args(&["file".to_string()], args, exec_ctx));

        if result.should_return() {
            return result;
        }

        let file_arg = args[0].clone();

        let filename = match &file_arg {
            Value::StringValue(string) => string.as_string(),
            _ => {
                return result.failure(Some(StandardError::new(
                    "expected type string",
                    file_arg.position_start().unwrap().clone(),
                    file_arg.position_end().unwrap().clone(),
                    Some("add a filename to read like 'test.txt'"),
                )));
            }
        };

        if fs::exists(&filename).is_err() {
            return result.failure(Some(StandardError::new(
                "file doesn't exist",
                file_arg.position_start().unwrap().clone(),
                file_arg.position_end().unwrap().clone(),
                Some("add a filename to read like 'test.txt'"),
            )));
        }

        let mut contents = String::new();

        match fs::read_to_string(&filename) {
            Ok(extra) => contents.push_str(&extra),
            Err(_) => {
                return result.failure(Some(StandardError::new(
                    "file contents couldn't be read properly",
                    file_arg.position_start().unwrap().clone(),
                    file_arg.position_end().unwrap().clone(),
                    Some("add a UTF-8 encoded file you would like to read"),
                )));
            }
        }

        result.success(Some(Str::from(contents.as_str())))
    }

    pub fn execute_write(&self, args: &[Value], exec_ctx: Rc<RefCell<Context>>) -> RuntimeResult {
        let mut result = RuntimeResult::new();
        result.register(self.check_and_populate_args(
            &["file".to_string(), "contents".to_string()],
            args,
            exec_ctx,
        ));

        if result.should_return() {
            return result;
        }

        let file_arg = args[0].clone();
        let contents_arg = args[1].clone();

        let filename = match &file_arg {
            Value::StringValue(string) => string.as_string(),
            _ => {
                return result.failure(Some(StandardError::new(
                    "expected type string",
                    file_arg.position_start().unwrap().clone(),
                    file_arg.position_end().unwrap().clone(),
                    Some("add a filename to write to like 'test.txt'"),
                )));
            }
        };

        let contents = match &contents_arg {
            Value::StringValue(string) => string.as_string(),
            _ => {
                return result.failure(Some(StandardError::new(
                    "expected type string",
                    file_arg.position_start().unwrap().clone(),
                    file_arg.position_end().unwrap().clone(),
                    Some("add the file contents to write into the file"),
                )));
            }
        };

        match fs::write(&filename, &contents) {
            Ok(_) => {}
            Err(_) => {
                return result.failure(Some(StandardError::new(
                    "file contents couldn't be written properly",
                    file_arg.position_start().unwrap().clone(),
                    file_arg.position_end().unwrap().clone(),
                    None,
                )));
            }
        }

        result.success(Some(Number::null_value()))
    }

    pub fn execute_tostring(
        &self,
        args: &[Value],
        exec_ctx: Rc<RefCell<Context>>,
    ) -> RuntimeResult {
        let mut result = RuntimeResult::new();
        result.register(self.check_and_populate_args(&["value".to_string()], args, exec_ctx));

        if result.should_return() {
            return result;
        }

        result.success(Some(Str::from(args[0].as_string().as_str())))
    }

    pub fn execute_tonumber(
        &self,
        args: &[Value],
        exec_ctx: Rc<RefCell<Context>>,
    ) -> RuntimeResult {
        let mut result = RuntimeResult::new();
        result.register(self.check_and_populate_args(&["value".to_string()], args, exec_ctx));

        if result.should_return() {
            return result;
        }

        let string_to_convert = args[0].clone();

        let value: f64 = match &string_to_convert {
            Value::StringValue(string) => match string.as_string().parse() {
                Ok(number) => number,
                Err(e) => {
                    return result.failure(Some(StandardError::new(
                        format!("string couldn't be converted to number {e}").as_str(),
                        string_to_convert.position_start().unwrap().clone(),
                        string_to_convert.position_end().unwrap().clone(),
                        Some("make sure the string is represented as a valid number like '1.0'"),
                    )));
                }
            },
            _ => {
                return result.failure(Some(StandardError::new(
                    "expected type string",
                    string_to_convert.position_start().unwrap().clone(),
                    string_to_convert.position_end().unwrap().clone(),
                    Some("add a string like '1.0' to convert to a number object"),
                )));
            }
        };

        result.success(Some(Number::from(value)))
    }

    pub fn execute_length(&self, args: &[Value], exec_ctx: Rc<RefCell<Context>>) -> RuntimeResult {
        let mut result = RuntimeResult::new();
        result.register(self.check_and_populate_args(&["value".to_string()], args, exec_ctx));

        if result.should_return() {
            return result;
        }

        let object_arg = args[0].clone();

        let length: f64 = match &object_arg {
            Value::StringValue(value) => value.value.len() as f64,
            Value::ListValue(value) => value.elements.len() as f64,
            _ => {
                return result.failure(Some(StandardError::new(
                    "expected type string or list",
                    object_arg.position_start().unwrap().clone(),
                    object_arg.position_end().unwrap().clone(),
                    None,
                )));
            }
        };

        result.success(Some(Number::from(length)))
    }

    pub fn execute_error(&self, args: &[Value], exec_ctx: Rc<RefCell<Context>>) -> RuntimeResult {
        let mut result = RuntimeResult::new();
        result.register(self.check_and_populate_args(&["msg".to_string()], args, exec_ctx));

        if result.should_return() {
            return result;
        }

        let error = args[0].clone();

        let message = match &error {
            Value::StringValue(_) => error,
            _ => {
                return result.failure(Some(StandardError::new(
                    "expected type string",
                    error.position_start().unwrap().clone(),
                    error.position_end().unwrap().clone(),
                    Some("add an error message"),
                )));
            }
        };

        result.failure(Some(StandardError::new(
            message.as_string().as_str(),
            message.position_start().unwrap().clone(),
            message.position_end().unwrap().clone(),
            None,
        )))
    }

    pub fn execute_type(&self, args: &[Value], exec_ctx: Rc<RefCell<Context>>) -> RuntimeResult {
        let mut result = RuntimeResult::new();
        result.register(self.check_and_populate_args(&["value".to_string()], args, exec_ctx));

        if result.should_return() {
            return result;
        }

        result.success(Some(Str::from(
            args[0].object_type().to_string().as_str(),
        )))
    }

    pub fn execute_exec(&self, args: &[Value], exec_ctx: Rc<RefCell<Context>>) -> RuntimeResult {
        let mut result = RuntimeResult::new();
        result.register(self.check_and_populate_args(&["code".to_string()], args, exec_ctx));

        if result.should_return() {
            return result;
        }

        let code_arg = args[0].clone();

        let code = match &code_arg {
            Value::StringValue(maid) => maid.as_string(),
            _ => {
                return result.failure(Some(StandardError::new(
                    "expected type string",
                    code_arg.position_start().unwrap().clone(),
                    code_arg.position_end().unwrap().clone(),
                    Some("add the maid code you would like to execute"),
                )));
            }
        };

        let mut lexer = Lexer::new(&code_arg.position_start().unwrap().filename, code.clone());
        let token_result = lexer.make_tokens();

        if token_result.is_err() {
            return result.failure(token_result.err());
        }

        let mut parser = Parser::new(&token_result.ok().unwrap());
        let ast = parser.parse();

        if ast.error.is_some() {
            return result.failure(ast.error);
        }

        let mut interpreter = Interpreter::new();
        let external_context =
            Rc::new(RefCell::new(Context::new("<exec>".to_string(), None, None)));
        external_context.borrow_mut().symbol_table = Some(interpreter.global_symbol_table.clone());
        let external_result = interpreter.visit(ast.node.unwrap(), external_context.clone());

        if external_result.error.is_some() {
            return result.failure(external_result.error);
        }

        result.success(Some(Number::null_value()))
    }

    pub fn execute_env(&self, args: &[Value], exec_ctx: Rc<RefCell<Context>>) -> RuntimeResult {
        let mut result = RuntimeResult::new();
        result.register(self.check_and_populate_args(&["var".to_string()], args, exec_ctx));

        if result.should_return() {
            return result;
        }

        let env_arg = args[0].clone();

        let variable = match &env_arg {
            Value::StringValue(maid) => maid.as_string(),
            _ => {
                return result.failure(Some(StandardError::new(
                    "expected type string",
                    env_arg.position_start().unwrap().clone(),
                    env_arg.position_end().unwrap().clone(),
                    Some("add the maid code you would like to execute"),
                )));
            }
        };

        match env::var(&variable) {
            Ok(var) => {
                result.success(Some(Str::from(&var)))
            }
            Err(_) => {
                result.failure(Some(StandardError::new(
                    "unable to access environment variable",
                    env_arg.position_start().unwrap().clone(),
                    env_arg.position_end().unwrap().clone(),
                    None,
                )))
            }
        }
    }

    pub fn as_string(&self) -> String {
        format!("built-in-function: {}", self.name).to_string()
    }
}