var fd = use("fd")
var json = use("json")
var tokenize = use("tokenize")
var parse = use("parse")
var fold = use("fold")

var src = text(fd.slurp("internal/bootstrap.cm"))
var tok_result = tokenize(src, "bootstrap.cm")
var ast = parse(tok_result.tokens, src, "bootstrap.cm", tokenize)
var i = 0
var folded = null
var ast_json = null
var f = null
var bytecode = null
var has_errors = ast.errors != null && length(ast.errors) > 0
if (has_errors) {
  log.error("PARSE ERRORS:")
  while (i < length(ast.errors)) {
    log.error(text(ast.errors[i].line) + ":" + text(ast.errors[i].column) + " " + ast.errors[i].message)
    i = i + 1
  }
} else {
  log.test("Parse OK")
  log.test("  statements: " + text(length(ast.statements)))
  if (ast.functions != null) {
    log.test("  functions: " + text(length(ast.functions)))
  } else {
    log.test("  functions: null")
  }
  folded = fold(ast)
  ast_json = json.encode(folded)
  f = fd.open("/tmp/bootstrap_ast.json", "w")
  fd.write(f, ast_json)
  fd.close(f)
  log.test("Wrote AST to /tmp/bootstrap_ast.json")
  bytecode = mach_compile_ast("bootstrap", ast_json)
  log.test("Bytecode size: " + text(length(bytecode)))
  f = fd.open("/tmp/bootstrap_test.mach", "w")
  fd.write(f, bytecode)
  fd.close(f)
  log.test("Wrote bytecode to /tmp/bootstrap_test.mach")
}
