Refactor the read loop into Reader

This commit is contained in:
2020-12-08 18:58:38 -07:00
parent 419e72e280
commit b4bf0d1576
2 changed files with 36 additions and 28 deletions

View File

@@ -62,35 +62,23 @@ class Kiss {
if (k == null) if (k == null)
k = defaultKissState(); k = defaultKissState();
while (true) { Reader.readAndProcess(stream, k.readTable, (nextExp) -> {
stream.dropWhitespace(); #if test
if (stream.isEmpty()) Sys.println(nextExp.def.toString());
break; #end
var position = stream.position(); var field = readerExpToField(nextExp, k);
var nextExp = Reader.read(stream, k.readTable); if (field != null) {
#if test
// The last expression might be a comment, in which case None will be returned switch (field.kind) {
switch (nextExp) { case FVar(_, expr) | FFun({ret: _, args: _, expr: expr}):
case Some(nextExp): Sys.println(expr.toString());
#if test default:
Sys.println(nextExp.def.toString()); throw CompileError.fromExp(nextExp, 'cannot print the expression of generated field $field');
#end }
var field = readerExpToField(nextExp, k); #end
if (field != null) { classFields.push(field);
#if test
switch (field.kind) {
case FVar(_, expr) | FFun({ret: _, args: _, expr: expr}):
Sys.println(expr.toString());
default:
throw CompileError.fromExp(nextExp, 'cannot print the expression of generated field $field');
}
#end
classFields.push(field);
}
case None:
stream.dropWhitespace(); // If there was a comment, drop whitespace that comes after
} }
} });
return classFields; return classFields;
} catch (err:CompileError) { } catch (err:CompileError) {

View File

@@ -148,6 +148,26 @@ class Reader {
return array; return array;
} }
/**
Read all the expressions in the given stream, processing them one by one while reading.
**/
public static function readAndProcess(stream:Stream, readTable:Map<String, ReadFunction>, process:(ReaderExp) -> Void) {
while (true) {
stream.dropWhitespace();
if (stream.isEmpty())
break;
var position = stream.position();
var nextExp = Reader.read(stream, readTable);
// The last expression might be a comment, in which case None will be returned
switch (nextExp) {
case Some(nextExp):
process(nextExp);
case None:
stream.dropWhitespace(); // If there was a comment, drop whitespace that comes after
}
}
}
public static function withPos(def:ReaderExpDef, pos:Position) { public static function withPos(def:ReaderExpDef, pos:Position) {
return { return {
pos: pos, pos: pos,