From 3518b7711d08cfd7ed44569ec5a69cbd209f78254765976acc53977208a4088c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Linus=20Bj=C3=B6rnstam?= Date: Tue, 1 Dec 2026 06:19:45 +0100 Subject: [PATCH] Phase 1: POSIX command lines, job control and the prompt - (bjosh syntax): a part of POSIX sh, parsed with (text parser-combinators). Syntax that is not supported raises an error that names it. - (bjosh expand): variables, ~ and globs. Values are not split. - (bjosh exec): pipes as (std run) jobs, && || ; &, redirections, and NAME=value through env. - (bjosh shell) and (bjosh builtins): the job table and cd, pwd, exit, export, unset, jobs, fg, bg, kill, type, help, history. - (bjosh editor): Enter waits for open quotes and trailing operators; completion of commands and files. - -c LINE, FILE, and stdin. A Native AOT build too. - Tests: the parser, expansion, the editor, lines through -c, and job control under script. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 + AGENTS.md | 29 ++++ manifest.bjodat | 2 + plan.org | 27 +++ src/builtins.bjo | 264 ++++++++++++++++++++++++++++ src/editor.bjo | 136 +++++++++++++++ src/exec.bjo | 215 +++++++++++++++++++++++ src/expand.bjo | 123 +++++++++++++ src/main.bjo | 86 ++++++++- src/shell.bjo | 272 +++++++++++++++++++++++++++++ src/syntax.bjo | 393 ++++++++++++++++++++++++++++++++++++++++++ tests/editor.bjo | 57 ++++++ tests/expand.bjo | 82 +++++++++ tests/interactive.bjo | 71 ++++++++ tests/run.bjo | 97 +++++++++++ tests/syntax.bjo | 110 ++++++++++++ 16 files changed, 1964 insertions(+), 3 deletions(-) create mode 100644 AGENTS.md create mode 100644 src/builtins.bjo create mode 100644 src/editor.bjo create mode 100644 src/exec.bjo create mode 100644 src/expand.bjo create mode 100644 src/shell.bjo create mode 100644 src/syntax.bjo create mode 100644 tests/editor.bjo create mode 100644 tests/expand.bjo create mode 100644 tests/interactive.bjo create mode 100644 tests/run.bjo create mode 100644 tests/syntax.bjo diff --git a/.gitignore b/.gitignore index ca84534..a4f04ee 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,6 @@ publish/ *.bjobuild *.runtimeconfig.json *.deps.json +/src/main +/tests/* +!/tests/*.bjo diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..64c8b45 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,29 @@ +# bjosh + +A shell in Bjolang. The design and the phases are in `plan.org`. + +## Comments + +Write clear, direct engineering comments, as in the Bjolang repo's +CLAUDE.md: "returns" and "raises", contracts and invariants, bullets for +non-trivial functions. No essays. + +## This package + +- `bjo build` builds the shell: `src/main.exe`, and the native + `src/main` (`(aot #t)`). +- `bjo test` runs the tests. `tests/run.bjo` and `tests/interactive.bjo` + run `src/main.exe`, so run `bjo build` first. +- It depends on bjoterm at `../bjoterm`. A change there needs `bjo build` + 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 builtins)`: the shell commands. + - `(bjosh exec)`: lines to `(std run)` forms and jobs. + - `(bjosh editor)`: when Enter runs a line, and the completer. +- Tests: + - `tests/syntax.bjo`, `tests/expand.bjo`, `tests/editor.bjo`: unit tests. + - `tests/run.bjo`: lines through `bjosh -c`, a file, and stdin. + - `tests/interactive.bjo`: job control and the prompt under `script`. diff --git a/manifest.bjodat b/manifest.bjodat index aaadceb..e8986a4 100644 --- a/manifest.bjodat +++ b/manifest.bjodat @@ -3,6 +3,8 @@ (version "0.1.0") (description "A shell: POSIX command lines, job control, and built-in commands in Bjolang that pass values. Linux.") (license "MPL-2.0") + ;; A native executable too, src/main: a shell must start fast. + (aot #t) (depends ;; The line editor and the terminal. On disk until it has a remote. diff --git a/plan.org b/plan.org index f97b661..3343c61 100644 --- a/plan.org +++ b/plan.org @@ -202,6 +202,33 @@ JSON is the format at the edge, not between built-ins. or ~vim~ stopped and brought back; Ctrl-C of a job. - Try a Native AOT build (~(aot #t)~), for start-up time. +*Implemented (2026-11-30). Where the code differs from the text above:* +- Modules: ~syntax~, ~expand~, ~shell~ (the state, variables and the job + table), ~builtins~, ~exec~ (lines to forms), ~editor~ (~input-done?~ and + the completer), ~main~. +- ~NAME=value command~ is done, not phase 3: the program runs through + ~env NAME=value~. +- Shell commands cannot have assignments or redirections yet, and cannot + be in a pipe or run with ~&~. Phase 2 makes them value commands. +- ~&~ runs one pipe, not a list with ~&&~ or ~||~, and needs job control. +- Without job control (~-c~, a file, stdin), ~run/interactive~ runs the + forms, so the status of a pipe is that of its last command. With job + control it is ~job-result~'s rule (decision 7). +- Job changes are found by ~job-state~ before each prompt, not by + ~job-next-change~. That needs no fiber. +- ~export X=~ removes ~X~: ~set-environment-variable!~ removes a variable + for the empty string. +- Ctrl-Z at the prompt rings the bell: bjoterm's ~make-line-editor~ got + ~#:suspend?~ for it. Without it, the shell stopped itself. +- Native AOT works: ~src/main~ starts in under 10 ms, against 110 ms with + ~dotnet~. +- Tests: ~tests/syntax.bjo~ (56), ~tests/expand.bjo~ (20), + ~tests/editor.bjo~ (24), ~tests/run.bjo~ (31, with ~-c~), and + ~tests/interactive.bjo~ (8, under ~script~). ~less~ stopped with Ctrl-Z + and brought back with ~fg~ works; it is not in the tests. +- Not done: the test of decision 4 (short names against ~PATH~). There + are no value commands yet. + ** Phase 2: values - First: the ~(std run)~ change of decision 10, in the Bjolang repo. diff --git a/src/builtins.bjo b/src/builtins.bjo new file mode 100644 index 0000000..99bf82d --- /dev/null +++ b/src/builtins.bjo @@ -0,0 +1,264 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; 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. +;; +;; - Each takes the shell and its arguments, and returns an exit status. +;; - Each writes to the current output and error ports. +;; - `find-program` is the search of PATH that `type` and the completer +;; use. + +(import (std prelude)) +(import (std run)) +(import (bjoterm line)) +(import (bjosh shell)) + +(export builtin? run-builtin builtin-names find-program) + +(type (: Builtin (Record (: name string) + (: usage string) + (: help string) + (: run (-> Shell (Vec string) int))))) + +;; =========================================================================== +;; The commands +;; =========================================================================== + +;; Runs `f` on each item, and returns the largest status: 0 when all +;; succeed. +(: (-> (Vec %a) (-> %a int) int)) +(defun (each-status items f) + (let go ((i 0) (status 0)) + (if (= i (vec-length items)) + status + (go (+ i 1) (max status (f (vec-ref items i))))))) + +(: (-> Shell (Vec string) int)) +(defun (cd sh args) + (def old (current-directory)) + (def target + (cond + ((vec-empty? args) (getenv "HOME")) + ((= (vec-ref args 0) "-") (getenv "OLDPWD")) + (else (Some (vec-ref args 0))))) + (match target + (None (shell-error "cd: no HOME or OLDPWD") 1) + ((Some dir) + (match (try (set-current-directory! dir) #:catch (System.Exception)) + ((Ok _) + (set-environment-variable! "OLDPWD" old) + (set-environment-variable! "PWD" (current-directory)) + (when (and (not (vec-empty? args)) (= (vec-ref args 0) "-")) + (println (current-directory))) + 0) + ((Err e) (shell-error (str "cd: " dir ": " (.-Message e))) 1))))) + +(: (-> Shell (Vec string) int)) +(defun (pwd sh args) + (println (current-directory)) + 0) + +(: (-> Shell (Vec string) int)) +(defun (exit-shell sh args) + (def code (if (vec-empty? args) + (Some (record-ref sh status)) + (string->int (vec-ref args 0)))) + (match code + (None (shell-error (str "exit: " (vec-ref args 0) ": not a number")) 2) + ((Some code) + (if (and (jobs-stopped? sh) (not (record-ref sh warned-stopped?))) + (begin + (warn-stopped! sh) + (shell-error "there are stopped jobs; exit again to end them") + 1) + (begin + (request-exit! sh code) + code))))) + +;; NAME=value sets and exports. NAME exports a shell variable. +(: (-> Shell (Vec string) int)) +(defun (export sh args) + (if (vec-empty? args) + (begin (shell-error "export: usage: export NAME[=value]...") 2) + (each-status args + (fun (arg) + (match (string-split-once arg "=") + ((Some (Tuple name value)) + (var-export! sh name value) + 0) + (None + (match (map-try-ref (record-ref sh vars) arg) + ((Some value) + (var-export! sh arg value) + 0) + (None + (match (getenv arg) + ((Some _) 0) + (None (shell-error (str "export: " arg ": not set")) 1)))))))))) + +(: (-> Shell (Vec string) int)) +(defun (unset sh args) + (for-each (fun (name) (var-unset! sh name)) args) + 0) + +(: (-> Shell (Vec string) int)) +(defun (jobs sh args) + (report-jobs sh) + (for-each (fun (e) (println (job-text-line sh e))) (record-ref sh jobs)) + 0) + +;; The job of the first argument, or the current job. +(: (-> Shell string (Vec string) (Result string JobEntry))) +(defun (job-arg sh command args) + (match (job-find sh (if (vec-empty? args) "%+" (vec-ref args 0))) + ((Ok e) (Ok e)) + ((Err message) + (Err (if (vec-empty? args) (str command ": no current job") (str command ": " message)))))) + +(: (-> Shell (Vec string) int)) +(defun (fg sh args) + (match (job-arg sh "fg" args) + ((Err message) (shell-error message) 1) + ((Ok e) + (println (record-ref e text)) + (foreground! sh (record-ref e job) (record-ref e text))))) + +(: (-> Shell (Vec string) int)) +(defun (bg sh args) + (match (job-arg sh "bg" args) + ((Err message) (shell-error message) 1) + ((Ok e) + (job-background (record-ref e job)) + (job-set-state! e JobRunning) + (job-mark-recent! sh (record-ref e number)) + (println (str "[" (int->string (record-ref e number)) "]+ " (record-ref e text) " &")) + 0))) + +(: (Vec (Tuple string int))) +(def signal-names + [(Tuple "HUP" 1) (Tuple "INT" 2) (Tuple "QUIT" 3) (Tuple "KILL" 9) (Tuple "USR1" 10) + (Tuple "USR2" 12) (Tuple "TERM" 15) (Tuple "CONT" 18) (Tuple "STOP" 19) (Tuple "TSTP" 20)]) + +;; A signal from -N, -NAME or -SIGNAME. +(: (-> string (Option int))) +(defun (signal-of text) + (def body (string-drop text 1)) + (def name (if (string-starts-with? body "SIG") (string-drop body 3) body)) + (match (string->int body) + ((Some n) (Some n)) + (None (match (find (fun (p) (= (fst p) name)) signal-names) + ((Some p) (Some (snd p))) + (None None))))) + +;; kill [-SIGNAL] %job|pid... Jobs get the signal here; pids go to the +;; kill program. +(: (-> Shell (Vec string) int)) +(defun (kill sh args) + (def has-signal? (and (not (vec-empty? args)) (string-starts-with? (vec-ref args 0) "-"))) + (def signal (if has-signal? (signal-of (vec-ref args 0)) (Some 15))) + (def targets (if has-signal? (vec-slice args 1 (- (vec-length args) 1)) args)) + (match signal + (None (shell-error (str "kill: " (vec-ref args 0) ": no such signal")) 2) + ((Some signal) + (if (vec-empty? targets) + (begin (shell-error "kill: usage: kill [-SIGNAL] %job|pid...") 2) + (let ((pids (vec-filter (fun (t) (not (string-starts-with? t "%"))) targets))) + (def job-status + (each-status (vec-filter (fun (t) (string-starts-with? t "%")) targets) + (fun (t) + (match (job-find sh t) + ((Ok e) + (job-signal (record-ref e job) signal) + ;; A stopped job gets the signal when it runs. + (match (record-ref e state) + ((JobStopped _) (unless (= signal 19) (job-signal (record-ref e job) 18))) + (_ unit)) + 0) + ((Err message) (shell-error (str "kill: " message)) 1))))) + (if (vec-empty? pids) + job-status + (match (run/interactive (FArgv (vec-append ["kill" (str "-" (int->string signal))] pids))) + ((Ok code) (max code job-status)) + ((Err e) (shell-error (run-error-message e)) 1)))))))) + +;; The path of a program on PATH, or a name with a / that exists. +(: (-> string (Option string))) +(defun (find-program name) + (if (string-contains? name "/") + (if (file-exists? name) (Some name) None) + (let ((dirs (match (getenv "PATH") ((Some p) (string-split p ":")) (None [])))) + (let go ((i 0)) + (if (= i (vec-length dirs)) + None + (let ((path (path-combine (vec-ref dirs i) name))) + (if (and (not (string-empty? (vec-ref dirs i))) (file-exists? path)) + (Some path) + (go (+ i 1))))))))) + +(: (-> Shell (Vec string) int)) +(defun (type-of sh args) + (each-status args + (fun (name) + (cond + ((builtin? name) (println (str name " is a shell command")) 0) + (else + (match (find-program name) + ((Some path) (println (str name " is " path)) 0) + (None (shell-error (str "type: " name ": not found")) 1))))))) + +(: (-> Shell (Vec string) int)) +(defun (help sh args) + (for-each (fun (b) + (println (str (string-pad-right (record-ref b usage) 28) (record-ref b help)))) + (builtins)) + 0) + +(: (-> Shell (Vec string) int)) +(defun (history sh args) + (match (record-ref sh editor) + (None 0) + ((Some ed) + (def entries (line-history ed)) + (loop (:for entry (in-vec entries)) + (:for i (range 1 (+ 1 (vec-length entries)))) + (:do (println (str (string-pad-left (int->string i) 5) " " entry)))) + 0))) + +;; =========================================================================== +;; The table +;; =========================================================================== + +(: (-> (Vec Builtin))) +(defun (builtins) + [(Builtin (name "cd") (usage "cd [DIR|-]") (help "change the directory; - is the one before") (run cd)) + (Builtin (name "pwd") (usage "pwd") (help "write the current directory") (run pwd)) + (Builtin (name "exit") (usage "exit [CODE]") (help "end the shell") (run exit-shell)) + (Builtin (name "export") (usage "export NAME[=VALUE]...") (help "put variables in the environment") (run export)) + (Builtin (name "unset") (usage "unset NAME...") (help "remove variables") (run unset)) + (Builtin (name "jobs") (usage "jobs") (help "list the jobs") (run jobs)) + (Builtin (name "fg") (usage "fg [%JOB]") (help "run a job in the foreground") (run fg)) + (Builtin (name "bg") (usage "bg [%JOB]") (help "continue a stopped job in the background") (run bg)) + (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))]) + +(: (-> string bool)) +(defun (builtin? name) + (any? (fun (b) (= (record-ref b name) name)) (builtins))) + +(: (Vec string)) +(def builtin-names (vec-map (fun (b) (record-ref b name)) (builtins))) + +;; Runs the shell command `name`. Returns its status; 127 when there is no +;; such command. +(: (-> Shell string (Vec string) int)) +(defun (run-builtin sh name args) + (match (find (fun (b) (= (record-ref b name) name)) (builtins)) + ((Some b) + (def status ((record-ref b run) sh args)) + (flush-port (parameter-ref current-output-port)) + status) + (None (shell-error (str name ": no such shell command")) 127))) diff --git a/src/editor.bjo b/src/editor.bjo new file mode 100644 index 0000000..579f13f --- /dev/null +++ b/src/editor.bjo @@ -0,0 +1,136 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; 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 editor): what the shell gives the line editor. +;; +;; - `input-done?`: whether Enter runs the input or starts a new line. +;; - `complete`: the completer. The first word of a command completes from +;; the shell commands and the programs on PATH; other words, and words +;; with a /, from file names. Names are quoted with \ where the parser +;; needs it. Directories end with /, everything else with a space. + +(import (std prelude)) +(import (std maths)) +(import (bjoterm line)) +(import (bjosh syntax)) +(import (bjosh builtins)) + +(export input-done? complete word-start command-position? quote-name file-candidates) + + +;; Whether Enter runs `text`: #f while a quote is open, or the line ends +;; with |, &&, || or \. A line with another error runs, to show it. +(: (-> string bool)) +(defun (input-done? text) + (and (not (odd-backslashes-at-end? text)) + (match (parse-line/message text) + ((Ok _) #t) + ((Err message) (not (string-contains? message "end of input")))))) + +;; Whether `text` ends with a \ that escapes the line break after it. +(: (-> string bool)) +(defun (odd-backslashes-at-end? text) + (def chars (string->vec text)) + (let go ((i (vec-length chars)) (n 0)) + (if (and (> i 0) (= (vec-ref chars (- i 1)) #\\)) + (go (- i 1) (+ n 1)) + (= (remainder n 2) 1)))) + +;; Where the word before the cursor starts: after the last space or +;; operator character. +(: (-> string int)) +(defun (word-start text) + (def chars (string->vec text)) + (let go ((i (vec-length chars))) + (cond + ((= i 0) 0) + ((string-contains? " \t\n|&;<>" (char->string (vec-ref chars (- i 1)))) i) + (else (go (- i 1)))))) + +;; Whether the word at `start` is the first word of a command. +(: (-> string int bool)) +(defun (command-position? text start) + (def before (string-trim-right (string-take text start))) + (or (string-empty? before) + (string-contains? "|&;" (string-take-right before 1)))) + +;; `name` with \ before characters that the parser would read as syntax. +(: (-> string string)) +(defun (quote-name name) + (string-join (vec-map (fun (c) + (def text (char->string c)) + (if (string-contains? " \t'\"\\$`|&;<>()*?[]#~" text) (str "\\" text) text)) + (string->vec name)) + "")) + +;; The last part of a path. +(: (-> Path string)) +(defun (base-name p) + (def parts (string-split (path->string/lossy p) "/")) + (vec-ref parts (- (vec-length parts) 1))) + +(: (-> string (Vec string))) +(defun (path-names dir) + (match (directory-files dir) + ((Ok paths) (vec-map base-name paths)) + ((Err _) []))) + +(: (-> string (Vec string))) +(defun (directory-names dir) + (match (directory-subdirectories dir) + ((Ok paths) (vec-map base-name paths)) + ((Err _) []))) + +;; Programs on PATH and shell commands that start with `prefix`. +(: (-> string (Vec string))) +(defun (command-candidates prefix) + (def dirs (match (getenv "PATH") ((Some p) (string-split p ":")) (None []))) + (def programs + (let go ((i 0) (all [])) + (if (= i (vec-length dirs)) + all + (go (+ i 1) (vec-append all (path-names (vec-ref dirs i))))))) + (vec-map (fun (n) (str (quote-name n) " ")) + (sorted-distinct (vec-filter (fun (n) (string-starts-with? n prefix)) + (vec-append builtin-names programs))))) + +;; `names` sorted, each once. +(: (-> (Vec string) (Vec string))) +(defun (sorted-distinct names) + (def sorted (vec-sort names)) + (let go ((i 0) (out [])) + (cond + ((= i (vec-length sorted)) out) + ((and (> i 0) (= (vec-ref sorted i) (vec-ref sorted (- i 1)))) (go (+ i 1) out)) + (else (go (+ i 1) (vec-add out (vec-ref sorted i))))))) + +;; Files and directories that start with `word`, which can have a +;; directory before it. Directories end with /, files with a space. +(: (-> string (Vec string))) +(defun (file-candidates word) + (def parts (string-split word "/")) + (def name-part (vec-ref parts (- (vec-length parts) 1))) + (def dir-part (string-take word (- (string-length word) (string-length name-part)))) + (def dir (cond + ((string-empty? dir-part) ".") + ((string-starts-with? dir-part "~/") + (str (match (getenv "HOME") ((Some h) h) (None "~")) (string-drop dir-part 1))) + (else dir-part))) + (defun (wanted? n) + (and (string-starts-with? n name-part) + (or (string-starts-with? name-part ".") (not (string-starts-with? n "."))))) + (vec-sort + (vec-append (vec-map (fun (n) (str dir-part (quote-name n) "/")) + (vec-filter wanted? (directory-names dir))) + (vec-map (fun (n) (str dir-part (quote-name n) " ")) + (vec-filter wanted? (path-names dir)))))) + +(: (-> string Completion)) +(defun (complete text) + (def start (word-start text)) + (def word (string-drop text start)) + (Completion (prefix word) + (candidates (if (and (command-position? text start) (not (string-contains? word "/"))) + (command-candidates word) + (file-candidates word))))) diff --git a/src/exec.bjo b/src/exec.bjo new file mode 100644 index 0000000..c5ac816 --- /dev/null +++ b/src/exec.bjo @@ -0,0 +1,215 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; 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 exec): runs lines. +;; +;; - A pipe of programs is one (std run) form. With job control it is a job +;; (`job-start`); without it, `run/interactive` runs it. +;; - A shell command runs in the shell. It must be alone, with no +;; assignments and no redirections (phase 1). +;; - A command of only assignments sets variables. One of only +;; redirections makes or checks its files, as in POSIX. +;; - NAME=value before a program puts NAME in its environment only, through +;; the program `env`. +;; - Status: see `state->status`. 127 for a program that is not found, 126 +;; for one that does not start, 2 for a line that does not parse or is +;; not supported. Without job control, the status of a pipe is that of +;; its last command. +;; - & runs one pipe in the background, and needs job control. + +(import (std prelude)) +(import (std run)) +(import (bjosh syntax)) +(import (bjosh expand)) +(import (bjosh shell)) +(import (bjosh builtins)) + +(export run-text) + +;; A command after expansion. +(type (: Expanded (Record (: assigns (Vec (Tuple string string))) + (: argv (Vec string)) + (: redirects (Vec (Tuple RedirectKind string)))))) + +(: (-> Shell Command (Result string Expanded))) +(defun (expand-command sh c) + (def ex (shell-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))) + (let go ((i 0) (redirects [])) + (def rs (record-ref c redirects)) + (if (= i (vec-length rs)) + (Ok (Expanded (assigns assigns) (argv argv) (redirects redirects))) + (let ((r (vec-ref rs i))) + (match (record-ref r kind) + (ErrToOut (go (+ i 1) (vec-add redirects (Tuple ErrToOut "")))) + (OutToErr (go (+ i 1) (vec-add redirects (Tuple OutToErr "")))) + (kind + (match (expand-target ex (record-ref r target)) + ((Ok path) (go (+ i 1) (vec-add redirects (Tuple kind path)))) + ((Err message) (Err message))))))))) + +;; The text of a command, for the job table. +(: (-> Expanded string)) +(defun (expanded->string e) + (string-join + (vec-append (vec-append (vec-map (fun (a) (str (fst a) "=" (snd a))) (record-ref e assigns)) + (record-ref e argv)) + (vec-map (fun (r) + (match (fst r) + (FromFile (str "<" (snd r))) + (IntoFile (str ">" (snd r))) + (AppendFile (str ">>" (snd r))) + (ErrIntoFile (str "2>" (snd r))) + (ErrAppendFile (str "2>>" (snd r))) + (ErrToOut "2>&1") + (OutToErr ">&2"))) + (record-ref e redirects))) + " ")) + +;; The form of one stage: its argv, through `env` for assignments, in its +;; redirections. +(: (-> Expanded (Result string Form))) +(defun (stage-form e) + (def assigns (record-ref e assigns)) + (def argv (if (vec-empty? assigns) + (record-ref e argv) + (vec-append (vec-append ["env"] (vec-map (fun (a) (str (fst a) "=" (snd a))) assigns)) + (record-ref e argv)))) + (let go ((i 0) (form (FArgv argv))) + (def rs (record-ref e redirects)) + (if (= i (vec-length rs)) + (Ok form) + (let ((path (snd (vec-ref rs i)))) + (match (fst (vec-ref rs i)) + (FromFile (go (+ i 1) (FFrom path form))) + (IntoFile (go (+ i 1) (FInto path form))) + (AppendFile (go (+ i 1) (FAppend path form))) + (ErrIntoFile (go (+ i 1) (FErrInto path form))) + (ErrAppendFile (go (+ i 1) (FErrAppend path form))) + (_ (Err "2>&1 and >&2 are not supported yet"))))))) + +;; The status for a form that did not start, after its message. +(: (-> RunError int)) +(defun (start-failed e) + (match e + ((NotFound name) (shell-error (str name ": command not found")) 127) + ((CannotStart name _) (shell-error (run-error-message e)) 126) + (_ (shell-error (run-error-message e)) 1))) + +;; A command of only assignments and redirections. +(: (-> Shell Expanded int)) +(defun (run-bare sh e) + (for-each (fun (a) (var-set! sh (fst a) (snd a))) (record-ref e assigns)) + (let go ((i 0)) + (def rs (record-ref e redirects)) + (if (= i (vec-length rs)) + 0 + (let* ((path (snd (vec-ref rs i))) + (problem (match (fst (vec-ref rs i)) + ((or IntoFile ErrIntoFile) + (match (file-write-text path "") ((Ok _) None) ((Err e) (Some (written e))))) + ((or AppendFile ErrAppendFile) + (match (file-append-text path "") ((Ok _) None) ((Err e) (Some (written e))))) + (FromFile (if (file-exists? path) None (Some "no such file"))) + (_ None)))) + (match problem + (None (go (+ i 1))) + ((Some message) (shell-error (str path ": " message)) 1)))))) + +(: (-> Shell (Vec Command) bool int)) +(defun (run-pipeline sh pipe background?) + (let go ((i 0) (expanded [])) + (if (< i (vec-length pipe)) + (match (expand-command sh (vec-ref pipe i)) + ((Ok e) (go (+ i 1) (vec-add expanded e))) + ((Err message) (shell-error message) 1)) + (run-expanded sh expanded background?)))) + +(: (-> Shell (Vec Expanded) bool int)) +(defun (run-expanded sh expanded background?) + (def text (string-join (vec-map expanded->string expanded) " | ")) + (def first (vec-ref expanded 0)) + (def name (if (vec-empty? (record-ref first argv)) "" (vec-ref (record-ref first argv) 0))) + (def builtin-in-pipe + (find (fun (e) (and (not (vec-empty? (record-ref e argv))) + (builtin? (vec-ref (record-ref e argv) 0)))) + expanded)) + (cond + ((and (= (vec-length expanded) 1) (vec-empty? (record-ref first argv))) + (run-bare sh first)) + ((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)) + (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)))) + (shell-error (str name ": assignments and redirections of shell commands are not supported yet")) + 2) + (else (run-builtin sh name (vec-slice (record-ref first argv) 1 (- (vec-length (record-ref first argv)) 1)))))) + (else + (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 (run-form sh expanded text background?)))))) + +(: (-> Shell (Vec Expanded) string bool int)) +(defun (run-form sh expanded text background?) + (let go ((i 0) (forms [])) + (if (< i (vec-length expanded)) + (match (stage-form (vec-ref expanded i)) + ((Ok f) (go (+ i 1) (vec-add forms f))) + ((Err message) (shell-error message) 2)) + (let ((form (if (= (vec-length forms) 1) (vec-ref forms 0) (FPipe (->list forms))))) + ;; The program writes to the same terminal or file. + (flush-port (parameter-ref current-output-port)) + (match (record-ref sh jc) + ((Some jc) + (match (job-start jc form (not background?)) + ((Ok job) + (if background? + (let ((entry (job-add! sh job text JobRunning))) + (println (str "[" (int->string (record-ref entry number)) "] " (int->string (job-id job)))) + 0) + (foreground! sh job text))) + ((Err e) (start-failed e)))) + (None + (if background? + (begin (shell-error "& needs an interactive shell with job control") 2) + (match (run/interactive form) + ((Ok code) code) + ((Err e) (start-failed e)))))))))) + +(: (-> Shell AndOr bool int)) +(defun (run-and-or sh a background?) + (if (and background? (not (vec-empty? (record-ref a rest)))) + (begin (shell-error "only one pipe can run in the background, not a list with && or ||") 2) + (let go ((status (run-pipeline sh (record-ref a first) background?)) (i 0)) + (set-status! sh status) + (def rest (record-ref a rest)) + (cond + ((= i (vec-length rest)) status) + ((not (= (record-ref sh exit-code) None)) status) + (else + (def (Tuple connector pipe) (vec-ref rest i)) + (def run? (match connector (AndThen (= status 0)) (OrElse (not (= status 0))))) + (if run? + (go (run-pipeline sh pipe #f) (+ i 1)) + (go status (+ i 1)))))))) + +;; Parses `text` and runs its items, until one of them is `exit`. Sets and +;; returns the status. +(: (-> Shell string int)) +(defun (run-text sh text) + (match (parse-line/message text) + ((Err message) + (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)))) diff --git a/src/expand.bjo b/src/expand.bjo new file mode 100644 index 0000000..35101aa --- /dev/null +++ b/src/expand.bjo @@ -0,0 +1,123 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; 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 expand): words of (bjosh syntax) to the strings a command gets. +;; +;; - $NAME is the value of the variable, or "" when there is none. +;; - ~ is $HOME, and ~user the home of that user in /etc/passwd. A user +;; that does not exist leaves ~user as written. +;; - A word with *, ? or [ in text that was not quoted is a glob, matched +;; with (std glob) from the current directory. Its matches are the words, +;; sorted. A glob that matches nothing stays as written, as in POSIX. +;; A file name that is not UTF-8 has U+FFFD for its bad bytes: a +;; 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. +;; - A word of only unquoted parameters that are all empty is no word, as +;; in POSIX. "$X" is always one word. + +(import (std prelude)) +(import (std glob)) +(import (bjosh syntax)) + +(export + Expander expand-word expand-words expand-text expand-target default-home-of) + +;; What expansion reads. +;; - `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 "". +(type (: Expander (Record (: lookup (-> string (Option string))) + (: home-of (-> string (Option string)))))) + +;; The home of `user` from /etc/passwd, or $HOME for "". +(: (-> string (Option string))) +(defun (default-home-of user) + (if (string-empty? user) + (getenv "HOME") + (match (file-read-lines "/etc/passwd") + ((Ok lines) + (let go ((i 0)) + (if (= i (vec-length lines)) + None + (let ((fields (string-split (vec-ref lines i) ":"))) + (if (and (>= (vec-length fields) 6) (= (vec-ref fields 0) user)) + (Some (vec-ref fields 5)) + (go (+ i 1))))))) + ((Err _) None)))) + +;; `s` with each glob character after a \, so that it matches itself. +(: (-> string string)) +(defun (glob-escape s) + (string-join (vec-map (fun (c) + (def text (char->string c)) + (if (string-contains? "\\*?[]{}" text) (str "\\" text) text)) + (string->vec s)) + "")) + +(: (-> string bool)) +(defun (glob-chars? s) + (or (string-contains? s "*") (string-contains? s "?") (string-contains? s "["))) + +;; A word expanded once: its text, the same as a glob pattern, whether it +;; is a glob, and whether it is only unquoted parameters. +(type (: Pieces (Record (: text string) (: pattern string) (: glob? bool) (: params-only? bool)))) + +(: (-> Expander (Vec WordPart) Pieces)) +(defun (pieces ex w) + (let go ((i 0) (text "") (pattern "") (glob? #f) (params-only? #t)) + (if (= i (vec-length w)) + (Pieces (text text) (pattern pattern) (glob? glob?) (params-only? params-only?)) + (match (vec-ref w i) + ((Lit s #f) (go (+ i 1) (str text s) (str pattern s) (or glob? (glob-chars? s)) #f)) + ((Lit s #t) (go (+ i 1) (str text s) (str pattern (glob-escape s)) glob? #f)) + ((Param n quoted?) + (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?)))) + ((Tilde user) + (def home (match ((record-ref ex home-of) user) + ((Some h) h) + (None (str "~" user)))) + (go (+ i 1) (str text home) (str pattern (glob-escape home)) glob? #f)))))) + +;; The words of `w`: one, none for empty unquoted parameters, or the +;; matches of a glob. +(: (-> Expander (Vec WordPart) (Vec string))) +(defun (expand-word ex w) + (def p (pieces ex w)) + (def text (record-ref p text)) + (cond + ((and (record-ref p params-only?) (string-empty? text)) []) + ((record-ref p glob?) + (match (glob-parse (record-ref p pattern)) + ((Ok g) + (def matches (vec-map path->string/lossy (->vec (glob g)))) + (if (vec-empty? matches) [text] matches)) + ((Err _) [text]))) + (else [text]))) + +;; The words of all of `words`, in order. +(: (-> Expander (Vec (Vec WordPart)) (Vec string))) +(defun (expand-words ex words) + (let go ((i 0) (out [])) + (if (= i (vec-length words)) + out + (go (+ i 1) (vec-append out (expand-word ex (vec-ref words i))))))) + +;; `w` as one string, with no glob: for the value of an assignment. +(: (-> Expander (Vec WordPart) string)) +(defun (expand-text ex w) + (record-ref (pieces ex w) text)) + +;; The file of a redirection: `w` expanded, which must be one word. +;; Returns the message "ambiguous redirect" for a glob of several matches, +;; and "no file name" for none. +(: (-> Expander (Vec WordPart) (Result string string))) +(defun (expand-target ex w) + (def words (expand-word ex w)) + (cond + ((= (vec-length words) 1) (Ok (vec-ref words 0))) + ((vec-empty? words) (Err (str (word->string w) ": no file name"))) + (else (Err (str (word->string w) ": ambiguous redirect"))))) diff --git a/src/main.bjo b/src/main.bjo index b7ea210..01f5a85 100644 --- a/src/main.bjo +++ b/src/main.bjo @@ -3,10 +3,90 @@ ;; file, You can obtain one at http://mozilla.org/MPL/2.0/. ;; (bjosh): the shell. See plan.org. +;; +;; bjosh interactive, with job control, when stdin is a +;; terminal; else runs the lines of stdin +;; bjosh -c LINE runs LINE +;; 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`. (import (std prelude)) +(import (std run)) (import (bjoterm terminal)) +(import (bjoterm line)) +(import (bjosh syntax)) +(import (bjosh shell)) +(import (bjosh builtins)) +(import (bjosh exec)) +(import (bjosh editor)) -(defun (main) - (println "bjosh: not yet") - 0) +;; =========================================================================== +;; The loop +;; =========================================================================== + +(: (-> string)) +(defun (history-path) + (def state (match (getenv "XDG_STATE_HOME") + ((Some s) s) + (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) + (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 ")) + +(: (-> Terminal int)) +(defun (interactive term) + (def jc (match (job-control) + ((Ok jc) (Some jc)) + ((Err _) (shell-error "no job control: & and Ctrl-Z do not work") None))) + (def ed (make-line-editor #:completer (Some complete) #:input-done? (Some input-done?) + #:suspend? #f)) + (def path (history-path)) + (ignore (line-history-load! ed path)) + (ignore (try (directory-create (path-combine path "..")) #:catch (System.Exception))) + (def sh (make-shell jc (Some ed) ["bjosh"])) + (let go () + (report-jobs sh) + (match (line-read ed term (prompt sh)) + ((LineText text) + (ignore (line-history-save ed path)) + (ignore (run-text sh text))) + (LineCancelled (set-status! sh 130)) + (LineEof (ignore (run-text sh "exit")))) + (match (record-ref sh exit-code) + ((Some code) code) + (None (go))))) + +(: (-> Shell string int)) +(defun (run-script sh text) + (ignore (run-text sh text)) + (match (record-ref sh exit-code) + ((Some code) code) + (None (record-ref sh status)))) + +(: (-> (Vec string) int)) +(defun (run-file args) + (match (file-read-text (vec-ref args 0)) + ((Ok text) (run-script (make-shell None None args) text)) + ((Err e) (shell-error (str (vec-ref args 0) ": " (written e))) 127))) + +(defun (main args) + (cond + ((and (>= (vec-length args) 2) (= (vec-ref args 0) "-c")) + (run-script (make-shell None None (vec-add-first (vec-slice args 2 (- (vec-length args) 2)) "bjosh")) + (vec-ref args 1))) + ((vec-empty? args) + (match (terminal-open) + ((Ok term) (interactive term)) + ((Err _) + (run-script (make-shell None None ["bjosh"]) (read-all (parameter-ref current-input-port)))))) + (else (run-file args)))) diff --git a/src/shell.bjo b/src/shell.bjo new file mode 100644 index 0000000..4368775 --- /dev/null +++ b/src/shell.bjo @@ -0,0 +1,272 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; 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 shell): the state of the shell, its variables, and the job table. +;; +;; - Variables: shell variables are in `vars`. A variable that is in the +;; environment is changed there, so that children get it. +;; - Jobs: a job is in the table when it runs in the background or is +;; stopped. A foreground job that ends is never in it. +;; - 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`. + +(import (std prelude)) +(import (std run)) +(import (bjoterm line)) +(import (bjosh expand)) + +(export + Shell JobEntry make-shell shell-error + 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 foreground! report-jobs state->status) + +(type (: JobEntry (Record (: number int) + (: job Job) + (: text string) + (: state JobState #:mutable)))) + +;; The state of the shell. +;; - `jc`: job control, for an interactive shell. None runs every line in +;; the foreground, with no jobs. +;; - `editor`: the line editor, for `history`. +;; - `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. +(type (: Shell (Record (: vars (Map string string) #:mutable) + (: status int #:mutable) + (: jc (Option JobControl)) + (: editor (Option LineEditor)) + (: args (Vec string)) + (: jobs (Vec JobEntry) #:mutable) + (: recent (Vec int) #:mutable) + (: exit-code (Option int) #:mutable) + (: warned-stopped? bool #:mutable)))) + +(import/extern + (pid (: System.Environment.ProcessId int #:get #:no-raise))) + +(: (-> (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))) + +;; Writes "bjosh: " and `message` to standard error. +(: (-> string void)) +(defun (shell-error message) + (flush-port (parameter-ref current-output-port)) + (def err (parameter-ref current-error-port)) + (write-string err (str "bjosh: " message "\n")) + (flush-port err)) + +;; The status of the last line, $?. +(: (-> Shell int void)) +(defun (set-status! sh status) (record-set! sh (status status))) + +;; Makes the loop end with `code`. +(: (-> Shell int void)) +(defun (request-exit! sh code) (record-set! sh (exit-code (Some code)))) + +;; Notes that `exit` warned about stopped jobs. +(: (-> Shell void)) +(defun (warn-stopped! sh) (record-set! sh (warned-stopped? #t))) + +(: (-> JobEntry JobState void)) +(defun (job-set-state! e state) (record-set! e (state state))) + +;; =========================================================================== +;; Variables +;; =========================================================================== + +;; Puts `name` in the environment with `value`, and takes it out of the +;; shell variables. +(: (-> Shell string string void)) +(defun (var-export! sh name value) + (set-environment-variable! name value) + (record-set! sh (vars (map-remove (record-ref sh vars) name)))) + +;; The value of `name`: a shell variable, the environment, or one of the +;; special names ? $ and 0 to 9. +(: (-> Shell string (Option string))) +(defun (var-ref sh name) + (cond + ((= name "?") (Some (int->string (record-ref sh status)))) + ((= name "$") (Some (int->string pid))) + ((and (= (string-length name) 1) (string-contains? "0123456789" name)) + (def i (- (char->int (string-cursor-ref name (string-cursor-start name))) 48)) + (def args (record-ref sh args)) + (if (< i (vec-length args)) (Some (vec-ref args i)) None)) + (else + (match (map-try-ref (record-ref sh vars) name) + ((Some v) (Some v)) + (None (getenv name)))))) + +;; Sets `name`: in the environment when it is there, else as a shell +;; variable. +(: (-> Shell string string void)) +(defun (var-set! sh name value) + (match (getenv name) + ((Some _) (set-environment-variable! name value)) + (None (record-set! sh (vars (map-set (record-ref sh vars) name value)))))) + +;; Removes `name` from the shell variables and the environment. +(: (-> Shell string void)) +(defun (var-unset! sh name) + (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))) + +;; =========================================================================== +;; Jobs +;; =========================================================================== + +;; The exit status of a job's state: 128 and the signal for a stop, else +;; the rule of `job-result`. +(: (-> Job JobState int)) +(defun (state->status job state) + (match state + ((JobStopped signal) (+ 128 signal)) + (JobRunning 0) + ((JobDone _) + (match (job-result job) + ((Ok _) 0) + ((Err (Exited _ code _)) code) + ((Err e) (shell-error (run-error-message e)) 1))))) + +;; Puts a job in the table with the lowest free number, as the current +;; job. Returns the entry. +(: (-> Shell Job string JobState JobEntry)) +(defun (job-add! sh job text state) + (def taken (vec-map (fun (e) (record-ref e number)) (record-ref sh jobs))) + (def number (let go ((n 1)) (if (vec-contains? taken n) (go (+ n 1)) n))) + (def entry (JobEntry (number number) (job job) (text text) (state state))) + (record-set! sh (jobs (vec-add (record-ref sh jobs) entry))) + (job-mark-recent! sh number) + entry) + +;; Makes job `number` the current job. +(: (-> Shell int void)) +(defun (job-mark-recent! sh number) + (record-set! sh (recent (vec-add (vec-filter (fun (n) (not (= n number))) (record-ref sh recent)) + number)))) + +(: (-> Shell int void)) +(defun (job-remove! sh number) + (record-set! sh (jobs (vec-filter (fun (e) (not (= (record-ref e number) number))) (record-ref sh jobs)))) + (record-set! sh (recent (vec-filter (fun (n) (not (= n number))) (record-ref sh recent))))) + +(: (-> Shell int (Option JobEntry))) +(defun (job-by-number sh number) + (find (fun (e) (= (record-ref e number) number)) (record-ref sh jobs))) + +;; The current job (`back` 0) or the previous one (`back` 1). +(: (-> Shell int (Option JobEntry))) +(defun (job-current sh back) + (def recent (record-ref sh recent)) + (def i (- (vec-length recent) 1 back)) + (if (< i 0) None (job-by-number sh (vec-ref recent i)))) + +;; The job that `spec` names: %n or n, %+ or %% or % (current), %- +;; (previous). Returns a message when there is none. +(: (-> Shell string (Result string JobEntry))) +(defun (job-find sh spec) + (def body (if (string-starts-with? spec "%") (string-drop spec 1) spec)) + (def found + (cond + ((or (= body "") (= body "+") (= body "%")) (job-current sh 0)) + ((= body "-") (job-current sh 1)) + (else (match (string->int body) + ((Some n) (job-by-number sh n)) + (None None))))) + (match found + ((Some e) (Ok e)) + (None (Err (str spec ": no such job"))))) + +(: (-> Shell bool)) +(defun (jobs-stopped? sh) + (any? (fun (e) (match (record-ref e state) ((JobStopped _) #t) (_ #f))) + (record-ref sh jobs))) + +;; How a job ended, for a code other than 0: the signal for a code above +;; 128, else "Exit n". +(: (-> int string)) +(defun (exit-text code) + (cond + ((= code 129) "Hangup") + ((= code 130) "Interrupt") + ((= code 131) "Quit") + ((= code 137) "Killed") + ((= code 143) "Terminated") + (else (str "Exit " (int->string code))))) + +;; A line of `jobs`: [n]+ State text. +(: (-> Shell JobEntry string)) +(defun (job-text-line sh e) + (def number (record-ref e number)) + (def mark (match (job-current sh 0) + ((Some c) (if (= (record-ref c number) number) "+" + (match (job-current sh 1) + ((Some p) (if (= (record-ref p number) number) "-" " ")) + (None " ")))) + (None " "))) + (def state-text + (match (record-ref e state) + (JobRunning "Running") + ((JobStopped 21) "Stopped (tty input)") + ((JobStopped 22) "Stopped (tty output)") + ((JobStopped _) "Stopped") + ((JobDone _) + (match (job-result (record-ref e job)) + ((Ok _) "Done") + ((Err (Exited _ code _)) (exit-text code)) + ((Err _) "Failed"))))) + (str "[" (int->string number) "]" mark " " (string-pad-right state-text 22) (record-ref e text))) + +;; Waits for a job in the foreground. A job that stops goes in the table +;; and gets a line; a job that ends leaves it. Returns its status. +(: (-> Shell Job string int)) +(defun (foreground! sh job text) + (match (job-foreground job) + ((Ok state) + (def existing (find (fun (e) (= (record-ref e job) job)) (record-ref sh jobs))) + (match state + ((JobStopped _) + (def entry (match existing + ((Some e) (record-set! e (state state)) (job-mark-recent! sh (record-ref e number)) e) + (None (job-add! sh job text state)))) + (println "") + (println (job-text-line sh entry))) + (_ (match existing + ((Some e) (job-remove! sh (record-ref e number))) + (None unit)))) + (def status (state->status job state)) + ;; Ctrl-C leaves the cursor after ^C. + (when (= status 130) (println "")) + status) + ((Err e) + (shell-error (run-error-message e)) + 1))) + +;; 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) + (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))))) + (match now + ((JobDone _) (job-remove! sh (record-ref e number))) + (_ unit))) + (record-ref sh jobs))) diff --git a/src/syntax.bjo b/src/syntax.bjo new file mode 100644 index 0000000..3d7b4b2 --- /dev/null +++ b/src/syntax.bjo @@ -0,0 +1,393 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; 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 syntax): command lines in a part of POSIX sh syntax, parsed to a +;; 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. +;; - 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. +;; - No field splitting: $NAME is one word, whatever its value holds. + +(import (std prelude)) +(import (text parser-combinators)) + +(export + WordPart RedirectKind Redirect Command Connector AndOr Item + parse-line parse-line/message 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))))))) + +;; An and-or list, and whether it ended with &. +(type (: Item (Record (: and-or AndOr) (: background? bool)))) + +;; One part of a command, while it is parsed. +(type (: Element (Union (: EWord (Vec WordPart)) (: ERedirect Redirect)))) + +;; =========================================================================== +;; Parsing +;; =========================================================================== + +(: (-> (List (List %a)) (Vec %a))) +(defun (flatten lists) + (let go ((rest lists) (acc [])) + (if (list-empty? rest) + acc + (go (list-tail rest) (vec-append acc (list->vec (list-head rest))))))) + +(: (-> char bool)) +(defun (blank? c) (or (= c #\space) (= c #\tab))) + +(: (-> char bool)) +(defun (ascii-letter? c) + (or (and (char>=? c #\a) (char<=? c #\z)) (and (char>=? c #\A) (char<=? c #\Z)))) + +(: (-> char bool)) +(defun (name-char? c) + (or (ascii-letter? c) (= c #\_) (and (char>=? c #\0) (char<=? c #\9)))) + +;; Whether `s` is a variable name: a letter or _, then letters, digits +;; and _. +(: (-> string bool)) +(defun (name? s) + (def chars (string->vec s)) + (and (> (vec-length chars) 0) + (or (ascii-letter? (vec-ref chars 0)) (= (vec-ref chars 0) #\_)) + (let go ((i 1)) + (cond + ((= i (vec-length chars)) #t) + ((name-char? (vec-ref chars i)) (go (+ i 1))) + (else #f))))) + +;; Characters that end plain text. +(: special string) +(def special "|&;<>()'\"\\$` \t\n") + +(: comment (Parser string)) +(def comment + (pright (pchar #\#) (many-satisfy (fun (c) (not (= c #\newline)))))) + +;; Spaces, tabs, \ and a line break, and a comment. +(: ws (Parser Unit)) +(def ws + (pmap (fun (_) unit) + (pboth (many (por (many-satisfy1 blank? "a space") (attempt (pstring "\\\n")))) + (opt comment)))) + +;; `ws`, and line breaks. +(: ws-nl (Parser Unit)) +(def ws-nl + (pmap (fun (_) unit) (many (por (pmap (fun (_) "") (pchar #\newline)) + (pmap (fun (_) "") (pright (look-ahead (any-of " \t#\\")) ws)))))) + +(: name (Parser string)) +(def name + (ppipe2 (satisfy (fun (c) (or (ascii-letter? c) (= c #\_))) "a name") + (many-satisfy name-char?) + (fun (c rest) (str (char->string c) rest)))) + +;; $NAME, ${NAME}, $?, $$, $0 to $9. A $ before anything else is a $. +(: (-> bool (Parser WordPart))) +(defun (param quoted?) + (pright (pchar #\$) + (choice (list + (pright (pchar #\{) + (pleft (pmap (fun (n) (Param n quoted?)) (plabel name "a name")) + (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")) + (preturn (Lit "$" quoted?)))))) + +(: backquote (Parser (List WordPart))) +(def backquote (pright (pchar #\`) (pfail "`...` is not supported"))) + +(: single-quoted (Parser (List WordPart))) +(def single-quoted + (pmap (fun (s) (list (Lit s #t))) + (between (pchar #\') (plabel (pchar #\') "a closing '") + (many-satisfy (fun (c) (not (= c #\'))))))) + +;; In double quotes, \ escapes only $ ` " \ and a line break. +(: 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"))))))) + +;; Outside quotes, \ makes the next character plain, and \ and a line break +;; is nothing. +(: escaped (Parser (List WordPart))) +(def escaped + (pright (pchar #\\) + (por (pmap (fun (c) (if (= c #\newline) (list) (list (Lit (char->string c) #t)))) + any-char) + (preturn (list (Lit "\\" #t)))))) + +(: plain (Parser (List WordPart))) +(def plain + (pmap (fun (s) (list (Lit s #f))) + (many-satisfy1 (fun (c) (not (string-contains? special (char->string c)))) "a word"))) + +(: word-part (Parser (List WordPart))) +(def word-part + (choice (list plain single-quoted double-quoted escaped + (pmap (fun (p) (list p)) (param #f)) + backquote))) + +(: tilde (Parser WordPart)) +(def tilde + (pright (pchar #\~) + (pmap (fun (user) (Tilde user)) + (many-satisfy (fun (c) (or (name-char? c) (= c #\.) (= c #\-))))))) + +;; A word: parts with nothing between them. ~ at its start is a `Tilde`. +(: word (Parser (Vec WordPart))) +(def word + (pbind (opt tilde) + (fun (t) + (match t + ((Some t) (pmap (fun (parts) (vec-add-first (flatten parts) t)) (many word-part))) + (None (pmap flatten (many1 word-part))))))) + +(: fd-and-op (Parser (Tuple (Option char) string))) +(def fd-and-op + (attempt (pboth (opt (any-of "0123456789")) + (choice (list (pstring ">>") (pstring ">&") (pstring ">") (pstring "<<") + (pstring "<&") (pstring "<")))))) + +(: unsupported-redirect string) +(def unsupported-redirect "only <, >, >>, 2>, 2>>, 2>&1 and >&2 are supported") + +(: redirect (Parser Redirect)) +(def redirect + (pbind fd-and-op + (fun (fo) + (def (Tuple fd op) fo) + (def fd-text (match fd ((Some c) (char->string c)) (None ""))) + (defun (to-file kind) (pmap (fun (w) (Redirect (kind kind) (target w))) + (pright ws (plabel word "a file name")))) + (defun (dup kind) (preturn (Redirect (kind kind) (target [])))) + (cond + ((= op "<<") (pfail "here-documents are not supported")) + ((= op "<&") (pfail unsupported-redirect)) + ((= op ">&") + (pbind (plabel (any-of "12") "1 or 2") + (fun (to) + (cond + ((and (= fd-text "2") (= to #\1)) (dup ErrToOut)) + ((and (or (= fd-text "") (= fd-text "1")) (= to #\2)) (dup OutToErr)) + (else (pfail unsupported-redirect)))))) + ((= op "<") + (if (or (= fd-text "") (= fd-text "0")) (to-file FromFile) (pfail unsupported-redirect))) + ((or (= fd-text "") (= fd-text "1")) + (to-file (if (= op ">") IntoFile AppendFile))) + ((= fd-text "2") + (to-file (if (= op ">") ErrIntoFile ErrAppendFile))) + (else (pfail unsupported-redirect)))))) + +(: element (Parser Element)) +(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 '('"))))) + +;; Words that start shell syntax that is not supported, at the start of a +;; command. +(: reserved (Vec string)) +(def reserved + ["if" "then" "else" "elif" "fi" "for" "while" "until" "do" "done" "case" "esac" + "function" "select" "{" "}" "!" "[[" "]]"]) + +;; The assignment of a word, when it is NAME=value. +(: (-> (Vec WordPart) (Option (Tuple string (Vec WordPart))))) +(defun (assignment w) + (if (vec-empty? w) + None + (match (vec-ref w 0) + ((Lit text #f) + (match (string-split-once text "=") + ((Some (Tuple n value)) + (if (name? n) + (Some (Tuple n (vec-add-first (vec-slice w 1 (- (vec-length w) 1)) (Lit value #f)))) + None)) + (None None))) + (_ None)))) + +(: (-> (Vec Element) Command)) +(defun (command-of elements) + (let go ((i 0) (assigns []) (words []) (redirects [])) + (if (= i (vec-length elements)) + (Command (assigns assigns) (words words) (redirects redirects)) + (match (vec-ref elements i) + ((ERedirect r) (go (+ i 1) assigns words (vec-add redirects r))) + ((EWord w) + (match (if (vec-empty? words) (assignment w) None) + ((Some a) (go (+ i 1) (vec-add assigns a) words redirects)) + (None (go (+ i 1) assigns (vec-add words w) redirects)))))))) + +(: command (Parser Command)) +(def command + (pbind (many1 (pleft element ws)) + (fun (elements) + (def c (command-of (list->vec elements))) + (def words (record-ref c words)) + (match (if (vec-empty? words) None (Some (vec-ref words 0))) + ((Some [(Lit w #f)]) + (if (vec-contains? reserved w) + (pfail (str "`" w "` is not supported")) + (preturn c))) + (_ (preturn c)))))) + +(: pipe-bar (Parser Unit)) +(def pipe-bar + (pright (attempt (pleft (pchar #\|) (not-followed-by (pchar #\|) "'|'"))) ws-nl)) + +(: pipeline (Parser (Vec Command))) +(def pipeline + (pmap list->vec (sep-by1 command pipe-bar))) + +(: connector (Parser Connector)) +(def connector + (pleft (por (pmap (fun (_) AndThen) (pstring "&&")) + (pmap (fun (_) OrElse) (pstring "||"))) + ws-nl)) + +(: and-or (Parser AndOr)) +(def and-or + (ppipe2 pipeline (many (pboth connector pipeline)) + (fun (first rest) (AndOr (first first) (rest (list->vec rest)))))) + +;; An and-or list and what ends it: &, ;, a line break, or the end. +(: item (Parser Item)) +(def item + (ppipe2 and-or + (pleft (choice (list (pmap (fun (_) #t) (pchar #\&)) + (pmap (fun (_) #f) (pchar #\;)) + (pmap (fun (_) #f) (pchar #\newline)) + (preturn #f))) + ws-nl) + (fun (a bg) (Item (and-or a) (background? bg))))) + +(: line (Parser (Vec Item))) +(def line + (pright ws-nl (pleft (pmap list->vec (many item)) eof))) + +;; The items of `text`, which can have several lines. Empty for a line of +;; spaces and comments. +(: (-> string (Result ParseError (Vec Item)))) +(defun (parse-line text) + (run-parser line text)) + +;; `parse-line`, with an error as the message of `error->string`. +(: (-> string (Result string (Vec Item)))) +(defun (parse-line/message text) + (run-parser/message line text)) + +;; =========================================================================== +;; Writing the tree back +;; =========================================================================== + +;; A word as text: quoted parts in double quotes. For tests and messages. +(: (-> (Vec WordPart) string)) +(defun (word->string w) + (string-join + (vec-map (fun (part) + (match part + ((Lit text #f) text) + ((Lit text #t) (str "\"" text "\"")) + ((Param n #f) (str "${" n "}")) + ((Param n #t) (str "\"${" n "}\"")) + ((Tilde user) (str "~" user)))) + w) + "")) + +(: (-> Redirect string)) +(defun (redirect->string r) + (def target (word->string (record-ref r target))) + (match (record-ref r kind) + (FromFile (str "<" target)) + (IntoFile (str ">" target)) + (AppendFile (str ">>" target)) + (ErrIntoFile (str "2>" target)) + (ErrAppendFile (str "2>>" target)) + (ErrToOut "2>&1") + (OutToErr ">&2"))) + +(: (-> Command string)) +(defun (command->string c) + (string-join + (vec-append (vec-append (vec-map (fun (a) (str (fst a) "=" (word->string (snd a)))) + (record-ref c assigns)) + (vec-map word->string (record-ref c words))) + (vec-map redirect->string (record-ref c redirects))) + " ")) + +(: (-> (Vec Command) string)) +(defun (pipeline->string p) + (string-join (vec-map command->string p) " | ")) + +;; The items as text, in one form: words split by one space, parts quoted +;; as `word->string` does, and items ended by " ;" or " &". For tests. +(: (-> (Vec Item) string)) +(defun (line->string items) + (string-join + (vec-map (fun (it) + (def a (record-ref it and-or)) + (str (pipeline->string (record-ref a first)) + (string-join (vec-map (fun (r) + (str (match (fst r) (AndThen " && ") (OrElse " || ")) + (pipeline->string (snd r)))) + (record-ref a rest)) + "") + (if (record-ref it background?) " &" " ;"))) + items) + " ")) diff --git a/tests/editor.bjo b/tests/editor.bjo new file mode 100644 index 0000000..00cfd5e --- /dev/null +++ b/tests/editor.bjo @@ -0,0 +1,57 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; 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 editor): when Enter runs a line, and completion. +;; +;; bjo test tests/editor.bjo + +(import (std prelude)) +(import (std simpletest)) +(import (bjoterm line)) +(import (bjosh editor)) + +(import/extern + (temp-dir (: System.IO.Path.GetTempPath (-> string))) + (process-id (: System.Environment.ProcessId int #:get #:no-raise))) + +(defun (main args) + (expect "a whole line runs" (input-done? "ls -l") #t) + (expect "an open quote waits" (input-done? "echo 'abc") #f) + (expect "an open double quote waits" (input-done? "echo \"abc") #f) + (expect "| at the end waits" (input-done? "ls |") #f) + (expect "&& at the end waits" (input-done? "make &&") #f) + (expect "\\ at the end waits" (input-done? "echo a \\") #f) + (expect "\\\\ at the end runs" (input-done? "echo a \\\\") #t) + (expect "a line that is not supported runs, to show the error" (input-done? "if true") #t) + (expect "two lines" (input-done? "echo 'a\nb'") #t) + + (expect "the word before the cursor" (word-start "ls -l fo") 6) + (expect "after an operator" (word-start "a|b") 2) + (expect "the first word is a command" (command-position? "ls" 0) #t) + (expect "the second is not" (command-position? "ls -l" 3) #f) + (expect "after | it is" (command-position? "a | b" 4) #t) + (expect "after && it is" (command-position? "a && b" 5) #t) + (expect "spaces are quoted" (quote-name "a b") "a\\ b") + (expect "and $" (quote-name "$x") "\\$x") + + (def dir (path-combine (temp-dir) (str "bjosh-editor-" (int->string process-id)))) + (ignore (directory-create (path-combine dir "abd"))) + (ignore (file-write-text (path-combine dir "abc.txt") "")) + (ignore (file-write-text (path-combine dir "a b") "")) + (ignore (file-write-text (path-combine dir ".hidden") "")) + (ignore (file-write-text (path-combine dir "abd/inner") "")) + (def here (current-directory)) + (set-current-directory! dir) + (expect "files and directories" (file-candidates "ab") ["abc.txt " "abd/"]) + (expect "not hidden files" (file-candidates "") ["a\\ b " "abc.txt " "abd/"]) + (expect "hidden files for a dot" (file-candidates ".h") [".hidden "]) + (expect "in a directory" (file-candidates "abd/i") ["abd/inner "]) + (expect "the second word completes files" (record-ref (complete "cat ab") candidates) ["abc.txt " "abd/"]) + (expect "the first word completes commands" + (any? (fun (c) (= c "jobs ")) (record-ref (complete "jo") candidates)) #t) + (expect "a first word with a / completes files" (record-ref (complete "./ab") candidates) + ["./abc.txt " "./abd/"]) + (set-current-directory! here) + (ignore (directory-delete-tree dir)) + 0) diff --git a/tests/expand.bjo b/tests/expand.bjo new file mode 100644 index 0000000..9656252 --- /dev/null +++ b/tests/expand.bjo @@ -0,0 +1,82 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; 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 expand): variables, ~ and globs, with a fake environment and a +;; directory of files made for the test. +;; +;; bjo test tests/expand.bjo + +(import (std prelude)) +(import (std simpletest)) +(import (bjosh syntax)) +(import (bjosh expand)) + +(import/extern + (temp-dir (: System.IO.Path.GetTempPath (-> string))) + (process-id (: System.Environment.ProcessId int #:get #:no-raise))) + +(: (-> string (Option string))) +(defun (lookup name) + (cond + ((= name "HOME") (Some "/home/me")) + ((= name "X") (Some "a b")) + ((= name "STAR") (Some "*")) + ((= name "EMPTY") (Some "")) + ((= name "?") (Some "0")) + (else None))) + +(: (-> string (Option string))) +(defun (home-of user) + (cond + ((string-empty? user) (Some "/home/me")) + ((= user "bob") (Some "/home/bob")) + (else None))) + +(def ex (Expander (lookup lookup) (home-of home-of))) + +;; The words of the first command of `text`, joined by "|". +(: (-> string string)) +(defun (words text) + (match (parse-line text) + ((Ok items) + (def pipe (record-ref (record-ref (vec-ref items 0) and-or) first)) + (string-join (expand-words ex (record-ref (vec-ref pipe 0) words)) "|")) + ((Err _) "parse error"))) + +(defun (main args) + (expect "plain words" (words "ls -l x") "ls|-l|x") + (expect "a variable" (words "echo $HOME/src") "echo|/home/me/src") + (expect "a value with spaces is one word" (words "echo $X") "echo|a b") + (expect "a variable that is not set is empty" (words "echo a${NOPE}b") "echo|ab") + (expect "an empty unquoted variable is no word" (words "echo $EMPTY $NOPE x") "echo|x") + (expect "a quoted empty variable is a word" (words "echo \"$EMPTY\" x") "echo||x") + (expect "$?" (words "echo $?") "echo|0") + (expect "~" (words "cd ~ ~/src") "cd|/home/me|/home/me/src") + (expect "~user" (words "cd ~bob/x") "cd|/home/bob/x") + (expect "a user that does not exist" (words "cd ~nobody") "cd|~nobody") + + ;; Globs, in a directory of our own. + (def dir (path-combine (temp-dir) (str "bjosh-expand-" (int->string process-id)))) + (ignore (directory-create dir)) + (for-each (fun (name) (ignore (file-write-text (path-combine dir name) ""))) + ["b.txt" "a.txt" "c.log" ".hidden.txt" "*.txt"]) + (def here (current-directory)) + (set-current-directory! dir) + (expect "a glob, sorted" (words "ls *.txt") "ls|*.txt|a.txt|b.txt") + (expect "? and [ ]" (words "ls [ab].tx?") "ls|a.txt|b.txt") + (expect "a glob that matches nothing stays" (words "ls *.md") "ls|*.md") + (expect "a quoted * is not a glob" (words "ls '*'.txt") "ls|*.txt") + (expect "a \\* is not a glob" (words "ls \\*.txt") "ls|*.txt") + (expect "a * from a variable is not a glob" (words "ls $STAR") "ls|*") + (expect "a quoted part in a glob matches itself" (words "ls '*'*") "ls|*.txt") + (expect "names with a dot only for a pattern with a dot" (words "ls .h*") "ls|.hidden.txt") + (set-current-directory! here) + (for-each (fun (name) (ignore (file-delete (path-combine dir name)))) + ["b.txt" "a.txt" "c.log" ".hidden.txt" "*.txt"]) + (ignore (directory-delete dir)) + + ;; Redirections. + (expect "a target" (expand-target ex [(Lit "out" #f)]) (Ok "out")) + (expect "an empty target" (expand-target ex [(Param "EMPTY" #f)]) (Err "${EMPTY}: no file name")) + 0) diff --git a/tests/interactive.bjo b/tests/interactive.bjo new file mode 100644 index 0000000..24e3838 --- /dev/null +++ b/tests/interactive.bjo @@ -0,0 +1,71 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; 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 on a terminal: job control and the prompt. +;; +;; 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. + +(import (std prelude)) +(import (std simpletest)) +(import (std run)) + +(import/extern + (temp-dir (: System.IO.Path.GetTempPath (-> string))) + (process-id (: System.Environment.ProcessId int #:get #:no-raise))) + +;; The output without escape sequences and carriage returns. +(: (-> string string)) +(defun (plain text) + (def chars (string->vec (string-replace text "\r" ""))) + (let go ((i 0) (out (stringbuilder-empty))) + (cond + ((= i (vec-length chars)) (stringbuilder->string out)) + ((and (= (char->int (vec-ref chars i)) 27) (< (+ i 1) (vec-length chars)) (= (vec-ref chars (+ i 1)) #\[)) + (let skip ((j (+ i 2))) + (if (and (< j (vec-length chars)) + (let ((code (char->int (vec-ref chars j)))) (and (>= code 0x20) (<= code 0x3f)))) + (skip (+ j 1)) + (go (+ j 1) out)))) + (else (stringbuilder-add! out (vec-ref chars i)) (go (+ i 1) out))))) + +(defun (main args) + (cond + ((not (file-exists? "/usr/bin/script")) (println "skipped: no script command")) + ((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)))) + (def keys (string-join ["sleep 2.5" + "printf 'sleep 30\\r'" "sleep 1" "printf '\\032'" "sleep 0.5" + "printf 'jobs\\r'" "sleep 0.5" + "printf 'bg\\r'" "sleep 0.5" + "printf 'kill %%1\\r'" "sleep 0.5" + "printf 'jobs\\r'" "sleep 0.5" + "printf 'sleep 30\\r'" "sleep 1" "printf '\\003'" "sleep 0.5" + "printf 'echo status $?\\r'" "sleep 0.5" + "printf 'ech'" "sleep 0.3" "printf '\\032'" "sleep 0.5" + "printf 'o alive\\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 out (match (run/output '(sh "-c" ,command)) + ((Ok (Tuple _ text)) (plain text)) + ((Err e) (run-error-message e)))) + (expect-true "Ctrl-Z stops the job" (string-contains? out "^Z\n[1]+ Stopped sleep 30")) + (expect-true "jobs lists it" (string-contains? out "jobs\n[1]+ Stopped sleep 30")) + (expect-true "bg continues it" (string-contains? out "bg\n[1]+ sleep 30 &")) + (expect-true "kill ends it" (string-contains? out "[1]+ Terminated sleep 30")) + (expect-true "Ctrl-C ends a job, and the prompt starts a new line" (string-contains? out "^C\n")) + (expect-true "with status 130" (string-contains? out "status 130")) + (expect-true "Ctrl-Z at the prompt does not stop the shell" (string-contains? out "\nalive\n")) + (expect-true "the history is saved" + (match (file-read-text (path-combine state "bjosh/history")) + ((Ok text) (string-contains? text "kill %1")) + ((Err _) #f))) + (unless (string-contains? out "status 130") + (println out)) + (ignore (directory-delete-tree state)))) + 0) diff --git a/tests/run.bjo b/tests/run.bjo new file mode 100644 index 0000000..bd77be2 --- /dev/null +++ b/tests/run.bjo @@ -0,0 +1,97 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; 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 -c LINE, bjosh FILE and bjosh < lines: what lines write, and the +;; exit code. +;; +;; bjo build && bjo test tests/run.bjo + +(import (std prelude)) +(import (std simpletest)) +(import (std run)) + +(import/extern + (temp-dir (: System.IO.Path.GetTempPath (-> string))) + (process-id (: System.Environment.ProcessId int #:get #:no-raise))) + +(def shell "src/main.exe") + +(def scratch (path-combine (temp-dir) (str "bjosh-run-" (int->string process-id)))) + +;; Runs `form` with stderr into a file. Returns "out", then "err: " and +;; the error text when there is one, then "code: n" when it is not 0. +(: (-> Form string)) +(defun (outcome form) + (def err-path (path-combine scratch "stderr")) + (match (run/output (FErrInto err-path form)) + ((Ok (Tuple code out)) + (def err (match (file-read-text err-path) ((Ok t) t) ((Err _) ""))) + (string-trim-right + (str out + (if (string-empty? err) "" (str "err: " err)) + (if (= code 0) "" (str "code: " (int->string code)))))) + ((Err e) (str "did not run: " (run-error-message e))))) + +(: (-> string string)) +(defun (c line) (outcome (FArgv ["dotnet" shell "-c" line]))) + +(defun (main args) + (unless (file-exists? shell) + (println "FAILURE: src/main.exe is missing: run bjo build first")) + (ignore (directory-create scratch)) + (def file (path-combine scratch "f.txt")) + + ;; Pipes, lists and status. + (expect "a pipe" (c "echo a b | tr a-z A-Z") "A B") + (expect "&& and ||" (c "false && echo no || echo yes") "yes") + (expect "; runs both" (c "echo a; echo b") "a\nb") + (expect "$? after a failure" (c "false; echo $?") "1") + (expect "without job control, a pipe's status is its last command's" (c "false | true; echo $?") "0") + (expect "the status of the last line is the exit code" (c "false") "code: 1") + (expect "exit" (c "exit 3; echo no") "code: 3") + + ;; Words and variables. + (expect "quotes" (c "echo 'a b' \"c d\" e\\ f") "a b c d e f") + (expect "a variable" (c "X=hi; echo $X ${X}x \"$X\"") "hi hix hi") + (expect "a value is not split" (c "X='a b'; printf '[%s]' $X") "[a b]") + (expect "an empty variable is no word" (c "printf '[%s]' $NOPE x") "[x]") + (expect "export" (c "export Y=1; env | grep '^Y='") "Y=1") + (expect "export of a shell variable" (c "Y=2; export Y; env | grep '^Y='") "Y=2") + (expect "unset" (c "Y=1; unset Y; echo [$Y]") "[]") + (expect "NAME=value for one command" (c "Z=2 env | grep '^Z='; echo [$Z]") "Z=2\n[]") + (expect "$0 and $1 of -c" (outcome (FArgv ["dotnet" shell "-c" "echo $0 $1" "one"])) "bjosh one") + + ;; Redirections. + (expect "> >> <" (c (str "echo x >" file "; echo y >>" file "; cat <" file)) "x\ny") + (expect "2>" (c (str "ls /no/such/dir 2>" file "; echo $?; grep -c . " file)) "2\n1") + (expect "> alone makes an empty file" (c (str ">" file "; wc -c <" file)) "0") + (expect "2>&1 is not supported yet" (c "ls 2>&1") + "err: bjosh: 2>&1 and >&2 are not supported yet\ncode: 2") + + ;; Shell commands. + (expect "cd and pwd" (c "cd /tmp; pwd") "/tmp") + (expect "cd -" (c "cd /tmp; cd /; cd -") "/tmp") + (expect "cd to nowhere" (string-contains? (c "cd /no/such/dir") "code: 1") #t) + (expect "type" (c "type cd") "cd is a shell command") + (expect "a shell command in a pipe" (c "cd | cat") + "err: bjosh: cd: a shell command cannot be in a pipe\ncode: 2") + + ;; Errors. + (expect "a program that is not found" (c "nosuchprogram") + "err: bjosh: nosuchprogram: command not found\ncode: 127") + (expect "syntax that is not supported" (string-contains? (c "if true; then ls; fi") "`if` is not supported") #t) + (expect "and its status" (string-ends-with? (c "if true; then ls; fi") "code: 2") #t) + (expect "& needs job control" (c "sleep 1 &") + "err: bjosh: & needs an interactive shell with job control\ncode: 2") + + ;; A file, and stdin. + (def script-path (path-combine scratch "script.sh")) + (ignore (file-write-text script-path "echo $0 $1\necho second line\n")) + (expect "a file, with its arguments" (outcome (FArgv ["dotnet" shell script-path "arg"])) + (str script-path " arg\nsecond line")) + (expect "lines on stdin" (outcome (FFrom script-path (FArgv ["dotnet" shell]))) + "bjosh\nsecond line") + + (ignore (directory-delete-tree scratch)) + 0) diff --git a/tests/syntax.bjo b/tests/syntax.bjo new file mode 100644 index 0000000..7c0cea7 --- /dev/null +++ b/tests/syntax.bjo @@ -0,0 +1,110 @@ +;; This Source Code Form is subject to the terms of the Mozilla Public +;; 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 syntax): lines to trees, and the errors. +;; +;; bjo test tests/syntax.bjo + +(import (std prelude)) +(import (std simpletest)) +(import (text parser-combinators)) +(import (bjosh syntax)) + +;; The tree of `text` as `line->string` writes it, or "error: " and the +;; first line of the message. +(: (-> string string)) +(defun (parsed text) + (match (parse-line/message text) + ((Ok items) (line->string items)) + ((Err e) (str "error: " (error-reason e))))) + +;; The lines of a message after "Expecting:" or the message's own text. +(: (-> string string)) +(defun (error-reason message) + (def lines (string-split message "\n")) + (string-join (vec-slice lines 3 (- (vec-length lines) 3)) " / ")) + +;; The column of the error for `text`, or 0. +(: (-> string int)) +(defun (error-column text) + (match (parse-line text) + ((Ok _) 0) + ((Err e) (record-ref (parse-error-position e) column)))) + +(defun (main args) + ;; Words and quotes. + (expect "a command" (parsed "ls -l /tmp") "ls -l /tmp ;") + (expect "spaces and tabs between words" (parsed " ls \t -l ") "ls -l ;") + (expect "single quotes" (parsed "echo 'a b' 'it''s'") "echo \"a b\" \"it\"\"s\" ;") + (expect "double quotes" (parsed "echo \"a b\"") "echo \"a b\" ;") + (expect "quotes inside a word" (parsed "echo a'b c'd") "echo a\"b c\"d ;") + (expect "\\ makes a character plain" (parsed "echo a\\ b") "echo a\" \"b ;") + (expect "\\ in double quotes escapes only some" (parsed "echo \"\\$a \\x\"") + "echo \"$\"\"a \"\"\\\"\"x\" ;") + (expect "\\ and a line break is nothing" (parsed "echo a\\\nb") "echo ab ;") + (expect "an empty quoted word" (parsed "echo ''") "echo \"\" ;") + + ;; Parameters and ~. + (expect "$NAME" (parsed "echo $HOME/x") "echo ${HOME}/x ;") + (expect "${NAME}" (parsed "echo ${HOME}x") "echo ${HOME}x ;") + (expect "$NAME in double quotes" (parsed "echo \"$HOME\"") "echo \"${HOME}\" ;") + (expect "$? and $$" (parsed "echo $? $$") "echo ${?} ${$} ;") + (expect "a $ before something else" (parsed "echo a$ $.") "echo a$ $. ;") + (expect "~ at the start" (parsed "cd ~/src ~bob") "cd ~/src ~bob ;") + (expect "~ elsewhere is text" (parsed "echo a~b") "echo a~b ;") + + ;; Operators. + (expect "a pipe" (parsed "ls | wc -l") "ls | wc -l ;") + (expect "a pipe without spaces" (parsed "ls|wc") "ls | wc ;") + (expect "&& and ||" (parsed "make && echo ok || echo bad") "make && echo ok || echo bad ;") + (expect "; between items" (parsed "a; b ;c") "a ; b ; c ;") + (expect "& runs in the background" (parsed "sleep 9 & ls") "sleep 9 & ls ;") + (expect "line breaks end items" (parsed "a\nb\n\n") "a ; b ;") + (expect "a line break after | continues it" (parsed "ls |\n wc") "ls | wc ;") + (expect "a line break after && continues it" (parsed "a &&\nb") "a && b ;") + + ;; Redirections. + (expect "< > >>" (parsed "sort out >>log") "sort out >>log ;") + (expect "a space after the operator" (parsed "sort < in > out") "sort out ;") + (expect "2> and 2>>" (parsed "make 2>err 2>>log") "make 2>err 2>>log ;") + (expect "2>&1 and >&2" (parsed "make 2>&1; echo x >&2") "make 2>&1 ; echo x >&2 ;") + (expect "1> is >" (parsed "ls 1>out") "ls >out ;") + (expect "a 2 that is a word" (parsed "echo 2 > x") "echo 2 >x ;") + (expect "a redirection first" (parsed ">out ls") "ls >out ;") + (expect "redirections in a pipe" (parsed "a out") "a out ;") + + ;; Assignments. + (expect "an assignment alone" (parsed "X=1") "X=1 ;") + (expect "assignments before a command" (parsed "A=1 B=\"x y\" env") "A=1 B=\"x y\" env ;") + (expect "after a word it is a word" (parsed "echo X=1") "echo X=1 ;") + (expect "not a name" (parsed "1X=2") "1X=2 ;") + + ;; Comments, and empty lines. + (expect "a comment" (parsed "ls # list") "ls ;") + (expect "# in a word" (parsed "echo a#b") "echo a#b ;") + (expect "only a comment" (parsed "# nothing") "") + (expect "an empty line" (parsed " ") "") + + ;; Errors. + (expect "an open quote" (parsed "echo 'abc") + "error: Expecting: a closing ' / Unexpected: end of input") + (expect "an open double quote" (parsed "echo \"abc") + "error: Expecting: a closing \" / Unexpected: end of input") + (expect "| at the end" (string-starts-with? (parsed "ls |") "error:") #t) + (expect "|| at the end" (string-starts-with? (parsed "ls ||") "error:") #t) + (expect "a ; first" (string-starts-with? (parsed "; ls") "error:") #t) + (expect "if" (parsed "if true; then ls; fi") "error: `if` is not supported") + (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 "`...`" (parsed "echo `ls`") "error: `...` is not supported") + (expect "here-documents" (parsed "cat <x") + "error: only <, >, >>, 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) + 0)