Skip to content

A peer-to-peer stack for code collaboration

Handles, processes, IO.

Julian K. Arni25152a790055
diff --git a/.gitignore b/.gitignore
index 11252a3..edd3eb2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,5 +16,6 @@ docs/build/
*.orig
*.swp
docs/build/
+my-keys.rad
TAGS
rad/my-keys.rad
diff --git a/.hlint.yaml b/.hlint.yaml
index 09ab05c..6708f61 100644
--- a/.hlint.yaml
+++ b/.hlint.yaml
@@ -16,7 +16,7 @@
- {name: [Data.ByteString.Lazy.Char8], as: L8}
- functions:
- - {name: unsafePerformIO, within: []}
+ - {name: unsafePerformIO, within: [Radicle.Tests, Radicle.Internal.TestCapabilities]}
- warn: {lhs: foldl, rhs: foldl'}
- warn: {lhs: return, rhs: pure}
diff --git a/docs/source/reference.rst b/docs/source/reference.rst
index 03991c8..f0d479c 100644
--- a/docs/source/reference.rst
+++ b/docs/source/reference.rst
@@ -358,7 +358,6 @@ is empty, in which case an exception is thrown.
Given a sequence ``xs`` and a function ``f``, returns a sequence with
the same elements ``x`` of ``xs`` but sorted according to ``(f x)``.
-<<<<<<< HEAD
``zip``
~~~~~~~
@@ -366,8 +365,6 @@ Takes two sequences and returns a sequence of corresponding pairs. In
one sequence is shorter than the other, the excess elements of the
longer sequence are discarded.
-=======
->>>>>>> UUIDs are just used as nonces and other improvements.
Dicts
-----
@@ -429,6 +426,13 @@ already exists, it is overwritten.
Given a function ``f`` and a dict ``d``, returns a dict with the same
keys as ``d`` but ``f`` applied to all the associated values.
+``map-keys``
+~~~~~~~~~~~~
+
+Given a function ``f`` and a dict ``d``, returns a dict with the same
+values as ``d`` but ``f`` applied to all the keys. If ``f`` maps two
+keys to the same thing, the greatest key and value are kept.
+
``(modify-map key f mp)``
~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -488,6 +492,32 @@ Create a set from a sequence.
Convert a set to a vector.
+Strings
+-------
+
+Functions for manipulating strings.
+
+``(intercalate sep strs)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Intercalates a string in a list of strings
+
+``(unlines x)``
+~~~~~~~~~~~~~~~
+
+Concatenate a list of strings, with newlines in between.
+
+``string-replace``
+~~~~~~~~~~~~~~~~~~
+
+Replace all occurrences of the first argument with the second in the
+third.
+
+``(unwords x)``
+~~~~~~~~~~~~~~~
+
+Concatenate a list of strings, with spaces in between.
+
Structures
----------
@@ -675,10 +705,10 @@ Input/Output
Effectful functions. These functions are not available in 'pure' chains,
but are available in the local REPL.
-``print!``
-~~~~~~~~~~
+``(print! x)``
+~~~~~~~~~~~~~~
-Pretty-prints a value.
+Print a value to the console or stdout.
``get-line!``
~~~~~~~~~~~~~
@@ -706,6 +736,34 @@ Read code (as data) from a file. Returns a vector of expressions
Send code from a file to a remote chain.
+``put-str!``
+~~~~~~~~~~~~
+
+Prints a string.
+
+``(process! command args to-write)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Executes ``command`` using 'execvp'. with 'to-write' as input. Stdout
+and stderr are inherit. See 'man exec' for more information on 'execvp'.
+Example: ``(process! "ls" ["-Glah"] "")``.
+
+``(shell! command to-write)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Executes ``command`` using the shell with ``to-write`` as input. Stdout
+and stderr are inherited. WARNING: using ``shell!`` with unsanitized
+user input is a security hazard! Example: ``(shell! "ls -Glah" "")``.
+
+``system!``
+~~~~~~~~~~~
+
+(system! proc) execute a system process. Returns the dict with the form
+``{ :stdin maybe-handle :stdout maybe-handle :stderr maybe-handle :proc prochandle }``
+Where ``maybe-handle`` is either ``[:just handle]`` or ``:nothing``.
+Note that this is quite a low-level function; higher-level ones are more
+convenient.
+
``(send-prelude! chain-id)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -734,6 +792,21 @@ Read a single line of input and interpret it as radicle data.
Exit the interpreter immediately.
+``read-line-handle!``
+~~~~~~~~~~~~~~~~~~~~~
+
+Read a single line from a handle.
+
+``wait-for-process!``
+~~~~~~~~~~~~~~~~~~~~~
+
+Block until process terminates.
+
+``write-handle!``
+~~~~~~~~~~~~~~~~~
+
+Write a string to the provided handle.
+
``now!``
~~~~~~~~
@@ -945,7 +1018,6 @@ functions before sending these to a remote chain.
Return an empty chain dictionary with the given url.
-<<<<<<< HEAD
``(@var ident)``
~~~~~~~~~~~~~~~~
@@ -953,15 +1025,6 @@ A lens for variables in states of chains.
``(eval-in-chain expr chain)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-=======
-``@var``
-~~~~~~~~
-
-A lens for variables in states of chains.
-
-``eval-in-chain``
-~~~~~~~~~~~~~~~~~
->>>>>>> UUIDs are just used as nonces and other improvements.
Evaluates 'expr' in the 'chain' and returns a dict with the ':result'
and the resulting ':chain'.
@@ -1055,4 +1118,4 @@ the next state.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Update a ref containing a chain with the new expressions from the remote
-chain
+chain
\ No newline at end of file
diff --git a/exe/ReferenceDoc.hs b/exe/ReferenceDoc.hs
index 3f3e249..0883cef 100644
--- a/exe/ReferenceDoc.hs
+++ b/exe/ReferenceDoc.hs
@@ -16,13 +16,11 @@ import Text.Pandoc
main :: IO ()
main = do
- res_ <- runInputT defaultSettings $
- interpret
+ (_, s) <- runInputT defaultSettings $
+ interpretWithState
"reference-doc"
- "(do (load! \"rad/prelude.rad\") (get-current-env))"
+ "(load! \"rad/prelude.rad\")"
replBindings
- res <- res_ `lPanic` "Error running the prelude."
- s :: Bindings () <- fromRad res `lPanic` "Couldn't convert radicle state."
let vars = GhcExts.toList (bindingsEnv s)
let undocd = [ fromIdent iden | (iden, Nothing, _) <- vars ]
checkAllDocumented undocd
@@ -50,6 +48,7 @@ main = do
, sec "Sequences" seqs $ typ "boths lists and vectors"
, sec "Dicts" dicts $ typ "dicts"
, sec "Sets" sets $ typ "sets"
+ , sec "Strings" strings $ typ "strings"
, sec "Structures" structs $ typ "lists, vectors and dicts"
, sec "Patterns" patterns
"Pattern matching is first-class in radicle so new patterns can easily be defined. These are the most essential."
@@ -91,8 +90,9 @@ main = do
vecs = ["<>", "add-left", "add-right"]
dicts =
["dict", "lookup", "insert", "delete", "dict-from-list", "keys", "values", "rekey"
- , "map-values", "modify-map", "delete-many", "exclusive-dict-merge"]
+ , "map-values", "map-keys", "modify-map", "delete-many", "exclusive-dict-merge"]
sets = ["set/empty", "set/insert", "set/delete", "set/member?", "set/delete", "set/from-seq", "set/to-vec"]
+ strings = ["intercalate", "unlines", "string-replace", "unwords"]
structs = ["member?"]
patterns = ["match-pat", "_", "/?", "/nil", "/cons", "/as", "non-linear-merge"]
refs = ["ref", "read-ref", "write-ref", "modify-ref"]
@@ -100,8 +100,9 @@ main = do
io =
[ "print!", "get-line!"
, "load!", "read-file!", "read-code!", "send-code!"
+ , "put-str!", "process!", "shell!", "system!"
, "send-prelude!", "subscribe-to!", "uuid!", "read-line!", "exit!"
- , "now!"]
+ , "read-line-handle!", "wait-for-process!", "write-handle!", "now!"]
maybe' = ["/Just", "maybe->>=", "maybe-foldlM"]
lens = ["@", "@nth", "make-lens", "view", "view-ref", "set", "set-ref", "over", "over-ref", "id-lens", "..", "..."]
validation =
@@ -123,7 +124,8 @@ main = do
allFns =
basics ++ maths ++ evalFns ++ envStuff ++ seqs ++ lists ++ vecs
- ++ dicts ++ sets ++ structs ++ patterns ++ refs ++ docs ++ io ++ maybe' ++ lens ++ validation ++ crypto ++ chainTools
+ ++ dicts ++ sets ++ strings ++ structs ++ patterns ++ refs ++ docs ++ io ++ maybe'
+ ++ lens ++ validation ++ crypto ++ chainTools
++ doNotInclude
valueDoc env name =
diff --git a/nix/shell.nix b/nix/shell.nix
index 823235c..1fec8c4 100644
--- a/nix/shell.nix
+++ b/nix/shell.nix
@@ -13,21 +13,22 @@ in
stdenv.mkDerivation {
name = "radicle-dev";
- buildInputs = [ ghc zlib python3 wget stack postgresql glibcLocales ]
+ buildInputs = [ ghc zlib python3 wget stack postgresql glibcLocales moreutils fzf]
++ (if doc then [docstuffs postgresql] else [])
++ (if extras then [ vimPlugins.stylish-haskell haskellPackages.apply-refact hlint ] else []);
libraryPkgconfigDepends = [ zlib ];
shellHook = ''
+ export PATH=$PATH:`stack path --local-bin`
eval $(grep export ${ghc}/bin/ghc)
alias check="pushd $PWD && ./scripts/check-fmt.sh && hlint . && popd"
alias mkdocs="pushd $PWD/docs && make html && popd"
alias sb="stack build --fast --system-ghc --nix-packages zlib"
alias sbs="stack build --fast --system-ghc --nix-packages zlib radicle:exe:radicle-server"
- alias sbc="stack build --fast --system-ghc --nix-packages zlib radicle:exe:radicle-client"
+ alias sbrad="stack build --fast --system-ghc --nix-packages zlib radicle:exe:radicle"
alias st="stack test --fast --system-ghc --nix-packages zlib"
alias sts="stack test --fast --system-ghc --nix-packages zlib radicle:spec"
alias str="stack test --fast --system-ghc --nix-packages zlib radicle:spec --ta '--pattern \"Radicle source file tests\"'"
alias server="stack exec radicle-server -- "
- alias client="stack exec radicle -- rad/repl.rad"
+ alias rad="stack exec radicle -- rad/repl.rad"
'';
}
diff --git a/package.yaml b/package.yaml
index ae0d198..b19b6d9 100644
--- a/package.yaml
+++ b/package.yaml
@@ -11,9 +11,6 @@ extra-source-files:
dependencies:
- base >=4 && <5
- protolude
-when:
- - condition: impl(ghcjs)
- dependencies: ghcjs-dom
ghc-options:
-Wall -Wcompat -Wincomplete-record-updates -Wincomplete-uni-patterns -Wredundant-constraints
@@ -38,6 +35,7 @@ library:
- pointed
- prettyprinter
- prettyprinter-ansi-terminal
+ - process
- servant
- servant-client
- scientific
@@ -61,6 +59,7 @@ tests:
- filemanip
- interpolate
- megaparsec
+ - process
- QuickCheck
- quickcheck-instances
- scientific
diff --git a/rad/monadic/issue-remote.rad b/rad/monadic/issue-remote.rad
index aa14c8e..da7954b 100644
--- a/rad/monadic/issue-remote.rad
+++ b/rad/monadic/issue-remote.rad
@@ -11,7 +11,7 @@
(def issue-counter
"We use a stateful counter for giving issues numbers."
- (lookup :next (make-counter)))
+ (make-counter))
(def used-nonces
"We keep track of the UUIDs which have been used as nonces in inputs."
@@ -104,7 +104,7 @@
"Create an issue from a dict, checking that it is valid and storing it in `issues`."
(fn [i]
(validator/issue-input i)
- (def n (issue-counter))
+ (def n (issue-counter :next))
(def i_
(strip-input
(<> i
diff --git a/rad/monadic/issues.rad b/rad/monadic/issues.rad
index b2ab6e5..0733f0f 100644
--- a/rad/monadic/issues.rad
+++ b/rad/monadic/issues.rad
@@ -128,17 +128,19 @@
(lookup id (list-issues))))
(:test
- "creating, manipulating and querying the issue chain"
- [:setup
- (do
- (def pk (gen-key-pair! (default-ecc-curve)))
- (def chain-name (uuid!))
- (def chain-ref (create-issues-chain! chain-name))
- (new-issue! chain-ref pk "Ah!" "if thou issueless shall hap to die")
- (update-chain-ref chain-ref)
- (def issues (values (list-issues chain-ref))))
- ]
- [ (length issues) ==> 1 ]
- [ (lookup :title (nth 0 issues)) ==> "Ah!" ]
- [ (lookup :body (nth 0 issues)) ==> "if thou issueless shall hap to die" ]
+ "The monadic issues chain works."
+ [:setup
+ (do (create-issues-chain!)
+ (simple-create-issue! "title0" "body0")
+ (simple-create-issue! "title1" "body1")
+ (simple-add-comment! 0 "comment0")
+ (simple-add-comment! 1 "comment1")
+ (fetch)
+ (def is (list-issues)))]
+ [ (length (seq is)) ==> 2 ]
+ [ (view (.. (@ 0) (@ :title)) is) ==> "title0" ]
+ [ (view (.. (@ 1) (@ :title)) is) ==> "title1" ]
+ [ (view (... [(@ 1) (@ :comments) (@nth 0) (@ :body)]) is) ==> "comment1" ]
+ [ (short (head (values is))) ==> "0: title0" ]
+ [ (short (head (list-last 1))) ==> "1: title1" ]
)
diff --git a/rad/prelude.rad b/rad/prelude.rad
index 0115e37..73d311b 100644
--- a/rad/prelude.rad
+++ b/rad/prelude.rad
@@ -1,6 +1,7 @@
(load! "rad/prelude/test.rad")
(load! "rad/prelude/basic.rad")
(load! "rad/prelude/patterns.rad")
+(load! "rad/prelude/strings.rad")
(load! "rad/prelude/io.rad")
(load! "rad/prelude/bool.rad")
(load! "rad/prelude/exception.rad")
@@ -63,4 +64,4 @@
(fn []
"radicle is a LISP-like language intended for programming chains, and interacting with those chains.
- Type (doc '<name>) for further documentation of <name>."))
\ No newline at end of file
+ Type (doc '<name>) for further documentation of <name>."))
diff --git a/rad/prelude/io-utils.rad b/rad/prelude/io-utils.rad
new file mode 100644
index 0000000..cc508ba
--- /dev/null
+++ b/rad/prelude/io-utils.rad
@@ -0,0 +1,6 @@
+(def fzf-select-by-key!
+ "Select from keys in `dict` with `fzf`, returning the corresponding values"
+ (fn [dict]
+ (def result (process! "/usr/bin/env" ["fzf"] (lines (keys dict))))
+ ;; TODO: pattern match on exit code when pattern matching is merged
+ (lookup (string-replace "\n" "" (nth 1 result)) dict)))
diff --git a/rad/prelude/io.rad b/rad/prelude/io.rad
index 221b857..e953eab 100644
--- a/rad/prelude/io.rad
+++ b/rad/prelude/io.rad
@@ -4,17 +4,56 @@
(fn [] (read (get-line!))))
(def read-code!
+ "Read code (as data) from a file. Returns a vector of expressions"
(fn [filename]
(read-many (read-file! filename))))
-(document 'read-code!
- '("filename" string)
- "Read code (as data) from a file. Returns a vector of expressions")
-
(def send-code!
+ "Send code from a file to a remote chain."
(fn [chain-id filename]
(send! chain-id (read-code! filename))))
-(document 'send-code!
- '(("chain-id" string) ("filename" string))
- "Send code from a file to a remote chain.")
+(def print!
+ "Print a value to the console or stdout."
+ (fn [x]
+ (put-str! (show x))))
+
+(def shell!
+ "Executes `command` using the shell with `to-write` as input. Stdout and stderr are inherited.
+WARNING: using `shell!` with unsanitized user input is a security hazard!
+Example: `(shell! \"ls -Glah\" \"\")`. "
+ (fn [command to-write]
+ (def cp
+ { :cmdspec [:shell command]
+ :stdin :create-pipe
+ :stdout :inherit
+ :stderr :inherit
+ })
+ (match (system! cp)
+ {:stdin [:just 'stdin]
+ :stdout :nothing
+ :stderr :nothing
+ :proc 'ph
+ } (do (write-handle! stdin to-write)
+ (wait-for-process! ph))
+ _ (throw 'io-error "expected only stdin to be open"))))
+
+(def process!
+ "Executes `command` using 'execvp'. with 'to-write' as input. Stdout and stderr are inherit.
+See 'man exec' for more information on 'execvp'.
+Example: `(process! \"ls\" [\"-Glah\"] \"\")`. "
+ (fn [command args to-write]
+ (def cp
+ { :cmdspec [:raw command args]
+ :stdin :create-pipe
+ :stdout :inherit
+ :stderr :inherit
+ })
+ (match (system! cp)
+ {:stdin [:just 'stdin]
+ :stdout :nothing
+ :stderr :nothing
+ :proc 'ph
+ } (do (write-handle! stdin to-write)
+ (wait-for-process! ph))
+ _ (throw 'io-error "expected only stdin to be open"))))
diff --git a/rad/prelude/strings.rad b/rad/prelude/strings.rad
new file mode 100644
index 0000000..7f11678
--- /dev/null
+++ b/rad/prelude/strings.rad
@@ -0,0 +1,31 @@
+(def intercalate
+ "Intercalates a string in a list of strings"
+ (fn [sep strs]
+ (if (eq? (length strs) 0)
+ ""
+ (foldl
+ string-append
+ (head strs)
+ (map (fn [ln] (string-append sep ln)) (tail strs))))))
+
+(:test "intercalate"
+ [ (intercalate "aa" ["hi" "there"]) ==> "hiaathere" ]
+)
+
+(def unlines
+ "Concatenate a list of strings, with newlines in between."
+ (fn [x]
+ (intercalate "\n" x)))
+
+(:test "unlines"
+ [ (unlines ["hi" "there"]) ==> "hi\nthere" ]
+)
+
+(def unwords
+ "Concatenate a list of strings, with spaces in between."
+ (fn [x]
+ (intercalate " " x)))
+
+(:test "unwords"
+ [ (unwords ["hi" "there"]) ==> "hi there" ]
+)
diff --git a/rad/prelude/test.rad b/rad/prelude/test.rad
index f9b30ce..a3be0ce 100644
--- a/rad/prelude/test.rad
+++ b/rad/prelude/test.rad
@@ -6,6 +6,7 @@
;; Annoyingly verbose since we have neither the prelude nor pattern-matching.
(def eval
+ "The evaluation function."
(fn [expr env]
(if (list? expr)
(if (> (foldr (fn [x acc] (+ acc 1)) 0 expr) 0)
@@ -15,7 +16,7 @@
(def test-name (nth 1 expr))
(def error
(fn [msg]
- (print! (string-append "Test '" test-name "' failed: " msg))))
+ (put-str! (string-append "Test '" test-name "' failed: " msg))))
;; Check a single test in a given env
(def check-single
(fn [single ix senv]
@@ -26,7 +27,7 @@
(do
(def lhs-res (head (eval lhs senv)))
(if (eq? lhs-res rhs)
- (print! (string-append "Test '" test-name " (" (show ix) ")' succeeded"))
+ (put-str! (string-append "Test '" test-name " (" (show ix) ")' succeeded"))
(error (string-append "failed: got " (show lhs-res) " but expected " (show rhs)))))
(error "Expected and actual not separate by ==>"))
(+ ix 1)))
diff --git a/src/Radicle.hs b/src/Radicle.hs
index ac1cdb0..3474e7f 100644
--- a/src/Radicle.hs
+++ b/src/Radicle.hs
@@ -16,6 +16,7 @@ module Radicle
-- | The definition of the core language.
-- ** Evaluation
interpret
+ , interpretWithState
, interpretMany
, eval
-- ** Datatypes
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index 9e2a370..9834964 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -5,7 +5,7 @@
module Radicle.Internal.Core where
import qualified Prelude
-import Protolude hiding (Constructor, TypeError, (<>))
+import Protolude hiding (Constructor, Handle, TypeError, (<>))
import Codec.Serialise (Serialise)
import Control.Monad.Except
@@ -26,6 +26,9 @@ import Data.Sequence (Seq(..))
import qualified Data.Sequence as Seq
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)
@@ -166,6 +169,52 @@ readRef (Reference r) = do
Nothing -> throwErrorHere $ Impossible "undefined reference"
Just v -> pure v
+-- | As with References and ProcHdls, we keep a counter for each handle, and in
+-- the environment map those to actual handles.
+newtype Hdl = Hdl { getHandle :: Int }
+ deriving (Show, Read, Ord, Eq, Generic, Serialise)
+
+-- | Create a new handle.
+newHandle :: Monad m => Handle.Handle -> Lang m Value
+newHandle h = do
+ b <- get
+ let ix = bindingsNextHandle b
+ put $ b { bindingsNextHandle = succ ix
+ , bindingsHandles = IntMap.insert ix h $ bindingsHandles b
+ }
+ pure $ Handle $ Hdl ix
+
+-- | Lookup a handle in the bindings, failing if it does not exist.
+lookupHandle :: Monad m => Hdl -> Lang m Handle.Handle
+lookupHandle (Hdl h) = do
+ hdls <- gets bindingsHandles
+ case IntMap.lookup h hdls of
+ Nothing -> throwErrorHere $ Impossible "no such handle"
+ Just v -> pure v
+
+-- | As with References and Hdls, we keep a counter for each handle, and in the
+-- environment map those to actual handles.
+newtype ProcHdl = ProcHdl { getProcHandle :: Int }
+ deriving (Show, Read, Ord, Eq, Generic, Serialise)
+
+-- | Lookup a process handle in the bindings, failing if it does not exist.
+lookupProcHandle :: Monad m => ProcHdl -> Lang m ProcessHandle
+lookupProcHandle (ProcHdl h) = do
+ hdls <- gets bindingsProcHandles
+ case IntMap.lookup h hdls of
+ Nothing -> throwErrorHere $ Impossible "no such process handle"
+ Just v -> pure v
+
+-- | Create a new process handle.
+newProcessHandle :: Monad m => ProcessHandle -> Lang m Value
+newProcessHandle h = do
+ b <- get
+ let ix = bindingsNextProcHandle b
+ put $ b { bindingsNextProcHandle = succ ix
+ , bindingsProcHandles = IntMap.insert ix h $ bindingsProcHandles b
+ }
+ pure $ ProcHandle $ ProcHdl ix
+
-- | An expression or value in the language.
data ValueF r =
-- | A regular (hyperstatic) variable.
@@ -181,6 +230,8 @@ data ValueF r =
-- | Map from *pure* Values -- annotations shouldn't change lookup semantics.
| DictF (Map.Map Value r)
| RefF Reference
+ | HandleF Hdl
+ | ProcHandleF ProcHdl
-- | Takes the arguments/parameters, a body, and possibly a closure.
--
-- The value of an application of a lambda is always the last value in the
@@ -202,6 +253,8 @@ valType = \case
PrimFn _ -> TFunction
Dict _ -> TDict
Ref _ -> TRef
+ Handle _ -> THandle
+ ProcHandle _ -> TProcHandle
Lambda{} -> TFunction
hashable :: (CPA t) => Annotated t ValueF -> Bool
@@ -213,6 +266,8 @@ hashable = \case
Keyword _ -> True
PrimFn _ -> False
Ref _ -> False
+ Handle _ -> False
+ ProcHandle _ -> False
Lambda{} -> False
List xs -> all hashable xs
Vec xs -> all hashable xs
@@ -225,7 +280,8 @@ dict kvs =
then pure $ Dict kvs
else throwErrorHere NonHashableKey
-{-# COMPLETE Atom, Keyword, String, Number, Boolean, List, Vec, PrimFn, Dict, Ref, Lambda #-}
+{-# COMPLETE Atom, Keyword, String, Number, Boolean, List, Vec, PrimFn, Dict
+ , Ref, Handle, ProcHandle, Lambda #-}
type ValueConC t = (HasCallStack, Ann.Annotation t, Copointed t)
@@ -279,6 +335,16 @@ pattern Ref i <- (Ann.match -> RefF i)
where
Ref = Ann.annotate . RefF
+pattern Handle :: ValueConC t => Hdl -> Annotated t ValueF
+pattern Handle i <- (Ann.match -> HandleF i)
+ where
+ Handle = Ann.annotate . HandleF
+
+pattern ProcHandle :: ValueConC t => ProcHdl -> Annotated t ValueF
+pattern ProcHandle i <- (Ann.match -> ProcHandleF i)
+ where
+ ProcHandle = Ann.annotate . ProcHandleF
+
pattern Lambda :: ValueConC t => [Ident] -> NonEmpty (Annotated t ValueF) -> Env (Annotated t ValueF) -> Annotated t ValueF
pattern Lambda vs exps env <- (Ann.match -> LambdaF vs exps env)
where
@@ -378,11 +444,77 @@ instance GhcExts.IsList (PrimFns m) where
-- | Bindings, either from the env or from the primops.
data Bindings prims = Bindings
- { bindingsEnv :: Env Value
- , bindingsPrimFns :: prims
- , bindingsRefs :: IntMap Value
- , bindingsNextRef :: Int
- } deriving (Eq, Show, Functor, Generic)
+ { bindingsEnv :: Env Value
+ , bindingsPrimFns :: prims
+ , bindingsRefs :: IntMap Value
+ , bindingsNextRef :: Int
+ , bindingsHandles :: IntMap Handle.Handle
+ , bindingsNextHandle :: Int
+ , bindingsProcHandles :: IntMap ProcessHandle
+ , bindingsNextProcHandle :: Int
+ } deriving (Functor, Generic)
+
+emptyBindings :: Bindings (PrimFns m)
+emptyBindings = Bindings mempty mempty mempty 0 mempty 0 mempty 0
+
+-- | Extract an environment and references from a Radicle value and put
+-- them as the current bindings. Primitive functions are not changed.
+--
+-- Throws 'OtherError' if @value@ cannot be parsed.
+--
+-- Satisfies the expected properties with `bindingsToRadicle`:
+-- * `gets bindingsToRadicle >>= setBindings == pure ()`
+-- * `setBindings x >> gets bindingsToRadicle == setBindings x >> pure x`
+setBindings :: Monad m => Value -> Lang m ()
+setBindings value = do
+ case bindingsFromRadicle value of
+ Left e -> throwErrorHere $ OtherError $ "Invalid bindings: " <> e
+ Right newBindings -> do
+ bnds <- get
+ put $ newBindings
+ { bindingsPrimFns = bindingsPrimFns bnds
+ , bindingsHandles = bindingsHandles bnds
+ , bindingsNextHandle = bindingsNextHandle bnds
+ , bindingsProcHandles = bindingsProcHandles bnds
+ , bindingsNextProcHandle = bindingsNextProcHandle bnds
+ }
+ where
+ 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"
+ makeRefs refs = case refs of
+ List ls -> pure (IntMap.fromList $ zip [0..] ls)
+ _ -> throwError $ "Expecting dict"
+ 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"
+
+-- | Serializes the environment and references into a Radicle value.
+--
+-- Satisfies the expected properties with `setBindings`:
+-- * `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 = Dict . Map.mapKeys Atom . Map.map toRad . fromEnv $ bindingsEnv x
+ refs = List $ IntMap.elems (bindingsRefs x)
-- | The environment in which expressions are evaluated.
newtype LangT r m a = LangT
@@ -413,16 +545,6 @@ runLang
-> m (Either (LangError Value) a, Bindings (PrimFns 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 (PrimFns m) -> Bindings (PrimFns 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.
@@ -467,18 +589,15 @@ defineAtom i d v = modify $ addBinding i d v
eval :: Monad m => Value -> Lang m Value
eval val = do
e <- lookupAtom (Ident "eval")
- st <- gets toRad
- logValPos e $ callFn e [val, st] >>= updateEnvAndReturn
- where
- updateEnvAndReturn :: Monad m => Value -> Lang m Value
- updateEnvAndReturn v = case v of
- List [val', newSt] -> do
- prims <- gets bindingsPrimFns
- newSt' <- either (throwErrorHere . OtherError) pure
- (fromRad newSt :: Either Text (Bindings ()))
- put $ newSt' { bindingsPrimFns = prims }
- pure val'
- _ -> throwErrorHere $ OtherError "eval: should return list with value and new env"
+ logValPos e $ do
+ st <- gets bindingsToRadicle
+ result <- callFn e [val, st]
+ case result of
+ List [val', newSt] -> do
+ setBindings newSt
+ pure val'
+ _ -> throwErrorHere
+ $ OtherError "eval: should return list with value and new env"
-- | The built-in, original, eval.
@@ -635,6 +754,15 @@ instance CPA t => FromRad t Text where
fromRad x = case x of
String n -> pure n
_ -> Left "Expecting string"
+instance {-# OVERLAPPING #-} CPA t => FromRad t [Char] where
+ fromRad x = case x of
+ String n -> pure $ toS n
+ _ -> Left "Expecting string"
+instance CPA t => FromRad t ExitCode where
+ fromRad x = case x of
+ Keyword (Ident "ok") -> pure $ ExitSuccess
+ Vec (Keyword (Ident "error") Seq.:<| errValue Seq.:<| Seq.Empty) -> ExitFailure <$> fromRad errValue
+ _ -> Left "Expecting either :ok or [:error errValue]"
instance (CPA t, FromRad t a) => FromRad t [a] where
fromRad x = case x of
List xs -> traverse fromRad xs
@@ -646,28 +774,47 @@ instance CPA t => FromRad t (Doc.Docd (Annotated t ValueF)) where
doc <- traverse fromRad (kwLookup "doc" d)
pure (Doc.Docd doc val)
fromRad _ = Left "Expecting a dict."
-instance FromRad Ann.WithPos (Env Value) where
+instance CPA t => FromRad t CmdSpec where
fromRad x = case x of
- Dict d -> fmap (Env . Map.fromList)
- $ forM (Map.toList d) $ \(k, v) -> case k of
- Atom i -> do
- docd <- fromRad v
- pure (i, docd)
- k' -> Left $ "Expecting atom keys. Got: " <> show k'
- _ -> Left "Expecting dict"
-instance FromRad Ann.WithPos (Bindings ()) where
+ Vec (Keyword (Ident "shell") Seq.:<| arg Seq.:<| Seq.Empty) ->
+ ShellCommand <$> fromRad arg
+ Vec (Keyword (Ident "raw") Seq.:<| comm Seq.:<| args Seq.:<| Seq.Empty) ->
+ RawCommand <$> fromRad comm <*> fromRad args
+ Vec (Keyword (Ident s) Seq.:<| _) ->
+ throwError $ "Expecting either :raw or :shell, got: " <> s
+ _ ->
+ throwError "Expecting vector"
+instance CPA t => FromRad t StdStream where
+ fromRad x = case x of
+ Keyword (Ident "inherit") -> pure Inherit
+ Keyword (Ident "create-pipe") -> pure CreatePipe
+ Keyword (Ident "no-stream") -> pure NoStream
+ _ -> throwError $ "Expecting :inherit, :create-pipe, or :no-stream"
+instance CPA t => FromRad t CreateProcess where
fromRad 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 <- fromRad 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"
+ cmdspec' <- fromRad =<< (kwLookup "cmdspec" d ?? "Expecting 'cmdspec' key")
+ stdin' <- fromRad =<< (kwLookup "stdin" d ?? "Expecting 'stdin' key")
+ stdout' <- fromRad =<< (kwLookup "stdout" d ?? "Expecting 'stdout' key")
+ stderr' <- fromRad =<< (kwLookup "stderr" d ?? "Expecting 'stderr' key")
+ pure CreateProcess
+ { cmdspec = cmdspec'
+ , cwd = Nothing
+ , env = Nothing
+ , std_in = stdin'
+ , std_out = stdout'
+ , std_err = stderr'
+ , close_fds = False
+ , create_group = False
+ , delegate_ctlc = False
+ , detach_console = False
+ , create_new_console = False
+ , new_session = False
+ , child_group = Nothing
+ , child_user = Nothing
+ , use_process_jobs = False
+ }
+ _ -> throwError "Expecting dictionary"
class ToRad t a where
@@ -681,7 +828,11 @@ instance CPA t => ToRad t () where
instance CPA t => ToRad t Bool where
toRad = Boolean
instance (CPA t, ToRad t a, ToRad t b) => ToRad t (a,b) where
- toRad (x,y) = Vec $ toRad x :<| toRad y :<| Empty
+ toRad (a,b) = Vec $ toRad a :<| toRad b :<| Empty
+instance (CPA t, ToRad t a, ToRad t b, ToRad t c) => ToRad t (a,b,c) where
+ toRad (a,b,c) = Vec $ toRad a :<| toRad b :<| toRad c :<| Empty
+instance (CPA t, ToRad t a, ToRad t b, ToRad t c, ToRad t d) => ToRad t (a,b,c,d) where
+ toRad (a,b,c,d) = Vec $ toRad a :<| toRad b :<| toRad c :<| toRad d :<| Empty
instance (CPA t, ToRad t a) => ToRad t (Maybe a) where
toRad Nothing = Keyword (Ident "nothing")
toRad (Just x) = Vec $ Keyword (Ident "just") :<| toRad x :<| Empty
@@ -693,6 +844,12 @@ instance CPA t => ToRad t Scientific where
toRad = Number . toRational
instance CPA t => ToRad t Text where
toRad = String
+instance {-# OVERLAPPING #-} CPA t => ToRad t [Char] where
+ toRad = String . toS
+instance CPA t => ToRad t ExitCode where
+ toRad x = case x of
+ ExitSuccess -> Keyword (Ident "ok")
+ ExitFailure c -> Vec $ Seq.fromList [Keyword (Ident "error"), toRad c]
instance ToRad t (Ann.Annotated t ValueF) where
toRad = identity
instance (CPA t, ToRad t a) => ToRad t [a] where
@@ -703,13 +860,21 @@ instance CPA t => ToRad t (Doc.Docd (Annotated t ValueF)) where
toRad (Doc.Docd d_ v) = Dict $ Map.fromList $ ( Keyword (Ident "val"), v) : case d_ of
Just d -> [ (Keyword (Ident "doc"), toRad d) ]
Nothing -> []
-instance ToRad Ann.WithPos (Env Value) where
- toRad x = Dict . Map.mapKeys Atom . Map.map toRad $ fromEnv x
-instance ToRad Ann.WithPos (Bindings m) where
- toRad x = Dict $ Map.fromList
- [ (Keyword $ Ident "env", toRad $ bindingsEnv x)
- , (Keyword $ Ident "refs", List $ IntMap.elems (bindingsRefs x))
- ]
+instance (CPA t) => ToRad t StdStream where
+ toRad x = case x of
+ Inherit -> Keyword $ Ident "inherit"
+ CreatePipe -> Keyword $ Ident "create-pipe"
+ NoStream -> Keyword $ Ident "no-stream"
+ _ -> panic "Cannot convert handle"
+instance (CPA t) => ToRad t CmdSpec where
+ toRad x = case x of
+ ShellCommand comm ->
+ let c = toRad comm
+ in Vec $ Seq.fromList [Keyword (Ident "shell"), c]
+ RawCommand f args ->
+ let f' = toRad f
+ args' = toRad args
+ in Vec $ Seq.fromList [Keyword (Ident "raw"), f', args']
-- * Helpers
diff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hs
index 93883e6..f1de80e 100644
--- a/src/Radicle/Internal/Effects.hs
+++ b/src/Radicle/Internal/Effects.hs
@@ -33,6 +33,7 @@ type ReplM m =
, MonadRandom m, UUID.MonadUUID m
, CurrentTime m
, ReadFile (Lang m)
+ , System m
, GetEnv (Lang m) Value
, SetEnv (Lang m) Value )
@@ -76,14 +77,14 @@ replBindings = addPrimFns replPrimFns pureEnv
replPrimFns :: ReplM m => PrimFns m
replPrimFns = fromList $ allDocs $
- [ ("print!"
- , "Pretty-prints a value."
- , \case
- [x] -> do
- putPrettyAnsi x
+ [ ("put-str!"
+ , "Prints a string."
+ , oneArg "put-str!" $ \case
+ (String x) -> do
+ putStrS x
pure nil
- xs -> throwErrorHere $ WrongNumberOfArgs "print!" 1 (length xs))
-
+ v -> throwErrorHere $ TypeError "put-str!" 0 TString v
+ )
, ( "doc!"
, "Prints the documentation attached to a value and returns `()`. To retrieve\
\ the docstring as a value use `doc` instead."
@@ -206,6 +207,62 @@ replPrimFns = fromList $ allDocs $
[] -> String <$> UUID.uuid
xs -> throwErrorHere $ WrongNumberOfArgs "uuid!" 0 (length xs)
)
+ , ( "system!"
+ , "(system! proc) execute a system process. Returns the dict with the form\
+ \ ```\
+ \ { :stdin maybe-handle\
+ \ :stdout maybe-handle\
+ \ :stderr maybe-handle\
+ \ :proc prochandle\
+ \ }\
+ \ ```\
+ \ Where `maybe-handle` is either `[:just handle]` or `:nothing`.\
+ \ Note that this is quite a low-level function; higher-level ones are more convenient."
+ , oneArg "system!" $ \proc -> do
+ proc' <- hoistEither $ first (toLangError . OtherError) $ fromRad proc
+ res <- systemS proc'
+ let ifJustCreate x = case x of
+ Nothing -> pure Nothing
+ Just v -> Just <$> newHandle v
+ case res of
+ (a, b, c, ph) -> do
+ a' <- ifJustCreate a
+ b' <- ifJustCreate b
+ c' <- ifJustCreate c
+ ph' <- newProcessHandle ph
+ pure $ Dict $ Map.fromList $ first (Keyword . Ident) <$>
+ [ ("stdin", toRad a')
+ , ("stdout", toRad b')
+ , ("stderr", toRad c')
+ , ("proc", toRad ph')
+ ]
+ )
+ , ( "write-handle!"
+ , "Write a string to the provided handle."
+ , twoArg "write-handle!" $ \case
+ (Handle h, String msg) -> do
+ h' <- lookupHandle h
+ hPutStrS h' msg
+ pure $ Keyword $ Ident "ok"
+ (Handle _, v) -> throwErrorHere $ TypeError "write-handle!" 1 TString v
+ (v, _) -> throwErrorHere $ TypeError "write-handle!" 0 THandle v
+ )
+ , ( "read-line-handle!"
+ , "Read a single line from a handle."
+ , oneArg "read-line-handle!" $ \case
+ Handle h -> do
+ h' <- lookupHandle h
+ String <$> hGetLineS h'
+ v -> throwErrorHere $ TypeError "read-line-handle!" 0 THandle v
+ )
+ , ( "wait-for-process!"
+ , "Block until process terminates."
+ , oneArg "wait-for-process!" $ \case
+ ProcHandle h -> do
+ h' <- lookupProcHandle h
+ toRad <$> waitForProcessS h'
+ v -> throwErrorHere $ TypeError "wait-for-process!" 0 TProcHandle v
+ )
, ( "exit!"
, "Exit the interpreter immediately."
, \case
diff --git a/src/Radicle/Internal/Effects/Capabilities.hs b/src/Radicle/Internal/Effects/Capabilities.hs
index 0e95189..4b9c2e6 100644
--- a/src/Radicle/Internal/Effects/Capabilities.hs
+++ b/src/Radicle/Internal/Effects/Capabilities.hs
@@ -11,7 +11,10 @@ import Data.Text.Prettyprint.Doc (PageWidth)
import Data.Time
import System.Console.ANSI (hSupportsANSI)
import System.Console.Haskeline hiding (catch)
-import System.IO (isEOF)
+import System.Exit (ExitCode)
+import System.IO (hGetLine, isEOF)
+import System.Process
+ (CreateProcess, ProcessHandle, createProcess, waitForProcess)
#ifdef ghcjs_HOST_OS
import GHCJS.DOM.XMLHttpRequest
(getResponseText, newXMLHttpRequest, openSimple, send)
@@ -47,6 +50,36 @@ instance (MonadException m, Monad m) => Stdout (InputT m) where
putStrS = outputStrLn . toS
supportsANSI = pure True
+
+class (Monad m) => System m where
+ systemS
+ :: CreateProcess
+ -> m (Maybe Handle, Maybe Handle, Maybe Handle, ProcessHandle)
+ waitForProcessS :: ProcessHandle -> m ExitCode
+ hPutStrS :: Handle -> Text -> m ()
+ hGetLineS :: Handle -> m Text
+
+instance System m => System (Lang m) where
+ systemS proc = lift $ systemS proc
+ waitForProcessS = lift . waitForProcessS
+ hPutStrS a b = lift $ hPutStrS a b
+ hGetLineS = lift . hGetLineS
+instance System IO where
+ systemS = createProcess
+ waitForProcessS = waitForProcess
+ hPutStrS = hPutStr
+ hGetLineS x = toS <$> hGetLine x
+instance System m => System (InputT m) where
+ systemS proc = lift $ systemS proc
+ waitForProcessS = lift . waitForProcessS
+ hPutStrS a b = lift $ hPutStrS a b
+ hGetLineS = lift . hGetLineS
+
+class (Monad m) => Exit m where
+ exitS :: m ()
+instance Exit m => Exit (Lang m) where
+ exitS = lift exitS
+
class Monad m => CurrentTime m where
currentTime :: m UTCTime
diff --git a/src/Radicle/Internal/Interpret.hs b/src/Radicle/Internal/Interpret.hs
index a95c8c4..11ed601 100644
--- a/src/Radicle/Internal/Interpret.hs
+++ b/src/Radicle/Internal/Interpret.hs
@@ -26,11 +26,21 @@ interpret
-> Text -- ^ Source code to be interpreted
-> Bindings (PrimFns m) -- ^ Bindings to be used
-> m (Either (LangError Value) Value)
-interpret sourceName expr bnds = do
+interpret sourceName expr bnds
+ = fst <$> interpretWithState sourceName expr bnds
+
+-- | Like 'interpret', but also returns the resulting state.
+interpretWithState
+ :: Monad m
+ => Text -- ^ Name of source file (for error reporting)
+ -> Text -- ^ Source code to be interpreted
+ -> Bindings (PrimFns m) -- ^ Bindings to be used
+ -> m (Either (LangError Value) Value, Bindings (PrimFns m))
+interpretWithState sourceName expr bnds = do
let parsed = runIdentity (runParserT (spaceConsumer *> valueP <* eof) (toS sourceName) expr)
case parsed of
- Left e -> pure . Left $ LangError [Ann.thisPos] (ParseError e)
- Right v -> fst <$> runLang bnds (eval v)
+ Left e -> pure (Left (LangError [Ann.thisPos] (ParseError e)), bnds)
+ Right v -> runLang bnds (eval v)
-- | Parse and evaluate a Text as multiple expressions.
--
@@ -55,3 +65,5 @@ interpretMany sourceName src = case parseValues sourceName src of
Just e -> pure e
_ -> throwErrorHere
$ OtherError "InterpretMany should be called with at least one expression."
+
+
diff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hs
index ad0144a..bfc18c0 100644
--- a/src/Radicle/Internal/Pretty.hs
+++ b/src/Radicle/Internal/Pretty.hs
@@ -29,6 +29,14 @@ class PrettyV a where
instance PrettyV Reference where
prettyV _ = annotate TRef $ angles "ref"
+-- | As with references, we do not print the actual counter of the handle.
+instance Pretty Hdl where
+ pretty _ = angles "handle"
+
+-- | As with references, we do not print the actual counter of the handle.
+instance Pretty ProcHdl where
+ pretty _ = angles "prochandle"
+
instance Pretty Ident where
pretty (Ident i) = pretty i
@@ -40,6 +48,8 @@ instance forall t. (Copointed t, Ann.Annotation t) => PrettyV (Ann.Annotated t V
Atom i -> pretty i
Keyword i -> ":" <> pretty i
Ref i -> prettyV i
+ Handle i -> pretty i
+ ProcHandle i -> pretty i
String t -> "\"" <> pretty (escapeStr t) <> "\""
Number (a :% b) -> pretty a <> if b == 1 then "" else "/" <> pretty b
Boolean True -> "#t"
diff --git a/src/Radicle/Internal/PrimFns.hs b/src/Radicle/Internal/PrimFns.hs
index b02f398..a511287 100644
--- a/src/Radicle/Internal/PrimFns.hs
+++ b/src/Radicle/Internal/PrimFns.hs
@@ -25,7 +25,7 @@ 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)
pureEnv =
- addPrimFns purePrimFns $ Bindings e mempty mempty 0
+ addPrimFns purePrimFns $ Bindings e mempty mempty 0 mempty 0 mempty 0
where
e = fromList . allDocs $
[ ( "eval"
@@ -57,21 +57,20 @@ purePrimFns = fromList $ allDocs $
\ state. Return a list of length 2 consisting of the result of the\
\ evaluation and the new state."
, \case
- [expr, st] -> case (fromRad st :: Either Text (Bindings ())) of
- Left e -> throwErrorHere $ OtherError e
- Right st' -> do
- prims <- gets bindingsPrimFns
- withBindings (const $ fmap (const prims) st') $ do
- val <- baseEval expr
- st'' <- get
- pure $ List [val, toRad st'']
+ [expr, st] -> do
+ originalBindings <- get
+ setBindings st
+ val <- baseEval expr
+ st' <- get
+ put originalBindings
+ pure $ List [val, bindingsToRadicle st']
xs -> throwErrorHere $ WrongNumberOfArgs "base-eval" 2 (length xs)
)
, ( "pure-env"
, "Returns a pure initial radicle state. This is the state of a radicle\
\ chain before it has processed any inputs."
, \case
- [] -> pure $ toRad (pureEnv :: Bindings (PrimFns m))
+ [] -> pure $ bindingsToRadicle (pureEnv :: Bindings (PrimFns m))
xs -> throwErrorHere $ WrongNumberOfArgs "pure-env" 0 (length xs)
)
, ("apply"
@@ -96,17 +95,12 @@ purePrimFns = fromList $ allDocs $
, ("get-current-env"
, "Returns the current radicle state."
, \case
- [] -> toRad <$> get
+ [] -> gets bindingsToRadicle
xs -> throwErrorHere $ WrongNumberOfArgs "get-current-env" 0 (length xs))
, ( "set-current-env"
, "Replaces the radicle state with the one provided."
, oneArg "set-current-env" $ \x -> do
- e' :: Bindings () <- fromRadOtherErr x
- e <- get
- put e { bindingsEnv = bindingsEnv e'
- , bindingsNextRef = bindingsNextRef e'
- , bindingsRefs = bindingsRefs e'
- }
+ setBindings x
pure ok
)
, ("list"
@@ -257,6 +251,17 @@ purePrimFns = fromList $ allDocs $
pure . Dict . Map.fromList $ zip (fst <$> kvs) vs
(_, v) -> throwErrorHere $ TypeError "map-values" 1 TDict v
)
+ , ( "map-keys"
+ , "Given a function `f` and a dict `d`, returns a dict with the same values as `d`\
+ \ but `f` applied to all the keys.\
+ \ If `f` maps two keys to the same thing, the greatest key and value are kept."
+ , twoArg "map-keys" $ \case
+ (f, Dict m) -> do
+ let kvs = Map.toList m
+ vs <- traverse (\v -> callFn f [v]) (fst <$> kvs)
+ dict . Map.fromList $ zip vs (snd <$> kvs)
+ (_, v) -> throwErrorHere $ TypeError "map-keys" 1 TDict v
+ )
-- Structures
, ( "<>"
@@ -289,6 +294,15 @@ purePrimFns = fromList $ allDocs $
Just (v, _, i) -> throwErrorHere $ TypeError "string-append" i TString v
Nothing -> pure . String . mconcat $ catMaybes $ (\(_,x,_) -> x) <$> ss
)
+ , ( "string-replace"
+ , "Replace all occurrences of the first argument with the second in the third."
+ , \case
+ [String old, String new, String str] -> pure $ String $ T.replace old new str
+ [String _, String _, v] -> throwErrorHere $ TypeError "string-replace" 2 TString v
+ [String _, v, _] -> throwErrorHere $ TypeError "string-replace" 1 TString v
+ [v, _, _] -> throwErrorHere $ TypeError "string-replace" 0 TString v
+ xs -> throwErrorHere $ WrongNumberOfArgs "string-replace" 3 (length xs)
+ )
, ( "insert"
, "Given `k`, `v` and a dict `d`, returns a dict with the same associations\
\ as `d` but with `k` associated to `d`. If `d` isn't a dict or if `k` isn't\
diff --git a/src/Radicle/Internal/Type.hs b/src/Radicle/Internal/Type.hs
index d96d5c5..5e9aded 100644
--- a/src/Radicle/Internal/Type.hs
+++ b/src/Radicle/Internal/Type.hs
@@ -17,6 +17,8 @@ data Type
| TDict
| TStructure
| TRef
+ | THandle
+ | TProcHandle
deriving (Eq, Show, Read, Generic)
instance Serialise Type
diff --git a/test/spec/Radicle/Internal/Arbitrary.hs b/test/spec/Radicle/Internal/Arbitrary.hs
index d955318..c28b258 100644
--- a/test/spec/Radicle/Internal/Arbitrary.hs
+++ b/test/spec/Radicle/Internal/Arbitrary.hs
@@ -64,7 +64,8 @@ instance Arbitrary a => Arbitrary (Bindings a) where
refs <- arbitrary
env <- arbitrary
prims <- arbitrary
- pure $ Bindings env prims (IntMap.fromList $ zip [0..] refs) (length refs)
+ pure $ Bindings env prims (IntMap.fromList $ zip [0..] refs)
+ (length refs) mempty 0 mempty 0
instance Arbitrary a => Arbitrary (Doc.Docd a) where
arbitrary = Doc.Docd Nothing <$> arbitrary
diff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hs
index ac496be..e186c5f 100644
--- a/test/spec/Radicle/Internal/TestCapabilities.hs
+++ b/test/spec/Radicle/Internal/TestCapabilities.hs
@@ -10,7 +10,7 @@ import qualified Data.Sequence as Seq
import qualified Data.Time as Time
import GHC.Exts (fromList)
import qualified System.FilePath.Find as FP
-import qualified Data.Time as Time
+import System.IO.Unsafe (unsafePerformIO)
import Radicle
import Radicle.Internal.Core (addBinding)
@@ -36,16 +36,16 @@ data WorldState = WorldState
}
-type TestLang = Lang (State WorldState)
+type TestLang = Lang (StateT WorldState IO)
-- | Run a possibly side-effecting program with the given stdin input lines.
runTestWithFiles
- :: Bindings (PrimFns (State WorldState))
+ :: Bindings (PrimFns (StateT WorldState IO))
-> [Text] -- The stdin (errors if it runs out)
-> Map Text Text -- The files
-> Text -- The program
- -> (Either (LangError Value) Value, [Text])
-runTestWithFiles bindings inputs files action =
+ -> IO (Either (LangError Value) Value, [Text])
+runTestWithFiles bindings inputs files action = do
let ws = WorldState
{ worldStateStdin = inputs
, worldStateStdout = []
@@ -56,15 +56,15 @@ runTestWithFiles bindings inputs files action =
, worldStateRemoteChains = mempty
, worldStateCurrentTime = Time.UTCTime (Time.ModifiedJulianDay 0) 0
}
- in case runState (fmap fst $ runLang bindings $ interpretMany "[test]" action) ws of
- (val, st) -> (val, worldStateStdout st)
+ (val, st) <- runStateT (fmap fst $ runLang bindings $ interpretMany "[test]" action) ws
+ pure (val, worldStateStdout st)
-- | Run a possibly side-effecting program with the given stdin input lines.
runTestWith
- :: Bindings (PrimFns (State WorldState))
+ :: Bindings (PrimFns (StateT WorldState IO))
-> [Text] -- The stdin (errors if it runs out)
-> Text -- The program
- -> (Either (LangError Value) Value, [Text])
+ -> IO (Either (LangError Value) Value, [Text])
runTestWith bindings inputs action = runTestWithFiles bindings inputs mempty action
-- | Like `runTestWith`, but uses the pureEnv
@@ -72,18 +72,18 @@ runTestWith'
:: [Text]
-> Text
-> (Either (LangError Value) Value, [Text])
-runTestWith' = runTestWith pureEnv
+runTestWith' a b = unsafePerformIO $ runTestWith pureEnv a b
-- | Run a test without stdin/stdout
runTest
- :: Bindings (PrimFns (State WorldState))
+ :: Bindings (PrimFns (StateT WorldState IO))
-> Text
- -> Either (LangError Value) Value
-runTest bnds prog = fst $ runTestWith bnds [] prog
+ -> IO (Either (LangError Value) Value)
+runTest bnds prog = fst <$> runTestWith bnds [] prog
-- | Like 'runTest', but uses the pureEnv
runTest' :: Text -> Either (LangError Value) Value
-runTest' = runTest pureEnv
+runTest' a = unsafePerformIO $ runTest pureEnv a
-- | The radicle source files, along with their directory.
sourceFiles :: IO (FilePath, [FilePath])
@@ -94,13 +94,13 @@ sourceFiles = do
-- | Bindings with REPL and client stuff mocked, and with -- a 'test-env__'
-- variable set to true.
-testBindings :: Bindings (PrimFns (State WorldState))
+testBindings :: Bindings (PrimFns (StateT WorldState IO))
testBindings
= addBinding (unsafeToIdent "test-env__") Nothing (Boolean True)
$ addPrimFns clientPrimFns replBindings
-- | Mocked versions of 'send!' and 'receive!'
-clientPrimFns :: PrimFns (State WorldState)
+clientPrimFns :: PrimFns (StateT WorldState IO)
clientPrimFns = fromList . allDocs $ [sendPrimop, receivePrimop]
where
sendPrimop =
@@ -151,14 +151,14 @@ instance {-# OVERLAPPING #-} ReadFile TestLang where
Just f -> pure $ Right f
Nothing -> throwErrorHere . OtherError $ "File not found: " <> fn
-instance MonadRandom (State WorldState) where
+instance Monad m => MonadRandom (StateT WorldState m) where
getRandomBytes i = do
drg <- gets worldStateDRG
let (a, drg') = CryptoRand.randomBytesGenerate i drg
modify $ \ws -> ws { worldStateDRG = drg' }
pure a
-instance UUID.MonadUUID (State WorldState) where
+instance Monad m => UUID.MonadUUID (StateT WorldState m) where
uuid = do
i <- gets worldStateUUID
modify $ \ws -> ws { worldStateUUID = i + 1 }
@@ -167,5 +167,11 @@ instance UUID.MonadUUID (State WorldState) where
prefix = "00000000-0000-0000-0000-"
pad i = toS $ prefix <> replicate (12 - length i) '0' <> i
-instance CurrentTime (State WorldState) where
- currentTime = gets worldStateCurrentTime
+instance CurrentTime (StateT WorldState IO) where
+ currentTime = gets worldStateCurrentTime
+
+instance System (StateT WorldState IO) where
+ systemS proc = lift $ systemS proc
+ waitForProcessS = lift . waitForProcessS
+ hPutStrS a b = lift $ hPutStrS a b
+ hGetLineS = lift . hGetLineS
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index fe9104f..eaab92b 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -11,6 +11,8 @@ import Data.String.Interpolate (i)
import Data.String.QQ (s)
import qualified Data.Text as T
import GHC.Exts (fromList, toList)
+import System.IO.Unsafe (unsafePerformIO)
+import System.Process (CmdSpec(..), StdStream(..))
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck
@@ -613,7 +615,8 @@ test_repl_primops :: [TestTree]
test_repl_primops =
[ testProperty "(read (get-line!)) returns the input line" $ \(v :: Value) ->
let prog = [i|(eq? (read (get-line!)) (quote #{renderPrettyDef v}))|]
- res = run [renderPrettyDef v] $ toS prog
+ -- We're not actually using IO
+ res = unsafePerformIO $ run [renderPrettyDef v] $ toS prog
in counterexample prog $ res == Right (Boolean True)
, testCase "catch catches read-line errors" $ do
@@ -621,20 +624,22 @@ test_repl_primops =
(catch 'any (read-line!) (fn [x] "caught"))
|]
input = ["\"blah"]
- res = run input prog
+ res <- run input prog
res @?= Right (String "caught")
, testCase "read-file! can read a file" $ do
let prog = "(read-file! \"foobar.rad\")"
files = Map.singleton "foobar.rad" "foobar"
- runFiles files prog @?= Right (String "foobar")
+ res <- runFiles files prog
+ res @?= Right (String "foobar")
, testCase "load! can load definitions" $ do
let prog = [s|
(load! "foo.rad")
(+ foo bar)
|]
files = Map.singleton "foo.rad" "(def foo 42) (def bar 8)"
- runFiles files prog @?= Right (int 50)
- , testCase "generating and verifying cryptographic signatures works" $
+ res <- runFiles files prog
+ res @?= Right (int 50)
+ , testCase "generating and verifying cryptographic signatures works" $ do
let prog = [s|
(def my-keys (gen-key-pair! (default-ecc-curve)))
(def not-my-keys (gen-key-pair! (default-ecc-curve)))
@@ -643,15 +648,17 @@ test_repl_primops =
(def ff (verify-signature (lookup :public-key not-my-keys) sig "hello"))
(list tt ff)
|]
- in run [] prog @?= Right (List [Boolean True, Boolean False])
- , testCase "uuid! generates a valid uuid" $
+ res <- run [] prog
+ res @?= Right (List [Boolean True, Boolean False])
+ , testCase "uuid! generates a valid uuid" $ do
let prog = [s| (uuid? (uuid!)) |]
- in run [] prog @?= Right (Boolean True)
+ res <- run [] prog
+ res @?= Right (Boolean True)
]
where
- run stdin' prog = fst $ runTestWith testBindings stdin' prog
- runFiles :: Map Text Text -> Text -> Either (LangError Value) Value
- runFiles files prog = fst $ runTestWithFiles testBindings [] files prog
+ run stdin' prog = fst <$> runTestWith testBindings stdin' prog
+ runFiles :: Map Text Text -> Text -> IO (Either (LangError Value) Value)
+ runFiles files prog = fst <$> runTestWithFiles testBindings [] files prog
test_repl :: [TestTree]
test_repl =
@@ -708,10 +715,6 @@ test_from_to_radicle =
[ testForType (Proxy :: Proxy ()) ]
, testGroup "(Foo, Foo)"
[ testForType (Proxy :: Proxy (Foo, Foo)) ]
- , testGroup "Env Value"
- [ testForType (Proxy :: Proxy (Env Value)) ]
- , testGroup "Bindings ()"
- [ testForType (Proxy :: Proxy (Bindings ())) ]
, testGroup "Scientific"
[ testForType (Proxy :: Proxy Scientific) ]
, testGroup "Text"
@@ -722,10 +725,29 @@ test_from_to_radicle =
[ testForType (Proxy :: Proxy [Text]) ]
, testGroup "Generic a => a"
[ testForType (Proxy :: Proxy Foo) ]
+
+ , testGroup "StdStream"
+ [ kw "inherit" ~~ Inherit
+ , kw "create-pipe" ~~ CreatePipe
+ , kw "no-stream" ~~ NoStream
+ ]
+
+ , testGroup "CmdSpec"
+ [ Vec (fromList [kw "shell", String "blah blah"]) ~~ ShellCommand "blah blah"
+ , Vec (fromList [kw "raw", String "blah", Vec $ fromList [String "blah", String "blah"]])
+ ~~ RawCommand "blah" ["blah", "blah"]
+ ]
]
where
+ (~~)
+ :: (FromRad Ann.WithPos a, ToRad Ann.WithPos a, Eq a, Show a)
+ => Value -> a -> TestTree
+ v ~~ v' =
+ testCase ("works on " <> show v') $ do
+ fromRad v @?= Right v'
+ untag (toRad v' :: Value) @?= untag v
testForType
- :: forall a. (Arbitrary a, Show a, ToRad Ann.WithPos a, FromRad Ann.WithPos a, Eq a)
+ :: forall a . (Arbitrary a, Show a, ToRad Ann.WithPos a, FromRad Ann.WithPos a, Eq a)
=> Proxy a -> TestTree
testForType _ =
testProperty "fromRadicle . toRadicle == id" $ \(v :: a ) -> do
@@ -771,15 +793,17 @@ test_source_files = do
contents <- readFile (dir <> f)
pure (toS f, contents)
contents <- readFile (dir <> file)
- let keyPair :: Text = case runTest testBindings "(gen-key-pair! (default-ecc-curve))" of
- Right kp -> renderCompactPretty kp
- Left _ -> panic "Couldn't generate keypair file."
- let (r, out) = runTestWithFiles testBindings [] (Map.insert "my-keys.rad" keyPair (fromList allFiles)) contents
+ keyPair :: Text <- runTest testBindings "(gen-key-pair! (default-ecc-curve))" >>= \case
+ Right kp -> pure $ renderCompactPretty kp
+ Left _ -> panic "Couldn't generate keypair file."
+ (r, out) <- runTestWithFiles testBindings []
+ (Map.insert "my-keys.rad" keyPair (fromList allFiles))
+ contents
let makeTest line =
let name = T.reverse $ T.drop 1 $ T.dropWhile (/= '\'')
$ T.reverse $ T.drop 1 $ T.dropWhile (/= '\'') line
in testCase (toS name) $
- if "' succeeded\"" `T.isSuffixOf` line
+ if "' succeeded" `T.isSuffixOf` line
then pure ()
else assertFailure . toS $ "test failed: " <> line
let doesntThrow = if isRight r
@@ -787,7 +811,7 @@ test_source_files = do
else assertFailure $ "Expected Right, got: " <> toS (prettyEither r)
pure $ [testGroup file
$ testCase "doesn't throw" doesntThrow
- : [ makeTest ln | ln <- reverse out, "\"Test" `T.isPrefixOf` ln ]]
+ : [ makeTest ln | ln <- reverse out, "Test" `T.isPrefixOf` ln ]]
test_macros :: [TestTree]
test_macros =
@@ -813,8 +837,8 @@ atom = Atom . unsafeToIdent
int :: Integer -> Value
int = Number . fromIntegral
--- -- | Like 'parse', but uses "(test)" as the source name and the default set of
--- -- primops.
+-- | 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
@@ -831,7 +855,7 @@ assertReplInteraction :: [Text] -> [Text] -> IO ()
assertReplInteraction input expected = do
(dir, srcs) <- sourceFiles
srcMap <- forM srcs (\src -> (T.pack src ,) <$> readFile (dir <> src))
- let (result, output) = runTestWithFiles testBindings input (Map.fromList srcMap) "(load! \"rad/repl.rad\")"
+ (result, output) <- runTestWithFiles testBindings input (Map.fromList srcMap) "(load! \"rad/repl.rad\")"
case result of
Left err -> assertFailure $ "Error thrown in Repl: " <> toS (renderPrettyDef err)
Right _ -> pure ()
diff --git a/utils/list-issues b/utils/list-issues
new file mode 100755
index 0000000..f9a79fd
--- /dev/null
+++ b/utils/list-issues
@@ -0,0 +1,29 @@
+#!/usr/bin/env bash
+
+FILE="$(mktemp)"
+cat << SRC > $FILE
+(load! "rad/monadic/issues.rad")
+
+(def mk-key (fn [v]
+ (def key (nth 0 v))
+ (def val (nth 1 v))
+ [(string-append (show key) " - " (lookup :title val)) val]))
+(def iss (dict-from-list (map mk-key (seq (list-issues)))))
+(def selected (fzf-select-by-key! iss))
+(def pretty-comment (fn [c]
+ (string-append
+ (lookup :github-username c) "[" (lookup :created-at c) "]: "
+ (lookup :body c)
+ "\n\n")))
+(def pretty-issue (fn [i]
+ (string-append
+ "Issue " (show (lookup :number i)) " : " (lookup :title i)
+ "\nDescription: " (lookup :body i)
+ "\nState: " (if (eq? (lookup :state i) :open) "open" "closed")
+ "\nLabels: " (show (lookup :labels i))
+ "\nComments:\n\n\n" (lines (map pretty-comment (lookup :comments i)))
+)))
+(put-str! (pretty-issue selected))
+SRC
+radicle -- $FILE | less
+
diff --git a/utils/new-issue b/utils/new-issue
new file mode 100755
index 0000000..2332cbe
--- /dev/null
+++ b/utils/new-issue
@@ -0,0 +1,21 @@
+#!/usr/bin/env bash
+
+TEMPLATE="$(mktemp)"
+cat << SRC > $TEMPLATE
+;; Issue template. An empty or invalid value will abort.
+{:title "Pick a title"
+ :body "Pick a body"
+ :labels []
+ :state :open
+ :comments []
+ :created-at (now!)}
+SRC
+
+SRC_FILE="$(mktemp)"
+cat << SRC > $SRC_FILE
+(load! "rad/monadic/issues.rad")
+(create-issue!
+ $(cat $TEMPLATE | vipe))
+SRC
+radicle $SRC_FILE
+