A peer-to-peer stack for code collaboration
[WIP/RFC] Documentation functionality (#177)
James Haydon7624b8e616ea
diff --git a/exe/Server/Client.hs b/exe/Server/Client.hsindex 8b83161..98150ee 100644--- a/exe/Server/Client.hs+++ b/exe/Server/Client.hs@@ -1,3 +1,5 @@+{-# LANGUAGE QuasiQuotes #-}+module Client whereimport API@@ -13,6 +15,9 @@ import Radicleimport Servant.Clientimport System.Console.Haskeline (InputT)+import Radicle.Internal.Doc (md)+import qualified Radicle.Internal.PrimFns as PrimFns+main :: IO ()main = doopts' <- execParser allOpts@@ -58,10 +63,12 @@ bindings :: HttpClient.Manager -> Bindings (PrimFns (InputT IO))bindings mgr = addPrimFns (replPrimFns <> clientPrimFns mgr) pureEnvclientPrimFns :: HttpClient.Manager -> PrimFns (InputT IO)-clientPrimFns mgr = PrimFns (fromList [sendPrimop, receivePrimop])+clientPrimFns mgr = fromList . PrimFns.allDocs $ [sendPrimop, receivePrimop]wheresendPrimop =- ( unsafeToIdent "send!"+ ( "send!"+ , [md|Given a URL (string) and a value, sends the value `v` to the remote+ chain located at the URL for evaluation.|], \case[String url, v] -> dores <- liftIO $ runClientM' url mgr (submit v)@@ -73,7 +80,9 @@ clientPrimFns mgr = PrimFns (fromList [sendPrimop, receivePrimop])xs -> throwErrorHere $ WrongNumberOfArgs "send!" 2 (length xs))receivePrimop =- ( unsafeToIdent "receive!"+ ( "receive!"+ , [md|Given a URL (string) and a integral number `n`, queries the remote chain+ for the last `n` inputs that have been evaluated.|], \case[String url, Number n] -> docase floatingOrInteger n ofdiff --git a/package.yaml b/package.yamlindex 5f0821e..ab9ce1d 100644--- a/package.yaml+++ b/package.yaml@@ -31,6 +31,9 @@ dependencies:- cryptonite- generics-eot- uuid+- data-default+- pandoc-types+- pandocwhen:- condition: impl(ghcjs)dependencies: ghcjs-domdiff --git a/rad/prelude.rad b/rad/prelude.radindex ec004ba..141bb02 100644--- a/rad/prelude.rad+++ b/rad/prelude.rad@@ -1,9 +1,7 @@-(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/maybe.rad")(load! "rad/prelude/list.rad")(load! "rad/prelude/dict.rad")(load! "rad/prelude/ref.rad")@@ -13,7 +11,6 @@(def pure-prelude-files(list- "rad/prelude/doc.rad""rad/prelude/pure-should-be.rad""rad/prelude/recursion.rad""rad/prelude/bool.rad"diff --git a/rad/prelude/doc.rad b/rad/prelude/doc.raddeleted file mode 100644index 8cb2b8b..0000000--- a/rad/prelude/doc.rad+++ /dev/null@@ -1,28 +0,0 @@-;; doc-related functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;--(def document- (fn [name args description]- (def 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--(def doc- (fn [name]- (def the-doc (lookup name (read-ref _doc-ref)))- (if (eq? the-doc '())- (string-append "No documentation found for " (show name))- (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.")diff --git a/rad/prelude/maybe.rad b/rad/prelude/maybe.raddeleted file mode 100644index 193a3d1..0000000--- a/rad/prelude/maybe.rad+++ /dev/null@@ -1,16 +0,0 @@-(def map-maybe- (fn [f]- (fn [m]- (maybe m :Nothing (fn [x] [:Just (f x)])))))--(document 'map-maybe- '(("f" function))- "Functor mapping for Maybe values.")--(should-be "map-maybe maps :Nothing"- ((map-maybe (fn [x] (+ x 1))) :Nothing)- :Nothing)--(should-be "map-maybe maps :Just"- ((map-maybe (fn [x] (+ x 1))) [:Just 0])- [:Just 1])diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hsindex 693399b..359760f 100644--- a/src/Radicle/Internal/Core.hs+++ b/src/Radicle/Internal/Core.hs@@ -30,6 +30,7 @@ import qualified Text.Megaparsec.Error as Parimport Radicle.Internal.Annotation (Annotated)import qualified Radicle.Internal.Annotation as Ann+import qualified Radicle.Internal.Doc as Docimport qualified Radicle.Internal.Identifier as Identifierimport Radicle.Internal.Orphans ()@@ -206,7 +207,6 @@ pattern Lambda vs exps env <- (Ann.match -> LambdaF vs exps env)whereLambda vs exps env = Ann.annotate $ LambdaF vs exps env-type UntaggedValue = Annotated Identity ValueFtype Value = Annotated Ann.WithPos ValueF@@ -287,18 +287,23 @@ unsafeToIdent :: Text -> IdentunsafeToIdent = 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, Serialise)+newtype Env s = Env { fromEnv :: Map Ident (Doc.Docd s) }+ deriving (Eq, Ord, Semigroup, Monoid, Show, Read, Generic, Functor, Foldable, Traversable, Serialise)instance GhcExts.IsList (Env s) where- type Item (Env s) = (Ident, s)- fromList = Env . Map.fromList- toList = GhcExts.toList . fromEnv+ type Item (Env s) = (Ident, Maybe Text, s)+ fromList xs = Env . Map.fromList $ [ (i, Doc.Docd d x)| (i, d, x) <- xs ]+ toList e = [ (i, d, x) | (i, Doc.Docd d x) <- GhcExts.toList . fromEnv $ e]--- | Primop mappings. The parameter specifies the monad the primops run in.-newtype PrimFns m = PrimFns { getPrimFns :: Map Ident ([Value] -> Lang m Value) }+-- | PrimFn mappings. The parameter specifies the monad the primops run in.+newtype PrimFns m = PrimFns { getPrimFns :: Map Ident (Doc.Docd ([Value] -> Lang m Value)) }deriving (Semigroup, Monoid)+instance GhcExts.IsList (PrimFns m) where+ type Item (PrimFns m) = (Ident, Maybe Text, [Value] -> Lang m Value)+ fromList xs = PrimFns . Map.fromList $ [ (i, Doc.Docd d x)| (i, d, x) <- xs ]+ toList e = [ (i, d, x) | (i, Doc.Docd d x) <- GhcExts.toList . getPrimFns $ e]+-- | Bindings, either from the env or from the primops.data Bindings prims = Bindings{ bindingsEnv :: Env Value@@ -359,24 +364,30 @@ withEnv modifier action = do-- * Functions-addBinding :: Ident -> Value -> Bindings m -> Bindings m-addBinding i v b = b- { bindingsEnv = Env . Map.insert i v . fromEnv $ bindingsEnv b }+addBinding :: Ident -> Maybe Text -> Value -> Bindings m -> Bindings m+addBinding i d v b = b+ { bindingsEnv = Env . Map.insert i (Doc.Docd d v) . fromEnv $ bindingsEnv b }++lookupAtomWithDoc :: Monad m => Ident -> Lang m (Doc.Docd Value)+lookupAtomWithDoc i = get >>= \e -> case Map.lookup i . fromEnv $ bindingsEnv e of+ Nothing -> throwErrorHere $ UnknownIdentifier i+ Just x -> pure x-- | Lookup an atom in the environmentlookupAtom :: Monad m => Ident -> Lang m Value-lookupAtom i = get >>= \e -> case Map.lookup i . fromEnv $ bindingsEnv e of- Nothing -> throwErrorHere $ UnknownIdentifier i- Just v -> pure v+lookupAtom = fmap copoint . lookupAtomWithDoc++lookupAtomDoc :: Monad m => Ident -> Lang m (Maybe Text)+lookupAtomDoc = fmap Doc.doc . lookupAtomWithDoc-- | Lookup a primop.lookupPrimop :: Monad m => Ident -> Lang m ([Value] -> Lang m Value)lookupPrimop i = get >>= \e -> case Map.lookup i $ getPrimFns $ bindingsPrimFns e ofNothing -> throwErrorHere $ Impossible $ "Unknown primop " <> fromIdent i- Just v -> pure v+ Just v -> pure (copoint v)-defineAtom :: Monad m => Ident -> Value -> Lang m ()-defineAtom i v = modify $ addBinding i v+defineAtom :: Monad m => Ident -> Maybe Text -> Value -> Lang m ()+defineAtom i d v = modify $ addBinding i d v-- * Eval@@ -432,18 +443,22 @@ specialForms = Map.fromList $ first Ident <$>, ("def", \case[Atom name, val] -> doval' <- baseEval val- defineAtom name val'+ defineAtom name Nothing val'pure nil[_, _] -> throwErrorHere $ OtherError "def expects atom for first arg"- xs -> throwErrorHere $ WrongNumberOfArgs "def" 2 (length xs))+ [Atom name, String d, val] -> do+ val' <- baseEval val+ defineAtom name (Just d) val'+ pure nil+ xs -> throwErrorHere $ WrongNumberOfArgs "def" 2 (length xs)), ( "def-rec", \case[Atom name, val] -> doval' <- baseEval valcase val' ofLambda is b e -> do- let v = Lambda is b (Env . Map.insert name v . fromEnv $ e)- defineAtom name v+ let v = Lambda is b (Env . Map.insert name (Doc.Docd Nothing v) . fromEnv $ e)+ defineAtom name Nothing vpure nil_ -> throwErrorHere $ OtherError "def-rec can only be used to define functions"[_, _] -> throwErrorHere $ OtherError "def-rec expects atom for first arg"@@ -499,7 +514,7 @@ instance (CPA t, FromRad t a) => FromRad t (Maybe a) wherefromRad (Vec (Keyword (Ident "Just") :<| x :<| Empty)) = Just <$> fromRad xfromRad (Keyword (Ident "Nothing")) = pure NothingfromRad _ = Left "Expecting :Nothing or [:Just _]"-instance FromRad Ann.WithPos Value where+instance FromRad t (Annotated t ValueF) wherefromRad = pureinstance CPA t => FromRad t Scientific wherefromRad x = case x of@@ -526,11 +541,17 @@ instance (CPA t, FromRad t a) => FromRad t [a] whereList xs -> traverse fromRad xsVec xs -> traverse fromRad (toList xs)_ -> Left "Expecting list"+instance CPA t => FromRad t (Doc.Docd (Annotated t ValueF)) where+ fromRad v = do+ (d, v') <- fromRad v+ pure (Doc.Docd d v')instance FromRad Ann.WithPos (Env Value) wherefromRad x = case x ofDict d -> fmap (Env . Map.fromList)$ forM (Map.toList d) $ \(k, v) -> case k of- Atom i -> pure (i, v)+ 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@@ -576,8 +597,10 @@ instance (CPA t, ToRad t a) => ToRad t [a] wheretoRad xs = Vec . Seq.fromList $ toRad <$> xsinstance (CPA t, ToRad t a) => ToRad t (Map.Map Text a) wheretoRad xs = Dict $ Map.mapKeys String $ toRad <$> xs+instance CPA t => ToRad t (Doc.Docd (Annotated t ValueF)) where+ toRad (Doc.Docd d v) = toRad (d, v)instance ToRad Ann.WithPos (Env Value) where- toRad x = Dict . Map.mapKeys Atom $ fromEnv x+ toRad x = Dict . Map.mapKeys Atom . Map.map toRad $ fromEnv xinstance ToRad Ann.WithPos (Bindings m) wheretoRad x = Dict $ Map.fromList[ (Keyword $ Ident "env", toRad $ bindingsEnv x)@@ -594,7 +617,7 @@ callFn f vs = case f ofthen throwErrorHere $ WrongNumberOfArgs "lambda" (length bnds)(length vs)else do- let mappings = GhcExts.fromList (zip bnds vs)+ let mappings = GhcExts.fromList (Doc.noDocs $ zip bnds vs)modEnv = mappings <> closureNonEmpty.last <$> withEnv (const modEnv)(traverse baseEval body)diff --git a/src/Radicle/Internal/Doc.hs b/src/Radicle/Internal/Doc.hsnew file mode 100644index 0000000..7b46e31--- /dev/null+++ b/src/Radicle/Internal/Doc.hs@@ -0,0 +1,51 @@+{-# LANGUAGE DuplicateRecordFields #-}+{-# LANGUAGE TemplateHaskell #-}++module Radicle.Internal.Doc where++import Protolude hiding (Any)++import Codec.Serialise (Serialise(..))+import Data.Copointed (Copointed(..))+import qualified Data.Default as Default+import Language.Haskell.TH.Quote+import Text.Pandoc++data Docd a = Docd (Maybe Text) a+ deriving (Show, Read, Functor, Foldable, Traversable, Generic)++instance Serialise a => Serialise (Docd a)++instance Copointed Docd where+ copoint (Docd _ x) = x++doc :: Docd a -> Maybe Text+doc (Docd d _) = d++instance Eq a => Eq (Docd a) where+ Docd _ x == Docd _ y = x == y++instance Ord a => Ord (Docd a) where+ compare (Docd _ x) (Docd _ y) = compare x y++noDocs :: [(a, c)] -> [(a, Maybe b, c)]+noDocs = fmap $ \(x,y) -> (x, Nothing, y)++-- | A quasiquoter that checks if a string is valid pandoc-markdown, then+-- returns the markdown with better formatting.+md :: QuasiQuoter+md = QuasiQuoter+ { quoteExp = \s -> [| case checkPandocMd s of+ Left e -> panic $ "Not valid pandoc-markdown: " <> show e+ Right s' -> s' |]+ , quoteType = err+ , quotePat = err+ , quoteDec = err+ }+ where+ err = panic "pan only works for expressions"++checkPandocMd :: Text -> Either PandocError Text+checkPandocMd s = runPure $ do+ p <- readMarkdown Default.def s+ writeMarkdown Default.def pdiff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hsindex 1b9cdf6..7ab7b5f 100644--- a/src/Radicle/Internal/Effects.hs+++ b/src/Radicle/Internal/Effects.hs@@ -1,12 +1,15 @@{-# OPTIONS_GHC -fno-warn-orphans #-}+{-# LANGUAGE QuasiQuotes #-}+module Radicle.Internal.Effects where-import Protolude hiding (TypeError)+import Protolude hiding (TypeError, toList)import qualified Data.Map as Mapimport qualified Data.Text as Timport Data.Text.Prettyprint.Doc (pretty)import Data.Text.Prettyprint.Doc.Render.Terminal (putDoc)+import GHC.Exts (IsList(..))import System.Console.Haskeline( CompletionFunc, InputT@@ -20,6 +23,7 @@ import System.Console.Haskelineimport Radicle.Internal.Coreimport Radicle.Internal.Crypto+import Radicle.Internal.Doc (md)import Radicle.Internal.Effects.Capabilitiesimport Radicle.Internal.Interpretimport Radicle.Internal.Pretty@@ -73,26 +77,59 @@ replBindings :: forall m. ReplM m => Bindings (PrimFns m)replBindings = addPrimFns replPrimFns pureEnvreplPrimFns :: forall m. ReplM m => PrimFns m-replPrimFns = PrimFns . Map.fromList $ first unsafeToIdent <$>- [ ("print!", \case+replPrimFns = fromList $ allDocs $+ [ ("print!"+ , [md|Pretty-prints a value.|]+ , \case[x] -> doputStrS (renderPrettyDef x)pure nilxs -> throwErrorHere $ WrongNumberOfArgs "print!" 1 (length xs))+ , ( "doc!"+ , [md|Prints the documentation attached to a value and returns `()`. To retreive+ the docstring as a value use `doc` instead.|]+ , oneArg "doc!" $ \case+ Atom i -> do+ d <- lookupAtomDoc i+ putStrS $ fromMaybe "No docs." d+ pure nil+ _ -> throwErrorHere $ TypeError "doc!: expects an atom"+ )++ , ( "apropos!"+ , [md|Prints documentation for all documented variables in scope.|]+ , \case+ [] -> do+ env <- gets bindingsEnv+ let docs = [ i <> "\n" <> doc | (Ident i, Just doc, _) <- toList env ]+ putStrS (T.intercalate "\n\n" docs)+ pure nil+ xs -> throwErrorHere $ WrongNumberOfArgs "apropos!" 0 (length xs)+ )- , ("set-env!", \case+ , ( "set-env!"+ , [md|Given an atom `x` and a value `v`, sets the value associated to `x` in+ the current environemtn to be `v`. Doesn't evaluate `v`.|]+ , \case[Atom x, v] -> do- defineAtom x v+ defineAtom x Nothing vpure nil[_, _] -> throwErrorHere $ TypeError "Expected atom as first arg"xs -> throwErrorHere $ WrongNumberOfArgs "set-env!" 2 (length xs))- , ("get-line!", \case- [] -> String <$> getLineS- xs -> throwErrorHere $ WrongNumberOfArgs "get-line!" 0 (length xs))+ , ( "get-line!"+ , [md|Reads a single line of input and returns it as a string.|]+ , \case+ [] -> String <$> getLineS+ xs -> throwErrorHere $ WrongNumberOfArgs "get-line!" 0 (length xs)+ )- , ("subscribe-to!", \case+ , ("subscribe-to!"+ , [md|Expects a dict `s` (representing a subscription) and a function `f`. The dict+ `s` should have a function `getter` at the key `:getter`. This function is called+ repeatedly (with no arguments), its result is then evaluated and passed to `f`.|]+ , \case[x, v] -> doe <- gets bindingsEnvcase (x, v) of@@ -123,16 +160,21 @@ replPrimFns = PrimFns . Map.fromList $ first unsafeToIdent <$>_ -> throwErrorHere $ TypeError "subscribe-to!: Expected dict"xs -> throwErrorHere $ WrongNumberOfArgs "subscribe-to!" 2 (length xs)), ( "read-file!"+ , [md|Reads the contents of a file and returns it as a string.|], oneArg "read-file" $ \caseString filename -> String <$> readFileS filename_ -> throwErrorHere $ TypeError "read-file: expects a string"), ( "load!"+ , [md|Evaluates the contents of a file. Each seperate radicle expression is+ `eval`uated according to the current definition of `eval`.|], oneArg "load!" $ \caseString filename -> readFileS filename >>= interpretMany ("[load! " <> filename <> "]")_ -> throwErrorHere $ TypeError "load: expects a string"), ( "gen-key-pair!"+ , [md|Given an elliptic curve, generates a cryptographic key-pair. Use+ `default-ecc-curve` for a default value for the elliptic curve.|], \case[curvev] -> docurve <- hoistEither . first (toLangError . OtherError) $ fromRad curvev@@ -146,6 +188,8 @@ replPrimFns = PrimFns . Map.fromList $ first unsafeToIdent <$>xs -> throwErrorHere $ WrongNumberOfArgs "gen-key-pair!" 0 (length xs)), ( "gen-signature!"+ , [md|Given a private key and a message (a string), generates a cryptographic+ signature for the message.|], \case[skv, String msg] -> dosk <- hoistEither . first (toLangError . OtherError) $ fromRad skv@@ -153,6 +197,7 @@ replPrimFns = PrimFns . Map.fromList $ first unsafeToIdent <$>_ -> throwErrorHere $ TypeError "gen-signature!: expects a string."), ( "uuid!"+ , [md|Generates a random UUID.|], \case[] -> String <$> UUID.uuidxs -> throwErrorHere $ WrongNumberOfArgs "uuid!" 0 (length xs)diff --git a/src/Radicle/Internal/PrimFns.hs b/src/Radicle/Internal/PrimFns.hsindex 70261ad..38a8622 100644--- a/src/Radicle/Internal/PrimFns.hs+++ b/src/Radicle/Internal/PrimFns.hs@@ -1,11 +1,6 @@-module Radicle.Internal.PrimFns- ( pureEnv- , addPrimFns- , purePrimFns- , oneArg- , evenArgs- , readValue- ) where+{-# LANGUAGE QuasiQuotes #-}++module Radicle.Internal.PrimFns whereimport Protolude hiding (TypeError)@@ -20,6 +15,8 @@ import GHC.Exts (IsList(..))import qualified Radicle.Internal.Annotation as Annimport Radicle.Internal.Coreimport Radicle.Internal.Crypto+import Radicle.Internal.Doc (md)+import qualified Radicle.Internal.Doc as Docimport Radicle.Internal.Parseimport Radicle.Internal.Prettyimport qualified Radicle.Internal.UUID as UUID@@ -27,12 +24,15 @@ 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 refs 1+ addPrimFns purePrimFns $ Bindings e mempty mempty 0where- e = fromList [ (unsafeToIdent "eval", PrimFn $ unsafeToIdent "base-eval")- , (unsafeToIdent "_doc-ref", Ref $ Reference 0)- ]- refs = fromList [ (0, Dict mempty) ]+ e = fromList . allDocs $+ [ ( "eval"+ , [md|The evaluation function used to evaluate inputs. Intially+ this is set to `base-eval`.|]+ , PrimFn $ unsafeToIdent "base-eval"+ )+ ]-- | The added primitives override previously defined primitives and-- variables with the same name.@@ -43,13 +43,18 @@ addPrimFns primFns bindings =}where- primFnsEnv = Env $ Map.mapWithKey (\k _ -> PrimFn k) (getPrimFns primFns)+ primFnsEnv = Env $ Map.fromList+ $+ [ (pfn, Doc.Docd d (PrimFn pfn)) | (pfn, Doc.Docd d _) <- Map.toList (getPrimFns primFns)]+--- | The universal primops. These are available in chain evaluation, and are--- not shadowable via 'define'.+-- | The universal primops. These are available in chain evaluation.purePrimFns :: forall m. (Monad m) => PrimFns m-purePrimFns = PrimFns $ fromList $ first Ident <$>+purePrimFns = fromList $ allDocs $[ ( "base-eval"+ , [md|The default evaluation function. Expects an expression and a radicle+ 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 ())) ofLeft e -> throwErrorHere $ OtherError e@@ -62,23 +67,32 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>xs -> throwErrorHere $ WrongNumberOfArgs "base-eval" 2 (length xs)), ( "pure-env"+ , [md|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))xs -> throwErrorHere $ WrongNumberOfArgs "pure-env" 0 (length xs))- , ("apply", \case+ , ("apply"+ , [md|Calls the first argument (a function) using as arguments the+ elements of the the second argument (a list).|]+ , \case[fn, List args] -> callFn fn args[_, _] -> throwErrorHere $ TypeError "apply: expecting list as second arg"xs -> throwErrorHere $ WrongNumberOfArgs "apply" 2 (length xs)), ( "read"+ , [md|Parses a string into a radicle value. Does not evaluate the value.|], oneArg "read" $ \caseString s -> readValue s_ -> throwErrorHere $ TypeError "read: expects string")- , ("get-current-env", \case+ , ("get-current-env"+ , [md|Returns the current radicle state.|]+ , \case[] -> toRad <$> getxs -> throwErrorHere $ WrongNumberOfArgs "get-current-env" 0 (length xs)), ( "set-current-env"+ , [md|Replaces the radicle state with the one provided.|], oneArg "set-current-env" $ \x -> doe' :: Bindings () <- fromRadOtherErr xe <- get@@ -88,59 +102,75 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>}pure ok)- , ("list", pure . List)- , ("dict", (Dict . foldr (uncurry Map.insert) mempty <$>)+ , ("list"+ , [md|Turns the arguments into a list.|]+ , pure . List)+ , ("dict"+ , [md|Given an even number of arguments, creates a dict where the `2i`-th argument+ is the key for the `2i+1`th argument.|]+ , (Dict . foldr (uncurry Map.insert) mempty <$>). evenArgs "dict")- , ("throw", \case+ , ("throw"+ , [md|Throws an exception. The first argument should be an atom used as a label for+ the exception, the second can be any value.|]+ , \case[Atom label, exc] -> throwErrorHere $ ThrownError label exc[_, _] -> throwErrorHere $ TypeError "throw: first argument must be atom"xs -> throwErrorHere $ WrongNumberOfArgs "throw" 2 (length xs))- , ("eq?", \case+ , ( "eq?"+ , [md|Checks if two values are equal.|]+ , \case[a, b] -> pure $ Boolean (a == b)xs -> throwErrorHere $ WrongNumberOfArgs "eq?" 2 (length xs))- -- Maybe- , ( "maybe"- , \case- [Keyword (Ident "Nothing"), nothing, _] -> pure nothing- [Vec (Keyword (Ident "Just") :<| v :<| Empty), _, just] -> callFn just [v]- [x, _, _] -> throwErrorHere $ TypeError $ "maybe: first argument should be a Maybe: " <> renderCompactPretty x- xs -> throwErrorHere $ WrongNumberOfArgs "maybe" 3 (length xs)- )--- Vectors, ( "<>"+ , [md|Concatenates two vectors.|], twoArg "<>" $ \case(Vec xs, Vec ys) -> pure $ Vec (xs Seq.>< ys)_ -> throwErrorHere $ TypeError "<>: both arguments must be vectors"), ( "add-left"+ , [md|Adds an element to the left side of a vector.|], twoArg "add-left" $ \case(x, Vec xs) -> pure $ Vec (x :<| xs)_ -> throwErrorHere $ TypeError "add-left: second argument must be a vector"), ( "add-right"+ , [md|Adds an element to the right side of a vector.|], twoArg "add-right" $ \case(x, Vec xs) -> pure $ Vec (xs :|> x)_ -> throwErrorHere $ TypeError "add-right: second argument must be a vector")-- Lists- , ("cons", \case+ , ("cons"+ , [md|Adds an element to the front of a list.|]+ , \case[x, List xs] -> pure $ List (x:xs)[_, _] -> throwErrorHere $ TypeError "cons: second argument must be list"xs -> throwErrorHere $ WrongNumberOfArgs "cons" 2 (length xs))- , ("head", oneArg "head" $ \case+ , ("head"+ , [md|Retrieves the first element of a list if it exists. Otherwise throws an+ exception.|]+ , oneArg "head" $ \caseList (x:_) -> pure xList [] -> throwErrorHere $ OtherError "head: empty list"_ -> throwErrorHere $ TypeError "head: expects list argument")- , ("tail", oneArg "tail" $ \case+ , ("tail"+ , [md|Given a non-empty list, returns the list of all the elements but the+ first. If the list is empty, throws an exception.|]+ , oneArg "tail" $ \caseList (_:xs) -> pure $ List xsList [] -> throwErrorHere $ OtherError "tail: empty list"_ -> throwErrorHere $ TypeError "tail: expects list argument")-- Lists and Vecs, ( "nth"+ , [md|Given an integral number `n` and `xs`, returns the `n`th element+ (zero indexed) of `xs` when `xs` is a list or a vector. If `xs`+ does not have an `n`-th element, or if it is not a list or vector, then+ an exception is thrown.|], \case[Number n, vs] -> case floatingOrInteger n ofLeft (_ :: Double) -> throwErrorHere $ OtherError "nth: first argument was not an integer"@@ -153,7 +183,11 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>xs -> throwErrorHere $ WrongNumberOfArgs "nth" 2 (length xs))- , ("lookup", \case+ , ("lookup"+ , [md|Given a value `k` (the 'key') and a dict `d`, returns the value associated+ with `k` in `d`. If the key does not exist in `d` then `()` is returned+ instead. If `d` is not a dict then an exception is thrown.|]+ , \case[a, Dict m] -> pure $ case Map.lookup a m ofJust v -> v-- Probably an exception is better, but that seems cruel@@ -161,14 +195,9 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>Nothing -> nil[_, _] -> throwErrorHere $ TypeError $ "lookup: second argument must be a dict"xs -> throwErrorHere $ WrongNumberOfArgs "lookup" 2 (length xs))- , ( "safe-lookup"- , twoArg "safe-lookup" $ \case- (a, Dict m) -> pure $ case Map.lookup a m of- Just v -> toRad [kw "Just", v]- Nothing -> kw "Nothing"- _ -> throwErrorHere $ TypeError $ "safe-lookup: second argument must be a dict"- ), ( "map-values"+ , [md|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.|], twoArg "map-values" $ \case(f, Dict m) -> dolet kvs = Map.toList m@@ -176,20 +205,29 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>pure (Dict (Map.fromList (zip (fst <$> kvs) vs)))_ -> throwErrorHere $ TypeError $ "map-values: second argument must be a dict")- , ("string-append", \args ->+ , ("string-append"+ , [md|Concatenates a variable number of string arguments. If one of the arguments+ isn't a string then an exception is thrown.|]+ , \args ->let fromStr (String s) = Just sfromStr _ = Nothingss = fromStr <$> argsin if all isJust ssthen pure . String . mconcat $ catMaybes sselse throwErrorHere $ TypeError "string-append: non-string argument")- , ("insert", \case+ , ( "insert"+ , [md|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 then an exception+ is thrown.|]+ , \case[k, v, Dict m] -> pure . Dict $ Map.insert k v m[_, _, _] -> throwErrorHere$ TypeError "insert: third argument must be a dict"xs -> throwErrorHere $ WrongNumberOfArgs "insert" 3 (length xs)), ( "delete"+ , [md|Given `k` and a dict `d`, returns a dict with the same associations as `d` but+ without the key `k`. If `d` isn't a dict then an exception is thrown.|], twoArg "delete" $ \case(k, Dict m) -> pure . Dict $ Map.delete k m_ -> throwErrorHere $ TypeError "delete: second argument must be a dict"@@ -202,45 +240,71 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>---- In order to avoid this sort of thing, we don't allow +,*,- and / to be-- applied to a single argument.- , numBinop (+) "+"- , numBinop (*) "*"- , numBinop (-) "-"- , ("<", \case+ , numBinop (+) "+" [md|Adds two numbers together.|]+ , numBinop (*) "*" [md|Multiplies two numbers together.|]+ , numBinop (-) "-" [md|Substracts one number from another.|]+ , ( "<"+ , [md|Checks if a number is strictly less than another.|]+ , \case[Number x, Number y] -> pure $ Boolean (x < y)[_, _] -> throwErrorHere $ TypeError "<: expecting number"xs -> throwErrorHere $ WrongNumberOfArgs "<" 2 (length xs))- , (">", \case+ , ( ">"+ , [md|Checks if a number is strictly greater than another.|]+ , \case[Number x, Number y] -> pure $ Boolean (x > y)[_, _] -> throwErrorHere $ TypeError ">: expecting number"xs -> throwErrorHere $ WrongNumberOfArgs ">" 2 (length xs))- , ("foldl", \case+ , ( "foldl"+ , [md|Given a function `f`, an initial value `i` and a sequence (list or vector)+ `xs`, reduces `xs` to a single value by starting with `i` and repetitively+ combining values with `f`, using elements of `xs` from left to right.|]+ , \case[fn, init', v] -> dols :: [Value] <- fromRadOtherErr vfoldlM (\b a -> callFn fn [b, a]) init' lsxs -> throwErrorHere $ WrongNumberOfArgs "foldl" 3 (length xs))- , ("foldr", \case+ , ( "foldr"+ , [md|Given a function `f`, an initial value `i` and a sequence (list or vector)+ `xs`, reduces `xs` to a single value by starting with `i` and repetitively+ combining values with `f`, using elements of `xs` from right to left.|]+ , \case[fn, init', v] -> dols :: [Value] <- fromRadOtherErr vfoldrM (\b a -> callFn fn [b, a]) init' lsxs -> throwErrorHere $ WrongNumberOfArgs "foldr" 3 (length xs))- , ("map", \case+ , ( "map"+ , [md|Given a function `f` and a sequence (list or vector) `xs`, returns a sequence+ of the same size and type as `xs` but with `f` applied to all the elements.|]+ , \case[fn, List ls] -> List <$> traverse (callFn fn) (pure <$> ls)[fn, Vec ls] -> Vec <$> traverse (callFn fn) (pure <$> ls)[_, _] -> throwErrorHere $ TypeError "map: second argument should be a list or vector"xs -> throwErrorHere $ WrongNumberOfArgs "map" 3 (length xs))- , ("keyword?", oneArg "keyword?" $ \case+ , ( "keyword?"+ , isTy "keyword"+ , oneArg "keyword?" $ \caseKeyword _ -> pure tt_ -> pure ff)- , ("atom?", oneArg "atom?" $ \case+ , ( "atom?"+ , isTy "atom"+ , oneArg "atom?" $ \caseAtom _ -> pure tt_ -> pure ff)- , ("list?", oneArg "list?" $ \case+ , ( "list?"+ , isTy "list"+ , oneArg "list?" $ \caseList _ -> pure tt_ -> pure ff)- , ("dict?", oneArg "dict?" $ \case+ , ( "dict?"+ , isTy "dict"+ , oneArg "dict?" $ \caseDict _ -> pure tt_ -> pure ff), ( "type"+ , [md|Returns a keyword representing the type of the argument; one of:+ `:atom`, `:keyword`, `:string`, `:number`, `:boolean`, `:list`,+ `:vector`, `:function`, `:dict`, `:ref`, `:function`.|], let kw' = pure . Keyword . Identin oneArg "type" $ \caseAtom _ -> kw' "atom"@@ -255,27 +319,44 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>Ref _ -> kw' "ref"Lambda{} -> kw' "function")- , ("string?", oneArg "string?" $ \case+ , ( "string?"+ , isTy "string"+ , oneArg "string?" $ \caseString _ -> pure tt_ -> pure ff)- , ("boolean?", oneArg "boolean?" $ \case+ , ( "boolean?"+ , isTy "boolean"+ , oneArg "boolean?" $ \caseBoolean _ -> pure tt_ -> pure ff)- , ("number?", oneArg "number?" $ \case+ , ( "number?"+ , isTy "number"+ , oneArg "number?" $ \caseNumber _ -> pure tt_ -> pure ff)- , ("member?", \case+ , ( "member?"+ , [md|Given `v` and structure `s`, checks if `x` exists in `s`. The structure `s`+ may be a list, vector or dict. If it is a list or a vector, it checks if `v`+ is one of the items. If `s` is a dict, it checks if `v` is one of the keys.|]+ , \case[x, List xs] -> pure . Boolean $ elem x xs[x, Vec xs] -> pure . Boolean . isJust $ Seq.elemIndexL x xs[x, Dict m] -> pure . Boolean $ Map.member x m[_, _] -> throwErrorHere$ TypeError "member?: second argument must be list"xs -> throwErrorHere $ WrongNumberOfArgs "eq?" 2 (length xs))- , ("ref", oneArg "ref" newRef)- , ("read-ref", oneArg "read-ref" $ \case+ , ( "ref"+ , [md|Creates a ref with the argument as the initial value.|]+ , oneArg "ref" newRef)+ , ( "read-ref"+ , [md|Returns the current value of a ref.|]+ , oneArg "read-ref" $ \caseRef ref -> readRef ref_ -> throwErrorHere $ TypeError "read-ref: argument must be a ref")- , ("write-ref", \case+ , ( "write-ref"+ , [md|Given a reference `r` and a value `v`, updates the value stored in `r` to be+ `v` and returns `v`.|]+ , \case[Ref (Reference x), v] -> dost <- getput $ st { bindingsRefs = IntMap.insert x v $ bindingsRefs st }@@ -284,8 +365,14 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>$ TypeError "write-ref: first argument must be a ref"xs -> throwErrorHere$ WrongNumberOfArgs "write-ref" 2 (length xs))- , ("show", oneArg "show" (pure . String . renderPrettyDef))+ , ( "show"+ , [md|Returns a string representing the argument value.|]+ , oneArg "show" (pure . String . renderPrettyDef)), ( "seq"+ , [md|Given a structure `s`, returns a sequence. Lists and vectors are returned+ without modification while for dicts a list of key-value-pairs is returned:+ these are lists of length 2 whose first item is a key and whose second item+ is the associated value.|], oneArg "seq" $\casex@(List _) -> pure x@@ -293,21 +380,21 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>Dict kvs -> pure $ List [List [k, v] | (k,v) <- Map.toList kvs ]_ -> throwErrorHere $ TypeError "seq: can only be used on a list, vector or dictionary")- , ( "from-just"- , oneArg "from-just" $ \case- Vec (Keyword (Ident "Just") Seq.:<| x Seq.:<| Seq.Empty) -> pure x- _ -> throwErrorHere $ TypeError "from-just: called on a non-just"- ), ( "to-json"+ , [md|Returns a JSON formatted string representing the input value.|], oneArg "to-json" $ \v -> String . toS . Aeson.encode <$>maybeJson v ?? toLangError (OtherError "Could not serialise value to JSON"))- , ( "default-ecc-curve",+ , ( "default-ecc-curve"+ , [md|Returns the default elliptic-curve used for generating cryptographic keys.|]+ ,\case[] -> pure $ toRad defaultCurvexs -> throwErrorHere $ WrongNumberOfArgs "default-ecc-curve" 0 (length xs)), ( "verify-signature"+ , [md|Given a public key `pk`, a signature `s` and a message (string) `m`, checks+ that `s` is a signature of `m` for the public key `pk`.|], \case[keyv, sigv, String msg] -> dokey <- fromRadOtherErr keyv@@ -317,12 +404,32 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>xs -> throwErrorHere $ WrongNumberOfArgs "verify-signature" 3 (length xs)), ( "uuid?"+ , [md|Checks if a string has the format of a UUID.|], oneArg "uuid?" $ \caseString t -> pure . Boolean . UUID.isUUID $ t_ -> throwErrorHere $ TypeError "uuid?: expects a string")+ , ( "document"+ , [md|Used to add documentation to variables.|]+ , \case+ [Atom i, List _, String desc] -> do+ v <- lookupAtom i+ defineAtom i (Just desc) v+ pure nil+ [_,_,_] -> throwErrorHere $ OtherError "document: expects an atom, a list of argument docs, and a string."+ xs -> throwErrorHere $ WrongNumberOfArgs "document" 3 (length xs)+ )+ , ( "doc"+ , [md|Returns the documentation string for a variable. To print it instead, use `doc!`.|]+ , oneArg "doc" $ \case+ Atom i -> do d <- lookupAtomDoc i+ pure . String $+ fromMaybe ("No documentation found for " <> fromIdent i <> ".") d+ _ -> throwErrorHere $ OtherError "doc: expects an atom"+ )]where+ isTy t = "Checks if the argument is a " <> t <> "."fromRadOtherErr :: (FromRad Ann.WithPos a) => Value -> Lang m afromRadOtherErr = hoistEither . first (toLangError . OtherError) . fromRad@@ -336,8 +443,9 @@ purePrimFns = PrimFns $ fromList $ first Ident <$>numBinop :: (Scientific -> Scientific -> Scientific)-> Text- -> (Text, [Value] -> Lang m Value)- numBinop fn name = (name, \case+ -> Text+ -> (Text, Text, [Value] -> Lang m Value)+ numBinop fn name doc = (name, doc, \caseNumber x:x':xs -> foldM go (Number x) (x':xs)wherego (Number a) (Number b) = pure . Number $ fn a b@@ -369,3 +477,6 @@ readValue s = docase p ofRight v -> pure vLeft e -> throwErrorHere $ ThrownError (Ident "parse-error") (String e)++allDocs :: [(Text, Text, a)] -> [(Ident, Maybe Text, a)]+allDocs = fmap $ \(x,y,z) -> (unsafeToIdent x, Just y, z)diff --git a/test/spec/Radicle/Internal/Arbitrary.hs b/test/spec/Radicle/Internal/Arbitrary.hsindex bbbeb63..d955318 100644--- a/test/spec/Radicle/Internal/Arbitrary.hs+++ b/test/spec/Radicle/Internal/Arbitrary.hs@@ -10,6 +10,7 @@ import Test.QuickCheckimport Test.QuickCheck.Instances ()import Radicle+import qualified Radicle.Internal.Doc as Docimport Radicle.Internal.Identifier(isValidIdentFirst, isValidIdentRest)import Radicle.Internal.PrimFns (purePrimFns)@@ -64,3 +65,6 @@ instance Arbitrary a => Arbitrary (Bindings a) whereenv <- arbitraryprims <- arbitrarypure $ Bindings env prims (IntMap.fromList $ zip [0..] refs) (length refs)++instance Arbitrary a => Arbitrary (Doc.Docd a) where+ arbitrary = Doc.Docd Nothing <$> arbitrary