Skip to content

A peer-to-peer stack for code collaboration

The new eval (#99)

Julian Arni1a5111794fd0
diff --git a/exe/Server/Client.hs b/exe/Server/Client.hs
index 5e78ff0..5c23800 100644
--- a/exe/Server/Client.hs
+++ b/exe/Server/Client.hs
@@ -62,14 +62,14 @@ opts = Opts
-- * Primops
-bindings :: ClientEnv -> Bindings (InputT IO)
+bindings :: ClientEnv -> Bindings (Primops (InputT IO))
bindings cEnv = e { bindingsPrimops = bindingsPrimops e <> primops cEnv }
where
- e :: Bindings (InputT IO)
+ e :: Bindings (Primops (InputT IO))
e = pureEnv
primops :: ClientEnv -> Primops (InputT IO)
-primops cEnv = fromList [sendPrimop, receivePrimop] <> replPrimops
+primops cEnv = Primops (fromList [sendPrimop, receivePrimop]) <> replPrimops
where
sendPrimop =
( Ident "send!"
diff --git a/exe/Server/Server.hs b/exe/Server/Server.hs
index 53601b2..7332a4e 100644
--- a/exe/Server/Server.hs
+++ b/exe/Server/Server.hs
@@ -91,7 +91,7 @@ getSince st name index = do
data Chain = Chain
{ chainName :: Text
- , chainState :: Bindings Identity
+ , chainState :: Bindings (Primops Identity)
, chainExprs :: Seq (Value, Value)
} deriving (Generic)
diff --git a/src/Radicle.hs b/src/Radicle.hs
index 18f6b98..7f082de 100644
--- a/src/Radicle.hs
+++ b/src/Radicle.hs
@@ -32,6 +32,9 @@ module Radicle
, runLang
, Bindings(..)
, replBindings
+ -- ** To/FromRadicle
+ , ToRadicle(..)
+ , FromRadicle(..)
-- ** Re-exports
, runIdentity
@@ -50,7 +53,7 @@ module Radicle
, repl
-- * Primops
- , Primops
+ , Primops(..)
, purePrimops
, replPrimops
, ReplM
@@ -65,8 +68,6 @@ module Radicle
, quote
, ($$)
, kwLookup
- , makeBindings
- , unmakeBindings
, (??)
) where
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index 7cc6cf6..39dcb32 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -1,7 +1,7 @@
-- | The core radicle datatypes and functionality.
module Radicle.Internal.Core where
-import Protolude hiding (TypeError, (<>))
+import Protolude hiding (TypeError, (<>), list)
import Codec.Serialise (Serialise)
import Control.Monad.Except
@@ -22,6 +22,7 @@ import qualified Text.Megaparsec.Error as Par
import Radicle.Internal.Orphans ()
+
-- * Value
-- | An error throw during parsing or evaluating expressions in the language.
@@ -187,15 +188,16 @@ instance GhcExts.IsList (Env s) where
toList = GhcExts.toList . fromEnv
-- | Primop mappings. The parameter specifies the monad the primops run in.
-type Primops m = Map Ident ([Value ] -> Lang m Value)
+newtype Primops m = Primops { getPrimops :: Map Ident ([Value ] -> Lang m Value) }
+ deriving (Semigroup)
-- | Bindings, either from the env or from the primops.
-data Bindings m = Bindings
+data Bindings prims = Bindings
{ bindingsEnv :: Env Value
- , bindingsPrimops :: Primops m
+ , bindingsPrimops :: prims
, bindingsRefs :: IntMap Value
, bindingsNextRef :: Int
- } deriving (Generic)
+ } deriving (Eq, Show, Functor, Generic)
-- | The environment in which expressions are evaluated.
newtype LangT r m a = LangT
@@ -206,16 +208,26 @@ instance MonadTrans (LangT r) where lift = LangT . lift . lift
-- | A monad for language operations specialized to have as state the Bindings
-- with appropriate underlying monad.
-type Lang m = LangT (Bindings m) m
+type Lang m = LangT (Bindings (Primops m)) m
-- | Run a `Lang` computation with the provided bindings. Returns the result as
-- well as the updated bindings.
runLang
- :: Bindings m
+ :: Bindings (Primops m)
-> Lang m a
- -> m (Either (LangError Value) a, Bindings m)
+ -> m (Either (LangError Value) a, Bindings (Primops m))
runLang e l = runStateT (runExceptT $ fromLangT l) e
+-- | Like 'local' or 'withState'. Will run an action with a modified environment
+-- and then restore the original bindings.
+withBindings :: Monad m => (Bindings (Primops m) -> Bindings (Primops m)) -> Lang m a -> Lang m a
+withBindings modifier action = do
+ oldBnds <- get
+ modify modifier
+ res <- action
+ put oldBnds
+ pure res
+
-- | Like 'local' or 'withState'. Will run an action with a modified environment
-- and then restore the original environment. Other bindings (i.e. primops and
-- refs) are not affected.
@@ -241,34 +253,41 @@ lookupAtom i = get >>= \e -> case Map.lookup i . fromEnv $ bindingsEnv e of
-- | Lookup a primop.
lookupPrimop :: Monad m => Ident -> Lang m ([Value] -> Lang m Value)
-lookupPrimop i = get >>= \e -> case Map.lookup i $ bindingsPrimops e of
+lookupPrimop i = get >>= \e -> case Map.lookup i $ getPrimops $ bindingsPrimops e of
Nothing -> throwError $ Impossible "Unknown primop"
Just v -> pure v
defineAtom :: Monad m => Ident -> Value -> Lang m ()
defineAtom i v = modify $ addBinding i v
-quote :: Value -> Value
-quote v = List [Primop (Ident "quote"), v]
-
-- * Eval
-- | The buck-passing eval. Uses whatever 'eval' is in scope.
eval :: Monad m => Value -> Lang m Value
eval val = do
e <- lookupAtom (toIdent "eval")
+ st <- gets toRadicle
case e of
Primop i -> do
fn <- lookupPrimop i
-- Primops get to decide whether and how their args are
-- evaluated.
- fn [quote val]
- Lambda [bnd] body closure -> do
- let mappings = GhcExts.fromList [(bnd, val)]
- modEnv = mappings <> closure
- NonEmpty.last <$> withEnv (const modEnv)
- (traverse eval body)
+ res <- fn [quote val, quote st]
+ updateEnvAndReturn res
+ l@Lambda{} -> callFn l [val, st] >>= updateEnvAndReturn
_ -> throwError $ 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
+ (fromRadicle newSt :: Either Text (Bindings ()))
+ put $ newSt' { bindingsPrimops = prims }
+ return val'
+ _ -> throwError $ OtherError "eval: should return list with value and new env"
+
+
-- | The built-in, original, eval.
baseEval :: Monad m => Value -> Lang m Value
@@ -284,6 +303,66 @@ baseEval val = case val of
Dict . Map.fromList <$> traverse evalBoth (Map.toList mp)
autoquote -> pure autoquote
+-- * From/ToRadicle
+
+class FromRadicle a where
+ fromRadicle :: Value -> Either Text a
+
+instance FromRadicle Scientific where
+ fromRadicle x = case x of
+ Number n -> pure n
+ _ -> Left "Expecting number"
+instance FromRadicle Text where
+ fromRadicle x = case x of
+ String n -> pure n
+ _ -> Left "Expecting string"
+instance FromRadicle a => FromRadicle [a] where
+ fromRadicle x = case x of
+ List xs -> traverse fromRadicle xs
+ _ -> Left "Expecting list"
+instance FromRadicle (Env Value) where
+ fromRadicle x = case x of
+ Dict d -> fmap (Env . Map.fromList)
+ $ forM (Map.toList d) $ \(k, v) -> case k of
+ Atom i -> pure (i, v)
+ k' -> Left $ "Expecting atom keys. Got: " <> show k'
+ _ -> Left "Expecting dict"
+instance FromRadicle (Bindings ()) where
+ fromRadicle x = case x of
+ Dict d -> do
+ env' <- kwLookup "env" d ?? "Expecting 'env' key"
+ refs' <- kwLookup "refs" d ?? "Expecting 'refs' key"
+ refs <- makeRefs refs'
+ env <- fromRadicle env'
+ pure $ Bindings env () refs (length refs)
+ _ -> throwError "Expecting dict"
+ where
+ makeRefs refs = case refs of
+ List ls -> pure (IntMap.fromList $ zip [0..] ls)
+ _ -> throwError $ "Expecting dict"
+
+
+
+class ToRadicle a where
+ toRadicle :: a -> Value
+
+instance ToRadicle Int where
+ toRadicle = Number . fromIntegral
+instance ToRadicle Scientific where
+ toRadicle = Number
+instance ToRadicle Text where
+ toRadicle = String
+instance ToRadicle a => ToRadicle [a] where
+ toRadicle xs = List $ toRadicle <$> xs
+instance ToRadicle a => ToRadicle (Map.Map Text a) where
+ toRadicle xs = Dict $ Map.mapKeys String $ toRadicle <$> xs
+instance ToRadicle (Env Value) where
+ toRadicle x = Dict . Map.mapKeys Atom $ fromEnv x
+instance ToRadicle (Bindings m) where
+ toRadicle x = Dict $ Map.fromList
+ [ (Keyword $ Ident "env", toRadicle $ bindingsEnv x)
+ , (Keyword $ Ident "refs", List $ IntMap.elems (bindingsRefs x))
+ ]
-- * Helpers
@@ -323,3 +402,15 @@ mfn $$ vs = do
nil :: Value
nil = List []
+
+quote :: Value -> Value
+quote v = List [Primop (Ident "quote"), v]
+
+list :: [Value] -> Value
+list vs = List (Primop (Ident "list") : vs)
+
+kwLookup :: Text -> Map Value Value -> Maybe Value
+kwLookup key = Map.lookup (Keyword $ Ident key)
+
+(??) :: MonadError e m => Maybe a -> e -> m a
+a ?? n = n `note` a
diff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hs
index 5118b2b..c6c35b6 100644
--- a/src/Radicle/Internal/Effects.hs
+++ b/src/Radicle/Internal/Effects.hs
@@ -31,7 +31,7 @@ type ReplM m =
, GetEnv (Lang m) Value
, SetEnv (Lang m) Value )
-repl :: Maybe FilePath -> Text -> Bindings (InputT IO) -> IO ()
+repl :: Maybe FilePath -> Text -> Bindings (Primops (InputT IO)) -> IO ()
repl histFile preCode bindings = do
let settings = setComplete completion
$ defaultSettings { historyFile = histFile }
@@ -47,23 +47,23 @@ completion :: Monad m => CompletionFunc m
completion = completeWord Nothing ['(', ')', ' ', '\n'] go
where
-- Any type for first param will do
- bnds :: Bindings (InputT IO)
+ bnds :: Bindings (Primops (InputT IO))
bnds = replBindings
go s = pure $ fmap simpleCompletion
$ filter (s `isPrefixOf`)
$ fmap (T.unpack . fromIdent)
$ (Map.keys . fromEnv $ bindingsEnv bnds)
- <> Map.keys (bindingsPrimops bnds)
+ <> Map.keys (getPrimops $ bindingsPrimops bnds)
-replBindings :: forall m. ReplM m => Bindings m
+replBindings :: forall m. ReplM m => Bindings (Primops m)
replBindings = e { bindingsPrimops = bindingsPrimops e <> replPrimops }
where
- e :: Bindings m
+ e :: Bindings (Primops m)
e = pureEnv
replPrimops :: forall m. ReplM m => Primops m
-replPrimops = Map.fromList $ first toIdent <$>
+replPrimops = Primops . Map.fromList $ first toIdent <$>
[ ("print!", \args -> case args of
[x] -> do
v <- eval x
diff --git a/src/Radicle/Internal/Interpret.hs b/src/Radicle/Internal/Interpret.hs
index 536de91..67774fd 100644
--- a/src/Radicle/Internal/Interpret.hs
+++ b/src/Radicle/Internal/Interpret.hs
@@ -22,12 +22,12 @@ import Radicle.Internal.Parse
-- Left (TypeError "Trying to apply a non-function")
interpret
:: Monad m
- => Text -- ^ Name of source file (for error reporting)
- -> Text -- ^ Source code to be interpreted
- -> Bindings m -- ^ Bindings to be used
+ => Text -- ^ Name of source file (for error reporting)
+ -> Text -- ^ Source code to be interpreted
+ -> Bindings (Primops m) -- ^ Bindings to be used
-> m (Either (LangError Value) Value)
interpret sourceName expr bnds = do
- let primopNames = Map.keys (bindingsPrimops bnds)
+ 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
@@ -49,7 +49,7 @@ interpretMany
-> Text -- ^ Source code to be interpreted
-> Lang m Value
interpretMany sourceName src = do
- primopNames <- gets $ Map.keys . bindingsPrimops
+ primopNames <- gets $ Map.keys . getPrimops . bindingsPrimops
let parsed = parseValues sourceName src primopNames
case partitionEithers parsed of
([], vs) -> do
diff --git a/src/Radicle/Internal/Primops.hs b/src/Radicle/Internal/Primops.hs
index 7217806..bef4718 100644
--- a/src/Radicle/Internal/Primops.hs
+++ b/src/Radicle/Internal/Primops.hs
@@ -4,10 +4,6 @@ module Radicle.Internal.Primops
, evalArgs
, evalOneArg
, readValue
- , kwLookup
- , makeBindings
- , unmakeBindings
- , (??)
) where
import Protolude hiding (TypeError)
@@ -23,7 +19,7 @@ import Radicle.Internal.Parse
import Radicle.Internal.Pretty
-- | A Bindings with an Env containing only 'eval' and only pure primops.
-pureEnv :: (Monad m) => Bindings m
+pureEnv :: (Monad m) => Bindings (Primops m)
pureEnv = Bindings e purePrimops r 1
where
e = fromList [ (toIdent "eval", Primop $ toIdent "base-eval")
@@ -34,29 +30,32 @@ pureEnv = Bindings e purePrimops r 1
-- | The universal primops. These are available in chain evaluation, and are
-- not shadowable via 'define'.
purePrimops :: forall m. (Monad m) => Primops m
-purePrimops = fromList $ first Ident <$>
+purePrimops = Primops $ fromList $ first Ident <$>
[ ( "lambda"
, \case
List atoms_ : b : bs -> do
- atoms <- traverse isAtom atoms_ ?? "lambda: expecting a list of symbols"
+ atoms <- traverse isAtom atoms_ ?? 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"
)
- , ("base-eval", evalOneArg "base-eval" baseEval)
+ , ( "base-eval"
+ , evalArgs $ \case
+ [expr, st] -> case (fromRadicle st :: Either Text (Bindings ())) of
+ Left e -> throwError $ OtherError e
+ Right st' -> do
+ prims <- gets bindingsPrimops
+ withBindings (const $ fmap (const prims) st') $ do
+ val <- baseEval expr
+ st'' <- get
+ pure $ List [val, toRadicle st'']
+ xs -> throwError $ WrongNumberOfArgs "base-eval" 2 (length xs)
+ )
, ( "pure-env"
, \case
- [] -> pure $ unmakeBindings (pureEnv :: Bindings m)
+ [] -> pure $ toRadicle (pureEnv :: Bindings (Primops m))
xs -> throwError $ WrongNumberOfArgs "pure-env" 0 (length xs)
)
- , ("eval-with-env", evalArgs $ \case
- [expr, env] -> do
- bnds <- makeBindings env
- let (evalRes, bnds') = runIdentity $ runLang bnds $ eval expr
- case evalRes of
- Left e -> throwError e
- Right res -> pure $ List [res, unmakeBindings bnds']
- xs -> throwError $ WrongNumberOfArgs "eval-with-env" 2 (length xs))
, ("apply", evalArgs $ \case
[fn, List args] -> eval . List $ fn:args
[_, _] -> throwError $ TypeError "apply: expecting list as second arg"
@@ -67,7 +66,7 @@ purePrimops = fromList $ first Ident <$>
_ -> throwError $ TypeError "read: expects string"
)
, ("get-current-env", \case
- [] -> unmakeBindings <$> get
+ [] -> toRadicle <$> get
xs -> throwError $ WrongNumberOfArgs "get-current-env" 0 (length xs))
, ("list", evalArgs $ \args -> pure $ List args)
, ("dict", evalArgs $ (Dict . foldr (uncurry Map.insert) mempty <$>) . evenArgs "dict")
@@ -129,9 +128,7 @@ purePrimops = fromList $ first Ident <$>
, evalArgs $ \case
[Number n, List xs] -> case floatingOrInteger n of
Left (_ :: Double) -> throwError $ OtherError "nth: first argument was not an integer"
- Right i -> do
- let x_ = indexMay i xs
- case x_ of
+ 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"
@@ -261,7 +258,7 @@ purePrimops = fromList $ first Ident <$>
)
, ( "to-json"
, evalOneArg "to-json" $ \v -> String . toS . Aeson.encode <$>
- maybeJson v ?? "Could not serialise value to JSON"
+ maybeJson v ?? OtherError "Could not serialise value to JSON"
)
]
where
@@ -274,11 +271,6 @@ purePrimops = fromList $ first Ident <$>
then baseEval e
else cond ps
- indexMay :: Int -> [a] -> Maybe a
- indexMay _ [] = Nothing
- indexMay 0 (x:_) = pure x
- indexMay n (_:xs) = indexMay (n - 1) xs
-
-- | Some forms/functions expect an even number or arguments.
evenArgs name = \case
[] -> pure []
@@ -315,51 +307,13 @@ evalOneArg fname f = evalArgs $ \case
[x] -> f x
xs -> throwError $ WrongNumberOfArgs fname 1 (length xs)
-readValue :: (MonadError (LangError Value) m, MonadState (Bindings n) m) => Text -> m Value
+readValue
+ :: (MonadError (LangError Value) m, MonadState (Bindings (Primops n)) m)
+ => Text
+ -> m Value
readValue s = do
- allPrims <- gets bindingsPrimops
+ allPrims <- gets (getPrimops . bindingsPrimops)
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)
-
--- | Convert Bindings into a Value that can be used with radicle.
-unmakeBindings :: Bindings m -> Value
-unmakeBindings bnds = Dict $ Map.fromList
- [ (Keyword $ Ident "env", Dict $ Map.mapKeys Atom $ fromEnv $ bindingsEnv bnds)
- , (Keyword $ Ident "refs", List $ IntMap.elems (bindingsRefs bnds))
- ]
-
--- | Convert a value into Bindings, or throw an error.
-makeBindings :: (Monad m, Monad n) => Value -> Lang m (Bindings n)
-makeBindings val = case val of
- Dict d -> do
- env' <- kwLookup "env" d ?? "expecting 'env' key"
- refs' <- kwLookup "refs" d ?? "expecting 'refs' key"
- (nextRef, refs) <- makeRefs refs'
- env <- makeEnv env'
- pure $ Bindings env purePrimops refs nextRef
- _ -> throwError $ TypeError "expecting dict"
- where
- makeEnv env = case env of
- Dict d -> fmap (Env . Map.fromList)
- $ forM (Map.toList d) $ \(k, v) -> case k of
- Atom i -> pure (i, v)
- _ -> throwError $ TypeError "Expecting atom keys"
- _ -> throwError $ TypeError "Expecting dict"
-
- makeRefs refs = case refs of
- List ls -> pure (length ls, IntMap.fromList $ zip [0..] ls)
- _ -> throwError $ TypeError "Expecting dict"
-
-
-kwLookup :: Text -> Map Value Value -> Maybe Value
-kwLookup key = Map.lookup (Keyword $ Ident key)
-
--- | Throws an OtherError with the specified message if the Maybe is not a
--- Just.
-(??) :: MonadError (LangError Value) m => Maybe a -> Text -> m a
-a ?? msg = case a of
- Nothing -> throwError $ OtherError msg
- Just v -> pure v
-
diff --git a/test/spec/Radicle/Internal/Arbitrary.hs b/test/spec/Radicle/Internal/Arbitrary.hs
index 53864c3..04b2462 100644
--- a/test/spec/Radicle/Internal/Arbitrary.hs
+++ b/test/spec/Radicle/Internal/Arbitrary.hs
@@ -4,6 +4,7 @@ module Radicle.Internal.Arbitrary where
import Protolude
import qualified Data.Map as Map
+import qualified Data.IntMap as IntMap
import Data.Scientific (Scientific)
import Test.QuickCheck
import Test.QuickCheck.Instances ()
@@ -28,7 +29,7 @@ instance Arbitrary Value where
, (3, Boolean <$> arbitrary)
, (3, Number <$> arbitrary)
, (1, List <$> sizedList)
- , (6, Primop <$> elements (Map.keys prims))
+ , (6, Primop <$> elements (Map.keys $ getPrimops prims))
, (1, Lambda <$> sizedList
<*> scale (`div` 3) arbitrary
<*> scale (`div` 3) arbitrary)
@@ -39,9 +40,9 @@ instance Arbitrary Value where
sizedList = sized $ \n -> do
k <- choose (0, n)
scale (`div` (k + 1)) $ vectorOf k arbitrary
- prims :: Map.Map Ident ([Value] -> Lang Identity Value)
+ prims :: Primops Identity
prims = purePrimops
- isPrimop x = x `elem` Map.keys prims
+ isPrimop x = x `elem` Map.keys (getPrimops prims)
isNum x = isJust (readMaybe (toS $ fromIdent x) :: Maybe Scientific)
instance Arbitrary Ident where
@@ -52,3 +53,10 @@ instance Arbitrary Ident where
rest = sized $ \n -> do
k <- choose (0, n)
vectorOf k . elements $ filter isValidIdentRest allChars
+
+instance Arbitrary a => Arbitrary (Bindings a) where
+ arbitrary = do
+ refs <- arbitrary
+ env <- arbitrary
+ prims <- arbitrary
+ pure $ Bindings env prims (IntMap.fromList $ zip [0..] refs) (length refs)
diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hs
index b41ef44..d5fd047 100644
--- a/test/spec/Radicle/Internal/TestCapabilities.hs
+++ b/test/spec/Radicle/Internal/TestCapabilities.hs
@@ -24,7 +24,7 @@ type TestLang = Lang (State WorldState)
-- | Run a possibly side-effecting program with the given stdin input lines.
runTestWithFiles
- :: Bindings (State WorldState)
+ :: Bindings (Primops (State WorldState))
-> [Text] -- The stdin (errors if it runs out)
-> Map Text Text -- The files
-> Text -- The program
@@ -41,7 +41,7 @@ runTestWithFiles bindings inputs files action =
-- | Run a possibly side-effecting program with the given stdin input lines.
runTestWith
- :: Bindings (State WorldState)
+ :: Bindings (Primops (State WorldState))
-> [Text] -- The stdin (errors if it runs out)
-> Text -- The program
-> (Either (LangError Value) Value, [Text])
@@ -56,7 +56,7 @@ runTestWith' = runTestWith pureEnv
-- | Run a test without stdin/stdout
runTest
- :: Bindings (State WorldState)
+ :: Bindings (Primops (State WorldState))
-> Text
-> Either (LangError Value) Value
runTest bnds prog = fst $ runTestWith bnds [] prog
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index c7346e7..ed4c5f2 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -6,13 +6,15 @@ import Protolude hiding (toList)
import Data.List (isInfixOf, isSuffixOf)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromJust)
+import Data.Scientific (Scientific)
import Data.String.Interpolate (i)
import Data.String.QQ (s)
import qualified Data.Text as T
import GHC.Exts (fromList, toList)
import Test.Tasty
import Test.Tasty.HUnit
-import Test.Tasty.QuickCheck (counterexample, testProperty, (==>))
+import Test.Tasty.QuickCheck (Arbitrary, counterexample, testProperty,
+ (==>))
import Radicle
import Radicle.Internal.Arbitrary ()
@@ -134,18 +136,18 @@ test_eval =
prog `succeedsWith` List [List [Number 1, Number 1]]
, testCase "'eval' evaluates the list" $ do
- let prog = [s|(eval (quote #t))|]
+ let prog = [s|(head (eval (quote #t) (get-current-env)))|]
prog `succeedsWith` Boolean True
, testCase "'eval' only evaluates the first quote" $ do
- let prog1 = [s|(eval (quote (quote (+ 3 2))))|]
+ let prog1 = [s|(head (eval (quote (quote (+ 3 2))) (get-current-env)))|]
prog2 = [s|(quote (+ 3 2))|]
res1 = runTest' prog1
res2 = runTest' prog2
res1 @?= res2
, testProperty "'eval' does not alter functions" $ \(_v :: Value) -> do
- let prog1 = [i| (eval (lambda () #{renderPrettyDef _v})) |]
+ let prog1 = [i| (head (eval (lambda () #{renderPrettyDef _v}) (get-current-env))) |]
prog2 = [i| (lambda () #{renderPrettyDef _v}) |]
res1 = runTest' $ toS prog1
res2 = runTest' $ toS prog2
@@ -153,14 +155,6 @@ test_eval =
<> "\nGot:\n" <> prettyEither res1
counterexample (toS info) $ res1 == res2
- , testCase "'eval-with-env' has access to variable definitions" $ do
- let prog = [s|(head (eval-with-env
- 't
- (dict :env (dict 'eval 'base-eval 't #t)
- :refs (list))))
- |]
- prog `succeedsWith` Boolean True
-
, testCase "lambdas work" $ do
let prog = [s|((lambda (x) x) #t)|]
prog `succeedsWith` Boolean True
@@ -326,11 +320,19 @@ test_eval =
, testCase "evaluation can be redefined" $ do
let prog = [s|
- (define eval (lambda (x) #f))
+ (define eval (lambda (expr env) (list #f env)))
#t
|]
prog `succeedsWith` Boolean False
+ , testCase "redefining eval keeps access to future definitions" $ do
+ let prog = [s|
+ (define eval (lambda (expr env) (eval expr env)))
+ (define t #t)
+ t
+ |]
+ prog `succeedsWith` Boolean True
+
, testCase "'read-ref' returns the most recent value" $ do
let prog = [s|
(define x (ref 5))
@@ -568,7 +570,7 @@ test_repl =
result @==> output
, testCase "handles 'eval' redefinition" $ do
- let input = [ "(define eval (lambda (x) #t))"
+ let input = [ "(define eval (lambda (expr env) (list #t env)))"
, "#f"
]
output = [ "()"
@@ -603,6 +605,31 @@ test_repl =
]
pure $ runTestWithFiles replBindings inp (Map.fromList srcMap) (fromJust replSrc)
+test_from_to_radicle :: [TestTree]
+test_from_to_radicle =
+ [ testGroup "Env Value"
+ [ testForType (Proxy :: Proxy (Env Value)) ]
+ , testGroup "Bindings ()"
+ [ testForType (Proxy :: Proxy (Bindings ())) ]
+ , testGroup "Scientific"
+ [ testForType (Proxy :: Proxy Scientific) ]
+ , testGroup "Text"
+ [ testForType (Proxy :: Proxy Text) ]
+ , testGroup "[Text]"
+ [ testForType (Proxy :: Proxy [Text]) ]
+ ]
+ where
+ testForType
+ :: forall a. (Arbitrary a, Show a, ToRadicle a, FromRadicle a, Eq a)
+ => Proxy a -> TestTree
+ testForType _ =
+ testProperty "fromRadicle . toRadicle == id" $ \(v :: a ) -> do
+ let expected = Right v
+ got = fromRadicle (toRadicle v)
+ info = "Expected\n\t" <> show expected
+ <> "\nGot\n\t" <> show got
+ counterexample info $ got == expected
+
-- Tests all radicle files 'repl' dir. These should use the 'should-be'
-- function to ensure they are in the proper format.
test_source_files :: IO TestTree
@@ -630,9 +657,9 @@ atom = Atom . toIdent
-- -- | Like 'parse', but uses "(test)" as the source name and the default set of
-- -- primops.
parseTest :: MonadError Text m => Text -> m Value
-parseTest t = parse "(test)" t (Map.keys $ bindingsPrimops e)
+parseTest t = parse "(test)" t (Map.keys . getPrimops $ bindingsPrimops e)
where
- e :: Bindings (Lang Identity)
+ e :: Bindings (Primops (Lang Identity))
e = pureEnv
prettyEither :: Either (LangError Value) Value -> T.Text