Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle error tokens before whitespace/comments #347

Merged
merged 1 commit into from
Oct 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -179,39 +179,45 @@ object Scanner {
}
}

def eatWhitespace(
) = {
val (wsp, rest) = remaining.span(ch => ch.isWhitespace)
if (wsp.isEmpty())
false
else {
val eatWhitespace: PartialFunction[Unit, Unit] = {
object matches {
def unapply(
@nowarn("cat=unused") u: Unit
): Option[
(
String,
String,
)
] = {
val (wsp, rest) = remaining.span(ch => ch.isWhitespace)
if (wsp.isEmpty())
None
else
Some((wsp, rest))
}
}

{ case matches(wsp, rest) =>
whitespaceChains(wsp).foreach(add)
remaining = rest

true
}
}

def eatComments(
) =
if (!remaining.startsWith("//"))
false
else {
val eatComments: PartialFunction[Unit, Unit] = {
case _ if remaining.startsWith("//") =>
while (remaining.startsWith("//")) {
val (comment, rest) = remaining.span(_ != '\n')
add(TokenKind.COMMENT(comment))
remaining = rest
}
}

true
}
val readAny = readOne.orElse(eatWhitespace).orElse(eatComments)

def eatErrors(
) = {
// todo: bug: even if the next character starts a multi-char token, this will consider it an error.
// instead, we should rework "readOne" to consume arbitrary constant-length tokens, and also include the possibility that `rest` has comments or whitespace.
val (failures, _) = remaining.span { _ =>
if (readOne.isDefinedAt(()))
if (readAny.isDefinedAt(()))
// this will match. stop!
false
else {
Expand All @@ -231,9 +237,9 @@ object Scanner {
while (remaining.nonEmpty) {
val last = remaining

readOne.lift(()).isDefined ||
eatWhitespace() ||
eatComments() ||
readAny
.lift(())
.isDefined ||
eatErrors(): Unit

// last-effort sanity check
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,19 @@ object ScannerTests extends SimpleIOSuite with Checkers with ScannerSuite {
)
)

scanTest(explicitName = "Error tokens before a comment", input = "--//hello")(
List(
Error("--"),
COMMENT("//hello"),
)
)

scanTest(explicitName = "Error tokens before whitespace", input = "-- ")(
List(
Error("--"),
SPACE(" "),
)
)
// complex cases

scanTestReverse(
Expand Down