flesh/snippets/genbind.f
Ava Affine 6d2925984f Big project dir refactor
* split into multi member workspace in preparation for a no_std core
* env and posix stuff neatly crammed into a seperate shell project
* some pokes at interactive-devel.f
* updated ci
* removed 'l' shortcut for 'load' and update docs
* remove out of date readme content
* updated tests
* more sensible cond implementation and extra tests
* substr stdlib function with tests

Signed-off-by: Ava Affine <ava@sunnypup.io>
2024-07-12 13:45:09 -07:00

57 lines
2.4 KiB
Forth

#!/bin/flesh
;; Flesh: Flexible Shell
;; Copyright (C) 2021 Ava Affine
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <http://www.gnu.org/licenses/>.
;; GENBIND
(def gen-binding
"Takes two arguments: a symbol (use quote) and a string token
The symbol should coorespond to a binary on the path (else command will fail)
The string token is taken to be an argument to that command
A lambda is then made which accepts a list of additional arguments.
When called, the resulting function will construct and execute a call to load
The point is to be able to autogenerate bindings for shell commands.
Example: (eval ((gen-binding (q ls) '-l') ('-a')))
Or: (def gcommit 'use: (gcommit my-message)'
(lambda (arg) (eval ((gen-binding 'git' 'commit') ('-s' '-m' arg)))))
Or, a more advanced use:
(def -git-opts 'all subcommands for guix'
('add' 'push' 'stash'))
;; define global functions for each subcommand
(let ((gx-iter (pop -git-opts)))
(while (gt? (len gx-iter) 1)
(let ((subc (car gx-iter))
(rest (cdr gx-iter)))
(def (concat 'g-' subc)
'subcommand binding for git. takes a list of args'
(lambda (args) (eval ((gen-binding 'git' subc) args))))
(set (q gx-iter) (pop rest)))))"
(sym subcommand)
(let ((lam ((q lambda)
(cons (q args))
(cons let (((q func-call) (cons cons (q l) (cons q sym) subcommand))
((q arg-iter) (cons pop (q args))))
(cons while (cons gt? (cons len (q arg-iter)) 1)
(cons set (cons q (q func-call)) (cons cons (q func-call) (cons car (q arg-iter))))
(cons set (cons q (q arg-iter)) (cons pop (cons cdr (q arg-iter)))))
(cons echo "+ " (cons cdr (cons pop (q func-call))))
(cons eval (q func-call))))))
(eval lam)))