Skip to content

A peer-to-peer stack for code collaboration

Machine environments and states now have their own value types. (#352)

James Haydon1659c503278a
diff --git a/bin/rad-issues b/bin/rad-issues
index 5400dce..54c04f9 100755
--- a/bin/rad-issues
+++ b/bin/rad-issues
@@ -6,9 +6,9 @@
(import prelude/validation :as 'validation)
-(def base-name "http://machines.radicle.xyz/chains/")
+(def base-name "http://staging.machines.radicle.xyz/chains/")
-(def name-base "http://machines.radicle.xyz/chains/names")
+(def name-base "http://staging.machines.radicle.xyz/chains/names")
(def help
(string-append
diff --git a/docs/source/reference.rst b/docs/source/reference.rst
index 5bd034c..5d2574d 100644
--- a/docs/source/reference.rst
+++ b/docs/source/reference.rst
@@ -369,27 +369,42 @@ from ``m``. ``(import m '[f g] :as 'foo')`` will import ``f`` and ``g``
from ``m`` as ``foo/f`` and ``foo/g``. To import definitions with no
qualification at all, use ``(import m :unqualified)``.
-``get-current-env``
-~~~~~~~~~~~~~~~~~~~
-
-Returns the current radicle state.
-
-``pure-env``
-~~~~~~~~~~~~
+``pure-state``
+~~~~~~~~~~~~~~
Returns a pure initial radicle state. This is the state of a radicle
chain before it has processed any inputs.
-``set-current-env``
-~~~~~~~~~~~~~~~~~~~
+``get-current-state``
+~~~~~~~~~~~~~~~~~~~~~
+
+Returns the current radicle state.
+
+``set-current-state``
+~~~~~~~~~~~~~~~~~~~~~
Replaces the radicle state with the one provided.
-``set-env!``
-~~~~~~~~~~~~
+``get-binding``
+~~~~~~~~~~~~~~~
+
+Lookup a binding in a radicle env.
+
+``set-binding``
+~~~~~~~~~~~~~~~
+
+Add a binding to a radicle env.
+
+``set-env``
+~~~~~~~~~~~
-Given an atom ``x`` and a value ``v``, sets the value associated to
-``x`` in the current environment to be ``v``. Doesn't evaluate ``v``.
+Sets the environment of a radicle state to a new value. Returns the
+updated state.
+
+``state->env``
+~~~~~~~~~~~~~~
+
+Extract the environment from a radicle state.
``timestamp?``
~~~~~~~~~~~~~~
@@ -661,6 +676,11 @@ Empty-sequence pattern. Matches ``[]`` and ``(list)``
Pattern which matches ``[:just x]``.
+``(/member vs)``
+~~~~~~~~~~~~~~~~
+
+Matches values that are members of a structure.
+
``prelude/strings``
-------------------
diff --git a/exe/ReferenceDoc.hs b/exe/ReferenceDoc.hs
index f9a27e8..8ef3197 100644
--- a/exe/ReferenceDoc.hs
+++ b/exe/ReferenceDoc.hs
@@ -37,7 +37,7 @@ main = do
( "(do"
<> "(file-module! \"rad/prelude/test-eval.rad\") (import prelude/test-eval '[eval tests] :unqualified)"
<> foldMap (\m -> "(file-module! \"rad/" <> m <> ".rad\")") (modules content)
- <> "(get-current-env))")
+ <> "(get-current-state))")
(replBindings [])
let res = res_ `lPanic` "Error running the prelude."
let env = bindingsEnv $ bindingsFromRadicle res `lPanic` "Couldn't convert radicle state."
@@ -77,8 +77,9 @@ moduleDoc (Env env) name =
getModuleEnv :: Map Value Value -> Env Value
getModuleEnv module' =
- envFromRad (lkp [kword|env|] module')
- `lPanic` ("Cannot parse environment for module " <> name)
+ case lkp [kword|env|] module' of
+ VEnv e -> e
+ _ -> panic "Module's `:env` was not an env."
lkp :: Value -> Map Value Value -> Value
lkp x m = case Map.lookup x m of
diff --git a/rad/monadic/issue-remote.rad b/rad/monadic/issue-remote.rad
index be2dcec..60db186 100644
--- a/rad/monadic/issue-remote.rad
+++ b/rad/monadic/issue-remote.rad
@@ -119,7 +119,8 @@
:body (validator/text 4000)
:labels (validator/every (validator/text 80))
:state (validator/member [:open :closed])
- :comments (validator/every validator/full-comment)})
+ :comments (validator/every (validator/and [validator/full-comment
+ validator/time-created]))})
(def validator/full-issue (validator/keys issue-keys))
@@ -128,7 +129,8 @@
(def validator/issue-input
"An issue should have all the required fields, be a signed input, etc."
(validator/and
- [validator/input
+ [;; NOTE that we don't check `validator/input` at this point, because some of
+ ;; the data is fixed before validation.
validator/time-created
validator/full-issue]))
@@ -181,16 +183,29 @@
(fn [e]
(delete-many [:chain-id :signature :nonce :issue-number] e)))
+(def fix-modified-at
+ "Some inputs come in with a missing `:modified-at` key. If this is the case, we
+ add it as equal to the `:created-at` key."
+ (fn [x]
+ (if (member? :modified-at x)
+ x
+ (insert :modified-at (lookup :created-at x) x))))
+
(def create-issue
"Create an issue from a dict, checking that it is valid and storing it in `issues`."
(fn [i]
- (validator/issue-input i)
+ (validator/input i)
+ (def fixed
+ (insert :comments
+ (map fix-modified-at (lookup :comments i))
+ (fix-modified-at i)))
+ (validator/issue-input fixed)
(def n (issue-counter :next))
(def i_
(strip-input
- (<> i
+ (<> fixed
{:number n
- :comments (map strip-input (lookup :comments i))})))
+ :comments (map strip-input (lookup :comments fixed))})))
(set-issues (@ n) i_)
(mark-used-nonce (lookup :nonce i))))
diff --git a/rad/monadic/issues-upgrade.rad b/rad/monadic/issues-upgrade.rad
new file mode 100644
index 0000000..c89fad3
--- /dev/null
+++ b/rad/monadic/issues-upgrade.rad
@@ -0,0 +1,24 @@
+(load! "rad/monadic/issues.rad")
+
+(import prelude/chain :unqualified)
+
+;; This is a script that migrates the issues chain. It is used when there is a
+;; breaking change.
+;; Example:
+;; (migrate-issues! "machines.radicle.xyz/chains/radicle-issues"
+;; "machines.radicle.xyz/chains/new-radicle-issues")
+
+(def input-pat
+ (list (/member ['create-issue 'edit-issue 'add-comment 'edit-comment]) _))
+
+(def input?
+ (fn [i]
+ (match i
+ input-pat #t
+ _ #f)))
+
+(def migrate-issues!
+ (fn [old new]
+ (def is (nth 1 (receive! old :nothing)))
+ (create-issues-chain! new)
+ (send! new (filter input? is))))
diff --git a/rad/monadic/names-upgrade.rad b/rad/monadic/names-upgrade.rad
new file mode 100644
index 0000000..22c95f8
--- /dev/null
+++ b/rad/monadic/names-upgrade.rad
@@ -0,0 +1,25 @@
+(load! "rad/monadic/names.rad")
+
+(import prelude/chain :unqualified)
+
+;; This is a script that migrates the names chain. It is used when there is a
+;; breaking change.
+
+;; Example:
+;; (migrate-names! "machines.radicle.xyz/chains/names"
+;; "staging.machines.radicle.xyz/chains/names")
+
+(def input-pat
+ (list (/member ['add-name]) _ _))
+
+(def input?
+ (fn [i]
+ (match i
+ input-pat #t
+ _ #f)))
+
+(def migrate-names!
+ (fn [old new]
+ (def is (nth 1 (receive! old :nothing)))
+ (create-name-chain! new)
+ (send! new (filter input? is))))
diff --git a/rad/prelude/chain.rad b/rad/prelude/chain.rad
index 9e8c4dd..212ae94 100644
--- a/rad/prelude/chain.rad
+++ b/rad/prelude/chain.rad
@@ -6,7 +6,7 @@
(import prelude/io '[read-file-values!] :as 'io)
(import prelude/ref '[modify-ref] :unqualified)
-(import prelude/lens '[.. ... view over @ @def] :unqualified)
+(import prelude/lens '[make-lens .. ... view set over @ @def] :unqualified)
(import prelude/basic :unqualified)
(import prelude/io :unqualified)
(import prelude/patterns :unqualified)
@@ -34,15 +34,25 @@
(fn [machine-id index]
(machine/eval-server/get-log! machine-id index)))
+(def env-var
+ "A lens for variables in envs."
+ (fn [i]
+ (make-lens (fn [e] (get-binding i e))
+ (fn [v e] (set-binding i v e)))))
+
+(def @env
+ "A lens for env part of a machine state."
+ (make-lens state->env set-env))
+
(def @var
- "A lens for variables in states of chains."
- (fn [ident]
- (... [(@ :env) (@ ident) (@ :val)])))
+ "A lens for variables in machine states."
+ (fn [i]
+ (.. @env (env-var i))))
(def new-chain
"Return an empty chain dictionary with the given url."
(fn [url]
- {:state (pure-env)
+ {:state (pure-state)
:inputs []
:url url
:index :nothing}))
@@ -178,16 +188,11 @@
(fn [url env]
(def chain (load-chain! url))
(def chain-state (lookup :state chain))
- (def mod-state1
- (over (@ :env) (fn [x] (insert '_inputs {:val []} x)) chain-state))
- (def mod-state2
- (over (@ :env)
- (fn [x] (insert '_cur-chain {:val (lookup :url chain)} x))
- mod-state1))
- (def mod-state3
- (over (@var 'eval)
- (fn [x] (add-quit env x))
- mod-state2))
+ (def mod-state1 (set (@var '_inputs) [] chain-state))
+ (def mod-state2 (set (@var '_cur-chain) (lookup :url chain) mod-state1))
+ (def mod-state3 (over (@var 'eval)
+ (fn [x] (add-quit env x))
+ mod-state2))
(list :ok mod-state3)))
(def eval__ "The eval in place when `chain.rad` is loaded." eval)
diff --git a/rad/prelude/patterns.rad b/rad/prelude/patterns.rad
index 462f18a..4a5985b 100644
--- a/rad/prelude/patterns.rad
+++ b/rad/prelude/patterns.rad
@@ -1,6 +1,6 @@
{:module 'prelude/patterns
:doc "Pattern matching is first-class in radicle so new patterns can easily be defined. These are the most essential."
- :exports '[match-pat _ /? /as /cons /nil /just]}
+ :exports '[match-pat _ /? /as /cons /nil /just /member]}
(import prelude/basic :unqualified)
@@ -82,7 +82,7 @@
(if (eq? pat v) [:just {}] :nothing)
(dict? pat)
((/dict pat) v)
- (vector? pat)
+ (or (vector? pat) (list? pat))
((/vec pat) v)
:else
(pat v))))
@@ -213,3 +213,17 @@
_ :no) ==> :no
]
)
+
+(def /member
+ "Matches values that are members of a structure."
+ (fn [vs]
+ (fn [v]
+ (if (member? v vs)
+ [:just {}]
+ :nothing))))
+
+(:test "/member"
+ [(match [1 4]
+ [1 (/member [1 3 5])] :no
+ [1 (/member [2 4 8])] :yes
+ _ :no) ==> :yes])
diff --git a/rad/prelude/test-eval.rad b/rad/prelude/test-eval.rad
index 0fd94ce..5c57fc4 100644
--- a/rad/prelude/test-eval.rad
+++ b/rad/prelude/test-eval.rad
@@ -13,21 +13,21 @@
;; Annoyingly verbose since we have neither the prelude nor pattern-matching.
(def eval
"Evaluation function that adds :test macro to register tests."
- (fn [expr env]
+ (fn [expr state]
(if (list? expr)
(if (eq? (first expr) :test)
(do
- (def bindings (lookup :env env))
- (def test-def {:doc-test (drop 2 expr) :name (nth 1 expr) :env env})
- (def next-tests {:val test-def})
- (def bindings_ (insert 'next-tests__ next-tests bindings))
- (def env (insert :env bindings_ env))
+ (def env (state->env state))
+ (def test-def {:doc-test (drop 2 expr) :name (nth 1 expr) :env state})
+ (def next-tests test-def)
+ (def env_ (set-binding 'next-tests__ next-tests env))
+ (def state (set-env env_ state))
(eval '(do
(write-ref tests (add-right next-tests__ (read-ref tests)))
:nil
- ) env))
- (eval expr env))
- (eval expr env))))
+ ) state))
+ (eval expr state))
+ (eval expr state))))
(:test "'test' works (including :setup)"
[:setup
diff --git a/reference-doc.yaml b/reference-doc.yaml
index 7670026..73494a4 100644
--- a/reference-doc.yaml
+++ b/reference-doc.yaml
@@ -82,11 +82,14 @@ primFns:
# Modules
- file-module!
- import
-# Environment
-- get-current-env
-- pure-env
-- set-current-env
-- set-env!
+# State and Environment
+- pure-state
+- get-current-state
+- set-current-state
+- get-binding
+- set-binding
+- set-env
+- state->env
# Time
- timestamp?
- unix-epoch
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index 3721875..2b11b87 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -5,12 +5,12 @@
module Radicle.Internal.Core where
import qualified Prelude
-import Protolude hiding (Constructor, Handle, TypeError, (<>))
+import Protolude hiding (Constructor, Handle, State, TypeError, (<>))
import Codec.Serialise (Serialise)
import Control.Monad.Except
(ExceptT(..), MonadError, runExceptT, throwError)
-import Control.Monad.State
+import Control.Monad.State hiding (State)
import Data.Aeson (FromJSON(..), ToJSON(..))
import qualified Data.Aeson as A
import Data.Copointed (Copointed(..))
@@ -25,7 +25,6 @@ import Generics.Eot
import qualified GHC.Exts as GhcExts
import qualified GHC.IO.Handle as Handle
import System.Process
- (CmdSpec(..), CreateProcess(..), ProcessHandle, StdStream(..))
import qualified Text.Megaparsec.Error as Par
import Radicle.Internal.Annotation (Annotated)
@@ -255,6 +254,8 @@ data ValueF r =
-- The first argument is the name for recursive calls to the
-- function in the body.
| LambdaRecF Ident [Ident] (NonEmpty r) (Env r)
+ | VEnvF (Env r)
+ | VStateF State
deriving (Eq, Ord, Read, Show, Generic, Functor)
instance Serialise r => Serialise (ValueF r)
@@ -275,6 +276,8 @@ valType = \case
ProcHandle _ -> TProcHandle
Lambda{} -> TFunction
LambdaRec{} -> TFunction
+ VEnv _ -> TEnv
+ VState _ -> TState
hashable :: (CPA t) => Annotated t ValueF -> Bool
hashable = \case
@@ -289,6 +292,8 @@ hashable = \case
ProcHandle _ -> False
Lambda{} -> False
LambdaRec{} -> False
+ VEnv _ -> False
+ VState _ -> False
List xs -> all hashable xs
Vec xs -> all hashable xs
Dict kvs -> getAll $ Map.foldMapWithKey (\k v -> All (hashable k && hashable v)) kvs
@@ -301,7 +306,7 @@ dict kvs =
else throwErrorHere NonHashableKey
{-# COMPLETE Atom, Keyword, String, Number, Boolean, List, Vec, PrimFn, Dict
- , Ref, Handle, ProcHandle, Lambda, LambdaRec #-}
+ , Ref, Handle, ProcHandle, Lambda, LambdaRec, VEnv, VState #-}
type ValueConC t = (HasCallStack, Ann.Annotation t, Copointed t)
@@ -375,6 +380,16 @@ pattern LambdaRec self vs exps env <- (Ann.match -> LambdaRecF self vs exps env)
where
LambdaRec self vs exps env = Ann.annotate $ LambdaRecF self vs exps env
+pattern VEnv :: ValueConC t => Env (Annotated t ValueF) -> Annotated t ValueF
+pattern VEnv e <- (Ann.match -> VEnvF e)
+ where
+ VEnv e = Ann.annotate $ VEnvF e
+
+pattern VState :: ValueConC t => State -> Annotated t ValueF
+pattern VState s <- (Ann.match -> VStateF s)
+ where
+ VState s = Ann.annotate $ VStateF s
+
type UntaggedValue = Annotated Identity ValueF
type Value = Annotated Ann.WithPos ValueF
@@ -450,6 +465,13 @@ instance GhcExts.IsList (PrimFns m) where
fromList xs = PrimFns . Map.fromList $ [ (i, Doc.Docd d x)| (i, d, x) <- xs ]
toList e = [ (i, d, x) | (i, Doc.Docd d x) <- GhcExts.toList . getPrimFns $ e]
+data State = State
+ { stateEnv :: Env Value
+ , stateRefs :: IntMap Value
+ } deriving (Eq, Ord, Read, Show, Generic)
+
+instance Serialise State
+
-- | Bindings, either from the env or from the primops.
data Bindings prims = Bindings
{ bindingsEnv :: Env Value
@@ -489,29 +511,12 @@ setBindings value = do
bindingsFromRadicle :: Value -> Either Text (Bindings (PrimFns m))
bindingsFromRadicle 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 <- envFromRad env'
- pure $ emptyBindings
- { bindingsEnv = env
- , bindingsRefs = refs
- , bindingsNextRef = length refs
- }
- _ -> throwError "Expecting dict"
- where
- makeRefs refs = case refs of
- List ls -> pure (IntMap.fromList $ zip [0..] ls)
- _ -> throwError $ "Expecting dict"
-
-envFromRad :: Value -> Either Text (Env Value)
-envFromRad env = case env of
- Dict d -> fmap (Env . Map.fromList)
- $ forM (Map.toList d) $ \(k, v) -> case k of
- Atom i -> (i, ) <$> fromRad v
- k' -> Left $ "Expecting atom keys. Got: " <> show k'
- _ -> Left "Expecting dict"
+ VState s -> pure $ emptyBindings
+ { bindingsEnv = stateEnv s
+ , bindingsRefs = stateRefs s
+ , bindingsNextRef = length (stateRefs s)
+ }
+ _ -> throwError "Expecting state"
-- | Serializes the environment and references into a Radicle value.
--
@@ -519,17 +524,7 @@ envFromRad env = case env of
-- * `gets bindingsToRadicle >>= setBindings == pure ()`
-- * `setBindings x >> gets bindingsToRadicle == setBindings x >> pure x`
bindingsToRadicle :: Bindings a -> Value
-bindingsToRadicle x =
- Dict $ Map.fromList
- [ (Keyword $ Ident "env", env)
- , (Keyword $ Ident "refs", refs)
- ]
- where
- env = envToRadicle (bindingsEnv x)
- refs = List $ IntMap.elems (bindingsRefs x)
-
-envToRadicle :: Env Value -> Value
-envToRadicle = Dict . Map.mapKeys Atom . Map.map toRad . fromEnv
+bindingsToRadicle x = VState State{ stateEnv = bindingsEnv x, stateRefs = bindingsRefs x }
-- | The environment in which expressions are evaluated.
newtype LangT r m a = LangT
@@ -646,7 +641,7 @@ instance (FromRad t a) => FromRad t [a] where
fromRad x = case x of
List xs -> traverse fromRad xs
Vec xs -> traverse fromRad (toList xs)
- _ -> Left "Expecting list"
+ _ -> Left "Expecting list or vector"
instance FromRad t (Doc.Docd (Annotated t ValueF)) where
fromRad (Dict d) = do
val <- kwLookup "val" d ?? "Expecting `:val` key"
diff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hs
index 9d530b2..3c1c678 100644
--- a/src/Radicle/Internal/Effects.hs
+++ b/src/Radicle/Internal/Effects.hs
@@ -121,16 +121,6 @@ replPrimFns sysArgs = fromList $ allDocs $
xs -> throwErrorHere $ WrongNumberOfArgs "apropos!" 0 (length xs)
)
- , ( "set-env!"
- , "Given an atom `x` and a value `v`, sets the value associated to `x` in\
- \ the current environment to be `v`. Doesn't evaluate `v`."
- , \case
- [Atom x, v] -> do
- defineAtom x Nothing v
- pure nil
- [v, _] -> throwErrorHere $ TypeError "set-env!" 0 TAtom v
- xs -> throwErrorHere $ WrongNumberOfArgs "set-env!" 2 (length xs))
-
, ( "get-line!"
, "Reads a single line of input and returns it as a string."
, \case
diff --git a/src/Radicle/Internal/Eval.hs b/src/Radicle/Internal/Eval.hs
index 06c0c55..e48335c 100644
--- a/src/Radicle/Internal/Eval.hs
+++ b/src/Radicle/Internal/Eval.hs
@@ -176,7 +176,7 @@ createModule = \case
let exportsSet = Set.fromList (exports m')
let undefinedExports = Set.difference exportsSet (Map.keysSet (fromEnv e))
env <- if null undefinedExports
- then pure . envToRadicle . Env $ Map.restrictKeys (fromEnv e) exportsSet
+ then pure . VEnv . Env $ Map.restrictKeys (fromEnv e) exportsSet
else throwErrorHere (ModuleError (UndefinedExports (name m') (Set.toList undefinedExports)))
let modu = Dict $ Map.fromList
[ (Keyword (Ident "module"), Atom (name m'))
diff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hs
index b4244af..5c32303 100644
--- a/src/Radicle/Internal/Pretty.hs
+++ b/src/Radicle/Internal/Pretty.hs
@@ -69,6 +69,8 @@ instance forall t. (Copointed t, Ann.Annotation t) => PrettyV (Ann.Annotated t V
| (k, val) <- Map.toList mp ]
Lambda ids vals _ -> prettyLambda ids vals
LambdaRec _ ids vals _ -> prettyLambda ids vals
+ VEnv _ -> angles "env"
+ VState _ -> angles "state"
where
-- We print string literals escaped just like Haskell does.
escapeStr = T.init . T.tail . show
diff --git a/src/Radicle/Internal/PrimFns.hs b/src/Radicle/Internal/PrimFns.hs
index ed34f99..e97e0f6 100644
--- a/src/Radicle/Internal/PrimFns.hs
+++ b/src/Radicle/Internal/PrimFns.hs
@@ -3,6 +3,7 @@ module Radicle.Internal.PrimFns where
import Protolude hiding (TypeError)
import qualified Data.Aeson as Aeson
+import Data.Copointed (Copointed(..))
import qualified Data.IntMap as IntMap
import Data.List (zip3)
import qualified Data.Map as Map
@@ -70,12 +71,41 @@ purePrimFns = fromList $ allDocs $
pure $ List [val, bindingsToRadicle st']
xs -> throwErrorHere $ WrongNumberOfArgs "base-eval" 2 (length xs)
)
- , ( "pure-env"
+ , ( "pure-state"
, "Returns a pure initial radicle state. This is the state of a radicle\
\ chain before it has processed any inputs."
, \case
[] -> pure $ bindingsToRadicle (pureEnv :: Bindings (PrimFns m))
- xs -> throwErrorHere $ WrongNumberOfArgs "pure-env" 0 (length xs)
+ xs -> throwErrorHere $ WrongNumberOfArgs "pure-state" 0 (length xs)
+ )
+ , ( "state->env"
+ , "Extract the environment from a radicle state."
+ , oneArg "state->env" $ \case
+ VState s -> pure (VEnv (stateEnv s))
+ v -> throwErrorHere $ TypeError "state->env" 0 TState v
+ )
+ , ( "set-binding"
+ , "Add a binding to a radicle env."
+ , threeArg "set-binding" $ \case
+ (Atom i, v, VEnv (Env m)) -> pure $ VEnv (Env (Map.insert i (Doc.Docd Nothing v) m))
+ (Atom _, _, e) -> throwErrorHere $ TypeError "set-binding" 2 TEnv e
+ (a, _, _) -> throwErrorHere $ TypeError "set-binding" 0 TAtom a
+ )
+ , ( "get-binding"
+ , "Lookup a binding in a radicle env."
+ , twoArg "get-binding" $ \case
+ (Atom i@(Ident t), VEnv (Env m)) -> case Map.lookup i m of
+ Just v -> pure (copoint v)
+ Nothing -> throwErrorHere $ OtherError $ "get-binding: " <> t <> " was not in the input env."
+ (Atom _, v) -> throwErrorHere $ TypeError "get-binding" 1 TEnv v
+ (v, _) -> throwErrorHere $ TypeError "get-binding" 0 TAtom v
+ )
+ , ( "set-env"
+ , "Sets the environment of a radicle state to a new value. Returns the updated state."
+ , twoArg "set-env" $ \case
+ (VEnv e, VState s) -> pure $ VState $ s { stateEnv = e }
+ (VEnv _, v) -> throwErrorHere $ TypeError "set-env" 1 TState v
+ (v, _) -> throwErrorHere $ TypeError "set-env" 0 TEnv v
)
, ( "apply"
, "Calls the first argument (a function) using as arguments the\
@@ -102,14 +132,14 @@ purePrimFns = fromList $ allDocs $
(String _, v) -> throwErrorHere $ TypeError "read-many" 1 TString v
(v, _) -> throwErrorHere $ TypeError "read-many" 0 TString v
)
- , ("get-current-env"
+ , ("get-current-state"
, "Returns the current radicle state."
, \case
[] -> gets bindingsToRadicle
- xs -> throwErrorHere $ WrongNumberOfArgs "get-current-env" 0 (length xs))
- , ( "set-current-env"
+ xs -> throwErrorHere $ WrongNumberOfArgs "get-current-state" 0 (length xs))
+ , ( "set-current-state"
, "Replaces the radicle state with the one provided."
- , oneArg "set-current-env" $ \x -> do
+ , oneArg "set-current-state" $ \x -> do
setBindings x
pure ok
)
@@ -650,9 +680,8 @@ purePrimFns = fromList $ allDocs $
import' (Dict d) v_ qual = do
v <- kwLookup "env" d ?? toLangError (OtherError "Modules should have an `:env` key")
n <- kwLookup "module" d ?? toLangError (OtherError "Modules should have an `:module` key")
- case n of
- Atom name -> do
- e <- hoistEither $ first (toLangError . OtherError) $ envFromRad v
+ case (n,v) of
+ (Atom name, VEnv e) -> do
let allMod = fromEnv e
toImport <- case v_ of
Just vs -> do
@@ -667,7 +696,7 @@ purePrimFns = fromList $ allDocs $
s <- get
put $ s { bindingsEnv = qualified <> bindingsEnv s }
pure ok
- _ -> throwErrorHere (OtherError "The `:module` key of a module should be an atom.")
+ _ -> throwErrorHere (OtherError "The `:module` key of a module should be an `:atom`, and the `:env` key should be an `:env`.")
import' _ _ _ = throwErrorHere (OtherError "Modules must be dicts")
data ImportQual = Unqualified | FullyQualified | Qualified Ident
diff --git a/src/Radicle/Internal/Type.hs b/src/Radicle/Internal/Type.hs
index 5e9aded..1f16bc9 100644
--- a/src/Radicle/Internal/Type.hs
+++ b/src/Radicle/Internal/Type.hs
@@ -19,6 +19,8 @@ data Type
| TRef
| THandle
| TProcHandle
+ | TEnv
+ | TState
deriving (Eq, Show, Read, Generic)
instance Serialise Type
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index c919ab9..fb5a106 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -153,7 +153,7 @@ test_eval =
f "(insert (ref 0) 1 {})"
f "{(ref 0) 1}"
"(lookup :k {'(fn [x] y) 1 :k :v})" `succeedsWith` Keyword [ident|v|]
- f "(eval {'(fn [y] y) :a-fun} (get-current-env))"
+ f "(eval {'(fn [y] y) :a-fun} (get-current-state))"
f "(dict (ref 0) 1)"
, testProperty "'string-append' concatenates string" $ \ss -> do
@@ -198,18 +198,18 @@ test_eval =
prog `succeedsWith` List [List [int 1, int 1]]
, testCase "'eval' evaluates the list" $ do
- let prog = [s|(first (eval (quote #t) (get-current-env)))|]
+ let prog = [s|(first (eval (quote #t) (get-current-state)))|]
prog `succeedsWith` Boolean True
, testCase "'eval' only evaluates the first quote" $ do
- let prog1 = [s|(first (eval (quote (quote (+ 3 2))) (get-current-env)))|]
+ let prog1 = [s|(first (eval (quote (quote (+ 3 2))) (get-current-state)))|]
prog2 = [s|(quote (+ 3 2))|]
res1 = runPureCode prog1
res2 = runPureCode prog2
res1 @?= res2
, testProperty "'eval' does not alter functions" $ \(_v :: Value) -> do
- let prog1 = [i| (first (eval (fn [] #{renderPrettyDef _v}) (get-current-env))) |]
+ let prog1 = [i| (first (eval (fn [] #{renderPrettyDef _v}) (get-current-state))) |]
prog2 = [i| (fn [] #{renderPrettyDef _v}) |]
res1 = runPureCode $ toS prog1
res2 = runPureCode $ toS prog2