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

264
src/builtins.bjo Normal file
View file

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