Skip to content

A peer-to-peer stack for code collaboration

Issues guide

James Haydonf8b6b198679c
diff --git a/docs/source/guide/Issues.lrad b/docs/source/guide/Issues.lrad
new file mode 100644
index 0000000..eea3177
--- /dev/null
+++ b/docs/source/guide/Issues.lrad
@@ -0,0 +1,285 @@
+# Issues chain
+
+## Adding an removing issues
+
+In this example we will create a chain which stores some issues about a code
+repository. At the start it will only support adding and removing issues, but then
+we will add more features.
+
+This is a literate radicle file, which means you can run it like this: `stack
+exec doc -- docs/source/guide/Issues.lrad`.
+
+First we load the prelude:
+
+ (load! "rad/prelude.rad")
+
+We'll use a ref to store the issues, as a dictionary from issue IDs to issues.
+
+ (def issues (ref {}))
+
+To update the state of our issues we'll use `modify-ref`, a function which takes
+a ref and a function. It updates the value held in the ref using the function
+and then returns the _new_ value. We'll be modifying `issues` a lot, so let's
+create a function for that:
+
+ (def mod-issues
+ (fn [f] (modify-ref issues f)))
+
+Next we'll define a function for creating a new issue. An issue is a dict which
+looks like:
+
+ { :id "ab12-xy23"
+ :author "user-id-here"
+ :title "I want pattern matching"
+ :body "I can't continue using radicle without it."
+ }
+
+The `:id` should be a valid UUID that is supplied by whoever submits the issue;
+we just check that the ID isn't already used for another issue:
+
+ (def id-valid-and-free?
+ (fn [id]
+ (and (uuid? id)
+ (not (member? id (read-ref issues))))))
+
+To add an issue we just add it to the `issues` dict, using the `:id` as the key. Note that in the case of an error we use `print!` in this tutorial, but in a real chain one would `throw` to refuse the transaction.
+
+ (def new-issue
+ (fn [i]
+ (def id (lookup :id i))
+ (if (id-valid-and-free? id)
+ (mod-issues
+ (fn [is] (insert id i is)))
+ (print! "Issue ID was not free or was invalid."))))
+
+Closing an issue is also easy--we just delete that issue from the dict:
+
+ (def close-issue
+ (fn [id]
+ (mod-issues (fn [is] (delete id is)))))
+
+The behaviour we want from our chain is to accept some commands to perform
+issue-related tasks. We'll store these commands in a dict, keyed by the command
+symbol. We put the whole thing in a ref so that we can add more commands later,
+or even update existing commands.
+
+ (def commands
+ (ref
+ {'create new-issue
+ 'close close-issue}))
+
+Now we create a function for handling these commands. We assume that the input
+is a list with at least 2 elements, the first of which is a symbol describing
+the command. We look up the command handler in the `commands` ref and then run
+it on the arguments using `apply`, which calls a function on a list of
+arguments. Finally we print the issues so that we can see how the state evolves.
+
+ (def process-command
+ (fn [expr]
+ (def command (head expr))
+ (def args (tail expr))
+ (def do-this (lookup command (read-ref commands)))
+ (apply do-this args)
+ (print! (read-ref issues))
+ :ok))
+
+Now we update the eval. We will check for a special command `update` for
+updating the semantics of our chain (by executing arbitrary code), but otherwise
+we delegate to `process-command`. In general of course you wouldn't want to
+leave such an `update` command with no restrictions; we'll talk about that
+later.
+
+ (load! "rad/chain.rad")
+
+ (def eval
+ (updatable-eval
+ (fn [expr state]
+ (eval-fn-app state 'process-command expr print!))))
+
+Now we can start creating some issues. To generate some UUIDs, use the `uuid!`
+function at the REPL.
+
+ (create {:id "f621caec-b0a3-4c5e-9fdd-147066a35af1"
+ :author "james"
+ :title "Pattern matching"
+ :body "Pleeease"})
+
+ (create {:id "a37e56bd-b66a-4f3f-af06-9eaeb4afdae9"
+ :author "julian"
+ :title "Better numbers"
+ :body "The ids are floats!"})
+
+## Comments on issues
+
+Now it would be nice to be able to comment on issues. For this we'll just use a
+`:comment` field in the issue, which will be a vector of comments. The first
+thing we need to do therefore is add an empty vector of comments to all our
+current issues. To do this we'll use the update command which allows us to run
+some arbitrary updating code:
+
+ (update
+ (modify-ref issues
+ (fn [is]
+ (map-values (fn [i] (insert :comments [] i))
+ is))))
+
+When creating issues we now need to be careful to add the comments:
+
+ (create {:id "4a4d4479-468e-46e5-b026-1f84288aa682"
+ :author "Alice"
+ :title "Can issues have comments please?"
+ :body "So that we can talk about them."
+ :comments []})
+
+A more sophisticated handler might add an empty comments field if it doesn't
+exist.
+
+To add the commenting feature, first we will add a new function to add comments
+to issues.
+
+ (update
+ (def add-comment
+ (fn [issue-id comment]
+ (mod-issues
+ (fn [is]
+ (modify-map issue-id
+ (fn [i]
+ (modify-map :comments
+ (fn [cs] (add-right comment cs))
+ i))
+ is))))))
+
+TODO: modify-map should be renamed to modify-dict
+
+(You'll note that there is a lot of painful nested updating going on; later we
+will see how this can be made a lot easier with lenses.)
+
+Adding this command to our commands dictionary will now make comments work:
+
+ (update
+ (modify-ref
+ commands
+ (fn [cs] (insert 'comment add-comment cs))))
+
+Now we can comment on issues:
+
+ (comment "a37e56bd-b66a-4f3f-af06-9eaeb4afdae9"
+ {:author "james"
+ :comment "Yes that is a good idea."})
+
+## Validating data
+
+It would be nice to validate issues and comments before they are added, e.g.
+checking if all the right keys exist.
+
+TODO
+
+## Verifying authors
+
+This chain has issues and comments coming from users but there is nothing that
+enforces that the issues and comments are actually submitted by these users. I
+(Alice) could easily submit the comment:
+
+ (update
+ { :author "bobs-id"
+ :comment "LGTM"})
+
+to the chain and no one would know it wasn't Bob. To remedy this we will use
+signatures. First of all we will assume that this chain has a unique ID:
+
+ (update
+ (def chain-id "some-unique-id"))
+
+Signatures are created using the `gen-signature!` function, which takes a secret
+key `sk` and a string `msg`. The signature `sig` that it returns can be used
+with the function `verify-signature` as follows: `(verify-signature pk sig
+msg)`. If this returns `#t` then this tells us that the person who signed the
+message is the person who knows the secret key.
+
+We create a function to verify that issues are valid:
+
+ (update
+ (def issue-valid?
+ (fn [i]
+ (verify-signature (lookup :author i)
+ (lookup :signature i)
+ (string-append chain-id
+ (lookup :id i)
+ (lookup :title i)
+ (lookup :body i))))))
+
+Finally we modify the `add-issue` function. Note that we re-use our old
+`add-issue` function, just adding the extra layer of security:
+
+ (update
+ (def add-verified-issue
+ (fn [issue]
+ (if (issue-valid? issue)
+ (new-issue issue)
+ ;; In a real chain we would throw, not print a message.
+ (print! "The issue was not valid.")
+ ))))
+
+And we update our commands:
+
+ (update
+ (modify-ref
+ commands
+ (fn [cs] (insert 'create add-verified-issue cs))))
+
+Issues now have to be signed to be valid, here is some code one could run in
+another file to create such comments:
+
+ ;; (def chain-id "some-unique-id")
+
+ ;; (def kp (gen-key-pair! (default-ecc-curve)))
+
+ ;; (def sk (lookup :private-key kp))
+ ;; (def pk (lookup :public-key kp))
+
+ ;; (def make-issue
+ ;; (fn [title body]
+ ;; (def id (uuid!))
+ ;; (def msg
+ ;; (string-append chain-id
+ ;; id
+ ;; title
+ ;; body))
+ ;; {:id id
+ ;; :author pk
+ ;; :title title
+ ;; :body body
+ ;; :signature (gen-signature! sk msg)}))
+
+
+To generate a signed issue we can call, after loading that code into a REPL:
+
+ ;; (make-issue "This issue has a verified author"
+ ;; "This is the body of the first issue with a verified author.")
+
+And submit the result to the chain:
+
+ (create
+ {:author [:PublicKey
+ {:public_curve [:CurveFP
+ [:CurvePrime
+ 1.15792089237316195423570985008687907853269984665640564039457584007908834671663e77
+ [:CurveCommon
+ {:ecc_a 0.0
+ :ecc_b 7.0
+ :ecc_g [:Point
+ 5.506626302227734366957871889516853432625060345377759417550018736038911672924e76
+ 3.2670510020758816978083085130507043184471273380659243275938904335757337482424e76]
+ :ecc_h 1.0
+ :ecc_n 1.15792089237316195423570985008687907852837564279074904382605163141518161494337e77}]]]
+ :public_q [:Point
+ 1.11054692487265016800292649812157504820937148585989526304621614094061257232989e77
+ 3.6059272479591624612420581719526072934261866833779446725219340058438651734523e76]}]
+ :body "This is the body of the first issue with a verified author."
+ :id "76dd218b-fbc1-4384-9962-8bfbec5da2a2"
+ :signature [:Signature
+ {:sign_r 1.07685492960818947345554835683887719269111710108141784367526228085824476440077e77
+ :sign_s 3.740767076693925401519339475669557891360406440839428851888372253368058490896e76}]
+ :title "This issue has a verified author"})
+
+Signing comments would be done in a similar way.
diff --git a/docs/source/guide/IssuesHelper.rad b/docs/source/guide/IssuesHelper.rad
new file mode 100644
index 0000000..289d7bd
--- /dev/null
+++ b/docs/source/guide/IssuesHelper.rad
@@ -0,0 +1,20 @@
+;; (def chain-id "some-unique-id")
+
+;; (def kp (gen-key-pair! (default-ecc-curve)))
+
+;; (def sk (lookup :private-key kp))
+;; (def pk (lookup :public-key kp))
+
+;; (def make-issue
+;; (fn [title body]
+;; (def id (uuid!))
+;; (def msg
+;; (string-append chain-id
+;; id
+;; title
+;; body))
+;; {:id id
+;; :author pk
+;; :title title
+;; :body body
+;; :signature (gen-signature! sk msg)}))
diff --git a/exe/Doc.hs b/exe/Doc.hs
index 8e993da..ee99a7b 100644
--- a/exe/Doc.hs
+++ b/exe/Doc.hs
@@ -2,8 +2,10 @@
-- runs the code inside code blocks (within three backticks).
module Doc where
-import Options.Applicative
import Protolude
+
+import qualified Data.Text as T
+import Options.Applicative
import Radicle
import System.Console.Haskeline (defaultSettings, runInputT)
import Text.Pandoc
@@ -30,9 +32,7 @@ run f = do
getCode :: Pandoc -> Text
getCode (Pandoc _ blocks)
- = toS $ mconcat [ content | CodeBlock attr content <- blocks, isRad attr ]
- where
- isRad (id, _, _) = id == "radicle"
+ = T.intercalate "\n\n" [ toS content | CodeBlock _ content <- blocks ]
newtype Opts = Opts
{ srcFile :: FilePath
diff --git a/package.yaml b/package.yaml
index f12d0ae..1589640 100644
--- a/package.yaml
+++ b/package.yaml
@@ -29,6 +29,7 @@ dependencies:
- unordered-containers
- cryptonite
- generics-eot
+- uuid
when:
- condition: impl(ghcjs)
dependencies: ghcjs-dom
diff --git a/rad/chain.rad b/rad/chain.rad
index 1985ef9..580f94f 100644
--- a/rad/chain.rad
+++ b/rad/chain.rad
@@ -129,3 +129,20 @@
:else (eval__ expr env))
(eval__ expr env))
(eval__ expr env))))
+
+(def eval-fn-app
+ (fn [state f arg cb]
+ (def exec (base-eval (list f (list 'quote arg)) state))
+ (cb (head exec))
+ exec))
+
+(def updatable-eval
+ (fn [sub-eval]
+ (fn [expr state]
+ (list-with-head
+ expr
+ (fn [cmd]
+ (if (eq? cmd 'update)
+ (base-eval (nth 1 expr) state)
+ (sub-eval expr state)))
+ (fn [] (sub-eval expr state))))))
diff --git a/rad/prelude.rad b/rad/prelude.rad
index 082daa8..ec004ba 100644
--- a/rad/prelude.rad
+++ b/rad/prelude.rad
@@ -3,6 +3,7 @@
(load! "rad/prelude/io.rad")
(load! "rad/prelude/bool.rad")
(load! "rad/prelude/recursion.rad")
+(load! "rad/prelude/maybe.rad")
(load! "rad/prelude/list.rad")
(load! "rad/prelude/dict.rad")
(load! "rad/prelude/ref.rad")
@@ -45,4 +46,18 @@
(document 'send-prelude!
'(("chain-id" string))
-"Send the pure prelude to a chain.")
\ No newline at end of file
+"Send the pure prelude to a chain.")
+
+(def make-counter
+ (fn []
+ (def i (ref -1))
+ {:next-will-be (fn [] (+ 1 (read-ref i)))
+ :next (fn [] (modify-ref i (fn [x] (+ x 1))))}))
+
+(def list-with-head
+ (fn [x f g]
+ (if (list? x)
+ (if (> (length x) 0)
+ (f (head x))
+ (g))
+ (g))))
diff --git a/rad/prelude/lens.rad b/rad/prelude/lens.rad
index 7d0d2e8..8847fa1 100644
--- a/rad/prelude/lens.rad
+++ b/rad/prelude/lens.rad
@@ -3,8 +3,8 @@
;; make-lens
(def make-lens
- (fn [g s]
- (dict 'getter g 'setter s)))
+ (fn [g s]
+ {:getter g :setter s}))
(document 'make-lens
'(("getter" function) ("setter" function))
@@ -14,7 +14,7 @@
(def view
(fn [lens target]
- ((lookup 'getter lens) target)))
+ ((lookup :getter lens) target)))
(document 'view
'(("lens" dict) ("target" any))
@@ -24,7 +24,7 @@
(def set
(fn [lens new-view target]
- ((lookup 'setter lens) new-view target)))
+ ((lookup :setter lens) new-view target)))
(document 'set
'(("lens" dict) ("value" any) ("target" any))
@@ -82,30 +82,30 @@
" Returns a lens targetting keys of dicts.")
(should-be "view lens"
- (view (@ :one) (dict :one 1 :two 2))
+ (view (@ :one) {:one 1 :two 2})
1)
(should-be "set lens"
- (set (@ :two) 42 (dict :one 1 :two 2))
- (dict :one 1 :two 42))
+ (set (@ :two) 42 {:one 1 :two 2})
+ {:one 1 :two 42})
(should-be "over lens"
- (over (@ :one) (fn [x] (+ x 1)) (dict :one 1 :two 2))
- (dict :one 2 :two 2))
+ (over (@ :one)
+ (fn [x] (+ x 1))
+ {:one 1 :two 2})
+ {:one 2 :two 2})
(should-be "lens composition"
(over (.. (@ :a) (@ :b))
(fn [x] (+ x 1))
- (dict :a (dict :b 2)))
- (dict :a (dict :b 3)))
+ {:a {:b 2}})
+ {:a {:b 3}})
-(do (def d
- (fn [x] (dict :a (dict :b (dict :c x)))))
- (should-be "deep lenses"
- (over (... (list (@ :a) (@ :b) (@ :c)))
- (fn [x] (+ x 1))
- (d 0))
- (d 1)))
+(should-be "deep lenses"
+ (over (... (list (@ :a) (@ :b) (@ :c)))
+ (fn [x] (+ x 1))
+ {:a {:b {:c 0}}})
+ {:a {:b {:c 1}}})
;; Lens access to refs
@@ -119,7 +119,7 @@
"Like 'view', but for refs.")
(should-be "view-ref"
- (view-ref (ref (dict :key 1)) (@ :key))
+ (view-ref (ref {:key 1}) (@ :key))
1)
;; set-ref
@@ -134,12 +134,12 @@
(should-be "set-ref"
((fn [r]
- (def r (ref (dict :a 1)))
(set-ref r (@ :a) 2)
(view-ref r (@ :a)))
- (ref (dict :a 1)))
+ (ref {:a 1}))
2)
-;; set-ref
+
+;; over-ref
(def over-ref
(fn [r lens f]
@@ -151,8 +151,7 @@
(should-be "over-ref"
((fn [r]
- (def r (ref (dict :a 2)))
(over-ref r (@ :a) (fn [x] (* x 2)))
(view-ref r (@ :a)))
- (ref (dict :a 2)))
+ (ref {:a 2}))
4)
diff --git a/rad/prelude/list.rad b/rad/prelude/list.rad
index b6e2f2f..5e05fc6 100644
--- a/rad/prelude/list.rad
+++ b/rad/prelude/list.rad
@@ -84,4 +84,4 @@
(should-be "filter"
(filter (fn [x] (< x 10)) (list 3 10 11))
- (list 3))
+ (list 3))
\ No newline at end of file
diff --git a/rad/prelude/maybe.rad b/rad/prelude/maybe.rad
new file mode 100644
index 0000000..193a3d1
--- /dev/null
+++ b/rad/prelude/maybe.rad
@@ -0,0 +1,16 @@
+(def map-maybe
+ (fn [f]
+ (fn [m]
+ (maybe m :Nothing (fn [x] [:Just (f x)])))))
+
+(document 'map-maybe
+ '(("f" function))
+ "Functor mapping for Maybe values.")
+
+(should-be "map-maybe maps :Nothing"
+ ((map-maybe (fn [x] (+ x 1))) :Nothing)
+ :Nothing)
+
+(should-be "map-maybe maps :Just"
+ ((map-maybe (fn [x] (+ x 1))) [:Just 0])
+ [:Just 1])
diff --git a/rad/prelude/ref.rad b/rad/prelude/ref.rad
index b145b7c..e58045a 100644
--- a/rad/prelude/ref.rad
+++ b/rad/prelude/ref.rad
@@ -7,4 +7,4 @@
(document 'modify-ref
'(("ref" ref) ("fn" function))
- "Modify 'ref' by applying the provided function.")
+ "Modify 'ref' by applying the provided function. Returns the new value.")
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index 653b4ae..5c5a39c 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -570,6 +570,8 @@ instance CPA t => ToRad t Scientific where
toRad = Number
instance CPA t => ToRad t Text where
toRad = String
+instance ToRad t (Ann.Annotated t ValueF) where
+ toRad = identity
instance (CPA t, ToRad t a) => ToRad t [a] where
toRad xs = Vec . Seq.fromList $ toRad <$> xs
instance (CPA t, ToRad t a) => ToRad t (Map.Map Text a) where
diff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hs
index 8fb8910..fc76bae 100644
--- a/src/Radicle/Internal/Effects.hs
+++ b/src/Radicle/Internal/Effects.hs
@@ -24,11 +24,12 @@ import Radicle.Internal.Effects.Capabilities
import Radicle.Internal.Interpret
import Radicle.Internal.Pretty
import Radicle.Internal.PrimFns
+import qualified Radicle.Internal.UUID as UUID
type ReplM m =
( Monad m, Stdout (Lang m), Stdin (Lang m)
- , MonadRandom m
+ , MonadRandom m, UUID.MonadUUID m
, ReadFile (Lang m)
, GetEnv (Lang m) Value
, SetEnv (Lang m) Value )
@@ -38,6 +39,11 @@ instance MonadRandom (InputT IO) where
instance MonadRandom m => MonadRandom (LangT (Bindings (PrimFns m)) m) where
getRandomBytes = lift . getRandomBytes
+instance UUID.MonadUUID (InputT IO) where
+ uuid = liftIO UUID.uuid
+instance UUID.MonadUUID m => UUID.MonadUUID (LangT (Bindings (PrimFns m)) m) where
+ uuid = lift UUID.uuid
+
repl :: Maybe FilePath -> Text -> Text -> Bindings (PrimFns (InputT IO)) -> IO ()
repl histFile preFileName preCode bindings = do
let settings = setComplete completion
@@ -152,4 +158,9 @@ replPrimFns = PrimFns . Map.fromList $ first unsafeToIdent <$>
toRad <$> signText sk msg
_ -> throwErrorHere $ TypeError "gen-signature!: expects a string."
)
+ , ( "uuid!"
+ , \case
+ [] -> String <$> UUID.uuid
+ xs -> throwErrorHere $ WrongNumberOfArgs "uuid!" 0 (length xs)
+ )
]
diff --git a/src/Radicle/Internal/PrimFns.hs b/src/Radicle/Internal/PrimFns.hs
index 9e58344..254f5cb 100644
--- a/src/Radicle/Internal/PrimFns.hs
+++ b/src/Radicle/Internal/PrimFns.hs
@@ -13,13 +13,16 @@ import qualified Data.Aeson as Aeson
import qualified Data.IntMap as IntMap
import qualified Data.Map as Map
import Data.Scientific (Scientific, floatingOrInteger)
+import Data.Sequence (Seq(..))
import qualified Data.Sequence as Seq
import GHC.Exts (IsList(..))
+import qualified Radicle.Internal.Annotation as Ann
import Radicle.Internal.Core
import Radicle.Internal.Crypto
import Radicle.Internal.Parse
import Radicle.Internal.Pretty
+import qualified Radicle.Internal.UUID as UUID
-- | A Bindings with an Env containing only 'eval' and only pure primops.
pureEnv :: forall m. (Monad m) => Bindings (PrimFns m)
@@ -64,6 +67,16 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>
, ("get-current-env", \case
[] -> toRad <$> get
xs -> throwErrorHere $ WrongNumberOfArgs "get-current-env" 0 (length xs))
+ , ( "set-current-env"
+ , oneArg "set-current-env" $ \x -> do
+ e' :: Bindings () <- fromRadOtherErr x
+ e <- get
+ put e { bindingsEnv = bindingsEnv e'
+ , bindingsNextRef = bindingsNextRef e'
+ , bindingsRefs = bindingsRefs e'
+ }
+ pure ok
+ )
, ("list", pure . List)
, ("dict", (Dict . foldr (uncurry Map.insert) mempty <$>)
. evenArgs "dict")
@@ -75,6 +88,15 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>
[a, b] -> pure $ Boolean (a == b)
xs -> throwErrorHere $ WrongNumberOfArgs "eq?" 2 (length xs))
+ -- Maybe
+ , ( "maybe"
+ , \case
+ [Keyword (Ident "Nothing"), nothing, _] -> pure nothing
+ [Vec (Keyword (Ident "Just") :<| v :<| Empty), _, just] -> callFn just [v]
+ [x, _, _] -> throwErrorHere $ TypeError $ "maybe: first argument should be a Maybe: " <> renderCompactPretty x
+ xs -> throwErrorHere $ WrongNumberOfArgs "maybe" 3 (length xs)
+ )
+
-- Vectors
, ( "<>"
, twoArg "<>" $ \case
@@ -83,12 +105,12 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>
)
, ( "add-left"
, twoArg "add-left" $ \case
- (x, Vec xs) -> pure $ Vec (x Seq.:<| xs)
+ (x, Vec xs) -> pure $ Vec (x :<| xs)
_ -> throwErrorHere $ TypeError "add-left: second argument must be a vector"
)
, ( "add-right"
, twoArg "add-right" $ \case
- (x, Vec xs) -> pure $ Vec (xs Seq.:|> x)
+ (x, Vec xs) -> pure $ Vec (xs :|> x)
_ -> throwErrorHere $ TypeError "add-right: second argument must be a vector"
)
@@ -126,8 +148,23 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>
-- Probably an exception is better, but that seems cruel
-- when you have no exception handling facilities.
Nothing -> nil
- [_, _] -> throwErrorHere $ TypeError "lookup: second argument must be map"
+ [_, _] -> throwErrorHere $ TypeError $ "lookup: second argument must be a dict"
xs -> throwErrorHere $ WrongNumberOfArgs "lookup" 2 (length xs))
+ , ( "safe-lookup"
+ , twoArg "safe-lookup" $ \case
+ (a, Dict m) -> pure $ case Map.lookup a m of
+ Just v -> toRad [kw "Just", v]
+ Nothing -> kw "Nothing"
+ _ -> throwErrorHere $ TypeError $ "safe-lookup: second argument must be a dict"
+ )
+ , ( "map-values"
+ , twoArg "map-values" $ \case
+ (f, Dict m) -> do
+ let kvs = Map.toList m
+ vs <- traverse (\v -> callFn f [v]) (snd <$> kvs)
+ pure (Dict (Map.fromList (zip (fst <$> kvs) vs)))
+ _ -> throwErrorHere $ TypeError $ "map-values: second argument must be a dict"
+ )
, ("string-append", \args ->
let fromStr (String s) = Just s
fromStr _ = Nothing
@@ -138,12 +175,14 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>
, ("insert", \case
[k, v, Dict m] -> pure . Dict $ Map.insert k v m
[_, _, _] -> throwErrorHere
- $ TypeError "insert: third argument must be a dict"
+
+ $ TypeError "insert: third argument must be a dict"
xs -> throwErrorHere $ WrongNumberOfArgs "insert" 3 (length xs))
- , ("delete", \case
- [k, Dict m] -> pure . Dict $ Map.delete k m
- [_, _] -> throwErrorHere $ TypeError "delete: second argument must be a dict"
- xs -> throwErrorHere $ WrongNumberOfArgs "delete" 2 (length xs))
+ , ( "delete"
+ , twoArg "delete" $ \case
+ (k, Dict m) -> pure . Dict $ Map.delete k m
+ _ -> throwErrorHere $ TypeError "delete: second argument must be a dict"
+ )
-- The semantics of + and - in Scheme is a little messed up. (+ 3)
-- evaluates to 3, and of (- 3) to -3. That's pretty intuitive.
-- But while (+ 3 2 1) evaluates to 6, (- 3 2 1) evaluates to 0. So with -
@@ -164,14 +203,14 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>
[_, _] -> throwErrorHere $ TypeError ">: expecting number"
xs -> throwErrorHere $ WrongNumberOfArgs ">" 2 (length xs))
, ("foldl", \case
- [fn, init', List ls] -> foldlM (\b a -> callFn fn [b, a]) init' ls
- [_, _, _] -> throwErrorHere
- $ TypeError "foldl: third argument should be a list"
+ [fn, init', v] -> do
+ ls :: [Value] <- fromRadOtherErr v
+ foldlM (\b a -> callFn fn [b, a]) init' ls
xs -> throwErrorHere $ WrongNumberOfArgs "foldl" 3 (length xs))
, ("foldr", \case
- [fn, init', List ls] -> foldrM (\b a -> callFn fn [b, a]) init' ls
- [_, _, _] -> throwErrorHere
- $ TypeError "foldr: third argument should be a list"
+ [fn, init', v] -> do
+ ls :: [Value] <- fromRadOtherErr v
+ foldrM (\b a -> callFn fn [b, a]) init' ls
xs -> throwErrorHere $ WrongNumberOfArgs "foldr" 3 (length xs))
, ("map", \case
[fn, List ls] -> List <$> traverse (callFn fn) (pure <$> ls)
@@ -191,19 +230,19 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>
Dict _ -> pure tt
_ -> pure ff)
, ( "type"
- , let kw = pure . Keyword . Ident
+ , let kw' = pure . Keyword . Ident
in oneArg "type" $ \case
- Atom _ -> kw "atom"
- Keyword _ -> kw "keyword"
- String _ -> kw "string"
- Number _ -> kw "number"
- Boolean _ -> kw "boolean"
- List _ -> kw "list"
- Vec _ -> kw "vector"
- PrimFn _ -> kw "function"
- Dict _ -> kw "dict"
- Ref _ -> kw "ref"
- Lambda{} -> kw "function"
+ Atom _ -> kw' "atom"
+ Keyword _ -> kw' "keyword"
+ String _ -> kw' "string"
+ Number _ -> kw' "number"
+ Boolean _ -> kw' "boolean"
+ List _ -> kw' "list"
+ Vec _ -> kw' "vector"
+ PrimFn _ -> kw' "function"
+ Dict _ -> kw' "dict"
+ Ref _ -> kw' "ref"
+ Lambda{} -> kw' "function"
)
, ("string?", oneArg "string?" $ \case
String _ -> pure tt
@@ -216,6 +255,8 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>
_ -> pure ff)
, ("member?", \case
[x, List xs] -> pure . Boolean $ elem x xs
+ [x, Vec xs] -> pure . Boolean . isJust $ Seq.elemIndexL x xs
+ [x, Dict m] -> pure . Boolean $ Map.member x m
[_, _] -> throwErrorHere
$ TypeError "member?: second argument must be list"
xs -> throwErrorHere $ WrongNumberOfArgs "eq?" 2 (length xs))
@@ -227,7 +268,7 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>
[Ref (Reference x), v] -> do
st <- get
put $ st { bindingsRefs = IntMap.insert x v $ bindingsRefs st }
- pure nil
+ pure v
[_, _] -> throwErrorHere
$ TypeError "write-ref: first argument must be a ref"
xs -> throwErrorHere
@@ -258,18 +299,30 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>
, ( "verify-signature"
, \case
[keyv, sigv, String msg] -> do
- key <- hoistEither . first (toLangError . OtherError) $ fromRad keyv
- sig <- hoistEither . first (toLangError . OtherError) $ fromRad sigv
+ key <- fromRadOtherErr keyv
+ sig <- fromRadOtherErr sigv
pure . Boolean $ verifySignature key sig msg
[_, _, _] -> throwErrorHere $ OtherError "verify-signature: message must be a string"
xs -> throwErrorHere $ WrongNumberOfArgs "verify-signature" 3 (length xs)
)
+ , ( "uuid?"
+ , oneArg "uuid?" $ \case
+ String t -> pure . Boolean . UUID.isUUID $ t
+ _ -> throwErrorHere $ TypeError "uuid?: expects a string"
+ )
]
where
+ fromRadOtherErr :: (FromRad Ann.WithPos a) => Value -> Lang m a
+ fromRadOtherErr = hoistEither . first (toLangError . OtherError) . fromRad
+
tt = Boolean True
ff = Boolean False
+ ok = kw "ok"
+
+ kw = Keyword . Ident
+
numBinop :: (Scientific -> Scientific -> Scientific)
-> Text
-> (Text, [Value] -> Lang m Value)
diff --git a/src/Radicle/Internal/UUID.hs b/src/Radicle/Internal/UUID.hs
new file mode 100644
index 0000000..50320f9
--- /dev/null
+++ b/src/Radicle/Internal/UUID.hs
@@ -0,0 +1,17 @@
+{-# LANGUAGE UndecidableInstances #-}
+
+module Radicle.Internal.UUID where
+
+import Protolude
+
+import Data.UUID
+import Data.UUID.V4
+
+class Monad m => MonadUUID m where
+ uuid :: m Text
+
+instance MonadUUID IO where
+ uuid = toText <$> nextRandom
+
+isUUID :: Text -> Bool
+isUUID t = isJust $ fromText t
diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hs
index acbf077..b78ece3 100644
--- a/test/spec/Radicle/Internal/TestCapabilities.hs
+++ b/test/spec/Radicle/Internal/TestCapabilities.hs
@@ -11,6 +11,7 @@ import qualified System.FilePath.Find as FP
import Radicle
import Radicle.Internal.Crypto
import Radicle.Internal.Effects.Capabilities
+import qualified Radicle.Internal.UUID as UUID
import Paths_radicle
@@ -19,7 +20,8 @@ data WorldState = WorldState
, worldStateStdout :: [Text]
, worldStateEnv :: Env Value
, worldStateFiles :: Map Text Text
- , worldDRG :: CryptoRand.ChaChaDRG
+ , worldStateDRG :: CryptoRand.ChaChaDRG
+ , worldStateUUID :: Int
}
@@ -38,7 +40,8 @@ runTestWithFiles bindings inputs files action =
, worldStateStdout = []
, worldStateEnv = bindingsEnv bindings
, worldStateFiles = files
- , worldDRG = CryptoRand.drgNewSeed (CryptoRand.seedFromInteger 4) -- chosen by fair dice roll
+ , worldStateDRG = CryptoRand.drgNewSeed (CryptoRand.seedFromInteger 4) -- chosen by fair dice roll
+ , worldStateUUID = 0
}
in case runState (fmap fst $ runLang bindings $ interpretMany "[test]" action) ws of
(val, st) -> (val, reverse $ worldStateStdout st)
@@ -97,7 +100,13 @@ instance {-# OVERLAPPING #-} ReadFile TestLang where
instance MonadRandom (State WorldState) where
getRandomBytes i = do
- drg <- gets worldDRG
+ drg <- gets worldStateDRG
let (a, drg') = CryptoRand.randomBytesGenerate i drg
- modify $ \ws -> ws { worldDRG = drg' }
+ modify $ \ws -> ws { worldStateDRG = drg' }
pure a
+
+instance UUID.MonadUUID (State WorldState) where
+ uuid = do
+ i <- gets worldStateUUID
+ modify $ \ws -> ws { worldStateUUID = i + 1 }
+ pure $ "uuid-" <> show i