Improve source excerpt highlighting

This commit is contained in:
Chris Penner 2024-03-13 12:14:31 -07:00
parent 3d95906195
commit 4ac7bb20cd
3 changed files with 17 additions and 9 deletions

View File

@ -215,7 +215,7 @@ foo = match 1 with
3 |
I was surprised to find an end of section here.
I was hoping for one of these instead:
I was expecting one of these instead:
* ","
* case match
@ -261,7 +261,7 @@ x = match Some a with
7 |
I was surprised to find an end of section here.
I was hoping for one of these instead:
I was expecting one of these instead:
* ","
* blank
@ -289,7 +289,7 @@ x = match Some a with
I was surprised to find a -> here.
I was hoping for one of these instead:
I was expecting one of these instead:
* newline or semicolon
@ -311,7 +311,7 @@ x = match Some a with
I was surprised to find a '|' here.
I was hoping for one of these instead:
I was expecting one of these instead:
* newline or semicolon

View File

@ -15,7 +15,7 @@ x =
I was surprised to find a 1 here.
I was hoping for one of these instead:
I was expecting one of these instead:
* end of input
* hash (ex: #af3sj3)
@ -79,7 +79,7 @@ x = "hi
2 |
I was surprised to find an end of input here.
I was hoping for one of these instead:
I was expecting one of these instead:
* "
* \s
@ -99,7 +99,7 @@ y : a
2 |
I was surprised to find an end of section here.
I was hoping for one of these instead:
I was expecting one of these instead:
* ->
* newline or semicolon

View File

@ -278,12 +278,20 @@ lexer0' scope rem =
& fmap errorItemToString
& maybeToList
& Set.fromList
errorLength :: Int
errorLength = case Set.toList unexpectedStr of
[] -> 0
(x : _) -> length x
expectedStr :: Set String
expectedStr =
expectedTokens
& Set.map errorItemToString
err = UnexpectedTokens $ formatTrivialError unexpectedStr expectedStr
in [Token (Err err) (toPos top) (toPos top)]
startPos = toPos top
-- This is just an attempt to highlight errors better in source excerpts.
-- It may not work in all cases, but should generally provide a better experience.
endPos = startPos & \(Pos l c) -> Pos l (c + errorLength)
in [Token (Err err) startPos endPos]
in errsWithSourcePos >>= errorToTokens
Right ts -> Token (Open scope) topLeftCorner topLeftCorner : tweak ts
where
@ -330,7 +338,7 @@ formatTrivialError unexpectedTokens expectedTokens =
xs -> "I was surprised to find these:\n\n* " <> List.intercalate "\n* " xs
expectedMsg = case Set.toList expectedTokens of
[] -> Nothing
xs -> Just $ "\nI was hoping for one of these instead:\n\n* " <> List.intercalate "\n* " xs
xs -> Just $ "\nI was expecting one of these instead:\n\n* " <> List.intercalate "\n* " xs
in concat $ catMaybes [Just unexpectedMsg, expectedMsg]
displayLexeme :: Lexeme -> String