ADD: set! function.

main
bog 2023-09-12 12:20:29 +02:00
parent 29fded5cb9
commit f7b470c0b1
4 changed files with 32 additions and 1 deletions

View File

@ -49,4 +49,4 @@
(-> (n)
(* 3 (- n 2))))
(assert-eq? 15 ( (h) 7 ))
(assert-eq? 15 ( (h) 7 ))

10
examples/set.gri Normal file
View File

@ -0,0 +1,10 @@
($ a 1)
(set! a 2)
(assert-eq? 2 a )
($ (b x) (+ x 1))
($ (c x) (* x 2))
($ d b)
(assert-eq? 3 (d 2))
(set! d c)
(assert-eq? 4 (d 2))

View File

@ -1,6 +1,7 @@
#include "../src/Loader.hpp"
#include "src/Logger.hpp"
#include "src/Value.hpp"
#include "src/opcodes.hpp"
GRINO_ERROR(assertion_error);
@ -345,6 +346,24 @@ extern "C" void lib(grino::Loader& loader)
return grino::Value::make_nil(args.back()->loc());
});
loader.add_static("set!", [](auto& compiler,
auto node,
auto& program,
auto& sym){
std::string ident = node->child(1).lock()->repr();
auto expr = node->child(2).lock();
auto entry = sym.find(ident, compiler.scope());
if (entry)
{
compiler.compile(expr, program, sym);
program.push_instr(grino::OPCODE_STORE_LOCAL, entry->addr);
}
program.push_value(grino::Value::make_nil(node->loc()));
});
loader.add_native("eq?", [](auto args){
auto lhs = args.front();

View File

@ -20,6 +20,8 @@ namespace grino
explicit Compiler(Logger& logger);
virtual ~Compiler();
size_t scope() const { return m_scope.size(); }
void compile(std::shared_ptr<Node> node,
Program& program,
SymTable& sym);