Refactor reader macros in AOC Day 8 pt 1

This commit is contained in:
2020-12-09 21:46:07 -07:00
parent 1a5eb07d48
commit 3afad56f71
4 changed files with 25 additions and 31 deletions

View File

@@ -197,6 +197,7 @@ class Helpers {
interp.variables.set("read", Reader.assertRead.bind(_, k.readTable));
interp.variables.set("readExpArray", Reader.readExpArray.bind(_, _, k.readTable));
interp.variables.set("ReaderExp", ReaderExpDef);
interp.variables.set("nextToken", Reader.nextToken.bind(_, "a token"));
interp.variables.set("kiss", {
Reader: {
ReaderExpDef: ReaderExpDef
@@ -247,8 +248,15 @@ class Helpers {
FieldExp(field, evalUnquotes(innerExp, k, args));
case KeyValueExp(keyExp, valueExp):
KeyValueExp(evalUnquotes(keyExp, k, args), evalUnquotes(valueExp, k, args));
case Unquote(exp):
runAtCompileTime(exp, k, args).def;
case Unquote(innerExp):
var unquoteValue:Dynamic = runAtCompileTime(innerExp, k, args);
if (unquoteValue == null) {
throw CompileError.fromExp(innerExp, "unquote evaluated to null");
} else if (Std.isOfType(unquoteValue, ReaderExpDef)) {
unquoteValue;
} else {
unquoteValue.def;
};
default:
throw CompileError.fromExp(exp, 'unquote evaluation not implemented');
};

View File

@@ -93,8 +93,12 @@ class Reader {
public static final terminators = [")", "]", "/*", "\n", " "];
static function nextToken(stream:Stream, expect:String) {
return stream.expect(expect, () -> stream.takeUntilOneOf(terminators));
public static function nextToken(stream:Stream, expect:String) {
var tok = stream.expect(expect, () -> stream.takeUntilOneOf(terminators));
if (tok.length == 0) {
throw 'Expected token $expect at ${stream.position()}';
}
return tok;
}
public static function assertRead(stream:Stream, readTable:Map<String, ReadFunction>):ReaderExp {

View File

@@ -158,7 +158,7 @@ class Stream {
switch (f()) {
case Some(s):
return s;
case None:
default:
throw 'Expected $whatToExpect at $position';
}
}

View File

@@ -1,28 +1,10 @@
(load "BootCodeCommon.kiss")
(defreadermacro "" [stream] #| ReaderExp.CallExp(
{
pos: {file: "bleh", line: 1, column: 1, absoluteChar: 1},
def: ReaderExp.Symbol(stream.expect("an instruction", function () { stream.takeUntilAndDrop(" "); }))
},
[
{
pos: {file: "fefea", line: 1, column: 1, absoluteChar: 1},
def: ReaderExp.CallExp(
{
pos: {file: "treh", line: 1, column: 1, absoluteChar: 1},
def: ReaderExp.Symbol(stream.expect("+/-", function () { stream.takeChars(1); }))
},
[
{
pos: {file: "smeeh", line: 1, column: 1, absoluteChar: 1},
def: ReaderExp.Symbol("0")
},
{
pos: {file: "greeeh", line: 1, column: 1, absoluteChar: 1},
def: ReaderExp.Symbol(stream.expect("an argument", function () { stream.takeUntilAndDrop("\n"); }))
}
])
}
])
|#)
(defreadermacro "" [stream]
`(,(ReaderExp.Symbol
(begin (stream.dropWhitespace) (nextToken stream)))
(,(ReaderExp.Symbol
(begin (stream.dropWhitespace) (stream.expect "+/-" (lambda [] (stream.takeChars 1)))))
0
,(ReaderExp.Symbol
(nextToken stream)))))