A peer-to-peer stack for code collaboration
Redefinable eval
Julian K. Arnic39b886fe1f6
diff --git a/package.yaml b/package.yamlindex dd8dc9d..88e9c7c 100644--- a/package.yaml+++ b/package.yaml@@ -19,6 +19,9 @@ dependencies:- syb- text+data-files:+- repl/config.rad+library:source-dirs: srcghc-options: -Walldiff --git a/src/Radicle.hs b/src/Radicle.hsindex 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.hsindex 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 Mapimport Data.Semigroup (Semigroup, (<>))import Data.Text (Text)-import qualified Data.Text as Timport 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 maddBinding i v b = b@@ -135,12 +137,9 @@ defineAtom i v = modify $ addBinding i v-- not shadowable via 'define'.purePrimops :: Monad m => Primops mpurePrimops = 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 vxs -> throwError $ WrongNumberOfArgs "quote" 1 (length xs))@@ -148,7 +147,7 @@ purePrimops = Map.fromList $ first identFromString <$>[Atom name, val] -> doval' <- eval valdefineAtom 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 txs -> 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 -> dolet 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 evaleval :: 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 ofAtom i -> lookupAtom iRef i -> pure $ Ref i- List vals -> List <$> traverse eval vals+ List vals -> List <$> traverse coreEval valsString s -> pure $ String sBoolean b -> pure $ Boolean bApply mfn vs -> do- mfn' <- eval mfn+ mfn' <- coreEval mfncase mfn' ofPrimop i -> dofn <- lookupPrimop i@@ -197,16 +218,16 @@ eval val = case val ofLambda _ _ Nothing -> throwError $ Impossible"lambda should already have an env"Lambda bnds body (Just closure) -> do- vs' <- traverse eval vs+ vs' <- traverse coreEval vslet 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 ie@(Lambda _ _ (Just _)) -> pure eLambda args body Nothing -> gets $ Lambda args body . Just . bindingsEnvSortedMap mp -> do- let evalSnd (a,b) = (a ,) <$> eval b+ let evalSnd (a,b) = (a ,) <$> coreEval bSortedMap . Map.fromList <$> traverse evalSnd (Map.toList mp)diff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hsindex 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 ValueinterpretMany sourceName src = do@@ -187,7 +187,7 @@ parseTest :: MonadError String m => Text -> m ValueparseTest t = parse "(test)" t (Map.keys $ bindingsPrimops e)wheree :: Bindings (Lang Identity)- e = pureEmptyEnv+ e = pureEnv-- ** Valid identifiersdiff --git a/src/Radicle/Internal/Subscriber.hs b/src/Radicle/Internal/Subscriber.hsindex 4f7fcba..b2a6dd5 100644--- a/src/Radicle/Internal/Subscriber.hs+++ b/src/Radicle/Internal/Subscriber.hs@@ -15,7 +15,8 @@ import Radicle.Internal.Parseimport Radicle.Internal.Prettyimport 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 mreplBindings = e { bindingsPrimops = bindingsPrimops e <> replPrimops }wheree :: Bindings m- e = pureEmptyEnv+ e = pureEnvreplPrimops :: forall m. ReplM m => Primops mreplPrimops = 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 vcase (x', v') of(SortedMap m, fn) -> case Map.lookup (identFromString "getter") m ofNothing -> throwError@@ -68,8 +69,8 @@ replPrimops = Map.fromList $ first identFromString <$>Just g -> gowherego = 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.hsindex 29f5853..44dae5c 100644--- a/src/Radicle/Internal/Subscriber/Capabilities.hs+++ b/src/Radicle/Internal/Subscriber/Capabilities.hs@@ -15,7 +15,7 @@ import Radicle.Internal.Coreclass (Monad m) => Stdin m wheregetLineS :: m Text-instance Stdin m => Stdin (Lang m) where+instance {-# OVERLAPPABLE #-} Stdin m => Stdin (Lang m) wheregetLineS = lift getLineSinstance (MonadException m, Monad m) => Stdin (InputT m) wheregetLineS = getInputLine "rad> " >>= \x -> case x of@@ -24,7 +24,7 @@ instance (MonadException m, Monad m) => Stdin (InputT m) whereclass (Monad m) => Stdout m whereputStrS :: Text -> m ()-instance Stdout m => Stdout (Lang m) where+instance {-# OVERLAPPABLE #-} Stdout m => Stdout (Lang m) whereputStrS = lift . putStrSinstance (MonadException m, Monad m) => Stdout (InputT m) whereputStrS = outputStrLn . T.unpackdiff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hsindex 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 whereimport Control.Monad.State+import Control.Monad.Exceptimport 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 pureEnvrunTestWith' :: [Text] -> TestLang a -> (Either LangError a, [Text])-runTestWith' = runTestWith pureEmptyEnv+runTestWith' = runTestWith pureEnv-instance Stdin (State WorldState) where+instance {-# OVERLAPPING #-} Stdin TestLang wheregetLineS = 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.hsindex 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_radicletest_eval :: [TestTree]test_eval =@@ -87,9 +87,16 @@ test_eval =, testCase "'define' fails when first arg is not an atom" $ dolet 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)" srcfailsWith src err = run src @?= Left errsucceedsWith 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 ytest_pretty :: [TestTree]@@ -172,13 +179,57 @@ test_repl_primops =, testProperty "deref-all . ref == id" $ \(i', v) -> dolet 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]whererun 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