Skip to content

A peer-to-peer stack for code collaboration

Add stack traces to error messages:

Luke Palmer2b0b37217901
diff --git a/.stylish-haskell.yaml b/.stylish-haskell.yaml
index 1140874..a4cc491 100644
--- a/.stylish-haskell.yaml
+++ b/.stylish-haskell.yaml
@@ -186,6 +186,7 @@ language_extensions:
- DeriveFunctor
- DeriveGeneric
- DeriveTraversable
+ - ExplicitNamespaces
- FlexibleContexts
- FlexibleInstances
- FunctionalDependencies
diff --git a/exe/Repl/Main.hs b/exe/Repl/Main.hs
index 1ee8904..f9881d8 100644
--- a/exe/Repl/Main.hs
+++ b/exe/Repl/Main.hs
@@ -8,13 +8,14 @@ import Radicle
main :: IO ()
main = do
opts' <- execParser allOpts
- cfgSrc <- readFile =<< case configFile opts' of
+ cfgFile <- case configFile opts' of
Nothing -> getConfig
Just cfg -> pure cfg
+ cfgSrc <- readFile cfgFile
hist <- case histFile opts' of
Nothing -> getHistory
Just h -> pure h
- repl (Just hist) cfgSrc replBindings
+ repl (Just hist) (toS cfgFile) cfgSrc replBindings
where
allOpts = info (opts <**> helper)
( fullDesc
diff --git a/exe/Server/Client.hs b/exe/Server/Client.hs
index 5c23800..159ab48 100644
--- a/exe/Server/Client.hs
+++ b/exe/Server/Client.hs
@@ -14,15 +14,16 @@ import System.Console.Haskeline (InputT)
main :: IO ()
main = do
opts' <- execParser allOpts
- cfgSrc <- readFile =<< case configFile opts' of
+ cfgFile <- case configFile opts' of
Nothing -> getConfig
Just cfg -> pure cfg
+ cfgSrc <- readFile cfgFile
hist <- case histFile opts' of
Nothing -> getHistory
Just h -> pure h
mgr <- newManager defaultManagerSettings
let cEnv = mkClientEnv mgr (serverURL opts')
- repl (Just hist) cfgSrc (bindings cEnv)
+ repl (Just hist) (toS cfgFile) cfgSrc (bindings cEnv)
where
allOpts = info (opts <**> helper)
( fullDesc
@@ -77,27 +78,27 @@ primops cEnv = Primops (fromList [sendPrimop, receivePrimop]) <> replPrimops
[String name, v] -> do
res <- liftIO $ runClientM (submit $ List $ [String name, v]) cEnv
case res of
- Left e -> throwError . OtherError
+ Left e -> throwErrorHere . OtherError
$ "send!: failed:" <> show e
Right () -> pure $ List []
- [_, _] -> throwError $ TypeError "send!: first argument should be a string"
- xs -> throwError $ WrongNumberOfArgs "send!" 2 (length xs)
+ [_, _] -> throwErrorHere $ TypeError "send!: first argument should be a string"
+ xs -> throwErrorHere $ WrongNumberOfArgs "send!" 2 (length xs)
)
receivePrimop =
( Ident "receive!"
, evalArgs $ \case
[String name, Number n] -> do
case floatingOrInteger n of
- Left (_ :: Float) -> throwError . OtherError
+ Left (_ :: Float) -> throwErrorHere . OtherError
$ "receive!: expecting int argument"
Right r -> do
liftIO (runClientM (since name r) cEnv) >>= \case
- Left err -> throwError . OtherError
+ Left err -> throwErrorHere . OtherError
$ "receive!: request failed:" <> show err
Right v' -> pure $ List v'
- [String _, _] -> throwError $ TypeError "receive!: expecting number as second arg"
- [_, _] -> throwError $ TypeError "receive!: expecting string as first arg"
- xs -> throwError $ WrongNumberOfArgs "receive!" 2 (length xs)
+ [String _, _] -> throwErrorHere $ TypeError "receive!: expecting number as second arg"
+ [_, _] -> throwErrorHere $ TypeError "receive!: expecting string as first arg"
+ xs -> throwErrorHere $ WrongNumberOfArgs "receive!" 2 (length xs)
)
-- * Helpers
diff --git a/package.yaml b/package.yaml
index fbd2196..6d282b3 100644
--- a/package.yaml
+++ b/package.yaml
@@ -18,6 +18,7 @@ dependencies:
- haskeline
- megaparsec
- mtl
+- pointed
- prettyprinter
- prettyprinter-ansi-terminal
- recursion-schemes
diff --git a/src/Radicle.hs b/src/Radicle.hs
index cf44c9b..acd9a44 100644
--- a/src/Radicle.hs
+++ b/src/Radicle.hs
@@ -1,3 +1,5 @@
+{-# LANGUAGE PatternSynonyms #-}
+
-- | `radicle` - A LISP for blocktrees.
--
-- `radicle` is a *reflective* language, meaning evaluation can be modified,
@@ -19,10 +21,23 @@ module Radicle
-- ** Datatypes
--
-- *** Value
- , Value(..)
+ , ValueF(..)
+ , type Value
+ , pattern Atom
+ , pattern Keyword
+ , pattern String
+ , pattern Number
+ , pattern Boolean
+ , pattern List
+ , pattern Primop
+ , pattern Dict
+ , pattern Ref
+ , pattern Lambda
, maybeJson
-- *** LangError
, LangError(..)
+ , LangErrorData(..)
+ , throwErrorHere
, Ident(..)
, Reference(..)
, mkIdent
diff --git a/src/Radicle/Internal/Annotation.hs b/src/Radicle/Internal/Annotation.hs
new file mode 100644
index 0000000..f834926
--- /dev/null
+++ b/src/Radicle/Internal/Annotation.hs
@@ -0,0 +1,70 @@
+{-# LANGUAGE UndecidableInstances #-}
+
+module Radicle.Internal.Annotation where
+
+import Codec.Serialise (Serialise)
+import Data.Copointed (Copointed(..))
+import Data.Text (pack)
+import Protolude
+import qualified Text.Megaparsec.Pos as Par
+
+newtype Annotated t f = Annotated (t (f (Annotated t f)))
+ deriving (Generic)
+
+-- Really should depend on Eq1 etc. but that is so much boilerplate.
+-- Instead we use some UndecidableInstances.
+deriving instance (Eq (t (f (Annotated t f)))) => Eq (Annotated t f)
+deriving instance (Ord (t (f (Annotated t f)))) => Ord (Annotated t f)
+deriving instance (Read (t (f (Annotated t f)))) => Read (Annotated t f)
+deriving instance (Show (t (f (Annotated t f)))) => Show (Annotated t f)
+deriving instance (Serialise (t (f (Annotated t f)))) => Serialise (Annotated t f)
+
+class Annotation t where
+ -- We use the call stack to create source location annotations for interpreter-created objects
+ toAnnotation :: HasCallStack => a -> t a
+
+instance Annotation Identity where
+ toAnnotation = Identity
+
+untag :: (Functor f, Copointed t) => Annotated t f -> Annotated Identity f
+untag (Annotated t) = Annotated . Identity $ untag <$> copoint t
+
+tagDefault :: (Functor f, Annotation t) => Annotated Identity f -> Annotated t f
+tagDefault (Annotated (Identity t)) = Annotated (toAnnotation (tagDefault <$> t))
+
+match :: (Copointed t) => Annotated t f -> f (Annotated t f)
+match (Annotated t) = copoint t
+
+annotate :: (HasCallStack, Annotation t) => f (Annotated t f) -> Annotated t f
+annotate = withFrozenCallStack (Annotated . toAnnotation)
+
+
+data SrcPos = SrcPos Par.SourcePos
+ -- | If not associated with a source position, record where
+ -- in the interpreter this node was created (if only to know
+ -- what we need to improve).
+ --
+ -- We use Text instead of CallStack because CallStack has no
+ -- Read instance, and it's not worth it to make a parser.
+ | InternalPos Text
+ deriving (Eq, Ord, Read, Show, Generic)
+
+thisPos :: HasCallStack => SrcPos
+thisPos = InternalPos (pack (prettyCallStack callStack))
+
+data WithPos a = WithPos SrcPos a
+ deriving (Read, Show, Generic, Functor, Foldable, Traversable)
+
+-- Ignore source locations when comparing.
+instance Eq a => Eq (WithPos a) where
+ WithPos _ x == WithPos _ y = x == y
+
+instance (Ord a) => Ord (WithPos a) where
+ compare (WithPos _ x) (WithPos _ y) = compare x y
+
+instance Copointed WithPos where
+ copoint (WithPos _ x) = x
+
+instance Annotation WithPos where
+ toAnnotation = WithPos thisPos
+
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index 4dbd98b..4e87f90 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -1,3 +1,6 @@
+{-# LANGUAGE PatternSynonyms #-}
+{-# LANGUAGE ViewPatterns #-}
+
-- | The core radicle datatypes and functionality.
module Radicle.Internal.Core where
@@ -9,6 +12,7 @@ import Control.Monad.Except
import Control.Monad.State
import Data.Aeson (FromJSON(..), ToJSON(..))
import qualified Data.Aeson as A
+import Data.Copointed (Copointed(..))
import Data.Data (Data)
import qualified Data.HashMap.Strict as HashMap
import qualified Data.IntMap as IntMap
@@ -21,13 +25,18 @@ import Generics.Eot
import qualified GHC.Exts as GhcExts
import qualified Text.Megaparsec.Error as Par
+import Radicle.Internal.Annotation (Annotated)
+import qualified Radicle.Internal.Annotation as Ann
import Radicle.Internal.Orphans ()
-- * Value
+data LangError r = LangError [Ann.SrcPos] (LangErrorData r)
+ deriving (Eq, Show, Read, Generic, Functor)
+
-- | An error throw during parsing or evaluating expressions in the language.
-data LangError r =
+data LangErrorData r =
UnknownIdentifier Ident
| Impossible Text
| TypeError Text
@@ -40,19 +49,30 @@ data LangError r =
| Exit
deriving (Eq, Show, Read, Generic, Functor)
+throwErrorHere :: (MonadError (LangError Value) m, HasCallStack) => LangErrorData Value -> m a
+throwErrorHere = withFrozenCallStack (throwError . LangError [Ann.thisPos])
+
+toLangError :: (HasCallStack) => LangErrorData Value -> LangError Value
+toLangError = LangError [Ann.thisPos]
+
+-- | Remove callstack information.
+noStack :: Either (LangError Value) a -> Either (LangErrorData Value) a
+noStack (Left (LangError _ err)) = Left err
+noStack (Right v) = Right v
+
-- | Convert an error to a radicle value, and the label for it. Used for
-- catching exceptions.
-errorToValue
+errorDataToValue
:: Monad m
- => LangError Value
+ => LangErrorData Value
-> Lang m (Ident, Value)
-errorToValue e = case e of
+errorDataToValue e = case e of
UnknownIdentifier i -> makeVal
( "unknown-identifier"
, [("identifier", makeA i)]
)
-- "Now more than ever seems it rich to die"
- Impossible _ -> throwError e
+ Impossible _ -> throwErrorHere e
TypeError i -> makeVal
( "type-error"
, [("info", String i)]
@@ -92,28 +112,91 @@ readRef :: Monad m => Reference -> Lang m Value
readRef (Reference r) = do
refs <- gets bindingsRefs
case IntMap.lookup r refs of
- Nothing -> throwError $ Impossible "undefined reference"
+ Nothing -> throwErrorHere $ Impossible "undefined reference"
Just v -> pure v
-- | An expression or value in the language.
-data Value =
+data ValueF r =
-- | A regular (hyperstatic) variable.
- Atom Ident
+ AtomF Ident
-- | Symbolic identifiers that evaluate to themselves.
- | Keyword Ident
- | String Text
- | Number Scientific
- | Boolean Bool
- | List [Value]
- | Primop Ident
- | Dict (Map.Map Value Value)
- | Ref Reference
+ | KeywordF Ident
+ | StringF Text
+ | NumberF Scientific
+ | BooleanF Bool
+ | ListF [r]
+ | PrimopF Ident
+ -- | Map from *pure* Values -- annotations shouldn't change lookup semantics.
+ | DictF (Map.Map Value r)
+ | RefF Reference
-- | Takes the arguments/parameters, a body, and possibly a closure.
--
-- The value of an application of a lambda is always the last value in the
-- body. The only reason to have multiple values is for effects.
- | Lambda [Ident] (NonEmpty Value) (Env Value)
- deriving (Eq, Show, Ord, Read, Generic)
+ | LambdaF [Ident] (NonEmpty r) (Env r)
+ deriving (Eq, Ord, Read, Show, Generic, Functor)
+
+{-# COMPLETE Atom, Keyword, String, Number, Boolean, List, Primop, Dict, Ref, Lambda #-}
+
+type ValueConC t = (HasCallStack, Ann.Annotation t, Copointed t)
+
+pattern Atom :: ValueConC t => Ident -> Annotated t ValueF
+pattern Atom i <- (Ann.match -> AtomF i)
+ where
+ Atom = Ann.annotate . AtomF
+
+pattern Keyword :: ValueConC t => Ident -> Annotated t ValueF
+pattern Keyword i <- (Ann.match -> KeywordF i)
+ where
+ Keyword = Ann.annotate . KeywordF
+
+pattern String :: ValueConC t => Text -> Annotated t ValueF
+pattern String i <- (Ann.match -> StringF i)
+ where
+ String = Ann.annotate . StringF
+
+pattern Number :: ValueConC t => Scientific -> Annotated t ValueF
+pattern Number i <- (Ann.match -> NumberF i)
+ where
+ Number = Ann.annotate . NumberF
+
+pattern Boolean :: ValueConC t => Bool -> Annotated t ValueF
+pattern Boolean i <- (Ann.match -> BooleanF i)
+ where
+ Boolean = Ann.annotate . BooleanF
+
+pattern List :: ValueConC t => [Annotated t ValueF] -> Annotated t ValueF
+pattern List vs <- (Ann.match -> ListF vs)
+ where
+ List = Ann.annotate . ListF
+
+pattern Primop :: ValueConC t => Ident -> Annotated t ValueF
+pattern Primop i <- (Ann.match -> PrimopF i)
+ where
+ Primop = Ann.annotate . PrimopF
+
+pattern Dict :: ValueConC t => Map.Map Value (Annotated t ValueF) -> Annotated t ValueF
+pattern Dict vs <- (Ann.match -> DictF vs)
+ where
+ Dict = Ann.annotate . DictF
+
+pattern Ref :: ValueConC t => Reference -> Annotated t ValueF
+pattern Ref i <- (Ann.match -> RefF i)
+ where
+ Ref = Ann.annotate . RefF
+
+pattern Lambda :: ValueConC t => [Ident] -> NonEmpty (Annotated t ValueF) -> Env (Annotated t ValueF) -> Annotated t ValueF
+pattern Lambda vs exps env <- (Ann.match -> LambdaF vs exps env)
+ where
+ Lambda vs exps env = Ann.annotate $ LambdaF vs exps env
+
+
+type UntaggedValue = Annotated Identity ValueF
+type Value = Annotated Ann.WithPos ValueF
+
+-- Remove polymorphism
+asValue :: Value -> Value
+asValue x = x
-- Should just be a prism
isAtom :: Value -> Maybe Ident
@@ -208,6 +291,16 @@ newtype LangT r m a = LangT
{ fromLangT :: ExceptT (LangError Value) (StateT r m) a }
deriving (Functor, Applicative, Monad, MonadError (LangError Value), MonadIO, MonadState r)
+mapError :: (Functor m) => (LangError Value -> LangError Value) -> LangT r m a -> LangT r m a
+mapError f = LangT . withExceptT f . fromLangT
+
+logPos :: (Functor m) => Ann.SrcPos -> LangT r m a -> LangT r m a
+logPos loc = mapError (\(LangError stack err) -> LangError (loc:stack) err)
+
+-- | Log the source location associated with a value.
+logValPos :: (Functor m) => Value -> LangT r m a -> LangT r m a
+logValPos (Ann.Annotated (Ann.WithPos pos _)) = logPos pos
+
instance MonadTrans (LangT r) where lift = LangT . lift . lift
-- | A monad for language operations specialized to have as state the Bindings
@@ -252,13 +345,13 @@ addBinding i v b = b
-- | Lookup an atom in the environment
lookupAtom :: Monad m => Ident -> Lang m Value
lookupAtom i = get >>= \e -> case Map.lookup i . fromEnv $ bindingsEnv e of
- Nothing -> throwError $ UnknownIdentifier i
+ Nothing -> throwErrorHere $ UnknownIdentifier i
Just v -> pure v
-- | Lookup a primop.
lookupPrimop :: Monad m => Ident -> Lang m ([Value] -> Lang m Value)
lookupPrimop i = get >>= \e -> case Map.lookup i $ getPrimops $ bindingsPrimops e of
- Nothing -> throwError $ Impossible "Unknown primop"
+ Nothing -> throwErrorHere $ Impossible "Unknown primop"
Just v -> pure v
defineAtom :: Monad m => Ident -> Value -> Lang m ()
@@ -271,7 +364,7 @@ eval :: Monad m => Value -> Lang m Value
eval val = do
e <- lookupAtom (toIdent "eval")
st <- gets toRad
- case e of
+ logValPos e $ case e of
Primop i -> do
fn <- lookupPrimop i
-- Primops get to decide whether and how their args are
@@ -279,25 +372,25 @@ eval val = do
res <- fn [quote val, quote st]
updateEnvAndReturn res
l@Lambda{} -> callFn l [val, st] >>= updateEnvAndReturn
- _ -> throwError $ TypeError "Trying to apply a non-function"
+ _ -> throwErrorHere $ TypeError "Trying to apply a non-function"
where
updateEnvAndReturn :: Monad m => Value -> Lang m Value
updateEnvAndReturn v = case v of
List [val', newSt] -> do
prims <- gets bindingsPrimops
- newSt' <- either (throwError . OtherError) pure
+ newSt' <- either (throwErrorHere . OtherError) pure
(fromRad newSt :: Either Text (Bindings ()))
put $ newSt' { bindingsPrimops = prims }
pure val'
- _ -> throwError $ OtherError "eval: should return list with value and new env"
+ _ -> throwErrorHere $ OtherError "eval: should return list with value and new env"
-- | The built-in, original, eval.
baseEval :: Monad m => Value -> Lang m Value
-baseEval val = case val of
+baseEval val = logValPos val $ case val of
Atom i -> lookupAtom i
List (f:vs) -> f $$ vs
- List xs -> throwError
+ List xs -> throwErrorHere
$ WrongNumberOfArgs ("application: " <> show xs)
2
(length xs)
@@ -380,22 +473,22 @@ instance ToRad (Bindings m) where
-- * Helpers
-
+-- Loc is the source location of the application.
callFn :: Monad m => Value -> [Value] -> Lang m Value
callFn f vs = case f of
Lambda bnds body closure ->
if length bnds /= length vs
- then throwError $ WrongNumberOfArgs "lambda" (length bnds)
- (length vs)
+ then throwErrorHere $ WrongNumberOfArgs "lambda" (length bnds)
+ (length vs)
else do
let mappings = GhcExts.fromList (zip bnds vs)
modEnv = mappings <> closure
NonEmpty.last <$> withEnv (const modEnv)
(traverse baseEval body)
- Primop i -> throwError . TypeError
+ Primop i -> throwErrorHere . TypeError
$ "Trying to call a non-function: the primop '" <> show i
<> "' cannot be used as a function."
- _ -> throwError . TypeError $ "Trying to call a non-function."
+ _ -> throwErrorHere . TypeError $ "Trying to call a non-function."
-- | Infix evaluation of application (of functions or primops)
infixr 1 $$
@@ -411,7 +504,7 @@ mfn $$ vs = do
f@Lambda{} -> do
vs' <- traverse baseEval vs
callFn f vs'
- _ -> throwError $ TypeError "Trying to apply a non-function"
+ _ -> throwErrorHere $ TypeError "Trying to apply a non-function"
nil :: Value
nil = List []
diff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hs
index 16d7942..7bef43f 100644
--- a/src/Radicle/Internal/Effects.hs
+++ b/src/Radicle/Internal/Effects.hs
@@ -36,19 +36,19 @@ type ReplM m =
instance MonadRandom (InputT IO) where
getRandomBytes = liftIO . getRandomBytes
instance MonadRandom m => MonadRandom (LangT (Bindings (Primops m)) m) where
- getRandomBytes = lift . getRandomBytes
+ getRandomBytes = lift . getRandomBytes
-repl :: Maybe FilePath -> Text -> Bindings (Primops (InputT IO)) -> IO ()
-repl histFile preCode bindings = do
+repl :: Maybe FilePath -> Text -> Text -> Bindings (Primops (InputT IO)) -> IO ()
+repl histFile preFileName preCode bindings = do
let settings = setComplete completion
$ defaultSettings { historyFile = histFile }
r <- runInputT settings
$ fmap fst $ runLang bindings
- $ void $ interpretMany "[pre]" preCode
+ $ void $ interpretMany preFileName preCode
case r of
- Left Exit -> pure ()
- Left e -> putDoc $ pretty e
- Right () -> pure ()
+ Left (LangError _ Exit) -> pure ()
+ Left e -> putDoc $ pretty e
+ Right () -> pure ()
completion :: Monad m => CompletionFunc m
completion = completeWord Nothing ['(', ')', ' ', '\n'] go
@@ -76,19 +76,19 @@ replPrimops = Primops . Map.fromList $ first toIdent <$>
v <- eval x
putStrS (renderPrettyDef v)
pure nil
- xs -> throwError $ WrongNumberOfArgs "print!" 1 (length xs))
+ xs -> throwErrorHere $ WrongNumberOfArgs "print!" 1 (length xs))
, ("set-env!", \args -> case args of
[Atom x, v] -> do
v' <- eval v
defineAtom x v'
pure nil
- [_, _] -> throwError $ TypeError "Expected atom as first arg"
- xs -> throwError $ WrongNumberOfArgs "set-env!" 2 (length xs))
+ [_, _] -> throwErrorHere $ TypeError "Expected atom as first arg"
+ xs -> throwErrorHere $ WrongNumberOfArgs "set-env!" 2 (length xs))
, ("get-line!", \args -> case args of
[] -> String <$> getLineS
- xs -> throwError $ WrongNumberOfArgs "get-line!" 0 (length xs))
+ xs -> throwErrorHere $ WrongNumberOfArgs "get-line!" 0 (length xs))
, ("subscribe-to!", \args -> case args of
[x, v] -> do
@@ -97,7 +97,7 @@ replPrimops = Primops . Map.fromList $ first toIdent <$>
e <- gets bindingsEnv
case (x', v') of
(Dict m, fn) -> case Map.lookup (Atom $ toIdent "getter") m of
- Nothing -> throwError
+ Nothing -> throwErrorHere
$ OtherError "subscribe-to!: Expected 'getter' key"
Just g -> forever (protect go)
where
@@ -105,8 +105,8 @@ replPrimops = Primops . Map.fromList $ first toIdent <$>
st <- get
action `catchError`
(\err -> case err of
- Exit -> throwError err
- Impossible _ -> do
+ LangError _ Exit -> throwError err
+ LangError _ (Impossible _) -> do
putStrS (renderPrettyDef err)
throwError err
_ -> putStrS (renderPrettyDef err) >> put st)
@@ -120,22 +120,22 @@ replPrimops = Primops . Map.fromList $ first toIdent <$>
-- function is evaluated in the original
-- environment.
void $ withEnv (const e) (fn $$ [quote line])
- _ -> throwError $ TypeError "subscribe-to!: Expected dict"
- xs -> throwError $ WrongNumberOfArgs "subscribe-to!" 2 (length xs))
+ _ -> throwErrorHere $ TypeError "subscribe-to!: Expected dict"
+ xs -> throwErrorHere $ WrongNumberOfArgs "subscribe-to!" 2 (length xs))
, ( "read-file!"
, evalOneArg "read-file" $ \case
String filename -> String <$> readFileS filename
- _ -> throwError $ TypeError "read-file: expects a string"
+ _ -> throwErrorHere $ TypeError "read-file: expects a string"
)
, ( "load!"
, evalOneArg "load!" $ \case
String filename -> readFileS filename >>= interpretMany "[load!]"
- _ -> throwError $ TypeError "load: expects a string"
+ _ -> throwErrorHere $ TypeError "load: expects a string"
)
, ( "gen-key-pair!"
, evalArgs $ \case
[curvev] -> do
- curve <- hoistEither . first OtherError $ fromRad curvev
+ curve <- hoistEither . first (toLangError . OtherError) $ fromRad curvev
(pk, sk) <- generateKeyPair curve
let pkv = toRad pk
let skv = toRad sk
@@ -143,13 +143,13 @@ replPrimops = Primops . Map.fromList $ first toIdent <$>
[ (Keyword (Ident "private-key"), skv)
, (Keyword (Ident "public-key"), pkv)
]
- xs -> throwError $ WrongNumberOfArgs "gen-key-pair!" 0 (length xs)
+ xs -> throwErrorHere $ WrongNumberOfArgs "gen-key-pair!" 0 (length xs)
)
, ( "gen-signature!"
, evalArgs $ \case
[skv, String msg] -> do
- sk <- hoistEither . first OtherError $ fromRad skv
+ sk <- hoistEither . first (toLangError . OtherError) $ fromRad skv
toRad <$> signText sk msg
- _ -> throwError $ TypeError "gen-signature!: expects a string."
+ _ -> throwErrorHere $ TypeError "gen-signature!: expects a string."
)
]
diff --git a/src/Radicle/Internal/Interpret.hs b/src/Radicle/Internal/Interpret.hs
index 67774fd..5a209a5 100644
--- a/src/Radicle/Internal/Interpret.hs
+++ b/src/Radicle/Internal/Interpret.hs
@@ -5,6 +5,7 @@ import Protolude
import qualified Data.Map.Strict as Map
import Text.Megaparsec (eof, runParserT)
+import qualified Radicle.Internal.Annotation as Ann
import Radicle.Internal.Core
import Radicle.Internal.Parse
@@ -14,11 +15,11 @@ import Radicle.Internal.Parse
--
-- >>> import Control.Monad.Identity
-- >>> import Radicle.Internal.Primops
--- >>> runIdentity $ interpret "test" "((lambda (x) x) #t)" pureEnv
--- Right (Boolean True)
+-- >>> fmap Ann.untag . runIdentity $ interpret "test" "((lambda (x) x) #t)" pureEnv
+-- Right (Annotated (Identity (BooleanF True)))
--
-- >>> import Control.Monad.Identity
--- >>> runIdentity $ interpret "test" "(#t #f)" pureEnv
+-- >>> noStack . runIdentity $ interpret "test" "(#t #f)" pureEnv
-- Left (TypeError "Trying to apply a non-function")
interpret
:: Monad m
@@ -30,7 +31,7 @@ interpret sourceName expr bnds = do
let primopNames = Map.keys (getPrimops $ bindingsPrimops bnds)
parsed = runReader (runParserT (spaceConsumer *> valueP <* eof) (toS sourceName) expr) primopNames
case parsed of
- Left e -> pure . Left $ ParseError e
+ Left e -> pure . Left $ LangError [Ann.thisPos] (ParseError e)
Right v -> fst <$> runLang bnds (eval v)
-- | Parse and evaluate a Text as multiple expressions.
@@ -41,8 +42,8 @@ interpret sourceName expr bnds = do
-- Examples:
--
-- >>> import Radicle.Internal.Primops
--- >>> fmap fst <$> runLang pureEnv $ interpretMany "test" "(define id (lambda (x) x))\n(id #t)"
--- Right (Boolean True)
+-- >>> fmap (fmap Ann.untag . fst) <$> runLang pureEnv $ interpretMany "test" "(define id (lambda (x) x))\n(id #t)"
+-- Right (Annotated (Identity (BooleanF True)))
interpretMany
:: Monad m
=> Text -- ^ Name of source file (for error reporting)
@@ -56,6 +57,6 @@ interpretMany sourceName src = do
es <- mapM eval vs
case lastMay es of
Just e -> pure e
- _ -> throwError
+ _ -> throwErrorHere
$ OtherError "InterpretMany should be called with at least one expression."
- (e:_, _) -> throwError $ ParseError e
+ (e:_, _) -> throwErrorHere $ ParseError e
diff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hs
index a53524a..b5ff5cd 100644
--- a/src/Radicle/Internal/Parse.hs
+++ b/src/Radicle/Internal/Parse.hs
@@ -1,6 +1,6 @@
module Radicle.Internal.Parse where
-import Protolude hiding (try)
+import Protolude hiding (SrcLoc, try)
import Data.Char (isAlphaNum, isLetter)
import Data.List.NonEmpty (NonEmpty((:|)))
@@ -14,6 +14,7 @@ import Text.Megaparsec
, choice
, defaultTabWidth
, eof
+ , getPosition
, initialPos
, manyTill
, runParserT'
@@ -26,6 +27,7 @@ import Text.Megaparsec.Char (char, satisfy, space1)
import qualified Text.Megaparsec.Char.Lexer as L
import qualified Text.Megaparsec.Error as Par
+import Radicle.Internal.Annotation as Ann
import Radicle.Internal.Core
-- * The parser
@@ -39,6 +41,11 @@ spaceConsumer = L.space space1 lineComment blockComment
lineComment = L.skipLineComment ";;"
blockComment = L.skipBlockComment "#|" "|#" -- R6RS
+tag :: ValueF Value -> VParser
+tag v = do
+ pos <- getPosition -- N.B. in megaparsec 7 this is called getSourcePos
+ pure $ Ann.Annotated (Ann.WithPos (Ann.SrcPos pos) v)
+
symbol :: Text -> Parser Text
symbol = L.symbol spaceConsumer
@@ -57,14 +64,14 @@ bracesP = inside "{" "}"
stringLiteralP :: VParser
stringLiteralP = lexeme $
- String . toS <$> (char '"' >> manyTill L.charLiteral (char '"'))
+ tag =<< StringF . toS <$> (char '"' >> manyTill L.charLiteral (char '"'))
boolLiteralP :: VParser
-boolLiteralP = lexeme $ Boolean <$> (char '#' >>
+boolLiteralP = lexeme $ tag =<< BooleanF <$> (char '#' >>
(char 't' >> pure True) <|> (char 'f' >> pure False))
numLiteralP :: VParser
-numLiteralP = Number <$> signed L.scientific
+numLiteralP = tag =<< NumberF <$> signed L.scientific
where
-- We don't allow spaces between the sign and digits so that we can remain
-- consistent with the general Scheme of things.
@@ -80,19 +87,19 @@ atomOrPrimP :: VParser
atomOrPrimP = do
i <- identP
prims <- ask
- pure $ if i `elem` prims then Primop i else Atom i
+ tag $ if i `elem` prims then PrimopF i else AtomF i
keywordP :: VParser
keywordP = do
_ <- char ':'
kw <- many (satisfy isValidIdentRest)
- pure . Keyword . Ident . fromString $ kw
+ tag . KeywordF . Ident . fromString $ kw
listP :: VParser
-listP = parensP (List <$> valueP `sepBy` spaceConsumer)
+listP = parensP (tag =<< (ListF <$> valueP `sepBy` spaceConsumer))
dictP :: VParser
-dictP = bracesP (Dict . Map.fromList <$> evenItems)
+dictP = bracesP (tag =<< (DictF . Map.fromList <$> evenItems))
where
evenItems = twoItems `sepBy` spaceConsumer
twoItems = do
@@ -102,7 +109,10 @@ dictP = bracesP (Dict . Map.fromList <$> evenItems)
pure (x,y)
quoteP :: VParser
-quoteP = List . ((Primop $ toIdent "quote") :) . pure <$> (char '\'' >> valueP)
+quoteP = do
+ val <- char '\'' >> valueP
+ q <- tag $ PrimopF (toIdent "quote")
+ pure $ List [q, val]
valueP :: VParser
valueP = do
@@ -147,14 +157,14 @@ parseValues sourceName srcCode prims = withoutLeadingSpaces
--
-- Examples:
--
--- >>> parse "test" "#t" [] :: Either Text Value
--- Right (Boolean True)
+-- >>> untag <$> parse "test" "#t" [] :: Either Text UntaggedValue
+-- Right (Annotated (Identity (BooleanF True)))
--
--- >>> parse "test" "hi" [toIdent "hi"] :: Either Text Value
--- Right (Primop (Ident {fromIdent = "hi"}))
+-- >>> untag <$> parse "test" "hi" [toIdent "hi"] :: Either Text UntaggedValue
+-- Right (Annotated (Identity (PrimopF (Ident {fromIdent = "hi"}))))
--
--- >>> parse "test" "hi" [] :: Either Text Value
--- Right (Atom (Ident {fromIdent = "hi"}))
+-- >>> untag <$> parse "test" "hi" [] :: Either Text UntaggedValue
+-- Right (Annotated (Identity (AtomF (Ident {fromIdent = "hi"}))))
parse :: MonadError Text m
=> Text -- ^ Name of source file (for error reporting)
-> Text -- ^ Source code to be parsed
diff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hs
index 90cfc35..ae929b9 100644
--- a/src/Radicle/Internal/Pretty.hs
+++ b/src/Radicle/Internal/Pretty.hs
@@ -3,12 +3,15 @@ module Radicle.Internal.Pretty where
import Protolude hiding (TypeError, (<>))
+import Data.Copointed (Copointed(..))
import qualified Data.Map as Map
import qualified Data.Text as T
import Data.Text.Prettyprint.Doc
import Data.Text.Prettyprint.Doc.Render.Text
import Text.Megaparsec.Error (parseErrorPretty)
+import Text.Megaparsec.Pos (sourcePosPretty)
+import qualified Radicle.Internal.Annotation as Ann
import Radicle.Internal.Core
-- | We can't just pretty print the pointer id since that would break
@@ -19,7 +22,7 @@ instance Pretty Reference where
instance Pretty Ident where
pretty (Ident i) = pretty i
-instance Pretty Value where
+instance (Copointed t, Ann.Annotation t) => Pretty (Ann.Annotated t ValueF) where
pretty v = case v of
Atom i -> pretty i
Keyword i -> ":" <> pretty i
@@ -44,7 +47,15 @@ instance Pretty Value where
where
escapeStr = T.replace "\"" "\\\"" . T.replace "\\" "\\\\"
+instance Pretty Ann.SrcPos where
+ pretty (Ann.SrcPos pos) = pretty (sourcePosPretty pos)
+ pretty (Ann.InternalPos stack) = pretty stack
+
instance Pretty r => Pretty (LangError r) where
+ pretty (LangError stack err) = vsep $
+ [pretty err, "Call stack:"] ++ map pretty (reverse stack)
+
+instance Pretty r => Pretty (LangErrorData r) where
pretty v = case v of
UnknownIdentifier i -> "Unknown identifier:" <+> pretty i
Impossible t -> "This cannot be!" <+> pretty t
@@ -62,7 +73,7 @@ instance Pretty r => Pretty (LangError r) where
--
-- Examples:
--
--- >>> renderCompactPretty (List [String "hi", String "there"])
+-- >>> renderCompactPretty (asValue (List [String "hi", String "there"]))
-- "(\"hi\"\n\"there\")"
renderCompactPretty :: Pretty v => v -> Text
renderCompactPretty = renderStrict . layoutCompact . pretty
@@ -71,10 +82,10 @@ renderCompactPretty = renderStrict . layoutCompact . pretty
--
-- Examples:
--
--- >>> renderPretty Unbounded (List [String "hi", String "there"])
+-- >>> renderPretty Unbounded (asValue (List [String "hi", String "there"]))
-- "(\"hi\" \"there\")"
--
--- >>> renderPretty (AvailablePerLine 6 0.5) (List [String "hi", String "there"])
+-- >>> renderPretty (AvailablePerLine 6 0.5) (asValue (List [String "hi", String "there"]))
-- "(\"hi\"\n \"there\")"
renderPretty :: Pretty v => PageWidth -> v -> Text
renderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . pretty
@@ -83,7 +94,7 @@ renderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . pretty
--
-- Examples:
--
--- >>> renderPrettyDef (List [String "hi", String "there"])
+-- >>> renderPrettyDef (asValue (List [String "hi", String "there"]))
-- "(\"hi\" \"there\")"
renderPrettyDef :: Pretty v => v -> Text
renderPrettyDef = renderStrict . layoutSmart defaultLayoutOptions . pretty
diff --git a/src/Radicle/Internal/Primops.hs b/src/Radicle/Internal/Primops.hs
index c23aeec..812bcfb 100644
--- a/src/Radicle/Internal/Primops.hs
+++ b/src/Radicle/Internal/Primops.hs
@@ -35,52 +35,53 @@ purePrimops = Primops $ fromList $ first Ident <$>
[ ( "lambda"
, \case
List atoms_ : b : bs -> do
- atoms <- traverse isAtom atoms_ ?? TypeError "lambda: expecting a list of symbols"
+ atoms <- traverse isAtom atoms_ ?? toLangError (TypeError "lambda: expecting a list of symbols")
e <- gets bindingsEnv
pure (Lambda atoms (b :| bs) e)
- xs -> throwError $ WrongNumberOfArgs "lambda" 2 (length xs) -- TODO: technically "at least 2"
+ xs -> throwErrorHere $ WrongNumberOfArgs "lambda" 2 (length xs) -- TODO: technically "at least 2"
)
, ( "base-eval"
, evalArgs $ \case
[expr, st] -> case (fromRad st :: Either Text (Bindings ())) of
- Left e -> throwError $ OtherError e
+ Left e -> throwErrorHere $ OtherError e
Right st' -> do
prims <- gets bindingsPrimops
withBindings (const $ fmap (const prims) st') $ do
val <- baseEval expr
st'' <- get
pure $ List [val, toRad st'']
- xs -> throwError $ WrongNumberOfArgs "base-eval" 2 (length xs)
+ xs -> throwErrorHere $ WrongNumberOfArgs "base-eval" 2 (length xs)
)
, ( "pure-env"
, \case
[] -> pure $ toRad (pureEnv :: Bindings (Primops m))
- xs -> throwError $ WrongNumberOfArgs "pure-env" 0 (length xs)
+ xs -> throwErrorHere $ WrongNumberOfArgs "pure-env" 0 (length xs)
)
, ("apply", evalArgs $ \case
[fn, List args] -> eval . List $ fn:args
- [_, _] -> throwError $ TypeError "apply: expecting list as second arg"
- xs -> throwError $ WrongNumberOfArgs "apply" 2 (length xs))
+ [_, _] -> throwErrorHere $ TypeError "apply: expecting list as second arg"
+ xs -> throwErrorHere $ WrongNumberOfArgs "apply" 2 (length xs))
, ( "read"
, evalOneArg "read" $ \case
String s -> readValue s
- _ -> throwError $ TypeError "read: expects string"
+ _ -> throwErrorHere $ TypeError "read: expects string"
)
, ("get-current-env", \case
[] -> toRad <$> get
- xs -> throwError $ WrongNumberOfArgs "get-current-env" 0 (length xs))
+ xs -> throwErrorHere $ WrongNumberOfArgs "get-current-env" 0 (length xs))
, ("list", evalArgs $ \args -> pure $ List args)
- , ("dict", evalArgs $ (Dict . foldr (uncurry Map.insert) mempty <$>) . evenArgs "dict")
+ , ("dict", evalArgs $ (Dict . foldr (uncurry Map.insert) mempty <$>)
+ . evenArgs "dict")
, ("quote", \args -> case args of
[v] -> pure v
- xs -> throwError $ WrongNumberOfArgs "quote" 1 (length xs))
+ xs -> throwErrorHere $ WrongNumberOfArgs "quote" 1 (length xs))
, ("define", \args -> case args of
[Atom name, val] -> do
val' <- baseEval val
defineAtom name val'
pure nil
- [_, _] -> throwError $ OtherError "define expects atom for first arg"
- xs -> throwError $ WrongNumberOfArgs "define" 2 (length xs))
+ [_, _] -> throwErrorHere $ OtherError "define expects atom for first arg"
+ xs -> throwErrorHere $ WrongNumberOfArgs "define" 2 (length xs))
, ( "define-rec"
, \case
[Atom name, val] -> do
@@ -90,50 +91,51 @@ purePrimops = Primops $ fromList $ first Ident <$>
let v = Lambda is b (Env . Map.insert name v . fromEnv $ e)
defineAtom name v
pure nil
- _ -> throwError $ OtherError "define-rec can only be used to define functions"
- [_, _] -> throwError $ OtherError "define-rec expects atom for first arg"
- xs -> throwError $ WrongNumberOfArgs "define-rec" 2 (length xs)
+ _ -> throwErrorHere $ OtherError "define-rec can only be used to define functions"
+ [_, _] -> throwErrorHere $ OtherError "define-rec expects atom for first arg"
+ xs -> throwErrorHere $ WrongNumberOfArgs "define-rec" 2 (length xs)
)
, ("do", evalArgs $ pure . lastDef nil)
, ("catch", \args -> case args of
[l, form, handler] -> do
mlabel <- baseEval l
case mlabel of
- Atom label -> baseEval form `catchError` \e -> do
- (thrownLabel, thrownValue) <- errorToValue e
+ -- TODO reify stack
+ Atom label -> baseEval form `catchError` \(LangError _stack e) -> do
+ (thrownLabel, thrownValue) <- errorDataToValue e
if thrownLabel == label || label == Ident "any"
then handler $$ [thrownValue]
else baseEval form
- _ -> throwError $ TypeError "catch: first argument must be atom"
- xs -> throwError $ WrongNumberOfArgs "catch" 3 (length xs))
+ _ -> throwErrorHere $ TypeError "catch: first argument must be atom"
+ xs -> throwErrorHere $ WrongNumberOfArgs "catch" 3 (length xs))
, ("throw", evalArgs $ \args -> case args of
- [Atom label, exc] -> throwError $ ThrownError label exc
- [_, _] -> throwError $ TypeError "throw: first argument must be atom"
- xs -> throwError $ WrongNumberOfArgs "throw" 2 (length xs))
+ [Atom label, exc] -> throwErrorHere $ ThrownError label exc
+ [_, _] -> throwErrorHere $ TypeError "throw: first argument must be atom"
+ xs -> throwErrorHere $ WrongNumberOfArgs "throw" 2 (length xs))
, ("eq?", evalArgs $ \args -> case args of
[a, b] -> pure $ Boolean (a == b)
- xs -> throwError $ WrongNumberOfArgs "eq?" 2 (length xs))
+ xs -> throwErrorHere $ WrongNumberOfArgs "eq?" 2 (length xs))
, ("cons", evalArgs $ \args -> case args of
[x, List xs] -> pure $ List (x:xs)
- [_, _] -> throwError $ TypeError "cons: second argument must be list"
- xs -> throwError $ WrongNumberOfArgs "cons" 2 (length xs))
+ [_, _] -> throwErrorHere $ TypeError "cons: second argument must be list"
+ xs -> throwErrorHere $ WrongNumberOfArgs "cons" 2 (length xs))
, ("head", evalOneArg "head" $ \case
List (x:_) -> pure x
- List [] -> throwError $ OtherError "head: empty list"
- _ -> throwError $ TypeError "head: expects list argument")
+ List [] -> throwErrorHere $ OtherError "head: empty list"
+ _ -> throwErrorHere $ TypeError "head: expects list argument")
, ("tail", evalOneArg "tail" $ \case
List (_:xs) -> pure $ List xs
- List [] -> throwError $ OtherError "tail: empty list"
- _ -> throwError $ TypeError "tail: expects list argument")
+ List [] -> throwErrorHere $ OtherError "tail: empty list"
+ _ -> throwErrorHere $ TypeError "tail: expects list argument")
, ( "nth"
, evalArgs $ \case
[Number n, List xs] -> case floatingOrInteger n of
- Left (_ :: Double) -> throwError $ OtherError "nth: first argument was not an integer"
+ Left (_ :: Double) -> throwErrorHere $ OtherError "nth: first argument was not an integer"
Right i -> case xs `atMay` i of
Just x -> pure x
- Nothing -> throwError $ OtherError "nth: index out of bounds"
- [_,_] -> throwError $ TypeError "nth: expects a integer and a list"
- xs -> throwError $ WrongNumberOfArgs "nth" 2 (length xs)
+ Nothing -> throwErrorHere $ OtherError "nth: index out of bounds"
+ [_,_] -> throwErrorHere $ TypeError "nth: expects a integer and a list"
+ xs -> throwErrorHere $ WrongNumberOfArgs "nth" 2 (length xs)
)
, ("lookup", evalArgs $ \args -> case args of
[a, Dict m] -> pure $ case Map.lookup a m of
@@ -141,20 +143,20 @@ purePrimops = Primops $ fromList $ first Ident <$>
-- Probably an exception is better, but that seems cruel
-- when you have no exception handling facilities.
Nothing -> nil
- [_, _] -> throwError $ TypeError "lookup: second argument must be map"
- xs -> throwError $ WrongNumberOfArgs "lookup" 2 (length xs))
+ [_, _] -> throwErrorHere $ TypeError "lookup: second argument must be map"
+ xs -> throwErrorHere $ WrongNumberOfArgs "lookup" 2 (length xs))
, ("string-append", evalArgs $ \args ->
let fromStr (String s) = Just s
fromStr _ = Nothing
ss = fromStr <$> args
in if all isJust ss
then pure . String . mconcat $ catMaybes ss
- else throwError $ TypeError "string-append: non-string argument")
+ else throwErrorHere $ TypeError "string-append: non-string argument")
, ("insert", evalArgs $ \args -> case args of
[k, v, Dict m] -> pure . Dict $ Map.insert k v m
- [_, _, _] -> throwError
+ [_, _, _] -> throwErrorHere
$ TypeError "insert: third argument must be a dict"
- xs -> throwError $ WrongNumberOfArgs "insert" 3 (length xs))
+ xs -> throwErrorHere $ WrongNumberOfArgs "insert" 3 (length xs))
-- The semantics of + and - in Scheme is a little messed up. (+ 3)
-- evaluates to 3, and of (- 3) to -3. That's pretty intuitive.
-- But while (+ 3 2 1) evaluates to 6, (- 3 2 1) evaluates to 0. So with -
@@ -168,26 +170,26 @@ purePrimops = Primops $ fromList $ first Ident <$>
, numBinop (-) "-"
, ("<", evalArgs $ \args -> case args of
[Number x, Number y] -> pure $ Boolean (x < y)
- [_, _] -> throwError $ TypeError "<: expecting number"
- xs -> throwError $ WrongNumberOfArgs "<" 2 (length xs))
+ [_, _] -> throwErrorHere $ TypeError "<: expecting number"
+ xs -> throwErrorHere $ WrongNumberOfArgs "<" 2 (length xs))
, (">", evalArgs $ \args -> case args of
[Number x, Number y] -> pure $ Boolean (x > y)
- [_, _] -> throwError $ TypeError ">: expecting number"
- xs -> throwError $ WrongNumberOfArgs ">" 2 (length xs))
+ [_, _] -> throwErrorHere $ TypeError ">: expecting number"
+ xs -> throwErrorHere $ WrongNumberOfArgs ">" 2 (length xs))
, ("foldl", evalArgs $ \args -> case args of
[fn, init', List ls] -> foldlM (\b a -> callFn fn [b, a]) init' ls
- [_, _, _] -> throwError
+ [_, _, _] -> throwErrorHere
$ TypeError "foldl: third argument should be a list"
- xs -> throwError $ WrongNumberOfArgs "foldl" 3 (length xs))
+ xs -> throwErrorHere $ WrongNumberOfArgs "foldl" 3 (length xs))
, ("foldr", evalArgs $ \args -> case args of
[fn, init', List ls] -> foldrM (\b a -> callFn fn [b, a]) init' ls
- [_, _, _] -> throwError
+ [_, _, _] -> throwErrorHere
$ TypeError "foldr: third argument should be a list"
- xs -> throwError $ WrongNumberOfArgs "foldr" 3 (length xs))
+ xs -> throwErrorHere $ WrongNumberOfArgs "foldr" 3 (length xs))
, ("map", evalArgs $ \args -> case args of
[fn, List ls] -> List <$> traverse (callFn fn) (pure <$> ls)
- [_, _] -> throwError $ TypeError "map: second argument should be a list"
- xs -> throwError $ WrongNumberOfArgs "map" 3 (length xs))
+ [_, _] -> throwErrorHere $ TypeError "map: second argument should be a list"
+ xs -> throwErrorHere $ WrongNumberOfArgs "map" 3 (length xs))
, ("keyword?", evalOneArg "keyword?" $ \case
Keyword _ -> pure tt
_ -> pure ff)
@@ -225,29 +227,29 @@ purePrimops = Primops $ fromList $ first Ident <$>
_ -> pure ff)
, ("member?", evalArgs $ \args -> case args of
[x, List xs] -> pure . Boolean $ elem x xs
- [_, _] -> throwError
+ [_, _] -> throwErrorHere
$ TypeError "member?: second argument must be list"
- xs -> throwError $ WrongNumberOfArgs "eq?" 2 (length xs))
+ xs -> throwErrorHere $ WrongNumberOfArgs "eq?" 2 (length xs))
, ("if", \args -> case args of
[condition, t, f] -> do
b <- baseEval condition
-- I hate this as much as everyone that might ever read Haskell, but
-- in Lisps a lot of things that one might object to are True...
if b == ff then baseEval f else baseEval t
- xs -> throwError $ WrongNumberOfArgs "if" 3 (length xs))
+ xs -> throwErrorHere $ WrongNumberOfArgs "if" 3 (length xs))
, ( "cond", (cond =<<) . evenArgs "cond" )
, ("ref", evalOneArg "ref" newRef)
, ("read-ref", evalOneArg "read-ref" $ \case
Ref ref -> readRef ref
- _ -> throwError $ TypeError "read-ref: argument must be a ref")
+ _ -> throwErrorHere $ TypeError "read-ref: argument must be a ref")
, ("write-ref", evalArgs $ \args -> case args of
[Ref (Reference x), v] -> do
st <- get
put $ st { bindingsRefs = IntMap.insert x v $ bindingsRefs st }
pure nil
- [_, _] -> throwError
+ [_, _] -> throwErrorHere
$ TypeError "write-ref: first argument must be a ref"
- xs -> throwError
+ xs -> throwErrorHere
$ WrongNumberOfArgs "write-ref" 2 (length xs))
, ("show", evalOneArg "show" (pure . String . renderPrettyDef))
, ( "seq"
@@ -255,25 +257,25 @@ purePrimops = Primops $ fromList $ first Ident <$>
\case
x@(List _) -> pure x
Dict kvs -> pure $ List [List [k, v] | (k,v) <- Map.toList kvs ]
- _ -> throwError $ TypeError "seq: can only create a list from a list or a dict"
+ _ -> throwErrorHere $ TypeError "seq: can only create a list from a list or a dict"
)
, ( "to-json"
, evalOneArg "to-json" $ \v -> String . toS . Aeson.encode <$>
- maybeJson v ?? OtherError "Could not serialise value to JSON"
+ maybeJson v ?? toLangError (OtherError "Could not serialise value to JSON")
)
, ( "default-ecc-curve",
evalArgs $ \case
[] -> pure $ toRad defaultCurve
- xs -> throwError $ WrongNumberOfArgs "default-ecc-curve" 0 (length xs)
+ xs -> throwErrorHere $ WrongNumberOfArgs "default-ecc-curve" 0 (length xs)
)
, ( "verify-signature"
, evalArgs $ \case
[keyv, sigv, String msg] -> do
- key <- hoistEither . first OtherError $ fromRad keyv
- sig <- hoistEither . first OtherError $ fromRad sigv
+ key <- hoistEither . first (toLangError . OtherError) $ fromRad keyv
+ sig <- hoistEither . first (toLangError . OtherError) $ fromRad sigv
pure . Boolean $ verifySignature key sig msg
- [_, _, _] -> throwError $ OtherError "verify-signature: message must be a string"
- xs -> throwError $ WrongNumberOfArgs "verify-signature" 3 (length xs)
+ [_, _, _] -> throwErrorHere $ OtherError "verify-signature: message must be a string"
+ xs -> throwErrorHere $ WrongNumberOfArgs "verify-signature" 3 (length xs)
)
]
where
@@ -289,7 +291,7 @@ purePrimops = Primops $ fromList $ first Ident <$>
-- | Some forms/functions expect an even number or arguments.
evenArgs name = \case
[] -> pure []
- [_] -> throwError . OtherError $ name <> ": expects an even number of arguments"
+ [_] -> throwErrorHere . OtherError $ name <> ": expects an even number of arguments"
x:y:xs -> do
ps <- evenArgs name xs
pure ((x,y):ps)
@@ -304,11 +306,11 @@ purePrimops = Primops $ fromList $ first Ident <$>
Number x:x':xs -> foldM go (Number x) (x':xs)
where
go (Number a) (Number b) = pure . Number $ fn a b
- go _ _ = throwError . TypeError
+ go _ _ = throwErrorHere . TypeError
$ name <> ": expecting number"
- [Number _] -> throwError
+ [Number _] -> throwErrorHere
$ OtherError $ name <> ": expects at least 2 arguments"
- _ -> throwError $ TypeError $ name <> ": expecting number")
+ _ -> throwErrorHere $ TypeError $ name <> ": expecting number")
-- * Helpers
@@ -320,7 +322,7 @@ evalArgs f args = traverse baseEval args >>= f
evalOneArg :: Monad m => Text -> (Value -> Lang m Value) -> [Value] -> Lang m Value
evalOneArg fname f = evalArgs $ \case
[x] -> f x
- xs -> throwError $ WrongNumberOfArgs fname 1 (length xs)
+ xs -> throwErrorHere $ WrongNumberOfArgs fname 1 (length xs)
readValue
:: (MonadError (LangError Value) m, MonadState (Bindings (Primops n)) m)
@@ -331,4 +333,4 @@ readValue s = do
let p = parse "[read-primop]" s (Map.keys allPrims)
case p of
Right v -> pure v
- Left e -> throwError $ ThrownError (Ident "parse-error") (String e)
+ Left e -> throwErrorHere $ ThrownError (Ident "parse-error") (String e)
diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hs
index 7954653..f182384 100644
--- a/test/spec/Radicle/Internal/TestCapabilities.hs
+++ b/test/spec/Radicle/Internal/TestCapabilities.hs
@@ -81,7 +81,7 @@ instance {-# OVERLAPPING #-} Stdin TestLang where
getLineS = do
ws <- lift get
case worldStateStdin ws of
- [] -> throwError Exit
+ [] -> throwErrorHere Exit
h:hs -> lift (put $ ws { worldStateStdin = hs }) >> pure h
instance {-# OVERLAPPING #-} Stdout TestLang where
@@ -93,7 +93,7 @@ instance {-# OVERLAPPING #-} ReadFile TestLang where
fs <- lift $ gets worldStateFiles
case Map.lookup fn fs of
Just f -> pure f
- Nothing -> throwError . OtherError $ "File not found: " <> fn
+ Nothing -> throwErrorHere . OtherError $ "File not found: " <> fn
instance MonadRandom (State WorldState) where
getRandomBytes i = do
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index e0ec8d8..89d517b 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -15,10 +15,12 @@ import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck
(Arbitrary, counterexample, testProperty, (==>))
+import qualified Text.Megaparsec.Pos as Par
import Radicle
+import qualified Radicle.Internal.Annotation as Ann
import Radicle.Internal.Arbitrary ()
-import Radicle.Internal.Core (toIdent)
+import Radicle.Internal.Core (asValue, noStack, toIdent)
import Radicle.Internal.Foo (Foo)
import Radicle.Internal.TestCapabilities
@@ -111,7 +113,7 @@ test_eval =
prog3 `succeedsWith` String "b"
, testProperty "'string-append' concatenates string" $ \ss -> do
- let args = T.unwords $ renderPrettyDef . String <$> ss
+ let args = T.unwords $ renderPrettyDef . asValue . String <$> ss
prog = "(string-append " <> args <> ")"
res = runTest' prog
expected = Right . String $ mconcat ss
@@ -286,12 +288,12 @@ test_eval =
prog `succeedsWith` Number 6
, testProperty "'>' works" $ \(x, y) -> do
- let prog = [i|(> #{renderPrettyDef $ Number x} #{renderPrettyDef $ Number y})|]
+ let prog = [i|(> #{renderPrettyDef . asValue $ Number x} #{renderPrettyDef . asValue $ Number y})|]
res = runTest' $ toS prog
counterexample prog $ res == Right (Boolean (x > y))
, testProperty "'<' works" $ \(x, y) -> do
- let prog = [i|(< #{renderPrettyDef $ Number x} #{renderPrettyDef $ Number y})|]
+ let prog = [i|(< #{renderPrettyDef . asValue $ Number x} #{renderPrettyDef . asValue $ Number y})|]
res = runTest' $ toS prog
counterexample prog $ res == Right (Boolean (x < y))
@@ -392,7 +394,7 @@ test_eval =
orig = runTest' $ toS [i|#{renderPrettyDef v}|]
info = "Expected:\n" <> toS (prettyEither orig)
<> "\nGot:\n" <> toS (prettyEither derefed)
- counterexample info $ derefed == orig
+ counterexample info $ noStack derefed == noStack orig
, testCase "'show' works" $ do
runTest' "(show 'a)" @?= Right (String "a")
@@ -412,7 +414,8 @@ test_eval =
, testCase "'to-json' works" $ do
runTest' "(to-json (dict \"foo\" #t))" @?= Right (String "{\"foo\":true}")
runTest' "(to-json (dict \"key\" (list 1 \"value\")))" @?= Right (String "{\"key\":[1,\"value\"]}")
- runTest' "(to-json (dict 1 2))" @?= Left (OtherError "Could not serialise value to JSON")
+ noStack (runTest' "(to-json (dict 1 2))") @?= Left (OtherError "Could not serialise value to JSON")
+
, testCase "define-rec can define recursive functions" $ do
let prog = [s|
(define-rec triangular
@@ -423,13 +426,42 @@ test_eval =
(triangular 10)
|]
runTest' prog @?= Right (Number 55)
+
, testCase "define-rec errors when defining a non-function" $
failsWith "(define-rec x 42)" (OtherError "define-rec can only be used to define functions")
+
+ , testCase "stack traces work" $ do
+ let prog = [s|
+ (define inner (lambda () (notdefined)))
+ (define outer (lambda () (inner)))
+ (outer)
+ |]
+ case runTest' prog of
+ Left (LangError stack (UnknownIdentifier (Ident "notdefined"))) ->
+ assertEqual "correct line numbers" [3,2,1,1] (stackTraceLines stack)
+ r -> assertFailure $ "Didn't fail the way we expected: " ++ show r
+
+ , testCase "stack traces work with HOFs" $ do
+ let prog = [s|
+ (define callit (lambda (f) (f)))
+ (define inner (lambda () (notdefined)))
+ (callit inner)
+ |]
+ case runTest' prog of
+ Left (LangError stack (UnknownIdentifier (Ident "notdefined"))) ->
+ assertEqual "correct line numbers" [3,1,2,2] (stackTraceLines stack)
+ r -> assertFailure $ "Didn't fail the way we expected: " ++ show r
]
where
- failsWith src err = runTest' src @?= Left err
+ failsWith src err = noStack (runTest' src) @?= Left err
succeedsWith src val = runTest' src @?= Right val
+stackTraceLines :: [Ann.SrcPos] -> [Int]
+stackTraceLines = concatMap go
+ where
+ go Ann.InternalPos{} = []
+ go (Ann.SrcPos pos) = [Par.unPos (Par.sourceLine pos)]
+
test_parser :: [TestTree]
test_parser =
[ testCase "parses strings" $ do
@@ -489,27 +521,26 @@ test_binding =
where
x ~~> y = runIdentity (interpret "test" x pureEnv) @?= Right y
-
test_pretty :: [TestTree]
test_pretty =
[ testCase "long lists are indented" $ do
- let r = renderPretty (apl 5) (List [String "fn", String "abc"])
+ let r = renderPretty (apl 5) (asValue (List [String "fn", String "abc"]))
r @?= "(\"fn\"\n \"abc\")"
, testCase "lists try to fit on one line" $ do
- let r = renderPretty (apl 80) (List [atom "fn", atom "arg1", atom "arg2"])
+ let r = renderPretty (apl 80) (asValue (List [atom "fn", atom "arg1", atom "arg2"]))
r @?= "(fn arg1 arg2)"
, testCase "dicts try to fit on one line" $ do
- let r = renderPretty (apl 80) (Dict $ Map.fromList [ (kw "k1", Number 1)
- , (kw "k2", Number 2)
- ])
+ let r = renderPretty (apl 80) (asValue (Dict $ Map.fromList [ (kw "k1", Number 1)
+ , (kw "k2", Number 2)
+ ]))
r @?= "{:k1 1.0 :k2 2.0}"
, testCase "dicts split with key-val pairs" $ do
- let r = renderPretty (apl 5) (Dict $ Map.fromList [ (kw "k1", Number 1)
- , (kw "k2", Number 2)
- ])
+ let r = renderPretty (apl 5) (asValue (Dict $ Map.fromList [ (kw "k1", Number 1)
+ , (kw "k2", Number 2)
+ ]))
r @?= "{:k1 1.0\n :k2 2.0}"
]
where