Refactor the read loop into Reader

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

View File

@@ -62,35 +62,23 @@ class Kiss {
if (k == null)
k = defaultKissState();
while (true) {
stream.dropWhitespace();
if (stream.isEmpty())
break;
var position = stream.position();
var nextExp = Reader.read(stream, k.readTable);
// The last expression might be a comment, in which case None will be returned
switch (nextExp) {
case Some(nextExp):
#if test
Sys.println(nextExp.def.toString());
#end
var field = readerExpToField(nextExp, k);
if (field != null) {
#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
Reader.readAndProcess(stream, k.readTable, (nextExp) -> {
#if test
Sys.println(nextExp.def.toString());
#end
var field = readerExpToField(nextExp, k);
if (field != null) {
#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);
}
}
});
return classFields;
} catch (err:CompileError) {

View File

@@ -148,6 +148,26 @@ class Reader {
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) {
return {
pos: pos,