diff --git a/AGENTS.md b/AGENTS.md index ac71988..eb8d179 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -18,10 +18,11 @@ non-trivial functions. No essays. here. - Modules: - `(bjosh syntax)`: the parser, with `(text parser-combinators)`. - - `(bjosh expand)`: variables, `~` and globs. - - `(bjosh shell)`: the state, variables and the job table. + - `(bjosh expand)`: variables, `~`, `$(...)` and globs. + - `(bjosh shell)`: the state, variables, aliases and the job table. - `(bjosh builtins)`: the shell commands. - - `(bjosh exec)`: lines to `(std run)` forms and jobs. + - `(bjosh exec)`: lines to `(std run)` forms and jobs, aliases, and + the subshell of `$(...)`. - `(bjosh values)`: values (`Json`), streams of them, text and tables. - `(bjosh commands)`: the value commands, and their table. - `(bjosh pipeline)`: value commands next to each other, as one unit. @@ -30,4 +31,5 @@ non-trivial functions. No essays. - `tests/syntax.bjo`, `tests/expand.bjo`, `tests/editor.bjo`: unit tests. - `tests/run.bjo`: lines through `bjosh -c`, a file, and stdin. - `tests/values.bjo`: the value commands through `bjosh -c`. - - `tests/interactive.bjo`: job control and the prompt under `script`. + - `tests/interactive.bjo`: job control, the prompt and the start-up + file under `script`. diff --git a/plan.org b/plan.org index 29b6231..d4a31c3 100644 --- a/plan.org +++ b/plan.org @@ -305,6 +305,65 @@ the text above:* once. - A prompt that the user sets. +*The design of phase 3 (2026-12-01), implemented the same day:* +- ~$(...)~: + - The parser reads the lines inside, up to the ~)~ that closes it, in + words and in double quotes. ~`...`~ stays an error. + - It runs in the shell, as a subshell: a copy of the variables, no job + control, and ~exit~ ends only it. Its output is what it writes: + programs (through a filter at the end of the form), shell commands, + and value commands, which write lines, not a table. Its stdin is the + shell's. + - The text loses its last line breaks. A word that is only an unquoted + ~$(...)~ is one word per line, with empty lines left out, so + ~kill $(pgrep x)~ works and a file name with spaces stays one word. + Elsewhere, and in double quotes, it is text in the word. + - ~$?~ after a line is the status of the line, not of the ~$(...)~. +- Aliases: + - ~alias NAME=TEXT~ sets one, ~alias~ lists them, ~alias NAME~ shows one, + ~unalias NAME~ removes one. + - TEXT must be one pipe: no ~;~, ~&&~, ~||~ or ~&~. It is checked when + the alias is set. + - The first word of a command is an alias when it is plain text, not + quoted. The pipe of the alias takes the place of the command: the + words and redirections after the name go to its last command, the + assignments to its first. An alias in the alias is expanded too, but + not the same name again. + - ~command NAME ARGS~ runs the program NAME: no alias, no value command. + ~type~ shows aliases. +- The start-up file: ~$XDG_CONFIG_HOME/bjosh/rc~, or ~~/.config/bjosh/rc~. + Its lines run before the first prompt of an interactive shell, not for + ~-c~ or a file. +- The prompt: the variable ~PROMPT~, when it is set. It is expanded as text + in double quotes (~$NAME~, ~$(...)~, ~$?~), with these escapes: + ~\w~ (the directory, with ~~~), ~\W~ (its last name), ~\u~ (the user), + ~\h~ (the host), ~\$~ (~#~ for root, else ~$~), ~\e~ (ESC, for + colors), ~\n~, ~\\~. Without ~PROMPT~ the prompt is as before. +- "Done" lines at once: bjoterm's ~line-read~ gets ~#:notices~, a function + it calls every 200 ms while it waits for a key. The lines it returns are + written above the input, which is drawn again below them. The shell + gives it the lines of the jobs that changed. +- ~>&2~: ~(std run)~ gets ~output-to-errors~. The command's stdout is a + pipe that the shell copies to stderr (or to the file of an + ~errors-into-file~ around it). Value commands take ~>&2~ too. + +*Where the code differs from the design, and what is left:* +- ~NAME=value command~ was done in phase 1. +- ~X=$(cmd)~ alone sets ~$?~ to the status of the ~$(...)~, as in POSIX, + so ~X=$(cmd) || ...~ works. Otherwise ~$?~ is the status of the line. +- In ~$(...)~, ~cd~ is undone after it, with ~PWD~ and ~OLDPWD~. A + variable that it exports stays in the environment. +- ~>&2~ cannot be combined with ~>~, ~>>~, ~2>~, ~2>>~ or ~2>&1~ on the + same command: the order of the two would matter. A stage with ~>&2~ + before another one in a pipe is an error, as one with ~>~ is. +- An alias of its own name (~alias ls='ls -d'~) runs the program. +- The completer does not complete aliases yet. +- Tests: ~tests/syntax.bjo~ (72), ~tests/expand.bjo~ (26), + ~tests/editor.bjo~ (24), ~tests/run.bjo~ (60), ~tests/values.bjo~ + (59), ~tests/interactive.bjo~ (16). bjoterm's + ~tests/line-terminal.bjo~ tests ~#:notices~; Bjolang's test 622 tests + ~output-to-errors~. + ** Phase 4: later - Commands that users write in Bjolang, compiled, and loaded at start-up diff --git a/src/builtins.bjo b/src/builtins.bjo index 4a2bdc4..52ebb03 100644 --- a/src/builtins.bjo +++ b/src/builtins.bjo @@ -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 diff --git a/src/exec.bjo b/src/exec.bjo index 97fe9dc..8c32ca0 100644 --- a/src/exec.bjo +++ b/src/exec.bjo @@ -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)))) diff --git a/src/expand.bjo b/src/expand.bjo index 35101aa..496c941 100644 --- a/src/expand.bjo +++ b/src/expand.bjo @@ -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 diff --git a/src/main.bjo b/src/main.bjo index 7982817..0594634 100644 --- a/src/main.bjo +++ b/src/main.bjo @@ -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))) diff --git a/src/shell.bjo b/src/shell.bjo index 02b108e..bc1fd36 100644 --- a/src/shell.bjo +++ b/src/shell.bjo @@ -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))) diff --git a/src/syntax.bjo b/src/syntax.bjo index 3d7b4b2..000babd 100644 --- a/src/syntax.bjo +++ b/src/syntax.bjo @@ -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) "")) diff --git a/tests/expand.bjo b/tests/expand.bjo index 9656252..005f7a2 100644 --- a/tests/expand.bjo +++ b/tests/expand.bjo @@ -33,7 +33,16 @@ ((= user "bob") (Some "/home/bob")) (else None))) -(def ex (Expander (lookup lookup) (home-of home-of))) +;; $(...): the words of its first command after the first, as lines, +;; without quotes, and two empty lines. +(: (-> (Vec Item) string)) +(defun (substitute items) + (def pipe (record-ref (record-ref (vec-ref items 0) and-or) first)) + (def words (vec-map (fun (w) (string-replace (word->string w) "\"" "")) + (record-ref (vec-ref pipe 0) words))) + (str (string-join (vec-drop words 1) "\n") "\n\n")) + +(def ex (Expander (lookup lookup) (home-of home-of) (substitute substitute))) ;; The words of the first command of `text`, joined by "|". (: (-> string string)) @@ -56,6 +65,14 @@ (expect "~user" (words "cd ~bob/x") "cd|/home/bob/x") (expect "a user that does not exist" (words "cd ~nobody") "cd|~nobody") + ;; $(...). `substitute` returns the words after `echo`, one per line. + (expect "a $(...) word is one word per line" (words "x $(echo a b)") "x|a|b") + (expect "its empty lines are no words" (words "x $(echo '' a)") "x|a") + (expect "nothing is no word" (words "x $(echo) y") "x|y") + (expect "in a word it is text, without the last line breaks" (words "x p$(echo a b)q") "x|pa\nbq") + (expect "in double quotes it is one word" (words "x \"$(echo a b)\"") "x|a\nb") + (expect "it is not a glob" (words "x $(echo '*')") "x|*") + ;; Globs, in a directory of our own. (def dir (path-combine (temp-dir) (str "bjosh-expand-" (int->string process-id)))) (ignore (directory-create dir)) diff --git a/tests/interactive.bjo b/tests/interactive.bjo index 37bbf93..2400aac 100644 --- a/tests/interactive.bjo +++ b/tests/interactive.bjo @@ -7,7 +7,8 @@ ;; bjo build && bjo test tests/interactive.bjo ;; ;; The test runs bjosh under `script`, and writes keys to it with pauses -;; between them. The history goes to a directory of the test. +;; between them. The history and the start-up file are in a directory of +;; the test. (import (std prelude)) (import (std simpletest)) @@ -38,6 +39,8 @@ ((not (file-exists? "src/main.exe")) (println "FAILURE: src/main.exe is missing: run bjo build first")) (else (def state (path-combine (temp-dir) (str "bjosh-interactive-" (int->string process-id)))) + (ignore (directory-create (path-combine state "bjosh"))) + (ignore (file-write-text (path-combine state "bjosh/rc") "alias fromrc='echo set in rc'\n")) (def keys (string-join ["sleep 2.5" "printf 'sleep 30\\r'" "sleep 1" "printf '\\032'" "sleep 0.5" "printf 'jobs\\r'" "sleep 0.5" @@ -56,9 +59,13 @@ "printf 'stty tostop; printf y | u; stty -tostop\\r'" "sleep 1" "printf 'li < /dev/tty\\r'" "sleep 1" "printf '\\003'" "sleep 0.5" "printf 'echo after $?\\r'" "sleep 0.5" + "printf 'fromrc\\r'" "sleep 0.5" + "printf 'sleep 0.5 &\\r'" "sleep 0.3" "printf 'ec'" "sleep 1.5" "printf 'ho typed\\r'" "sleep 0.5" + "printf 'cd /tmp\\r'" "sleep 0.3" + "printf \"PROMPT='<\\\\W \\$(echo s)>\\\\$ '\\r\"" "sleep 0.5" "printf 'exit\\r'" "sleep 1"] "; ")) - (def command (str "(" keys ") | XDG_STATE_HOME=" state " script -qec 'dotnet src/main.exe' /dev/null")) + (def command (str "(" keys ") | XDG_STATE_HOME=" state " XDG_CONFIG_HOME=" state " script -qec 'dotnet src/main.exe' /dev/null")) (def out (match (run/output '(sh "-c" ,command)) ((Ok (Tuple _ text)) (plain text)) ((Err e) (run-error-message e)))) @@ -76,6 +83,12 @@ (expect-true "and with tostop set" (string-contains? out "stty -tostop\ny\n")) (expect-true "Ctrl-C of a read of the terminal, and the next line runs" (string-contains? out "\nafter 130\n")) + (expect-true "the start-up file runs" (string-contains? out "fromrc\nset in rc\n")) + (expect-true "a job that ends is reported while the prompt waits" + (match (string-split-once out "Done sleep 0.5") + ((Some (Tuple _ after)) (string-contains? after "echo typed\ntyped\n")) + (None #f))) + (expect-true "PROMPT" (string-contains? out "$ ")) (expect-true "the history is saved" (match (file-read-text (path-combine state "bjosh/history")) ((Ok text) (string-contains? text "kill %1")) diff --git a/tests/run.bjo b/tests/run.bjo index 0a7ba78..14d3ddb 100644 --- a/tests/run.bjo +++ b/tests/run.bjo @@ -70,8 +70,40 @@ (expect ">FILE 2>&1" (c (str "ls /no/such/dir >" file " 2>&1; grep -c such " file)) "1") (expect "2>&1 before >" (c (str "ls 2>&1 >" file)) "err: bjosh: 2>&1 before > or >> is not supported yet: write >FILE 2>&1\ncode: 2") - (expect ">&2 is not supported yet" (c "printf x >&2") - "err: bjosh: >&2 is not supported yet\ncode: 2") + (expect ">&2" (c "printf x >&2; echo y") "y\nerr: x") + (expect ">&2 with 2>" (c "printf x >&2 2>f") + "err: bjosh: >&2 with >, >>, 2>, 2>> or 2>&1 is not supported\ncode: 2") + + ;; $(...). + (expect "$(...)" (c "echo a$(echo b)c") "abc") + (expect "a $(...) word is one word per line" (c "printf '[%s]' $(printf 'a b\\nc\\n\\n')") "[a b][c]") + (expect "in double quotes, one word" (c "printf '[%s]' \"$(printf 'a\\nb\\n')\"") "[a\nb]") + (expect "nested" (c "echo $(echo $(echo in))") "in") + (expect "value commands write lines" (c "echo $(printf 'b\\na\\n' | so)") "a b") + (expect "shell commands" (c "cd /tmp; echo $(pwd)") "/tmp") + (expect "cd in it is undone" (c "cd /tmp; echo $(cd /; pwd); pwd") "/\n/tmp") + (expect "variables in it are its own" (c "X=1; echo $(X=2; echo $X) $X") "2 1") + (expect "exit ends only it" (c "echo $(exit 3; echo no)x") "x") + (expect "an assignment's status is its $(...)'s" (c "X=$(exit 4) || echo $?") "4") + (expect "a redirection in it" (c (str "echo [$(echo hidden >" file ")]; cat " file)) "[]\nhidden") + (expect "its stderr is not captured" (c "echo [$(echo e >&2)]") "[]\nerr: e") + (expect "2>&1 in it is" (c "echo [$(ls /no/such/dir 2>&1 | grep -c such)]") "[1]") + + ;; Aliases and command. + (expect "an alias" (c "alias say='echo said'; say it") "said it") + (expect "an alias with a pipe" (c "alias up='tr a-z A-Z'; echo x | up") "X") + (expect "an alias in an alias" (c "alias a1='echo one'; alias a2='a1 two'; a2 three") "one two three") + (expect "an alias of its own name" (c "alias ls='ls -d'; ls /") "/") + (expect "a quoted name is no alias" (c "alias say='echo said'; 'say' x") "err: bjosh: say: command not found\ncode: 127") + (expect "alias lists, sorted and quoted" (c "alias b='x y'; alias a=\"echo \\\"it's\\\"\"; alias") + "alias a='echo \"it'\\''s\"'\nalias b='x y'") + (expect "and runs that alias" (c "alias a=\"echo \\\"it's\\\"\"; a") "it's") + (expect "an alias must be one pipe" (c "alias x='a; b'") + "err: bjosh: alias: x: not one pipe: ;, &&, || and & are not allowed\ncode: 1") + (expect "unalias" (c "alias x=ls; unalias x; type x") "err: bjosh: type: x: not found\ncode: 1") + (expect "type of an alias" (c "alias x='ls -l'; type x") "x is an alias for ls -l") + (expect "command runs the program" (c "alias echo='echo E'; command echo x") "x") + (expect "command skips the value command" (c "printf 'a\\na\\n' | command uniq | wc -l") "1") ;; Shell commands. (expect "cd and pwd" (c "cd /tmp; pwd") "/tmp") diff --git a/tests/syntax.bjo b/tests/syntax.bjo index 7c0cea7..9757beb 100644 --- a/tests/syntax.bjo +++ b/tests/syntax.bjo @@ -54,6 +54,17 @@ (expect "~ at the start" (parsed "cd ~/src ~bob") "cd ~/src ~bob ;") (expect "~ elsewhere is text" (parsed "echo a~b") "echo a~b ;") + ;; $(...). + (expect "$(...)" (parsed "echo $(ls -l)") "echo $(ls -l ;) ;") + (expect "$(...) in a word" (parsed "echo a$(b)c") "echo a$(b ;)c ;") + (expect "$(...) in double quotes" (parsed "echo \"x $(ls)\"") "echo \"x \"\"$(ls ;)\" ;") + (expect "a pipe and a list in $(...)" (parsed "echo $(a | b; c && d)") "echo $(a | b ; c && d ;) ;") + (expect "$(...) in $(...)" (parsed "echo $(echo $(ls))") "echo $(echo $(ls ;) ;) ;") + (expect "quotes in $(...)" (parsed "echo $(echo ')')") "echo $(echo \")\" ;) ;") + (expect "line breaks in $(...)" (parsed "echo $(\na\nb\n)") "echo $(a ; b ;) ;") + (expect "an empty $(...)" (parsed "echo $()") "echo $() ;") + (expect "$(...) in an assignment" (parsed "X=$(ls)") "X=$(ls ;) ;") + ;; Operators. (expect "a pipe" (parsed "ls | wc -l") "ls | wc -l ;") (expect "a pipe without spaces" (parsed "ls|wc") "ls | wc ;") @@ -98,7 +109,9 @@ (expect "for" (parsed "for x in a; do ls; done") "error: `for` is not supported") (expect "a quoted if is a word" (parsed "'if' x") "\"if\" x ;") (expect "( )" (parsed "(ls)") "error: subshells ( ) are not supported") - (expect "$(...)" (parsed "echo $(ls)") "error: $(...) is not supported yet") + (expect "an open $(" (parsed "echo $(ls") + "error: Expecting: ')' to close $( / Unexpected: end of input") + (expect "a ) without (" (parsed "echo )") "error: ')' without '('") (expect "`...`" (parsed "echo `ls`") "error: `...` is not supported") (expect "here-documents" (parsed "cat <, >>, 2>, 2>>, 2>&1 and >&2 are supported") (expect "a number before a space is a word" (parsed "echo 3 >x") "echo 3 >x ;") (expect "the column of an open quote" (error-column "echo 'abc") 10) + + ;; One pipe, for an alias. + (expect "one pipe" (match (parse-pipe "ls -l | wc") ((Ok cs) (vec-length cs)) ((Err _) 0)) 2) + (expect "a list is not one pipe" (parse-pipe "a; b") (Err "not one pipe: ;, &&, || and & are not allowed")) + (expect "&& is not one pipe" (parse-pipe "a && b") (Err "not one pipe: ;, &&, || and & are not allowed")) + (expect "& is not one pipe" (parse-pipe "a &") (Err "not one pipe: ;, &&, || and & are not allowed")) + (expect "nothing is no pipe" (parse-pipe " ") (Err "no command")) + + ;; Text as in double quotes, for the prompt. + (expect "text" (match (parse-text "a \"b\" $X $(c)") ((Ok ps) (word->string ps)) ((Err e) e)) + "\"a \"\"\"\"\"b\"\"\"\"\" \"\"${X}\"\" \"\"$(c ;)\"") 0) diff --git a/tests/values.bjo b/tests/values.bjo index 24f4b86..b25bd3e 100644 --- a/tests/values.bjo +++ b/tests/values.bjo @@ -107,9 +107,13 @@ (expect "< after another value command" (c "n | so < a.txt") "err: bjosh: so: < on a value command after another one\ncode: 2") (expect "a value command after >" (c "l > f | n") - "err: bjosh: n: the value command before it writes to a file, so nothing can be piped into it\ncode: 2") + "err: bjosh: n: the value command before it writes to a file or to stderr, so nothing can be piped into it\ncode: 2") (expect "2> of a value command" (c "l 2> e") - "err: bjosh: l: 2>, 2>&1 and >&2 of value commands are not supported yet\ncode: 2") + "err: bjosh: l: 2> and 2>&1 of value commands are not supported yet\ncode: 2") + (expect ">&2 of a value command" (c "l >&2 | n") + "err: bjosh: n: the value command before it writes to a file or to stderr, so nothing can be piped into it\ncode: 2") + (expect ">&2 at the end writes lines" (c "l | g name | hd 1 >&2") "err: a.txt") + (expect ">&2 after a program" (c "printf 'b\\na\\n' | so >&2; echo done") "done\nerr: a\nb") (expect "an assignment of a value command" (c "X=1 l") "err: bjosh: l: assignments of value commands are not supported\ncode: 2")