summaryrefslogtreecommitdiffhomepage
path: root/formal/zash-spec.typ
blob: b2ac5943d66b38a65db0fb7c5520996c80bdf456 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
// 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 <lexical>

== 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 <reserved>

#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 <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 <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 <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"))[
  `$(<file)` is replaced by the contents of _file_, with trailing newlines
  removed, as if by `$(cat file)`. A file that cannot be opened is an
  expansion error.
]

#note[
  Whether a substitution creates a process is not part of the language;
  zash runs many of them in the shell. The observable behaviour must be
  that of a subshell: assignments and `cd` inside do not affect the
  caller. The process-accounting tests (`tests/proc/`) check the cost,
  and are not cited by rules.
]

== Arithmetic expansion

#rule("EXP", tests: ("posix/arith",))[
  `$((expression))` is replaced by the decimal value of the expression
  (@arithmetic). The text of the expression first undergoes parameter
  expansion, command substitution and quote removal, as in double
  quotes.
]

== Field splitting

Let $I$ be the value of `IFS` (if unset, space, tab and newline). Bytes
of $I$ that are space, tab or newline are _IFS white space_; the others
are _IFS delimiters_.

#rule("EXP", tests: ("posix/split",), key: "split")[
  Only unquoted bytes that came from an unquoted expansion are
  considered. If $I$ is empty, no splitting is done. Otherwise:
  + IFS white space at the start and end of the expansion result is
    ignored;
  + each IFS delimiter, with any IFS white space next to it, ends a field;
  + each other sequence of IFS white space ends a field;
  + a field is produced between two delimiters even if it is empty, but no
    empty field is produced at the end.
]

#rule("EXP", tests: ("posix/split",))[
  A word whose expansion produces no bytes at all and contains no quoted
  part produces no field (it disappears). A word with a quoted part that
  is empty (`""`) produces one empty field.
]

== Pathname expansion

#rule("EXP", tests: ("posix/glob", "posix/glob-edge"))[
  A field containing an unquoted `*`, `?` or `[` is a pattern (@patterns)
  matched against pathnames. `/` is never matched by a pattern
  character; each slash-separated component is matched separately. A
  component beginning with `.` is matched only by a pattern component
  beginning with an unquoted `.`. The matches replace the field, in the
  collating order of @patterns. If nothing matches, the field is left
  as it is.
]

#rule("EXP", tests: ("posix/glob",))[
  With `set -f`, pathname expansion is not performed.
]

#pagebreak()

= Patterns <patterns>

#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 <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 <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 `[[ ]]` <conditional>

```
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 <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),
    [`n<f`], [open _f_ for reading],
    [`n>f`],
    [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<<d`, `n<<-d`],
    [open the here-document body for reading on
      descriptor _n_],
  )
]

#rule("RED", tests: ("posix/fdmap",))[
  Descriptors 0 to 9 are available to scripts. A redirection of a larger
  descriptor, or a duplication from a descriptor that is not open, is a
  redirection error.
]

#rule("RED", tests: ("posix/redir",))[
  A redirection on a compound command or a function definition applies to
  the whole command each time it runs, and is undone after it.
]

#rule("RED", tests: ("posix/redir",))[
  `exec` with only redirections applies them to the current shell
  permanently.
]

#pagebreak()

= Environment and variables <environment>

#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 <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 <traps>

#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 <zos>

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 <differences>

#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.