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
#![allow(incomplete_features)]
#![feature(const_generics)]

#![feature(iter_intersperse)]

#![deny(rust_2018_idioms)]

// #![warn(clippy::pedantic)]
#![allow(clippy::needless_lifetimes)]
#![allow(clippy::upper_case_acronyms)]

use std::{fmt, fs};
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};

use lazy_static::lazy_static;
use maplit::hashmap;

#[cfg(feature = "readline")]
use rustyline as rl;
#[cfg(not(feature = "readline"))]
use std::io::{self, BufRead, Write};

#[cfg(feature = "compile")]
use serde::{Serialize, Deserialize, Serializer, Deserializer, ser, de};

#[cfg(feature = "compile")]
use std::fmt::Display;

mod hashablemap;
use hashablemap::*;

mod parsing;
use parsing::*;
mod runnable;
pub use runnable::*;

mod ops;
use ops::*;
mod umcore;
mod umstd;
mod ummod;

#[derive(Debug, Clone)]
pub enum Error {
    ArgumentError(String),
    ParseError(String, Option<Pos>),
    ScriptError(String, Option<Pos>),
    ControlError(String, Option<TVal>),

    CustomError(TVal),
}
impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use Error::*;
        match self {
            ArgumentError(m) => write!(f, "Argument Error: {}", m),
            ParseError(m, pos) => match pos {
                Some(pos) => write!(f, "Parse Error at {}: {}", pos, m),
                None => write!(f, "Parse Error: {}", m),
            },
            ScriptError(m, pos) => match pos {
                Some(pos) => write!(f, "Script Error at {}: {}", pos, m),
                None => write!(f, "Script Error: {}", m),
            },
            ControlError(m, v) => write!(f, "Control Error: {}: {:?}", m, v),
            CustomError(v) => write!(f, "Other Error: {}", v.val),
        }
    }
}
#[cfg(feature = "compile")]
impl ser::Error for Error {
    fn custom<T: Display>(msg: T) -> Self
    {
        Error::ScriptError(msg.to_string(), None)
    }
}
#[cfg(feature = "compile")]
impl de::Error for Error {
    fn custom<T: Display>(msg: T) -> Self
    {
        Error::ScriptError(msg.to_string(), None)
    }
}
impl std::error::Error for Error {}

pub struct Args {
    pub longflags: Vec<String>,
    pub script: Vec<String>,
}
impl Args {
    pub fn handle() -> Result<Args, Error> {
        let mut args = Args {
            longflags: vec![],
            script: vec![],
        };

        let eargs: Vec<String> = std::env::args().collect();
        let mut i = 1;
        let mut sa = false;
        while i < eargs.len() {
            if sa {
                // Add script args
                args.script.push(eargs[i].clone());
            } else if eargs[i].starts_with('-') {
                if eargs[i].starts_with("--") {
                    // Parse double dash flags
                    args.longflags.push(eargs[i][2..].into());
                } else {
                    // Parse single dash flags
                    return Err(Error::ArgumentError(format!("Unsupported arg: {}", eargs[i])))
                }
            } else {
                // Enable script arg mode when a non-dash arg is met
                sa = true;
                continue;
            }
            i += 1;
        }

        Ok(args)
    }
}

