use std::sync::Arc;
use lex_ast::canonicalize_program;
use lex_bytecode::vm::Vm;
use lex_bytecode::{compile_program, Value};
use lex_syntax::parse_source;
const SRC: &str = r#"
fn sum_to(n :: Int, acc :: Int) -> Int {
match n {
0 => acc,
_ => sum_to(n - 1, acc + n),
}
}
fn drive(n :: Int) -> Int {
sum_to(n, 0)
}
"#;
fn main() {
let args: Vec<String> = std::env::args().collect();
let n: i64 = args.get(1).and_then(|s| s.parse().ok()).unwrap_or(20000);
let iters: u64 = args.get(2).and_then(|s| s.parse().ok()).unwrap_or(3);
let prog = parse_source(SRC).expect("parse");
let stages = canonicalize_program(&prog);
lex_types::check_program(&stages).expect("typecheck");
let p = Arc::new(compile_program(&stages));
let mut acc = 0i64;
for _ in 0..iters {
let mut vm = Vm::new(&p);
vm.set_step_limit(u64::MAX);
if let Value::Int(v) = vm.call("drive", vec![Value::Int(n)]).unwrap() {
acc = acc.wrapping_add(v);
}
}
std::process::exit((acc & 0x7f) as i32);
}