packages feed

morley-1.17.0: src/Morley/Michelson/Parser/Error.hs

-- SPDX-FileCopyrightText: 2021 Oxhead Alpha
-- SPDX-License-Identifier: LicenseRef-MIT-OA

-- |  Custom exceptions that can happen during parsing.

module Morley.Michelson.Parser.Error
  ( CustomParserException (..)
  , StringLiteralParserException (..)
  , ParseErrorBundle
  , ParserException (..)
  ) where

import Data.Data (Data(..))
import Fmt (Buildable(build), pretty)
import Text.Megaparsec (ParseErrorBundle, ShowErrorComponent(..), errorBundlePretty)

import Morley.Michelson.Untyped.View
import Morley.Util.Instances ()

data CustomParserException
  = StringLiteralException StringLiteralParserException
  | ViewNameException BadViewNameError
  | OddNumberBytesException
  | ExcessFieldAnnotation
  deriving stock (Eq, Data, Ord, Show, Generic)

instance NFData CustomParserException

instance ShowErrorComponent CustomParserException where
  showErrorComponent (StringLiteralException e) = showErrorComponent e
  showErrorComponent (ViewNameException e) = pretty e
  showErrorComponent OddNumberBytesException = "odd number bytes"
  showErrorComponent ExcessFieldAnnotation = "excess field annotation"

data StringLiteralParserException
  = InvalidEscapeSequence Char
  | InvalidChar Char
  deriving stock (Eq, Data, Ord, Show, Generic)

instance NFData StringLiteralParserException

instance ShowErrorComponent StringLiteralParserException where
  showErrorComponent (InvalidEscapeSequence c) =
    "invalid escape sequence '\\" <> [c] <> "'"
  showErrorComponent (InvalidChar c) =
    "invalid character '" <> [c] <> "'"

data ParserException =
  ParserException (ParseErrorBundle Text CustomParserException)
  deriving stock (Eq, Show)

instance Exception ParserException where
  displayException (ParserException bundle) = errorBundlePretty bundle

instance Buildable ParserException where
  build (ParserException bundle) = build $ errorBundlePretty bundle