#[derive(Clone, PartialEq, Eq)]
pub struct Env<'a> {
    parent: Option<&'a Env<'a>>,
    vars: HashMap<String, RefTVal>,
}
lazy_static! {
    static ref PRELUDE: Env<'static> = {
        let mut vars: HashMap<String, RefTVal> = hashmap!{
            "_".into() => Value::Type(Type::any(), HashableMap::arc()).into(),
        };

        // Import Umbra Core
        umcore::init(&mut vars);

        // Import Umbra STD
        umstd::init(&mut vars);

        Env {
            parent: None,
            vars,
        }
    };
}
impl<'a> Env<'a> {
    pub fn prelude() -> Env<'a> {
        PRELUDE.clone()
    }
    pub fn empty() -> Env<'a> {
        Env {
            parent: None,
            vars: hashmap!{},
        }
    }
    pub fn child(parent: &'a Env<'a>) -> Env<'a> {
        Env {
            parent: Some(parent),
            vars: hashmap!{},
        }
    }

    pub fn iter_flatten<'b>(it: &'b Env<'a>) -> Box<dyn Iterator<Item = (&'b String, &'b RefTVal)> + 'b> {
        if let Some (p) = it.parent {
            return Box::new(Self::iter_flatten(p).chain(it.vars.iter()));
        } else {
            return Box::new(it.vars.iter());
        }
    }
    pub fn flatten<'b>(old: &'b Env<'a>) -> Env<'a> {
        Env::from(
            Self::iter_flatten(old)
                .map(|(k, v)| {
                    (k.clone(), v.clone())
                }).collect::<HashMap<String, RefTVal>>()
        )
    }

    pub fn get(&self, name: &str) -> Option<&RefTVal> {
        match self.vars.get(name) {
            Some(v) => Some(v),
            None => match &self.parent {
                Some(p) => p.get(name), // Recursively fetch variable values
                None => None,
            },
        }
    }
    pub fn has(&self, name: &str) -> bool {
        match self.vars.contains_key(name) {
            true => true,
            false => match &self.parent {
                Some(p) => p.has(name),
                None => false,
            },
        }
    }
    pub fn set(&mut self, name: &str, rv: &RefTVal) {
        self.vars.insert(name.into(), RefTVal::clone(rv));
    }
    pub fn update(&mut self, vars: HashMap<String, RefTVal>) {
        self.vars.extend(vars);
    }

    // Computes the changed vars in the nenv that exist in the outside env (self)
    pub fn diff(&self, nenv: &'a mut Env<'a>) -> HashMap<String, RefTVal> {
        let outer = match self.parent {
            Some(p) => p,
            None => self,
        };
        let mut vars = hashmap!{};
        for (k, v) in nenv.vars.drain() {
            if let Some(ov) = outer.get(&k) {
                if ov != &v {
                    vars.insert(k, v);
                }
            }
        }
        vars
    }
}
impl<'a> From<HashableMap<String, RefTVal>> for Env<'a> {
    fn from(vars: HashableMap<String, RefTVal>) -> Env<'a> {
        Env {
            parent: None,
            vars: vars.map,
        }
    }
}
impl<'a> From<HashMap<String, RefTVal>> for Env<'a> {
    fn from(vars: HashMap<String, RefTVal>) -> Env<'a> {
        Env {
            parent: None,
            vars,
        }
    }
}
impl<'a> fmt::Debug for Env<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let parent = match self.parent {
            Some(_) => "Some(Env {...})",
            None => "None",
        };
        write!(f, "Env {{ parent: {}, vars: {{{:?}}} }}", parent, self.vars)
    }
}
#[cfg(feature = "compile")]
impl<'a> Serialize for Env<'a> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer
    {
        let nenv = Env::flatten(self);
        nenv.vars.serialize(serializer)
    }
}
#[cfg(feature = "compile")]
impl<'a, 'de> Deserialize<'de> for Env<'a> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>
    {
        Ok(Env::from(HashMap::deserialize(deserializer)?))
    }
}

