A peer-to-peer stack for code collaboration
Add exception facilities.
Julian K. Arnibf6696dd39aa
diff --git a/.hlint.yaml b/.hlint.yamlindex 0232ca0..09ab05c 100644--- a/.hlint.yaml+++ b/.hlint.yaml@@ -27,6 +27,7 @@- ignore: {name: Redundant do}- ignore: {name: Use ++}- ignore: {name: Use &&}+- ignore: {name: Use fromMaybe}- ignore: {name: Eta reduce}- ignore: {name: Use lambda-case}- ignore: {name: Redundant $}diff --git a/repl/config.rad b/repl/config.radindex 1be1df9..2bfc69e 100644--- a/repl/config.rad+++ b/repl/config.rad@@ -1,5 +1,10 @@(define repl- (sorted-map name "repl" getter (quote (get-line!))))+ (sorted-map+ name "repl"+ ;; Parse errors are thrown here+ getter (lambda () (catch 'parse-error (get-line!) print!))))-(subscribe-to! repl- (lambda (x) (print! x)))+;; Evaluation errors are thrown here+(catch 'any+ (subscribe-to! repl print!)+ (lambda (x) (print! x) (subscribe-to! repl print!)))diff --git a/repl/prelude.rad b/repl/prelude.radindex e6d0516..f93439c 100644--- a/repl/prelude.rad+++ b/repl/prelude.rad@@ -100,8 +100,29 @@(print! "error: currency- unknown message"))))))dispatch))-(define repl- (sorted-map name "repl" getter (quote (get-line!))))+(define currency (create-currency))+++(define new-eval (lambda (expr)+ (if (eq? (car expr) 'new-account)+ ((currency 'new-account) (car (cdr expr)))+ (if (eq? (car expr) 'account-balance)+ ((currency 'account-balance) (car (cdr expr)))+ (if (eq? (car expr) 'transfer)+ ((currency 'transfer) (car (cdr expr)) (car (cdr (cdr expr))) (car (cdr+ (cdr (cdr expr)))))+ (print! "transaction must be new-account, transfer, or account-balance"))))))-(subscribe-to! repl- (lambda (x) (print! x)))++;; The Repl++(define repl+ (sorted-map+ name "repl"+ ;; Parse errors are thrown here+ getter (lambda () (catch 'parse-error (get-line!) print!))))++;; Evaluation errors are thrown here+(catch 'any+ (subscribe-to! repl print!)+ (lambda (x) (print! x) (subscribe-to! repl print!)))diff --git a/src/Radicle.hs b/src/Radicle.hsindex e4afc80..bb828b6 100644--- a/src/Radicle.hs+++ b/src/Radicle.hs@@ -24,6 +24,7 @@ module Radicle, coerceRefs, fromIdent, mkIdent+ , quote, Env(..), pureEnv, Langdiff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hsindex 72ff3bc..7e48c39 100644--- a/src/Radicle/Internal/Core.hs+++ b/src/Radicle/Internal/Core.hs@@ -2,16 +2,16 @@{-# LANGUAGE TemplateHaskell #-}module Radicle.Internal.Core where-import Control.Monad.Except (ExceptT(..), MonadError, runExceptT,- throwError)+import Control.Monad.Except (ExceptT(..), MonadError, catchError,+ runExceptT, throwError)import Control.Monad.ST.Trans (STRef, STT, newSTRef, readSTRef,runSTT, writeSTRef)import Control.Monad.Stateimport Data.Bifunctor (first)import Data.Data (Data)import Data.Deriving (deriveEq1, deriveShow1)+import Data.Foldable (foldlM, foldrM)import Data.Functor.Foldable (Fix(..), cata)-import Data.List (foldl')import Data.List.NonEmpty (NonEmpty)import qualified Data.List.NonEmpty as NonEmptyimport Data.Map (Map)@@ -25,11 +25,13 @@ import GHC.Exts (IsList(..), fromString)import GHC.Generics (Generic)import qualified Text.Megaparsec.Error as Parimport Unsafe.Coerce (unsafeCoerce)+import qualified Data.Text as T+-- * Value-- | An error throw during parsing or evaluating expressions in the language.-data LangError =+data LangError r =UnknownIdentifier Ident| Impossible Text| TypeError Text@@ -38,8 +40,43 @@ data LangError =| WrongNumberOfArgs Text Int Int| OtherError Text| ParseError (Par.ParseError Char Void)+ | ThrownError Ident r| Exit- deriving (Eq, Show, Read, Generic)+ deriving (Eq, Show, Read, Generic, Functor)++-- | Convert an error to a radicle value, and the label for it. Used for+-- catching exceptions.+errorToValue :: LangError (Value r) -> (Ident, Value r)+errorToValue e = case e of+ UnknownIdentifier i -> makeVal+ ( "unknown-identifier"+ , [("identifier", makeA i)]+ )+ -- Should this even be catchable?+ Impossible i -> makeVal+ ( "impossible"+ , [("info", String i)]+ )+ TypeError i -> makeVal+ ( "type-error"+ , [("info", String i)]+ )+ WrongNumberOfArgs i expected actual -> makeVal+ ( "wrong-number-of-args"+ , [ ("function", makeA $ Ident i)+ , ("expected", Number $ fromIntegral expected)+ , ("actual", Number $ fromIntegral actual)]+ )+ OtherError i -> makeVal+ ( "other-error"+ , [("info", String i)]+ )+ ParseError _ -> makeVal ("parse-error", [])+ ThrownError label val -> (label , val)+ Exit -> makeVal ("exit", [])+ where+ makeA = quote . Atom+ makeVal (t,v) = (Ident t, SortedMap $ Map.mapKeys Ident . fromList $ v)newtype Reference s = Reference { getReference :: STRef s (Value (Reference s)) }deriving (Eq)@@ -68,7 +105,6 @@ data Value r =| Boolean Bool| List [Value r]| Primop Ident- | Apply (Value r) [Value r]| SortedMap (Map.Map Ident (Value r))| Ref r-- | Takes the arguments/parameters, a body, and possibly a closure.@@ -91,7 +127,6 @@ makeRefs v = cata go (Fix v)Boolean i -> pure $ Boolean iNumber i -> pure $ Number iPrimop i -> pure $ Primop i- Apply f vs -> Apply <$> go f <*> sequence (go <$> vs)SortedMap m -> SortedMap <$> sequence (go <$> m)List vs -> List <$> sequence (go <$> vs)Ref i -> i >>= newRef@@ -144,8 +179,8 @@ data Bindings s m = Bindings-- | The environment in which expressions are evaluated.newtype LangT s r m a = LangT- { fromLangT :: ExceptT LangError (StateT r (STT s m)) a }- deriving (Functor, Applicative, Monad, MonadError LangError, MonadState r)+ { fromLangT :: ExceptT (LangError (Value (Reference s))) (StateT r (STT s m)) a }+ deriving (Functor, Applicative, Monad, MonadError (LangError (Value (Reference s))), MonadState r)instance MonadTrans (LangT s r) where lift = LangT . lift . lift . lift@@ -157,8 +192,8 @@ runLang:: Monad m=> (forall s. Bindings s m)-> (forall s. Lang s m a)- -> m (Either LangError a)-runLang e l = runSTT $ evalStateT (runExceptT $ fromLangT l) e+ -> m (Either (LangError (Value Int)) a)+runLang e l = runSTT $ first (fmap labelRefs) <$> evalStateT (runExceptT $ fromLangT l) e-- | Like 'local' or 'withState'withEnv :: Monad m => (Bindings s m -> Bindings s m) -> Lang s m a -> Lang s m a@@ -196,25 +231,44 @@ lookupPrimop i = get >>= \e -> case Map.lookup i $ bindingsPrimops e ofdefineAtom :: Monad m => Ident -> Value (Reference r) -> Lang r m ()defineAtom i v = modify $ addBinding i v+quote :: Value r -> Value r+quote v = List $ Primop (Ident "quote"):[v]+-- | The universal primops. These are available in chain evaluation, and are-- not shadowable via 'define'.purePrimops :: forall r m. (Monad m) => Primops r mpurePrimops = Map.fromList $ first Ident <$>- [ ("base-eval", \args -> case args of+ [ ("base-eval", evalArgs $ \args -> case args of[x] -> baseEval xxs -> throwError $ WrongNumberOfArgs "base-eval" 1 (length xs))+ , ("list", evalArgs $ \args -> pure $ List args), ("quote", \args -> case args of[v] -> pure vxs -> throwError $ WrongNumberOfArgs "quote" 1 (length xs)), ("define", \args -> case args of[Atom name, val] -> do- val' <- eval val+ val' <- baseEval valdefineAtom name val'pure nil[_, _] -> throwError $ OtherError "define expects atom for first arg"xs -> throwError $ WrongNumberOfArgs "define" 2 (length xs))+ , ("catch", \args -> case args of+ [l, form, handler] -> do+ mlabel <- baseEval l+ case mlabel of+ Atom label -> baseEval form `catchError` \e ->+ let (thrownLabel, thrownValue) = errorToValue e+ in if thrownLabel == label || label == Ident "any"+ then handler $$ [thrownValue]+ else baseEval form+ _ -> throwError $ TypeError "catch: first argument must be atom"+ xs -> throwError $ WrongNumberOfArgs "catch" 1 (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)), ("eq?", evalArgs $ \args -> case args of- [a, b] -> fmap Boolean $ (==) <$> eval a <*> eval b+ [a, b] -> pure $ Boolean (a == b)xs -> throwError $ WrongNumberOfArgs "eq?" 2 (length xs)), ("cons", evalArgs $ \args -> case args of[x, List xs] -> pure $ List (x:xs)@@ -231,11 +285,11 @@ purePrimops = Map.fromList $ first Ident <$>[_] -> throwError $ TypeError "cdr: expects list argument"xs -> throwError $ WrongNumberOfArgs "cdr" 1 (length xs)), ("lookup", evalArgs $ \args -> case args of- [Atom a, SortedMap m] -> case Map.lookup a m of- Just v -> eval v+ [Atom a, SortedMap m] -> pure $ case Map.lookup a m of+ Just v -> v-- Probably an exception is better, but that seems cruel-- when you have no exception handling facilities.- Nothing -> pure nil+ Nothing -> nil[Atom _, _] -> throwError$ TypeError "lookup: second argument must be map"[_, SortedMap _] -> throwError@@ -275,15 +329,15 @@ purePrimops = Map.fromList $ first Ident <$>[_, _] -> throwError $ TypeError ">: expecting number"xs -> throwError $ WrongNumberOfArgs ">" 2 (length xs)), ("foldl", evalArgs $ \args -> case args of- [fn, init', List ls] -> eval $ foldl' (\b a -> (fn $$) [b,a]) init' ls+ [fn, init', List ls] -> foldlM (\b a -> (fn $$) [b,a]) init' ls[_, _, _] -> throwError $ TypeError "foldl: third argument should be a list"xs -> throwError $ WrongNumberOfArgs "foldl" 3 (length xs)), ("foldr", evalArgs $ \args -> case args of- [fn, init', List ls] -> eval $ foldr (\b a -> (fn $$) [b,a]) init' ls+ [fn, init', List ls] -> foldrM (\b a -> (fn $$) [b,a]) init' ls[_, _, _] -> throwError $ TypeError "foldr: third argument should be a list"xs -> throwError $ WrongNumberOfArgs "foldr" 3 (length xs))- , ("map", \args -> case args of- [fn, List ls] -> List <$> traverse eval [fn $$ [l] | l <- ls]+ , ("map", evalArgs $ \args -> case args of+ [fn, List ls] -> List <$> traverse (fn $$) (pure <$> ls)[_, _] -> throwError $ TypeError "map: second argument should be a list"xs -> throwError $ WrongNumberOfArgs "map" 3 (length xs)), ("string?", evalArgs $ \args -> case args of@@ -299,16 +353,16 @@ purePrimops = Map.fromList $ first Ident <$>[_] -> pure $ Boolean Falsexs -> throwError $ WrongNumberOfArgs "number?" 1 (length xs)), ("member?", evalArgs $ \args -> case args of- [x, List xs] -> fmap Boolean $ elem <$> eval x <*> traverse eval xs+ [x, List xs] -> pure . Boolean $ elem x xs[_, _] -> throwError$ TypeError "member?: second argument must be list"xs -> throwError $ WrongNumberOfArgs "eq?" 2 (length xs)), ("if", \args -> case args of[cond, t, f] -> do- b <- eval cond+ b <- baseEval cond-- 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 == Boolean False then eval f else eval t+ if b == Boolean False then baseEval f else baseEval txs -> throwError $ WrongNumberOfArgs "if" 3 (length xs)), ("deref", evalArgs $ \args -> docase args of@@ -323,7 +377,7 @@ purePrimops = Map.fromList $ first Ident <$>]where-- Many primops evaluate their arguments just as normal functions do.- evalArgs f args = traverse eval args >>= f+ evalArgs f args = traverse baseEval args >>= fnumBinop :: (Scientific -> Scientific -> Scientific)-> Text@@ -349,7 +403,7 @@ eval val = dofn <- lookupPrimop i-- Primops get to decide whether and how their args are-- evaluated.- fn [val]+ fn [quote val]Lambda _ _ Nothing -> throwError $ Impossible"lambda should already have an env"Lambda [bnd] body (Just closure) -> do@@ -364,33 +418,14 @@ baseEval :: Monad m => Value (Reference r) -> Lang r m (Value (Reference r))baseEval val = case val ofAtom i -> lookupAtom iRef i -> pure $ Ref i- List vals -> List <$> traverse baseEval vals+ List (f:vs) -> f $$ vs+ List xs -> throwError+ $ WrongNumberOfArgs ("application: " <> T.pack (show $ labelRefs <$> xs))+ 2+ (length xs)String s -> pure $ String sNumber n -> pure $ Number nBoolean b -> pure $ Boolean b- Apply mfn vs -> do- mfn' <- baseEval mfn- case mfn' of- Primop i -> do- fn <- lookupPrimop i- -- Primops get to decide whether and how their args are- -- evaluated.- fn vs- -- This happens if a quoted lambda is explicitly evaled. We then- -- give it the current environment.- Lambda bnds body Nothing -> do- vs' <- traverse baseEval vs- let mappings = fromList (zip bnds vs')- NonEmpty.last <$> withEnv- (\e -> e { bindingsEnv = mappings <> bindingsEnv e })- (traverse baseEval body)- Lambda bnds body (Just closure) -> do- vs' <- traverse baseEval vs- let mappings = fromList (zip bnds vs')- modEnv = mappings <> closure- NonEmpty.last <$> withEnv (\e -> e { bindingsEnv = modEnv })- (traverse baseEval body)- _ -> throwError $ TypeError "Trying to apply a non-function"Primop i -> pure $ Primop ie@(Lambda _ _ (Just _)) -> pure eLambda args body Nothing -> gets $ Lambda args body . Just . bindingsEnv@@ -404,8 +439,38 @@ baseEval val = case val of-- | Infix function applicationinfixr 1 $$-($$) :: Value r -> [Value r] -> Value r-($$) = Apply+($$) :: Monad m => Value (Reference r) -> [Value (Reference r)] -> Lang r m (Value (Reference r))+mfn $$ vs = do+ mfn' <- baseEval mfn+ case mfn' of+ Primop i -> do+ fn <- lookupPrimop i+ -- Primops get to decide whether and how their args are+ -- evaluated.+ fn vs+ -- This happens if a quoted lambda is explicitly evaled. We then+ -- give it the current environment.+ Lambda bnds body Nothing ->+ if length bnds /= length vs+ then throwError $ WrongNumberOfArgs "lambda" (length bnds)+ (length vs)+ else do+ vs' <- traverse baseEval vs+ let mappings = fromList (zip bnds vs')+ NonEmpty.last <$> withEnv+ (\e -> e { bindingsEnv = mappings <> bindingsEnv e })+ (traverse baseEval body)+ Lambda bnds body (Just closure) ->+ if length bnds /= length vs+ then throwError $ WrongNumberOfArgs "lambda" (length bnds)+ (length vs)+ else do+ vs' <- traverse baseEval vs+ let mappings = fromList (zip bnds vs')+ modEnv = mappings <> closure+ NonEmpty.last <$> withEnv (\e -> e { bindingsEnv = modEnv })+ (traverse baseEval body)+ _ -> throwError $ TypeError "Trying to apply a non-function"nil :: Value rnil = List []diff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hsindex b55d75e..37c61ff 100644--- a/src/Radicle/Internal/Parse.hs+++ b/src/Radicle/Internal/Parse.hs@@ -18,8 +18,8 @@ import Data.Void (Void)import GHC.Exts (IsString(..))import Text.Megaparsec (ParsecT, State(..), between, choice,defaultTabWidth, eof, initialPos, manyTill,- runParserT, runParserT', sepBy, sepBy1, some,- try, (<?>))+ runParserT, runParserT', sepBy, some, try,+ (<?>))import qualified Text.Megaparsec as Mimport Text.Megaparsec.Char (char, satisfy, space1)import qualified Text.Megaparsec.Char.Lexer as L@@ -76,15 +76,10 @@ atomOrPrimP = dopure $ if i `elem` prims then Primop i else Atom iapplyP :: VParser-applyP = do- fn:args <- valueP `sepBy1` spaceConsumer- pure $ fn $$ args+applyP = List <$> valueP `sepBy` spaceConsumerquoteP :: VParser-quoteP = Apply (Primop $ toIdent "quote") . pure <$> (char '\'' >> valueP)--listP :: VParser-listP = List <$> (symbol "list" >> (valueP `sepBy` spaceConsumer))+quoteP = List . ((Primop $ toIdent "quote") :) . pure <$> (char '\'' >> valueP)sortedMapP :: VParsersortedMapP = do@@ -122,7 +117,6 @@ valueP = do[ lambdaP <?> "lambda", sortedMapP <?> "sorted-map", refP <?> "ref"- , listP <?> "list", applyP <?> "application"]@@ -144,7 +138,7 @@ interpret=> String-> Text-> (forall s . Bindings s m)- -> m (Either LangError (Value Int))+ -> m (Either (LangError (Value Int)) (Value Int))interpret sourceName expr bnds = dolet primopNames = Map.keys (bindingsPrimops bnds)parsed = runReader (runParserT (valueP <* eof) sourceName expr) primopNamesdiff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hsindex 2dc69e6..fd1d066 100644--- a/src/Radicle/Internal/Pretty.hs+++ b/src/Radicle/Internal/Pretty.hs@@ -29,9 +29,8 @@ instance Pretty r => Pretty (Value r) whereNumber n -> pretty $ show nBoolean True -> "#t"Boolean False -> "#f"- List vs -> parens $ sep ("list" : (pretty <$> vs))+ List vs -> parens $ sep (pretty <$> vs)Primop i -> pretty i- Apply fn vs -> parens $ pretty fn <+> sep (pretty <$> vs)SortedMap mp -> parens $"sorted-map" <+> sep [ pretty k <+> pretty val| (k, val) <- Map.toList mp ]@@ -45,7 +44,7 @@ instance Pretty (Fix Value) where-- pretty indeed!pretty = pretty . unfix-instance Pretty LangError where+instance Pretty r => Pretty (LangError r) wherepretty v = case v ofUnknownIdentifier i -> "Unknown identifier:" <+> pretty iImpossible t -> "This cannot be!" <+> pretty t@@ -56,6 +55,7 @@ instance Pretty LangError whereOtherError t -> "Error:" <+> pretty tParseError t -> "Parser error:" <+> pretty (parseErrorPretty t)Exit -> "Exit"+ ThrownError i val -> "Exception" <+> pretty i <+> pretty val-- | A fast and compact layout. Primarily intended for testing.@@ -64,7 +64,7 @@ instance Pretty LangError where---- >>> import Data.Void-- >>> renderCompactPretty (List [String "hi", String "there"] :: Value Void)--- "(list\n\"hi\"\n\"there\")"+-- "(\"hi\"\n\"there\")"renderCompactPretty :: Pretty v => v -> TextrenderCompactPretty = renderStrict . layoutCompact . pretty@@ -74,11 +74,11 @@ renderCompactPretty = renderStrict . layoutCompact . pretty---- >>> import Data.Void-- >>> renderPretty Unbounded (List [String "hi", String "there"] :: Value Void)--- "(list \"hi\" \"there\")"+-- "(\"hi\" \"there\")"---- >>> import Data.Void-- >>> renderPretty (AvailablePerLine 6 0.5) (List [String "hi", String "there"] :: Value Void)--- "(list\n\"hi\"\n\"there\")"+-- "(\"hi\"\n\"there\")"renderPretty :: Pretty v => PageWidth -> v -> TextrenderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . pretty@@ -88,6 +88,6 @@ renderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . pretty---- >>> import Data.Void-- >>> renderPrettyDef (List [String "hi", String "there"] :: Value Void)--- "(list \"hi\" \"there\")"+-- "(\"hi\" \"there\")"renderPrettyDef :: Pretty v => v -> TextrenderPrettyDef = renderStrict . layoutSmart defaultLayoutOptions . prettydiff --git a/src/Radicle/Internal/Subscriber.hs b/src/Radicle/Internal/Subscriber.hsindex d98b8b0..8398f72 100644--- a/src/Radicle/Internal/Subscriber.hs+++ b/src/Radicle/Internal/Subscriber.hs@@ -3,9 +3,8 @@ module Radicle.Internal.Subscriber whereimport Control.Monad (void)import Control.Monad.Except (throwError)-import Control.Monad.State (gets)+import Control.Monad.State (gets, get)import Data.Bifunctor (first)-import Data.Either (partitionEithers)import Data.List (isPrefixOf)import qualified Data.Map as Mapimport Data.Monoid ((<>))@@ -23,6 +22,7 @@ import Radicle.Internal.Parseimport Radicle.Internal.Prettyimport Radicle.Internal.Subscriber.Capabilities+type ReplM s m =( Monad m, Stdout (Lang s m), Stdin (Lang s m), GetEnv (Lang s m) (Value (Reference s))@@ -65,7 +65,7 @@ replPrimops = Map.fromList $ first toIdent <$>[x] -> dov <- eval xputStrS (renderPrettyDef v)- pure v+ pure nilxs -> throwError $ WrongNumberOfArgs "print!" 1 (length xs)), ("set-env!", \args -> case args of@@ -80,16 +80,18 @@ replPrimops = Map.fromList $ first toIdent <$>[] -> doln <- getLineSallPrims <- gets bindingsPrimops- let p = parseValues "[stdin]" ln (Map.keys allPrims)- case partitionEithers p of- ([], results) -> makeRefs $ List results- (e:_, _) -> throwError $ ParseError e+ let p = parse "[stdin]" ln (Map.keys allPrims)+ case p of+ Right v -> makeRefs v+ Left e -> throwError $ ThrownError (Ident "parse-error")+ (String $ T.pack e)xs -> throwError $ WrongNumberOfArgs "get-line!" 0 (length xs)), ("subscribe-to!", \args -> case args of[x, v] -> do- x' <- baseEval x- v' <- baseEval v+ x' <- eval x+ v' <- eval v+ s <- getcase (x', v') of(SortedMap m, fn) -> case Map.lookup (toIdent "getter") m ofNothing -> throwError@@ -97,8 +99,15 @@ replPrimops = Map.fromList $ first toIdent <$>Just g -> gowherego = do- newBlock <- eval =<< baseEval g- _ <- baseEval (fn $$ [newBlock])+ -- We need to evaluate the getter in the original+ -- environment in which it was defined, but the+ -- /result/ of the getter is then evaluated in the+ -- current environment.+ line <- eval =<< (g $$ [])+ -- Similarly, the application of the subscriber+ -- function is evaluated in the original+ -- environment.+ _ <- withEnv (const s) (fn $$ [quote line])go_ -> throwError $ TypeError "subscribe-to!: Expected sorted-map"xs -> throwError $ WrongNumberOfArgs "subscribe-to!" 2 (length xs))diff --git a/test/spec/Radicle/Internal/Arbitrary.hs b/test/spec/Radicle/Internal/Arbitrary.hsindex f52c1f0..2da346a 100644--- a/test/spec/Radicle/Internal/Arbitrary.hs+++ b/test/spec/Radicle/Internal/Arbitrary.hs@@ -29,7 +29,6 @@ instance {-# OVERLAPPING #-} Arbitrary (Value Void) where, (3, Number <$> arbitrary), (1, List <$> sizedList), (3, Primop <$> elements (Map.keys prims))- , (1, Apply <$> scale (`div` 2) arbitrary <*> sizedList), (3, SortedMap . Map.fromList <$> sizedList), (1, Lambda <$> sizedList<*> scale (`div` 3) arbitrarydiff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hsindex f7d5e90..551ddf3 100644--- a/test/spec/Radicle/Internal/TestCapabilities.hs+++ b/test/spec/Radicle/Internal/TestCapabilities.hs@@ -23,7 +23,7 @@ runTestWith:: (forall s. Bindings s (State WorldState))-> [Text] -- The stdin (errors if it runs out)-> Text -- The program- -> (Either LangError (Value Int), [Text])+ -> (Either (LangError (Value Int)) (Value Int), [Text])runTestWith bindings inputs action =let ws = WorldState{ worldStateStdin = inputs@@ -37,18 +37,18 @@ runTestWith bindings inputs action =runTestWith':: [Text]-> Text- -> (Either LangError (Value Int), [Text])+ -> (Either (LangError (Value Int)) (Value Int), [Text])runTestWith' = runTestWith pureEnv-- | Run a test without stdin/stdoutrunTest:: (forall s. Bindings s (State WorldState))-> Text- -> Either LangError (Value Int)+ -> Either (LangError (Value Int)) (Value Int)runTest bnds prog = fst $ runTestWith bnds [] prog-- | Like 'runTest', but uses the pureEnv-runTest' :: Text -> Either LangError (Value Int)+runTest' :: Text -> Either (LangError (Value Int)) (Value Int)runTest' = runTest pureEnvdiff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hsindex 400e47f..c4237ae 100644--- a/test/spec/Radicle/Tests.hs+++ b/test/spec/Radicle/Tests.hs@@ -23,7 +23,7 @@ import Radicle.Internal.Arbitrary ()import Radicle.Internal.Core (toIdent)import Radicle.Internal.TestCapabilities-import Paths_radicle -- generate by cabal via 'data-files'+import Paths_radicle -- generated by cabal via 'data-files'test_eval :: [TestTree]test_eval =@@ -58,6 +58,10 @@ test_eval =res = runTest' $ T.pack progcounterexample prog $ isLeft res || res == Right (Boolean True)+ , testCase "'eq?' works for quoted values" $ do+ let prog = [s|(eq? 'hi 'hi)|]+ prog `succeedsWith` Boolean True+, testProperty "'eq?' considers different values different"$ \(v1 :: Value Int, v2 :: Value Int) ->v1 /= v2 ==> do@@ -113,6 +117,22 @@ test_eval =let prog = [s|(eval (quote #t))|]prog `succeedsWith` Boolean True+ , testCase "'eval' only evaluates the first quote" $ do+ let prog1 = [s|(eval (quote (quote (+ 3 2))))|]+ prog2 = [s|(quote (+ 3 2))|]+ res1 = runTest' prog1+ res2 = runTest' prog2+ res1 @?= res2++ , testProperty "'eval' does not alter functions" $ \(_v :: Value Int) -> do+ let prog1 = [i| (eval (lambda () #{renderPrettyDef _v})) |]+ prog2 = [i| (lambda () #{renderPrettyDef _v}) |]+ res1 = runTest' $ T.pack prog1+ res2 = runTest' $ T.pack prog2+ info = "Expected:\n" <> prettyEither res2+ <> "\nGot:\n" <> prettyEither res1+ counterexample (T.unpack info) $ res1 == res2+, testCase "lambdas work" $ dolet prog = [s|((lambda (x) x) #t)|]prog `succeedsWith` Boolean True@@ -134,6 +154,17 @@ test_eval =|]prog `succeedsWith` Number 3+ , testCase "lambdas throw WrongNumberOfArgs if given wrong number of args" $ do+ let prog = [s| ((lambda (x) 3)) |]+ prog `failsWith` WrongNumberOfArgs "lambda" 1 0++ , testCase "'quote' gets evaluated the right number of times" $ do+ let prog = [s|+ (define test (lambda (x) (eq? x 'hi)))+ (test 'hi)+ |]+ prog `succeedsWith` Boolean True+, testCase "'if' works with three arguments and true cond" $ dolet prog = [s|(if #t "a" "b")|]prog `succeedsWith` String "a"@@ -204,6 +235,26 @@ test_eval =let prog = [s|(define "hi" "there")|]prog `failsWith` OtherError "define expects atom for first arg"+ , testCase "'catch' catches thrown exceptions" $ do+ let prog = [s|+ (catch (quote exc) (throw (quote exc) #t) (lambda (y) y))+ |]+ prog `succeedsWith` Boolean True++ , testCase "'catch' has the correct environment" $ do+ let prog = [s|+ (define t #t)+ (define f #f)+ (catch (quote exc) (throw (quote exc) f) (lambda (y) t))+ |]+ prog `succeedsWith` Boolean True++ , testCase "'catch 'any' catches any exception" $ do+ let prog = [s|+ (catch 'any (throw (quote exc) #f) (lambda (y) #t))+ |]+ prog `succeedsWith` Boolean True+, testCase "evaluation can be redefined" $ dolet prog = [s|(define eval (lambda (x) #f))@@ -252,8 +303,8 @@ test_parser ="evaluate" ~~> Atom (toIdent "evaluate"), testCase "parses function application" $ do- "(++)" ~~> (Atom (toIdent "++") $$ [])- "(++ \"merge\" \"d\")" ~~> (Atom (toIdent "++") $$ [String "merge", String "d"])+ "(++)" ~~> List [Atom (toIdent "++")]+ "(++ \"merge\" \"d\")" ~~> List [Atom (toIdent "++"), String "merge", String "d"], testCase "parses number" $ do"0.15" ~~> Number 0.15@@ -265,10 +316,6 @@ test_parser =, testCase "parses identifiers that have a primop as prefix" $ do"evaluate" ~~> Atom (toIdent "evaluate")-- , testCase "parses function application" $ do- "(++)" ~~> (Atom (toIdent "++") $$ [])- "(++ \"merge\" \"d\")" ~~> (Atom (toIdent "++") $$ [String "merge", String "d"])]wherex ~~> y = parseTest x @?= Right y@@ -285,7 +332,7 @@ test_binding =test_pretty :: [TestTree]test_pretty =[ testProperty "pretty . parse == identity" $ \(val :: Value (Fix Value)) ->- let rendered = renderCompactPretty val+ let rendered = renderPrettyDef valactual = parseTest renderedoriginal = removeEnv' valinfo = case actual of@@ -306,10 +353,20 @@ test_env =test_repl_primops :: [TestTree]test_repl_primops =[ testProperty "get-line! returns the input line" $ \(v :: Value Void) ->- let res = run [renderCompactPretty v] [s|(get-line!)|]- expected = Right $ List [removeEnv v]- info = "Expected: " <> show expected <> "\nGot: " <> show res- in counterexample info $ res == (coerceRefs <$> expected)+ let prog = [i|(eq? (get-line!) (quote #{renderPrettyDef v}))|]+ res = run [renderPrettyDef v] $ T.pack prog+ in counterexample prog $ res == Right (Boolean True)++ , testCase "catch catches get-line errors" $ do+ let prog = [s|+ (define repl (sorted-map name "repl" getter get-line!))+ (catch 'any+ (subscribe-to! repl (lambda (x) (print! x)))+ (lambda (x) "caught"))+ |]+ input = ["\"blah"]+ res = run input prog+ res @?= Right (String "caught")]whererun stdin prog = fst $ runTestWith replBindings stdin prog@@ -319,7 +376,7 @@ test_repl :: [TestTree]test_repl =[ testCase "evaluates correctly" $ dolet input = [ "((lambda (x) x) #t)" ]- output = [ "(list #t)" ]+ output = [ "#t" ](_, result) <- runInRepl inputresult @?= output@@ -327,8 +384,8 @@ test_repl =let input = [ "(define id (lambda (x) x))", "(id #t)"]- output = [ "(list (list))"- , "(list #t)"+ output = [ "()"+ , "#t"](_, result) <- runInRepl inputresult @?= output@@ -337,7 +394,7 @@ test_repl =let input = [ "(define eval (lambda (x) #t))", "#f"]- output = [ "(list (list))"+ output = [ "()", "#t"](_, result) <- runInRepl input@@ -348,16 +405,19 @@ test_repl =, "(define id (lambda (x) x))", "(id #t)"]- output = [ "(list (list))"- , "(list (list))"- , "(list #t)"+ output = [ "()"+ , "()"+ , "#t"](_, result) <- runInRepl inputresult @?= output]wheregetCfg = getDataFileName "repl/config.rad" >>= T.readFile- runInRepl inp = runTestWith replBindings inp <$> getCfg+ -- The repl catches exceptions, including the "out of stdin" exception+ -- that occurs at the end of a session, so we take the 'init' of the+ -- result.+ runInRepl inp = fmap init <$> (runTestWith replBindings inp <$> getCfg)-- Tests all radicle files 'repl' dir. These should use the 'should-be'-- function to ensure they are in the proper format.@@ -367,7 +427,6 @@ test_source_files = testGroup "Radicle source file tests" <$> dolet dir = reverse $ drop (length ("config.rad" :: String)) $ reverse oneOf'Emfiles <- getDirectoryContents dirlet radFiles = filter (".rad" `isSuffixOf`) files- print radFilessequence $ radFiles <&> \file -> docontents <- T.readFile $ dir <> filelet (_, out) = runTestWith replBindings [] contents@@ -375,11 +434,9 @@ test_source_files = testGroup "Radicle source file tests" <$> do$ T.drop 1$ T.dropWhile (/= '\'') linein testCase (T.unpack name) $ result @?= "' succeeded\""- print outpure $ testGroup file$ [ makeTest ln | ln <- out, "\"Test" `T.isPrefixOf` ln ]--- * Utils-- | Environments are neither printed nor parsed, but are generated by the@@ -387,7 +444,6 @@ test_source_files = testGroup "Radicle source file tests" <$> doremoveEnv :: Value s -> Value sremoveEnv v = case v ofList xs -> List $ removeEnv <$> xs- Apply fn xs -> Apply (removeEnv fn) (removeEnv <$> xs)SortedMap m -> SortedMap $ removeEnv <$> mLambda ids bd _ -> Lambda ids (removeEnv <$> bd) Nothingx -> x@@ -395,7 +451,7 @@ removeEnv v = case v ofremoveEnv' :: Value (Fix Value) -> Value (Fix Value)removeEnv' v = Fix . removeEnv' . unfix <$> removeEnv v-prettyEither :: Pretty s => Either LangError (Value s) -> T.Text+prettyEither :: Pretty s => Either (LangError (Value s)) (Value s) -> T.TextprettyEither (Left e) = "Error: " <> renderPrettyDef eprettyEither (Right v) = renderPrettyDef v