aboutsummaryrefslogtreecommitdiff
path: root/src/main.rs
blob: 30bd1367546e88f063e01cdba97f4e1a3344a7ad (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
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

use myslip::parse::parsetree::parse_to_ast;
use myslip::sexp::{SExp, SExp::*, SLeaf::Nil, util::scons};
use myslip::r#type::Type::NilType;
use std::{io, io::Write, io::Read, env};
use std::fs::File;


fn read_bind_files(
    file_names: Vec<String>
) -> Result<Vec<SExp>, String> {
    let mut res = vec![];
    for name in file_names {
	let mut file = File::open(name).map_err(|e| e.to_string())?;
	let mut contents = String::new();
	file.read_to_string(&mut contents)
	    .map_err(|e| e.to_string())?;
	let exps = parse_to_ast(&contents)?.parts();
	for exp in exps {
	    if exp.clone().check_let().is_some() {
		res.push(exp);
	    } else {
		return Err(format!("'{}' isn't a declaration", exp));
	    }
	}
    }
    Ok(res)
}

fn read_file_to_execute(
    file_name: String
) -> Result<SExp, String> {
    let mut file = File::open(file_name)
	.map_err(|e| e.to_string())?;
    let mut contents = String::new();
    file.read_to_string(&mut contents)
	.map_err(|e| e.to_string())?;
    match parse_to_ast(&contents) {
	Ok(SCons(a, b)) if *b == Atom(Nil) => Ok(*a),
	t => t
    }
}

fn main() {

    let mut file_to_execute: Option<String> = None;

    let mut bind_files: Vec<String> = vec!["stdlib.slip".to_string()];

    let mut next_is_load = false;
    let mut no_stdlib = false;
    let mut help = false;
    for arg in env::args() {

	if next_is_load {
	    bind_files.push(arg);
	    next_is_load = false;
	    continue;
	}

	match arg.as_str() {
	    s if s.ends_with("myslip") => continue,
	    "-l" | "--load" => next_is_load = true,
	    "--no-stdlib" => no_stdlib = true,
	    "--help" | "-h" | "-?" => help = true,
	    s => match file_to_execute {
		Some(n) => {
		    println!("Error: can't execute both '{}' and '{}', please specify just one file. See '--help' for correct syntax.", s, n);
		    return;
		},
		None => file_to_execute = Some(s.to_string()),
	    }
	}

    }
    if help {
	println!("{}", String::from("") +
		 "myslip [options] [file]\n" +
		 "\n" +
		 "If [file] is given, executes the s-expression contained by\n" +
		 "the file. Otherwise starts the myslip repl.\n" +
		 "\n" +
		 "Options:\n" +
		 "\n" +
		 "  --load [defs] | -l [defs]  loads declarations from file\n" +
		 "                             named [defs] before execution\n" +
		 "\n" +
		 "  --no-stdlib                stops myslip from loading the\n" +
		 "                             standard library at startup\n" +
		 "\n" +
		 "  --help | -h | -?           displays this help message\n"

	);
	return;
    }
    if next_is_load {
	println!(
"Error: '--load' can't be the last element of the argument list. See '--help' for correct syntax."
	);
	return;
    }
    if no_stdlib {
	bind_files.remove(0);
    }

    let binds = match read_bind_files(bind_files) {
	Ok(x) => x,
	Err(e) => {
	    println!(
		"Error reading declarations from files: {}",
		e.to_string()
	    );
	    return;
	}
    };

    match file_to_execute {
	Some(name) => {
	    let exp = match read_file_to_execute(name) {
		Ok(e) => e,
		Err(e) => {
		    println!("Error reading source file: {e}");
		    return;
		}
	    };
	    execute_expression(&binds, exp);
	},
	None => {
	    match repl(binds) {
		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 execute_expression(binds: &Vec<SExp>, mut exp: SExp) {

    for bind in binds.into_iter().rev() {
	exp = scons(bind.clone(), exp);
    }

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

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

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

}

fn repl(mut binds: Vec<SExp>) -> Result<(), io::Error> {

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

    loop {

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

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

        let orig_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;
	    },
        };
	if let Some((name, _value)) = orig_expression.clone().check_let() {
	    let mut expr = scons(orig_expression.clone(), scons(Nil, Nil));
	    for i in 1..=binds.len() {
		expr = scons(binds[binds.len() - i].clone(), expr);
	    }
	    match expr.type_check() {
		Ok(NilType) => {
		    binds.push(orig_expression);
		    println!("{name} saved");
		    continue;
		},
		Err(e) => {
		    println!("Type error: {}", e);
		    continue;
		},
		Ok(_) => (),
	    }
	}

	execute_expression(&binds, orig_expression);
    }

    Ok(())

}