pub fn compile<'a>(scriptname: &str, script: &str, env: &'a Env<'a>, pos: Option<Pos>, printout: usize) -> Result<Runnable<'a>, Error> {
    // Split script string into lines while preserving containers
    let lines: Vec<Line> = Lines::split(scriptname, script, pos)
        // Expression debug print
        .inspect(|l| {
            if printout > 0 && !l.data.starts_with("//") {
                println!("{}", l);
            }
        }).collect();

    // Convert the line into a series of expressions
    let exprs: Vec<Expr> = lines.iter().flat_map(|l| Exprs::split(&l)).collect();

    // Convert the expr into a series of tokens
    let mut tokens: Vec<Tokens> = exprs.iter().map(|e| Tokens::tokenize(&e))
        // Token debug prints
        .inspect(|ts| {
            if printout > 1 {
                print!("    tokens: [");
                for t in ts.clone() {
                    print!("{}, ", t);
                }
                println!("]");
            }
        }).collect();

    // Parse the tokens into an AST
    let asts: Result<Vec<AST>, Error> = tokens.drain(0..).map(|ts| {
            AST::parse(ts, &env)
        }).collect();

    let mut shash = DefaultHasher::new();
    env!("CARGO_PKG_VERSION").hash(&mut shash);
    script.hash(&mut shash);

    Ok(Runnable {
        hash: shash.finish(),
        env: Env::child(env),
        ast: AST::Container {
            token: Token {
                ttype: TokenType::Container,
                pos: Pos {
                    filename: scriptname.into(),
                    line: 0,
                    col: 0,
                },
                data: "{".into(),
            },
            children: asts?,
        },
    })
}
pub fn run<'a>(scriptname: &str, script: &str, env: &'a Env<'a>, pos: Option<Pos>, printout: (usize, bool)) -> FnReturn {
    // Compile the AST then execute it
    let run = match compile(scriptname, script, env, pos, printout.0) {
        Ok(r) => r,
        Err(m) => {
            if printout.1 {
                eprintln!("{}\n", m);
            }
            return (None, Err(m));
        },
    };

    match run.ast {
        AST::Container { children, .. } => {
            let mut nenv = Env::child(env);
            let vals: Result<Vec<RefTVal>, Error> = children.iter()
                .map(|ast| {

                    let (vars, val) = ast.run(&nenv);
                    if let Some(vars) = vars {
                        nenv.update(vars);
                    }

                    // Expression value debug print
                    if printout.1 {
                        match val {
                            Ok(ref v) => {
                                match ast {
                                    AST::Container { token, .. } if token.data.starts_with("//") => {},
                                    _ => println!("==> {}\n", v),
                                }
                            },
                            Err(ref m) => eprintln!("{}\n", m),
                        }
                    }

                    val
                }).collect();
            match vals {
                Ok(mut vals) => match vals.pop() {
                    Some(v) => (Some(nenv.vars), Ok(v)),
                    None => (None, Ok(Value::none().into())),
                },
                Err(m) => (None, Err(m)),
            }
        },
        _ => (None, Err(Error::ScriptError("expected script container AST".into(), None))),
    }
}
pub fn run_path<'a, P: AsRef<Path>>(path: &P, env: &'a Env<'a>, run_main: bool) -> FnReturn {
    // Correct path for modules
    let path = path.as_ref();
    let path: PathBuf = if path.is_dir() {
        path.join("main.um")
    } else if !path.is_file() {
        path.with_extension("um")
    } else {
        PathBuf::from(path)
    };

    // Read script into string
    let script = match fs::read_to_string(&path) {
        Ok(s) => s,
        Err(m) => return (None, Err(Error::ScriptError(format!("Failed to load {}: {}", path.display(), m), None))),
    };
    // Run script
    let (vars, val) = match run(&path.to_string_lossy(), &script, env, None, (0, false)) {
        (vars, Ok(v)) => (vars, v),
        (vars, Err(m)) => return (vars, Err(m)),
    };

    // Run main if exists and needed
    if run_main {
        if let Some(vars) = &vars {
            if let Some(main) = vars.get("main") {
                if let Value::Function { body, .. } = main.clone_out().val {
                    let mut nenv = Env::child(env);
                    nenv.update(vars.clone());
                    let (_, val) = body.call(&nenv, FnArgs::Normal {
                        this: Box::new(main.clone()),
                        pos: None,
                        args: TVal {
                            ttype: Type::none(),
                            val: Value::none(),
                        }.into(),
                    });
                    return (Some(nenv.vars), val);
                }
            }
        }
    }
    (vars, Ok(val))
}

#[cfg(feature = "readline")]
fn run_interactive_readline<'a>(env: &'a Env<'a>) {
    let mut nenv = Env::child(env);
    let mut pos = Pos::start("<stdin>");
    let mut ed = rl::Editor::<()>::new();
    loop {
        // Read a line from input
        use rl::error::ReadlineError::*;
        match ed.readline(&format!("um:{}> ", pos.line)) {
            Ok(line) => {
                if line.trim().is_empty() {
                    println!();
                    continue;
                }
                ed.add_history_entry(line.clone());

                // Run the line
                let (vars, _) = run("<stdin>", &line, &nenv, Some(pos.clone()), (0, true));
                if let Some(vars) = vars {
                    nenv.update(vars);
                }
                pos.line += 1;
            },
            Err(Interrupted) => {
                println!("^C");
                return
            },
            Err(Eof) => continue,
            Err(m) => {
                println!("Error: {:?}", m);
                continue;
            },
        }
    }
}
pub fn run_interactive<'a>(env: &'a Env<'a>) {
    #[cfg(feature = "readline")]
    return run_interactive_readline(env);

    #[cfg(not(feature = "readline"))]
    {
        let mut nenv = Env::child(env);
        let mut pos = Pos::start("<stdin>");
        let mut line = String::new();
        loop {
            // Read a line from input
            line.clear();
            print!("um:{}> ", pos.line);
            io::stdout().flush().unwrap();
            io::stdin().lock().read_line(&mut line).unwrap();
            if line.trim().is_empty() {
                println!();
                continue;
            }

            // Run the line
            let (vars, _) = run("<stdin>", &line, &nenv, Some(pos.clone()), (0, true));
            if let Some(vars) = vars {
                nenv.update(vars);
            }
            pos.line += 1;
        }
    }
}