From b4bf0d1576c8f45ebb8eb1d2ff0d062c4f15ef97 Mon Sep 17 00:00:00 2001 From: Nat Quayle Nelson Date: Tue, 8 Dec 2020 18:58:38 -0700 Subject: [PATCH] Refactor the read loop into Reader --- kiss/src/kiss/Kiss.hx | 44 +++++++++++++++-------------------------- kiss/src/kiss/Reader.hx | 20 +++++++++++++++++++ 2 files changed, 36 insertions(+), 28 deletions(-) diff --git a/kiss/src/kiss/Kiss.hx b/kiss/src/kiss/Kiss.hx index 8e5bc429..7d30d766 100644 --- a/kiss/src/kiss/Kiss.hx +++ b/kiss/src/kiss/Kiss.hx @@ -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) { diff --git a/kiss/src/kiss/Reader.hx b/kiss/src/kiss/Reader.hx index 7fb7e0e9..5d31afd0 100644 --- a/kiss/src/kiss/Reader.hx +++ b/kiss/src/kiss/Reader.hx @@ -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, 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,