From 3535bfefccea789169786767ac80c54241cae019 Mon Sep 17 00:00:00 2001 From: mryouse Date: Thu, 25 May 2023 22:45:23 +0000 Subject: lambdas! --- compiler.d | 48 +++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 41 insertions(+), 7 deletions(-) (limited to 'compiler.d') diff --git a/compiler.d b/compiler.d index 6f5f0fd..92711f1 100644 --- a/compiler.d +++ b/compiler.d @@ -555,6 +555,36 @@ class Compiler { // create a copy of the list } + void compileLambda(Form form) { + Lambda lamb = cast(Lambda)form; + Compiler compiler = new Compiler(ObjType.FUNCTION, this.parser, ""); + compiler.beginScope(); + + if (lamb.args.type != FormType.NIL) { + Symbol sym = cast(Symbol)lamb.args.head; + int constant = compiler.parseVariable(sym); + compiler.defineVariable(constant); + + foreach (Form inner ; lamb.args.tail) { + sym = cast(Symbol)inner; + constant = compiler.parseVariable(sym); + compiler.defineVariable(constant); + } + } + + advance(); // ?? + + Block b = new Block(lamb.line); + b.blockBody = lamb.lambdaBody; + compiler.compileBlock(b); + + // write the function as a Value + Function outFunc = compiler.finish(); + this.func.chunk.writeOp(OpCode.OP_CONSTANT, lamb.line); + int funcAddr = this.func.chunk.addConstant(makeObjValue(outFunc)); + this.func.chunk.writeOp(to!ubyte(funcAddr), lamb.line); + } + void compileFunc(Form form) { Func f = cast(Func)form; @@ -576,13 +606,6 @@ class Compiler { } } - /* - // compile each inner Form - foreach (Form inner; f.funcBody) { - compiler.resolve(inner); - } - */ - advance(); // ?? Block b = new Block(f.line); @@ -602,6 +625,14 @@ class Compiler { ValueType compileCons(Form form, ValueType expected) { Cons cons = cast(Cons)form; Form head = cons.head; + + if (head.type == FormType.LAMBDA) { + this.resolve(head); + this.call(cons.tail); + this.advance(); + return ValueType.NIL; + } + if (head.type != FormType.SYMBOL) { writeln("cons must start with a symbol"); this.advance(); @@ -700,6 +731,9 @@ class Compiler { case FormType.FUNC: this.compileFunc(form); break; + case FormType.LAMBDA: + this.compileLambda(form); + break; default: write("not sure how to resolve: "); printForm(form); -- cgit v1.2.3