Skip to content

A peer-to-peer stack for code collaboration

Redefinable eval

Julian K. Arnic39b886fe1f6
diff --git a/package.yaml b/package.yaml
index dd8dc9d..88e9c7c 100644
--- a/package.yaml
+++ b/package.yaml
@@ -19,6 +19,9 @@ dependencies:
- syb
- text
+data-files:
+- repl/config.rad
+
library:
source-dirs: src
ghc-options: -Wall
diff --git a/src/Radicle.hs b/src/Radicle.hs
index a47ea14..405c2a4 100644
--- a/src/Radicle.hs
+++ b/src/Radicle.hs
@@ -21,7 +21,7 @@ module Radicle
, fromIdent
, mkIdent
, Env(..)
- , pureEmptyEnv
+ , pureEnv
, Lang
, runLang
, Bindings(..)
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index d949030..d10a00e 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -13,12 +13,12 @@ import Data.Map (Map)
import qualified Data.Map as Map
import Data.Semigroup (Semigroup, (<>))
import Data.Text (Text)
-import qualified Data.Text as T
import Data.Void (Void)
import GHC.Exts (IsList(..), fromString)
import GHC.Generics (Generic)
import qualified Text.Megaparsec.Error as Par
+
-- * Value
-- | An error throw during parsing or evaluating expressions in the language.
@@ -108,9 +108,11 @@ withEnv modifier action = do
-- * Functions
--- | A Bindings with an empty Env and only pure primops.
-pureEmptyEnv :: Monad m => Bindings m
-pureEmptyEnv = Bindings mempty purePrimops
+-- | A Bindings with an Env containing only 'eval' and only pure primops.
+pureEnv :: Monad m => Bindings m
+pureEnv = Bindings e purePrimops
+ where
+ e = fromList [(identFromString "eval", Primop $ identFromString "core-eval")]
addBinding :: Monad m => Ident -> Value -> Bindings m -> Bindings m
addBinding i v b = b
@@ -135,12 +137,9 @@ defineAtom i v = modify $ addBinding i v
-- not shadowable via 'define'.
purePrimops :: Monad m => Primops m
purePrimops = Map.fromList $ first identFromString <$>
- [ ("eval", \args -> case args of
- [List (v:vs)] -> eval (Apply v vs)
- [Apply fn v ] -> eval =<< Apply <$> eval fn <*> traverse eval v
- [x] -> eval x
- x -> throwError $
- OtherError . T.pack $ "'eval' requires list as argument: " <> show x)
+ [ ("core-eval", \args -> case args of
+ [x] -> coreEval x
+ xs -> throwError $ WrongNumberOfArgs "core-eval" 1 (length xs))
, ("quote", \args -> case args of
[v] -> pure v
xs -> throwError $ WrongNumberOfArgs "quote" 1 (length xs))
@@ -148,7 +147,7 @@ purePrimops = Map.fromList $ first identFromString <$>
[Atom name, val] -> do
val' <- eval val
defineAtom name val'
- pure $ List [Atom $ identFromString "set!", Atom name, val']
+ pure nil
[_, _] -> throwError $ OtherError "define expects atom for first arg"
xs -> throwError $ WrongNumberOfArgs "define" 2 (length xs))
, ("string?", \args -> case args of
@@ -166,6 +165,10 @@ purePrimops = Map.fromList $ first identFromString <$>
-- in Lisps a lot of things that one might object to are True...
if b == Boolean False then eval f else eval t
xs -> throwError $ WrongNumberOfArgs "if" 3 (length xs))
+ , ("ref", \args -> case args of
+ [Atom var] -> pure $ Ref var
+ [_] -> throwError $ TypeError "get: expecting atom"
+ xs -> throwError $ WrongNumberOfArgs "get" 1 (length xs))
, ("deref-all", \args -> do
let derefOne :: forall m b. (Monad m, Data b) => (b -> Lang m b)
derefOne x = case (cast x, eqT :: Maybe (b :~: Value)) of
@@ -178,16 +181,34 @@ purePrimops = Map.fromList $ first identFromString <$>
-- * Eval
--- | Evaluate a Value.
+-- Let val be finale of eval
eval :: Monad m => Value -> Lang m Value
-eval val = case val of
+eval val = do
+ e <- lookupAtom (identFromString "eval")
+ case e of
+ Primop i -> do
+ fn <- lookupPrimop i
+ -- Primops get to decide whether and how their args are
+ -- evaluated.
+ fn [val]
+ Lambda _ _ Nothing -> throwError $ Impossible
+ "lambda should already have an env"
+ Lambda [bnd] body (Just closure) -> do
+ let mappings = fromList [(bnd, val)]
+ modEnv = mappings <> closure
+ withEnv (\e' -> e' { bindingsEnv = modEnv}) (eval body)
+ _ -> throwError $ TypeError "Trying to apply a non-function"
+
+-- | The built-in, original, eval.
+coreEval :: Monad m => Value -> Lang m Value
+coreEval val = case val of
Atom i -> lookupAtom i
Ref i -> pure $ Ref i
- List vals -> List <$> traverse eval vals
+ List vals -> List <$> traverse coreEval vals
String s -> pure $ String s
Boolean b -> pure $ Boolean b
Apply mfn vs -> do
- mfn' <- eval mfn
+ mfn' <- coreEval mfn
case mfn' of
Primop i -> do
fn <- lookupPrimop i
@@ -197,16 +218,16 @@ eval val = case val of
Lambda _ _ Nothing -> throwError $ Impossible
"lambda should already have an env"
Lambda bnds body (Just closure) -> do
- vs' <- traverse eval vs
+ vs' <- traverse coreEval vs
let mappings = fromList (zip bnds vs')
modEnv = mappings <> closure
- withEnv (\e -> e { bindingsEnv = modEnv }) (eval body)
+ withEnv (\e -> e { bindingsEnv = modEnv }) (coreEval body)
_ -> throwError $ TypeError "Trying to apply a non-function"
Primop i -> pure $ Primop i
e@(Lambda _ _ (Just _)) -> pure e
Lambda args body Nothing -> gets $ Lambda args body . Just . bindingsEnv
SortedMap mp -> do
- let evalSnd (a,b) = (a ,) <$> eval b
+ let evalSnd (a,b) = (a ,) <$> coreEval b
SortedMap . Map.fromList <$> traverse evalSnd (Map.toList mp)
diff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hs
index 3aa3616..b40e205 100644
--- a/src/Radicle/Internal/Parse.hs
+++ b/src/Radicle/Internal/Parse.hs
@@ -118,10 +118,10 @@ valueP = do
--
-- Examples:
--
--- >>> interpret "test" "((lambda (x) x) #t)" pureEmptyEnv
+-- >>> interpret "test" "((lambda (x) x) #t)" pureEnv
-- Right (Boolean True)
--
--- >>> interpret "test" "(#t #f)" pureEmptyEnv
+-- >>> interpret "test" "(#t #f)" pureEnv
-- Left (TypeError "Trying to apply a non-function")
interpret :: Monad m => String -> Text -> Bindings m -> m (Either LangError Value)
interpret sourceName expr bnds = do
@@ -135,7 +135,7 @@ interpret sourceName expr bnds = do
--
-- Examples:
--
--- >>> runLang pureEmptyEnv $ interpretMany "test" "(define id (lambda (x) x))\n(id #t)"
+-- >>> runLang pureEnv $ interpretMany "test" "(define id (lambda (x) x))\n(id #t)"
-- Right (Boolean True)
interpretMany :: Monad m => String -> Text -> Lang m Value
interpretMany sourceName src = do
@@ -187,7 +187,7 @@ parseTest :: MonadError String m => Text -> m Value
parseTest t = parse "(test)" t (Map.keys $ bindingsPrimops e)
where
e :: Bindings (Lang Identity)
- e = pureEmptyEnv
+ e = pureEnv
-- ** Valid identifiers
diff --git a/src/Radicle/Internal/Subscriber.hs b/src/Radicle/Internal/Subscriber.hs
index 4f7fcba..b2a6dd5 100644
--- a/src/Radicle/Internal/Subscriber.hs
+++ b/src/Radicle/Internal/Subscriber.hs
@@ -15,7 +15,8 @@ import Radicle.Internal.Parse
import Radicle.Internal.Pretty
import Radicle.Internal.Subscriber.Capabilities
-type ReplM m = (Stdout m, Stdin m, GetEnv (Lang m), SetEnv (Lang m))
+type ReplM m = ( Monad m, Stdout (Lang m), Stdin (Lang m), GetEnv (Lang m)
+ , SetEnv (Lang m))
repl :: Text -> IO ()
repl preCode = do
@@ -28,7 +29,7 @@ replBindings :: forall m. ReplM m => Bindings m
replBindings = e { bindingsPrimops = bindingsPrimops e <> replPrimops }
where
e :: Bindings m
- e = pureEmptyEnv
+ e = pureEnv
replPrimops :: forall m. ReplM m => Primops m
replPrimops = Map.fromList $ first identFromString <$>
@@ -59,8 +60,8 @@ replPrimops = Map.fromList $ first identFromString <$>
, ("subscribe-to!", \args -> case args of
[x, v] -> do
- x' <- eval x
- v' <- eval v
+ x' <- coreEval x
+ v' <- coreEval v
case (x', v') of
(SortedMap m, fn) -> case Map.lookup (identFromString "getter") m of
Nothing -> throwError
@@ -68,8 +69,8 @@ replPrimops = Map.fromList $ first identFromString <$>
Just g -> go
where
go = do
- newBlock <- eval g
- _ <- eval (fn $$ [newBlock])
+ newBlock <- eval =<< coreEval g
+ _ <- coreEval (fn $$ [newBlock])
go
_ -> throwError $ TypeError "subscribe-to!: Expected sorted-map"
xs -> throwError $ WrongNumberOfArgs "subscribe-to!" 2 (length xs))
diff --git a/src/Radicle/Internal/Subscriber/Capabilities.hs b/src/Radicle/Internal/Subscriber/Capabilities.hs
index 29f5853..44dae5c 100644
--- a/src/Radicle/Internal/Subscriber/Capabilities.hs
+++ b/src/Radicle/Internal/Subscriber/Capabilities.hs
@@ -15,7 +15,7 @@ import Radicle.Internal.Core
class (Monad m) => Stdin m where
getLineS :: m Text
-instance Stdin m => Stdin (Lang m) where
+instance {-# OVERLAPPABLE #-} Stdin m => Stdin (Lang m) where
getLineS = lift getLineS
instance (MonadException m, Monad m) => Stdin (InputT m) where
getLineS = getInputLine "rad> " >>= \x -> case x of
@@ -24,7 +24,7 @@ instance (MonadException m, Monad m) => Stdin (InputT m) where
class (Monad m) => Stdout m where
putStrS :: Text -> m ()
-instance Stdout m => Stdout (Lang m) where
+instance {-# OVERLAPPABLE #-} Stdout m => Stdout (Lang m) where
putStrS = lift . putStrS
instance (MonadException m, Monad m) => Stdout (InputT m) where
putStrS = outputStrLn . T.unpack
diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hs
index 19d587c..bb18c1b 100644
--- a/test/spec/Radicle/Internal/TestCapabilities.hs
+++ b/test/spec/Radicle/Internal/TestCapabilities.hs
@@ -1,9 +1,9 @@
-{-# LANGUAGE TemplateHaskell #-}
-- | This module defines instances for the classes in
-- Radicle.Internal.Subscriber.Capabilities that may be used for testing.
module Radicle.Internal.TestCapabilities where
import Control.Monad.State
+import Control.Monad.Except
import Data.Text (Text)
import Radicle
@@ -33,16 +33,18 @@ runTestWith bindings inputs action =
in case runState (runLang bindings action) ws of
(val, st) -> (val, reverse $ worldStateStdout st)
--- | Like `runTestWith`, but uses the pureEmptyEnv
+-- | Like `runTestWith`, but uses the pureEnv
runTestWith' :: [Text] -> TestLang a -> (Either LangError a, [Text])
-runTestWith' = runTestWith pureEmptyEnv
+runTestWith' = runTestWith pureEnv
-instance Stdin (State WorldState) where
+instance {-# OVERLAPPING #-} Stdin TestLang where
getLineS = do
- ws <- get
- put $ ws { worldStateStdin = tail $ worldStateStdin ws }
- pure $ head $ worldStateStdin ws
-
-instance Stdout (State WorldState) where
- putStrS t = modify (\ws -> ws { worldStateStdout = t:worldStateStdout ws })
+ ws <- lift get
+ case worldStateStdin ws of
+ [] -> throwError $ OtherError "test: out of stdin"
+ h:hs -> lift (put $ ws { worldStateStdin = hs }) >> pure h
+
+instance {-# OVERLAPPING #-} Stdout TestLang where
+ putStrS t = lift $
+ modify (\ws -> ws { worldStateStdout = t:worldStateStdout ws })
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index a4d8af9..04623f4 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -16,8 +16,8 @@ import Test.Tasty.QuickCheck (counterexample, testProperty)
import Radicle.Internal.Arbitrary ()
import Radicle.Internal.Core (identFromString)
import Radicle.Internal.TestCapabilities
-
import Radicle
+import Paths_radicle
test_eval :: [TestTree]
test_eval =
@@ -87,9 +87,16 @@ test_eval =
, testCase "'define' fails when first arg is not an atom" $ do
let prog = [s|(define "hi" "there")|]
prog `failsWith` OtherError "define expects atom for first arg"
+
+ , testCase "evaluation can be redefined" $ do
+ let prog = [s|
+ (define eval (lambda (x) #f))
+ #t
+ |]
+ prog `succeedsWith` Boolean False
]
where
- run src = runIdentity $ runLang pureEmptyEnv
+ run src = runIdentity $ runLang pureEnv
$ interpretMany "(test)" src
failsWith src err = run src @?= Left err
succeedsWith src val = run src @?= Right val
@@ -105,7 +112,7 @@ test_parser =
, testCase "parses primops" $ do
"boolean?" ==> Primop (i "boolean?")
- "eval" ==> Primop (i "eval")
+ "core-eval" ==> Primop (i "core-eval")
, testCase "parses identifiers" $ do
"++" ==> Atom (i "++")
@@ -127,7 +134,7 @@ test_binding =
[s|(((lambda (x) (lambda (x) x)) "inner") "outer")|] ==> String "outer"
]
where
- x ==> y = runIdentity (interpret "test" x pureEmptyEnv) @?= Right y
+ x ==> y = runIdentity (interpret "test" x pureEnv) @?= Right y
test_pretty :: [TestTree]
@@ -172,13 +179,57 @@ test_repl_primops =
, testProperty "deref-all . ref == id" $ \(i', v) -> do
let derefed = Primop (i "deref-all") $$ [Ref i']
atom = Atom i'
- run' p = runTestWith (addBinding i' v pureEmptyEnv) [] (eval p)
+ run' p = runTestWith (addBinding i' v pureEnv) [] (eval p)
run' derefed == run' atom
]
where
run inp prog = fst $ runTestWith replBindings inp
$ interpretMany "(test)" prog
+test_repl :: [TestTree]
+test_repl =
+ [ testCase "evaluates correctly" $ do
+ let input = [ "((lambda (x) x) #t)" ]
+ output = [ "'(#t)" ]
+ (_, result) <- runInRepl input
+ result @?= output
+
+ , testCase "handles env modifications" $ do
+ let input = [ "(define id (lambda (x) x))"
+ , "(id #t)"
+ ]
+ output = [ "'('())"
+ , "'(#t)"
+ ]
+ (_, result) <- runInRepl input
+ result @?= output
+
+ , testCase "handles 'eval' redefinition" $ do
+ let input = [ "(define eval (lambda (x) #t))"
+ , "#f"
+ ]
+ output = [ "'('())"
+ , "#t"
+ ]
+ (_, result) <- runInRepl input
+ result @?= output
+
+ , testCase "(define eval (quote core-eval)) doesn't change things" $ do
+ let input = [ "(define eval (quote core-eval))"
+ , "(define id (lambda (x) x))"
+ , "(id #t)"
+ ]
+ output = [ "'('())"
+ , "'('())"
+ , "'(#t)"
+ ]
+ (_, result) <- runInRepl input
+ result @?= output
+ ]
+ where
+ getCfg = getDataFileName "repl/config.rad" >>= fmap T.pack . readFile
+ runInRepl inp = runTestWith replBindings inp
+ . interpretMany "(test)" <$> getCfg
-- * Utils