Skip to content

A peer-to-peer stack for code collaboration

Adds modules (#257)

James Haydon24000fe5fc5b
diff --git a/docs/source/guide/Modules.lrad b/docs/source/guide/Modules.lrad
new file mode 100644
index 0000000..8b91b5d
--- /dev/null
+++ b/docs/source/guide/Modules.lrad
@@ -0,0 +1,109 @@
+# Modules
+
+To create a module, use the `module` special form. All modules must start with a
+*module declaration* which provides the module with a name, documentation string
+and an exports vector. Module declarations are evaluated, so you must quote any exports.
+
+Here is a simple example of a module:
+
+ (module
+ {:module 'my-module
+ :doc "Just for showing off modules."
+ :exports '[foo bar]}
+
+ (def foo-helper
+ (fn [x] (+ x 1)))
+
+ (def foo
+ (fn [x] (foo-helper (foo-helper x))))
+
+ (def bar
+ (fn [x] (foo (+ x 2)))))
+
+To import a module, use `import`:
+
+ (import my-module)
+
+The content of a module is evaluated in a new scope that is identical to the
+scope of the module definition site. This means you you can use whatever has
+already been defined before the module was, and that definitions in the module
+don't leak outside the module. The form returns the module value, which can be
+passed around just like any other value. This means that we can write functions
+which create modules:
+
+ (def make-taxes
+ (fn [VAT]
+ (module
+ {:module 'taxes
+ :doc "Calculates taxes."
+ :exports ['add-VAT]}
+ (def add-VAT (fn [x] (* (+ 1 VAT) x))))))
+
+And then we could use this module with different values of `VAT`:
+
+ (import (make-taxes 2/10))
+ ;; We also need to import `prelude/io` to be able to use `print!`
+ (import (file-module! "rad/prelude/io.rad") :unqualified)
+
+ (print! (string-append "100 EUR + VAT is: " (show (taxes/add-VAT 100))))
+
+By default `import` will add all the definitions of the module in
+fully-qualified form, which means `my-module/foo` and `my-module/bar` (but not
+`my-module/foo-helper`) are in scope:
+
+ (print! (my-module/bar 0))
+
+You can narrow down exactly which definitions you would like to import by
+including a list of atoms:
+
+ (import my-module ['foo])
+
+Which would only import `my-module/foo`. And you can also use a custom
+qualifier:
+
+ (import my-module :as 'baz)
+
+After which we can:
+
+ (print! (baz/bar 42))
+
+So we could import our taxes module twive using different qualifiers:
+
+ (def taxes-fr (make-taxes 20/100))
+ (def taxes-de (make-taxes 19/100))
+
+ (import taxes-de :as 'de)
+ (import taxes-fr :as 'fr)
+
+ (print!
+ (string-append
+ "100 EUR + VAT is "
+ (show (de/add-VAT 100))
+ " EUR in Germany and "
+ (show (fr/add-VAT 100))
+ " EUR in France."))
+
+If you really want to import all the definitions without a qualification, then
+you can use the keyword `:unqualified` like so:
+
+ (import my-module :unqualified)
+
+And then we can:
+
+ (print! (foo 128))
+
+Qualification and import lists can be combined like so:
+
+ (import my-module ['bar] :as 'useful)
+
+Would only add `useful/bar` to the current scope:
+
+ (print! (useful/bar 0))
+
+When working at the REPL, the function `file-module!` is also available, which
+can create a module from a file. It assumes the file starts with a module
+declaration, and is then equivalent to wrapping the contents of the file in
+`(module ...)`.
+
+Modules can be passed around and manipulated because they are just dicts with
+some metadata, and an `:env` key containing a radicle environment.
diff --git a/docs/source/guide/index.rst b/docs/source/guide/index.rst
index 19942cd..c6f7719 100644
--- a/docs/source/guide/index.rst
+++ b/docs/source/guide/index.rst
@@ -58,5 +58,6 @@ how to allow for future changes to the chain.
GettingStarted.md
Basics.lrad
+ Modules.rst
Chains.lrad
DataValidation.rst
diff --git a/docs/source/reference.rst b/docs/source/reference.rst
index 0915618..dabc50d 100644
--- a/docs/source/reference.rst
+++ b/docs/source/reference.rst
@@ -1,60 +1,51 @@
Radicle Reference
=================
-These are the functions that are available in a new radicle chain after
-the prelude has been loaded.
+This is the ``radicle`` reference document, with documentation for all
+functions which come as part of the standard distribution.
-Basics
-------
-
-Basic function used for checking equality, determining the type of a
-value, etc.
-
-``eq?``
-~~~~~~~
-
-Checks if two values are equal.
-
-``(not x)``
-~~~~~~~~~~~
+Primitive functions
+-------------------
-True if ``x`` is ``#f``, false otherwise.
+Primitive functions are those that are built into the compiler. They are
+available on all chains but may be shadowed by later definitions. Those
+that end in a ``!`` are only available locally, not on 'pure' chains.
-``(and x y)``
-~~~~~~~~~~~~~
+``*``
+~~~~~
-Returns ``y`` if ``x`` is not ``#f``, otherwise returns ``x``
+Multiplies two numbers together.
-``(or x y)``
-~~~~~~~~~~~~
+``+``
+~~~~~
-Returns 'arg1' if 'arg1' is not #f, otherwise returns 'arg2'
+Adds two numbers together.
-``(all xs)``
-~~~~~~~~~~~~
+``-``
+~~~~~
-Checks that all the items of a list are truthy.
+Substracts one number from another.
-``(some xs)``
-~~~~~~~~~~~~~
+``/``
+~~~~~
-Checks that there is a least one truthy value in a list.
+Divides one number by another. Throws an exception if the second
+argument is 0.
-``show``
-~~~~~~~~
+``<``
+~~~~~
-Returns a string representing the argument value.
+Checks if a number is strictly less than another.
-``string-append``
-~~~~~~~~~~~~~~~~~
+``>``
+~~~~~
-Concatenates a variable number of string arguments. If one of the
-arguments isn't a string then an exception is thrown.
+Checks if a number is strictly greater than another.
-``string-length``
-~~~~~~~~~~~~~~~~~
+``eq?``
+~~~~~~~
-Returns the length of a string.
+Checks if two values are equal.
``apply``
~~~~~~~~~
@@ -62,53 +53,21 @@ Returns the length of a string.
Calls the first argument (a function) using as arguments the elements of
the the second argument (a list).
-``type``
+``show``
~~~~~~~~
-Returns a keyword representing the type of the argument; one of:
-``:atom``, ``:keyword``, ``:string``, ``:number``, ``:boolean``,
-``:list``, ``:vector``, ``:function``, ``:dict``, ``:ref``,
-``:function``.
-
-``atom?``
-~~~~~~~~~
-
-Checks if the argument is a atom.
-
-``boolean?``
-~~~~~~~~~~~~
-
-Checks if the argument is a boolean.
-
-``string?``
-~~~~~~~~~~~
-
-Checks if the argument is a string.
-
-``number?``
-~~~~~~~~~~~
-
-Checks if the argument is a number.
-
-``keyword?``
-~~~~~~~~~~~~
-
-Checks if the argument is a keyword.
-
-``vector?``
-~~~~~~~~~~~
-
-Checks if the argument is a vector.
+Returns a string representing the argument value.
-``list?``
+``throw``
~~~~~~~~~
-Checks if the argument is a list.
+Throws an exception. The first argument should be an atom used as a
+label for the exception, the second can be any value.
-``dict?``
+``exit!``
~~~~~~~~~
-Checks if the argument is a dict.
+Exit the interpreter immediately.
``read``
~~~~~~~~
@@ -121,96 +80,122 @@ Parses a string into a radicle value. Does not evaluate the value.
Parses a string into a vector of radicle values. Does not evaluate the
values.
-``throw``
-~~~~~~~~~
+``base-eval``
+~~~~~~~~~~~~~
-Throws an exception. The first argument should be an atom used as a
-label for the exception, the second can be any value.
+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.
-``to-json``
-~~~~~~~~~~~
+``(eval expr env)``
+~~~~~~~~~~~~~~~~~~~
-Returns a JSON formatted string representing the input value.
+The evaluation function.
-``uuid?``
-~~~~~~~~~
+``ref``
+~~~~~~~
-Checks if a string has the format of a UUID.
+Creates a ref with the argument as the initial value.
-``(make-counter)``
-~~~~~~~~~~~~~~~~~~
+``read-ref``
+~~~~~~~~~~~~
-Creates a stateful counter. Returns a dict with two keys: the function
-at ``:next-will-be`` will return the next number (without incrementing
-it), while the function at ``:next`` increments the number and returns
-it.
+Returns the current value of a ref.
-``public-key?``
-~~~~~~~~~~~~~~~
+``write-ref``
+~~~~~~~~~~~~~
-Checks if a value represents a valid public key.
+Given a reference ``r`` and a value ``v``, updates the value stored in
+``r`` to be ``v`` and returns ``v``.
-Numerical functions
--------------------
+``match-pat``
+~~~~~~~~~~~~~
-Operations on numbers.
+The most basic built-in pattern-matching dispatch function.
-``+``
-~~~~~
+``head``
+~~~~~~~~
-Adds two numbers together.
+Retrieves the first element of a sequence if it exists. Otherwise throws
+an exception.
-``*``
-~~~~~
+``cons``
+~~~~~~~~
-Multiplies two numbers together.
+Adds an element to the front of a list.
-``-``
-~~~~~
+``add-left``
+~~~~~~~~~~~~
-Substracts one number from another.
+Adds an element to the left side of a vector.
-``/``
-~~~~~
+``add-right``
+~~~~~~~~~~~~~
-Divides one number by another. Throws an exception if the second
-argument is 0.
+Adds an element to the right side of a vector.
-``<``
-~~~~~
+``<>``
+~~~~~~
-Checks if a number is strictly less than another.
+Merges two structures together. On vectors this performs concatenations.
+On dicts this performs the right-biased merge.
-``>``
-~~~~~
+``list``
+~~~~~~~~
-Checks if a number is strictly greater than another.
+Turns the arguments into a list.
-``integral?``
-~~~~~~~~~~~~~
+``list-to-vec``
+~~~~~~~~~~~~~~~
-Checks if a number is an integer.
+Transforms lists into vectors.
-Lists
------
+``vec-to-list``
+~~~~~~~~~~~~~~~
-Functions for manipulating lists.
+Transforms vectors to lists.
-``list``
-~~~~~~~~
+``zip``
+~~~~~~~
-Turns the arguments into a list.
+Takes two sequences and returns a sequence of corresponding pairs. In
+one sequence is shorter than the other, the excess elements of the
+longer sequence are discarded.
-``nil``
+``map``
~~~~~~~
-The empty list.
+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.
-``head``
+``foldl``
+~~~~~~~~~
+
+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.
+
+``foldr``
+~~~~~~~~~
+
+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.
+
+``drop``
~~~~~~~~
-Retrieves the first element of a sequence if it exists. Otherwise throws
-an exception.
+Returns all but the first ``n`` items of a sequence, unless the sequence
+is empty, in which case an exception is thrown.
+
+``sort-by``
+~~~~~~~~~~~
+
+Given a sequence ``xs`` and a function ``f``, returns a sequence with
+the same elements ``x`` of ``xs`` but sorted according to ``(f x)``.
``tail``
~~~~~~~~
@@ -218,311 +203,355 @@ an exception.
Given a non-empty sequence, returns the sequence of all the elements but
the first. If the sequence is empty, throws an exception.
-``(empty? ls)``
-~~~~~~~~~~~~~~~
-
-True if 'seq' is empty, false otherwise.
-
-``cons``
+``take``
~~~~~~~~
-Adds an element to the front of a list.
+Returns the first ``n`` items of a sequence, unless the sequence is too
+short, in which case an exception is thrown.
-``(reverse ls)``
-~~~~~~~~~~~~~~~~
+``nth``
+~~~~~~~
-Returns the reversed 'ls'.
+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.
-``(length xs)``
-~~~~~~~~~~~~~~~
+``seq``
+~~~~~~~
-Returns the length of 'list'.
+Given a structure ``s``, returns a sequence. Lists and vectors are
+returned without modification while for dicts a vector of
+key-value-pairs is returned: these are vectors of length 2 whose first
+item is a key and whose second item is the associated value.
-``(concat list1 list2)``
-~~~~~~~~~~~~~~~~~~~~~~~~
+``dict``
+~~~~~~~~
-Concatenates 'list1' and 'list2'.
+Given an even number of arguments, creates a dict where the ``2i``-th
+argument is the key for the ``2i+1``\ th argument. If one of the even
+indexed arguments is not hashable then an exception is thrown.
-``(filter pred ls)``
-~~~~~~~~~~~~~~~~~~~~
+``lookup``
+~~~~~~~~~~
-Returns 'list' with only the elements that satisfy 'filter-cond'.
+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.
-``(range from to)``
-~~~~~~~~~~~~~~~~~~~
+``insert``
+~~~~~~~~~~
-Returns a list with all integers from ``from`` to ``end``, inclusive.
+Given ``k``, ``v`` and a dict ``d``, returns a dict with the same
+associations as ``d`` but with ``k`` associated to ``d``. If ``d`` isn't
+a dict or if ``k`` isn't hashable then an exception is thrown.
-``(list-with-head x f g)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~
+``delete``
+~~~~~~~~~~
-Given a value ``x``, and two functions ``f`` and ``g``, checks if ``x``
-is a list with a head. If so applies ``f`` to the head, otherwise calls
-``g`` with no args.
+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.
-Vectors
--------
+``member?``
+~~~~~~~~~~~
-Functions for manipulating vectors.
+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.
-``<>``
-~~~~~~
+``map-keys``
+~~~~~~~~~~~~
-Merges two structures together. On vectors this performs concatenations.
-On dicts this performs the right-biased merge.
+Given a function ``f`` and a dict ``d``, returns a dict with the same
+values as ``d`` but ``f`` applied to all the keys. If ``f`` maps two
+keys to the same thing, the greatest key and value are kept.
-``add-left``
-~~~~~~~~~~~~
+``map-values``
+~~~~~~~~~~~~~~
-Adds an element to the left side of a vector.
+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.
-``add-right``
-~~~~~~~~~~~~~
+``string-append``
+~~~~~~~~~~~~~~~~~
-Adds an element to the right side of a vector.
+Concatenates a variable number of string arguments. If one of the
+arguments isn't a string then an exception is thrown.
-Sequences
----------
+``string-length``
+~~~~~~~~~~~~~~~~~
-Functions for manipulating boths lists and vectors.
+Returns the length of a string.
-``(empty-seq? xs)``
-~~~~~~~~~~~~~~~~~~~
+``string-replace``
+~~~~~~~~~~~~~~~~~~
-Returns true if the input is an empty sequence (either list or vector).
+Replace all occurrences of the first argument with the second in the
+third.
-``nth``
-~~~~~~~
+``type``
+~~~~~~~~
-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.
+Returns a keyword representing the type of the argument; one of:
+``:atom``, ``:keyword``, ``:string``, ``:number``, ``:boolean``,
+``:list``, ``:vector``, ``:function``, ``:dict``, ``:ref``,
+``:function``.
-``foldl``
+``atom?``
~~~~~~~~~
-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.
+Checks if the argument is a atom.
-``foldr``
-~~~~~~~~~
+``keyword?``
+~~~~~~~~~~~~
-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.
+Checks if the argument is a keyword.
-``map``
-~~~~~~~
+``boolean?``
+~~~~~~~~~~~~
-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.
+Checks if the argument is a boolean.
-``seq``
-~~~~~~~
+``string?``
+~~~~~~~~~~~
-Given a structure ``s``, returns a sequence. Lists and vectors are
-returned without modification while for dicts a vector of
-key-value-pairs is returned: these are vectors of length 2 whose first
-item is a key and whose second item is the associated value.
+Checks if the argument is a string.
-``take``
-~~~~~~~~
+``number?``
+~~~~~~~~~~~
-Returns the first ``n`` items of a sequence, unless the sequence is too
-short, in which case an exception is thrown.
+Checks if the argument is a number.
-``drop``
-~~~~~~~~
+``integral?``
+~~~~~~~~~~~~~
-Returns all but the first ``n`` items of a sequence, unless the sequence
-is empty, in which case an exception is thrown.
+Checks if a number is an integer.
-``sort-by``
+``vector?``
~~~~~~~~~~~
-Given a sequence ``xs`` and a function ``f``, returns a sequence with
-the same elements ``x`` of ``xs`` but sorted according to ``(f x)``.
+Checks if the argument is a vector.
-``zip``
-~~~~~~~
+``list?``
+~~~~~~~~~
-Takes two sequences and returns a sequence of corresponding pairs. In
-one sequence is shorter than the other, the excess elements of the
-longer sequence are discarded.
+Checks if the argument is a list.
-Dicts
------
+``dict?``
+~~~~~~~~~
-Functions for manipulating dicts.
+Checks if the argument is a dict.
-``dict``
-~~~~~~~~
+``file-module!``
+~~~~~~~~~~~~~~~~
-Given an even number of arguments, creates a dict where the ``2i``-th
-argument is the key for the ``2i+1``\ th argument. If one of the even
-indexed arguments is not hashable then an exception is thrown.
+Given a file whose code starts with module metadata, creates the module.
+That is, the file is evaluated as if the code was wrapped in
+``(module ...)``.
-``lookup``
+``import``
~~~~~~~~~~
-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.
+Import a module, making all the definitions of that module available in
+the current scope. The first argument must be a module to import. Two
+optional arguments affect how and which symbols are imported.
+``(import m :as 'foo)`` will import all the symbols of ``m`` with the
+prefix ``foo/``. ``(import m '[f g])`` will only import ``f`` and ``g``
+from ``m``. ``(import m '[f g] :as 'foo')`` will import ``f`` and ``g``
+from ``m`` as ``foo/f`` and ``foo/g``. To import definitions with no
+qualification at all, use ``(import m :unqualified)``.
-``insert``
-~~~~~~~~~~
+``get-current-env``
+~~~~~~~~~~~~~~~~~~~
-Given ``k``, ``v`` and a dict ``d``, returns a dict with the same
-associations as ``d`` but with ``k`` associated to ``d``. If ``d`` isn't
-a dict or if ``k`` isn't hashable then an exception is thrown.
+Returns the current radicle state.
-``delete``
-~~~~~~~~~~
+``pure-env``
+~~~~~~~~~~~~
-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.
+Returns a pure initial radicle state. This is the state of a radicle
+chain before it has processed any inputs.
-``(dict-from-list xs)``
-~~~~~~~~~~~~~~~~~~~~~~~
+``set-current-env``
+~~~~~~~~~~~~~~~~~~~
-Creates a dictionary from a list of key-value pairs.
+Replaces the radicle state with the one provided.
-``(keys d)``
+``set-env!``
~~~~~~~~~~~~
-Given a ``dict``, returns a vector of its keys.
+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``.
-``(values d)``
-~~~~~~~~~~~~~~
+``to-json``
+~~~~~~~~~~~
-Given a ``dict``, returns a vector of its values.
+Returns a JSON formatted string representing the input value.
-``(rekey old-key new-key mp)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+``uuid!``
+~~~~~~~~~
-Change the key from 'old-key' to 'new-key' in 'dict'. If 'new-key'
-already exists, it is overwritten.
+Generates a random UUID.
-``map-values``
-~~~~~~~~~~~~~~
+``uuid?``
+~~~~~~~~~
-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.
+Checks if a string has the format of a UUID.
-``map-keys``
-~~~~~~~~~~~~
+``default-ecc-curve``
+~~~~~~~~~~~~~~~~~~~~~
-Given a function ``f`` and a dict ``d``, returns a dict with the same
-values as ``d`` but ``f`` applied to all the keys. If ``f`` maps two
-keys to the same thing, the greatest key and value are kept.
+Returns the default elliptic-curve used for generating cryptographic
+keys.
-``(modify-map key f mp)``
-~~~~~~~~~~~~~~~~~~~~~~~~~
+``verify-signature``
+~~~~~~~~~~~~~~~~~~~~
-Given a key, a function and a dict, applies the function to the value
-associated to that key.
+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``.
-``(delete-many ks d)``
-~~~~~~~~~~~~~~~~~~~~~~
+``public-key?``
+~~~~~~~~~~~~~~~
-Delete several keys from a dict.
+Checks if a value represents a valid public key.
-``(exclusive-dict-merge m n)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+``gen-key-pair!``
+~~~~~~~~~~~~~~~~~
-Merges two dicts while checking for key conflicts. Returns
-``{:merge m :conflicts c}`` where ``m`` is the merged dict for all
-non-conflicting keys and ``c`` is a dict with all the conflicting keys,
-mapping to pairs of values, one from each input dict.
+Given an elliptic curve, generates a cryptographic key-pair. Use
+``default-ecc-curve`` for a default value for the elliptic curve.
-Sets
-----
+``gen-signature!``
+~~~~~~~~~~~~~~~~~~
-Functions for manipulating sets.
+Given a private key and a message (a string), generates a cryptographic
+signature for the message.
-``set/empty``
+``put-str!``
+~~~~~~~~~~~~
+
+Prints a string.
+
+``get-line!``
~~~~~~~~~~~~~
-An empty set.
+Reads a single line of input and returns it as a string.
-``(set/insert x s)``
-~~~~~~~~~~~~~~~~~~~~
+``load!``
+~~~~~~~~~
-Insert a value into a set.
+Evaluates the contents of a file. Each seperate radicle expression is
+``eval``\ uated according to the current definition of ``eval``.
-``(set/delete x s)``
-~~~~~~~~~~~~~~~~~~~~
+``read-file!``
+~~~~~~~~~~~~~~
-Delete a value from a set.
+Reads the contents of a file and returns it as a string.
-``(set/member? x s)``
+``read-line-handle!``
~~~~~~~~~~~~~~~~~~~~~
-Query if an value is an element of a set.
+Read a single line from a handle.
-``(set/delete x s)``
-~~~~~~~~~~~~~~~~~~~~
+``now!``
+~~~~~~~~
-Delete a value from a set.
+Returns a timestamp for the current Coordinated Universal Time (UTC),
+right now, formatted according to ISO 8601.
-``(set/from-seq xs)``
+``system!``
+~~~~~~~~~~~
+
+(system! proc) execute a system process. Returns the dict with the form
+``{ :stdin maybe-handle :stdout maybe-handle :stderr maybe-handle :proc prochandle }``
+Where ``maybe-handle`` is either ``[:just handle]`` or ``:nothing``.
+Note that this is quite a low-level function; higher-level ones are more
+convenient.
+
+``wait-for-process!``
~~~~~~~~~~~~~~~~~~~~~
-Create a set from a sequence.
+Block until process terminates.
+
+``write-handle!``
+~~~~~~~~~~~~~~~~~
+
+Write a string to the provided handle.
+
+``subscribe-to!``
+~~~~~~~~~~~~~~~~~
+
+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``.
+
+``doc``
+~~~~~~~
+
+Returns the documentation string for a variable. To print it instead,
+use ``doc!``.
+
+``doc!``
+~~~~~~~~
+
+Prints the documentation attached to a value and returns ``()``. To
+retrieve the docstring as a value use ``doc`` instead.
+
+``apropos!``
+~~~~~~~~~~~~
+
+Prints documentation for all documented variables in scope.
-``(set/to-vec s)``
-~~~~~~~~~~~~~~~~~~
+Prelude modules
+---------------
-Convert a set to a vector.
+These are the modules included in the radicle prelude and the functions
+these modules expose.
-Strings
--------
+``prelude/basic``
+-----------------
-Functions for manipulating strings.
+Basic function used for checking equality, determining the type of a
+value, etc.
-``(intercalate sep strs)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~
+``(or x y)``
+~~~~~~~~~~~~
-Intercalates a string in a list of strings
+Returns 'arg1' if 'arg1' is not #f, otherwise returns 'arg2'
-``(unlines x)``
-~~~~~~~~~~~~~~~
+``(some xs)``
+~~~~~~~~~~~~~
-Concatenate a list of strings, with newlines in between.
+Checks that there is a least one truthy value in a list.
-``string-replace``
-~~~~~~~~~~~~~~~~~~
+``(empty-seq? xs)``
+~~~~~~~~~~~~~~~~~~~
-Replace all occurrences of the first argument with the second in the
-third.
+Returns true if the input is an empty sequence (either list or vector).
-``(unwords x)``
+``(length xs)``
~~~~~~~~~~~~~~~
-Concatenate a list of strings, with spaces in between.
+Returns the length of 'list'.
-Structures
-----------
+``(maybe->>= v f)``
+~~~~~~~~~~~~~~~~~~~
-Functions for manipulating lists, vectors and dicts.
+Monadic bind for the maybe monad.
-``member?``
-~~~~~~~~~~~
+``(maybe-foldlM f i xs)``
+~~~~~~~~~~~~~~~~~~~~~~~~~
-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.
+Monadic fold over the elements of a seq, associating to the left (i.e.
+from left to right) in the maybe monad.
-Patterns
---------
+``prelude/patterns``
+--------------------
Pattern matching is first-class in radicle so new patterns can easily be
defined. These are the most essential.
@@ -548,16 +577,6 @@ The wildcard pattern.
Predicate pattern. Takes a predicate function as argument. Values match
against this pattern if the predicate returns a truthy value.
-``(/nil v)``
-~~~~~~~~~~~~
-
-Empty-list pattern.
-
-``(/cons x-pat xs-pat)``
-~~~~~~~~~~~~~~~~~~~~~~~~
-
-A pattern for lists with a head and a tail.
-
``(/as var pat)``
~~~~~~~~~~~~~~~~~
@@ -565,275 +584,226 @@ As pattern. Takes a variable and a sub-pattern. If the subpattern
matches then the whole pattern matches and furthermore the variable is
bound to the matched value.
-``(non-linear-merge m n)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~
+``(/cons x-pat xs-pat)``
+~~~~~~~~~~~~~~~~~~~~~~~~
-The bindings merge strategy for non-linear patterns. Use this function
-to merge bindings returned by sub-patterns if you want your pattern to
-be non-linear.
+A pattern for lists with a head and a tail.
-Refs
-----
+``(/nil v)``
+~~~~~~~~~~~~
-Functions for creating, querying and modifying refs.
+Empty-list pattern.
-``ref``
-~~~~~~~
+``(/just pat)``
+~~~~~~~~~~~~~~~
-Creates a ref with the argument as the initial value.
+Pattern which matches ``[:just x]``.
-``read-ref``
-~~~~~~~~~~~~
+``prelude/strings``
+-------------------
-Returns the current value of a ref.
+String manipulation functions.
-``write-ref``
-~~~~~~~~~~~~~
+``(intercalate sep strs)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~
-Given a reference ``r`` and a value ``v``, updates the value stored in
-``r`` to be ``v`` and returns ``v``.
+Intercalates a string in a list of strings
-``(modify-ref r f)``
-~~~~~~~~~~~~~~~~~~~~
+``(unlines x)``
+~~~~~~~~~~~~~~~
-Modify 'ref' by applying the provided function. Returns the new value.
+Concatenate a list of strings, with newlines in between.
-Evaluation functions
---------------------
+``(unwords x)``
+~~~~~~~~~~~~~~~
-Utilities for creating and extending evaluation functions.
+Concatenate a list of strings, with spaces in between.
-``base-eval``
-~~~~~~~~~~~~~
+``prelude/io``
+--------------
-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.
+Some basic I/O functions.
-``(eval expr env)``
-~~~~~~~~~~~~~~~~~~~
+``(print! x)``
+~~~~~~~~~~~~~~
-An eval in which one can use ``(:enter-chain url)`` to make the eval
-behave as that of a remote chain, and ``:send`` to send all enqueued
-expressions.
+Print a value to the console or stdout.
-``(updatable-eval sub-eval)``
+``(shell! command to-write)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Given an evaluation function ``f``, returns a new one which augments
-``f`` with a new command ``(update expr)`` which evaluates arbitrary
-expression using ``base-eval``.
+Executes ``command`` using the shell with ``to-write`` as input. Stdout
+and stderr are inherited. WARNING: using ``shell!`` with unsanitized
+user input is a security hazard! Example: ``(shell! "ls -Glah" "")``.
-Documentation and testing
--------------------------
+``(process! command args to-write)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Functions for creating and querying documentation of variables in scope,
-and testing functions.
+Executes ``command`` using 'execvp'. with 'to-write' as input. Stdout
+and stderr are inherit. See 'man exec' for more information on 'execvp'.
+Example: ``(process! "ls" ["-Glah"] "")``.
-``(help)``
-~~~~~~~~~~
+``(read-line!)``
+~~~~~~~~~~~~~~~~
-Default help text.
+Read a single line of input and interpret it as radicle data.
-``doc``
-~~~~~~~
+``(send-code! chain-id filename)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Returns the documentation string for a variable. To print it instead,
-use ``doc!``.
+Send code from a file to a remote chain.
-``doc!``
-~~~~~~~~
+``(read-code! filename)``
+~~~~~~~~~~~~~~~~~~~~~~~~~
-Prints the documentation attached to a value and returns ``()``. To
-retrieve the docstring as a value use ``doc`` instead.
+Read code (as data) from a file. Returns a vector of expressions
-``apropos!``
-~~~~~~~~~~~~
+``prelude/bool``
+----------------
-Prints documentation for all documented variables in scope.
+Functions for dealing with truthiness and #f.
-``is-test-env``
-~~~~~~~~~~~~~~~
+``(not x)``
+~~~~~~~~~~~
-True iff file is being run as part of the Haskell suite
+True if ``x`` is ``#f``, false otherwise.
-Environment functions
----------------------
+``(and x y)``
+~~~~~~~~~~~~~
-Utilities for modifying the current environment.
+Returns ``y`` if ``x`` is not ``#f``, otherwise returns ``x``
-``pure-env``
+``(all xs)``
~~~~~~~~~~~~
-Returns a pure initial radicle state. This is the state of a radicle
-chain before it has processed any inputs.
+Checks that all the items of a list are truthy.
-``get-current-env``
-~~~~~~~~~~~~~~~~~~~
+``prelude/exception``
+---------------------
-Returns the current radicle state.
+Tests for exceptions.
-``set-current-env``
-~~~~~~~~~~~~~~~~~~~
+``prelude/list``
+----------------
-Replaces the radicle state with the one provided.
+Functions for manipulating lists.
-``set-env!``
-~~~~~~~~~~~~
+``nil``
+~~~~~~~
-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``.
+The empty list.
-Input/Output
-------------
+``(empty? ls)``
+~~~~~~~~~~~~~~~
-Effectful functions. These functions are not available in 'pure' chains,
-but are available in the local REPL.
+True if 'seq' is empty, false otherwise.
-``(print! x)``
-~~~~~~~~~~~~~~
+``(reverse ls)``
+~~~~~~~~~~~~~~~~
-Print a value to the console or stdout.
+Returns the reversed 'ls'.
-``get-line!``
-~~~~~~~~~~~~~
+``(range from to)``
+~~~~~~~~~~~~~~~~~~~
-Reads a single line of input and returns it as a string.
+Returns a list with all integers from ``from`` to ``end``, inclusive.
-``load!``
-~~~~~~~~~
+``(concat list1 list2)``
+~~~~~~~~~~~~~~~~~~~~~~~~
-Evaluates the contents of a file. Each seperate radicle expression is
-``eval``\ uated according to the current definition of ``eval``.
+Concatenates 'list1' and 'list2'.
-``read-file!``
-~~~~~~~~~~~~~~
+``(filter pred ls)``
+~~~~~~~~~~~~~~~~~~~~
-Reads the contents of a file and returns it as a string.
+Returns 'list' with only the elements that satisfy 'filter-cond'.
-``(read-code! filename)``
-~~~~~~~~~~~~~~~~~~~~~~~~~
+``prelude/dict``
+----------------
-Read code (as data) from a file. Returns a vector of expressions
+Functions for manipualting dicts.
-``(send-code! chain-id filename)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+``(dict-from-seq xs)``
+~~~~~~~~~~~~~~~~~~~~~~
-Send code from a file to a remote chain.
+Creates a dictionary from a list of key-value pairs.
-``put-str!``
+``(keys d)``
~~~~~~~~~~~~
-Prints a string.
-
-``(process! command args to-write)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Executes ``command`` using 'execvp'. with 'to-write' as input. Stdout
-and stderr are inherit. See 'man exec' for more information on 'execvp'.
-Example: ``(process! "ls" ["-Glah"] "")``.
-
-``(shell! command to-write)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Executes ``command`` using the shell with ``to-write`` as input. Stdout
-and stderr are inherited. WARNING: using ``shell!`` with unsanitized
-user input is a security hazard! Example: ``(shell! "ls -Glah" "")``.
-
-``system!``
-~~~~~~~~~~~
-
-(system! proc) execute a system process. Returns the dict with the form
-``{ :stdin maybe-handle :stdout maybe-handle :stderr maybe-handle :proc prochandle }``
-Where ``maybe-handle`` is either ``[:just handle]`` or ``:nothing``.
-Note that this is quite a low-level function; higher-level ones are more
-convenient.
-
-``(send-prelude! chain-id)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Send the pure prelude to a chain.
-
-``subscribe-to!``
-~~~~~~~~~~~~~~~~~
-
-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``.
+Given a ``dict``, returns a vector of its keys.
-``uuid!``
-~~~~~~~~~
+``(values d)``
+~~~~~~~~~~~~~~
-Generates a random UUID.
+Given a ``dict``, returns a vector of its values.
-``(read-line!)``
-~~~~~~~~~~~~~~~~
+``(rekey old-key new-key mp)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Read a single line of input and interpret it as radicle data.
+Change the key from 'old-key' to 'new-key' in 'dict'. If 'new-key'
+already exists, it is overwritten.
-``exit!``
-~~~~~~~~~
+``(modify-map key f mp)``
+~~~~~~~~~~~~~~~~~~~~~~~~~
-Exit the interpreter immediately.
+Given a key, a function and a dict, applies the function to the value
+associated to that key.
-``read-line-handle!``
-~~~~~~~~~~~~~~~~~~~~~
+``(delete-many ks d)``
+~~~~~~~~~~~~~~~~~~~~~~
-Read a single line from a handle.
+Delete several keys from a dict.
-``wait-for-process!``
-~~~~~~~~~~~~~~~~~~~~~
+``prelude/set``
+---------------
-Block until process terminates.
+Sets, built using dicts.
-``write-handle!``
-~~~~~~~~~~~~~~~~~
+``empty``
+~~~~~~~~~
-Write a string to the provided handle.
+An empty set.
-``now!``
-~~~~~~~~
+``(insert x s)``
+~~~~~~~~~~~~~~~~
-Returns a timestamp for the current Coordinated Universal Time (UTC),
-right now, formatted according to ISO 8601.
+Insert a value into a set.
-Maybe
------
+``(delete x s)``
+~~~~~~~~~~~~~~~~
-Optionality is represented using ``[:just x]`` for when the value
-exists, and ``:nothing`` when it doesn't.
+Delete a value from a set.
-``(/Just pat)``
-~~~~~~~~~~~~~~~
+``(member? x s)``
+~~~~~~~~~~~~~~~~~
-Pattern which matches ``[:just x]``.
+Query if an value is an element of a set.
-``(maybe->>= v f)``
-~~~~~~~~~~~~~~~~~~~
+``(to-vec s)``
+~~~~~~~~~~~~~~
-Monadic bind for the maybe monad.
+Convert a set to a vector.
-``(maybe-foldlM f i xs)``
-~~~~~~~~~~~~~~~~~~~~~~~~~
+``(from-seq xs)``
+~~~~~~~~~~~~~~~~~
-Monadic fold over the elements of a seq, associating to the left (i.e.
-from left to right) in the maybe monad.
+Create a set from a sequence.
-Lenses
-------
+``prelude/ref``
+---------------
-Functional references into radicle values.
+Functions for dealing with reference cells.
-``(@ k)``
-~~~~~~~~~
+``(modify-ref r f)``
+~~~~~~~~~~~~~~~~~~~~
-Returns a lens targetting keys of dicts.
+Modify 'ref' by applying the provided function. Returns the new value.
-``(@nth n)``
-~~~~~~~~~~~~
+``prelude/lens``
+----------------
-Lenses into the nth element of a vector
+Functional references.
``(make-lens g s)``
~~~~~~~~~~~~~~~~~~~
@@ -845,31 +815,11 @@ Makes a lens out of a getter and a setter.
View a value through a lens.
-``(view-ref r lens)``
-~~~~~~~~~~~~~~~~~~~~~
-
-Like 'view', but for refs.
-
``(set lens new-view target)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Set a value though a lens.
-``(set-ref r lens v)``
-~~~~~~~~~~~~~~~~~~~~~~
-
-Like 'set', but for refs.
-
-``(over lens f target)``
-~~~~~~~~~~~~~~~~~~~~~~~~
-
-Modify a value through a lens.
-
-``(over-ref r lens f)``
-~~~~~~~~~~~~~~~~~~~~~~~
-
-Like 'over', but for refs.
-
``id-lens``
~~~~~~~~~~~
@@ -885,128 +835,51 @@ Compose two lenses.
Compose multiple lenses.
-Validation
-----------
-
-Functions for creating or combining *validators*, which are functions
-which return the input unchanged or throw with an error message. These
-can be used for checking data before accepting it onto a chain.
-
-``(validator/= x)``
-~~~~~~~~~~~~~~~~~~~
-
-Given ``x``, returns a validator that checks for equality with ``x``.
-
-``(validator/member xs)``
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Given a structure, returns a validator which checks for membership in
-the structure.
-
-``(validator/type t)``
-~~~~~~~~~~~~~~~~~~~~~~
-
-Checks that a value has a type. Expects a keyword describing the type,
-as returned by the ``type`` function.
-
-``(validator/pred name p)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Given a description and a predicate, returns a validator that checks if
-the predicate is true.
-
-``(validator/every v)``
-~~~~~~~~~~~~~~~~~~~~~~~
-
-Given a validator, creates a new validator which checks that all the
-items in a sequence conform to it.
-
-``(validator/and vs)``
-~~~~~~~~~~~~~~~~~~~~~~
-
-Given a sequence of validators ``vs``, returns a new validator which,
-given a value, checks if it conforms to all the validators in ``vs``.
-
-``(validator/or vs)``
-~~~~~~~~~~~~~~~~~~~~~
-
-Given a vector of validators ``vs``, returns a new validator which,
-given a value, checks if it conforms to at least one of the ``vs``.
-
-``(validator/key k v)``
-~~~~~~~~~~~~~~~~~~~~~~~
-
-Given a key and a validator, returns a validator which checks for the
-existence of that key and that the associated value conforms to the
-validator.
-
-``(validator/keys ks)``
-~~~~~~~~~~~~~~~~~~~~~~~
-
-Given a dict associating keys to validators, returns a validator which
-checks a dict for the existence of those keys, and that they conform to
-the associated validators.
-
-``(validator/uuid x)``
-~~~~~~~~~~~~~~~~~~~~~~
-
-Validates UUIDs.
-
-``(validator/signed x)``
+``(over lens f target)``
~~~~~~~~~~~~~~~~~~~~~~~~
-Checks that a value is a dict with ``:signature`` and ``:author`` keys,
-and that the signature is valid for the rest of the dict for that
-author. The rest of the dict is turned into a string according to
-``show``.
+Modify a value through a lens.
-Cryptography
-------------
+``(@ k)``
+~~~~~~~~~
-Tools for creating and verifying cryptographic signatures, and
-generating private/public key pairs.
+Returns a lens targetting keys of dicts.
-``verify-signature``
-~~~~~~~~~~~~~~~~~~~~
+``(@nth n)``
+~~~~~~~~~~~~
-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``.
+Lenses into the nth element of a vector
-``default-ecc-curve``
+``(view-ref r lens)``
~~~~~~~~~~~~~~~~~~~~~
-Returns the default elliptic-curve used for generating cryptographic
-keys.
+Like 'view', but for refs.
-``gen-key-pair!``
-~~~~~~~~~~~~~~~~~
+``(set-ref r lens v)``
+~~~~~~~~~~~~~~~~~~~~~~
-Given an elliptic curve, generates a cryptographic key-pair. Use
-``default-ecc-curve`` for a default value for the elliptic curve.
+Like 'set', but for refs.
-``gen-signature!``
-~~~~~~~~~~~~~~~~~~
+``(over-ref r lens f)``
+~~~~~~~~~~~~~~~~~~~~~~~
-Given a private key and a message (a string), generates a cryptographic
-signature for the message.
+Like 'over', but for refs.
-Chain tools
------------
+``prelude/chain``
+-----------------
-These functions can be used to simulate remote chains in the local REPL.
-This is useful for experimenting with inputs or even new evaluation
-functions before sending these to a remote chain.
+Functions for simulating remote chains.
``(new-chain url)``
~~~~~~~~~~~~~~~~~~~
Return an empty chain dictionary with the given url.
-``(@var ident)``
-~~~~~~~~~~~~~~~~
+``(load-chain! url)``
+~~~~~~~~~~~~~~~~~~~~~
-A lens for variables in states of chains.
+Takes a ``url``, and fetches the inputs of a remote chain and return a
+chain dictionary with the chain state.
``(eval-in-chain expr chain)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1014,11 +887,25 @@ A lens for variables in states of chains.
Evaluates 'expr' in the 'chain' and returns a dict with the ':result'
and the resulting ':chain'.
-``(enter-remote-chain! url env)``
+``(update-chain-ref! chain-ref)``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Make the eval behave as that of a remote chain. The second param is the
-env to return to after :quit.
+Update ``chain-ref`` containing a chain with the new expressions from
+the remote chain
+
+``(eval expr env)``
+~~~~~~~~~~~~~~~~~~~
+
+An eval in which one can use ``(:enter-chain url)`` to make the eval
+behave as that of a remote chain, and ``:send`` to send all enqueued
+expressions.
+
+``(updatable-eval sub-eval)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Given an evaluation function ``f``, returns a new one which augments
+``f`` with a new command ``(update expr)`` which evaluates arbitrary
+expression using ``base-eval``.
``(update-chain! chain)``
~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -1026,81 +913,108 @@ env to return to after :quit.
Takes a chain, and returns a new chain updated with the new expressions
from the remote chain
-``(add-quit after-quit-state before-quit-eval)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+``(eval-fn-app state f arg cb)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Adds a ``:quit`` command to ``before-quit-eval``, which switches to
-``after-quit-state`` (and to the eval in that state)
+Given a state, a function, an argument and a callback, returns the
+result of evaluating the function call on the arg in the given state,
+while also calling the callback on the result.
-``(add-send! oeval)``
-~~~~~~~~~~~~~~~~~~~~~
+``(send-prelude! chain-id)``
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-Add a ``:send`` special form that sends the contents of ``_input`` to
-the chain ``_cur-chain``
+Send the pure prelude to a chain.
-``(load-chain! url)``
-~~~~~~~~~~~~~~~~~~~~~
+``prelude/state-machine``
+-------------------------
-Takes a ``url``, and fetches the inputs of a remote chain and return a
-chain dictionary with the chain state.
+An eval for running a state-machine with an updatable transition
+function.
-``pure-prelude-files``
-~~~~~~~~~~~~~~~~~~~~~~
+``prelude/validation``
+----------------------
-List of files which together define the pure prelude.
+Functions for creating or combining *validators*, which are functions
+which return the input unchanged or throw with an error message. These
+can be used for checking data before accepting it onto a chain.
-``pure-prelude-code!``
-~~~~~~~~~~~~~~~~~~~~~~
+``(= x)``
+~~~~~~~~~
-The pure prelude.
+Given ``x``, returns a validator that checks for equality with ``x``.
-``(store-exprs evalfn)``
-~~~~~~~~~~~~~~~~~~~~~~~~
+``(member xs)``
+~~~~~~~~~~~~~~~
-Store each new evaluated expression in ``_inputs``
+Given a structure, returns a validator which checks for membership in
+the structure.
-``(eval-fn-app state f arg cb)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+``(and vs)``
+~~~~~~~~~~~~
-Given a state, a function, an argument and a callback, returns the
-result of evaluating the function call on the arg in the given state,
-while also calling the callback on the result.
+Given a sequence of validators ``vs``, returns a new validator which,
+given a value, checks if it conforms to all the validators in ``vs``.
+
+``(or vs)``
+~~~~~~~~~~~
+
+Given a vector of validators ``vs``, returns a new validator which,
+given a value, checks if it conforms to at least one of the ``vs``.
+
+``(type t)``
+~~~~~~~~~~~~
-``(state-machine-eval voters init-state init-transition)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Checks that a value has a type. Expects a keyword describing the type,
+as returned by the ``type`` function.
-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.
+``(pred name p)``
+~~~~~~~~~~~~~~~~~
-``(state-machine-input state i)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Given a description and a predicate, returns a validator that checks if
+the predicate is true.
-Handle an input in the morphing state-machine.
+``(key k v)``
+~~~~~~~~~~~~~
-``(state-machine-new-trans state func)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Given a key and a validator, returns a validator which checks for the
+existence of that key and that the associated value conforms to the
+validator.
-Trigger a new vote.
+``(keys ks)``
+~~~~~~~~~~~~~
-``(state-machine-agree state voters userid)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Given a dict associating keys to validators, returns a validator which
+checks a dict for the existence of those keys, and that they conform to
+the associated validators.
-Vote to agree on a new transition function.
+``(every v)``
+~~~~~~~~~~~~~
-``(state-machine-disagree state voters userid)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Given a validator, creates a new validator which checks that all the
+items in a sequence conform to it.
-Vote to disagree on a new transition function.
+``(uuid x)``
+~~~~~~~~~~~~
-``(simple-trans f)``
-~~~~~~~~~~~~~~~~~~~~
+Validates UUIDs.
-Given a function ``f``, makes a transition function who's output is also
-the next state.
+``(signed x)``
+~~~~~~~~~~~~~~
-``(update-chain-ref! chain-ref)``
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Checks that a value is a dict with ``:signature`` and ``:author`` keys,
+and that the signature is valid for the rest of the dict for that
+author. The rest of the dict is turned into a string according to
+``show``.
-Update ``chain-ref`` containing a chain with the new expressions from
-the remote chain
\ No newline at end of file
+``prelude/util``
+----------------
+
+Utility functions. For the moment just a counter.
+
+``(make-counter)``
+~~~~~~~~~~~~~~~~~~
+
+Creates a stateful counter. Returns a dict with two keys: the function
+at ``:next-will-be`` will return the next number (without incrementing
+it), while the function at ``:next`` increments the number and returns
+it.
\ No newline at end of file
diff --git a/exe/ReferenceDoc.hs b/exe/ReferenceDoc.hs
index 42bf019..de8ce2b 100644
--- a/exe/ReferenceDoc.hs
+++ b/exe/ReferenceDoc.hs
@@ -1,157 +1,106 @@
+{-# LANGUAGE QuasiQuotes #-}
+
-- | This executable generates the radicle reference docs. This is a markdown
-- document which contains documentation for all the primitive functions and all
--- the functions defined in the prelude.
+-- the functions defined in the prelude modules.
module ReferenceDoc (main) where
import Protolude
import qualified Data.Default as Default
-import Data.List hiding (map)
+import Data.List ((\\))
import qualified Data.Map.Strict as Map
import qualified Data.Text as T
+import Data.Yaml hiding (Value)
import qualified GHC.Exts as GhcExts
import Radicle
+import Radicle.Internal.Core
+import Radicle.Internal.Identifier
import System.Console.Haskeline (defaultSettings, runInputT)
import Text.Pandoc
+data Content = Content
+ { intro :: Text
+ , primFnsDoc :: Text
+ , preludeModulesDoc :: Text
+ , primFns :: [Text]
+ , modules :: [Text]
+ } deriving (Generic)
+
+instance FromJSON Content
+
main :: IO ()
main = do
- (_, s) <- runInputT defaultSettings $
- interpretWithState
+ content <- decodeFileThrow "reference-doc.yaml"
+ res_ <- runInputT defaultSettings $
+ interpret
"reference-doc"
- "(load! \"rad/prelude.rad\")"
+ ( "(do"
+ <> "(file-module! \"rad/prelude/test.rad\") (import prelude/test :unqualified)"
+ <> foldMap (\m -> "(file-module! \"rad/" <> m <> ".rad\")") (modules content)
+ <> "(get-current-env))")
replBindings
+ let res = res_ `lPanic` "Error running the prelude."
+ let s = bindingsFromRadicle res `lPanic` "Couldn't convert radicle state."
let vars = GhcExts.toList (bindingsEnv s)
- let undocd = [ fromIdent iden | (iden, Nothing, _) <- vars ]
- checkAllDocumented undocd
+ checkAllDocumented [ fromIdent iden | (iden, Nothing, _) <- vars ]
let e = Map.fromList [ (fromIdent iden, (docString, val)) | (iden, Just docString, val) <- vars ]
- checkAllInReference e
- rst <- runPure (writeRST Default.def $ Pandoc nullMeta (doc e)) `lPanic` "Couldn't generate RST"
+ checkAllInReference content e
+ let rst = runPure (writeRST Default.def $ Pandoc nullMeta (doc content e)) `lPanic` "Couldn't generate RST"
writeFile "docs/source/reference.rst" rst
where
- doc e =
- let sec tit names p =
- [ Header 2 nullAttr (inlinePandoc tit)
- , Para (inlinePandoc p)
- ] ++ foldMap (valueDoc e) names in
- mconcat
- [ [ Header 1 nullAttr (inlinePandoc "Radicle Reference") ]
- , [ Para $ inlinePandoc $
- "These are the functions that are available in a new radicle chain after"
- <> " the prelude has been loaded."
- ]
- , sec "Basics" basics
- "Basic function used for checking equality, determining the type of a value, etc."
- , sec "Numerical functions" maths "Operations on numbers."
- , sec "Lists" lists $ typ "lists"
- , sec "Vectors" vecs $ typ "vectors"
- , sec "Sequences" seqs $ typ "boths lists and vectors"
- , sec "Dicts" dicts $ typ "dicts"
- , sec "Sets" sets $ typ "sets"
- , sec "Strings" strings $ typ "strings"
- , sec "Structures" structs $ typ "lists, vectors and dicts"
- , sec "Patterns" patterns
- "Pattern matching is first-class in radicle so new patterns can easily be defined. These are the most essential."
- , sec "Refs" refs "Functions for creating, querying and modifying refs."
- , sec "Evaluation functions" evalFns "Utilities for creating and extending evaluation functions."
- , sec "Documentation and testing" docs
- "Functions for creating and querying documentation of variables in scope, and testing functions."
- , sec "Environment functions" envStuff "Utilities for modifying the current environment."
- , sec "Input/Output" io
- "Effectful functions. These functions are not available in 'pure' chains, but are available in the local REPL."
- , sec "Maybe" maybe'
- "Optionality is represented using `[:just x]` for when the value exists, and `:nothing` when it doesn't."
- , sec "Lenses" lens
- "Functional references into radicle values."
- , sec "Validation" validation
- "Functions for creating or combining *validators*, which are functions which return the\
- \ input unchanged or throw with an error message. These can be used for checking data before\
- \ accepting it onto a chain."
- , sec "Cryptography" crypto
- "Tools for creating and verifying cryptographic signatures, and generating private/public key pairs."
- , sec "Chain tools" chainTools
- "These functions can be used to simulate remote chains in the local REPL.\
- \ This is useful for experimenting with inputs or even new evaluation functions\
- \ before sending these to a remote chain."
- ]
-
- basics =
- [ "eq?", "not", "and", "or", "all", "some", "show", "string-append", "string-length"
- , "apply", "type", "atom?", "boolean?", "string?", "number?", "keyword?", "vector?", "list?"
- , "dict?", "read", "read-many", "throw", "to-json", "uuid?", "make-counter"
- , "public-key?" ]
- maths = ["+", "*", "-", "/", "<", ">", "integral?"]
- evalFns = ["base-eval", "eval", "updatable-eval"]
- envStuff = ["pure-env", "get-current-env", "set-current-env", "set-env!"]
- seqs = ["empty-seq?", "nth", "foldl", "foldr", "map", "seq", "take", "drop", "sort-by", "zip"]
- lists =
- [ "list", "nil", "head", "tail", "empty?", "cons", "reverse", "length", "concat"
- , "filter", "range", "list-with-head" ]
- vecs = ["<>", "add-left", "add-right"]
- dicts =
- ["dict", "lookup", "insert", "delete", "dict-from-list", "keys", "values", "rekey"
- , "map-values", "map-keys", "modify-map", "delete-many", "exclusive-dict-merge"]
- sets = ["set/empty", "set/insert", "set/delete", "set/member?", "set/delete", "set/from-seq", "set/to-vec"]
- strings = ["intercalate", "unlines", "string-replace", "unwords"]
- structs = ["member?"]
- patterns = ["match-pat", "_", "/?", "/nil", "/cons", "/as", "non-linear-merge"]
- refs = ["ref", "read-ref", "write-ref", "modify-ref"]
- docs = ["help", "doc", "doc!", "apropos!", "is-test-env"]
- io =
- [ "print!", "get-line!"
- , "load!", "read-file!", "read-code!", "send-code!"
- , "put-str!", "process!", "shell!", "system!"
- , "send-prelude!", "subscribe-to!", "uuid!", "read-line!", "exit!"
- , "read-line-handle!", "wait-for-process!", "write-handle!", "now!"]
- maybe' = ["/Just", "maybe->>=", "maybe-foldlM"]
- lens = ["@", "@nth", "make-lens", "view", "view-ref", "set", "set-ref", "over", "over-ref", "id-lens", "..", "..."]
- validation =
- [ "validator/=", "validator/member", "validator/type", "validator/pred", "validator/every"
- , "validator/and", "validator/or", "validator/key", "validator/keys", "validator/uuid", "validator/signed"]
- crypto = ["verify-signature", "default-ecc-curve", "gen-key-pair!", "gen-signature!"]
- chainTools =
- [ "new-chain", "@var", "eval-in-chain", "enter-remote-chain!", "update-chain!", "add-quit", "add-send!"
- , "load-chain!", "pure-prelude-files", "pure-prelude-code!", "store-exprs", "eval-fn-app"
- , "state-machine-eval", "state-machine-input", "state-machine-new-trans"
- , "state-machine-agree", "state-machine-disagree", "simple-trans", "update-chain-ref!"]
-
- -- issueChain = ["create-issues-chain!", "list-issues", "new-issue!"]
-
- typ s = "Functions for manipulating " <> s <> "."
-
- -- Functions which shouldn't be in the reference docs.
- doNotInclude = ["head-shots", "get-head-shot", "eval__", "kim-trans", "pr-thread", "pr-trans", "_initial-prompt-text"]
-
- allFns =
- basics ++ maths ++ evalFns ++ envStuff ++ seqs ++ lists ++ vecs
- ++ dicts ++ sets ++ strings ++ structs ++ patterns ++ refs ++ docs ++ io ++ maybe'
- ++ lens ++ validation ++ crypto ++ chainTools
- ++ doNotInclude
+
+ doc content e =
+ [ Header 1 nullAttr (inlinePandoc "Radicle Reference")
+ , Para $ inlinePandoc (intro content)
+ , Header 2 nullAttr (inlinePandoc "Primitive functions")
+ , Para $ inlinePandoc $ primFnsDoc content
+ ] ++ foldMap (valueDoc e) (primFns content) ++
+ [ Header 2 nullAttr (inlinePandoc "Prelude modules")
+ , Para $ inlinePandoc $ preludeModulesDoc content
+ ] ++ foldMap (module' e) (modules content)
+
+ defs v = let env = envFromRad v `lPanic` "Couldn't convert radicle value to as environment"
+ in Map.fromList [ (fromIdent iden, (docString, val)) | (iden, Just docString, val) <- GhcExts.toList env ]
+
+ module' env name = case lkp name env "Couldn't find module in the env" of
+ (docString, Dict d) -> case (lkp [kword|exports|] d "invalid module", lkp [kword|env|] d "invalid module") of
+ (Vec es, e) ->
+ [ Header 2 nullAttr [ Code nullAttr (toS name) ]
+ , Para (inlinePandoc docString)
+ ] ++ foldMap (export (defs e)) es
+ _ -> panic $ "Module " <> name <> " didn't have an exports vec."
+ _ -> panic $ "Module " <> name <> " was not a dict."
+
+ export env (Atom (Ident name)) = valueDoc env name
+ export _ _ = panic "Export was not an atom."
valueDoc env name =
- case Map.lookup name env of
- Just (docString, Lambda args _ _) ->
+ case lkp name env "couldn't find value" of
+ (docString, Lambda args _ _) ->
let callExample = "(" <> T.intercalate " " (name : map fromIdent args) <> ")"
in [ Header 3 nullAttr [Code nullAttr (toS callExample) ]
, Para (inlinePandoc docString) ]
- Just (docString, _) ->
+ (docString, _) ->
[ Header 3 nullAttr [Code nullAttr (toS name) ]
, Para (inlinePandoc docString) ]
- Nothing -> panic $ "While creating reference doc, couldn't find the docs for: " <> name
-
checkAllDocumented = \case
[] -> pure ()
vs -> panic $ "The following functions have no documentation strings: " <> T.intercalate ", " vs
- checkAllInReference e =
- let notDocumented = Map.keys e \\ allFns in
+ checkAllInReference content e =
+ let notDocumented = Map.keys e \\ (primFns content ++ modules content ++ ["prelude/test"]) in
if null notDocumented
then pure ()
- else panic $ "The following functions need to be added to the reference doc: " <> T.intercalate ", " notDocumented
+ else panic $ "The following functions need to be added to the reference doc: " <> T.intercalate ", " notDocumented
lPanic (Left e) m = panic $ m <> ": " <> show e
- lPanic (Right r) _ = pure r
+ lPanic (Right r) _ = r
+
+ lkp x m e = case Map.lookup x m of
+ Just y -> y
+ Nothing -> panic $ e <> ": couldn't find " <> show x
inlinePandoc t = case runPure (readMarkdown Default.def t) of
Right (Pandoc _ [Para is]) -> is
diff --git a/package.yaml b/package.yaml
index f8d5be8..30fefdc 100644
--- a/package.yaml
+++ b/package.yaml
@@ -175,6 +175,7 @@ executables:
- containers
- haskeline
- text
+ - yaml
ghc-options: -main-is ReferenceDoc
radicle-github-issues:
diff --git a/rad/monadic/issue-remote.rad b/rad/monadic/issue-remote.rad
index da7954b..f1af842 100644
--- a/rad/monadic/issue-remote.rad
+++ b/rad/monadic/issue-remote.rad
@@ -1,6 +1,15 @@
;; Issue chain
;; Meant to be sent to a chain with send-code!
+(import prelude/bool :unqualified)
+(import prelude/dict :unqualified)
+(import prelude/set :as 'set)
+(import prelude/ref :unqualified)
+(import prelude/validation :as 'validator)
+(import prelude/patterns :unqualified)
+(import prelude/util :unqualified)
+(import prelude/lens :unqualified)
+
(def chain-id
"The name of this chain."
"monadic/radicle/issues")
@@ -170,13 +179,11 @@
command `(update expr)` which evaluates arbitrary expression using `base-eval`."
(fn [sub-eval]
(fn [expr state]
- (list-with-head
- expr
- (fn [cmd]
- (if (eq? cmd 'update)
- (base-eval (nth 1 expr) state)
- (sub-eval expr state)))
- (fn [] (sub-eval expr state))))))
+ (match expr
+ (/cons 'cmd _) (if (eq? cmd 'update)
+ (base-eval (nth 1 expr) state)
+ (sub-eval expr state))
+ _ (sub-eval expr state)))))
(def eval (updatable-eval
(fn [expr state]
diff --git a/rad/monadic/issues.rad b/rad/monadic/issues.rad
index 9c291db..c6a9e87 100644
--- a/rad/monadic/issues.rad
+++ b/rad/monadic/issues.rad
@@ -6,18 +6,20 @@
(load! "rad/prelude.rad")
+(import prelude/lens :unqualified)
+
(def radicle-issues-chain-id
"The name of this chain."
"monadic/radicle/issues")
-(def issues-chain!
- (ref (load-chain! "http://radicle.xyz/chains/radicle-issues")))
+(def issues-chain
+ (ref (chain/load-chain! "http://radicle.xyz/chains/radicle-issues")))
(def create-issues-chain!
"Create a remote issue chain with the given url."
(fn []
- (def url (lookup :url (read-ref issues-chain!)))
- (send-prelude! url)
+ (def url (lookup :url (read-ref issues-chain)))
+ (chain/send-prelude! url)
(send-code! url "rad/monadic/issue-remote.rad")))
(def sign-entity!
@@ -56,13 +58,13 @@
(def create-issue!
"Create a new remote issue with the keys in `my-keys.rad`."
(fn [i]
- (send! (lookup :url (read-ref issues-chain!))
+ (send! (lookup :url (read-ref issues-chain))
[(list 'create-issue (sign-entity! i))])))
(def add-comment!
"Create a remote comment with the keys in `my-keys.rad`."
(fn [c]
- (send! (lookup :url (read-ref issues-chain!))
+ (send! (lookup :url (read-ref issues-chain))
[(list 'add-comment (sign-entity! c))])))
(def simple-create-issue!
@@ -75,15 +77,15 @@
(fn [in b]
(add-comment! (simple-comment in b))))
-(def list-issues!
+(def list-issues
"Return the full map of issues."
(fn []
- (lookup :result (eval-in-chain '(list-issues) (read-ref issues-chain!)))))
+ (lookup :result (chain/eval-in-chain '(list-issues) (read-ref issues-chain)))))
(def fetch!
"Update the locally cached state of the chain."
(fn []
- (update-chain-ref! issues-chain!)))
+ (chain/update-chain-ref! issues-chain)))
(def import-github
"Imports the github issues stored in file `githubissues.rad`. To create this
@@ -117,15 +119,15 @@
": "
(lookup :title i))))
-(def list-last!
+(def list-last
"Get the last `n` issues."
(fn [n]
- (def is (sort-by (fn [i] (- 0 (lookup :number i))) (values (list-issues!))))
+ (def is (sort-by (fn [i] (- 0 (lookup :number i))) (values (list-issues))))
(take n is)))
-(def get-by-id!
+(def get-by-id
(fn [id]
- (lookup id (list-issues!))))
+ (lookup id (list-issues))))
(:test
"The monadic issues chain works."
@@ -136,11 +138,11 @@
(simple-add-comment! 0 "comment0")
(simple-add-comment! 1 "comment1")
(fetch!)
- (def is (list-issues!)))]
+ (def is (list-issues)))]
[ (length (seq is)) ==> 2 ]
[ (view (.. (@ 0) (@ :title)) is) ==> "title0" ]
[ (view (.. (@ 1) (@ :title)) is) ==> "title1" ]
[ (view (... [(@ 1) (@ :comments) (@nth 0) (@ :body)]) is) ==> "comment1" ]
[ (short (head (values is))) ==> "0: title0" ]
- [ (short (head (list-last! 1))) ==> "1: title1" ]
+ [ (short (head (list-last 1))) ==> "1: title1" ]
)
diff --git a/rad/prelude.rad b/rad/prelude.rad
index 637af4d..a6063ef 100644
--- a/rad/prelude.rad
+++ b/rad/prelude.rad
@@ -1,47 +1,34 @@
-(load! "rad/prelude/test.rad")
-(load! "rad/prelude/basic.rad")
-(load! "rad/prelude/patterns.rad")
-(load! "rad/prelude/strings.rad")
-(load! "rad/prelude/io.rad")
-(load! "rad/prelude/bool.rad")
-(load! "rad/prelude/exception.rad")
-(load! "rad/prelude/list.rad")
-(load! "rad/prelude/dict.rad")
-(load! "rad/prelude/set.rad")
-(load! "rad/prelude/ref.rad")
-(load! "rad/prelude/lens.rad")
-(load! "rad/chain.rad")
-(load! "rad/state-machine.rad")
-(load! "rad/prelude/validation.rad")
-(load! "rad/prelude/util.rad")
+(file-module! "rad/prelude/test.rad")
+(import prelude/test '[eval] :unqualified)
-(def pure-prelude-files
- "List of files which together define the pure prelude."
- (list
- "rad/prelude/test.rad" ;; pure unless test env
- "rad/prelude/basic.rad"
- "rad/prelude/patterns.rad"
- "rad/prelude/bool.rad"
- "rad/prelude/list.rad"
- "rad/prelude/dict.rad"
- "rad/prelude/set.rad"
- "rad/prelude/ref.rad"
- "rad/prelude/lens.rad"
- "rad/state-machine.rad"
- "rad/prelude/validation.rad"
- "rad/prelude/util.rad"
- ))
+(file-module! "rad/prelude/basic.rad")
+(file-module! "rad/prelude/patterns.rad")
+(file-module! "rad/prelude/strings.rad")
+(file-module! "rad/prelude/io.rad")
+(file-module! "rad/prelude/bool.rad")
+(file-module! "rad/prelude/exception.rad")
+(file-module! "rad/prelude/list.rad")
+(file-module! "rad/prelude/dict.rad")
+(file-module! "rad/prelude/set.rad")
+(file-module! "rad/prelude/ref.rad")
+(file-module! "rad/prelude/lens.rad")
+(file-module! "rad/prelude/chain.rad")
+(file-module! "rad/prelude/state-machine.rad")
+(file-module! "rad/prelude/validation.rad")
+(file-module! "rad/prelude/util.rad")
-(def pure-prelude-code!
- "The pure prelude."
- (read-many
- (apply string-append
- (map (fn [f] (read-file! f)) pure-prelude-files))))
-
-(def send-prelude!
- "Send the pure prelude to a chain."
- (fn [chain-id]
- (send! chain-id pure-prelude-code!)))
+(import prelude/basic :unqualified)
+(import prelude/patterns :unqualified)
+(import prelude/strings :as 'string)
+(import prelude/io :unqualified)
+(import prelude/bool :unqualified)
+(import prelude/list :unqualified)
+(import prelude/dict :unqualified)
+(import prelude/ref :unqualified)
+(import prelude/validation :as 'validator)
+(import prelude/util :unqualified)
+(import prelude/chain :as 'chain)
+(import prelude/chain '[eval] :unqualified)
(def _initial-prompt-text
"Text used for greeting in the repl."
diff --git a/rad/prelude/basic.rad b/rad/prelude/basic.rad
index 097d408..c85e102 100644
--- a/rad/prelude/basic.rad
+++ b/rad/prelude/basic.rad
@@ -1,3 +1,7 @@
+{:module 'prelude/basic
+ :doc "Basic function used for checking equality, determining the type of a value, etc."
+ :exports '[or some empty-seq? length maybe->>= maybe-foldlM]}
+
;; or
(def or
@@ -44,3 +48,23 @@
[ (length (list)) ==> 0]
[ (length (list 2)) ==> 1]
)
+
+(def maybe->>=
+ "Monadic bind for the maybe monad."
+ (fn [v f]
+ (if (vector? v)
+ (if (eq? (length v) 2)
+ (if (eq? (nth 0 v) :just)
+ (f (nth 1 v))
+ :nothing)
+ :nothing)
+ :nothing)))
+
+(def-rec maybe-foldlM
+ "Monadic fold over the elements of a seq, associating to the left (i.e. from
+ left to right) in the maybe monad."
+ (fn [f i xs]
+ (if (empty-seq? xs)
+ [:just i]
+ (maybe->>= (f i (nth 0 xs))
+ (fn [b] (maybe-foldlM f b (drop 1 xs)))))))
diff --git a/rad/prelude/bool.rad b/rad/prelude/bool.rad
index 7b34eb2..0a20ea0 100644
--- a/rad/prelude/bool.rad
+++ b/rad/prelude/bool.rad
@@ -1,3 +1,7 @@
+{:module 'prelude/bool
+ :doc "Functions for dealing with truthiness and #f."
+ :exports '[not and all]}
+
;; boolean functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; not
diff --git a/rad/chain.rad b/rad/prelude/chain.rad
similarity index 79%
rename from rad/chain.rad
rename to rad/prelude/chain.rad
index b9d2010..f1ca930 100644
--- a/rad/chain.rad
+++ b/rad/prelude/chain.rad
@@ -1,3 +1,10 @@
+{:module 'prelude/chain
+ :doc "Functions for simulating remote chains."
+ :exports '[new-chain load-chain! eval-in-chain update-chain-ref! eval updatable-eval update-chain! eval-fn-app send-prelude!]}
+
+(import prelude/ref '[modify-ref] :unqualified)
+(import prelude/lens '[.. ... view over @] :unqualified)
+
;; Chains: Functions for dealing with chains.
;; A chain is conceptually:
@@ -178,10 +185,39 @@
command `(update expr)` which evaluates arbitrary expression using `base-eval`."
(fn [sub-eval]
(fn [expr state]
- (list-with-head
- expr
- (fn [cmd]
- (if (eq? cmd 'update)
- (base-eval (nth 1 expr) state)
- (sub-eval expr state)))
- (fn [] (sub-eval expr state))))))
+ (match expr
+ (/cons 'cmd _) (if (eq? cmd 'update)
+ (base-eval (nth 1 expr) state)
+ (sub-eval expr state))
+ _ (sub-eval expr state)))))
+
+(def pure-prelude-files
+ "List of files which together define the pure prelude."
+ ["rad/prelude/basic.rad"
+ "rad/prelude/patterns.rad"
+ "rad/prelude/strings.rad"
+ "rad/prelude/bool.rad"
+ "rad/prelude/list.rad"
+ "rad/prelude/dict.rad"
+ "rad/prelude/set.rad"
+ "rad/prelude/ref.rad"
+ "rad/prelude/lens.rad"
+ "rad/prelude/state-machine.rad"
+ "rad/prelude/validation.rad"
+ "rad/prelude/util.rad"])
+
+(def file-to-module
+ "Make the text of a file into code for a module."
+ (fn [file]
+ (cons 'module (vec-to-list (read-many (read-file! file))))))
+
+(def pure-prelude-code
+ "Code for the pure prelude. Useful as the first inputs to a new chain."
+ (<> [(file-to-module "rad/prelude/test.rad")
+ '(import prelude/test :unqualified)]
+ (map file-to-module pure-prelude-files)))
+
+(def send-prelude!
+ "Send the pure prelude to a chain."
+ (fn [chain-id]
+ (send! chain-id pure-prelude-code)))
diff --git a/rad/prelude/dict.rad b/rad/prelude/dict.rad
index 55cea75..acea4a6 100644
--- a/rad/prelude/dict.rad
+++ b/rad/prelude/dict.rad
@@ -1,14 +1,14 @@
-;; dict functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+{:module 'prelude/dict
+ :doc "Functions for manipualting dicts."
+ :exports '[dict-from-seq keys values rekey modify-map delete-many]}
-;; dict-from-list
-
-(def dict-from-list
+(def dict-from-seq
"Creates a dictionary from a list of key-value pairs."
(fn [xs]
(foldr (fn [kv acc] (insert (head kv) (head (tail kv)) acc)) (dict) xs)))
-(:test "dict-from-list"
- [ (dict-from-list (list (list :one 1) (list :two 2)))
+(:test "dict-from-seq"
+ [ (dict-from-seq (list (list :one 1) (list :two 2)))
==> { :one 1 :two 2 } ])
;; keys
diff --git a/rad/prelude/exception.rad b/rad/prelude/exception.rad
index d60b6ad..74e1217 100644
--- a/rad/prelude/exception.rad
+++ b/rad/prelude/exception.rad
@@ -1,3 +1,7 @@
+{:module 'prelude/exception
+ :doc "Tests for exceptions."
+ :exports []}
+
(:test "catch handles scope correctly"
;; Issue #191, catch used to accidentally use the lexical environment of
;; the `throw` that generated the exception.
diff --git a/rad/prelude/io.rad b/rad/prelude/io.rad
index e953eab..ce13355 100644
--- a/rad/prelude/io.rad
+++ b/rad/prelude/io.rad
@@ -1,3 +1,7 @@
+{:module 'prelude/io
+ :doc "Some basic I/O functions."
+ :exports '[print! shell! process! read-line! send-code! read-code!]}
+
;; read-line
(def read-line!
"Read a single line of input and interpret it as radicle data."
diff --git a/rad/prelude/lens.rad b/rad/prelude/lens.rad
index cf64aab..5ceec89 100644
--- a/rad/prelude/lens.rad
+++ b/rad/prelude/lens.rad
@@ -1,3 +1,9 @@
+{:module 'prelude/lens
+ :doc "Functional references."
+ :exports ['make-lens 'view 'set 'id-lens '.. '... 'over '@ '@nth 'view-ref 'set-ref 'over-ref]}
+
+(import prelude/ref :unqualified)
+
;; Lenses ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; make-lens
diff --git a/rad/prelude/list.rad b/rad/prelude/list.rad
index 5903783..3a99aaf 100644
--- a/rad/prelude/list.rad
+++ b/rad/prelude/list.rad
@@ -1,7 +1,11 @@
-;; List functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+{:module 'prelude/list
+ :doc "Functions for manipulating lists."
+ :exports ['nil 'empty? 'reverse 'range 'concat 'filter]}
;; nil
+(import prelude/basic :unqualified)
+
(def nil "The empty list." (list))
;; empty?
@@ -70,13 +74,3 @@
[ (filter (fn [x] (< x 10)) (list 3 10 11))
==> (3) ]
)
-
-(def list-with-head
- "Given a value `x`, and two functions `f` and `g`, checks if `x` is a list with a
- head. If so applies `f` to the head, otherwise calls `g` with no args."
- (fn [x f g]
- (if (list? x)
- (if (> (length x) 0)
- (f (head x))
- (g))
- (g))))
diff --git a/rad/prelude/patterns.rad b/rad/prelude/patterns.rad
index 2d5641d..03873ef 100644
--- a/rad/prelude/patterns.rad
+++ b/rad/prelude/patterns.rad
@@ -1,25 +1,8 @@
-;; Because pattern matching uses the Maybe-monad, it's helpful to define some
-;; essential Maybe-monad function now.
-
-(def maybe->>=
- "Monadic bind for the maybe monad."
- (fn [v f]
- (if (vector? v)
- (if (eq? (length v) 2)
- (if (eq? (nth 0 v) :just)
- (f (nth 1 v))
- :nothing)
- :nothing)
- :nothing)))
+{:module 'prelude/patterns
+ :doc "Pattern matching is first-class in radicle so new patterns can easily be defined. These are the most essential."
+ :exports '[match-pat _ /? /as /cons /nil /just]}
-(def-rec maybe-foldlM
- "Monadic fold over the elements of a seq, associating to the left (i.e. from
- left to right) in the maybe monad."
- (fn [f i xs]
- (if (empty-seq? xs)
- [:just i]
- (maybe->>= (f i (nth 0 xs))
- (fn [b] (maybe-foldlM f b (drop 1 xs)))))))
+(import prelude/basic :unqualified)
(def exclusive-dict-merge
"Merges two dicts while checking for key conflicts. Returns `{:merge
@@ -120,7 +103,7 @@
['x 'x] :yes
['x 'y] :no) ==> :yes])
-(def /Just
+(def /just
"Pattern which matches `[:just x]`."
(fn [pat]
(fn [v]
@@ -128,8 +111,8 @@
(fn [x] (match-pat pat x))))))
(:test "Just patterns"
- [ (match [:just 42] (/Just 'x) x _ :no) ==> 42 ]
- [ (match :nothing (/Just 'x) x _ :yes) ==> :yes ])
+ [ (match [:just 42] (/just 'x) x _ :no) ==> 42 ]
+ [ (match :nothing (/just 'x) x _ :yes) ==> :yes ])
(def /cons
"A pattern for lists with a head and a tail."
diff --git a/rad/prelude/ref.rad b/rad/prelude/ref.rad
index 5ab3f07..89fab10 100644
--- a/rad/prelude/ref.rad
+++ b/rad/prelude/ref.rad
@@ -1,6 +1,7 @@
-;; ref functions ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+{:module 'prelude/ref
+ :doc "Functions for dealing with reference cells."
+ :exports ['modify-ref]}
-;; modify-ref
(def modify-ref
"Modify 'ref' by applying the provided function. Returns the new value."
(fn [r f]
diff --git a/rad/prelude/set.rad b/rad/prelude/set.rad
index 28fa39b..5bccd68 100644
--- a/rad/prelude/set.rad
+++ b/rad/prelude/set.rad
@@ -1,26 +1,30 @@
-(def set/empty
+{:module 'prelude/set
+ :doc "Sets, built using dicts."
+ :exports '[empty insert delete member? to-vec from-seq]}
+
+(def empty
"An empty set."
{})
-(def set/insert
+(def insert
"Insert a value into a set."
(fn [x s]
(insert x #t s)))
-(def set/delete
+(def delete
"Delete a value from a set."
(fn [x s]
(delete x s)))
-(def set/member?
+(def member?
"Query if an value is an element of a set."
(fn [x s]
(member? x s)))
-(def set/to-vec
+(def to-vec
"Convert a set to a vector."
(fn [s] (keys s)))
-(def set/from-seq
+(def from-seq
"Create a set from a sequence."
(fn [xs] (foldr set/insert {} xs)))
diff --git a/rad/state-machine.rad b/rad/prelude/state-machine.rad
similarity index 97%
rename from rad/state-machine.rad
rename to rad/prelude/state-machine.rad
index 2995b04..1b696d9 100644
--- a/rad/state-machine.rad
+++ b/rad/prelude/state-machine.rad
@@ -1,3 +1,6 @@
+{:module 'prelude/state-machine
+ :doc "An eval for running a state-machine with an updatable transition function."
+ :exports []}
(def head-shots
"Avatars for some of the monadic team members."
diff --git a/rad/prelude/strings.rad b/rad/prelude/strings.rad
index 7f11678..9b657a9 100644
--- a/rad/prelude/strings.rad
+++ b/rad/prelude/strings.rad
@@ -1,3 +1,10 @@
+{:module 'prelude/strings
+ :doc "String manipulation functions."
+ :exports '[intercalate unlines unwords]
+ }
+
+(import prelude/basic :unqualified)
+
(def intercalate
"Intercalates a string in a list of strings"
(fn [sep strs]
diff --git a/rad/prelude/test.rad b/rad/prelude/test.rad
index a3be0ce..8fa2240 100644
--- a/rad/prelude/test.rad
+++ b/rad/prelude/test.rad
@@ -1,3 +1,7 @@
+{:module 'prelude/test
+ :doc "An eval used for testing."
+ :exports ['eval]}
+
;; testing functions
(def is-test-env
diff --git a/rad/prelude/util.rad b/rad/prelude/util.rad
index 2d3e84a..7999e52 100644
--- a/rad/prelude/util.rad
+++ b/rad/prelude/util.rad
@@ -1,3 +1,9 @@
+{:module 'prelude/util
+ :doc "Utility functions. For the moment just a counter."
+ :exports ['make-counter]}
+
+(import prelude/ref :unqualified)
+
(def make-counter
"Creates a stateful counter. Returns a dict with two keys: the function at `:next-will-be`
will return the next number (without incrementing it), while the function at `:next`
diff --git a/rad/prelude/validation.rad b/rad/prelude/validation.rad
index 75468e6..9dd4902 100644
--- a/rad/prelude/validation.rad
+++ b/rad/prelude/validation.rad
@@ -1,4 +1,10 @@
-(def validator/=
+{:module 'prelude/validation
+ :doc "Functions for creating or combining *validators*, which are functions which return the input unchanged or throw with an error message. These can be used for checking data before accepting it onto a chain."
+ :exports ['= 'member 'and 'or 'type 'pred 'key 'keys 'every 'uuid 'signed]}
+
+(import prelude/dict :unqualified)
+
+(def =
"Given `x`, returns a validator that checks for equality with `x`."
(fn [x]
(fn [y]
@@ -6,7 +12,7 @@
x
(throw 'validation-failure (string-append "Not equal to: " (show x)))))))
-(def validator/member
+(def member
"Given a structure, returns a validator which checks for membership in the structure."
(fn [xs]
(fn [x]
@@ -14,7 +20,7 @@
x
(throw 'validation-failure (string-append "Not a member of: " (show xs)))))))
-(def validator/and
+(def and
"Given a sequence of validators `vs`, returns a new validator which, given a
value, checks if it conforms to all the validators in `vs`."
(fn [vs]
@@ -22,7 +28,7 @@
(map (fn [v] (v x)) vs)
x)))
-(def-rec validator/or
+(def-rec or
"Given a vector of validators `vs`, returns a new validator which, given a
value, checks if it conforms to at least one of the `vs`."
(fn [vs]
@@ -32,9 +38,9 @@
(catch
'validation-failure
((nth 0 vs) x)
- (fn [y] ((validator/or (drop 1 vs)) x)))))))
+ (fn [y] ((or (drop 1 vs)) x)))))))
-(def validator/type
+(def type
"Checks that a value has a type. Expects a keyword describing the type, as
returned by the `type` function."
(fn [t]
@@ -43,7 +49,7 @@
x
(throw 'validation-failure (string-append "Did not have type " (show t) ": " (show x)))))))
-(def validator/pred
+(def pred
"Given a description and a predicate, returns a validator that checks if the
predicate is true."
(fn [name p]
@@ -52,7 +58,7 @@
x
(throw 'validation-failure (string-append "Did not satisfy predicate: " name))))))
-(def validator/key
+(def key
"Given a key and a validator, returns a validator which checks for
the existence of that key and that the associated value conforms to the validator."
(fn [k v]
@@ -61,39 +67,39 @@
(v (lookup k d))
(throw 'validation-failure (string-append "Missing required key: " (show k)))))))
-(def validator/keys
+(def keys
"Given a dict associating keys to validators, returns a validator which checks a dict
for the existence of those keys, and that they conform to the associated validators."
(fn [ks]
(fn [d]
(if (dict? d)
- ((validator/and
- (map (fn [kv] (validator/key (nth 0 kv) (nth 1 kv)))
+ ((and
+ (map (fn [kv] (key (nth 0 kv) (nth 1 kv)))
(seq ks)))
d)
(throw 'validation-failure (string-append "Not a dict: " (show d)))))))
-(def validator/every
+(def every
"Given a validator, creates a new validator which checks that all the items in
a sequence conform to it."
(fn [v]
(fn [xs]
(map v xs))))
-(def validator/uuid
+(def uuid
"Validates UUIDs."
- (validator/and
- [(validator/type :string)
- (validator/pred "valid UUID" uuid?)]))
+ (and
+ [(type :string)
+ (pred "valid UUID" uuid?)]))
-(def validator/signed
+(def signed
"Checks that a value is a dict with `:signature` and `:author` keys, and that
the signature is valid for the rest of the dict for that author. The rest of
the dict is turned into a string according to `show`."
- (validator/and
- [(validator/keys
- {:author (validator/pred "valid public key" public-key?)})
- (validator/pred
+ (and
+ [(keys
+ {:author (pred "valid public key" public-key?)})
+ (pred
"Valid signature"
(fn [d]
(verify-signature
@@ -101,7 +107,7 @@
(lookup :signature d)
(show (delete-many [:author :signature] d)))))]))
-(:test "validator/signed"
+(:test "signed"
[:setup
(do (def keys (gen-key-pair! (default-ecc-curve)))
(def sk (lookup :private-key keys))
@@ -116,7 +122,7 @@
(def full (<> payload seal))
(def full_ (<> payload_ seal))
(def ok
- (catch 'any (do (validator/signed full) :ok) (fn [x] :not-ok)))
+ (catch 'any (do (signed full) :ok) (fn [x] :not-ok)))
)
]
[ ok ==> :ok ]
diff --git a/reference-doc.yaml b/reference-doc.yaml
new file mode 100644
index 0000000..2b904c0
--- /dev/null
+++ b/reference-doc.yaml
@@ -0,0 +1,134 @@
+---
+
+intro: >-
+ This is the `radicle` reference document, with documentation for all functions
+ which come as part of the standard distribution.
+
+primFnsDoc: >-
+ Primitive functions are those that are built into the compiler. They are
+ available on all chains but may be shadowed by later definitions. Those that
+ end in a `!` are only available locally, not on 'pure' chains.
+
+preludeModulesDoc: >-
+ These are the modules included in the radicle prelude and the functions these
+ modules expose.
+
+primFns:
+# Basics
+- "*"
+- "+"
+- "-"
+- "/"
+- "<"
+- ">"
+- eq?
+- apply
+- show
+- throw
+- exit!
+- read
+- read-many
+# Eval
+- base-eval
+- eval
+# Refs
+- ref
+- read-ref
+- write-ref
+# Pattern matching
+- match-pat
+# Sequences
+- head
+- cons
+- add-left
+- add-right
+- <>
+- list
+- list-to-vec
+- vec-to-list
+- zip
+- map
+- foldl
+- foldr
+- drop
+- sort-by
+- tail
+- take
+- nth
+- seq
+# Dicts
+- dict
+- lookup
+- insert
+- delete
+- member?
+- map-keys
+- map-values
+# Strings
+- string-append
+- string-length
+- string-replace
+# Types
+- type
+- atom?
+- keyword?
+- boolean?
+- string?
+- number?
+- integral?
+- vector?
+- list?
+- dict?
+# Modules
+- file-module!
+- import
+# Environment
+- get-current-env
+- pure-env
+- set-current-env
+- set-env!
+# JSON
+- to-json
+# UUIDs
+- uuid!
+- uuid?
+# Crypto
+- default-ecc-curve
+- verify-signature
+- public-key?
+- gen-key-pair!
+- gen-signature!
+# I/O
+- put-str!
+- get-line!
+- load!
+- read-file!
+- read-line-handle!
+- now!
+- system!
+- wait-for-process!
+- write-handle!
+# Repl
+- subscribe-to!
+# Documentation
+- doc
+- doc!
+- apropos!
+
+# All modules apart from prelude/test
+modules:
+- prelude/basic
+- prelude/patterns
+- prelude/strings
+- prelude/io
+- prelude/bool
+- prelude/exception
+- prelude/list
+- prelude/dict
+- prelude/set
+- prelude/ref
+- prelude/lens
+- prelude/chain
+- prelude/state-machine
+- prelude/validation
+- prelude/util
diff --git a/src/Radicle/Internal/Core.hs b/src/Radicle/Internal/Core.hs
index 9834964..53a6421 100644
--- a/src/Radicle/Internal/Core.hs
+++ b/src/Radicle/Internal/Core.hs
@@ -14,7 +14,6 @@ import Control.Monad.State
import Data.Aeson (FromJSON(..), ToJSON(..))
import qualified Data.Aeson as A
import Data.Copointed (Copointed(..))
-import Data.Data (Data)
import qualified Data.HashMap.Strict as HashMap
import qualified Data.IntMap as IntMap
import Data.List.NonEmpty (NonEmpty)
@@ -24,6 +23,7 @@ import Data.Scientific (Scientific)
import Data.Semigroup ((<>))
import Data.Sequence (Seq(..))
import qualified Data.Sequence as Seq
+import qualified Data.Set as Set
import Generics.Eot
import qualified GHC.Exts as GhcExts
import qualified GHC.IO.Handle as Handle
@@ -34,6 +34,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 Radicle.Internal.Identifier (Ident(..))
import qualified Radicle.Internal.Identifier as Identifier
import qualified Radicle.Internal.Number as Num
import Radicle.Internal.Orphans ()
@@ -70,6 +71,8 @@ data LangErrorData r =
-- args
| WrongNumberOfArgs Text Int Int
| NonHashableKey
+ | MissingModuleDeclaration
+ | InvalidModuleDeclaration Text Value
| OtherError Text
| ParseError (Par.ParseError Char Void)
-- | Raised if @(throw ident value)@ is evaluated. Arguments are
@@ -133,6 +136,8 @@ errorDataToValue e = case e of
, ("actual", Number $ fromIntegral actual)]
)
NonHashableKey -> makeVal ( "non-hashable-key", [])
+ MissingModuleDeclaration -> makeVal ( "missing-module-declaration", [])
+ InvalidModuleDeclaration t v -> makeVal ( "invalid-module-declaration", [("info", String t), ("declaration", v)])
OtherError i -> makeVal
( "other-error"
, [("info", String i)]
@@ -407,23 +412,6 @@ maybeJson = \case
isStr (String s) = pure s
isStr _ = Nothing
--- | An identifier in the language.
---
--- Not all `Text`s are valid identifiers, so use 'Ident' at your own risk.
--- `mkIdent` is the safe version.
-newtype Ident = Ident { fromIdent :: Text }
- deriving (Eq, Show, Read, Ord, Generic, Data, Serialise)
-
-pattern Identifier :: Text -> Ident
-pattern Identifier t <- Ident t
-
--- | Convert a text to an identifier.
---
--- Unsafe! Only use this if you know the string at compile-time and know it's a
--- valid identifier. Otherwise, use 'mkIdent'.
-unsafeToIdent :: Text -> Ident
-unsafeToIdent = Ident
-
-- | The environment, which keeps all known bindings.
newtype Env s = Env { fromEnv :: Map Ident (Doc.Docd s) }
deriving (Eq, Ord, Semigroup, Monoid, Show, Read, Generic, Functor, Foldable, Traversable, Serialise)
@@ -478,28 +466,32 @@ setBindings value = do
, bindingsProcHandles = bindingsProcHandles bnds
, bindingsNextProcHandle = bindingsNextProcHandle bnds
}
+
+bindingsFromRadicle :: Value -> Either Text (Bindings (PrimFns m))
+bindingsFromRadicle x = case x of
+ Dict d -> do
+ env' <- kwLookup "env" d ?? "Expecting 'env' key"
+ refs' <- kwLookup "refs" d ?? "Expecting 'refs' key"
+ refs <- makeRefs refs'
+ env <- envFromRad env'
+ pure $ emptyBindings
+ { bindingsEnv = env
+ , bindingsRefs = refs
+ , bindingsNextRef = length refs
+ }
+ _ -> throwError "Expecting dict"
where
- bindingsFromRadicle x = case x of
- Dict d -> do
- env' <- kwLookup "env" d ?? "Expecting 'env' key"
- refs' <- kwLookup "refs" d ?? "Expecting 'refs' key"
- refs <- makeRefs refs'
- env <- envFromRad env'
- pure $ emptyBindings
- { bindingsEnv = env
- , bindingsRefs = refs
- , bindingsNextRef = length refs
- }
- _ -> throwError "Expecting dict"
makeRefs refs = case refs of
List ls -> pure (IntMap.fromList $ zip [0..] ls)
_ -> throwError $ "Expecting dict"
- envFromRad env = case env of
- Dict d -> fmap (Env . Map.fromList)
- $ forM (Map.toList d) $ \(k, v) -> case k of
- Atom i -> (i, ) <$> fromRad v
- k' -> Left $ "Expecting atom keys. Got: " <> show k'
- _ -> Left "Expecting dict"
+
+envFromRad :: Value -> Either Text (Env Value)
+envFromRad env = case env of
+ Dict d -> fmap (Env . Map.fromList)
+ $ forM (Map.toList d) $ \(k, v) -> case k of
+ Atom i -> (i, ) <$> fromRad v
+ k' -> Left $ "Expecting atom keys. Got: " <> show k'
+ _ -> Left "Expecting dict"
-- | Serializes the environment and references into a Radicle value.
--
@@ -513,9 +505,12 @@ bindingsToRadicle x =
, (Keyword $ Ident "refs", refs)
]
where
- env = Dict . Map.mapKeys Atom . Map.map toRad . fromEnv $ bindingsEnv x
+ env = envToRadicle (bindingsEnv x)
refs = List $ IntMap.elems (bindingsRefs x)
+envToRadicle :: Env Value -> Value
+envToRadicle = Dict . Map.mapKeys Atom . Map.map toRad . fromEnv
+
-- | The environment in which expressions are evaluated.
newtype LangT r m a = LangT
{ fromLangT :: ExceptT (LangError Value) (StateT r m) a }
@@ -629,6 +624,7 @@ specialForms = Map.fromList $ first Ident <$>
_ -> throwErrorHere $ SpecialForm "fn" "First argument must be a vector of argument atoms"
_ -> throwErrorHere $ SpecialForm "fn" "Need an argument vector and a body"
)
+ , ( "module", createModule )
, ("quote", \case
[v] -> pure v
xs -> throwErrorHere $ WrongNumberOfArgs "quote" 1 (length xs))
@@ -720,7 +716,43 @@ specialForms = Map.fromList $ first Ident <$>
pure nil
_ -> throwErrorHere $ OtherError "def-rec can only be used to define functions"
--- * From/ToRadicle
+data ModuleMeta = ModuleMeta
+ { name :: Ident
+ , exports :: [Ident]
+ , doc :: Text
+ }
+
+-- | Given a list of forms, the first of which should be module declaration,
+-- runs the rest of the forms in a new scope, and then defs the module value
+-- according to the name in the declaration.
+createModule :: forall m. Monad m => [Value] -> Lang m Value
+createModule = \case
+ (m : forms) -> do
+ m' <- baseEval m >>= meta
+ e <- withEnv identity $ traverse_ eval forms *> gets bindingsEnv
+ let env = envToRadicle $ Env $ Map.restrictKeys (fromEnv e) (Set.fromList (exports m'))
+ let modu = Dict $ Map.fromList
+ [ (Keyword (Ident "module"), Atom (name m'))
+ , (Keyword (Ident "env"), env)
+ , (Keyword (Ident "exports"), Vec (Seq.fromList (Atom <$> exports m')))
+ ]
+ defineAtom (name m') (Just (doc m')) modu
+ pure modu
+ _ -> throwErrorHere MissingModuleDeclaration
+ where
+ meta v@(Dict d) = do
+ name <- modLookup v "module" d "missing `:module` key"
+ doc <- modLookup v "doc" d "missing `:doc` key"
+ exports <- modLookup v "exports" d "Missing `:exports` key"
+ case (name, doc, exports) of
+ (Atom n, String ds, Vec es) -> do
+ is <- traverse isAtom es ?? toLangError (InvalidModuleDeclaration "`:exports` must be a vector of atoms" v)
+ pure $ ModuleMeta n (toList is) ds
+ _ -> throwErrorHere (InvalidModuleDeclaration "`:module` must be an atom, `:doc` must be a string and `:exports` must be a vector" v)
+ meta v = throwErrorHere (InvalidModuleDeclaration "must be dict" v)
+ modLookup v k d e = kwLookup k d ?? toLangError (InvalidModuleDeclaration e v)
+
+-- * From/ ToRadicle
type CPA t = (Ann.Annotation t, Copointed t)
diff --git a/src/Radicle/Internal/Effects.hs b/src/Radicle/Internal/Effects.hs
index 31d7b62..e3cd6eb 100644
--- a/src/Radicle/Internal/Effects.hs
+++ b/src/Radicle/Internal/Effects.hs
@@ -22,6 +22,7 @@ import System.Console.Haskeline
import Radicle.Internal.Core
import Radicle.Internal.Crypto
import Radicle.Internal.Effects.Capabilities
+import Radicle.Internal.Identifier (Ident(..), unsafeToIdent)
import Radicle.Internal.Interpret
import Radicle.Internal.Pretty
import Radicle.Internal.PrimFns
@@ -280,4 +281,15 @@ replPrimFns = fromList $ allDocs $
pure . String . toS . Time.formatTime Time.defaultTimeLocale (Time.iso8601DateFormat (Just "%H:%M:%SZ")) $ t
xs -> throwErrorHere $ WrongNumberOfArgs "exit!" 0 (length xs)
)
+ , ( "file-module!"
+ , "Given a file whose code starts with module metadata, creates the module.\
+ \ That is, the file is evaluated as if the code was wrapped in `(module ...)`."
+ , oneArg "file-module!" $ \case
+ String filename -> do
+ t_ <- readFileS filename
+ t <- hoistEither . first (toLangError . OtherError) $ t_
+ vs <- readValues ("file-module!: " <> filename) t
+ createModule vs
+ v -> throwErrorHere $ TypeError "file-module!" 0 TString v
+ )
]
diff --git a/src/Radicle/Internal/Identifier.hs b/src/Radicle/Internal/Identifier.hs
index aaca2d5..e59d121 100644
--- a/src/Radicle/Internal/Identifier.hs
+++ b/src/Radicle/Internal/Identifier.hs
@@ -1,9 +1,13 @@
+{-# LANGUAGE PatternSynonyms #-}
+
module Radicle.Internal.Identifier where
import qualified Prelude
import Protolude
+import Codec.Serialise (Serialise)
import Data.Char (isAlphaNum, isLetter, isUpper, toLower)
+import Data.Data (Data)
import qualified Data.Map as Map
import qualified Data.Text as T
@@ -67,3 +71,20 @@ kebabCons = T.intercalate "-" . fmap (toS . lowerFirst) . go .keywordWord
-- Makes a string safe to use in a keyword.
keywordWord = concat . fmap keywordChar
+
+-- | An identifier in the language.
+--
+-- Not all `Text`s are valid identifiers, so use 'Ident' at your own risk.
+-- `mkIdent` is the safe version.
+newtype Ident = Ident { fromIdent :: Text }
+ deriving (Eq, Show, Read, Ord, Generic, Data, Serialise, Semigroup)
+
+pattern Identifier :: Text -> Ident
+pattern Identifier t <- Ident t
+
+-- | Convert a text to an identifier.
+--
+-- Unsafe! Only use this if you know the string at compile-time and know it's a
+-- valid identifier. Otherwise, use 'mkIdent'.
+unsafeToIdent :: Text -> Ident
+unsafeToIdent = Ident
diff --git a/src/Radicle/Internal/Pretty.hs b/src/Radicle/Internal/Pretty.hs
index bfc18c0..159740f 100644
--- a/src/Radicle/Internal/Pretty.hs
+++ b/src/Radicle/Internal/Pretty.hs
@@ -19,6 +19,7 @@ import Text.Megaparsec.Pos (sourcePosPretty)
import qualified Radicle.Internal.Annotation as Ann
import Radicle.Internal.Core
import Radicle.Internal.Effects.Capabilities (Stdout(..))
+import Radicle.Internal.Identifier (Ident(..))
import Radicle.Internal.Type
class PrettyV a where
@@ -101,6 +102,11 @@ instance PrettyV r => PrettyV (LangErrorData r) where
<+> "Expected:" <+> pretty x
<+> "Got:" <+> pretty y
NonHashableKey -> "Non-hashable key in dict."
+ MissingModuleDeclaration -> "Modules must start with a metadata declaration"
+ InvalidModuleDeclaration t decl -> vsep
+ [ "Invalid module declaration:" <+> pretty t <> ":"
+ , indent 2 $ prettyV decl
+ ]
OtherError t -> "Error:" <+> pretty t
SpecialForm f t -> "Error using special form" <+> pretty f <> ":" <+> pretty t <> "."
ParseError t -> "Parser error:" <+> pretty (parseErrorPretty t)
diff --git a/src/Radicle/Internal/PrimFns.hs b/src/Radicle/Internal/PrimFns.hs
index 3a65fe8..4be6d17 100644
--- a/src/Radicle/Internal/PrimFns.hs
+++ b/src/Radicle/Internal/PrimFns.hs
@@ -8,6 +8,7 @@ import Data.List (zip3)
import qualified Data.Map as Map
import Data.Sequence (Seq(..))
import qualified Data.Sequence as Seq
+import qualified Data.Set as Set
import qualified Data.Text as T
import GHC.Exts (IsList(..), sortWith)
import Text.Megaparsec (parseErrorPretty)
@@ -16,6 +17,7 @@ import qualified Radicle.Internal.Annotation as Ann
import Radicle.Internal.Core
import Radicle.Internal.Crypto
import qualified Radicle.Internal.Doc as Doc
+import Radicle.Internal.Identifier (Ident(..), unsafeToIdent)
import qualified Radicle.Internal.Number as Num
import Radicle.Internal.Parse
import Radicle.Internal.Pretty
@@ -89,7 +91,7 @@ purePrimFns = fromList $ allDocs $
, ( "read-many"
, "Parses a string into a vector of radicle values. Does not evaluate the values."
, oneArg "read-many" $ \case
- String s -> readValues s
+ String s -> Vec . Seq.fromList <$> readValues "read-many" s
v -> throwErrorHere $ TypeError "read-many" 0 TString v
)
, ("get-current-env"
@@ -165,7 +167,7 @@ purePrimFns = fromList $ allDocs $
Vec Seq.Empty -> throwErrorHere $ OtherError "tail: empty vector"
v -> throwErrorHere $ TypeError "tail" 0 TSequence v)
- -- Lists and Vecs
+ -- Sequences: Lists and Vecs
, ( "drop"
, "Returns all but the first `n` items of a sequence, unless the sequence is empty,\
\ in which case an exception is thrown."
@@ -229,6 +231,18 @@ purePrimFns = fromList $ allDocs $
(Vec _, v) -> throwErrorHere $ TypeError "zip" 1 TList v
(v, _) -> throwErrorHere $ TypeError "zip" 0 TSequence v
)
+ , ( "vec-to-list"
+ , "Transforms vectors to lists."
+ , oneArg "vec-to-list" $ \case
+ Vec xs -> pure (List (Protolude.toList xs))
+ v -> throwErrorHere $ TypeError "vec-to-list" 0 TVec v
+ )
+ , ( "list-to-vec"
+ , "Transforms lists into vectors."
+ , oneArg "list-to-vec" $ \case
+ List xs -> pure (Vec (Seq.fromList xs))
+ v -> throwErrorHere $ TypeError "list-to-vec" 0 TList v
+ )
-- Dicts
, ("lookup"
@@ -531,6 +545,24 @@ purePrimFns = fromList $ allDocs $
(x@(Atom _), v) -> pure $ toRad (Just (Dict (Map.singleton x v)))
(pat, v) -> callFn pat [v]
)
+ , ( "import"
+ , "Import a module, making all the definitions of that module available\
+ \ in the current scope. The first argument must be a module to import.\
+ \ Two optional arguments affect how and which symbols are imported.\
+ \ `(import m :as 'foo)` will import all the symbols of `m` with the prefix\
+ \ `foo/`. `(import m '[f g])` will only import `f` and `g` from `m`.\
+ \ `(import m '[f g] :as 'foo')` will import `f` and `g` from `m` as `foo/f`\
+ \ and `foo/g`. To import definitions with no qualification at all, use\
+ \ `(import m :unqualified)`."
+ , \case
+ [v] -> import' v Nothing FullyQualified
+ [v, Vec these] -> import' v (Just these) FullyQualified
+ [v, Keyword (Ident "as"), Atom q] -> import' v Nothing (Qualified q)
+ [v, Vec these, Keyword (Ident "as"), Atom q] -> import' v (Just these) (Qualified q)
+ [v, Keyword (Ident "unqualified")] -> import' v Nothing Unqualified
+ [v, Vec these, Keyword (Ident "unqualified")] -> import' v (Just these) Unqualified
+ _ -> throwErrorHere $ OtherError "import: expects a module, an optional list of symbols to import, and an optional qualifier."
+ )
]
where
isTy t = "Checks if the argument is a " <> t <> "."
@@ -561,6 +593,31 @@ purePrimFns = fromList $ allDocs $
(v, _) -> throwErrorHere $ TypeError name 0 TNumber v
)
+ import' (Dict d) v_ qual = do
+ v <- kwLookup "env" d ?? toLangError (OtherError "Modules should have an `:env` key")
+ n <- kwLookup "module" d ?? toLangError (OtherError "Modules should have an `:module` key")
+ case n of
+ Atom name -> do
+ e <- hoistEither $ first (toLangError . OtherError) $ envFromRad v
+ let allMod = fromEnv e
+ toImport <- case v_ of
+ Just vs -> do
+ is <- Protolude.toList <$> traverse isAtom vs ?? toLangError (OtherError "import: must be given a vector of symbols to import")
+ pure $ Map.restrictKeys allMod (Set.fromList is)
+ Nothing -> pure allMod
+ let qualifier = case qual of
+ Qualified q -> ((q <> Ident "/") <>)
+ Unqualified -> identity
+ FullyQualified -> ((name <> Ident "/") <>)
+ let qualified = Env $ Map.mapKeysMonotonic qualifier toImport
+ s <- get
+ put $ s { bindingsEnv = qualified <> bindingsEnv s }
+ pure ok
+ _ -> throwErrorHere (OtherError "The `:module` key of a module should be an atom.")
+ import' _ _ _ = throwErrorHere (OtherError "Modules must be dicts")
+
+data ImportQual = Unqualified | FullyQualified | Qualified Ident
+
-- * Helpers
-- Many primFns have a single argument.
@@ -587,11 +644,12 @@ readValue s = do
readValues
:: (MonadError (LangError Value) m)
=> Text
- -> m Value
-readValues s = do
- let p = parseValues "[read-many-primop]" s
+ -> Text
+ -> m [Value]
+readValues name s = do
+ let p = parseValues ("[" <> name <> "-primop]") s
case p of
- Right v -> pure . Vec $ Seq.fromList v
+ Right vs -> pure vs
Left e -> throwErrorHere $ ThrownError (Ident "parse-error") (String . toS $ parseErrorPretty e)
allDocs :: [(Text, Text, a)] -> [(Ident, Maybe Text, a)]
diff --git a/src/Radicle/Internal/Storage.hs b/src/Radicle/Internal/Storage.hs
index 3d3a4e3..221e2a4 100644
--- a/src/Radicle/Internal/Storage.hs
+++ b/src/Radicle/Internal/Storage.hs
@@ -17,6 +17,7 @@ import Protolude hiding (TypeError)
import GHC.Exts (fromList)
import Radicle.Internal.Core
+import Radicle.Internal.Identifier
import qualified Radicle.Internal.Number as Num
import qualified Radicle.Internal.PrimFns as PrimFns
import Radicle.Internal.Type
diff --git a/test/spec/Radicle/Tests.hs b/test/spec/Radicle/Tests.hs
index 28f9be7..bb4ccde 100644
--- a/test/spec/Radicle/Tests.hs
+++ b/test/spec/Radicle/Tests.hs
@@ -504,6 +504,28 @@ test_eval =
Left (LangError stack (UnknownIdentifier (Identifier "notdefined"))) ->
assertEqual "correct line numbers" [3,1,2,2] (stackTraceLines stack)
r -> assertFailure $ "Didn't fail the way we expected: " ++ show r
+
+ , testCase "Modules work" $ do
+ let prog = [s|(module
+ {:module 'foo :doc "" :exports '[z]}
+ (def x 1)
+ (def y 2)
+ (def z (+ x y)))
+ (import foo)
+ (import foo :as 'bar)
+ (import foo ['z] :as 'baz)
+ (import foo :unqualified)
+ (list foo/z bar/z baz/z z)|]
+ prog `succeedsWith` List (replicate 4 (Number 3))
+ , testCase "Modules don't leak non-exported defs" $ do
+ let prog = [s|(module
+ {:module 'foo :doc "" :exports '[z]}
+ (def x 1)
+ (def y 2)
+ (def z (+ x y)))
+ (import foo :unqualified)
+ x|]
+ prog `failsWith` UnknownIdentifier [ident|x|]
]
where
failsWith src err = noStack (runPureCode src) @?= Left err