Read and compile full toplevel multiline program

This commit is contained in:
Konstantin Nazarov 2024-08-18 22:08:47 +01:00
parent 4bd21e0e17
commit fdf38c71bf
Signed by: knazarov
GPG key ID: 4CFE0A42FA409C22
6 changed files with 57 additions and 3 deletions

View file

@ -95,7 +95,13 @@ Result<bool> is_primitive_op(Symbol& sym) {
Result<Value> Compiler::compile(Value& expr) {
auto context = TRY(Context::create());
auto ex = TRY(compile_expr(context, expr));
if (!expr.is<Pair>()) {
return ERROR(CompilationError);
}
Pair& expr_pair = *expr.to<Pair>();
auto ex = TRY(compile_body(context, expr_pair));
TRY(ex.add_opcode(Oc::Ret, {0, (int64_t)ex.reg}));
Value name = TRY(Nil::create());

View file

@ -423,3 +423,8 @@ Result<Value> read_one(const char* value) {
auto r = Reader(s);
return r.read_one();
}
Result<Value> read_multiple(String& value) {
auto r = Reader(value);
return r.read_multiple();
}

View file

@ -45,3 +45,5 @@ class Reader {
Result<Value> read_one(Value& value);
Result<Value> read_one(String& value);
Result<Value> read_one(const char* value);
Result<Value> read_multiple(String& value);

View file

@ -26,8 +26,8 @@ Result<void> run(int argc, const char* argv[]) {
// auto code_str =
// TRY(String::create("((lambda (f y) (f y)) (lambda (x) (* x x)) 2)"));
auto parsed = TRY(read_one(src));
auto code_str_written = TRY(write_one(parsed));
auto parsed = TRY(read_multiple(src));
auto code_str_written = TRY(write_multiple(parsed));
TRY(arena_gc());

View file

@ -37,6 +37,31 @@ Result<String> Writer::write_one(const Value& obj) {
return String();
}
Result<String> Writer::write_multiple(const Value& val) {
String res = TRY(String::create(""));
Value cur = TRY(val.copy());
bool is_first = true;
while (!cur.is<Nil>()) {
if (!cur.is<Pair>()) return ERROR(MalformedList);
Pair& pair = *cur.to<Pair>();
Value first = TRY(pair.first());
if (!is_first) res = TRY(res.concat("\n"));
String first_str = TRY(write_one(first));
res = TRY(res.concat(first_str));
cur = TRY(pair.rest());
is_first = false;
}
res = TRY(res.concat(""));
return res;
}
Result<String> Writer::write_int64(const Int64& val) {
char tmp[32];
sprintf(tmp, "%lu", val.value());
@ -301,3 +326,8 @@ Result<String> write_one(const Value& value) {
auto w = Writer();
return w.write_one(value);
}
Result<String> write_multiple(const Value& value) {
auto w = Writer();
return w.write_multiple(value);
}

View file

@ -37,3 +37,14 @@ Result<String> write_one(const T& value)
auto v = DIEX(value.copy_value());
return w.write_one(v);
}
Result<String> write_multiple(const Value& value);
template <class T>
Result<String> write_multiple(const T& value)
requires std::derived_from<T, Object>
{
auto w = Writer();
auto v = DIEX(value.copy_value());
return w.write_multiple(v);
}