aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: b507cbd66d23a99b0474fee622a90b893c0fe07d (plain)
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

use myslip::parse::parsetree::parse_to_ast;
use myslip::sexp::{SExp::*, SLeaf::{Nil, Let}, util::scons};
use std::{io, io::Write};

fn main() {
    match repl() {
        Ok(()) => println!("bye :)"),
        Err(e) => println!("Error: {}", e),
    }
}

fn prompt_line(stdin: &io::Stdin, stdout: &mut io::Stdout) -> Result<(bool, String), io::Error> {
    let mut line = String::new();
    print!("> ");
    match stdout.flush() {
        Ok(_) => (),
        Err(_) => println!("Enter s-expression:"),
    };
    let code = stdin.read_line(&mut line)?;
    Ok((code == 0, line))
}

fn repl() -> Result<(), io::Error> {

    let stdin = io::stdin();
    let mut stdout = io::stdout();

    let mut binds = vec![];

    loop {

	let (eof, input) = prompt_line(&stdin, &mut stdout)?;

	if eof || input == "exit\n" {
	    break;
	}

        let mut expression = match parse_to_ast(&input) {
            Ok(SCons(a, b)) if *b == Atom(Nil) => *a,
            Ok(t) => t,
	    Err(e) => {
		println!("Syntax error: {}", e);
		continue;
	    },
        };

	match &expression {
	    SCons(l, _) if **l == Atom(Let) => match scons(expression.clone(), Nil).type_check() {
		Ok(_) => {
		    binds.push(expression);
		    println!("Bind saved");
		    continue;
		},
		Err(e) => {
		    println!("Type error: {e}");
		    continue;
		}
	    },
	    _ => (),
	}

	for i in 1..=binds.len() {
	    expression = scons(binds[binds.len() - i].clone(), expression);
	}

        let ty = match expression
	    .type_check()
	    .map_err(|e| e.to_string()) {
		Ok(t) => t,
		Err(e) => {
		    println!("Type error: {}", e);
		    continue;
		},
	    };

        let result = match expression.multistep() {
	    Ok(t) => t,
	    Err(e) => {
		println!("Runtime error: {}", e);
		continue;
	    },
	};

        println!("{} : {}", result, ty);

    }

    Ok(())

}