Skip to content

Commit 8412e63

Browse files
jamesdbrockshmish111
authored andcommitted
Parsing failure context region (purescript-contrib#97)
1 parent 3febeaf commit 8412e63

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
@@ -13,7 +13,7 @@ import Data.Tuple (Tuple(..))
1313
import Effect (Effect)
1414
import Effect.Console (logShow)
1515
import Test.Assert (assert')
16-
import Text.Parsing.Parser (Parser, ParserT, ParseError(..), runParser, parseErrorPosition, label)
16+
import Text.Parsing.Parser (Parser, ParserT, ParseError(..), runParser, parseErrorPosition, region)
1717
import Text.Parsing.Parser.Combinators (endBy1, sepBy1, optionMaybe, try, chainl, between)
1818
import Text.Parsing.Parser.Expr (Assoc(..), Operator(..), buildExprParser)
1919
import Text.Parsing.Parser.Language (javaStyle, haskellStyle, haskellDef)
@@ -500,11 +500,12 @@ main = do
500500
case runParser "aa" p of
501501
Right _ -> assert' "error: ParseError expected!" false
502502
Left (ParseError message pos) -> do
503-
let messageExpected = "context1context2Expected \"b\""
503+
let messageExpected = "context1 context2 Expected \"b\""
504504
assert' ("expected message: " <> messageExpected <> ", message: " <> message) (message == messageExpected)
505505
logShow messageExpected
506506
where
507-
p = label "context1" $ do
507+
prependContext m' (ParseError m pos) = ParseError (m' <> m) pos
508+
p = region (prependContext "context1 ") $ do
508509
_ <- string "a"
509-
label "context2" $ do
510+
region (prependContext "context2 ") $ do
510511
string "b"

0 commit comments

Comments
 (0)