Skip to content

Commit b0d23a3

Browse files
jamesdbrockthomashoneyman
authored andcommitted
Parsing failure context region (#97)
1 parent fe969c3 commit b0d23a3

File tree

2 files changed

+12
-10
lines changed

2 files changed

+12
-10
lines changed

src/Text/Parsing/Parser.purs

+7-6
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ module Text.Parsing.Parser
1313
, position
1414
, fail
1515
, failWithPosition
16-
, label
16+
, region
1717
) where
1818

1919
import Prelude
@@ -138,8 +138,9 @@ fail message = failWithPosition message =<< position
138138
failWithPosition :: forall m s a. Monad m => String -> Position -> ParserT s m a
139139
failWithPosition message pos = throwError (ParseError message pos)
140140

141-
-- | If parsing fails inside this labelled context, then prepend the `String`
142-
-- | to the error `String` in the `ParseError`.
143-
label :: forall m s a. Monad m => String -> ParserT s m a -> ParserT s m a
144-
label messagePrefix p = catchError p $ \ (ParseError message pos) ->
145-
throwError $ ParseError (messagePrefix <> message) pos
141+
-- | Contextualize parsing failures inside a region. If a parsing failure
142+
-- | occurs, then the `ParseError` will be transformed by each containing
143+
-- | `region` as the parser backs out the call stack.
144+
region :: forall m s a. Monad m => (ParseError -> ParseError) -> ParserT s m a -> ParserT s m a
145+
region context p = catchError p $ \err -> throwError $ context err
146+

test/Main.purs

+5-4
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import Data.Tuple (Tuple(..))
1414
import Effect (Effect)
1515
import Effect.Console (logShow)
1616
import Test.Assert (assert')
17-
import Text.Parsing.Parser (Parser, ParserT, ParseError(..), runParser, parseErrorPosition, label)
17+
import Text.Parsing.Parser (Parser, ParserT, ParseError(..), runParser, parseErrorPosition, region)
1818
import Text.Parsing.Parser.Combinators (endBy1, sepBy1, optionMaybe, try, chainl, between)
1919
import Text.Parsing.Parser.Expr (Assoc(..), Operator(..), buildExprParser)
2020
import Text.Parsing.Parser.Language (javaStyle, haskellStyle, haskellDef)
@@ -501,11 +501,12 @@ main = do
501501
case runParser "aa" p of
502502
Right _ -> assert' "error: ParseError expected!" false
503503
Left (ParseError message pos) -> do
504-
let messageExpected = "context1context2Expected \"b\""
504+
let messageExpected = "context1 context2 Expected \"b\""
505505
assert' ("expected message: " <> messageExpected <> ", message: " <> message) (message == messageExpected)
506506
logShow messageExpected
507507
where
508-
p = label "context1" $ do
508+
prependContext m' (ParseError m pos) = ParseError (m' <> m) pos
509+
p = region (prependContext "context1 ") $ do
509510
_ <- string "a"
510-
label "context2" $ do
511+
region (prependContext "context2 ") $ do
511512
string "b"

0 commit comments

Comments
 (0)