Phase 3: $(...), aliases, a start-up file, PROMPT, Done lines, >&2

- $(...) runs in a subshell. A word that is only an unquoted $(...) is
  one word per line. X=$(cmd) sets $? to its status.
- alias, unalias, and command NAME. An alias is one pipe.
- ~/.config/bjosh/rc runs before the first prompt.
- PROMPT, expanded as in double quotes, with \w \W \u \h \$ \e \n.
- "Done" lines are written above the input while the prompt waits.
- >&2, for programs and value commands.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Linus Björnstam 2026-12-01 09:50:15 +01:00
parent f54ceb35af
commit f8c4ad64bc
13 changed files with 680 additions and 128 deletions

View file

@ -2,8 +2,8 @@
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;; (bjosh builtins): the shell commands of phase 1. They change the shell,
;; so they run in its process and must be alone in a pipe.
;; (bjosh builtins): the shell commands. They change the shell, so they run
;; in its process and must be alone in a pipe.
;;
;; - Each takes the shell and its arguments, and returns an exit status.
;; - Each writes to the current output and error ports.
@ -13,6 +13,7 @@
(import (std prelude))
(import (std run))
(import (bjoterm line))
(import (bjosh syntax))
(import (bjosh shell))
(import (bjosh commands))
(import (bjosh values))
@ -186,6 +187,48 @@
((Ok code) (max code job-status))
((Err e) (shell-error (run-error-message e)) 1))))))))
;; The names of the aliases, sorted.
(: (-> Shell (Vec string)))
(defun (alias-names sh)
(list->vec (list-sort (->list (map-keys (record-ref sh aliases))))))
;; alias NAME='TEXT', as `alias` writes it, which the shell reads back.
(: (-> string string string))
(defun (alias-line name text)
(str "alias " name "='" (string-replace text "'" "'\\''") "'"))
;; alias: lists the aliases. alias NAME: shows one. alias NAME=TEXT: sets
;; one; TEXT must be one pipe.
(: (-> Shell (Vec string) int))
(defun (alias sh args)
(if (vec-empty? args)
(begin
(for-each (fun (name)
(match (alias-ref sh name)
((Some text) (println (alias-line name text)))
(None unit)))
(alias-names sh))
0)
(each-status args
(fun (arg)
(match (string-split-once arg "=")
((Some (Tuple name text))
(match (parse-pipe text)
((Ok _) (alias-set! sh name text) 0)
((Err message) (shell-error (str "alias: " name ": " message)) 1)))
(None
(match (alias-ref sh arg)
((Some text) (println (alias-line arg text)) 0)
(None (shell-error (str "alias: " arg ": not found")) 1))))))))
(: (-> Shell (Vec string) int))
(defun (unalias sh args)
(each-status args
(fun (name)
(match (alias-ref sh name)
((Some _) (alias-remove! sh name) 0)
(None (shell-error (str "unalias: " name ": not found")) 1)))))
;; The path of a program on PATH, or a name with a / that exists.
(: (-> string (Option string)))
(defun (find-program name)
@ -205,6 +248,10 @@
(each-status args
(fun (name)
(cond
((some? (alias-ref sh name))
(println (str name " is an alias for "
(match (alias-ref sh name) ((Some t) t) (None ""))))
0)
((builtin? name) (println (str name " is a shell command")) 0)
(else
(match (value-command name (fun (n) (some? (find-program n))))
@ -229,6 +276,7 @@
(defun (help sh args)
(println "Shell commands:")
(for-each (fun (b) (println (builtin-help-line b))) (builtins))
(println (str " " (string-pad-right "command NAME [ARG]..." 28) "run the program NAME, not an alias or a value command"))
(println "")
(println "Value commands, by long and short name. A long name that is a program runs the program.")
(for-each (fun (c) (println (value-help-line c))) (value-commands))
@ -262,7 +310,9 @@
(Builtin (name "kill") (usage "kill [-SIGNAL] %JOB|PID...") (help "send a signal; TERM by default") (run kill))
(Builtin (name "type") (usage "type NAME...") (help "what a name runs") (run type-of))
(Builtin (name "help") (usage "help") (help "this list") (run help))
(Builtin (name "history") (usage "history") (help "the lines written before") (run history))])
(Builtin (name "history") (usage "history") (help "the lines written before") (run history))
(Builtin (name "alias") (usage "alias [NAME[=TEXT]]...") (help "list, show or set aliases; TEXT is one pipe") (run alias))
(Builtin (name "unalias") (usage "unalias NAME...") (help "remove aliases") (run unalias))])
;; ===========================================================================
;; Shell commands as values, in a pipe

View file

@ -20,8 +20,14 @@
;; - Value commands next to each other in a pipe are one (std run) filter
;; (see (bjosh pipeline)). A pipe with programs is one form, as above. A
;; pipe of only value commands runs in the shell, and Ctrl-C stops it.
;; - A name is, in this order: a shell command, the short name of a value
;; command, a program on PATH, the long name of a value command.
;; - A name is, in this order: an alias, a shell command, the short name of
;; a value command, a program on PATH, the long name of a value command.
;; `command NAME` is always the program.
;; - $(...) runs in a subshell (see `capture`). Its output is captured:
;; programs write through a filter at the end of their form, and value
;; commands write lines.
;; - >&2 copies stdout to stderr. It cannot be combined with another
;; redirection of stdout or stderr.
(import (std prelude))
(import (std run))
@ -33,22 +39,31 @@
(import (bjosh pipeline))
(import (std os))
(export run-text)
(export run-text expand-quoted)
;; A command after expansion.
;; A command after expansion. `program?`: it was `command NAME`, so NAME is
;; a program, and `command` is not in `argv`.
(type (: Expanded (Record (: assigns (Vec (Tuple string string)))
(: argv (Vec string))
(: redirects (Vec (Tuple RedirectKind string))))))
(: redirects (Vec (Tuple RedirectKind string)))
(: program? bool))))
(: (-> Shell Expander))
(defun (expander sh)
(shell-expander sh (fun (items) (capture sh items))))
(: (-> Shell Command (Result string Expanded)))
(defun (expand-command sh c)
(def ex (shell-expander sh))
(set-subst-status! sh None)
(def ex (expander sh))
(def assigns (vec-map (fun (a) (Tuple (fst a) (expand-text ex (snd a)))) (record-ref c assigns)))
(def argv (expand-words ex (record-ref c words)))
(def words (expand-words ex (record-ref c words)))
(def program? (and (> (vec-length words) 1) (= (vec-ref words 0) "command")))
(def argv (if program? (vec-drop words 1) words))
(let go ((i 0) (redirects []))
(def rs (record-ref c redirects))
(if (= i (vec-length rs))
(Ok (Expanded (assigns assigns) (argv argv) (redirects redirects)))
(Ok (Expanded (assigns assigns) (argv argv) (redirects redirects) (program? program?)))
(let ((r (vec-ref rs i)))
(match (record-ref r kind)
(ErrToOut (go (+ i 1) (vec-add redirects (Tuple ErrToOut ""))))
@ -103,7 +118,13 @@
(vec-drop rs (+ i 1)))
(Err "2>&1 before > or >> is not supported yet: write >FILE 2>&1")
(go (+ i 1) (FErrToOut form))))
(OutToErr (Err ">&2 is not supported yet")))))))
;; Alone: with another redirection of stdout or stderr, the
;; order of the two would matter.
(OutToErr
(if (any? (fun (r) (match (fst r) ((or IntoFile AppendFile ErrIntoFile ErrAppendFile ErrToOut) #t) (_ #f)))
rs)
(Err ">&2 with >, >>, 2>, 2>> or 2>&1 is not supported")
(go (+ i 1) (FOutToErr form)))))))))
;; The status for a form that did not start, after its message.
(: (-> RunError int))
@ -120,7 +141,7 @@
(let go ((i 0))
(def rs (record-ref e redirects))
(if (= i (vec-length rs))
0
(match (record-ref sh subst-status) ((Some status) status) (None 0))
(let* ((path (snd (vec-ref rs i)))
(problem (match (fst (vec-ref rs i))
((or IntoFile ErrIntoFile)
@ -134,7 +155,63 @@
((Some message) (shell-error message) 1))))))
(: (-> Shell (Vec Command) bool int))
(defun (run-pipeline sh pipe background?)
(defun (run-pipeline sh written background?)
(match (with-aliases sh written)
((Err message) (shell-error message) 2)
((Ok pipe) (run-commands sh pipe background?))))
;; `pipe` with each command whose first word is an alias replaced by the
;; pipe of the alias.
(: (-> Shell (Vec Command) (Result string (Vec Command))))
(defun (with-aliases sh pipe)
(let go ((i 0) (out []))
(if (= i (vec-length pipe))
(Ok out)
(match (alias-commands sh (vec-ref pipe i) [])
((Ok cs) (go (+ i 1) (vec-append out cs)))
((Err message) (Err message))))))
;; The name of `c`'s alias: its first word, when that is plain text, an
;; alias, and not in `seen`.
(: (-> Shell Command (Vec string) (Option (Tuple string string))))
(defun (alias-of sh c seen)
(def words (record-ref c words))
(match (if (vec-empty? words) [] (vec-ref words 0))
([(Lit name #f)]
(if (vec-contains? seen name)
None
(match (alias-ref sh name)
((Some text) (Some (Tuple name text)))
(None None))))
(_ None)))
;; `c`, or the pipe of its alias. The words and redirections after the name
;; go to the last command of the alias, its assignments to the first. The
;; first command is expanded again, without the names in `seen`.
(: (-> Shell Command (Vec string) (Result string (Vec Command))))
(defun (alias-commands sh c seen)
(match (alias-of sh c seen)
(None (Ok [c]))
((Some (Tuple name text))
(match (parse-pipe text)
((Err message) (Err (str "alias " name ": " message)))
((Ok cmds)
(def n (vec-length cmds))
(def first (vec-ref cmds 0))
(def with-assigns
(vec-set cmds 0 (record-set first (assigns (vec-append (record-ref c assigns) (record-ref first assigns))))))
(def last (vec-ref with-assigns (- n 1)))
(def spliced
(vec-set with-assigns (- n 1)
(record-set last
(words (vec-append (record-ref last words) (vec-drop (record-ref c words) 1)))
(redirects (vec-append (record-ref last redirects) (record-ref c redirects))))))
(match (alias-commands sh (vec-ref spliced 0) (vec-add seen name))
((Ok head) (Ok (vec-append head (vec-drop spliced 1))))
((Err message) (Err message))))))))
(: (-> Shell (Vec Command) bool int))
(defun (run-commands sh pipe background?)
(let go ((i 0) (expanded []))
(if (< i (vec-length pipe))
(match (expand-command sh (vec-ref pipe i))
@ -150,6 +227,7 @@
;; jobs and history are values in a pipe.
(def builtin-in-pipe
(find (fun (e) (and (not (vec-empty? (record-ref e argv)))
(not (record-ref e program?))
(builtin? (vec-ref (record-ref e argv) 0))
(not (some? (shell-value-command sh (vec-ref (record-ref e argv) 0))))))
expanded))
@ -159,7 +237,7 @@
((any? (fun (e) (vec-empty? (record-ref e argv))) expanded)
(shell-error "a command in a pipe has no words")
2)
((and (= (vec-length expanded) 1) (builtin? name))
((and (= (vec-length expanded) 1) (not (record-ref first program?)) (builtin? name))
(cond
(background? (shell-error (str name ": a shell command cannot run in the background")) 2)
((not (and (vec-empty? (record-ref first assigns)) (vec-empty? (record-ref first redirects))))
@ -170,7 +248,7 @@
(match builtin-in-pipe
((Some e) (shell-error (str (vec-ref (record-ref e argv) 0) ": a shell command cannot be in a pipe")) 2)
(None
(if (any? (fun (e) (some? (stage-command-of sh (record-ref e argv)))) expanded)
(if (any? (fun (e) (some? (stage-command-of sh e))) expanded)
(run-mixed sh expanded text background?)
(run-form sh expanded text background?)))))))
@ -185,15 +263,20 @@
((Some c) (Some c))
(None (value-command-of name))))
;; Value commands next to each other, with the file the first reads (<)
;; and the file the last writes (> or >>, with append?).
(: (-> Shell (Vec string) (Option ValueCommand)))
(defun (stage-command-of sh argv)
(if (echo-flags? argv) None (stage-command sh (vec-ref argv 0))))
;; The value command of a stage: none for `command NAME`, and for echo
;; with flags.
(: (-> Shell Expanded (Option ValueCommand)))
(defun (stage-command-of sh e)
(def argv (record-ref e argv))
(if (or (record-ref e program?) (echo-flags? argv)) None (stage-command sh (vec-ref argv 0))))
;; Value commands next to each other, with the file the first reads (<),
;; and where the last writes: the file of > or >> (with append?), or
;; stderr for >&2.
(type (: Segment (Record (: stages (Vec ValueStage))
(: from (Option string))
(: into (Option (Tuple string bool))))))
(: into (Option (Tuple string bool)))
(: to-errors? bool))))
;; A part of a pipe: a program, or a segment.
(type (: Part (Union (: PartProgram Form)
@ -217,18 +300,21 @@
(Err (str name ": < on a value command after another one"))))
(IntoFile (go (+ i 1) (record-set seg (into (Some (Tuple path #f))))))
(AppendFile (go (+ i 1) (record-set seg (into (Some (Tuple path #t))))))
(_ (Err (str name ": 2>, 2>&1 and >&2 of value commands are not supported yet"))))))))
(OutToErr (go (+ i 1) (record-set seg (to-errors? #t))))
(_ (Err (str name ": 2> and 2>&1 of value commands are not supported yet"))))))))
;; Whether the segment's output goes to a file: nothing can follow it.
;; Whether the segment's output goes to a file or to stderr: nothing can
;; follow it.
(: (-> Segment bool))
(defun (closed? seg)
(match (record-ref seg into)
((Some _) #t)
(None #f)))
(or (record-ref seg to-errors?)
(match (record-ref seg into)
((Some _) #t)
(None #f))))
(: (-> (Vec ValueStage) Segment))
(defun (segment-of stages)
(Segment (stages stages) (from None) (into None)))
(Segment (stages stages) (from None) (into None) (to-errors? #f)))
(: (-> Shell (Vec Expanded) (Result string (Vec Part))))
(defun (parts-of sh expanded)
@ -242,7 +328,7 @@
(let* ((e (vec-ref expanded i))
(argv (record-ref e argv))
(name (vec-ref argv 0)))
(match (stage-command-of sh argv)
(match (stage-command-of sh e)
((Some c)
(def stage (ValueStage (command c) (args (vec-drop argv 1))))
(def seg (match current
@ -251,7 +337,7 @@
(_ (segment-of [stage]))))
(cond
((match current ((Some old) (closed? old)) (None #f))
(Err (str name ": the value command before it writes to a file, so nothing can be piped into it")))
(Err (str name ": the value command before it writes to a file or to stderr, so nothing can be piped into it")))
((not (vec-empty? (record-ref e assigns)))
(Err (str name ": assignments of value commands are not supported")))
(else
@ -263,19 +349,21 @@
((Ok f) (parts-from sh expanded (+ i 1) (vec-add (close parts) (PartProgram f)) None))
((Err message) (Err message))))))))
;; The form of a part. `show?`: values at the end of the pipe are shown as a
;; table, not written as lines.
(: (-> Part bool Form))
(defun (part-form part last?)
(defun (part-form part show-last?)
(match part
((PartProgram f) f)
((PartValues seg)
(def stages (record-ref seg stages))
(def show? (and last? (not (closed? seg))))
(def show? (and show-last? (not (closed? seg))))
(def base (FFilter (bjoroutine (in out) (run-segment stages in out show?))))
(def read (match (record-ref seg from) ((Some path) (FFrom path base)) (None base)))
(match (record-ref seg into)
((Some (Tuple path #t)) (FAppend path read))
((Some (Tuple path #f)) (FInto path read))
(None read)))))
(None (if (record-ref seg to-errors?) (FOutToErr read) read))))))
(: (-> Shell (Vec Expanded) string bool int))
(defun (run-mixed sh expanded text background?)
@ -286,7 +374,8 @@
([(PartValues seg)] (run-values sh seg background?))
(_
(def n (vec-length parts))
(def forms (vec-map (fun (i) (part-form (vec-ref parts i) (= i (- n 1))))
(def show? (not (record-ref sh capture?)))
(def forms (vec-map (fun (i) (part-form (vec-ref parts i) (and show? (= i (- n 1)))))
(->vec (range 0 n))))
(start-form sh (FPipe (->list forms)) text background?))))))
@ -300,7 +389,8 @@
;; Value commands only, in the shell.
;; - Input: the file of <, else nothing.
;; - Output: the file of > or >>, as lines, else shown on stdout.
;; - Output: the file of > or >>, or stderr for >&2, as lines. Else shown
;; on stdout, or written as lines in $(...).
;; - Status 130 after Ctrl-C, 1 when a command raises or a file does not
;; open.
(: (-> Shell Segment bool int))
@ -330,7 +420,13 @@
(close-output-port out)
status)
((Err e) (shell-error (fs-error-message e)) 1)))
(None (run-values-into seg in (parameter-ref current-output-port) #t))))
(None
(if (record-ref seg to-errors?)
(let ((err (parameter-ref current-error-port)))
(def status (run-values-into seg in err #f))
(flush-port err)
status)
(run-values-into seg in (parameter-ref current-output-port) (not (record-ref sh capture?)))))))
(close-input-port in)
status)
@ -355,9 +451,37 @@
(start-form sh (if (= (vec-length forms) 1) (vec-ref forms 0) (FPipe (->list forms)))
text background?))))
;; Whether `form` writes to stdout, and not to a file or stderr.
(: (-> Form bool))
(defun (writes-output? form)
(match form
((or (FInto _ _) (FAppend _ _) (FOutToErr _)) #f)
((FPipe forms)
(let go ((fs forms))
(match fs
(Nil #t)
((Cons f Nil) (writes-output? f))
((Cons _ more) (go more)))))
((FFrom _ inner) (writes-output? inner))
((FErrInto _ inner) (writes-output? inner))
((FErrAppend _ inner) (writes-output? inner))
((FErrToOut inner) (writes-output? inner))
(_ #t)))
;; Copies its input to its output, at the end of a form in $(...).
(: Filter)
(defbjo (copy-out in out)
(write-string out (read-all in))
unit)
;; Starts `form` as a job, or with `run/interactive` without job control.
;; In $(...), the output goes through `copy-out` to the current output
;; port.
(: (-> Shell Form string bool int))
(defun (start-form sh form text background?)
(defun (start-form sh written text background?)
(def form (if (and (record-ref sh capture?) (writes-output? written))
(FPipe (list written (FFilter copy-out)))
written))
;; The program writes to the same terminal or file.
(flush-port (parameter-ref current-output-port))
(match (record-ref sh jc)
@ -403,9 +527,42 @@
(shell-error message)
(set-status! sh 2)
2)
((Ok items)
(for-each (fun (it)
(when (= (record-ref sh exit-code) None)
(set-status! sh (run-and-or sh (record-ref it and-or) (record-ref it background?)))))
items)
(record-ref sh status))))
((Ok items) (run-items sh items))))
(: (-> Shell (Vec Item) int))
(defun (run-items sh items)
(for-each (fun (it)
(when (= (record-ref sh exit-code) None)
(set-status! sh (run-and-or sh (record-ref it and-or) (record-ref it background?)))))
items)
(record-ref sh status))
;; Runs the items of $(...) in a subshell, and returns what they write to
;; stdout.
;; - The subshell has a copy of the variables; `exit` ends only it.
;; - Its status goes in `subst-status`.
;; - The directory is set back after it, with PWD and OLDPWD. Variables
;; it exports stay in the environment.
(: (-> Shell (Vec Item) string))
(defun (capture sh items)
(def sub (subshell sh))
(def dir (current-directory))
(def pwd (getenv "PWD"))
(def oldpwd (getenv "OLDPWD"))
(def out (open-output-string))
(parameterize ((current-output-port out))
(set-subst-status! sh (Some (run-items sub items)))
(flush-port out))
(unless (= (current-directory) dir)
(ignore (try (set-current-directory! dir) #:catch (System.Exception)))
(set-environment-variable! "PWD" (match pwd ((Some p) p) (None "")))
(set-environment-variable! "OLDPWD" (match oldpwd ((Some p) p) (None ""))))
(get-output-string out))
;; `text` expanded as in double quotes: $NAME, $(...) and \ escapes. For
;; the prompt. Returns the message of a parse error.
(: (-> Shell string (Result string string)))
(defun (expand-quoted sh text)
(match (parse-text text)
((Ok parts) (Ok (expand-text (expander sh) parts)))
((Err message) (Err message))))

View file

@ -14,6 +14,10 @@
;; command's arguments are strings.
;; - Values of variables are never split, and never globs. This is not
;; POSIX: `rm $FILES` with spaces in FILES removes one file.
;; - $(...) is the output of its lines, without the line breaks at its
;; end. A word that is only an unquoted $(...) is one word per line, and
;; empty lines are no words. Elsewhere it is text in the word, and never
;; a glob.
;; - A word of only unquoted parameters that are all empty is no word, as
;; in POSIX. "$X" is always one word.
@ -28,8 +32,18 @@
;; - `lookup`: the value of a name: a shell variable, then the
;; environment, and the special names ?, $ and 0 to 9.
;; - `home-of`: the home of a user, or of the current user for "".
;; - `substitute`: runs the items of $(...), and returns their output.
(type (: Expander (Record (: lookup (-> string (Option string)))
(: home-of (-> string (Option string))))))
(: home-of (-> string (Option string)))
(: substitute (-> (Vec Item) string)))))
;; `text` without the line breaks at its end.
(: (-> string string))
(defun (trim-line-breaks text)
(cond
((string-ends-with? text "\r\n") (trim-line-breaks (string-drop-right text 2)))
((string-ends-with? text "\n") (trim-line-breaks (string-drop-right text 1)))
(else text)))
;; The home of `user` from /etc/passwd, or $HOME for "".
(: (-> string (Option string)))
@ -76,6 +90,9 @@
(def v (match ((record-ref ex lookup) n) ((Some v) v) (None "")))
(go (+ i 1) (str text v) (str pattern (glob-escape v)) glob?
(and params-only? (not quoted?))))
((Subst items _)
(def v (trim-line-breaks ((record-ref ex substitute) items)))
(go (+ i 1) (str text v) (str pattern (glob-escape v)) glob? #f))
((Tilde user)
(def home (match ((record-ref ex home-of) user)
((Some h) h)
@ -86,6 +103,14 @@
;; matches of a glob.
(: (-> Expander (Vec WordPart) (Vec string)))
(defun (expand-word ex w)
(match w
([(Subst items #f)]
(vec-filter (fun (line) (not (string-empty? line)))
(string-split (string-replace ((record-ref ex substitute) items) "\r\n" "\n") "\n")))
(_ (expand-pieces ex w))))
(: (-> Expander (Vec WordPart) (Vec string)))
(defun (expand-pieces ex w)
(def p (pieces ex w))
(def text (record-ref p text))
(cond

View file

@ -10,6 +10,10 @@
;; bjosh FILE ARG... runs the lines of FILE, with $0 FILE, $1 ARG...
;;
;; The exit code is the status of the last line, or the code of `exit`.
;;
;; - An interactive shell first runs the lines of the start-up file,
;; $XDG_CONFIG_HOME/bjosh/rc or ~/.config/bjosh/rc.
;; - The prompt is $PROMPT when it is set; see `custom-prompt`.
(import (std prelude))
(import (std run))
@ -32,16 +36,84 @@
(None (path-combine (match (getenv "HOME") ((Some h) h) (None ".")) ".local/state"))))
(path-combine state "bjosh/history"))
;; The directory, with ~ for home, and $ green after status 0, else red.
(: (-> Shell string))
(defun (prompt sh)
;; The start-up file.
(: (-> string))
(defun (rc-path)
(def config (match (getenv "XDG_CONFIG_HOME")
((Some c) c)
(None (path-combine (match (getenv "HOME") ((Some h) h) (None ".")) ".config"))))
(path-combine config "bjosh/rc"))
;; The directory, with ~ for home.
(: (-> string))
(defun (shown-directory)
(def dir (current-directory))
(def home (match (getenv "HOME") ((Some h) h) (None "")))
(def shown (if (and (not (string-empty? home)) (string-starts-with? dir home))
(str "~" (string-drop dir (string-length home)))
dir))
(def color (if (= (record-ref sh status) 0) "32" "31"))
(str "\u{1B}[1;34m" shown "\u{1B}[0m \u{1B}[" color "m$\u{1B}[0m "))
(if (and (not (string-empty? home)) (string-starts-with? dir home))
(str "~" (string-drop dir (string-length home)))
dir))
;; The prompt: `custom-prompt` of $PROMPT, else the directory, and $ green
;; after status 0, else red.
(: (-> Shell string))
(defun (prompt sh)
(match (var-ref sh "PROMPT")
((Some template) (custom-prompt sh template))
(None
(def color (if (= (record-ref sh status) 0) "32" "31"))
(str "\u{1B}[1;34m" (shown-directory) "\u{1B}[0m \u{1B}[" color "m$\u{1B}[0m "))))
(import/extern
(user-name (: System.Environment.UserName string #:get #:no-raise))
(machine-name (: System.Environment.MachineName string #:get #:no-raise)))
;; The text of a prompt escape: \w, \W, \u, \h, \$, \e, \n or \\.
(: (-> char (Option string)))
(defun (prompt-escape c)
(cond
((= c #\w) (Some (shown-directory)))
((= c #\W) (Some (let ((dir (shown-directory)))
(if (= dir "/") dir
(match (path-filename dir) ((Some n) n) (None dir))))))
((= c #\u) (Some user-name))
((= c #\h) (Some machine-name))
((= c #\$) (Some (if (= user-name "root") "#" "$")))
((= c #\e) (Some "\u{1B}"))
((= c #\n) (Some "\n"))
((= c #\\) (Some "\\"))
(else None)))
;; $PROMPT, with its escapes replaced (see `prompt-escape`), and the text
;; between them expanded as in double quotes. A part that does not parse
;; is shown as written.
(: (-> Shell string string))
(defun (custom-prompt sh template)
(def chars (string->vec template))
(def out (stringbuilder-empty))
(def pending (stringbuilder-empty))
(defun (flush!)
(def text (stringbuilder->string pending))
(stringbuilder-clear! pending)
(unless (string-empty? text)
(stringbuilder-add-string! out (match (expand-quoted sh text)
((Ok expanded) expanded)
((Err _) text)))))
(let go ((i 0))
(when (< i (vec-length chars))
(def c (vec-ref chars i))
(def escape (if (and (= c #\\) (< (+ i 1) (vec-length chars)))
(prompt-escape (vec-ref chars (+ i 1)))
None))
(match escape
((Some text)
(flush!)
(stringbuilder-add-string! out text)
(go (+ i 2)))
(None
(stringbuilder-add! pending c)
(go (+ i 1))))))
(flush!)
(stringbuilder->string out))
(: (-> Terminal int))
(defun (interactive term)
@ -54,9 +126,14 @@
(ignore (line-history-load! ed path))
(ignore (try (directory-create (path-combine path "..")) #:catch (System.Exception)))
(def sh (make-shell jc (Some ed) ["bjosh"]))
(def rc (rc-path))
(when (file-exists? rc)
(match (file-read-text rc)
((Ok text) (ignore (run-text sh text)))
((Err e) (shell-error (str rc ": " (fs-error-message e))))))
(let go ()
(report-jobs sh)
(match (line-read ed term (prompt sh))
(match (line-read ed term (prompt sh) #:notices (Some (fun () (job-changes sh))))
((LineText text)
(ignore (line-history-save ed path))
(ignore (run-text sh text)))

View file

@ -11,20 +11,24 @@
;; - Job numbers are 1 and up, the lowest free one first. The current job
;; (%+) is the last one stopped or put in the background, and the
;; previous one (%-) the one before it.
;; - Changes of state are found before each prompt, as bash does: see
;; `report-jobs`.
;; - Changes of state are found before each prompt, as bash does, and
;; while the prompt waits: see `job-changes`.
;; - A subshell, for $(...), is a copy with its own variables and status,
;; no jobs and no job control.
(import (std prelude))
(import (std run))
(import (bjoterm line))
(import (bjosh syntax))
(import (bjosh expand))
(export
Shell JobEntry make-shell shell-error
Shell JobEntry make-shell subshell shell-error
alias-ref alias-set! alias-remove! set-subst-status!
set-status! request-exit! warn-stopped! var-export!
var-ref var-set! var-unset! shell-expander job-set-state!
job-add! job-remove! job-find job-current job-mark-recent! jobs-stopped?
job-text-line job-mark job-state-text foreground! report-jobs state->status error-text)
job-text-line job-mark job-state-text foreground! report-jobs job-changes state->status error-text)
(type (: JobEntry (Record (: number int)
(: job Job)
@ -38,6 +42,11 @@
;; - `args`: $0 and the arguments of a script, $1 to $9.
;; - `exit-code`: set by `exit`; the loop ends with it.
;; - `warned-stopped?`: `exit` has warned once about stopped jobs.
;; - `aliases`: the text of each alias, by name.
;; - `capture?`: a subshell of $(...). Its output is captured, so value
;; commands write lines, not tables.
;; - `subst-status`: the status of the last $(...) of the command being
;; expanded. A command of only assignments returns it, as in POSIX.
(type (: Shell (Record (: vars (Map string string) #:mutable)
(: status int #:mutable)
(: jc (Option JobControl))
@ -46,7 +55,10 @@
(: jobs (Vec JobEntry) #:mutable)
(: recent (Vec int) #:mutable)
(: exit-code (Option int) #:mutable)
(: warned-stopped? bool #:mutable))))
(: warned-stopped? bool #:mutable)
(: aliases (Map string string) #:mutable)
(: capture? bool)
(: subst-status (Option int) #:mutable))))
(import/extern
(pid (: System.Environment.ProcessId int #:get #:no-raise)))
@ -54,7 +66,32 @@
(: (-> (Option JobControl) (Option LineEditor) (Vec string) Shell))
(defun (make-shell jc editor args)
(Shell (vars (map-empty)) (status 0) (jc jc) (editor editor) (args args)
(jobs []) (recent []) (exit-code None) (warned-stopped? #f)))
(jobs []) (recent []) (exit-code None) (warned-stopped? #f)
(aliases (map-empty)) (capture? #f) (subst-status None)))
;; A copy of `sh` for $(...): the same variables, aliases and status, which
;; it can change for itself, and no jobs or job control.
(: (-> Shell Shell))
(defun (subshell sh)
(Shell (vars (record-ref sh vars)) (status (record-ref sh status)) (jc None)
(editor (record-ref sh editor)) (args (record-ref sh args))
(jobs []) (recent []) (exit-code None) (warned-stopped? #f)
(aliases (record-ref sh aliases)) (capture? #t) (subst-status None)))
(: (-> Shell (Option int) void))
(defun (set-subst-status! sh status) (record-set! sh (subst-status status)))
(: (-> Shell string (Option string)))
(defun (alias-ref sh name)
(map-try-ref (record-ref sh aliases) name))
(: (-> Shell string string void))
(defun (alias-set! sh name text)
(record-set! sh (aliases (map-set (record-ref sh aliases) name text))))
(: (-> Shell string void))
(defun (alias-remove! sh name)
(record-set! sh (aliases (map-remove (record-ref sh aliases) name))))
;; Writes "bjosh: " and `message` to standard error.
(: (-> string void))
@ -120,9 +157,10 @@
(record-set! sh (vars (map-remove (record-ref sh vars) name)))
(set-environment-variable! name ""))
(: (-> Shell Expander))
(defun (shell-expander sh)
(Expander (lookup (fun (name) (var-ref sh name))) (home-of default-home-of)))
(: (-> Shell (-> (Vec Item) string) Expander))
(defun (shell-expander sh substitute)
(Expander (lookup (fun (name) (var-ref sh name))) (home-of default-home-of)
(substitute substitute)))
;; ===========================================================================
;; Jobs
@ -271,18 +309,23 @@
((FilterFailed x) (.-Message x))
(_ (run-error-message e))))
;; Writes a line for each job whose state changed since it was last seen,
;; and takes the jobs that are done out of the table.
(: (-> Shell void))
(defun (report-jobs sh)
(for-each (fun (e)
;; A line for each job whose state changed since it was last seen. Takes the
;; jobs that are done out of the table.
(: (-> Shell (Vec string)))
(defun (job-changes sh)
(vec-fold (fun (e lines)
(def now (job-state (record-ref e job)))
(unless (= now (record-ref e state))
(record-set! e (state now))
(match now
(JobRunning unit)
(_ (println (job-text-line sh e)))))
(def changed? (not (= now (record-ref e state))))
(record-set! e (state now))
(def line (if (and changed? (not (= now JobRunning))) [(job-text-line sh e)] []))
(match now
((JobDone _) (job-remove! sh (record-ref e number)))
(_ unit)))
(_ unit))
(vec-append lines line))
[]
(record-ref sh jobs)))
;; Writes the lines of `job-changes`.
(: (-> Shell void))
(defun (report-jobs sh)
(for-each println (job-changes sh)))

View file

@ -6,16 +6,16 @@
;; tree. Nothing is expanded here; see (bjosh expand).
;;
;; - Words: plain text, 'single' and "double" quotes, \ escapes, $NAME,
;; ${NAME}, $?, $$, $0 to $9, and ~ or ~user at the start.
;; ${NAME}, $?, $$, $0 to $9, $(...), and ~ or ~user at the start.
;; - Operators: |, &&, ||, ;, & and line breaks.
;; - Redirections: <, >, >>, 2>, 2>>, 2>&1 and >&2, with an optional
;; descriptor 0, 1 or 2 before them.
;; - NAME=value words before a command are assignments.
;; - # starts a comment at the start of a word. \ and a line break is
;; nothing.
;; - Not supported: if, for, while, case, functions, ( ), { }, !, $(...),
;; `...`, here-documents, and ${NAME} with an operator. Each raises a
;; parse error that names it.
;; - Not supported: if, for, while, case, functions, ( ), { }, !, `...`,
;; here-documents, and ${NAME} with an operator. Each raises a parse
;; error that names it.
;; - No field splitting: $NAME is one word, whatever its value holds.
(import (std prelude))
@ -23,42 +23,46 @@
(export
WordPart RedirectKind Redirect Command Connector AndOr Item
parse-line parse-line/message line->string word->string)
parse-line parse-line/message parse-text parse-pipe line->string word->string)
;; ===========================================================================
;; The tree
;; ===========================================================================
;; One part of a word, before expansion.
;; - `Lit`: text, and whether it was quoted. Only text that was not quoted
;; can be a glob.
;; - `Param`: $NAME, and whether it was in double quotes.
;; - `Tilde`: ~ or ~user at the start of a word: the user, or "".
(type (: WordPart (Union (: Lit string bool) (: Param string bool) (: Tilde string))))
;; - `FromFile`: <, 0<. `IntoFile`: >, 1>. `AppendFile`: >>, 1>>.
;; - `ErrIntoFile`: 2>. `ErrAppendFile`: 2>>.
;; - `ErrToOut`: 2>&1. `OutToErr`: >&2, 1>&2. These have no target.
(type (: RedirectKind (Union FromFile IntoFile AppendFile ErrIntoFile ErrAppendFile
ErrToOut OutToErr)))
(type (: Redirect (Record (: kind RedirectKind) (: target (Vec WordPart)))))
;; One command: its assignments, words and redirections, each in the order
;; written. A command can have only assignments, or only redirections.
(type (: Command (Record (: assigns (Vec (Tuple string (Vec WordPart))))
(: words (Vec (Vec WordPart)))
(: redirects (Vec Redirect)))))
(type (: Connector (Union AndThen OrElse)))
;; A pipe, then more pipes joined by && or ||. A pipe is one or more
;; commands.
(type (: AndOr (Record (: first (Vec Command))
(: rest (Vec (Tuple Connector (Vec Command)))))))
(type-rec
;; One part of a word, before expansion.
;; - `Lit`: text, and whether it was quoted. Only text that was not
;; quoted can be a glob.
;; - `Param`: $NAME, and whether it was in double quotes.
;; - `Subst`: $(...), its items, and whether it was in double quotes.
;; - `Tilde`: ~ or ~user at the start of a word: the user, or "".
(: WordPart (Union (: Lit string bool) (: Param string bool) (: Subst (Vec Item) bool)
(: Tilde string)))
;; An and-or list, and whether it ended with &.
(type (: Item (Record (: and-or AndOr) (: background? bool))))
(: Redirect (Record (: kind RedirectKind) (: target (Vec WordPart))))
;; One command: its assignments, words and redirections, each in the
;; order written. A command can have only assignments, or only
;; redirections.
(: Command (Record (: assigns (Vec (Tuple string (Vec WordPart))))
(: words (Vec (Vec WordPart)))
(: redirects (Vec Redirect))))
;; A pipe, then more pipes joined by && or ||. A pipe is one or more
;; commands.
(: AndOr (Record (: first (Vec Command))
(: rest (Vec (Tuple Connector (Vec Command))))))
;; An and-or list, and whether it ended with &.
(: Item (Record (: and-or AndOr) (: background? bool))))
;; One part of a command, while it is parsed.
(type (: Element (Union (: EWord (Vec WordPart)) (: ERedirect Redirect))))
@ -125,7 +129,19 @@
(many-satisfy name-char?)
(fun (c rest) (str (char->string c) rest))))
;; $NAME, ${NAME}, $?, $$, $0 to $9. A $ before anything else is a $.
;; The grammar is recursive: $(...) holds items, which hold words. A def is
;; in scope only below itself, so `param` reaches the items of $(...)
;; through `items-ref`, which `tie!` fills in at `line`.
(: tie! (-> (ParserRef %a) (Parser %a) (Parser %a)))
(defun (tie! ref p)
(pforward-set! ref p)
p)
(: items-ref (ParserRef (Vec Item)))
(def items-ref (pforward))
;; $NAME, ${NAME}, $?, $$, $0 to $9, $(...). A $ before anything else is
;; a $.
(: (-> bool (Parser WordPart)))
(defun (param quoted?)
(pright (pchar #\$)
@ -135,7 +151,9 @@
(plabel (pchar #\}) "'}' (only ${NAME} is supported)")))
(pmap (fun (n) (Param n quoted?)) name)
(pmap (fun (c) (Param (char->string c) quoted?)) (any-of "?$0123456789"))
(pright (pchar #\() (pfail "$(...) is not supported yet"))
(pmap (fun (items) (Subst items quoted?)) (pright (pchar #\()
(pright ws-nl (pleft (pforwarded items-ref)
(plabel (pchar #\)) "')' to close $(")))))
(preturn (Lit "$" quoted?))))))
(: backquote (Parser (List WordPart)))
@ -147,20 +165,24 @@
(between (pchar #\') (plabel (pchar #\') "a closing '")
(many-satisfy (fun (c) (not (= c #\')))))))
;; In double quotes, \ escapes only $ ` " \ and a line break.
;; A part of the text in double quotes. \ escapes only $ ` " \ and a line
;; break.
(: quoted-part (Parser WordPart))
(def quoted-part
(choice (list
(param #t)
(pright (pchar #\\)
(por (pmap (fun (c) (if (= c #\newline) (Lit "" #t) (Lit (char->string c) #t)))
(any-of "$`\"\\\n"))
(preturn (Lit "\\" #t))))
(pright (pchar #\`) (pfail "`...` is not supported"))
(pmap (fun (s) (Lit s #t))
(many-satisfy1 (fun (c) (not (string-contains? "\"\\$`" (char->string c))))
"text")))))
(: double-quoted (Parser (List WordPart)))
(def double-quoted
(between (pchar #\") (plabel (pchar #\") "a closing \"")
(many (choice (list
(param #t)
(pright (pchar #\\)
(por (pmap (fun (c) (if (= c #\newline) (Lit "" #t) (Lit (char->string c) #t)))
(any-of "$`\"\\\n"))
(preturn (Lit "\\" #t))))
(pright (pchar #\`) (pfail "`...` is not supported"))
(pmap (fun (s) (Lit s #t))
(many-satisfy1 (fun (c) (not (string-contains? "\"\\$`" (char->string c))))
"text")))))))
(between (pchar #\") (plabel (pchar #\") "a closing \"") (many quoted-part)))
;; Outside quotes, \ makes the next character plain, and \ and a line break
;; is nothing.
@ -237,8 +259,7 @@
(def element
(choice (list (pmap (fun (r) (ERedirect r)) redirect)
(pmap (fun (w) (EWord w)) word)
(pright (pchar #\() (pfail "subshells ( ) are not supported"))
(pright (pchar #\)) (pfail "')' without '('")))))
(pright (pchar #\() (pfail "subshells ( ) are not supported")))))
;; Words that start shell syntax that is not supported, at the start of a
;; command.
@ -319,7 +340,13 @@
(: line (Parser (Vec Item)))
(def line
(pright ws-nl (pleft (pmap list->vec (many item)) eof)))
(pright ws-nl (pleft (tie! items-ref (pmap list->vec (many item)))
(por eof (pright (pchar #\)) (pfail "')' without '('"))))))
;; Text as in double quotes, where " is text too. For the prompt.
(: text-parts (Parser (Vec WordPart)))
(def text-parts
(pleft (pmap list->vec (many (por quoted-part (pmap (fun (_) (Lit "\"" #t)) (pchar #\"))))) eof))
;; The items of `text`, which can have several lines. Empty for a line of
;; spaces and comments.
@ -332,6 +359,26 @@
(defun (parse-line/message text)
(run-parser/message line text))
;; The commands of `text` when it is one pipe: no ;, &&, || or &. For the
;; text of an alias. Returns the message of an error.
(: (-> string (Result string (Vec Command))))
(defun (parse-pipe text)
(match (parse-line/message text)
((Err message) (Err message))
((Ok [only])
(def a (record-ref only and-or))
(if (or (record-ref only background?) (not (vec-empty? (record-ref a rest))))
(Err "not one pipe: ;, &&, || and & are not allowed")
(Ok (record-ref a first))))
((Ok []) (Err "no command"))
((Ok _) (Err "not one pipe: ;, &&, || and & are not allowed"))))
;; The parts of `text`, read as in double quotes: $NAME, $(...) and \
;; escapes. " is text. Returns the message of an error.
(: (-> string (Result string (Vec WordPart))))
(defun (parse-text text)
(run-parser/message text-parts text))
;; ===========================================================================
;; Writing the tree back
;; ===========================================================================
@ -346,6 +393,8 @@
((Lit text #t) (str "\"" text "\""))
((Param n #f) (str "${" n "}"))
((Param n #t) (str "\"${" n "}\""))
((Subst items #f) (str "$(" (line->string items) ")"))
((Subst items #t) (str "\"$(" (line->string items) ")\""))
((Tilde user) (str "~" user))))
w)
""))