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

Make parseEscape errors more informative #37

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
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
18 changes: 15 additions & 3 deletions crypto-sodium/lib/Crypto/Sodium/Salt/Internal.hs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ module Crypto.Sodium.Salt.Internal
( parseEscapes
) where

import Control.Monad (liftM2)
import Data.Char (isSpace)
import Data.Maybe (listToMaybe)
import Text.ParserCombinators.ReadP (eof, readP_to_S, many)
import Text.ParserCombinators.ReadP (ReadP, readP_to_S, (<++))
import Text.Read.Lex (lexChar)

-- | Parse a Haskell string literal with escapes.
Expand All @@ -19,6 +21,16 @@ import Text.Read.Lex (lexChar)
--
-- This function can fail if there are invalid escape sequences.
parseEscapes :: MonadFail m => String -> m String
parseEscapes str = case listToMaybe (readP_to_S (many lexChar <* eof) str) of
parseEscapes str = case listToMaybe (readP_to_S (many' lexChar) str) of
Just (result, "") -> pure result
_ -> fail $ "Failed to parse raw bytes (no parse): " <> str
Just (_, rest) -> fail $ case rest of
'\\':rest' -> "Failed to parse character escape '\\"
<> takeWhile (\c -> not (isSpace c) && c /= '\\') rest' <> "'"
-- the next case shouldn't happen since 'lexChar' can only fail on escapes
_ -> "Failed to parse string with escapes"
<> " at input position " <> show (length str - length rest)
-- the last case shouldn't happen since parser will happily parse zero characters
_ -> fail $ "Failed to parse string with escapes: " <> str

many' :: ReadP a -> ReadP [a]
many' p = liftM2 (:) p (many' p) <++ pure []