A peer-to-peer stack for code collaboration
(import prelude/basic :unqualified)
(import prelude/bool :unqualified)
(import prelude/dict :unqualified)
(import prelude/ref :unqualified)
(import prelude/validation :as 'validator)
(import prelude/patterns :unqualified)
(import prelude/util :unqualified)
(import prelude/lens :unqualified)
(def names (ref []))
(def name-unused?
(fn [name]
(not (elem? name (map first (read-ref names))))))
(def key-unused?
(fn [key]
(not (elem? key (map (fn [x] (nth 1 x)) (read-ref names))))))
(def validator/name
(validator/and
[(validator/type :string)
(validator/pred "Name has been taken" name-unused?)
]))
(def add-name
(fn [name pubkey]
(validator/name name)
((validator/pred "Key has been taken" key-unused?) pubkey)
(modify-ref names (fn [n] (cons [name pubkey] n)))))
(def list-names
(fn []
(read-ref names)))
;; Commands
(def commands
"The set of allowed chain commands."
(ref
{'add-name add-name
'list-names list-names}))
(def process-command
"Function that maps post-eval commands to existing functions"
(fn [expr]
(def command (first expr))
(def args (rest expr))
(def do-this (lookup command (read-ref commands)))
(apply do-this args)))
(def eval-fn-app
"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."
(fn [state f arg cb]
(def exec (base-eval (list f (list 'quote arg)) state))
(cb (first exec))
exec))
(def updatable-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`."
(fn [sub-eval]
(fn [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]
(eval-fn-app state 'process-command expr (fn [x] x)))))