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:
parent
7f585bd0b2
commit
3518b7711d
16 changed files with 1964 additions and 3 deletions
264
src/builtins.bjo
Normal file
264
src/builtins.bjo
Normal 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)))
|
||||
136
src/editor.bjo
Normal file
136
src/editor.bjo
Normal file
|
|
@ -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)))))
|
||||
215
src/exec.bjo
Normal file
215
src/exec.bjo
Normal file
|
|
@ -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))))
|
||||
123
src/expand.bjo
Normal file
123
src/expand.bjo
Normal file
|
|
@ -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")))))
|
||||
86
src/main.bjo
86
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))))
|
||||
|
|
|
|||
272
src/shell.bjo
Normal file
272
src/shell.bjo
Normal file
|
|
@ -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)))
|
||||
393
src/syntax.bjo
Normal file
393
src/syntax.bjo
Normal file
|
|
@ -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)
|
||||
" "))
|
||||
Loading…
Add table
Add a link
Reference in a new issue