Skip to content

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.hs
index 8b83161..98150ee 100644
--- a/exe/Server/Client.hs
+++ b/exe/Server/Client.hs
@@ -1,3 +1,5 @@
+{-# LANGUAGE QuasiQuotes #-}
+
module Client where
import API
@@ -13,6 +15,9 @@ import Radicle
import Servant.Client
import System.Console.Haskeline (InputT)
+import Radicle.Internal.Doc (md)
+import qualified Radicle.Internal.PrimFns as PrimFns
+
main :: IO ()
main = do
opts' <- execParser allOpts
@@ -58,10 +63,12 @@ bindings :: HttpClient.Manager -> Bindings (PrimFns (InputT IO))
bindings mgr = addPrimFns (replPrimFns <> clientPrimFns mgr) pureEnv
clientPrimFns :: HttpClient.Manager -> PrimFns (InputT IO)
-clientPrimFns mgr = PrimFns (fromList [sendPrimop, receivePrimop])
+clientPrimFns mgr = fromList . PrimFns.allDocs $ [sendPrimop, receivePrimop]
where
sendPrimop =
- ( 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] -> do
res <- 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] -> do
case floatingOrInteger n of
diff --git a/package.yaml b/package.yaml
index 5f0821e..ab9ce1d 100644
--- a/package.yaml
+++ b/package.yaml
@@ -31,6 +31,9 @@ dependencies:
- cryptonite
- generics-eot
- uuid
+- data-default
+- pandoc-types
+- pandoc
when:
- condition: impl(ghcjs)
dependencies: ghcjs-dom
diff --git a/rad/prelude.rad b/rad/prelude.rad
index 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.rad
deleted file mode 100644
index 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.rad
deleted file mode 100644
index 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.hs
index 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 Par
import Radicle.Internal.Annotation (Annotated)
import qualified Radicle.Internal.Annotation as Ann
+import qualified Radicle.Internal.Doc as Doc
import qualified Radicle.Internal.Identifier as Identifier
import Radicle.Internal.Orphans ()
@@ -206,7 +207,6 @@ pattern Lambda vs exps env <- (Ann.match -> LambdaF vs exps env)
where
Lambda vs exps env = Ann.annotate $ LambdaF vs exps env
-
type UntaggedValue = Annotated Identity ValueF
type Value = Annotated Ann.WithPos ValueF
@@ -287,18 +287,23 @@ unsafeToIdent :: Text -> Ident
unsafeToIdent = 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 environment
lookupAtom :: 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 of
Nothing -> 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] -> do
val' <- 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] -> do
val' <- baseEval val
case val' of
Lambda 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 v
pure 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) where
fromRad (Vec (Keyword (Ident "Just") :<| x :<| Empty)) = Just <$> fromRad x
fromRad (Keyword (Ident "Nothing")) = pure Nothing
fromRad _ = Left "Expecting :Nothing or [:Just _]"
-instance FromRad Ann.WithPos Value where
+instance FromRad t (Annotated t ValueF) where
fromRad = pure
instance CPA t => FromRad t Scientific where
fromRad x = case x of
@@ -526,11 +541,17 @@ instance (CPA t, FromRad t a) => FromRad t [a] where
List xs -> traverse fromRad xs
Vec 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) where
fromRad x = case x of
Dict 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] where
toRad xs = Vec . Seq.fromList $ toRad <$> xs
instance (CPA t, ToRad t a) => ToRad t (Map.Map Text a) where
toRad 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 x
instance ToRad Ann.WithPos (Bindings m) where
toRad x = Dict $ Map.fromList
[ (Keyword $ Ident "env", toRad $ bindingsEnv x)
@@ -594,7 +617,7 @@ callFn f vs = case f of
then 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 <> closure
NonEmpty.last <$> withEnv (const modEnv)
(traverse baseEval body)
diff --git a/src/Radicle/Internal/Doc.hs b/src/Radicle/Internal/Doc.hs
new file mode 100644
index 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 p
diff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hs
index 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 Map
import qualified Data.Text as T
import 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.Haskeline
import Radicle.Internal.Core
import Radicle.Internal.Crypto
+import Radicle.Internal.Doc (md)
import Radicle.Internal.Effects.Capabilities
import Radicle.Internal.Interpret
import Radicle.Internal.Pretty
@@ -73,26 +77,59 @@ replBindings :: forall m. ReplM m => Bindings (PrimFns m)
replBindings = addPrimFns replPrimFns pureEnv
replPrimFns :: 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] -> do
putStrS (renderPrettyDef x)
pure nil
xs -> 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 v
pure 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] -> do
e <- gets bindingsEnv
case (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" $ \case
String 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!" $ \case
String 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] -> do
curve <- 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] -> do
sk <- 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.uuid
xs -> throwErrorHere $ WrongNumberOfArgs "uuid!" 0 (length xs)
diff --git a/src/Radicle/Internal/PrimFns.hs b/src/Radicle/Internal/PrimFns.hs
index 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 where
import Protolude hiding (TypeError)
@@ -20,6 +15,8 @@ import GHC.Exts (IsList(..))
import qualified Radicle.Internal.Annotation as Ann
import Radicle.Internal.Core
import Radicle.Internal.Crypto
+import Radicle.Internal.Doc (md)
+import qualified Radicle.Internal.Doc as Doc
import Radicle.Internal.Parse
import Radicle.Internal.Pretty
import 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 0
where
- 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 ())) of
Left 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" $ \case
String s -> readValue s
_ -> throwErrorHere $ TypeError "read: expects string"
)
- , ("get-current-env", \case
+ , ("get-current-env"
+ , [md|Returns the current radicle state.|]
+ , \case
[] -> toRad <$> get
xs -> 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 -> do
e' :: Bindings () <- fromRadOtherErr x
e <- 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" $ \case
List (x:_) -> pure x
List [] -> 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" $ \case
List (_:xs) -> pure $ List xs
List [] -> 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 of
Left (_ :: 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 of
Just 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) -> do
let 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 s
fromStr _ = Nothing
ss = fromStr <$> args
in if all isJust ss
then pure . String . mconcat $ catMaybes ss
else 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] -> do
ls :: [Value] <- fromRadOtherErr v
foldlM (\b a -> callFn fn [b, a]) init' ls
xs -> 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] -> do
ls :: [Value] <- fromRadOtherErr v
foldrM (\b a -> callFn fn [b, a]) init' ls
xs -> 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?" $ \case
Keyword _ -> pure tt
_ -> pure ff)
- , ("atom?", oneArg "atom?" $ \case
+ , ( "atom?"
+ , isTy "atom"
+ , oneArg "atom?" $ \case
Atom _ -> pure tt
_ -> pure ff)
- , ("list?", oneArg "list?" $ \case
+ , ( "list?"
+ , isTy "list"
+ , oneArg "list?" $ \case
List _ -> pure tt
_ -> pure ff)
- , ("dict?", oneArg "dict?" $ \case
+ , ( "dict?"
+ , isTy "dict"
+ , oneArg "dict?" $ \case
Dict _ -> 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 . Ident
in oneArg "type" $ \case
Atom _ -> 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?" $ \case
String _ -> pure tt
_ -> pure ff)
- , ("boolean?", oneArg "boolean?" $ \case
+ , ( "boolean?"
+ , isTy "boolean"
+ , oneArg "boolean?" $ \case
Boolean _ -> pure tt
_ -> pure ff)
- , ("number?", oneArg "number?" $ \case
+ , ( "number?"
+ , isTy "number"
+ , oneArg "number?" $ \case
Number _ -> 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" $ \case
Ref 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] -> do
st <- get
put $ 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" $
\case
x@(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 defaultCurve
xs -> 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] -> do
key <- 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?" $ \case
String 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 a
fromRadOtherErr = 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, \case
Number x:x':xs -> foldM go (Number x) (x':xs)
where
go (Number a) (Number b) = pure . Number $ fn a b
@@ -369,3 +477,6 @@ readValue s = do
case p of
Right v -> pure v
Left 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.hs
index bbbeb63..d955318 100644
--- a/test/spec/Radicle/Internal/Arbitrary.hs
+++ b/test/spec/Radicle/Internal/Arbitrary.hs
@@ -10,6 +10,7 @@ import Test.QuickCheck
import Test.QuickCheck.Instances ()
import Radicle
+import qualified Radicle.Internal.Doc as Doc
import Radicle.Internal.Identifier
(isValidIdentFirst, isValidIdentRest)
import Radicle.Internal.PrimFns (purePrimFns)
@@ -64,3 +65,6 @@ instance Arbitrary a => Arbitrary (Bindings a) where
env <- arbitrary
prims <- arbitrary
pure $ Bindings env prims (IntMap.fromList $ zip [0..] refs) (length refs)
+
+instance Arbitrary a => Arbitrary (Doc.Docd a) where
+ arbitrary = Doc.Docd Nothing <$> arbitrary