@@ -2,7 +2,7 @@ module Parser.Advanced exposing
22 ( Parser, run, DeadEnd, inContext, Token(..)
33 , int, float, number, symbol, keyword, variable, end
44 , succeed, (|=), (|.), keep, skip, lazy, andThen, problem
5- , oneOf, map, backtrackable, commit, token
5+ , oneOf, map, mapError, backtrackable, commit, token
66 , sequence, Trailing(..), loop, Step(..)
77 , spaces, lineComment, multiComment, Nestable(..)
88 , getChompedString, chompIf, chompWhile, chompUntil, chompUntilEndOr, mapChompedString
@@ -30,7 +30,7 @@ certain scenarios.**
3030@docs succeed, (|=), (|.), keep, skip, lazy, andThen, problem
3131
3232# Branches
33- @docs oneOf, map, backtrackable, commit, token
33+ @docs oneOf, map, mapError, backtrackable, commit, token
3434
3535# Loops
3636@docs sequence, Trailing, loop, Step
@@ -254,7 +254,6 @@ bagToArray bag array =
254254 bagToArray bag1 (bagToArray bag2 array)
255255
256256
257-
258257-- PRIMITIVES
259258
260259
@@ -288,8 +287,45 @@ map func (Parser parse) =
288287 Good { pred = p, value = a, state = s1 } ->
289288 Good { pred = p, value = (func a), state = s1 }
290289
291- Bad { pred, bag = x } ->
292- Bad { pred = pred, bag = x }
290+ Bad { pred, bag } ->
291+ Bad { pred = pred, bag = bag }
292+
293+
294+ {-| Transform the `Error` of a parser.
295+ -}
296+ mapError : (errA -> errB) -> Parser c errA x -> Parser c errB x
297+ mapError func (Parser parse) =
298+ Parser <| \s0 ->
299+ when parse s0 is
300+ Good { pred = p, value = a, state = s1 } ->
301+ Good { pred = p, value = a, state = s1 }
302+
303+ Bad { pred, bag } ->
304+ Bad { pred = pred, bag = mapBagProblem func bag }
305+
306+
307+ mapBagProblem : (a -> b) -> Bag c a -> Bag c b
308+ mapBagProblem mapper bag =
309+ when bag is
310+ Empty ->
311+ Empty
312+
313+ AddRight { bag = bag1, deadEnd } ->
314+ AddRight
315+ { bag = mapBagProblem mapper bag1
316+ , deadEnd =
317+ { row = deadEnd.row
318+ , col = deadEnd.col
319+ , problem = mapper deadEnd.problem
320+ , contextStack = deadEnd.contextStack
321+ }
322+ }
323+
324+ Append { left = bag1, right = bag2 } ->
325+ Append
326+ { left = mapBagProblem mapper bag1
327+ , right = mapBagProblem mapper bag2
328+ }
293329
294330
295331map2 : (a -> b -> value) -> Parser c x a -> Parser c x b -> Parser c x value
0 commit comments