// zash language specification // Compile with: typst compile zash-spec.typ #set document(title: "The zash Shell Language", author: "Sean Kurtz") #set page(paper: "us-letter", margin: (x: 1in, y: 1in)) #set text(font: ("Libertinus Serif", "New Computer Modern"), size: 10.5pt) #set par(justify: true) #set heading(numbering: "1.1") #show raw: set text(font: ("DejaVu Sans Mono", "Liberation Mono"), size: 9pt) #show raw.where(block: true): block.with( fill: luma(245), inset: 8pt, radius: 3pt, width: 100%, ) #show link: underline // --------------------------------------------------------------------- // Highlighting in inline code. A builtin or utility name at the start // of an inline code span is set in blue bold; a reserved word in purple. // Every inline span gets a light background so code stands out from prose. // --------------------------------------------------------------------- #let mono = ("DejaVu Sans Mono", "Liberation Mono") #let command-names = ( ".", ":", "[", "alias", "alloc", "bg", "bind", "break", "cd", "chdir", "command", "continue", "echo", "eval", "exec", "exit", "export", "false", "fc", "fg", "free", "getopts", "hash", "integer", "jobs", "kill", "let", "local", "print", "printf", "pwd", "read", "readonly", "return", "set", "setvar", "shift", "tag", "test", "times", "trap", "true", "type", "typeset", "ulimit", "umask", "unalias", "unset", "wait", "whence", // utilities the text names "cat", "cmp", "diff", "sed", "sh", "zash", "dash", "bash", "ksh", ) #let reserved-names = ( "!", "{", "}", "case", "do", "done", "elif", "else", "esac", "fi", "for", "function", "if", "in", "select", "then", "time", "until", "while", "[[", "]]", ) #let cmd-style(s) = text(fill: rgb("#1f5fa8"), weight: "bold", s) #let kw-style(s) = text(fill: rgb("#7a3e9d"), weight: "bold", s) #let known(w) = w in command-names or w in reserved-names #let styled(w) = if w in command-names { cmd-style(w) } else if ( w in reserved-names ) { kw-style(w) } else { w } // A short span gets a padded, rounded box. A box cannot break across // lines, so a long span gets a flat highlight instead. The highlight has // no horizontal extent: Typst draws it once per text run, and a run with // extent would paint over the last glyph of the run before it. #let code-bg(body, len: 0) = if len <= 32 { box(fill: luma(240), inset: (x: 1.6pt), outset: (y: 1.6pt), radius: 2pt, body) } else { highlight( fill: luma(240), extent: 0pt, top-edge: "ascender", bottom-edge: "descender", body, ) } // The first word is highlighted if it names a command or a reserved word. // A span that is nothing but such names (a list of builtins) has every // word highlighted. #show raw.where(block: false): it => { // A span written across a source line break holds a newline; treat it // as one space, or the box would be two lines high. let src = it.text.trim().replace(regex("\s+"), " ") let words = src.split(" ") let all-names = words.len() > 1 and words.all(w => w == "" or known(w)) let body = if all-names { words.map(styled).join(" ") } else if known(words.first()) { styled(words.first()) + src.slice(words.first().len()) } else { src } code-bg(text(font: mono, size: 9pt, body), len: src.len()) } /// A command name in running text, highlighted the same way. #let cmd(name) = code-bg(text(font: mono, size: 9pt, cmd-style(name))) // --------------------------------------------------------------------- // Rules. Every normative statement is a numbered rule, so that tests // can cite it ("covers R-EXP-12") and a later formalisation can map // rule to theorem one for one. // --------------------------------------------------------------------- /// A normative rule: `prefix` names the chapter (LEX, GRM, ...). /// `tests` lists the test files that exercise it; `key` gives it a name /// that #rref() can cite, so citations follow renumbering. #let rule(prefix, body, tests: (), status: none, key: none) = { let c = counter("rule-" + prefix) c.step() context { let id = "R-" + prefix + "-" + str(c.get().first()) if key != none [#metadata(id)#label("rule-" + key)] block( width: 100%, inset: (left: 8pt, y: 4pt), stroke: (left: 2pt + luma(160)), breakable: true, )[ #text(weight: "bold", font: ("DejaVu Sans Mono",), size: 8.5pt)[#id] #if status != none [ #text(fill: rgb("#a33"), size: 8.5pt)[(#status)] ] #h(0.5em) #body #if tests.len() > 0 [ #linebreak() #text( size: 8.5pt, fill: luma(90), )[Tests: #tests.map(t => raw(t)).join(", ")] ] ] } } /// Cite a rule by its key; prints its current identifier. #let rref(key) = context { let m = query(label("rule-" + key)) if m.len() == 0 { text(fill: red)[??#key] } else { raw(m.first().value) } } /// Something the specification does not yet decide. #let open(body) = block( width: 100%, fill: rgb("#fff4e0"), inset: 8pt, radius: 3pt, )[*Open.* #body] /// A note: explanation, not a rule. #let note(body) = block( width: 100%, fill: rgb("#eef3fb"), inset: 8pt, radius: 3pt, )[*Note.* #body] // Semantic brackets. #let sem(x) = $lr(⟦ #x ⟧)$ // --------------------------------------------------------------------- // --------------------------------------------------------------------- // Cover page // --------------------------------------------------------------------- #page(numbering: none, margin: (x: 1.1in, y: 1.2in))[ #v(1fr) #align(center)[ #image("../packaging/zash-logo.svg", width: 1.3in) #v(18pt) #text(size: 34pt, weight: "bold")[zash] #v(2pt) #text(size: 17pt)[The Shell Language] #v(4pt) #text(size: 13pt, fill: luma(90))[Specification] #v(28pt) #line(length: 55%, stroke: 0.6pt + luma(150)) #v(14pt) #text(size: 11pt)[Draft 1] #v(4pt) #text(size: 10pt, fill: luma(80))[ Describes zash at commit #raw("b4d7dc3") with the audit fixes applied ] #v(4pt) #text(size: 10pt, fill: luma(80))[#( datetime.today().display("[month repr:long] [day], [year]") )] ] #v(1fr) #block(width: 100%, inset: (x: 0.4in))[ #set par(justify: true) #set text(size: 9.5pt) zash is a small, fast POSIX shell for z/OS UNIX System Services in the Almquist tradition. This document specifies the language it accepts and what each construct means, as numbered rules that the test suite cites and that a later machine-checked model can follow one for one. ] #v(0.6fr) #align(center)[ #text(size: 9pt, fill: luma(100))[ Sean Kurtz · MIT OR Apache-2.0 OR BSD-2-Clause ] ] ] #set page(numbering: "1") #counter(page).update(1) #outline(depth: 2, indent: auto) #pagebreak() = Introduction This document specifies the language that zash accepts and what each construct means. It is the reference for script writers and zash reviewers. Each rule has an identifier that tests cite, and a later Lean formalisation will encode each rule as a definition or a theorem. The base is the Shell Command Language of POSIX.1-2024 (XCU chapter 2). Where this document is silent, POSIX applies. Where zash differs from POSIX or extends it, the rule says so and is listed again in @differences. The Korn shell constructs the z/OS `/bin/sh` (of the ksh88 line) offers are part of the language too, because zash is that shell's successor; each is a rule of its own, marked with zash's status. == Scope In scope: the input language (lexical structure and grammar), word expansion, the meaning of commands, redirections, the environment a command runs in, exit statuses and errors. Out of scope: the interactive line editor, history and completion; the behaviour of individual builtins beyond what the language depends on; z/OS file tagging and character conversion, which affect the bytes a file holds but not what a script means (see @zos). == Notation - Grammar productions are in EBNF: `a b` is sequence, `a | b` alternation, `[ a ]` optional, `{ a }` zero or more, `'x'` a literal token. Terminals in capitals (`WORD`, `NAME`, `NEWLINE`) are defined in @lexical. - #sem($e$) is the meaning of the phrase $e$: the value of an arithmetic expression, or the list of fields a word expands to. - A _byte_ is an octet of the input. zash is built for ASCII or for IBM-1047 (EBCDIC); every character named in this document by its glyph (such as `$` or newline) stands for that character's code in the build's character set. No rule depends on the numeric value of a code unless it says so. - Numbered rules are normative. _Note_ blocks are not. - *Open* blocks mark questions this draft has not decided. Each must be answered by reading the implementation or by a test before the rule it belongs to is final. == Rule identifiers Rules are numbered `R-`_chapter_`-`_n_. The chapter codes are `LEX` (lexical structure), `ALI` (aliases), `GRM` (grammar), `EXP` (word expansion), `ARI` (arithmetic), `PAT` (patterns), `CMD` (commands), `CND` (conditional expressions), `RED` (redirection), `ENV` (environment and variables), `ERR` (errors) and `SIG` (traps). An identifier, once published, is not reused for a different statement. #pagebreak() = Lexical structure == Input #rule("LEX")[ The input is a sequence of bytes, read from a file, a string (`-c`, `eval`, command substitution) or standard input. The byte value 0 (NUL) ends a line's text; behaviour after it within the same line is unspecified. ] #rule("LEX", tests: ("zash/stdin-script",), key: "stdin")[ When the input is standard input, zash reads no byte beyond the end of the command it is about to run. A command that reads standard input therefore sees the rest of the script. _Extension: POSIX allows a shell to read ahead._ ] #rule("LEX")[ A backslash immediately followed by newline, outside single quotes and outside `$'...'`, is removed together with the newline before tokenisation (line continuation). Inside a here-document body it is removed only when the delimiter was unquoted. ] == Tokens The lexer turns input into a sequence of tokens. A token is an _operator_, a _word_, an `IO_NUMBER` or `NEWLINE`. #rule("LEX")[ The operators are exactly: ``` control: & && ( ) ; ;; | || NEWLINE redirection: < > >| >> <> <& >& << <<- ``` The longest operator that matches the input is taken. There is no `;&`, `;;&`, `|&`, `&>` or `<<<`. ] #rule("LEX")[ Unquoted blanks (space and tab) separate tokens and are otherwise discarded. An unquoted `#` at the start of a token begins a comment that extends to, but does not include, the next newline. ] #rule("LEX", tests: ("posix/redir", "posix/fdmap"))[ A token consisting only of decimal digits, immediately followed by `<` or `>` with no blank between, is an `IO_NUMBER`. Only the values 0 to 9 name descriptors a script may use; a larger `IO_NUMBER` is an error when the redirection is performed (see @redirection). ] #rule("LEX")[ Any other token is a `WORD`. A `WORD` that is a valid `NAME` followed by `=` is an _assignment word_ when it appears where @grammar allows one. A `NAME` is a non-empty sequence of letters, digits and underscores that does not begin with a digit; letters are `a`--`z` and `A`--`Z` of the build's character set. ] == Quoting Quoting determines which characters are literal. Each byte of a word carries a _quoted_ flag that survives until field splitting and pathname expansion have used it (@expansion); nothing is encoded in the text. #rule("LEX", tests: ("posix/quoting",))[ *Backslash.* Outside quotes, `\c` makes `c` literal and quoted, for any `c` but newline (line continuation, above). ] #rule("LEX", tests: ("posix/quoting",))[ *Single quotes.* `'...'` makes every byte up to the next `'` literal and quoted. A single quote cannot occur inside. ] #rule("LEX", tests: ("posix/quoting", "posix/param-word"))[ *Double quotes.* Inside `"..."` every byte is quoted. `$` and backquote keep their meaning. A backslash keeps its meaning only before `$`, backquote, `"`, `\` and newline; elsewhere it is literal. Inside `"${...}"` a further pair of double quotes nests: `"${x:-"}"}"` is one word whose default is the string `}`. ] #rule("LEX", tests: ("zash/ansi-quote.ascii",), key: "dsq")[ *Dollar-single quotes.* `$'...'` is a quoted string in which these escapes are decoded when the word is read, and the result is literal and quoted: #table( columns: 2, inset: 4pt, stroke: 0.4pt + luma(180), [`\a \b \e \f \n \r \t \v`], [the control character so named (`\e` is escape)], [`\\` `\'` `\"` `\?`], [the character itself], [`\`_ooo_], [the byte with octal value _ooo_ (one to three digits)], [`\x`_hh_], [the byte with hexadecimal value _hh_ (one or two digits)], [`\c`_X_], [control-_X_, in ASCII builds only], [any other escape], [kept as written, backslash included], ) `$'...'` is recognised only where `$` would begin an expansion outside double quotes. Inside double quotes and in here-documents it is not special. _Extension: POSIX.1-2024 has `$'...'`; the set of escapes is zash's._ ] #open[ Does `\u` (and `\U`) in `$'...'` decode a code point? zash currently keeps it literally; bash, ksh93 and mksh encode UTF-8 and dash rejects it. Decide, then write the rule. ] == Reserved words #rule( "LEX", tests: ("posix/syntax", "zash/function-kw", "zash/cond"), key: "reserved", )[ The reserved words are ``` ! { } case do done elif else esac fi for function if in select then time until while [[ ]] ``` A word is recognised as reserved only when it is unquoted, is the whole token and appears where @grammar expects that reserved word (in particular, as the first word of a command, or `in`/`do` in the positions of `for` and `case`). Elsewhere it is an ordinary word. _Difference: `function`, `select`, `time`, `[[` and `]]` are reserved in zash, so no command can be named `function`._ ] == Here-documents #rule("LEX", tests: ("posix/heredoc", "posix/heredoc-edge"))[ For each `<<` or `<<-` operator, the word after it is the _delimiter_. The body is read starting at the line after the next `NEWLINE` token that is not itself inside a here-document, and consists of the lines up to (not including) a line equal to the delimiter after quote removal. Several here-documents on one line are read in order. ] #rule("LEX", tests: ("posix/heredoc", "posix/heredoc-edge"))[ If any part of the delimiter was quoted, the body is literal. Otherwise the body is expanded as if in double quotes, except that `"` is not special: parameter, command and arithmetic expansion are performed and `\` is special only before `$`, backquote, `\` and newline. ] #rule("LEX", tests: ("posix/heredoc",))[ With `<<-`, leading tab characters are removed from each body line and from the delimiter line before the comparison. ] #rule("LEX", tests: ("posix/heredoc-cmdsub", "zash/heredoc-fuzz"))[ A command substitution has its own here-document queue. A here-document started inside `$(...)` is read inside it, and one started outside is not satisfied by lines inside it. A `$(...)` that appears in a here-document body is parsed with the same rule. ] #rule("LEX", tests: ("posix/heredoc",))[ End of input before the delimiter line ends the body without error. zash does not warn about it (`bash` does). ] #pagebreak() = Aliases #rule("ALI", tests: ("zash/alias",))[ When a `WORD` that is unquoted and a valid alias name occurs where the first word of a simple command is expected, and an alias of that name is defined, the word is replaced by the alias's value, which is then read as input. ] #rule("ALI", tests: ("zash/alias",))[ If an alias's value ends in a blank, the next word is also checked for alias substitution. ] #rule("ALI", tests: ("posix/alias-cycle",))[ *Cycles.* While substituting, each alias may be used at most once in one chain of substitutions: a chain starts at a command word and continues only through values that end in a blank or that consist of a single word that is itself an alias. An alias already used in the current chain is left as an ordinary word. Thus `alias a=b b=a; a` runs a command named `a` (or `b`) and does not loop. ] #rule("ALI")[ Alias substitution happens when a command is parsed, not when it runs. An alias defined by a command takes effect for commands parsed after that command has run, never for the rest of the line or compound command that defined it. ] #pagebreak() = Grammar == Productions ``` program = linebreak [ complete_list ] ; complete_list = list [ separator ] ; list = and_or { separator_op linebreak and_or } ; and_or = pipeline { ( '&&' | '||' ) linebreak pipeline } ; pipeline = [ 'time' [ '-p' ] ] [ '!' ] pipe_sequence | 'time' [ '-p' ] ; (* time with no command *) pipe_sequence = command { '|' linebreak command } ; command = simple_command | compound_command { redirection } | function_definition ; compound_command = brace_group | subshell | arith_command | cond_command | for_clause | case_clause | if_clause | while_clause | until_clause ; brace_group = '{' compound_list '}' ; subshell = '(' compound_list ')' ; arith_command = '((' ARITH_TEXT '))' ; (* see the (( rule *) cond_command = '[[' cond_expr ']]' ; (* see the [[ ]] chapter *) for_clause = ( 'for' | 'select' ) NAME linebreak [ 'in' { WORD } sequential_sep ] do_group ; case_clause = 'case' WORD linebreak 'in' linebreak { case_item } 'esac' ; case_item = [ '(' ] pattern { '|' pattern } ')' ( compound_list | linebreak ) ( ';;' linebreak | (* before esac *) ) ; pattern = WORD ; if_clause = 'if' compound_list 'then' compound_list { 'elif' compound_list 'then' compound_list } [ 'else' compound_list ] 'fi' ; while_clause = 'while' compound_list do_group ; until_clause = 'until' compound_list do_group ; do_group = 'do' compound_list 'done' ; function_definition = NAME '(' ')' linebreak function_body | 'function' NAME linebreak function_body ; function_body = compound_command { redirection } ; simple_command = prefix [ WORD { WORD | redirection } ] | WORD { WORD | redirection } ; prefix = ( ASSIGNMENT_WORD | redirection ) { ASSIGNMENT_WORD | redirection } ; redirection = [ IO_NUMBER ] redir_op WORD ; redir_op = '<' | '>' | '>|' | '>>' | '<>' | '<&' | '>&' | '<<' | '<<-' ; compound_list = linebreak list [ separator ] ; separator_op = '&' | ';' ; separator = separator_op linebreak | newline_list ; sequential_sep = ';' linebreak | newline_list ; linebreak = [ newline_list ] ; newline_list = NEWLINE { NEWLINE } ; ``` == Rules attached to the grammar #rule("GRM", tests: ("posix/syntax",))[ The grammar above is that of POSIX XCU 2.10 with these changes: `time` and `!` prefixes on a pipeline, the `function` form of a function definition, `arith_command`, `cond_command` and `select` in place of `for`. A program that the grammar does not derive is a syntax error (@errors). ] #rule("GRM", tests: ("posix/syntax",))[ An `ASSIGNMENT_WORD` is recognised only in `prefix`, that is, before the command name. After the command name, `NAME=value` is an ordinary argument. ] #rule("GRM", tests: ("zash/function-kw",), key: "funcform")[ `function NAME body` and `NAME() body` define the same thing: a function whose body is the compound command with its redirections. The two forms are identical. _Difference: ksh gives the `function` form local traps and `$0`; zash does not._ ] #rule("GRM", tests: ("posix/case-edge",))[ In a `case_clause`, the last `case_item` may omit `;;` before `esac`. There is no fall-through operator. ] #rule("GRM")[ `for NAME do ...` and `for NAME; do ...` without `in` iterate over the positional parameters as they were when the loop started (@commands). ] #rule("GRM", status: "zash", tests: ("zash/select",), key: "select")[ `select NAME [in WORD ...] do LIST done` is the ksh88 menu loop, and zash is that shell's successor, so it is part of the language. It is the `for_clause` with `select` in place of `for`, and it repeats: + write the words to standard error, one per line, as the number of the word, a tab, and the word; + write the value of `PS3` (default `#? `) to standard error, with no newline, and flush; + read one line from standard input into `REPLY`, with the rules of `read` without `-r`; end of input ends the loop; + if the line is empty, repeat from the top; + if the line is a number in range, assign that word to `NAME`; otherwise assign the empty string; + run the list. The menu is written again before every prompt, not once per loop. _Difference: no other shell in scope has `select`._ ] #rule("GRM", tests: ("zash/arith-ext", "posix/subshell-edge"), key: "dparen")[ *Choosing between `((` and `( (`.* When `((` begins a command, the text up to the matching `))` is an `arith_command` unless one of the following holds, in which case the input is read as a subshell whose first command is itself a subshell: + a `;` occurs outside quotes before the matching `))`; + a word character (letter, digit, `_`, `$`, `"`, `'`) follows a word that ended in a letter, digit, `_` or `}`, with only blanks or newlines between them (two adjacent words: a command, not an expression); + the text exceeds 4096 bytes; + the text begins with more than 8 consecutive `(`; + a `)` that closes the outermost level is not immediately followed by a second `)`. The scan for the matching `))` honours quotes and backslashes. To be certain of nested subshells, write `( (`. _Difference: a heuristic; POSIX leaves `((` unspecified._ ] #note[ The parser decides this with a bounded scan of the characters. A formalisation should state the rule as a decidable predicate on the character sequence and prove that the parser applies it. ] #rule("GRM", tests: ("posix/cmdsub",))[ `$((` always begins arithmetic expansion. Write `$( (` for a command substitution that begins with a subshell. ] #pagebreak() = Word expansion == Words and fields A word, as parsed, is a list of _parts_. A part is literal text, a parameter expansion, a command substitution or an arithmetic expansion, and each part carries a _quoted_ flag. Expansion turns a word into a list of _fields_; each byte of a field carries a quoted flag inherited from the part that produced it. Formally, let $B$ be the set of bytes and $Q = B times {0, 1}$ the set of flagged bytes. A field is a finite sequence in $Q^*$, and $ sem(w) : "Word" -> ("Field")^* $ is computed in the four steps below. Quote removal is the projection $pi_1$ from $Q^*$ to $B^*$ applied to every resulting field. #rule("EXP", tests: ("posix/expand-edge", "posix/edge"), key: "order")[ *Order.* For each word, the shell performs + tilde expansion, parameter expansion, command substitution and arithmetic expansion, in one left-to-right pass over the parts; + field splitting of the results of unquoted expansions (step 1 only); + pathname expansion of each field that contains an unquoted pattern character; + quote removal. No byte that came from the text of the script is ever split, and no quoted byte is ever split or treated as a pattern character. ] #rule("EXP", tests: ("posix/expand-edge",))[ *Contexts without splitting.* In assignments (`NAME=word`), the word of a `case`, the target of a redirection other than a here-document, the operands of `[[ ]]` and the word in `${x op word}`, steps 2 and 3 are not performed and the result is one field. (A redirection target that would expand to more than one field is still one field.) ] == Tilde expansion #rule("EXP", tests: ("posix/misc", "posix/param-word"))[ An unquoted `~` at the start of a word, followed by the characters up to the first unquoted `/` (or the end of the word), is a tilde-prefix. `~` alone is replaced by `$HOME`; `~name` by the home directory of user _name_. If the user does not exist the prefix is left unchanged. The result is quoted (it is not split or globbed). ] #rule("EXP", tests: ("posix/misc",))[ In an assignment word, tilde expansion is also performed after each unquoted `:` in the value. ] #rule("EXP", tests: ("posix/param-word",))[ The word in `${x-word}`, `${x=word}`, `${x?word}` and `${x+word}` (and their `:` forms) undergoes tilde expansion when it is not within double quotes. ] == Parameter expansion #rule("EXP", tests: ("posix/params",))[ A parameter is a `NAME` (a variable), a positional parameter (a decimal number; more than one digit requires braces: `${10}`), or one of the special parameters `@ * # ? - $ !` and `0`. ] #rule("EXP", tests: ("posix/params", "posix/expand-edge"))[ The conditional forms, for a parameter $x$ and a word $w$, yield: #table( columns: 4, inset: 4pt, stroke: 0.4pt + luma(180), [*form*], [*$x$ set, non-empty*], [*$x$ set, empty*], [*$x$ unset*], [`${x:-w}`], [$x$], [#sem($w$)], [#sem($w$)], [`${x-w}`], [$x$], [empty], [#sem($w$)], [`${x:=w}`], [$x$], [assign #sem($w$)], [assign #sem($w$)], [`${x=w}`], [$x$], [empty], [assign #sem($w$)], [`${x:?w}`], [$x$], [error], [error], [`${x?w}`], [$x$], [empty], [error], [`${x:+w}`], [#sem($w$)], [empty], [empty], [`${x+w}`], [#sem($w$)], [#sem($w$)], [empty], ) _assign_ sets $x$ to the value and yields it; a positional or special parameter cannot be assigned to this way; attempting to do so is an error. _error_ writes #sem($w$), or a default message if $w$ is empty, and is an expansion error (@errors). The word $w$ is expanded only when its value is used. ] #rule("EXP", tests: ("posix/params",))[ `${#x}` is the length of the value of $x$ in bytes, as a decimal number. `${#*}` and `${#@}` are the number of positional parameters. ] #rule("EXP", tests: ("posix/params", "zash/trim-long", "zash/trim-all"), key: "trim")[ *Trimming.* For a pattern $p$ (the word, expanded, with its quoted bytes literal): - `${x#p}` removes the shortest prefix of $x$ that $p$ matches; - `${x##p}` removes the longest such prefix; - `${x%p}` removes the shortest matching suffix; - `${x%%p}` removes the longest matching suffix. If no prefix (suffix) matches, the value is unchanged. Matching is that of @patterns, applied to the whole candidate prefix or suffix. For `${@#p}`, `${*#p}` and the other three operators the trim applies to each positional parameter on its own, before the results are joined the way `$@` and `$*` are joined below: quoted `@` gives one field per parameter, quoted `*` joins them with the first character of `IFS`, and an unquoted expansion is split. ] #note[ zash computes a trim in one pass for patterns of up to 63 elements and tries each length otherwise. Both methods must give the shortest or longest match this rule defines. That proof is the first theorem planned for the Lean model. ] #rule("EXP", tests: ("zash/ash-differences",))[ With `set -u`, expanding an unset parameter other than `@` and `*`, except in a conditional form that handles unset, is an expansion error. ] #rule("EXP", tests: ("posix/expand-edge", "posix/split"))[ *`$@` and `$*`.* Unquoted, each positional parameter becomes a separate field before field splitting, and each is then split. Quoted, `"$@"` yields one field per positional parameter, with any adjacent text of the word joined to the first and last of them, and no field at all when there are none; `"$*"` yields one field: the parameters joined by the first character of `IFS` (by nothing if `IFS` is empty, by a space if `IFS` is unset). ] #open[ Unquoted `$@` and `$*` in a here-document body and in other no-splitting contexts. Differential testing showed zash treating quote characters there differently from dash, bash and ksh93. Decide which behaviour is intended, then write the rule. ] == Command substitution #rule("EXP", tests: ("posix/cmdsub",))[ `$(list)`, and the older backquoted form, run _list_ in a subshell environment and are replaced by its standard output with every trailing newline removed. `$(...)` is parsed when the enclosing word is read; the backquoted form is parsed after backquote backslash processing. ] #rule("EXP", tests: ("zash/purebuiltin", "zash/cmdsub-file"))[ `$( #rule("PAT", tests: ("posix/case-edge", "posix/glob-edge"))[ A pattern is a sequence of elements. Each unquoted byte is: - `*`: matches any sequence of bytes, including the empty one; - `?`: matches any one byte; - `[`: begins a bracket expression (below) if a matching `]` follows; otherwise it is literal; - anything else: matches itself. A quoted byte always matches only itself. ] #rule("PAT", tests: ("posix/case-edge", "posix/charset"), key: "bracket")[ A bracket expression `[...]` matches one byte that is in its set. If its first byte is `!` or `^`, it matches one byte that is not in the set. A `]` in the first position (immediately after any negation) is a literal member. `a-b` is a range: all bytes whose code is between those of $a$ and $b$ inclusive, _in the build's character set_. `[:class:]` adds the bytes of a character class: `alnum alpha blank cntrl digit graph lower print punct space upper xdigit`. _Difference: `^` as negation is not POSIX._ ] #rule("PAT", tests: ("posix/collate.ascii",), key: "byteorder")[ Ranges and the collating order of pathname expansion use byte codes, not the locale. In an EBCDIC build `[a-z]` therefore contains more than the 26 lower-case letters; scripts that must be portable use `[[:lower:]]`. ] #rule("PAT", key: "match")[ For a pattern $p$ and a string $s$, $"match"(p, s)$ holds when $p$ matches the whole of $s$. It is defined by: $ "match"(epsilon, s) & <==> s = epsilon \ "match"(* p', s) & <==> exists i. "match"(p', s[i..]) \ "match"(e p', c s') & <==> e "matches" c and "match"(p', s') $ where $e$ is `?`, a bracket expression or a literal byte. ] #pagebreak() = Arithmetic == Syntax ``` expr = assign { ',' assign } ; assign = cond | LVALUE assign_op assign ; assign_op= '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|=' ; cond = lor [ '?' expr ':' cond ] ; lor = land { '||' land } ; land = bor { '&&' bor } ; bor = bxor { '|' bxor } ; bxor = band { '^' band } ; band = equ { '&' equ } ; equ = rel { ( '==' | '!=' ) rel } ; rel = shift { ( '<' | '<=' | '>' | '>=' ) shift } ; shift = add { ( '<<' | '>>' ) add } ; add = mul { ( '+' | '-' ) mul } ; mul = unary { ( '*' | '/' | '%' ) unary } ; unary = ( '+' | '-' | '!' | '~' ) unary | ( '++' | '--' ) LVALUE | postfix ; postfix = primary | LVALUE ( '++' | '--' ) ; primary = NUMBER | LVALUE | '(' expr ')' ; LVALUE = NAME ; NUMBER = decimal | '0' octal_digits | ( '0x' | '0X' ) hex_digits ; ``` Blanks and newlines between tokens are ignored. == Values #rule("ARI", tests: ("posix/arith", "posix/arith-edge"), key: "wrap")[ Values are 64-bit two's-complement integers. Every operation is computed modulo $2^64$ and the result is taken as signed: overflow wraps and is not an error. In particular $ sem(a + b) = "signed"((sem(a) + sem(b)) mod 2^64) $ and likewise for `-`, `*`, unary `-` and `<<`. ] #rule("ARI", tests: ("posix/arith-edge",))[ `/` truncates toward zero and `%` has the sign of the dividend. A right operand of 0 for `/` or `%` is an error. The quotient of the most negative value by $-1$ is the most negative value (it wraps). ] #rule("ARI", tests: ("posix/arith-edge",))[ Shift counts are taken modulo 64. `>>` is an arithmetic shift. ] #rule("ARI", tests: ("posix/arith",), key: "shortcircuit")[ Relational, equality and logical operators yield 1 for true and 0 for false. `&&`, `||` and `?:` evaluate their right (or untaken) operand only when needed; an assignment in an operand that is not evaluated does not happen. ] #rule("ARI", tests: ("zash/arith-ext", "zash/ash-differences"), key: "arivars")[ *Variables.* A `NAME` in an expression stands for the value of that variable: 0 if it is unset or empty; otherwise the value is itself evaluated as an arithmetic expression. Such nested evaluation may go 16 levels deep; exceeding this depth is an error ("expression recursion too deep"). ] #rule("ARI", tests: ("zash/arith-ext",), key: "arincr")[ `++`, `--`, the compound assignments and `,` are as in C. An assignment stores the decimal value in the variable and yields it. Assigning to a read-only variable is an error. _Extension: POSIX requires neither `++`/`--` nor `,`._ ] #rule("ARI", tests: ("posix/arith-edge",))[ A `NUMBER` that does not fit in 64 bits, or text that the syntax does not derive, is an error. ] #rule("ARI", tests: ("zash/arith-base",), key: "aribase")[ _Extension._ `base#number`, as in `bash` and `ksh93`: the number is read in `base`, 2 to 64, with the digits `0`-`9` (0 to 9), `a`-`z` (10 to 35), `A`-`Z` (36 to 61), `@` (62) and `_` (63). A base outside 2 to 64, no digits at all, a digit not in the base, or a number that does not fit in 64 bits is an error. POSIX requires none of this; `16#ff` is the form scripts use. ] #pagebreak() = Commands == Exit status #rule("CMD")[ Every command has an exit status, an integer from 0 to 255. Zero is _true_ (success), anything else _false_. `$?` is the status of the most recently completed pipeline. ] #rule("CMD", tests: ("posix/execfail",))[ For a simple command the status is the program's exit status, except: 127 if the command was not found; 126 if it was found but could not be run; $128 + n$ if it was ended by signal $n$; 2 if a redirection on it failed; the status of the last command substitution if the command had no command name; 0 if it had neither. ] == Simple commands #rule("CMD", tests: ("posix/vars", "posix/redir"))[ A simple command is performed in this order: + the words that are not assignments or redirections are expanded (@expansion); the first field, if any, is the command name; + redirections are performed, left to right (@redirection); + each assignment is expanded and applied, left to right. If there is no command name, the assignments affect the current shell and redirections are performed and undone. ] #rule("CMD", tests: ("posix/functions", "posix/misc-builtins"))[ *Command search.* A command name without `/` is looked up in this order: special builtin; function; regular builtin; then the directories of `PATH`, left to right, selecting the first executable file found. An empty `PATH` entry means the current directory. A name containing `/` is run as that path. A path found in `PATH` is remembered; it is looked up again if running it fails with "no such file" or "not a directory". ] #rule("CMD", tests: ("posix/execfail", "scripts/library"))[ If the system refuses to execute a file because it is not an executable format, and the file begins with `#!`, the interpreter named on that line is run with the file as its argument; otherwise zash runs the file as a script in a new zash process, with the same arguments. ] #rule("CMD", tests: ("posix/vars", "posix/functions"))[ *Assignments before a command.* For an external command they are put in that command's environment only. For a special builtin they affect the current shell and persist. For a function or a regular builtin they are in effect while it runs and are then undone. ] #rule("CMD", tests: ("posix/command-special",))[ The special builtins are `: . break continue eval exec exit export readonly return set shift times trap unset`. An error in a special builtin is a fatal error in a non-interactive shell (@errors), except when the builtin was run through `command`, in which case the error is only the command's status. ] == Pipelines #rule("CMD", tests: ("posix/pipes",))[ In `c1 | c2 | ... | cn`, the standard output of each command is connected to the standard input of the next. The commands run concurrently. The status is that of `cn`, unless `set -o pipefail` is on, in which case it is that of the last command that failed, or 0. ] #rule("CMD", tests: ("zash/lastpipe", "posix/pipes"), key: "laststage")[ *The last stage.* When job control is off, `cn` runs in the current shell environment if it is not an external command: assignments and `cd` in it persist after the pipeline. Every other stage runs in a subshell environment. When job control is on (`set -m`), every stage runs in a subshell environment. _Difference: dash and bash run every stage in a subshell; this is the ksh and z/OS `/bin/sh` behaviour._ ] #rule("CMD", tests: ("posix/control",))[ `! pipeline` has status 0 if the pipeline's status is not 0, and 1 otherwise. ] #rule("CMD", tests: ("zash/zos-options",))[ `time pipeline` runs the pipeline and then writes to standard error the real time and the user and system CPU time it used, shell and children. `-p` selects the POSIX format. `time` alone reports the shell's own totals. The status is the pipeline's. ] == Lists #rule("CMD", tests: ("posix/control",))[ `a && b` runs `b` only if `a` succeeded; `a || b` only if it failed. The status is that of the last command run. `;` and newline run commands in sequence. ] #rule("CMD", tests: ("zash/jobs",))[ `c &` runs `c` asynchronously in a subshell environment, with standard input from `/dev/null` when job control is off and no input redirection is given. `$!` is set to the process ID of `c` (of its last stage, for a pipeline). The status of `c &` itself is 0. ] == Compound commands #rule("CMD", tests: ("posix/subshell-edge",), key: "subshell")[ `( list )` runs _list_ in a subshell environment: nothing it changes (variables, functions, options, directory, traps, open files) is visible afterwards. `{ list; }` runs _list_ in the current environment. The status of each is that of _list_. ] #rule("CMD", tests: ("posix/control", "posix/for-set"))[ `for x in w1 ... wn; do body; done` expands the words (with field splitting and pathname expansion) once, then for each resulting field assigns it to _x_ and runs _body_. Without `in`, the fields are the positional parameters as they were when the loop started; changing them inside the body (for example with `set --`) does not change the iteration. The status is that of the last _body_ run, or 0 if none ran. ] #rule("CMD", tests: ("posix/case-edge",))[ `case w in ...` expands _w_ once (without splitting or globbing) and runs the body of the first item with a matching pattern (expanded likewise; @patterns). Status: that of the body run, or 0 if none matched. ] #rule("CMD", tests: ("posix/control",))[ `if`, `while` and `until` are as in POSIX. The status of a loop is that of the last body run, or 0 if none ran. ] #rule("CMD", tests: ("posix/control",))[ `break n` and `continue n` (default 1) leave, or go to the next iteration of, the _n_-th enclosing loop. An _n_ larger than the depth refers to the outermost loop. ] #rule("CMD", tests: ("zash/arith-ext",))[ `(( expr ))` evaluates _expr_ (@arithmetic). Its status is 0 if the value is not zero and 1 if it is zero; 2 on an error. ] == Functions #rule("CMD", tests: ("posix/functions", "posix/func-edge"))[ Defining a function stores its body; running the definition has status 0. Calling it runs the body with the positional parameters set to the call's arguments, and restores them afterwards. `$0` is unchanged. ] #rule("CMD", tests: ("posix/func-edge", "zash/ash-differences"), key: "return")[ `return n` ends the function with status _n_ modulo 256 (so `return 300` gives 44); `return` alone uses `$?`. ] #rule("CMD", tests: ("zash/local", "zash/typeset"), key: "local")[ `local NAME` and `typeset NAME` inside a function make _NAME_ local to that call: its previous value and attributes are restored when the function returns. Callees see the local value (dynamic scope). ] #pagebreak() = Conditional expressions `[[ ]]` ``` cond_expr = cond_or ; cond_or = cond_and { '||' cond_and } ; cond_and = cond_not { '&&' cond_not } ; cond_not = '!' cond_not | cond_prim ; cond_prim = '(' cond_expr ')' | UNARY_OP WORD | WORD BINARY_OP WORD | WORD ; UNARY_OP = '-a' | '-b' | '-c' | '-d' | '-e' | '-f' | '-g' | '-G' | '-h' | '-k' | '-L' | '-n' | '-o' | '-O' | '-p' | '-r' | '-s' | '-S' | '-t' | '-u' | '-v' | '-w' | '-x' | '-z' ; BINARY_OP = '=' | '==' | '!=' | '=~' | '<' | '>' | '-eq' | '-ne' | '-lt' | '-le' | '-gt' | '-ge' | '-nt' | '-ot' | '-ef' ; ``` Newlines are allowed before `]]` and after `&&` and `||`. Inside `[[ ]]`, `<`, `>`, `(` and `)` are operators, not redirections or subshells. #rule("CND", tests: ("zash/cond",))[ The operands of `[[ ]]` are expanded without field splitting and without pathname expansion, and only when the evaluation reaches them: `&&` and `||` do not expand an operand they do not need. ] #rule("CND", tests: ("zash/cond",))[ `a = b`, `a == b` and `a != b`: _b_ is a pattern (@patterns), with its quoted bytes literal. `a =~ b`: _b_ is a POSIX extended regular expression, matched anywhere in _a_; quoted parts of _b_ are literal; an invalid expression gives status 2. ] #rule("CND", tests: ("zash/cond",))[ `<` and `>` compare by byte value. `-eq` and the other numeric operators evaluate both operands as arithmetic expressions (@arithmetic). `-o name` is true if the option is on; `-v name` if the variable is set; the remaining unary operators are those of `test`. A lone `WORD` is true if it is not empty. ] #rule("CND", tests: ("zash/ash-differences",), key: "nt")[ `f1 -nt f2` is true if _f1_ exists and _f2_ does not, or both exist and _f1_ is newer; `-ot` is the converse (POSIX.1-2024). ] #rule("CND", tests: ("zash/cond",))[ The status of `[[ e ]]` is 0 if _e_ is true, 1 if false, 2 on a syntax or evaluation error. ] #pagebreak() = Redirection #rule("RED", tests: ("posix/redir", "posix/redir-edge"))[ Redirections are performed left to right. The descriptor _n_ is the `IO_NUMBER` if given, otherwise 0 for `<`, `<>`, `<&`, `<<`, `<<-` and 1 for the others. The target word is expanded as one field (@expansion). #table( columns: 2, inset: 4pt, stroke: 0.4pt + luma(180), [`nf`], [create or truncate _f_; an error if `set -C` is on and _f_ is an existing regular file], [`n>|f`], [as `>`, ignoring `set -C`], [`n>>f`], [open _f_ for appending, creating it if it does not exist], [`n<>f`], [open _f_ for reading and writing, creating it if it does not exist], [`n<&m`, `n>&m`], [make _n_ a copy of descriptor _m_; `-` closes _n_], [`n< #rule("ENV", tests: ("posix/vars",))[ A variable has a name, a value (a byte string) and attributes: _exported_, _read-only_, _integer_. Exported variables are passed in the environment of commands the shell runs. At startup every environment entry with a valid name becomes an exported variable. ] #rule("ENV", tests: ("posix/vars",))[ Assigning to a read-only variable, or unsetting one, is an error. ] #rule("ENV", tests: ("zash/typeset", "zash/let"))[ Assigning to an _integer_ variable (`typeset -i`, `integer`) evaluates the value as an arithmetic expression and stores the decimal result. ] #rule("ENV", tests: ("zash/dynvars",))[ `RANDOM` yields a pseudo-random integer from 0 to 32767 on each expansion; assigning to it sets the seed. `SECONDS` yields the whole seconds since the shell started, or since it was last assigned plus the assigned value. Unsetting either removes the special behaviour. ] #rule("ENV")[ A shell started interactively, and not set-user-ID or set-group-ID, expands `ENV` by parameter expansion and reads the resulting file before its first command. A set-ID shell ignores `ENV`. ] #rule("ENV", tests: ("zash/options",))[ The options are those of `set`: `-a -b -C -e -f -h -m -n -u -v -x`, and by name `allexport errexit ignoreeof monitor noclobber noexec noglob nolog notify nounset pipefail trackall verbose vi emacs xtrace`. `notify`, `trackall` and `nolog` are accepted and have no effect. The z/OS build adds `jobnames`, `shareas`, `msgid` and `pipetag` (@zos). ] #pagebreak() = Errors #rule("ERR", tests: ("posix/errexit", "posix/command-special", "posix/invoke"))[ The consequence of an error depends on its kind and on whether the shell is interactive: #table( columns: 3, inset: 4pt, stroke: 0.4pt + luma(180), [*error*], [*non-interactive*], [*interactive*], [syntax error], [exit, status 2], [status 2, next command], [special builtin error], [exit], [status, next command], [redirection error on a special builtin], [exit], [status 2], [redirection error on any other command], [status 2], [status 2], [variable assignment error], [exit], [status, next command], [expansion error], [exit], [status, next command], [command not found], [status 127], [status 127], ) An error that exits the shell runs the `EXIT` trap first. ] #rule("ERR", status: "zash", tests: ("zash/script-errors",))[ *Input that cannot be read.* A script named on the command line that cannot be opened is reported on standard error and the shell exits at once: 127 if the name does not exist, 126 if it exists but cannot be opened, including when it is a directory. Once a script, `.` file or standard input is being read, a read error is a fatal error (status 2, after the `EXIT` trap) and end of input is not. ] #rule("ERR", tests: ("posix/errexit", "posix/errexit-edge"))[ *errexit.* With `set -e`, when a pipeline (or a single command) fails, the shell exits with its status, unless the failing command is: part of the condition of `if`, `while` or `until`; part of an `&&` or `||` list other than the last command; or preceded by `!`. The exemption extends to everything executed within those positions, including function bodies. ] #rule("ERR", tests: ("posix/command-special",))[ `command` before a special builtin makes errors inside it (including errors in `eval`ed or `.`-read text) set the status instead of exiting the shell. `exit` still exits. ] #rule("ERR", status: "zash", tests: ("zash/errtrap",), key: "errtrap")[ *ERR trap.* When a command fails in a position where `errexit` would apply, the `ERR` trap, if set, runs before `errexit` exits the shell. ] #pagebreak() = Traps and signals #rule("SIG", tests: ("posix/traps", "scripts/signals"))[ `trap action sig...` sets _action_ to run when a signal arrives. The action runs after the command being executed completes, not in the middle of it, and with `$?` equal to that command's status; afterwards `$?` is restored. An action of `-` resets to the default, and an empty action ignores the signal. ] #rule("SIG", tests: ("posix/trap-input",))[ A trap that becomes due while the shell is reading a command runs before that command and does not disturb the command being read. ] #rule("SIG", tests: ("posix/subshell-edge",), key: "trapsub")[ A subshell resets traps to their defaults, except that ignored signals stay ignored. _Difference: in a pipeline stage or `$( )`, `trap` with no arguments lists the parent shell's traps until the subshell sets one of its own._ ] #rule("SIG", tests: ("posix/invoke",))[ The `EXIT` trap (signal 0) runs when the shell exits, whether by `exit`, end of input or a fatal error. ] #pagebreak() = z/OS These rules hold only for the z/OS builds. They affect only character encoding and process creation, not script semantics. #rule("ENV", status: "z/OS")[ The build is ASCII (ISO8859-1) or EBCDIC (IBM-1047), fixed at compile time. Script text is interpreted in the build's character set. An untagged script whose first block looks like the other character set is converted when it is read. ] #rule("ENV", status: "z/OS")[ `set -o jobnames`, `shareas`, `msgid`, `pipetag` and the variables `_TAG_REDIR_IN`, `_TAG_REDIR_OUT`, `_TAG_REDIR_ERR`, `_BPX_SHAREAS`, `_BPX_JOBNAME` and `ZOS_*` change process attributes and file tags. They are specified in DESIGN.md, "The z/OS layer", not here. ] #pagebreak() = Differences from POSIX and other shells #table( columns: (auto, 1fr), inset: 4pt, stroke: 0.4pt + luma(180), [*rule*], [*difference*], [#rref("stdin")], [standard input is never read ahead of the running command], [#rref("dsq")], [`$'...'` escapes, `\c`_X_ in ASCII builds only], [#rref("reserved")], [`function`, `time`, `[[`, `]]` are reserved], [#rref("funcform")], [`function` form has no ksh-style local traps or `$0`], [#rref("dparen")], [heuristic choice between `((` and `( (`], [#rref("bracket")], [`[^...]` negates], [#rref("byteorder")], [ranges and sorting by byte code, not locale], [#rref("arincr")], [`++`, `--` and `,`], [#rref("arivars")], [variable values evaluated as expressions, 16 levels deep], [#rref("laststage")], [last pipeline stage in the current shell], [#rref("return")], [`return 300` gives 44], [#rref("local")], [`local`, `typeset` with dynamic scope], [#rref("nt")], [`-nt` true against a missing file], [#rref("errtrap")], [`ERR` trap], [#rref("trapsub")], [`trap` in a subshell lists the parent's traps], ) #note[ The identifiers in this table are looked up from the rules themselves, so they stay right when rules are added. ] = Mapping to a formal model Each chapter becomes one Lean module. The first things to formalise: #table( columns: (auto, 1fr), inset: 4pt, stroke: 0.4pt + luma(180), [*chapter*], [*what to formalise first*], [Patterns], [`match` as an inductive predicate (#rref("match")); prove the trimming rule (#rref("trim")) correct for the shortest and longest match], [Arithmetic], [the grammar as an inductive type and #sem($e$) as a total function into `Int64`; prove #rref("wrap") (wrapping) and #rref("shortcircuit") (unevaluated operands have no effect)], [Field splitting], [#rref("split") as a function on flagged bytes; prove that quoted bytes are never split (#rref("order"))], [Grammar], [the productions as an inductive type; the `((` rule (#rref("dparen")) as a decidable predicate], [Commands], [a small-step semantics over an environment; last-stage and subshell isolation as theorems (#rref("laststage"), #rref("subshell"))], ) Differential testing then checks the C code against the model, with the existing suite and random inputs. CBMC checks the smallest pieces.