From 38dc63a67879a42f208b5642a8590e1192e8e2e5 Mon Sep 17 00:00:00 2001 From: Ben Winston Date: Sat, 20 May 2023 18:58:51 -0400 Subject: global variables --- compiler.d | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) (limited to 'compiler.d') diff --git a/compiler.d b/compiler.d index 51e45ba..739f887 100644 --- a/compiler.d +++ b/compiler.d @@ -1,5 +1,7 @@ import std.stdio; import std.string; +import std.conv; +import std.algorithm : canFind; import parser; import chunk; @@ -86,6 +88,33 @@ class Compiler { func.chunk.writeOp(OpCode.OP_LESS, current.line); } + void compileDef(Form form) { + Def def = cast(Def)form; + + // add the variable name to the chunk + int addr = func.chunk.addConstant(makeStringValue(def.name.name)); + + // resolve the value + resolve(def.val); + + // define the variable + func.chunk.writeOp(OpCode.OP_DEFINE_GLOBAL, current.line); + func.chunk.writeOp(to!ubyte(addr), current.line); + } + + void compileSymbol(Form form) { + Symbol sym = cast(Symbol)form; + + // add the symbol name to the chunk + int addr = func.chunk.addConstant(makeStringValue(sym.name)); + + // get the variable + func.chunk.writeOp(OpCode.OP_GET_GLOBAL, sym.line); + func.chunk.writeOp(to!ubyte(addr), sym.line); + + advance(); + } + void compileCons(Form form) { Cons cons = cast(Cons)form; Form head = cons.head; @@ -110,8 +139,11 @@ class Compiler { compileLess(cons.tail); break; default: + /* writefln("unsure how to compile %s", sym.name); advance(); + */ + resolve(head); break; } @@ -130,6 +162,12 @@ class Compiler { case FormType.NIL: this.compileNil(form); break; + case FormType.DEF: + this.compileDef(form); + break; + case FormType.SYMBOL: + this.compileSymbol(form); + break; default: write("not sure how to resolve: "); printForm(form); -- cgit v1.2.3