diff options
| author | mryouse | 2023-05-25 22:45:23 +0000 |
|---|---|---|
| committer | mryouse | 2023-05-25 22:45:23 +0000 |
| commit | 3535bfefccea789169786767ac80c54241cae019 (patch) | |
| tree | ecc376d5d0effd75b31fb0a78ee55fedfc92b64a /compiler.d | |
| parent | 9fe6496202bd95d252ed2323a88fd24781780b64 (diff) | |
lambdas!
Diffstat (limited to 'compiler.d')
| -rw-r--r-- | compiler.d | 48 |
1 files changed, 41 insertions, 7 deletions
@@ -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, "<lambda>"); + 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); |
