A peer-to-peer stack for code collaboration
Demo
Julian Arnib3fe7057e2b4
diff --git a/.gitignore b/.gitignoreindex 072b493..2c2b5fe 100644--- a/.gitignore+++ b/.gitignore@@ -5,7 +5,7 @@ radicle.cabal*.hi*.chi*.chs.h-.virthualenv.hsenv.cabal-sandbox/cabal.sandbox.config+out/diff --git a/.stylish-haskell.yaml b/.stylish-haskell.yamlindex 027a6b7..d2eff5b 100644--- a/.stylish-haskell.yaml+++ b/.stylish-haskell.yaml@@ -179,6 +179,7 @@ newline: nativelanguage_extensions:- FlexibleContexts- FunctionalDependencies+ - LambdaCase- MultiParamTypeClasses- MultiWayIf- RecordWildCardsdiff --git a/repl/Main.hs b/exe/Repl/Main.hssimilarity index 61%rename from repl/Main.hsrename to exe/Repl/Main.hsindex 4b984d7..18d623c 100644--- a/repl/Main.hs+++ b/exe/Repl/Main.hs@@ -1,9 +1,7 @@module Main (main) whereimport Protolude-import Options.Applicative-import System.Environmentimport Radicle@@ -16,7 +14,7 @@ main = dohist <- case histFile opts' ofNothing -> getHistoryJust h -> pure h- repl hist cfgSrc+ repl (Just hist) cfgSrc replBindingswhereallOpts = info (opts <**> helper)( fullDesc@@ -24,22 +22,6 @@ main = do<> header "rad - The radicle REPL")--- | Uses XDG_CONFIG_HOME if available.-getConfig :: IO FilePath-getConfig = do- mCfgHome <- lookupEnv "XDG_CONFIG_HOME"- pure $ case mCfgHome of- Nothing -> "$HOME/.config/rad/config.rad"- Just cfgHome -> cfgHome <> "/rad/config.rad"---- | Uses XDG_CACHE_HOME if available.-getHistory :: IO FilePath-getHistory = do- mCfgHome <- lookupEnv "XDG_CACHE_HOME"- pure $ case mCfgHome of- Nothing -> "$HOME/.cache/rad/history"- Just cfgHome -> cfgHome <> "/rad/history"-data Opts = Opts{ configFile :: Maybe FilePath, histFile :: Maybe FilePathdiff --git a/exe/Server/API.hs b/exe/Server/API.hsnew file mode 100644index 0000000..7650171--- /dev/null+++ b/exe/Server/API.hs@@ -0,0 +1,23 @@+{-# OPTIONS_GHC -fno-warn-orphans #-}+module API where++import Protolude+import Radicle+import Servant.API+import qualified Data.ByteString.Lazy as LBS+import qualified Data.Text as T++instance Show a => MimeRender PlainText a where+ mimeRender _ x = show x++instance Read a => MimeUnrender PlainText a where+ mimeUnrender _ x = readEither $ T.unpack $ decodeUtf8 $ LBS.toStrict x++type API+ = "submit" :> ReqBody '[PlainText] Value :> Post '[PlainText] ()+ :<|> "since" :> Capture "chain" Text :> Capture "index" Int :> Get '[PlainText] [Value]+ :<|> "outputs" :> Capture "chain" Text :> Get '[JSON, PlainText] [Maybe DataValue]+ :<|> Raw++api :: Proxy API+api = Proxydiff --git a/exe/Server/Client.hs b/exe/Server/Client.hsnew file mode 100644index 0000000..5e78ff0--- /dev/null+++ b/exe/Server/Client.hs@@ -0,0 +1,112 @@+module Client where++import API+import Data.Scientific (floatingOrInteger)+import GHC.Exts (fromList)+import Network.HTTP.Client (defaultManagerSettings, newManager)+import Options.Applicative+import Protolude hiding (TypeError, option)+import Radicle+import Servant.API ((:<|>)(..))+import Servant.Client+import System.Console.Haskeline (InputT)++main :: IO ()+main = do+ opts' <- execParser allOpts+ cfgSrc <- readFile =<< case configFile opts' of+ Nothing -> getConfig+ Just cfg -> pure cfg+ hist <- case histFile opts' of+ Nothing -> getHistory+ Just h -> pure h+ mgr <- newManager defaultManagerSettings+ let cEnv = mkClientEnv mgr (serverURL opts')+ repl (Just hist) cfgSrc (bindings cEnv)+ where+ allOpts = info (opts <**> helper)+ ( fullDesc+ <> progDesc "Run the radicle REPL"+ <> header "rad - The radicle REPL"+ )++-- * CLI Opts++data Opts = Opts+ { configFile :: Maybe FilePath+ , serverURL :: BaseUrl+ , histFile :: Maybe FilePath+ }++opts :: Parser Opts+opts = Opts+ <$> optional (strOption+ ( long "config"+ <> metavar "FILE"+ <> help "rad configuration file"+ ))+ <*> option (str >>= parseBaseUrl')+ ( long "url"+ <> metavar "URL"+ <> help "URL of server"+ )+ <*> optional (strOption+ ( long "histfile"+ <> metavar "FILE"+ <> help "repl history file"+ ))+ where+ parseBaseUrl' x = case parseBaseUrl x of+ Nothing -> readerError "can't parse URL"+ Just v -> pure v++-- * Primops++bindings :: ClientEnv -> Bindings (InputT IO)+bindings cEnv = e { bindingsPrimops = bindingsPrimops e <> primops cEnv }+ where+ e :: Bindings (InputT IO)+ e = pureEnv++primops :: ClientEnv -> Primops (InputT IO)+primops cEnv = fromList [sendPrimop, receivePrimop] <> replPrimops+ where+ sendPrimop =+ ( Ident "send!"+ , evalArgs $ \case+ [String name, v] -> do+ res <- liftIO $ runClientM (submit $ List $ [String name, v]) cEnv+ case res of+ Left e -> throwError . OtherError+ $ "send!: failed:" <> show e+ Right () -> pure $ List []+ [_, _] -> throwError $ TypeError "send!: first argument should be a string"+ xs -> throwError $ WrongNumberOfArgs "send!" 2 (length xs)+ )+ receivePrimop =+ ( Ident "receive!"+ , evalArgs $ \case+ [String name, Number n] -> do+ case floatingOrInteger n of+ Left (_ :: Float) -> throwError . OtherError+ $ "receive!: expecting int argument"+ Right r -> do+ liftIO (runClientM (since name r) cEnv) >>= \case+ Left err -> throwError . OtherError+ $ "receive!: request failed:" <> show err+ Right v' -> pure $ List v'+ [String _, _] -> throwError $ TypeError "receive!: expecting number as second arg"+ [_, _] -> throwError $ TypeError "receive!: expecting string as first arg"+ xs -> throwError $ WrongNumberOfArgs "receive!" 2 (length xs)+ )++-- * Helpers++identV :: Text -> Value+identV = Keyword . Ident++-- * Client functions++submit :: Value -> ClientM ()+since :: Text -> Int -> ClientM [Value]+submit :<|> since :<|> _ = client apidiff --git a/exe/Server/GHCJS.hs b/exe/Server/GHCJS.hsnew file mode 100644index 0000000..31a6953--- /dev/null+++ b/exe/Server/GHCJS.hs@@ -0,0 +1,112 @@+{-# OPTIONS_GHC -fno-warn-deprecations #-}+module GHCJS where++import Protolude hiding (TypeError)++import API+import Data.IORef+import qualified Data.JSString as JSS+import Data.Scientific (floatingOrInteger)+import qualified Data.Text as T+import GHC.Exts (fromList)+import GHCJS.Foreign.Callback (Callback, OnBlocked(..), syncCallback1)+import GHCJS.Marshal+import GHCJS.Types+import JavaScript.Object (getProp, setProp)+import JavaScript.Object.Internal (Object(..))+import Radicle+import Servant.API ((:<|>)(..))+import Servant.Client.Ghcjs+import System.Console.Haskeline (InputT, defaultSettings, runInputT)++main :: IO ()+main = do+ bndsRef <- newIORef bindings+ res <- runInputT defaultSettings+ $ runLang bindings+ $ interpretMany "[repl]" "(load! \"rad/prelude.rad\")"+ case res of+ (Left err, _) -> liftIO $ print $ renderPrettyDef err+ (Right _, newBnds) -> liftIO $ writeIORef bndsRef newBnds+ cb <- syncCallback1 ContinueAsync (jsEval bndsRef)+ js_set_eval cb++-- * FFI++foreign import javascript unsafe "eval_fn_ = $1"+ js_set_eval :: Callback a -> IO ()++-- * Export++-- | Interop with JS is quite nasty. We take a JS object, expecting the 'arg'+-- property to be set to the argument, and we set the 'result' property of it+-- with the result.+--+-- The IORef keeps the state/env of the REPL so far.+jsEval :: IORef (Bindings (InputT IO)) -> JSVal -> IO ()+jsEval bndsRef v = runInputT defaultSettings $ do+ let o = Object v+ ms <- liftIO $ fromJSVal =<< getProp "arg" o+ let s = case ms of+ Just s' -> s'+ _ -> error "expecting 'arg' key"+ bnds <- liftIO $ readIORef bndsRef+ res <- runLang bnds $ interpretMany "[repl]" s+ out <- JSS.pack . T.unpack <$> case res of+ (Left err, _) -> pure $ renderPrettyDef err+ (Right v', newBnds) -> do+ _ <- liftIO $ writeIORef bndsRef newBnds+ pure $ renderPrettyDef v'+ sout <- liftIO $ toJSVal out+ liftIO $ setProp "result" sout o++-- * Primops++bindings :: Bindings (InputT IO)+bindings = e { bindingsPrimops = bindingsPrimops e <> primops }+ where+ e :: Bindings (InputT IO)+ e = pureEnv++primops :: Primops (InputT IO)+primops = fromList [sendPrimop, receivePrimop] <> replPrimops+ where+ sendPrimop =+ ( Ident "send!"+ , evalArgs $ \case+ [String name, v] -> do+ res <- liftIO $ runClientM (submit $ List $ [String name, v])+ case res of+ Left e -> throwError . OtherError+ $ "send!: failed:" <> show e+ Right () -> pure $ List []+ [_, _] -> throwError $ TypeError "send!: first argument should be a string"+ xs -> throwError $ WrongNumberOfArgs "send!" 2 (length xs)+ )+ receivePrimop =+ ( Ident "receive!"+ , evalArgs $ \case+ [String name, Number n] -> do+ case floatingOrInteger n of+ Left (_ :: Float) -> throwError . OtherError+ $ "receive!: expecting int argument"+ Right r -> do+ liftIO (runClientM (since name r)) >>= \case+ Left err -> throwError . OtherError+ $ "receive!: request failed:" <> show err+ Right v' -> pure $ List v'+ [String _, _] -> throwError $ TypeError "receive!: expecting number as second arg"+ [_, _] -> throwError $ TypeError "receive!: expecting string as first arg"+ xs -> throwError $ WrongNumberOfArgs "receive!" 2 (length xs)+ )++-- * Helpers++identV :: Text -> Value+identV = Keyword . Ident++-- * Client functions++submit :: Value -> ClientM ()+since :: Text -> Int -> ClientM [Value]+submit :<|> since :<|> _ = client apidiff --git a/exe/Server/Server.hs b/exe/Server/Server.hsnew file mode 100644index 0000000..31eb793--- /dev/null+++ b/exe/Server/Server.hs@@ -0,0 +1,100 @@+module Server where++import API+import Data.ByteString.Lazy (fromStrict)+import qualified Data.Sequence as Seq+import Network.Wai.Handler.Warp+import Network.Wai.Middleware.Cors+import Network.Wai.Middleware.Gzip+import Protolude hiding (fromStrict)+import Radicle+import Servant+import qualified STMContainers.Map as STMMap++-- * Main++main :: IO ()+main = do+ st <- newState+ let gzipSettings = def { gzipFiles = GzipPreCompressed GzipIgnore }+ app = simpleCors $ gzip gzipSettings (serve api (server st))+ args <- getArgs+ case args of+ [portStr] -> case readEither portStr of+ Right port -> run port app+ Left _ -> die "Expecting argument to be a port (integer)"+ [] -> run 80 app+ _ -> die "Expecting zero or one arguments (port)"+++server :: Chains -> Server API+server st = submit st :<|> since st :<|> jsonOutputs st :<|> static++-- * Handlers++-- | Submit something to a chain. The value is expected to be a pair, with the+-- first item specifying the chain the value is being submitted to, and the+-- second the expression being submitted.+submit :: Chains -> Value -> Handler ()+submit st val = case val of+ List [String i, v] -> do+ r <- liftIO . atomically $ insertExpr st i v+ case r of+ Right () -> pure ()+ Left err -> throwError+ $ err400 { errBody = fromStrict $ encodeUtf8 err }+ _ -> throwError+ $ err400 { errBody = "Expecting pair with chain name and val" }++getActivitySince :: Chains -> Text -> Int -> Handler [(Value, Value)]+getActivitySince st name index = do+ r <- liftIO . atomically $ getSince st name index+ case r of+ Nothing -> throwError $ err400 { errBody = "No such chain/index" }+ Just v -> pure v++-- | Get all expressions submitted to a chain since 'index'.+since :: Chains -> Text -> Int -> Handler [Value]+since st name index =+ fmap fst <$> getActivitySince st name index++jsonOutputs :: Chains -> Text -> Handler [Maybe DataValue]+jsonOutputs st name = do+ vs <- fmap snd <$> getActivitySince st name 0+ pure (isData <$> vs)++static :: Server Raw+static = serveDirectoryFileServer "static/"++-- * Helpers++insertExpr :: Chains -> Text -> Value -> STM (Either Text ())+insertExpr st name val = do+ x <- STMMap.lookup name $ getChains st+ let chain = fromMaybe (Chain name pureEnv mempty) x+ let (r, s) = runIdentity $ runLang (chainState chain) (eval val)+ case r of+ Left e -> pure . Left $ "invalid expression: " <> show e+ Right o -> Right <$> STMMap.insert+ (chain { chainState = s+ , chainExprs = chainExprs chain Seq.|> (val, o) })+ name+ (getChains st)++getSince :: Chains -> Text -> Int -> STM (Maybe [(Value, Value)])+getSince st name index = do+ x <- STMMap.lookup name $ getChains st+ pure $ toList . Seq.drop index . chainExprs <$> x++-- * Types++data Chain = Chain+ { chainName :: Text+ , chainState :: Bindings Identity+ , chainExprs :: Seq (Value, Value)+ } deriving (Generic)++newtype Chains = Chains { getChains :: STMMap.Map Text Chain }++newState :: IO Chains+newState = Chains <$> STMMap.newIOdiff --git a/package.yaml b/package.yamlindex ef69642..74b62e6 100644--- a/package.yaml+++ b/package.yaml@@ -11,6 +11,7 @@ extra-source-files:dependencies:- base >=4 && <5- protolude+- aeson- containers- deriving-compat- haskeline@@ -20,28 +21,34 @@ dependencies:- prettyprinter-ansi-terminal- recursion-schemes- scientific+- serialise- text+- unordered-containers+when:+ - condition: impl(ghcjs)+ dependencies: ghcjs-dom+ghc-options:+ -Wall -Wcompat -Wincomplete-record-updates -Wincomplete-uni-patterns -Wredundant-constraintsdata-files:-- repl/config.rad-- repl/prelude.rad+- rad/**/*.radlibrary:source-dirs: src- ghc-options: -Walltests:spec:main: Main.hssource-dirs:- test/spec- ghc-options: -Wall -threaded+ ghc-options: -threadeddependencies:- radicle- directory+ - filemanip+ - interpolate- QuickCheck- quickcheck-instances- - interpolate- safe- string-qq- tasty@@ -52,7 +59,7 @@ tests:main: Main.hssource-dirs:- test/docs- ghc-options: -Wall -threaded+ ghc-options: -threadedother-modules:- Paths_radicledependencies:@@ -64,31 +71,94 @@ tests:executables:repl:main: Main.hs- source-dirs: repl+ source-dirs: exe/Repl+ when:+ - condition: impl(ghcjs)+ buildable: false+ dependencies:+ - radicle+ - optparse-applicative+ ghc-options: -threaded -O3++ server:+ main: Server.hs+ source-dirs: exe/Server+ other-modules: API+ when:+ - condition: impl(ghcjs)+ buildable: falsedependencies:- radicle- optparse-applicative- ghc-options: -Wall -threaded -Wcompat -Wincomplete-record-updates -Wincomplete-uni-patterns -Wredundant-constraints+ - bytestring+ - servant+ - servant-server+ - stm-containers+ - stm+ - warp+ - wai-extra+ - wai-cors+ ghc-options: -main-is Server -O3 -threaded++ client:+ main: Client.hs+ source-dirs: exe/Server+ other-modules: API+ dependencies:+ - radicle+ - exceptions+ - optparse-applicative+ - bytestring+ - servant+ - http-media+ - http-client+ - servant-client+ when:+ - condition: impl(ghcjs)+ buildable: false+ ghc-options: -main-is Client -O3 -threaded++ client-ghcjs:+ main: GHCJS.hs+ source-dirs: exe/Server+ other-modules: API+ dependencies:+ - radicle+ - ghcjs-base+ - exceptions+ - bytestring+ - servant+ - servant-client-ghcjs+ - http-media+ when:+ - condition: impl(ghcjs)+ then:+ buildable: true+ else:+ buildable: false+ ghc-options: -main-is GHCJS -threadeddefault-extensions:-- NoImplicitPrelude- AutoDeriveTypeable- ConstraintKinds+- DataKinds- DeriveDataTypeable-- DeriveFunctor- DeriveFoldable-- DeriveTraversable+- DeriveFunctor- DeriveGeneric+- DeriveTraversable- FlexibleContexts- FlexibleInstances- FunctionalDependencies- GeneralizedNewtypeDeriving+- LambdaCase- MultiParamTypeClasses+- NoImplicitPrelude- OverloadedStrings- RankNTypes- RecordWildCards+- ScopedTypeVariables+- StandaloneDeriving- TupleSections- TypeFamilies- TypeOperators-- ScopedTypeVariables-- LambdaCasediff --git a/rad/chain.rad b/rad/chain.radnew file mode 100644index 0000000..4850f43--- /dev/null+++ b/rad/chain.rad@@ -0,0 +1,91 @@+"not a comment"++;; Chains: Functions for dealing with chains.++;; A chain is conceptually:+;; - A known starting state (i.e. environment, and the assumption that `eval+;; == base-eval')+;; - A sequence of inputs.++(define empty-chain+ (dict :state (pure-env)+ :inputs (list)+ :index 0))++(define eval-in-chain+ (lambda (expr chain)+ (define x (eval-with-env expr (lookup :state chain)))+ (dict :chain (dict :state (head (tail x))+ :input (cons expr (lookup :logs chain))+ :index (+ 1 (lookup :index chain)))+ :result (head x))))++(document 'eval-in-chain+ '(("expr" any) ("chain" chain))+ "Evaluates 'expr' in the 'chain' and returns a dict with the ':result' and the resulting ':chain'.")++(define update-chain-with+ (lambda (chain remote-chain-id cb-expr cb-res)+ (define new-inputs+ (receive! remote-chain-id (lookup :index chain)))+ (define upd-ch+ (lambda (ch expr)+ (define x (eval-in-chain expr ch))+ (cb-expr expr)+ (cb-res (view (@ :result) x))+ (view (@ :chain) x)))+ (foldl upd-ch chain new-inputs)))++(document 'update-chain-with+ '(("chain" chain) ("chain-id" string) ("cb-expr" function) ("cb-res" function))+ "Updates 'chain' according to activity on the remote chain with ID 'chain-id', by pulling down and evaluating new inputs. Accepts two callbacks: 'cb-expr' is applied to the incoming expressions, and 'cb-res' is applied to the resulting values. Usually one uses 'print!' for both of these. If 'chain' is not a past version of the remote chain then the behaviour is unspecified.")++(define enter-chain+ (lambda (eval-definer chain)+ (define old-eval eval)+ (define ch (ref chain))+ (define ev+ (lambda (e)+ (if (eq? e :quit)+ (do (print! "leaving chain")+ (eval-definer old-eval))+ (do (define x (eval-in-chain e (read-ref ch)))+ (write-ref ch (view (@ :chain) x))+ (view (@ :result) x)))))+ (eval-definer ev)))++(document 'enter-chain+ '(("eval-definer" function) ("chain" chain))+ "Instantiates an 'eval' which evaluates expressions in 'chain'. The expression ':quit' will return to the previous eval. Uses the parameter 'eval-definer' for eval redefinition, this should be a function which can be used to redefine 'eval': it should set eval to it's input.")++(define enter-remote-chain+ (lambda (eval-definer chain-id)+ (define old-eval eval)+ (define chain (update-chain-with empty-chain chain-id (lambda (e) '()) (lambda (e) '())))+ (print! (string-append "Synced with remote chain, at index: " (show (view (@ :index) chain))))+ (define ch (ref chain))+ (define inputs (ref (list)))+ (eval-definer+ (lambda (e)+ (cond+ (eq? e :quit) (do (print! "Leaving remote-chain.")+ (eval-definer old-eval))+ (eq? e :send) (do (print! "Sending inputs to remote chain.")+ (map (lambda (i) (send! chain-id i)) (reverse (read-ref inputs)))+ (print! "Done! Leaving remote-chain.")+ (eval-definer old-eval))+ :else (do (define x (eval-in-chain e (read-ref ch)))+ (write-ref ch (view (@ :chain) x))+ (modify-ref inputs (lambda (is) (cons e is)))+ (view (@ :result) x)))))))++(document 'enter-remote-chain+ '(("eval-definer" function) ("chain-id" string))+ "Syncs up to a remote chain, and allows experimentation inputs. There are two special inputs: ':quit' will leave the chain, ':send' will send all the accumulated inputs to the remote chain, one by one, and then leave the chain. Uses the parameter 'eval-definer' for eval redefinition, this should be a function which can be used to redefine 'eval': it should set eval to it's input.")++;; Setup an eval definer+(define boom+ (quote+ (do (define eval-ref (ref eval))+ (define eval-definer (lambda (f) (write-ref eval-ref f)))+ (define eval (lambda (e) ((read-ref eval-ref) e))))))diff --git a/rad/currency.rad b/rad/currency.radnew file mode 100644index 0000000..d682a4c--- /dev/null+++ b/rad/currency.rad@@ -0,0 +1,44 @@+;; Account stuff. Should be moved elsewhere when we have an import mechanism++(define create-currency (lambda ()++ ;; The map of all accounts+ (define accounts (ref (dict)))++ ;; Create an account with 10 coins.+ (define new-account (lambda (name)+ (modify-ref accounts (lambda (acc)+ (insert name 10 acc)))))++ ;; Get an account's balance+ (define account-balance (lambda (name)+ (lookup name (read-ref accounts))))++ ;; Transfer money+ (define transfer (lambda (from to amount)+ (define acc (read-ref accounts))+ (write-ref accounts+ (if (> amount (lookup from acc))+ (print! "not enough balance")+ (modify-map+ to+ (lambda (x) (+ x amount))+ (modify-map from (lambda (x) (- x amount)) acc))))))++ (define dispatch (lambda (m)+ (cond+ (eq? m 'new-account) new-account+ (eq? m 'account-balance) account-balance+ (eq? m 'transfer) transfer+ :else (print! "error: currency- unknown message"))))+ dispatch))++(define currency (create-currency))+++(define new-eval (lambda (expr)+ (cond+ (eq? (head expr) 'new-account) ((currency 'new-account) (nth 1 expr))+ (eq? (head expr) 'account-balance) ((currency 'account-balance) (nth 2 expr))+ (eq? (head expr) 'transfer) ((currency 'transfer) (nth 1 expr) (nth 2 expr) (nth 3 expr)))+ else: (print! "transaction must be new-account, transfer, or account-balance")))diff --git a/rad/issues.rad b/rad/issues.radnew file mode 100644index 0000000..31028fd--- /dev/null+++ b/rad/issues.rad@@ -0,0 +1,47 @@+"not a comment"++;; Issues for rad prelude++(define create-rad-issue-chain (lambda ()+ (define issues (ref nil))+ (define should-be (lambda (name x y) (eq? x y)))+ (define current-prelude (ref (dict :env (dict 'should-be should-be 'eval eval) :refs nil)))+++ (define failing? (lambda (expr)+ (define res (catch 'any+ (head (eval-with-env expr (read-ref current-prelude)))+ (lambda (x) #f)))+ (eq? res #f)))++ (define new-issue (lambda (creator title desc failing-test)+ (if (failing? failing-test)+ (modify-ref+ issues+ (lambda (x)+ (cons (dict+ :creator creator+ :title title+ :description desc+ :failing-test failing-test) x)))+ "Test is not failing")))++ (define list-issues (lambda () (read-ref issues)))++ (define dispatch (lambda (m)+ (cond+ (eq? m 'new-issue) new-issue+ (eq? m 'list-issues) list-issues+ :else "error: unknown message")))++ dispatch))++(define rad-issue-chain (create-rad-issue-chain))++(define rad-issue-chain-eval (lambda (expr)+ (if (eq? (head expr) 'new-issue)+ (apply (rad-issue-chain 'new-issue) (tail expr))+ (if (eq? (head expr) 'list-issues)+ ((rad-issue-chain 'list-issues))+ "must be one of: 'new-issue', 'list-issues'"))+ ))diff --git a/rad/prelude.rad b/rad/prelude.radnew file mode 100644index 0000000..5ea5b2e--- /dev/null+++ b/rad/prelude.rad@@ -0,0 +1,48 @@+(load! "rad/prelude/doc.rad")+(load! "rad/prelude/should-be.rad")+(load! "rad/prelude/io.rad")+(load! "rad/prelude/bool.rad")+(load! "rad/prelude/recursion.rad")+(load! "rad/prelude/list.rad")+(load! "rad/prelude/dict.rad")+(load! "rad/prelude/ref.rad")+(load! "rad/prelude/lens.rad")+(load! "rad/chain.rad")+(load! "rad/state-machine.rad")++(define pure-prelude-files+ (list+ "rad/prelude/doc.rad"+ "rad/prelude/pure-should-be.rad"+ "rad/prelude/recursion.rad"+ "rad/prelude/bool.rad"+ "rad/prelude/list.rad"+ "rad/prelude/dict.rad"+ "rad/prelude/ref.rad"+ "rad/prelude/lens.rad"+ "rad/state-machine.rad"+ ))++(document 'pure-prelude-files+ '()+ "List of files which together define the pure prelude.")++(define pure-prelude-code+ (read+ (string-append+ "(do "+ (apply string-append+ (map (lambda (f) (read-file! f)) pure-prelude-files))+ ")")))++(document 'pure-prelude-code+ '()+ "The pure prelude.")++(define send-prelude!+ (lambda (chain-id)+ (send! chain-id pure-prelude-code)))++(document 'send-prelude!+ '(("chain-id" string))+"Send the pure prelude to a chain.")diff --git a/rad/prelude/bool.rad b/rad/prelude/bool.radnew file mode 100644index 0000000..df42938--- /dev/null+++ b/rad/prelude/bool.rad@@ -0,0 +1,64 @@+"not a comment"++;; boolean functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;++;; not++(define not (lambda (x) (if x #f #t)))++(document 'not+ '(("arg" any))+ "True if 'arg' is #f, false otherwise.")++;; and++(define and+ (lambda (x y)+ (if x y x)))++(document 'and+ '(("arg1" any) ("arg2" any))+ "Returns 'arg2' if 'arg1' is not #f, otherwise returns 'arg1'")++(should-be "and" (and #t #t) #t)+(should-be "and" (and #t #f) #f)+(should-be "and" (and #f #t) #f)+(should-be "and" (and #f #f) #f)++;; or++(define or+ (lambda (x y)+ (if x x y)))++(document 'or+ '(("arg1" any) ("arg2" any))+ "Returns 'arg1' if 'arg1' is not #f, otherwise returns 'arg2'")++(should-be "or" (or #t #t) #t)+(should-be "or" (or #t #f) #t)+(should-be "or" (or #f #t) #t)+(should-be "or" (or #f #f) #f)++;; all++(define all+ (lambda (xs) (foldr and #t xs)))++(should-be "all" (all '()) #t)+(should-be "all" (all '(#t)) #t)+(should-be "all" (all '(#f)) #f)+(should-be "all" (all '(#t #t #t #t)) #t)+(should-be "all" (all '(#t #t #f #t)) #f)++;; some++(define some+ (lambda (xs) (foldr or #f xs)))++(should-be "some" (some '()) #f)+(should-be "some" (some '(#t)) #t)+(should-be "some" (some '(#f)) #f)+(should-be "some" (some '(#f #f #f)) #f)+(should-be "some" (some '(#t #t #t #t)) #t)+(should-be "some" (some '(#t #t #f #t)) #t)\ No newline at end of filediff --git a/rad/prelude/dict.rad b/rad/prelude/dict.radnew file mode 100644index 0000000..1037765--- /dev/null+++ b/rad/prelude/dict.rad@@ -0,0 +1,41 @@+"not a comment"++;; dict functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;++;; dict-from-list++(define dict-from-list+ (lambda (xs)+ (foldr (lambda (kv acc) (insert (head kv) (head (tail kv)) acc)) (dict) xs)))++(document 'dict-from-list+ '(("list" list))+ "Creates a dictionary from a list of key-value pairs.")++(should-be "dict-from-list"+ (dict-from-list (list (list :one 1) (list :two 2)))+ (dict :one 1 :two 2))++;; keys++(define keys+ (lambda (d)+ (map head (seq d))))++(document 'keys+ '(("dict" dict))+ "Returns the list of keys in a dictionary.")++;; Uncomment this test once map is fixed.+;; (should-be "keys"+;; (keys (dict :one 1 :two 2))+;; '(:one :two))+++;; modify-map+(define modify-map (lambda (key fn mp)+ (insert key (fn (lookup key mp)) mp)))++(should-be "modify-map"+ (modify-map 'a (lambda (x) (+ x 1)) (dict 'a 5))+ (dict 'a 6))\ No newline at end of filediff --git a/rad/prelude/doc.rad b/rad/prelude/doc.radnew file mode 100644index 0000000..464ffaf--- /dev/null+++ b/rad/prelude/doc.rad@@ -0,0 +1,24 @@+(define document+ (lambda (name args description)+ (define old (read-ref _doc-ref))+ (write-ref+ _doc-ref+ (insert name (dict :args args :desc description) old))))++(document 'document+ '(("name" atom) '("args" list) '("description" desc))+ "Documents an atom. The documentation can then be retrieved with '(doc name)'.")++;; doc++(define doc+ (lambda (name)+ (define the-doc (lookup name (read-ref _doc-ref)))+ (string-append+ (lookup :desc the-doc)+ "\nArguments:\n\t"+ (show (lookup :args the-doc)))))++(document 'doc+ '(("name" atom))+ "Retrieves the documentation for an atom, if there is any.")\ No newline at end of filediff --git a/rad/prelude/io.rad b/rad/prelude/io.radnew file mode 100644index 0000000..9fc5ab1--- /dev/null+++ b/rad/prelude/io.rad@@ -0,0 +1,21 @@+"not a comment"++;; read-line+(define read-line!+ (lambda () (read (get-line!))))++(define read-code!+ (lambda (filename)+ (read (string-append "(do " (read-file! filename) ")"))))++(document 'read-code!+ '("filename" string)+ "Read code (as data) from a file.")++(define send-code!+ (lambda (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.")\ No newline at end of filediff --git a/rad/prelude/lens.rad b/rad/prelude/lens.radnew file mode 100644index 0000000..5e1122f--- /dev/null+++ b/rad/prelude/lens.rad@@ -0,0 +1,160 @@+"not a comment"++;; Lenses ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;++;; make-lens++(define make-lens+ (lambda (g s)+ (dict 'getter g 'setter s)))++(document 'make-lens+ '(("getter" function) ("setter" function))+ "Makes a lens out of a getter and a setter.")++;; view++(define view+ (lambda (lens target)+ ((lookup 'getter lens) target)))++(document 'view+ '(("lens" dict) ("target" any))+ "View a value through a lens.")++;; set++(define set+ (lambda (lens new-view target)+ ((lookup 'setter lens) new-view target)))++(document 'set+ '(("lens" dict) ("value" any) ("target" any))+ "Set a value though a lens.")++;; id-lens++(define id-lens+ (make-lens+ (lambda (target) target)+ (lambda (new-view target) new-view)))++(document 'id-lens+ '()+ "The identity lens.")++;; ..++(define ..+ (lambda (lens1 lens2)+ (make-lens+ (lambda (target) (view lens2 (view lens1 target)))+ (lambda (new-view target) (set lens1 (set lens2 new-view (view lens1 target)) target)))))++(document '..+ '(("lens1" dict) ("lens2" dict))+ "Compose two lenses.")++;; ...++(define ... (lambda (lenses) (foldr .. id-lens lenses)))++(document '...+ '(("lenses" list))+ "Compose multiple lenses.")++;; over+(define over+ (lambda (lens f target)+ (set lens (f (view lens target)) target)))++(document 'over+ '(("lens" dict) ("fn" function) ("target" any))+ "Modify a value through a lens.")++;; @++(define @+ (lambda (k)+ (make-lens (lambda (mp) (lookup k mp))+ (lambda (v mp) (insert k v mp)))))++(document '@+ '(("key" any))+ " Returns a lens targetting keys of dicts.")++(should-be "view lens"+ (view (@ :one) (dict :one 1 :two 2))+ 1)++(should-be "set lens"+ (set (@ :two) 42 (dict :one 1 :two 2))+ (dict :one 1 :two 42))++(should-be "over lens"+ (over (@ :one) (lambda (x) (+ x 1)) (dict :one 1 :two 2))+ (dict :one 2 :two 2))++(should-be "lens composition"+ (over (.. (@ :a) (@ :b))+ (lambda (x) (+ x 1))+ (dict :a (dict :b 2)))+ (dict :a (dict :b 3)))++(do (define d+ (lambda (x) (dict :a (dict :b (dict :c x)))))+ (should-be "deep lenses"+ (over (... (list (@ :a) (@ :b) (@ :c)))+ (lambda (x) (+ x 1))+ (d 0))+ (d 1)))++;; Lens access to refs++;; view-ref+(define view-ref+ (lambda (r lens)+ (view lens (read-ref r))))++(document 'view-ref+ '(("ref" ref) ("lens" dict))+ "Like 'view', but for refs.")++(should-be "view-ref"+ (view-ref (ref (dict :key 1)) (@ :key))+ 1)++;; set-ref++(define set-ref+ (lambda (r lens v)+ (modify-ref r (lambda (x) (set lens v x)))))++(document 'set-ref+ '(("ref" ref) ("lens" dict) ("new-value" any))+ "Like 'set', but for refs.")++(should-be "set-ref"+ ((lambda (r)+ (define r (ref (dict :a 1)))+ (set-ref r (@ :a) 2)+ (view-ref r (@ :a)))+ (ref (dict :a 1)))+ 2)+;; set-ref++(define over-ref+ (lambda (r lens f)+ (modify-ref r (lambda (x) (over lens f x)))))++(document 'over-ref+ '(("ref" ref) ("lens" dict) ("fn" function))+ "Like 'over', but for refs.")++(should-be "over-ref"+ ((lambda (r)+ (define r (ref (dict :a 2)))+ (over-ref r (@ :a) (lambda (x) (* x 2)))+ (view-ref r (@ :a)))+ (ref (dict :a 2)))+ 4)diff --git a/rad/prelude/list.rad b/rad/prelude/list.radnew file mode 100644index 0000000..8444598--- /dev/null+++ b/rad/prelude/list.rad@@ -0,0 +1,89 @@+"not a comment"++;; List functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;++;; nil++(define nil (list))++;; empty?++(define empty? (lambda (ls) (eq? ls nil)))++(document 'empty?+ '(("list" list))+ "True if 'list' is empty, false otherwise.")++(should-be "empty" (empty? (list 2)) #f)+++;; length++(define length+ (lambda (xs)+ (foldr (lambda (x acc) (+ acc 1)) 0 xs)))++(document 'length+ '(("list" list))+ "Returns the length of 'list'.")++(should-be "length" (length nil) 0)+(should-be "length" (length (list 2)) 1)++;; reverse++(define reverse (lambda (ls)+ (define go (Y2 (lambda (go)+ (lambda (acc new)+ (if (empty? new)+ acc+ (go (cons (head new) acc) (tail new)))))))+ (go (list) ls)))++(document 'reverse+ '(("list" list))+ "Returns the reversed 'list'.")++(should-be "reverse" (reverse (list 1 2 3)) (list 3 2 1))++;; range++(define range (Y2 (lambda (range) (lambda (from to)+ (if (eq? from to)+ (list to)+ (cons from (range (+ 1 from) to)))))))++(document 'range+ '(("start" number) ("end" number))+ "Returns a list with all integers from 'start' to 'end', inclusive.")++(should-be "range" (range 1 5) (list 1 2 3 4 5))++;; concat++(define concat (lambda (list1 list2)+ (foldr (lambda (a b) (cons a b)) list2 list1)))++(document 'concat+ '(("list1" list) ("list2" list))+ "Concatenates 'list1' and 'list2'.")++(should-be "concat" (concat '(1 2 3) '(4 5 6)) '(1 2 3 4 5 6))+++;; filter++(define filter (Y2 (lambda (filter) (lambda (pred ls)+ (if (empty? ls)+ ls+ (if (pred (head ls))+ (cons (head ls) (filter pred (tail ls)))+ (filter pred (tail ls))))))))++(document 'filter+ '(("filter-cond" function) ("list" list))+ "Returns 'list' with only the elements that satisfy 'filter-cond'.")++(should-be "filter"+ (filter (lambda (x) (< x 10)) (list 3 10 11))+ (list 3))\ No newline at end of filediff --git a/rad/prelude/pure-should-be.rad b/rad/prelude/pure-should-be.radnew file mode 100644index 0000000..8186bb5--- /dev/null+++ b/rad/prelude/pure-should-be.rad@@ -0,0 +1,15 @@+"not a comment"++;; A version of should-be for pure environments.++(define should-be+ (lambda (name x y)+ (if (eq? x y)+ (string-append "Test '" name "' succeeded")+ (string-append "Test '" name "' failed"))))++(document 'should-be+ '(("test-name" string) ("actual" any) ("expected" any))+ "Checks that 'actual' equals 'expected'. Used for tests")++(should-be "doc" (string? (doc 'doc)) #t)\ No newline at end of filediff --git a/rad/prelude/recursion.rad b/rad/prelude/recursion.radnew file mode 100644index 0000000..03c02ac--- /dev/null+++ b/rad/prelude/recursion.rad@@ -0,0 +1,18 @@+"not a comment"++;; y-combinators ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;++(define Y+ (lambda (h)+ ((lambda (x) (x x))+ (lambda (g)+ (h (lambda (arg) ((g g) arg)))))))+(define Y2+ (lambda (h)+ ((lambda (x) (x x))+ (lambda (g)+ (h (lambda (arg1 arg2) ((g g) arg1 arg2)))))))++((lambda ()+ (define fac (Y (lambda (f) (lambda (x) (if (< x 2) 1 (* x (f (- x 1))))))))+ (should-be "fac" (fac 10) 3628800)))\ No newline at end of filediff --git a/rad/prelude/ref.rad b/rad/prelude/ref.radnew file mode 100644index 0000000..6aab113--- /dev/null+++ b/rad/prelude/ref.rad@@ -0,0 +1,12 @@+"not a comment"++;; ref functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;++;; modify-ref+(define modify-ref+ (lambda (r fn)+ (write-ref r (fn (read-ref r)))))++(document 'modify-ref+ '(("ref" ref) ("fn" function))+ "Modify 'ref' by applying the provided function.")\ No newline at end of filediff --git a/rad/prelude/should-be.rad b/rad/prelude/should-be.radnew file mode 100644index 0000000..36a851d--- /dev/null+++ b/rad/prelude/should-be.rad@@ -0,0 +1,15 @@+"not a comment"++;; should-be++(define should-be+ (lambda (name x y)+ (if (eq? x y)+ (print! (string-append "Test '" name "' succeeded"))+ (print! (string-append "Test '" name "' failed")))))++(document 'should-be+ '(("test-name" string) ("actual" any) ("expected" any))+ "Checks that 'actual' equals 'expected'. Used for tests")++(should-be "doc" (string? (doc 'doc)) #t)\ No newline at end of filediff --git a/rad/repl.rad b/rad/repl.radnew file mode 100644index 0000000..40974b9--- /dev/null+++ b/rad/repl.rad@@ -0,0 +1,21 @@+(load! "rad/prelude.rad")++;; The Repl+++(define _initial_prompt-text+ "Welcome to radicle. Type (help) for help.")++(define help (lambda ()+ "radicle is a LISP-like language intendended for programming chains, and interacting with those chains.++ Type (doc '<name>) for further documentation of <name>."))+++(define repl+ (dict+ 'name "repl"+ ;; Parse errors are thrown here+ 'getter read-line!))++(subscribe-to! repl print!)diff --git a/rad/self-amending-store.rad b/rad/self-amending-store.radnew file mode 100644index 0000000..97fde4c--- /dev/null+++ b/rad/self-amending-store.rad@@ -0,0 +1,16 @@+(define sas-password "very secret")+(define sas-store (ref (dict)))+(define sas-eval-ref (ref eval))++;; self-amending key-val store+(define sas-starting-eval+ (lambda (expr)+ (define command (head expr))+ (cond+ (eq? command 'get) (lookup (nth 1 expr) (read-ref sas-store))+ (eq? command 'set) (modify-ref sas-store (lambda (s) (insert (nth 1 expr) (nth 2 expr) s)))+ (and (eq? command 'update)+ (eq? (nth 1 expr)+ sas-password))+ (write-ref sas-eval-ref (eval (nth 2 expr)))+ :else (throw 'invalid-command "Valid commands are: 'get', 'set' and 'update'."))))\ No newline at end of filediff --git a/rad/state-machine.rad b/rad/state-machine.radnew file mode 100644index 0000000..6a5b7f9--- /dev/null+++ b/rad/state-machine.rad@@ -0,0 +1,101 @@+"not a comment"++(define head-shots+ (dict "onur" "https://res.cloudinary.com/juliendonck/image/upload/v1536080565/avatars/1712926.png"+ "ele" "https://res.cloudinary.com/juliendonck/image/upload/v1536080565/avatars/853825.png"+ "alexis" "https://res.cloudinary.com/juliendonck/image/upload/v1536080565/avatars/40774.png"+ "kim" "https://res.cloudinary.com/juliendonck/image/upload/v1536080565/avatars/6163.png"+ "julien" "https://res.cloudinary.com/juliendonck/image/upload/v1536080565/avatars/2326909.jpg"))++(define get-head-shot+ (lambda (x)+ (define y (lookup x head-shots))+ (if (eq? y '())+ "https://res.cloudinary.com/juliendonck/image/upload/v1536080565/avatars/2326909.jpg"+ y)))++(define pr-trans+ (lambda (state inp)+ (define c (dict "key" (show (view (@ :next-id) state))+ "username" (nth 0 inp)+ "comment" (nth 1 inp)+ "profile_pic_url" (get-head-shot (nth 0 inp))))+ (dict :state (over (@ :comments)+ (lambda (cs) (cons c cs))+ (over (@ :next-id)+ (lambda (x) (+ x 1))+ state))+ :output c)))++(define kim-trans+ (lambda (state i)+ (if (eq? (nth 0 i) "kim")+ (pr-trans state (list "kim" "LGTM"))+ (pr-trans state i))))++;; Handle an input in the morphing state-machine.+(define state-machine-input+ (lambda (state i)+ (define trans-fn (view-ref state (@ :transition-fn)))+ (define current-state (view-ref state (@ :machine-state)))+ (define next (trans-fn current-state i))+ (set-ref state (@ :machine-state) (view (@ :state) next))+ (view (@ :output) next)))++;; Trigger a new vote+(define state-machine-new-trans+ (lambda (state func)+ (if (eq? (view-ref state (@ :voting)) :nothing)+ (do (set-ref state (@ :voting) (dict :votes (dict)+ :proposed-function func))+ (string-append "A new transition function has been proposed! Please either agree or disagree with:\n" (show func)))+ (throw 'invalid-input "Can't propose new transition function while vote is ongoing."))))++(define state-machine-agree+ (lambda (state voters userid)+ (if (member? userid voters)+ (do (set-ref state (... (list (@ :voting) (@ :votes) (@ userid))) #t)+ (if (eq? (length (seq (view-ref state (.. (@ :voting) (@ :votes))))) (length voters))+ (do (set-ref state (@ :transition-fn) (eval (view-ref state (.. (@ :voting) (@ :proposed-function)))))+ (set-ref state (@ :voting) :nothing)+ "Voting has finished; a new transition function is in effect.")+ '()))+ (throw 'invalid-input "Not allowed to vote."))))++(define state-machine-disagree+ (lambda (state voters userid)+ (if (member? userid voters)+ (do (set-ref state (@ :voting) :nothing)+ "Voting has ended; someone disagreed.")+ (throw 'invalid-input "You are not allowed to vote."))))++;; Returns an eval which operates a state machine whose transition function may+;; be updated. To update the transition function all voters must agree on it.+(define state-machine-eval+ (lambda (voters init-state init-transition)+ (define state (ref (dict :machine-state init-state+ :transition-fn init-transition+ :voting :nothing)))+ (lambda (expr)+ (define verb (nth 0 expr))+ (define input (nth 1 expr))+ (cond+ (eq? verb 'input) (state-machine-input state input)+ (eq? verb 'new-trans-func) (state-machine-new-trans state input)+ (eq? verb 'agree) (state-machine-agree state voters input)+ (eq? verb 'disagree) (state-machine-disagree state voters input)+ :else (throw 'invalid-input (string-append "The only valid commands are 'input', 'new-trans-func', 'agree' and 'disagree': " (show expr)))))))++(define simple-trans+ (lambda (f)+ (lambda (s i)+ (define y (f s i))+ (dict :state y+ :output y))))++(define pr-thread+ (state-machine-eval+ (list "alice" "bob")+ (dict :next-id 0 :comments (list))+ pr-trans+ ))diff --git a/repl/config.rad b/repl/config.raddeleted file mode 100644index 6c00c23..0000000--- a/repl/config.rad+++ /dev/null@@ -1,10 +0,0 @@-(define repl- (dict- 'name "repl"- ;; Parse errors are thrown here- 'getter (lambda () (catch 'parse-error (get-line!) print!))))--;; Evaluation errors are thrown here-(catch 'any- (subscribe-to! repl print!)- (lambda (x) (print! x) (subscribe-to! repl print!)))diff --git a/repl/prelude.rad b/repl/prelude.raddeleted file mode 100644index 983ff8d..0000000--- a/repl/prelude.rad+++ /dev/null@@ -1,285 +0,0 @@--(define should-be- (lambda (name x y)- (if (eq? x y)- (print! (string-append "Test '" name "' succeeded"))- (print! (string-append "Test '" name "' failed")))))--;; empty?-(define empty? (lambda (ls) (eq? ls (list))))-(should-be "empty" (empty? (list 2)) #f)--;; boolean functions--(define and- (lambda (x y)- (if x y x)))--(should-be "and" (and #t #t) #t)-(should-be "and" (and #t #f) #f)-(should-be "and" (and #f #t) #f)-(should-be "and" (and #f #f) #f)--(define or- (lambda (x y)- (if x x y)))--(should-be "or" (or #t #t) #t)-(should-be "or" (or #t #f) #t)-(should-be "or" (or #f #t) #t)-(should-be "or" (or #f #f) #f)--(define all- (lambda (xs) (foldr and #t xs)))--(should-be "all" (all '()) #t)-(should-be "all" (all '(#t)) #t)-(should-be "all" (all '(#f)) #f)-(should-be "all" (all '(#t #t #t #t)) #t)-(should-be "all" (all '(#t #t #f #t)) #f)--(define some- (lambda (xs) (foldr or #f xs)))--(should-be "some" (some '()) #f)-(should-be "some" (some '(#t)) #t)-(should-be "some" (some '(#f)) #f)-(should-be "some" (some '(#f #f #f)) #f)-(should-be "some" (some '(#t #t #t #t)) #t)-(should-be "some" (some '(#t #t #f #t)) #t)--;; y-combinators--(define Y- (lambda (h)- ((lambda (x) (x x))- (lambda (g)- (h (lambda (arg) ((g g) arg)))))))-(define Y2- (lambda (h)- ((lambda (x) (x x))- (lambda (g)- (h (lambda (arg1 arg2) ((g g) arg1 arg2)))))))--((lambda ()- (define fac (Y (lambda (f) (lambda (x) (if (< x 2) 1 (* x (f (- x 1))))))))- (should-be "fac" (fac 10) 3628800)))--;; List functions--(define length- (lambda (xs)- (foldr (lambda (x acc) (+ acc 1)) 0 xs)))--;; reverse-(define reverse (lambda (ls)- (define go (Y2 (lambda (go)- (lambda (acc new)- (if (empty? new)- acc- (go (cons (head new) acc) (tail new)))))))- (go (list) ls)))--(should-be "reverse" (reverse (list 1 2 3)) (list 3 2 1))--;; range-(define range (Y2 (lambda (range) (lambda (from to)- (if (eq? from to)- (list to)- (cons from (range (+ 1 from) to)))))))--(should-be "range" (range 1 5) (list 1 2 3 4 5))--;; filter-(define filter (Y2 (lambda (filter) (lambda (cond ls)- (if (empty? ls)- ls- (if (cond (head ls))- (cons (head ls) (filter cond (tail ls)))- (filter cond (tail ls))))))))--(should-be "filter"- (filter (lambda (x) (< x 10)) (list 3 10 11))- (list 3))--;; dict functions--(define dict-from-list- (lambda (xs)- (foldr (lambda (kv acc) (insert (head kv) (head (tail kv)) acc)) (dict) xs)))--(should-be "dict-from-list"- (dict-from-list '('(:one 1) '(:two 2)))- (dict :one 1 :two 2))--(define keys- (lambda (d)- (map head (seq d))))--;; Uncomment this test once map is fixed.-;; (should-be "keys"-;; (keys (dict :one 1 :two 2))-;; '(:one :two))--;; modify-ref-(define modify-ref- (lambda (r fn)- (write-ref r (fn (read-ref r)))))--;; modify-map-(define modify-map (lambda (key fn mp)- (insert key (fn (lookup key mp)) mp)))--(should-be "modify-map"- (modify-map 'a (lambda (x) (+ x 1)) (dict 'a 5))- (dict 'a 6))--;; Lenses--;; Makes a lens out of a getter and a setter.-(define make-lens- (lambda (g s)- (dict 'getter g 'setter s)))--;; View a value through a lens.-(define view- (lambda (lens target)- ((lookup 'getter lens) target)))--;; Set a value though a lens.-(define set- (lambda (lens new-view target)- ((lookup 'setter lens) new-view target)))--;; Compose lenses-(define ..- (lambda (lens1 lens2)- (make-lens- (lambda (target) (view lens2 (view lens1 target)))- (lambda (new-view target) (set lens1 (set lens2 new-view (view lens1 target)) target)))))--;; Modify a value through a lens.-(define over- (lambda (lens f target)- (set lens (f (view lens target)) target)))--;; A lens targetting keys of dicts.-(define key- (lambda (k)- (make-lens (lambda (mp) (lookup k mp))- (lambda (v mp) (insert k v mp)))))--(should-be "view lens"- (view (key :one) (dict :one 1 :two 2))- 1)--(should-be "set lens"- (set (key :two) 42 (dict :one 1 :two 2))- (dict :one 1 :two 42))--(should-be "over lens"- (over (key :one) (lambda (x) (+ x 1)) (dict :one 1 :two 2))- (dict :one 2 :two 2))--(should-be "lens composition"- (over (.. (key :a) (key :b))- (lambda (x) (+ x 1))- (dict :a (dict :b 2)))- (dict :a (dict :b 3)))--;; Voting stuff. Should be moved elsewhere when we have an import mechanism.--;; Initial state of the vote-(define state- (ref- (dict- 'voters '("Alice" "Bob" "Charlie" "Dan")- 'votes (dict))))--;; Takes a state and a vote and returns a new state, or throws and error if the-;; voting expression is invalid.-(define ev-vote- (lambda (s expr)- (if (eq? (head expr) 'vote)- (if (and (string? (head (tail expr)))- (boolean? (head (tail (tail expr)))))- (if (member? (head (tail expr)) (view (key 'voters) (read-ref state)))- (set (.. (key 'votes) (key (head (tail expr))))- (head (tail (tail expr)))- s)- (throw 'invalid-input "You do not have permission to vote."))- (throw 'invalid-input "A vote must be a name and a bool."))- (throw 'invalid-input "All you can do is vote."))- ))--(define voting-ended?- (lambda (s)- (define votes (dict-from-list (map reverse (seq (view (key 'votes) s)))))- votes- ))--(define boom- (quote- (define eval ev-vote)))----;; Account stuff. Should be moved elsewhere when we have an import mechanism--(define create-currency (lambda ()-- ;; The map of all accounts- (define accounts (ref (dict)))-- ;; Create an account with 10 coins.- (define new-account (lambda (name)- (modify-ref accounts (lambda (acc)- (insert name 10 acc)))))-- ;; Get an account's balance- (define account-balance (lambda (name)- (lookup name (read-ref accounts))))-- ;; Transfer money- (define transfer (lambda (from to amount)- (define acc (read-ref accounts))- (write-ref accounts (if (> amount (lookup from acc))- (print! "not enough balance")- (modify-map- to- (lambda (x) (+ x amount))- (modify-map from (lambda (x) (- x amount)) acc))))))-- (define dispatch (lambda (m)- (if (eq? m 'new-account) new-account- (if (eq? m 'account-balance) account-balance- (if (eq? m 'transfer) transfer- (print! "error: currency- unknown message"))))))- dispatch))--(define currency (create-currency))---(define new-eval (lambda (expr)- (if (eq? (head expr) 'new-account)- ((currency 'new-account) (head (tail expr)))- (if (eq? (head expr) 'account-balance)- ((currency 'account-balance) (head (tail expr)))- (if (eq? (head expr) 'transfer)- ((currency 'transfer) (head (tail expr)) (head (tail (tail expr))) (head- (tail- (tail (tail expr)))))- (print! "transaction must be new-account, transfer, or account-balance"))))))---;; The Repl--(define repl- (dict- 'name "repl"- ;; Parse errors are thrown here- 'getter (lambda () (catch 'parse-error (get-line!) print!))))--(catch 'any- (subscribe-to! repl print!)- (lambda (x) (print! x) (subscribe-to! repl print!)))diff --git a/scripts/upload-ghcjs.sh b/scripts/upload-ghcjs.shnew file mode 100755index 0000000..9acaea6--- /dev/null+++ b/scripts/upload-ghcjs.sh@@ -0,0 +1,26 @@+#!/bin/bash -+#===============================================================================+#+# FILE: upload-ghcjs.sh+#+# USAGE: ./upload-ghcjs.sh+#+# DESCRIPTION: Build and upload radicle JS+#+# OPTIONS: ---+# REQUIREMENTS: UglifyJS, gsutil+# CREATED: 08/29/2018 14:52+#===============================================================================++set -o nounset+set -o errexit++export STACK_YAML=stack-ghcjs.yaml++[[ -d out ]] || mkdir out+stack build+ORIG=$(find .stack-work/dist -name all.js)++uglifyjs $ORIG > out/all.min.js++gsutil cp out/all.min.js gs://static.radicle.xyzdiff --git a/src/Radicle.hs b/src/Radicle.hsindex f493a8b..d57a77a 100644--- a/src/Radicle.hs+++ b/src/Radicle.hs@@ -13,13 +13,14 @@ module Radicle---- | The definition of the core language.Value(..)+ , DataValue(..)+ , isData, interpret, interpretMany, LangError(..), ($$)- , Ident+ , Ident(..), Reference(..)- , fromIdent, mkIdent, quote, Env(..)@@ -35,7 +36,6 @@ module Radicle-- * Parsing, parse- , parseTest-- * Pretty-printing, renderPretty@@ -47,6 +47,25 @@ module Radicle-- * Repl, repl++ -- * Primops+ , Primops+ , purePrimops+ , replPrimops+ , ReplM+ -- ** Primop helpers+ , evalArgs++ -- * CLI+ , getConfig+ , getHistory++ -- * Helpers+ , kwLookup+ , makeBindings+ , unmakeBindings+ , (??)+) whereimport Control.Monad.Identity (runIdentity)diff --git a/src/Radicle/Internal.hs b/src/Radicle/Internal.hsindex 47d2b9d..4554d4c 100644--- a/src/Radicle/Internal.hs+++ b/src/Radicle/Internal.hs@@ -10,6 +10,7 @@ import Radicle.Internal.Parse as Ximport Radicle.Internal.Pretty as Ximport Radicle.Internal.Primops as Ximport Radicle.Internal.Subscriber as X+import Radicle.Internal.CLI as Ximport qualified Text.Megaparsec as Mdiff --git a/src/Radicle/Internal/CLI.hs b/src/Radicle/Internal/CLI.hsnew file mode 100644index 0000000..4e5580b--- /dev/null+++ b/src/Radicle/Internal/CLI.hs@@ -0,0 +1,20 @@+module Radicle.Internal.CLI where++import Protolude+import System.Environment (lookupEnv)++-- | Uses XDG_CONFIG_HOME if available.+getConfig :: IO FilePath+getConfig = do+ mCfgHome <- lookupEnv "XDG_CONFIG_HOME"+ pure $ case mCfgHome of+ Nothing -> "$HOME/.config/rad/config.rad"+ Just cfgHome -> cfgHome <> "/rad/config.rad"++-- | Uses XDG_CACHE_HOME if available.+getHistory :: IO FilePath+getHistory = do+ mCfgHome <- lookupEnv "XDG_CACHE_HOME"+ pure $ case mCfgHome of+ Nothing -> "$HOME/.cache/rad/history"+ Just cfgHome -> cfgHome <> "/rad/history"diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hsindex 7e10d5a..d70184a 100644--- a/src/Radicle/Internal/Core.hs+++ b/src/Radicle/Internal/Core.hs@@ -2,9 +2,15 @@ module Radicle.Internal.Core whereimport Protolude hiding (TypeError, (<>))+import Codec.Serialise (Serialise)+import Control.Monad.Except (ExceptT(..), MonadError, runExceptT,+ throwError)import Control.Monad.State+import Data.Aeson (ToJSON(..), FromJSON(..))+import qualified Data.Aeson as Aimport Data.Data (Data)import qualified Data.IntMap as IntMap+import qualified Data.HashMap.Strict as HashMapimport Data.List.NonEmpty (NonEmpty)import qualified Data.List.NonEmpty as NonEmptyimport qualified Data.Map as Map@@ -13,6 +19,8 @@ import Data.Semigroup ((<>))import qualified GHC.Exts as GhcExtsimport qualified Text.Megaparsec.Error as Par+import Radicle.Internal.Orphans ()+-- * Value-- | An error throw during parsing or evaluating expressions in the language.@@ -64,7 +72,7 @@ errorToValue e = case e ofmakeVal (t,v) = pure (Ident t, Dict $ Map.mapKeys (Atom . Ident) . GhcExts.fromList $ v)newtype Reference = Reference { getReference :: Int }- deriving (Show, Read, Ord, Eq, Generic)+ deriving (Show, Read, Ord, Eq, Generic, Serialise)-- | Create a new ref with the supplied initial value.newRef :: Monad m => Value -> Lang m Value@@ -77,7 +85,7 @@ newRef v = dopure . Ref $ Reference ix-- | Read the value of a reference.-readRef :: MonadError (LangError Value) m => Reference -> Lang m Value+readRef :: Monad m => Reference -> Lang m ValuereadRef (Reference r) = dorefs <- gets bindingsRefscase IntMap.lookup r refs of@@ -104,13 +112,72 @@ data Value =| Lambda [Ident] (NonEmpty Value) (Maybe (Env Value))deriving (Eq, Show, Ord, Read, Generic)+instance Serialise Value++-- | The data portion of values.+data DataValue =+ DAtom Ident+ | DKeyword Ident+ | DString Text+ | DNumber Scientific+ | DBoolean Bool+ | DList [DataValue]+ | DDict (Map.Map DataValue DataValue)+ deriving (Eq, Show, Ord, Read, Generic)++instance A.ToJSON Ident+instance A.FromJSON Ident+instance A.ToJSONKey DataValue+instance A.FromJSONKey DataValue++instance A.ToJSON DataValue where+ toJSON = \case+ DNumber n -> toJSON n+ DList ls -> toJSON ls+ DBoolean b -> toJSON b+ DString s -> toJSON s+ DDict m ->+ let kvs = Map.toList m+ in case traverse isString (fst <$> kvs) of+ Just ss -> A.Object (HashMap.fromList (zip ss (toJSON . snd <$> kvs)))+ Nothing -> toJSON m+ x -> A.genericToJSON A.defaultOptions x+ where+ isString (DString s) = Just s+ isString _ = Nothing++instance A.FromJSON DataValue where+ parseJSON = \case+ A.Number n -> pure $ DNumber n+ A.String s -> pure $ DString s+ A.Array ls -> DList . toList <$> traverse parseJSON ls+ A.Bool b -> pure $ DBoolean b+ A.Null -> pure $ DKeyword (toIdent "null")+ o@(A.Object hm) ->+ A.genericParseJSON A.defaultOptions o+ <|> do let kvs = HashMap.toList hm+ vs <- traverse parseJSON (snd <$> kvs)+ pure . DDict . Map.fromList $ zip (DString . fst <$> kvs) vs++isData :: Value -> Maybe DataValue+isData = \case+ Atom i -> pure $ DAtom i+ Keyword i -> pure $ DKeyword i+ String s -> pure $ DString s+ Number n -> pure $ DNumber n+ Boolean b -> pure $ DBoolean b+ List ls -> DList <$> traverse isData ls+ Dict m -> DDict . Map.fromList <$> traverse kv (Map.toList m)+ _ -> Nothing+ where+ kv (k,v) = (,) <$> isData k <*> isData v-- | An identifier in the language.----- Not all `Text`s are valid identifiers, so we do not export the constructor.--- Instead, use `makeIdent`.+-- Not all `Text`s are valid identifiers, so use Ident at your own risk.+-- `makeIdent` is the safe version.newtype Ident = Ident { fromIdent :: Text }- deriving (Eq, Show, Read, Ord, Generic, Data)+ deriving (Eq, Show, Read, Ord, Generic, Data, Serialise)-- Unsafe! Only use this if you know the string at compile-time and know it's a-- valid identifier@@ -119,7 +186,7 @@ toIdent = Ident-- | The environment, which keeps all known bindings.newtype Env s = Env { fromEnv :: Map Ident s }- deriving (Eq, Semigroup, Monoid, Ord, Show, Read, Generic, Functor, Foldable, Traversable)+ deriving (Eq, Semigroup, Monoid, Ord, Show, Read, Generic, Functor, Foldable, Traversable, Serialise)instance GhcExts.IsList (Env s) wheretype Item (Env s) = (Ident, s)@@ -140,7 +207,7 @@ data Bindings m = Bindings-- | The environment in which expressions are evaluated.newtype LangT r m a = LangT{ fromLangT :: ExceptT (LangError Value) (StateT r m) a }- deriving (Functor, Applicative, Monad, MonadError (LangError Value), MonadState r)+ deriving (Functor, Applicative, Monad, MonadError (LangError Value), MonadIO, MonadState r)instance MonadTrans (LangT r) where lift = LangT . lift . lift@@ -235,7 +302,35 @@ baseEval val = case val of-- * Helpers--- | Infix function application++callFn :: Monad m => Value -> [Value] -> Lang m Value+callFn f vs = case f of+ -- This happens if a quoted lambda is explicitly evaled. We then+ -- give it the current environment.+ Lambda bnds body Nothing ->+ if length bnds /= length vs+ then throwError $ WrongNumberOfArgs "lambda" (length bnds)+ (length vs)+ else do+ let mappings = GhcExts.fromList (zip bnds vs)+ NonEmpty.last <$> withEnv+ (mappings <>)+ (traverse baseEval body)+ Lambda bnds body (Just closure) ->+ if length bnds /= length vs+ then throwError $ WrongNumberOfArgs "lambda" (length bnds)+ (length vs)+ else do+ let mappings = GhcExts.fromList (zip bnds vs)+ modEnv = mappings <> closure+ NonEmpty.last <$> withEnv (const modEnv)+ (traverse baseEval body)+ Primop i -> throwError . TypeError+ $ "Trying to call a non-function: the primop '" <> show i+ <> "' cannot be used as a function."+ _ -> throwError . TypeError $ "Trying to call a non-function."++-- | Infix evaluation of application (of functions or primops)infixr 1 $$($$) :: Monad m => Value -> [Value] -> Lang m Valuemfn $$ vs = do@@ -246,29 +341,11 @@ mfn $$ vs = do-- Primops get to decide whether and how their args are-- evaluated.fn vs- -- This happens if a quoted lambda is explicitly evaled. We then- -- give it the current environment.- Lambda bnds body Nothing ->- if length bnds /= length vs- then throwError $ WrongNumberOfArgs "lambda" (length bnds)- (length vs)- else do- vs' <- traverse baseEval vs- let mappings = GhcExts.fromList (zip bnds vs')- NonEmpty.last <$> withEnv- (mappings <>)- (traverse baseEval body)- Lambda bnds body (Just closure) ->- if length bnds /= length vs- then throwError $ WrongNumberOfArgs "lambda" (length bnds)- (length vs)- else do- vs' <- traverse baseEval vs- let mappings = GhcExts.fromList (zip bnds vs')- modEnv = mappings <> closure- NonEmpty.last <$> withEnv (const modEnv)- (traverse baseEval body)+ f@Lambda{} -> do+ vs' <- traverse baseEval vs+ callFn f vs'_ -> throwError $ TypeError "Trying to apply a non-function"+nil :: Valuenil = List []diff --git a/src/Radicle/Internal/Orphans.hs b/src/Radicle/Internal/Orphans.hsnew file mode 100644index 0000000..2d5638e--- /dev/null+++ b/src/Radicle/Internal/Orphans.hs@@ -0,0 +1,11 @@+{-# OPTIONS_GHC -fno-warn-orphans #-}+module Radicle.Internal.Orphans () where++import Protolude+import Prelude (fail)+import Codec.Serialise (Serialise(..))+import Data.Scientific++instance Serialise Scientific where+ encode = encode . (show :: Scientific -> Text)+ decode = decode >>= either fail pure . readEitherdiff --git a/src/Radicle/Internal/Parse.hs b/src/Radicle/Internal/Parse.hsindex a500b59..3a9706f 100644--- a/src/Radicle/Internal/Parse.hs+++ b/src/Radicle/Internal/Parse.hs@@ -17,7 +17,6 @@ import qualified Text.Megaparsec.Char.Lexer as Limport qualified Text.Megaparsec.Error as Parimport Radicle.Internal.Core-import Radicle.Internal.Primops-- * The parser@@ -112,6 +111,7 @@ valueP = do-- Examples:---- >>> import Control.Monad.Identity+-- >>> import Radicle.Internal.Primops-- >>> runIdentity $ interpret "test" "((lambda (x) x) #t)" pureEnv-- Right (Boolean True)--@@ -135,6 +135,7 @@ interpret sourceName expr bnds = do---- Examples:--+-- >>> import Radicle.Internal.Primops-- >>> fmap fst <$> runLang pureEnv $ interpretMany "test" "(define id (lambda (x) x))\n(id #t)"-- Right (Boolean True)interpretMany :: Monad m => Text -> Text -> Lang m Value@@ -184,15 +185,6 @@ parse file src ids = doLeft err -> throwError . toS $ M.parseErrorPretty' src errRight v -> pure v--- | 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 (Map.keys $ bindingsPrimops e)- where- e :: Bindings (Lang Identity)- e = pureEnv---- ** Valid identifiers-- These are made top-level so construction of arbitrary instances that matches-- parsing is easier. Note that additionally an identifier must not be a validdiff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hsindex 0f6f13a..3cd4837 100644--- a/src/Radicle/Internal/Pretty.hs+++ b/src/Radicle/Internal/Pretty.hs@@ -28,16 +28,22 @@ instance Pretty Value whereNumber n -> pretty (show n :: Text)Boolean True -> "#t"Boolean False -> "#f"- List vs -> parens (sep (pretty <$> vs))+ List vs -> case vs of+ [] -> "()"+ [v'] -> parens $ pretty v'+ _ -> parens $ hang 1 (sep $ pretty <$> vs)Primop i -> pretty i- Dict mp -> parens $- "dict" <+> sep [ pretty k <+> pretty val+ Dict mp -> parens . hang 1 $+ "dict" <%> sep [ pretty k <+> pretty val| (k, val) <- Map.toList mp ]Lambda ids vals _ -> parens $- "lambda" <+> parens (sep $ pretty <$> ids)- <+> sep (pretty <$> toList vals)+ "lambda" <+> align (sep+ [ parens . sep $ pretty <$> ids+ , sep $ pretty <$> toList vals+ ])whereescapeStr = T.replace "\"" "\\\"" . T.replace "\\" "\\\\"+ a <%> b = a <> softline <> binstance Pretty r => Pretty (LangError r) wherepretty v = case v of@@ -66,12 +72,11 @@ renderCompactPretty = renderStrict . layoutCompact . pretty---- Examples:----- >>> import Data.Void-- >>> renderPretty Unbounded (List [String "hi", String "there"])-- "(\"hi\" \"there\")"---- >>> renderPretty (AvailablePerLine 6 0.5) (List [String "hi", String "there"])--- "(\"hi\"\n\"there\")"+-- "(\"hi\"\n \"there\")"renderPretty :: Pretty v => PageWidth -> v -> TextrenderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . pretty@@ -79,7 +84,6 @@ renderPretty pg = renderStrict . layoutSmart (LayoutOptions pg) . pretty---- Examples:----- >>> import Data.Void-- >>> renderPrettyDef (List [String "hi", String "there"])-- "(\"hi\" \"there\")"renderPrettyDef :: Pretty v => v -> Textdiff --git a/src/Radicle/Internal/Primops.hs b/src/Radicle/Internal/Primops.hsindex 1d9ed8a..3938ddb 100644--- a/src/Radicle/Internal/Primops.hs+++ b/src/Radicle/Internal/Primops.hs@@ -1,37 +1,67 @@module Radicle.Internal.Primops( pureEnv, purePrimops+ , evalArgs+ , evalOneArg+ , readValue+ , kwLookup+ , makeBindings+ , unmakeBindings+ , (??)) whereimport Protolude hiding (TypeError)import qualified Data.IntMap as IntMapimport qualified Data.Map as Map-import Data.Scientific (Scientific)+import Data.Scientific (Scientific, floatingOrInteger)import GHC.Exts (IsList(..))import Radicle.Internal.Core+import Radicle.Internal.Parseimport Radicle.Internal.Pretty-- | A Bindings with an Env containing only 'eval' and only pure primops.pureEnv :: (Monad m) => Bindings m-pureEnv = Bindings e purePrimops mempty 0+pureEnv = Bindings e purePrimops r 1where- e = fromList [(toIdent "eval", Primop $ toIdent "base-eval")]+ e = fromList [ (toIdent "eval", Primop $ toIdent "base-eval")+ , (toIdent "_doc-ref", Ref $ Reference 0)+ ]+ r = fromList [ (0, Dict mempty) ]-- | The universal primops. These are available in chain evaluation, and are-- not shadowable via 'define'.purePrimops :: forall m. (Monad m) => Primops mpurePrimops = fromList $ first Ident <$>[ ("base-eval", evalOneArg "base-eval" baseEval)+ , ( "pure-env"+ , \case+ [] -> pure $ unmakeBindings (pureEnv :: Bindings m)+ xs -> throwError $ WrongNumberOfArgs "pure-env" 0 (length xs)+ )+ , ("eval-with-env", evalArgs $ \case+ [expr, env] -> do+ bnds <- makeBindings env+ let (evalRes, bnds') = runIdentity $ runLang bnds $ eval expr+ case evalRes of+ Left e -> throwError e+ Right res -> pure $ List [res, unmakeBindings bnds']+ xs -> throwError $ WrongNumberOfArgs "eval-with-env" 2 (length xs))+ , ("apply", evalArgs $ \case+ [fn, List args] -> eval . List $ fn:args+ [_, _] -> throwError $ TypeError "apply: expecting list as second arg"+ xs -> throwError $ WrongNumberOfArgs "apply" 2 (length xs))+ , ( "read"+ , evalOneArg "read" $ \case+ String s -> readValue s+ _ -> throwError $ TypeError "read: expects string"+ )+ , ("get-current-env", \case+ [] -> unmakeBindings <$> get+ xs -> throwError $ WrongNumberOfArgs "get-current-env" 0 (length xs)), ("list", evalArgs $ \args -> pure $ List args)- , ("dict", evalArgs $ \args ->- let go (k:v:rest) = Map.insert k v $ go rest- go [] = mempty- go _ = panic "impossible"- in if length args `mod` 2 == 0- then pure . Dict $ go args- else throwError $ OtherError "'dict' expects even number of args")+ , ("dict", evalArgs $ (Dict . foldr (uncurry Map.insert) mempty <$>) . evenArgs "dict"), ("quote", \args -> case args of[v] -> pure vxs -> throwError $ WrongNumberOfArgs "quote" 1 (length xs))@@ -73,6 +103,18 @@ purePrimops = fromList $ first Ident <$>List (_:xs) -> pure $ List xsList [] -> throwError $ OtherError "tail: empty list"_ -> throwError $ TypeError "tail: expects list argument")+ , ( "nth"+ , evalArgs $ \case+ [Number n, List xs] -> case floatingOrInteger n of+ Left (_ :: Double) -> throwError $ OtherError "nth: first argument was not an integer"+ Right i -> do+ let x_ = indexMay i xs+ case x_ of+ Just x -> pure x+ Nothing -> throwError $ OtherError "nth: index out of bounds"+ [_,_] -> throwError $ TypeError "nth: expects a integer and a list"+ xs -> throwError $ WrongNumberOfArgs "nth" 2 (length xs)+ ), ("lookup", evalArgs $ \args -> case args of[a, Dict m] -> pure $ case Map.lookup a m ofJust v -> v@@ -113,17 +155,17 @@ purePrimops = fromList $ first Ident <$>[_, _] -> throwError $ TypeError ">: expecting number"xs -> throwError $ WrongNumberOfArgs ">" 2 (length xs)), ("foldl", evalArgs $ \args -> case args of- [fn, init', List ls] -> foldlM (\b a -> (fn $$) [b,a]) init' ls+ [fn, init', List ls] -> foldlM (\b a -> callFn fn [b, a]) init' ls[_, _, _] -> throwError$ TypeError "foldl: third argument should be a list"xs -> throwError $ WrongNumberOfArgs "foldl" 3 (length xs)), ("foldr", evalArgs $ \args -> case args of- [fn, init', List ls] -> foldrM (\b a -> (fn $$) [b,a]) init' ls+ [fn, init', List ls] -> foldrM (\b a -> callFn fn [b, a]) init' ls[_, _, _] -> throwError$ TypeError "foldr: third argument should be a list"xs -> throwError $ WrongNumberOfArgs "foldr" 3 (length xs)), ("map", evalArgs $ \args -> case args of- [fn, List ls] -> List <$> traverse (fn $$) (pure <$> ls)+ [fn, List ls] -> List <$> traverse (callFn fn) (pure <$> ls)[_, _] -> throwError $ TypeError "map: second argument should be a list"xs -> throwError $ WrongNumberOfArgs "map" 3 (length xs)), ("keyword?", evalOneArg "keyword?" $ \case@@ -135,6 +177,23 @@ purePrimops = fromList $ first Ident <$>, ("list?", evalOneArg "list?" $ \caseList _ -> pure tt_ -> pure ff)+ , ("dict?", evalOneArg "dict?" $ \case+ Dict _ -> pure tt+ _ -> pure ff)+ , ( "type"+ , let kw = pure . Keyword . Ident+ in evalOneArg "type" $ \case+ Atom _ -> kw "atom"+ Keyword _ -> kw "keyword"+ String _ -> kw "string"+ Number _ -> kw "number"+ Boolean _ -> kw "boolean"+ List _ -> kw "list"+ Primop _ -> kw "primop"+ Dict _ -> kw "dict"+ Ref _ -> kw "ref"+ Lambda{} -> kw "lambda"+ ), ("string?", evalOneArg "string?" $ \caseString _ -> pure tt_ -> pure ff)@@ -150,18 +209,17 @@ purePrimops = fromList $ first Ident <$>$ TypeError "member?: second argument must be list"xs -> throwError $ WrongNumberOfArgs "eq?" 2 (length xs)), ("if", \args -> case args of- [cond, t, f] -> do- b <- baseEval cond+ [condition, t, f] -> do+ b <- baseEval condition-- I hate this as much as everyone that might ever read Haskell, but-- in Lisps a lot of things that one might object to are True...if b == ff then baseEval f else baseEval txs -> throwError $ WrongNumberOfArgs "if" 3 (length xs))+ , ( "cond", (cond =<<) . evenArgs "cond" ), ("ref", evalOneArg "ref" newRef), ("read-ref", evalOneArg "read-ref" $ \case- Ref (Reference x) -> gets bindingsRefs >>= \m -> case IntMap.lookup x m of- Nothing -> throwError $ Impossible "undefined reference"- Just v -> pure v- _ -> throwError $ TypeError "read-ref: argument must be a ref")+ Ref ref -> readRef ref+ _ -> throwError $ TypeError "read-ref: argument must be a ref"), ("write-ref", evalArgs $ \args -> case args of[Ref (Reference x), v] -> dost <- get@@ -177,17 +235,31 @@ purePrimops = fromList $ first Ident <$>\casex@(List _) -> pure xDict kvs -> pure $ List [List [k, v] | (k,v) <- Map.toList kvs ]- _ -> throwError $ TypeError "seq: can only create a list from a list of a dict"+ _ -> throwError $ TypeError "seq: can only create a list from a list or a dict")]where- -- Many primops evaluate their arguments just as normal functions do.- evalArgs f args = traverse baseEval args >>= f- -- Many primops evaluate a single argument.- evalOneArg fname f = evalArgs $ \case- [x] -> f x- xs -> throwError $ WrongNumberOfArgs fname 1 (length xs)+ cond = \case+ [] -> pure nil+ (c,e):ps -> do+ b <- baseEval c+ if b /= ff+ then baseEval e+ else cond ps++ indexMay :: Int -> [a] -> Maybe a+ indexMay _ [] = Nothing+ indexMay 0 (x:_) = pure x+ indexMay n (_:xs) = indexMay (n - 1) xs++ -- | Some forms/functions expect an even number or arguments.+ evenArgs name = \case+ [] -> pure []+ [_] -> throwError . OtherError $ name <> ": expects an even number of arguments"+ x:y:xs -> do+ ps <- evenArgs name xs+ pure ((x,y):ps)tt = Boolean Trueff = Boolean False@@ -204,3 +276,64 @@ purePrimops = fromList $ first Ident <$>[Number _] -> throwError$ OtherError $ name <> ": expects at least 2 arguments"_ -> throwError $ TypeError $ name <> ": expecting number")++-- * Helpers++-- | Many primops evaluate their arguments just as normal functions do.+evalArgs :: Monad m => ([Value] -> Lang m Value) -> [Value] -> Lang m Value+evalArgs f args = traverse baseEval args >>= f++-- Many primops evaluate a single argument.+evalOneArg :: Monad m => Text -> (Value -> Lang m Value) -> [Value] -> Lang m Value+evalOneArg fname f = evalArgs $ \case+ [x] -> f x+ xs -> throwError $ WrongNumberOfArgs fname 1 (length xs)++readValue :: (MonadError (LangError Value) m, MonadState (Bindings n) m) => Text -> m Value+readValue s = do+ allPrims <- gets bindingsPrimops+ let p = parse "[read-primop]" s (Map.keys allPrims)+ case p of+ Right v -> pure v+ Left e -> throwError $ ThrownError (Ident "parse-error") (String e)++-- | Convert Bindings into a Value that can be used with radicle.+unmakeBindings :: Bindings m -> Value+unmakeBindings bnds = Dict $ Map.fromList+ [ (Keyword $ Ident "env", Dict $ Map.mapKeys Atom $ fromEnv $ bindingsEnv bnds)+ , (Keyword $ Ident "refs", List $ IntMap.elems (bindingsRefs bnds))+ ]++-- | Convert a value into Bindings, or throw an error.+makeBindings :: (Monad m, Monad n) => Value -> Lang m (Bindings n)+makeBindings val = case val of+ Dict d -> do+ env' <- kwLookup "env" d ?? "expecting 'env' key"+ refs' <- kwLookup "refs" d ?? "expecting 'refs' key"+ (nextRef, refs) <- makeRefs refs'+ env <- makeEnv env'+ pure $ Bindings env purePrimops refs nextRef+ _ -> throwError $ TypeError "expecting dict"+ where+ makeEnv env = case env of+ Dict d -> fmap (Env . Map.fromList)+ $ forM (Map.toList d) $ \(k, v) -> case k of+ Atom i -> pure (i, v)+ _ -> throwError $ TypeError "Expecting atom keys"+ _ -> throwError $ TypeError "Expecting dict"++ makeRefs refs = case refs of+ List ls -> pure (length ls, IntMap.fromList $ zip [0..] ls)+ _ -> throwError $ TypeError "Expecting dict"+++kwLookup :: Text -> Map Value Value -> Maybe Value+kwLookup key = Map.lookup (Keyword $ Ident key)++-- | Throws an OtherError with the specified message if the Maybe is not a+-- Just.+(??) :: MonadError (LangError Value) m => Maybe a -> Text -> m a+a ?? msg = case a of+ Nothing -> throwError $ OtherError msg+ Just v -> pure v+diff --git a/src/Radicle/Internal/Subscriber.hs b/src/Radicle/Internal/Subscriber.hsindex 388d3e4..ab7dfa2 100644--- a/src/Radicle/Internal/Subscriber.hs+++ b/src/Radicle/Internal/Subscriber.hs@@ -20,15 +20,16 @@ import Radicle.Internal.Subscriber.Capabilitiestype ReplM m =( Monad m, Stdout (Lang m), Stdin (Lang m)+ , ReadFile (Lang m), GetEnv (Lang m) Value, SetEnv (Lang m) Value )-repl :: FilePath -> Text -> IO ()-repl histFile preCode = do+repl :: Maybe FilePath -> Text -> Bindings (InputT IO) -> IO ()+repl histFile preCode bindings = dolet settings = setComplete completion- $ defaultSettings { historyFile = Just histFile }+ $ defaultSettings { historyFile = histFile }r <- runInputT settings- $ fmap fst $ runLang replBindings+ $ fmap fst $ runLang bindings$ void $ interpretMany "[pre]" preCodecase r ofLeft Exit -> pure ()@@ -72,14 +73,7 @@ replPrimops = Map.fromList $ first toIdent <$>xs -> throwError $ WrongNumberOfArgs "set-env!" 2 (length xs)), ("get-line!", \args -> case args of- [] -> do- ln <- getLineS- allPrims <- gets bindingsPrimops- let p = parse "[stdin]" ln (Map.keys allPrims)- case p of- Right v -> pure v- Left e -> throwError $ ThrownError (Ident "parse-error")- (String e)+ [] -> String <$> getLineSxs -> throwError $ WrongNumberOfArgs "get-line!" 0 (length xs)), ("subscribe-to!", \args -> case args of@@ -91,8 +85,17 @@ replPrimops = Map.fromList $ first toIdent <$>(Dict m, fn) -> case Map.lookup (Atom $ toIdent "getter") m ofNothing -> throwError$ OtherError "subscribe-to!: Expected 'getter' key"- Just g -> forever go+ Just g -> forever (protect go)where+ protect action = do+ st <- get+ action `catchError`+ (\err -> case err of+ Exit -> throwError err+ Impossible _ -> do+ putStrS (renderPrettyDef err)+ throwError err+ _ -> putStrS (renderPrettyDef err) >> put st)go = do-- We need to evaluate the getter in the original-- environment in which it was defined, but the@@ -105,4 +108,14 @@ replPrimops = Map.fromList $ first toIdent <$>void $ withEnv (const e) (fn $$ [quote line])_ -> throwError $ TypeError "subscribe-to!: Expected dict"xs -> throwError $ WrongNumberOfArgs "subscribe-to!" 2 (length xs))+ , ( "read-file!"+ , evalOneArg "read-file" $ \case+ String filename -> String <$> readFileS filename+ _ -> throwError $ TypeError "read-file: expects a string"+ )+ , ( "load!"+ , evalOneArg "load" $ \case+ String filename -> readFileS filename >>= interpretMany "[load!]"+ _ -> throwError $ TypeError "load: expects a string"+ )]diff --git a/src/Radicle/Internal/Subscriber/Capabilities.hs b/src/Radicle/Internal/Subscriber/Capabilities.hsindex 15a56c9..485e78d 100644--- a/src/Radicle/Internal/Subscriber/Capabilities.hs+++ b/src/Radicle/Internal/Subscriber/Capabilities.hs@@ -2,12 +2,17 @@---- The intent is that any set of primops may wear on their sleaves (i.e.-- constraints) what effects they do.+{-# LANGUAGE CPP #-}module Radicle.Internal.Subscriber.Capabilities whereimport Protoludeimport Data.Text.Prettyprint.Doc (PageWidth)import System.Console.Haskeline+#ifdef ghcjs_HOST_OS+import GHCJS.DOM.XMLHttpRequest (getResponseText, newXMLHttpRequest,+ openSimple, send)+#endifimport Radicle.Internal.Core@@ -51,6 +56,29 @@ class (Monad m) => GetSubs m whereclass (Monad m) => SetSubs m wheresetSubS :: Text -> (Value -> m ()) -> m ()+class (Monad m) => ReadFile m where+ readFileS :: Text -> m Text+#ifdef ghcjs_HOST_OS+instance ReadFile (InputT IO) where+ readFileS = lift . requestFile+ where+ requestFile :: Text -> IO Text+ requestFile filename = do+ req <- newXMLHttpRequest+ openSimple req ("GET" :: Text) filename+ send req+ resp <- getResponseText req+ pure $ case resp of+ Nothing -> ""+ Just v -> v+#else+instance ReadFile (InputT IO) where+ readFileS = lift . readFile . toS+#endif+instance {-# OVERLAPPABLE #-} ReadFile m => ReadFile (Lang m) where+ readFileS = lift . readFileS++putStrLnS :: (Stdout m) => Text -> m ()putStrLnS t = putStrS t >> putStrS "\n"diff --git a/stack-ghcjs.yaml b/stack-ghcjs.yamlnew file mode 100644index 0000000..c9c71d3--- /dev/null+++ b/stack-ghcjs.yaml@@ -0,0 +1,51 @@+resolver: lts-7.24+compiler: ghcjs-0.2.1.9007019_ghc-8.0.1+compiler-check: match-exact++setup-info:+ ghcjs:+ source:+ ghcjs-0.2.1.9007019_ghc-8.0.1:+ url: http://ghcjs.tolysz.org/ghc-8.0-2017-02-05-lts-7.19-9007019.tar.gz+ sha1: d2cfc25f9cda32a25a87d9af68891b2186ee52f9+packages:+- .+extra-deps:+- git: [email protected]:well-typed/cborg.git+ commit: 37de2c0ae6bc7fa53f24f8d13748a7c370da9149+ subdirs:+ - serialise+ - cborg+- git: https://github.com/ghcjs/ghcjs-base.git+ commit: 3bb9ed0ffd3f384ed37456b4d6247be732c79c8e+- git: [email protected]:haskell-servant/servant.git+ commit: c3caa149551843fdd74eb5abf3251a16547161dd+ subdirs:+ - servant+ - servant-client-ghcjs+ - servant-client-core+- aeson-1.2.4.0+- attoparsec-0.13.2.2+- attoparsec-iso8601-1.0.0.0+- cabal-doctest-1.0.6+- case-insensitive-1.2.0.11+- free-4.12.4+- natural-transformation-0.4+- th-abstraction-0.2.8.0+- mmorph-1.1.2+- singleton-bool-0.1.4+- vault-0.3.1.2+- base-compat-0.9.3+- exceptions-0.10.0+- generics-sop-0.3.2.0+- http-api-data-0.3.8.1+- http-media-0.7.1.2+- http-types-0.12.1+- safe-0.3.17+- text-1.2.3.0+- megaparsec-6.4.1+- parser-combinators-0.4.0+- prettyprinter-1.2.1+- prettyprinter-ansi-terminal-1.1.1.2+- ghcjs-dom-0.9.2.0+- ghcjs-dom-jsffi-0.9.2.0diff --git a/stack.yaml b/stack.yamlindex b4d7d51..9f6fa7b 100644--- a/stack.yaml+++ b/stack.yaml@@ -39,7 +39,16 @@ packages:- .# Dependency packages to be pulled from upstream that are not in the resolver# (e.g., acme-missiles-0.3)-# extra-deps: []+extra-deps:+- serialise-0.2.0.0+- cborg-0.2.0.0++image:+ containers:+ - base: "fpco/ubuntu-with-libgmp:14.04"+ name: "radicle/server"+ executables:+ - server# Override default flag values for local packages and extra-deps# flags: {}@@ -63,4 +72,4 @@ packages:# extra-lib-dirs: [/path/to/dir]## Allow a newer minor version of GHC than the snapshot specifies-# compiler-check: newer-minor\ No newline at end of file+# compiler-check: newer-minordiff --git a/static/issues.html b/static/issues.htmlnew file mode 100644index 0000000..61efcbb--- /dev/null+++ b/static/issues.html@@ -0,0 +1,17 @@+<!DOCTYPE html>+<html>+ <head>+ <meta charset="UTF-8" />+ <title>Radicle issues</title>+ </head>+ <body>++ <div id="issues_container"></div>++ <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>+ <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>++ <script src="issues.js"></script>++ </body>+</html>diff --git a/static/issues.js b/static/issues.jsnew file mode 100644index 0000000..7059f3a--- /dev/null+++ b/static/issues.js@@ -0,0 +1,65 @@+'use strict';++// Get outputs of a chain.+var getOutputsByChain = function(chain, onSuccess, onError) {+ var xhr = new XMLHttpRequest();+ xhr.open('GET', '/outputs/' + encodeURIComponent(chain) + '', true);+ xhr.setRequestHeader('Accept', 'application/json');+ xhr.onreadystatechange = function () {+ var res = null;+ if (xhr.readyState === 4) {+ if (xhr.status === 204 || xhr.status === 205) {+ onSuccess();+ } else if (xhr.status >= 200 && xhr.status < 300) {+ try { res = JSON.parse(xhr.responseText); } catch (e) { onError(e); }+ if (res) onSuccess(res);+ } else {+ try { res = JSON.parse(xhr.responseText); } catch (e) { onError(e); }+ if (res) onError(res);+ }+ }+ };+ xhr.send(null);+};+++const e = React.createElement;++// Display an issue (to be replaced by Julien's component).+function Issue(props) {+ return e(+ "div",+ {},+ JSON.stringify(props.issue)+ );+}++class Issues extends React.Component {+ constructor(props) {+ super(props);+ this.state = { issues: [], error: null };+ var self = this;++ setInterval(function(){+ getOutputsByChain("issues",+ function(d){ self.setState({issues: d}); },+ function(err){ self.setState({error: err}); }+ );+ }, 1000);+ }++ render() {+ console.log("rendering!");+ console.log(this.state);+ if (this.state.error != null) {+ return "There was an error! " + this.state.error ;+ }++ return this.state.issues.filter(i => i.hasOwnProperty("issue_id")).map(+ (i) => e("div", {key: i.issue_id}, e(Issue, {issue: i}))+ );+ }+}++const domContainer = document.querySelector('#issues_container');+ReactDOM.render(e(Issues), domContainer);diff --git a/test/docs/Main.hs b/test/docs/Main.hsindex 8d9d5ea..582c921 100644--- a/test/docs/Main.hs+++ b/test/docs/Main.hs@@ -9,6 +9,8 @@ import Test.DocTestmain :: IO ()main = doRight pkg <- fmap decodeResultPackage <$> readPackageConfig defaultDecodeOptions- let Just exts = sectionDefaultExtensions <$> packageLibrary pkg+ exts <- case sectionDefaultExtensions <$> packageLibrary pkg of+ Just es -> pure es+ Nothing -> die "No default-extensions in package.yaml"srcs <- glob "src/**/*.hs"doctest $ srcs ++ fmap ("-X" ++) extsdiff --git a/test/spec/Radicle/Internal/TestCapabilities.hs b/test/spec/Radicle/Internal/TestCapabilities.hsindex 70d956b..d6aafce 100644--- a/test/spec/Radicle/Internal/TestCapabilities.hs+++ b/test/spec/Radicle/Internal/TestCapabilities.hs@@ -4,33 +4,49 @@ module Radicle.Internal.TestCapabilities whereimport Protolude+import qualified Data.Map.Strict as Map+import qualified System.FilePath.Find as FP+import Radicleimport Radicle.Internal.Subscriber.Capabilities+import Paths_radicle+data WorldState = WorldState{ worldStateStdin :: [Text], worldStateStdout :: [Text], worldStateEnv :: Env Value+ , worldStateFiles :: Map Text Text}type TestLang = Lang (State WorldState)-- | Run a possibly side-effecting program with the given stdin input lines.-runTestWith+runTestWithFiles:: Bindings (State WorldState)-> [Text] -- The stdin (errors if it runs out)+ -> Map Text Text -- The files-> Text -- The program-> (Either (LangError Value) Value, [Text])-runTestWith bindings inputs action =+runTestWithFiles bindings inputs files action =let ws = WorldState{ worldStateStdin = inputs, worldStateStdout = [], worldStateEnv = bindingsEnv bindings+ , worldStateFiles = files}in case runState (fmap fst $ runLang bindings $ interpretMany "[test]" action) ws of(val, st) -> (val, reverse $ worldStateStdout st)+-- | Run a possibly side-effecting program with the given stdin input lines.+runTestWith+ :: Bindings (State WorldState)+ -> [Text] -- The stdin (errors if it runs out)+ -> Text -- The program+ -> (Either (LangError Value) Value, [Text])+runTestWith bindings inputs action = runTestWithFiles bindings inputs mempty action+-- | Like `runTestWith`, but uses the pureEnvrunTestWith':: [Text]@@ -49,14 +65,28 @@ runTest bnds prog = fst $ runTestWith bnds [] progrunTest' :: Text -> Either (LangError Value) ValuerunTest' = runTest pureEnv+-- | The radicle source files, along with their directory.+sourceFiles :: IO (FilePath, [FilePath])+sourceFiles = do+ dir <- getDataDir+ allFiles <- FP.find FP.always (FP.extension FP.==? ".rad") dir+ pure (dir <> "/", drop (length dir + 1) <$> allFiles)+instance {-# OVERLAPPING #-} Stdin TestLang wheregetLineS = dows <- lift getcase worldStateStdin ws of- [] -> throwError $ OtherError "test: out of stdin"+ [] -> throwError Exith:hs -> lift (put $ ws { worldStateStdin = hs }) >> pure hinstance {-# OVERLAPPING #-} Stdout TestLang whereputStrS t = lift $modify (\ws -> ws { worldStateStdout = t:worldStateStdout ws })++instance {-# OVERLAPPING #-} ReadFile TestLang where+ readFileS fn = do+ fs <- lift $ gets worldStateFiles+ case Map.lookup fn fs of+ Just f -> pure f+ Nothing -> throwError . OtherError $ "File not found: " <> fndiff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hsindex 0d5d401..73b3d7a 100644--- a/test/spec/Radicle/Tests.hs+++ b/test/spec/Radicle/Tests.hs@@ -3,12 +3,13 @@ module Radicle.Tests whereimport Protolude hiding (toList)-import Data.List (isSuffixOf)+import Data.List (isInfixOf, isSuffixOf)+import qualified Data.Map.Strict as Map+import Data.Maybe (fromJust)import Data.String.Interpolate (i)import Data.String.QQ (s)import qualified Data.Text as Timport GHC.Exts (fromList, toList)-import System.Directory (getDirectoryContents)import Test.Tastyimport Test.Tasty.HUnitimport Test.Tasty.QuickCheck (counterexample, testProperty, (==>))@@ -18,8 +19,6 @@ import Radicle.Internal.Arbitrary ()import Radicle.Internal.Core (toIdent)import Radicle.Internal.TestCapabilities-import Paths_radicle-test_eval :: [TestTree]test_eval =[ testCase "Fails for undefined atoms" $@@ -114,17 +113,22 @@ test_eval =counterexample (toS info) $ res == expected, testCase "'foldl' foldls the list" $ do- let prog = [s|(foldl - 0 (list 1 2 3))|]+ let prog = [s|(foldl (lambda (x y) (- x y)) 0 (list 1 2 3))|]prog `succeedsWith` Number (-6), testCase "'foldr' foldrs the list" $ do- let prog = [s|(foldr - 0 (list 1 2 3))|]+ let prog = [s|(foldr (lambda (x y) (- x y)) 0 (list 1 2 3))|]prog `succeedsWith` Number 2, testCase "'map' maps over the list" $ dolet prog = [s|(map (lambda (x) (+ x 1)) (list 1 2))|]prog `succeedsWith` List [Number 2, Number 3]+ , testCase "'map' (and co.) don't over-eval elements of argument list" $ do+ let prog = [s|(map (lambda (x) (cons 1 x)) (list (list 1)))+ |]+ prog `succeedsWith` List [List [Number 1, Number 1]]+, testCase "'eval' evaluates the list" $ dolet prog = [s|(eval (quote #t))|]prog `succeedsWith` Boolean True@@ -145,6 +149,14 @@ test_eval =<> "\nGot:\n" <> prettyEither res1counterexample (toS info) $ res1 == res2+ , testCase "'eval-with-env' has access to variable definitions" $ do+ let prog = [s|(head (eval-with-env+ 't+ (dict :env (dict 'eval 'base-eval 't #t)+ :refs (list))))+ |]+ prog `succeedsWith` Boolean True+, testCase "lambdas work" $ dolet prog = [s|((lambda (x) x) #t)|]prog `succeedsWith` Boolean True@@ -194,6 +206,7 @@ test_eval =, testCase "'keyword?' is false for non keywords" $ do"(keyword? #t)" `succeedsWith` Boolean False+, testCase "'do' returns the empty list if called on nothing" $ do"(do)" `succeedsWith` List []@@ -234,6 +247,29 @@ test_eval =let prog = [s|(number? #t)|]prog `succeedsWith` Boolean False+ , testCase "'list?' works" $ do+ "(list? '(1 :foo ))" `succeedsWith` Boolean True+ "(list? '())" `succeedsWith` Boolean True+ "(list? :foo)" `succeedsWith` Boolean False++ , testCase "'dict?' works" $ do+ "(dict? (dict))" `succeedsWith` Boolean True+ "(dict? (dict :key 2))" `succeedsWith` Boolean True+ "(dict? :foo)" `succeedsWith` Boolean False++ , testCase "'type' returns the type, as a keyword" $ do+ let hasTy prog ty = prog `succeedsWith` Keyword (Ident ty)+ "(type :keyword)" `hasTy` "keyword"+ "(type \"string\")" `hasTy` "string"+ "(type 'a)" `hasTy` "atom"+ "(type 1)" `hasTy` "number"+ "(type #t)" `hasTy` "boolean"+ "(type list?)" `hasTy` "primop"+ "(type (list 1 2 3))" `hasTy` "list"+ "(type (dict 1 2))" `hasTy` "dict"+ "(type (ref 0))" `hasTy` "ref"+ "(type (lambda (x) x))" `hasTy` "lambda"+, testCase "'+' sums the list of numbers" $ dolet prog1 = [s|(+ 2 (+ 2 3))|]prog1 `succeedsWith` Number 7@@ -362,6 +398,9 @@ test_eval =runTest' "eval" @?= Right (Primop (toIdent "base-eval"))runTest' "(show (dict 'a 1))" @?= Right (String "(dict a 1.0)")runTest' "(show (lambda (x) x))" @?= Right (String "(lambda (x) x)")++ , testCase "'read' works" $+ runTest' "(read \"(:hello 42)\")" @?= Right (List [Keyword (toIdent "hello"), Number 42])]wherefailsWith src err = runTest' src @?= Left err@@ -381,7 +420,6 @@ test_parser ="base-eval" ~~> Primop (toIdent "base-eval"), testCase "parses keywords" $ do- let kw = Keyword . toIdent":foo" ~~> kw "foo"":what?crazy!" ~~> kw "what?crazy!"":::" ~~> kw "::"@@ -435,7 +473,29 @@ test_pretty =<> "reparsed: " <> show v <> "\n"<> "original: " <> show original <> "\n"in counterexample info $ actual == Right original++ , testCase "long lists are indented" $ do+ let r = renderPretty (apl 5) (List [String "fn", String "abc"])+ r @?= "(\"fn\"\n \"abc\")"++ , testCase "lists try to fit on one line" $ do+ let r = renderPretty (apl 80) (List [atom "fn", atom "arg1", atom "arg2"])+ r @?= "(fn arg1 arg2)"++ , testCase "dicts try to fit on one line" $ do+ let r = renderPretty (apl 80) (Dict $ Map.fromList [ (kw "k1", Number 1)+ , (kw "k2", Number 2)+ ])+ r @?= "(dict :k1 1.0 :k2 2.0)"++ , testCase "dicts split with key-val pairs" $ do+ let r = renderPretty (apl 5) (Dict $ Map.fromList [ (kw "k1", Number 1)+ , (kw "k2", Number 2)+ ])+ r @?= "(dict\n :k1 1.0\n :k2 2.0)"]+ where+ apl cols = AvailablePerLine cols 1test_env :: [TestTree]test_env =@@ -445,25 +505,34 @@ test_env =test_repl_primops :: [TestTree]test_repl_primops =- [ testProperty "get-line! returns the input line" $ \(v :: Value) ->- let prog = [i|(eq? (get-line!) (quote #{renderPrettyDef v}))|]+ [ 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 progin counterexample prog $ res == Right (Boolean True)- , testCase "catch catches get-line errors" $ do+ , testCase "catch catches read-line errors" $ dolet prog = [s|- (define repl (dict 'name "repl" 'getter get-line!))- (catch 'any- (subscribe-to! repl (lambda (x) (print! x)))- (lambda (x) "caught"))+ (catch 'any (read-line!) (lambda (x) "caught"))|]input = ["\"blah"]res = run input progres @?= 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")+ , testCase "load! can load definitions" $ do+ let prog = [s|+ (load! "foo.rad")+ (+ foo bar)+ |]+ files = Map.singleton "foo.rad" "(define foo 42) (define bar 8)"+ runFiles files prog @?= Right (Number 50)]whererun stdin' prog = fst $ runTestWith replBindings stdin' prog-+ runFiles :: Map Text Text -> Text -> Either (LangError Value) Value+ runFiles files prog = fst $ runTestWithFiles replBindings [] files progtest_repl :: [TestTree]test_repl =@@ -471,7 +540,7 @@ test_repl =let input = [ "((lambda (x) x) #t)" ]output = [ "#t" ](_, result) <- runInRepl input- result @?= output+ result @==> output, testCase "handles env modifications" $ dolet input = [ "(define id (lambda (x) x))"@@ -481,7 +550,7 @@ test_repl =, "#t"](_, result) <- runInRepl input- result @?= output+ result @==> output, testCase "handles 'eval' redefinition" $ dolet input = [ "(define eval (lambda (x) #t))"@@ -491,7 +560,7 @@ test_repl =, "#t"](_, result) <- runInRepl input- result @?= output+ result @==> output, testCase "(define eval (quote base-eval)) doesn't change things" $ dolet input = [ "(define eval (quote base-eval))"@@ -503,25 +572,30 @@ test_repl =, "#t"](_, result) <- runInRepl input- result @?= output+ result @==> output]where- getCfg = getDataFileName "repl/config.rad" >>= readFile- -- The repl catches exceptions, including the "out of stdin" exception- -- that occurs at the end of a session, so we take the 'init' of the- -- result.- runInRepl inp = fmap initSafe <$> (runTestWith replBindings inp <$> getCfg)+ -- In addition to the output of the lines tested, 'should-be's get+ -- printed, so we take only the last few output lines.+ r @==> out = reverse (take (length out) $ reverse r) @?= out+ -- Find repl.rad, give it all other files as possible imports, and run+ -- it.+ runInRepl inp = do+ (dir, srcs) <- sourceFiles+ srcMap <- forM srcs (\src -> (T.pack src ,) <$> readFile (dir <> src))+ let replSrc = head [ src | (name, src) <- srcMap+ , "repl.rad" `T.isSuffixOf` name+ ]+ pure $ runTestWithFiles replBindings inp (Map.fromList srcMap) (fromJust replSrc)-- Tests all radicle files 'repl' dir. These should use the 'should-be'-- function to ensure they are in the proper format.test_source_files :: IO TestTreetest_source_files = testGroup "Radicle source file tests" <$> do- oneOf'Em <- getDataFileName "repl/config.rad"- let dir = reverse $ drop (T.length ("config.rad" :: Text)) $ reverse oneOf'Em- files <- getDirectoryContents dir- let radFiles = filter (".rad" `isSuffixOf`) files+ (dir, files) <- sourceFiles+ let radFiles = filter (\x -> ".rad" `isSuffixOf` x && "repl." `isInfixOf` x) filessequence $ radFiles <&> \file -> do- contents <- readFile $ dir <> file+ contents <- readFile (dir <> file)let (_, out) = runTestWith replBindings [] contentslet makeTest line = let (name, result) = T.span (/= '\'')$ T.drop 1@@ -532,6 +606,20 @@ test_source_files = testGroup "Radicle source file tests" <$> do-- * Utils+kw :: Text -> Value+kw = Keyword . toIdent++atom :: Text -> Value+atom = Atom . toIdent++-- -- | 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 (Map.keys $ bindingsPrimops e)+ where+ e :: Bindings (Lang Identity)+ e = pureEnv+-- | Environments are neither printed nor parsed, but are generated by the-- arbitrary instance.removeEnv :: Value -> Value