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 <noreply@anthropic.com>
This commit is contained in:
Linus Björnstam 2026-12-01 06:19:45 +01:00
parent 7f585bd0b2
commit 3518b7711d
16 changed files with 1964 additions and 3 deletions

57
tests/editor.bjo Normal file
View file

@ -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)

82
tests/expand.bjo Normal file
View file

@ -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)

71
tests/interactive.bjo Normal file
View file

@ -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)

97
tests/run.bjo Normal file
View file

@ -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)

110
tests/syntax.bjo Normal file
View file

@ -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 <in >out >>log") "sort <in >out >>log ;")
(expect "a space after the operator" (parsed "sort < in > out") "sort <in >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 <in | b >out") "a <in | b >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 <<EOF") "error: here-documents are not supported")
(expect "${NAME:-x}" (parsed "echo ${A:-x}")
"error: Expecting: '}' (only ${NAME} is supported) / Unexpected: ':'")
(expect "descriptors above 2" (parsed "ls 3>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)