@amritk/nish-x86_64-linux 0.44.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/INSTALL.md +3 -1
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +18 -16
  4. package/package.json +1 -1
  5. package/runtime/core/numbers.mjs +3 -1
  6. package/runtime/core/strings.mjs +90 -38
  7. package/runtime/core.d.ts +8 -0
  8. package/runtime/core.mjs +16 -0
  9. package/runtime/nish.d.ts +88 -5
  10. package/runtime/nish.h +10 -0
  11. package/runtime/nish.mjs +5 -0
  12. package/runtime/runtime-host.c +15 -0
  13. package/runtime/runtime-net.c +223 -4
  14. package/runtime/runtime-os.c +15 -1
  15. package/runtime/runtime-uring.c +291 -31
  16. package/runtime/sqlite/nish-sqlite.c +301 -128
  17. package/std/README.md +15 -15
  18. package/std/array.ts +10 -2
  19. package/std/bytes.ts +239 -26
  20. package/std/cli-args.ts +1072 -606
  21. package/std/cli-flags.ts +180 -98
  22. package/std/cli.ts +21 -13
  23. package/std/collections.ts +245 -127
  24. package/std/compress/checksum.ts +32 -37
  25. package/std/compress/deflate.ts +1102 -542
  26. package/std/compress/gzip.ts +290 -145
  27. package/std/compress/zlib.ts +57 -21
  28. package/std/crypto/aes.ts +153 -75
  29. package/std/crypto/base64url.ts +84 -61
  30. package/std/crypto/bcrypt-batch.ts +164 -90
  31. package/std/crypto/bcrypt.ts +185 -107
  32. package/std/crypto/chacha20poly1305.ts +84 -68
  33. package/std/crypto/ct.ts +9 -7
  34. package/std/crypto/ed25519.ts +64 -27
  35. package/std/crypto/hkdf.ts +105 -63
  36. package/std/crypto/hmac.ts +95 -89
  37. package/std/crypto/jwt.ts +248 -126
  38. package/std/crypto/p256.ts +758 -444
  39. package/std/crypto/p384.ts +20 -13
  40. package/std/crypto/pki-roots.ts +95 -38
  41. package/std/crypto/pki.ts +164 -60
  42. package/std/crypto/rsa.ts +266 -223
  43. package/std/crypto/scram.ts +3 -4
  44. package/std/crypto/sha1.ts +107 -65
  45. package/std/crypto/sha256.ts +502 -422
  46. package/std/crypto/sha512.ts +204 -135
  47. package/std/crypto/x509-random.ts +9 -3
  48. package/std/crypto/x509.ts +331 -171
  49. package/std/json-equal.ts +35 -19
  50. package/std/json-format.ts +215 -108
  51. package/std/json-number.ts +126 -72
  52. package/std/json-pointer.ts +42 -13
  53. package/std/json-tokenizer.ts +498 -307
  54. package/std/json-typed.ts +115 -36
  55. package/std/json-value.ts +341 -152
  56. package/std/json.ts +300 -158
  57. package/std/net/buffer-pool.ts +17 -7
  58. package/std/net/dns-config.ts +427 -236
  59. package/std/net/dns-message.ts +114 -47
  60. package/std/net/dns-resolver.ts +736 -237
  61. package/std/net/dns.ts +205 -52
  62. package/std/net/fetch.ts +320 -184
  63. package/std/net/grpc.ts +948 -0
  64. package/std/net/handler.ts +1315 -222
  65. package/std/net/hpack.ts +395 -180
  66. package/std/net/http-compress.ts +502 -65
  67. package/std/net/http-fields.ts +85 -49
  68. package/std/net/http-server.ts +1764 -602
  69. package/std/net/http1-client-codec.ts +372 -161
  70. package/std/net/http1-codec.ts +665 -331
  71. package/std/net/http1-server.ts +660 -278
  72. package/std/net/http2-cleartext.ts +165 -95
  73. package/std/net/http2-frame.ts +232 -89
  74. package/std/net/http2-tls.ts +42 -12
  75. package/std/net/http2.ts +327 -101
  76. package/std/net/http3-frame.ts +68 -33
  77. package/std/net/http3-server.ts +647 -192
  78. package/std/net/http3.ts +667 -189
  79. package/std/net/oidc.ts +63 -24
  80. package/std/net/outbound.ts +207 -142
  81. package/std/net/postgres-async.ts +1165 -443
  82. package/std/net/postgres-carrier.ts +575 -372
  83. package/std/net/postgres.ts +1459 -559
  84. package/std/net/prefork.ts +254 -98
  85. package/std/net/protobuf.ts +1017 -0
  86. package/std/net/qpack.ts +143 -92
  87. package/std/net/quic-conn-ack.ts +50 -18
  88. package/std/net/quic-conn-cid.ts +66 -26
  89. package/std/net/quic-conn-params.ts +13 -7
  90. package/std/net/quic-datagram.ts +90 -27
  91. package/std/net/quic-frame.ts +225 -124
  92. package/std/net/quic-listener.ts +197 -89
  93. package/std/net/quic-packet.ts +289 -163
  94. package/std/net/quic-recovery.ts +279 -128
  95. package/std/net/quic-stream.ts +466 -167
  96. package/std/net/quic.ts +568 -257
  97. package/std/net/router.ts +450 -99
  98. package/std/net/serve.ts +651 -232
  99. package/std/net/static.ts +1458 -0
  100. package/std/net/tls/client.ts +140 -45
  101. package/std/net/tls/codec.ts +510 -260
  102. package/std/net/tls/record-client.ts +268 -76
  103. package/std/net/tls/record-server.ts +236 -79
  104. package/std/net/tls/record.ts +173 -47
  105. package/std/net/tls/schedule.ts +58 -39
  106. package/std/net/tls/ticket.ts +295 -103
  107. package/std/net/tls/verify.ts +1 -1
  108. package/std/net/tls-tcp.ts +218 -75
  109. package/std/net/tls.ts +260 -152
  110. package/std/net/upstream.ts +283 -86
  111. package/std/net/url.ts +277 -102
  112. package/std/net/websocket.ts +370 -186
  113. package/std/net/webtransport.ts +755 -436
  114. package/std/regex.ts +1659 -829
  115. package/std/sqlite.ts +171 -0
  116. package/std/sync/ring.ts +320 -156
  117. package/std/sync/shm.ts +53 -6
  118. package/std/text.ts +205 -124
  119. package/std/threads.ts +22 -2
package/std/cli-args.ts CHANGED
@@ -19,7 +19,11 @@
19
19
  * cannot carry its handler; what a builder gives instead is a handle for
20
20
  * every command, flag and argument, so the program reads a value by the
21
21
  * handle it declared rather than by a name a typo can miss, and every
22
- * declaration mistake panics at the call that made it.
22
+ * declaration mistake panics at the call that made it. Each declaration has
23
+ * a `try` twin (`tryCommand`, `tryFlag`, ...) that answers the same mistake
24
+ * as an `Err` instead, and the twins that declare a flag or an argument
25
+ * answer a `CliFlag` or `CliArgument` that `ParseResult`'s `read` methods
26
+ * take, so a program that uses them reaches no panic.
23
27
  *
24
28
  * **What it costs.** Declaring is linear in the declarations and builds no
25
29
  * help text. Parsing walks the arguments once, with one map lookup per
@@ -68,8 +72,11 @@ const VALUE_OPTIONAL: i32 = 2
68
72
  /** The owner of a global flag, which no command handle is. */
69
73
  const GLOBAL: i32 = -1
70
74
 
71
- /** No handle: a group's id, a command without arguments, the last argument's successor. */
72
- const NONE: i32 = -1
75
+ /** The parent of the root, which no command handle is. */
76
+ const NO_PARENT: i32 = -1
77
+
78
+ /** The id a group answers in `ParseResult.id`, which no command's is. */
79
+ const GROUP_ID: i32 = -1
73
80
 
74
81
  /** Where descriptions start at the latest, in a help row. */
75
82
  const MAX_COLUMN: i32 = 32
@@ -84,50 +91,96 @@ const scopeKey = (scope: i32, name: string): string => `${scope}\u0000${name}`
84
91
  const isWord = (name: string): boolean =>
85
92
  name.length > 0 && name.indexOf(" ") < 0 && name.indexOf("=") < 0 && toI32(name.charCodeAt(0)) !== DASH
86
93
 
87
- /** The smaller of two widths. */
88
- const minI32 = (a: i32, b: i32): i32 => (a < b ? a : b)
94
+ /** The smaller of two widened edit costs. */
95
+ const minI64 = (a: i64, b: i64): i64 => (a < b ? a : b)
96
+
97
+ /**
98
+ * One column of the edit-distance table: the byte of `b` it stands for, and
99
+ * its cells in the row two above, the row above and the row being worked.
100
+ */
101
+ class Cell {
102
+ /** @internal Used by `editDistance`. */
103
+ ch: i32
104
+ /** @internal Used by `editDistance`. */
105
+ two: i32
106
+ /** @internal Used by `editDistance`. */
107
+ up: i32
108
+ /** @internal Used by `editDistance`. */
109
+ cur: i32
110
+
111
+ constructor(ch: i32, up: i32) {
112
+ this.ch = ch
113
+ this.two = 0
114
+ this.up = up
115
+ this.cur = 0
116
+ }
117
+ }
89
118
 
90
119
  /**
91
120
  * The edit distance between `a` and `b` in bytes, a swap of two neighbours
92
- * counting as one edit (`kyes` is one from `keys`), worked in the three rows
93
- * `rows` holds, each at least one longer than `b`.
121
+ * counting as one edit (`kyes` is one from `keys`). The table is kept as one
122
+ * `Cell` per byte of `b`, each holding its own column of the last three rows,
123
+ * so every cell is read through the one array the loops are bounded by.
124
+ * `cols` is the caller's, reused across calls: it is cut or grown here to
125
+ * one cell per byte of `b`.
94
126
  */
95
- const editDistance = (a: string, b: string, rows: i32[][]): i32 => {
96
- const n: i32 = toI32(b.length)
97
- if (toI32(rows.length) !== 3) {
98
- panic("cli-args: edit distance needs three rows")
99
- }
100
- for (let j: i32 = 0; j <= n && j < toI32(rows[0].length); j++) {
101
- rows[0][j] = j
102
- }
103
- for (let i: i32 = 1; i <= toI32(a.length); i++) {
104
- const into = rows[i % 3]
105
- const above = rows[(i + 2) % 3]
106
- const twoUp = rows[(i + 1) % 3]
107
- if (!(n >= 0 && n < toI32(into.length) && n < toI32(above.length) && n < toI32(twoUp.length))) {
108
- panic("cli-args: edit distance rows too short")
109
- }
110
- into[0] = i
111
- for (
112
- let j: i32 = 1;
113
- j <= n && j < toI32(into.length) && j < toI32(above.length) && j < toI32(twoUp.length);
114
- j++
115
- ) {
116
- const cost: i32 = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1
117
- let d = minI32(minI32(above[j] + 1, into[j - 1] + 1), above[j - 1] + cost)
118
- if (
119
- i > 1 &&
120
- j > 1 &&
121
- a.charCodeAt(i - 1) === b.charCodeAt(j - 2) &&
122
- a.charCodeAt(i - 2) === b.charCodeAt(j - 1)
123
- ) {
124
- d = minI32(d, twoUp[j - 2] + 1)
127
+ const editDistance = (a: string, b: string, cols: Cell[]): i32 => {
128
+ // Row 0: `b`'s first `j + 1` bytes are `j + 1` inserts from nothing.
129
+ for (let j: i32 = 0; j < toI32(b.length); j++) {
130
+ const ch: i32 = toI32(b.charCodeAt(j))
131
+ if (j < toI32(cols.length)) {
132
+ const cell = cols[j]
133
+ cell.ch = ch
134
+ cell.up = j + 1
135
+ } else {
136
+ cols.push(new Cell(ch, j + 1))
137
+ }
138
+ }
139
+ while (toI32(cols.length) > toI32(b.length) && cols.length > 0) {
140
+ cols.pop()
141
+ }
142
+ for (let k: i32 = 0; k < toI32(a.length); k++) {
143
+ const ch: i32 = toI32(a.charCodeAt(k))
144
+ // The byte before `a`'s, for a swap; -1, which no byte is, on the first row.
145
+ const before: i32 = k > 0 ? toI32(a.charCodeAt(k - 1)) : -1
146
+ for (let j: i32 = 0; j < toI32(cols.length); j++) {
147
+ const cell = cols[j]
148
+ // Column 0 of the table, left of every cell, is `k + 1` deletes in this
149
+ // row and `k` in the row above; `k - 1` two rows up.
150
+ let left: i32 = k + 1
151
+ let diag: i32 = k
152
+ let leftCh: i32 = -1
153
+ let swap: i32 = k - 1
154
+ if (j > 0) {
155
+ const prev = cols[j - 1]
156
+ left = prev.cur
157
+ diag = prev.up
158
+ leftCh = prev.ch
159
+ }
160
+ if (j > 1) {
161
+ swap = cols[j - 2].two
162
+ }
163
+ // Widened: a cell holds at most the longer string's length, so the sum
164
+ // fits an i64 and narrowing it back to i32 keeps it whole.
165
+ const change: i64 = cell.ch === ch ? toI64(diag) : toI64(diag) + toI64(1)
166
+ let d: i64 = minI64(minI64(toI64(cell.up) + toI64(1), toI64(left) + toI64(1)), change)
167
+ if (k > 0 && j > 0 && cell.ch === before && leftCh === ch) {
168
+ d = minI64(d, toI64(swap) + toI64(1))
125
169
  }
126
- into[j] = d
170
+ cell.cur = toI32(d)
127
171
  }
172
+ for (let j: i32 = 0; j < toI32(cols.length); j++) {
173
+ const cell = cols[j]
174
+ cell.two = cell.up
175
+ cell.up = cell.cur
176
+ }
177
+ }
178
+ // The last column's newest row; with `b` empty, deleting all of `a`.
179
+ let distance: i32 = toI32(a.length)
180
+ for (let j: i32 = 0; j < toI32(cols.length); j++) {
181
+ distance = cols[j].up
128
182
  }
129
- const last = rows[toI32(a.length) % 3]
130
- return n >= 0 && n < toI32(last.length) ? last[n] : n
183
+ return distance
131
184
  }
132
185
 
133
186
  /**
@@ -136,31 +189,23 @@ const editDistance = (a: string, b: string, rows: i32[][]): i32 => {
136
189
  * declared wins a tie.
137
190
  */
138
191
  const closest = (typed: string, names: string[]): string => {
139
- let longest: i32 = 0
140
- for (let i: i32 = 0; i < toI32(names.length); i++) {
141
- longest = toI32(names[i].length) > longest ? toI32(names[i].length) : longest
142
- }
143
- const rows: i32[][] = [[], [], []]
144
- for (let j: i32 = 0; j <= longest; j++) {
145
- rows[0].push(j)
146
- rows[1].push(j)
147
- rows[2].push(j)
148
- }
149
192
  let dashes: i32 = 0
150
193
  while (dashes < toI32(typed.length) && toI32(typed.charCodeAt(dashes)) === DASH) {
151
194
  dashes = dashes + 1
152
195
  }
153
196
  const third: i32 = (toI32(typed.length) - dashes) / 3
154
197
  let best: i32 = third > 2 ? third : 2
155
- let at: i32 = -1
198
+ let near = ""
199
+ const cols: Cell[] = []
156
200
  for (let i: i32 = 0; i < toI32(names.length); i++) {
157
- const d = editDistance(typed, names[i], rows)
158
- if (d <= best && (at < 0 || d < best)) {
201
+ const name = names[i]
202
+ const d = editDistance(typed, name, cols)
203
+ if (d <= best && (near.length === 0 || d < best)) {
159
204
  best = d
160
- at = i
205
+ near = name
161
206
  }
162
207
  }
163
- return at >= 0 && at < toI32(names.length) ? names[at] : ""
208
+ return near
164
209
  }
165
210
 
166
211
  /** A flag spec taken apart: `-r, --raw-output`, `--limit <n>`, `--no-color`. */
@@ -176,46 +221,231 @@ class FlagSpec {
176
221
  /** @internal Used by `Cli`. */
177
222
  negated: boolean
178
223
 
179
- constructor(call: string, spec: string) {
180
- let rest = spec
181
- this.short = ""
182
- if (rest.startsWith("-") && !rest.startsWith("--")) {
183
- if (!(rest.length >= 6 && rest.substring(2, 4) === ", ")) {
184
- panic(`cli-args: ${call}: bad flag spec '${spec}': a short flag is one letter, then ', --name'`)
185
- }
186
- this.short = rest.substring(1, 2)
187
- if (!isWord(this.short)) {
188
- panic(`cli-args: ${call}: bad flag spec '${spec}': the short flag is not a letter`)
189
- }
190
- rest = rest.substring(4)
191
- }
192
- if (!rest.startsWith("--")) {
193
- panic(`cli-args: ${call}: bad flag spec '${spec}': a flag is written '--name'`)
194
- }
195
- const space: i32 = toI32(rest.indexOf(" "))
196
- this.long = space < 0 ? rest.substring(2) : rest.substring(2, space)
197
- this.meta = space < 0 ? "" : rest.substring(space + 1)
198
- if (!isWord(this.long)) {
199
- panic(
200
- `cli-args: ${call}: bad flag spec '${spec}': the name is empty or has a space, '=' or leading dash`
201
- )
224
+ constructor(short: string, long: string, meta: string, value: i32, negated: boolean) {
225
+ this.short = short
226
+ this.long = long
227
+ this.meta = meta
228
+ this.value = value
229
+ this.negated = negated
230
+ }
231
+ }
232
+
233
+ /** `spec` taken apart, or why it is not a flag spec; `call` names the declaration in the error. */
234
+ const parseFlagSpec = (call: string, spec: string): Result<FlagSpec, string> => {
235
+ let rest = spec
236
+ let short = ""
237
+ if (rest.startsWith("-") && !rest.startsWith("--")) {
238
+ if (!(rest.length >= 6 && rest.substring(2, 4) === ", ")) {
239
+ return Err(`cli-args: ${call}: bad flag spec '${spec}': a short flag is one letter, then ', --name'`)
202
240
  }
203
- this.value = VALUE_NONE
204
- if (this.meta.length > 0) {
205
- const inner = this.meta.substring(1, this.meta.length - 1)
206
- if (this.meta.startsWith("<") && this.meta.endsWith(">") && isWord(inner)) {
207
- this.value = VALUE_REQUIRED
208
- } else if (this.meta.startsWith("[") && this.meta.endsWith("]") && isWord(inner)) {
209
- this.value = VALUE_OPTIONAL
210
- } else {
211
- panic(`cli-args: ${call}: bad flag spec '${spec}': a value is written <value> or [value]`)
212
- }
241
+ short = rest.substring(1, 2)
242
+ if (!isWord(short)) {
243
+ return Err(`cli-args: ${call}: bad flag spec '${spec}': the short flag is not a letter`)
213
244
  }
214
- this.negated = this.value === VALUE_NONE && this.long.startsWith("no-") && this.long.length > 3
215
- if (this.negated) {
216
- this.long = this.long.substring(3)
245
+ rest = rest.substring(4)
246
+ }
247
+ if (!rest.startsWith("--")) {
248
+ return Err(`cli-args: ${call}: bad flag spec '${spec}': a flag is written '--name'`)
249
+ }
250
+ const space: i32 = toI32(rest.indexOf(" "))
251
+ let long = space < 0 ? rest.substring(2) : rest.substring(2, space)
252
+ // From the space on, less the space itself: no index arithmetic.
253
+ const meta = space < 0 ? "" : rest.substring(space).substring(1)
254
+ if (!isWord(long)) {
255
+ return Err(
256
+ `cli-args: ${call}: bad flag spec '${spec}': the name is empty or has a space, '=' or leading dash`
257
+ )
258
+ }
259
+ let value = VALUE_NONE
260
+ if (meta.length > 0) {
261
+ const inner = meta.substring(1, meta.length - 1)
262
+ if (meta.startsWith("<") && meta.endsWith(">") && isWord(inner)) {
263
+ value = VALUE_REQUIRED
264
+ } else if (meta.startsWith("[") && meta.endsWith("]") && isWord(inner)) {
265
+ value = VALUE_OPTIONAL
266
+ } else {
267
+ return Err(`cli-args: ${call}: bad flag spec '${spec}': a value is written <value> or [value]`)
217
268
  }
218
269
  }
270
+ const negated = value === VALUE_NONE && long.startsWith("no-") && long.length > 3
271
+ if (negated) {
272
+ long = long.substring(3)
273
+ }
274
+ return Ok(new FlagSpec(short, long, meta, value, negated))
275
+ }
276
+
277
+ /** A command or group as declared: everything the walk and the help read of it. */
278
+ class CommandRec {
279
+ /** @internal Used by `Cli`. */
280
+ name: string
281
+ /** @internal Used by `Cli`. The parent's path; empty for the root. */
282
+ parentPath: string
283
+ /** @internal Used by `Cli`. */
284
+ description: string
285
+ /** @internal Used by `Cli` and `ParseResult`. */
286
+ path: string
287
+ /** @internal Used by `Cli`. Its aliases, joined by `, ` for its help row. */
288
+ aliases: string
289
+ /** @internal Used by `Cli`. */
290
+ epilog: string
291
+ /** @internal Used by `Cli` and `ParseResult`. Its arguments in order, each at its own index. */
292
+ args: CliArgument[]
293
+ /** @internal Used by `Cli` and `ParseResult`. */
294
+ handle: i32
295
+ /** @internal Used by `Cli`. The parent's handle; -1 for the root. */
296
+ parent: i32
297
+ /** @internal Used by `ParseResult`. */
298
+ id: i32
299
+ /** @internal Used by `Cli` and `ParseResult`. */
300
+ group: boolean
301
+ /** @internal Used by `Cli`. Whether its last argument is variadic. */
302
+ variadic: boolean
303
+ /** @internal Used by `Cli`. Whether its last argument is optional. */
304
+ optionalArg: boolean
305
+ /** @internal Used by `Cli`. Whether one of its own flags is required. */
306
+ hasRequired: boolean
307
+
308
+ constructor(
309
+ handle: i32,
310
+ name: string,
311
+ parent: i32,
312
+ parentPath: string,
313
+ id: i32,
314
+ description: string,
315
+ group: boolean,
316
+ path: string
317
+ ) {
318
+ this.handle = handle
319
+ this.name = name
320
+ this.parent = parent
321
+ this.parentPath = parentPath
322
+ this.id = id
323
+ this.description = description
324
+ this.group = group
325
+ this.path = path
326
+ this.aliases = ""
327
+ this.epilog = ""
328
+ this.args = []
329
+ this.variadic = false
330
+ this.optionalArg = false
331
+ this.hasRequired = false
332
+ }
333
+ }
334
+
335
+ /** An alias, kept in declaration order for the did-you-mean candidates. */
336
+ class AliasRec {
337
+ /** @internal Used by `Cli`. */
338
+ name: string
339
+ /** @internal Used by `Cli`. The handle of the group it is a name in. */
340
+ parent: i32
341
+
342
+ constructor(name: string, parent: i32) {
343
+ this.name = name
344
+ this.parent = parent
345
+ }
346
+ }
347
+
348
+ /**
349
+ * A flag as declared, answered by `Cli.tryFlag` and `Cli.tryGlobalFlag`:
350
+ * `ParseResult`'s `read` methods take it, and need no handle check to.
351
+ */
352
+ export class CliFlag {
353
+ /** The flag's handle, for the methods that take one, such as `Cli.tryDefaultValue`. */
354
+ handle: i32
355
+ /** @internal Used by `Cli` and `ParseResult`. The owning command's handle, or -1 for a global flag. */
356
+ owner: i32
357
+ /** @internal Used by `Cli`. The owning command; the root for a global flag. */
358
+ scope: CommandRec
359
+ /** @internal Used by `Cli`. */
360
+ short: string
361
+ /** @internal Used by `Cli` and `ParseResult`. */
362
+ long: string
363
+ /** @internal Used by `Cli`. */
364
+ meta: string
365
+ /** @internal Used by `Cli` and `ParseResult`. */
366
+ value: i32
367
+ /** @internal Used by `Cli` and `ParseResult`. */
368
+ negated: boolean
369
+ /** @internal Used by `Cli`. */
370
+ negatable: boolean
371
+ /** @internal Used by `Cli`. */
372
+ description: string
373
+ /** @internal Used by `Cli` and `ParseResult`. */
374
+ fallback: string
375
+ /** @internal Used by `Cli` and `ParseResult`. */
376
+ hasDefault: boolean
377
+ /** @internal Used by `Cli`. */
378
+ required: boolean
379
+ /** @internal Used by `Cli` and `ParseResult`. */
380
+ repeatable: boolean
381
+
382
+ /** @internal Called by `Cli`. */
383
+ constructor(handle: i32, owner: i32, scope: CommandRec, spec: FlagSpec, description: string) {
384
+ this.handle = handle
385
+ this.owner = owner
386
+ this.scope = scope
387
+ this.short = spec.short
388
+ this.long = spec.long
389
+ this.meta = spec.meta
390
+ this.value = spec.value
391
+ this.negated = spec.negated
392
+ this.negatable = spec.negated
393
+ this.description = description
394
+ this.fallback = ""
395
+ this.hasDefault = false
396
+ this.required = false
397
+ this.repeatable = false
398
+ }
399
+
400
+ /** @internal Called by `Cli` and `ParseResult`. How it is spelled on the command line: its long name, or `--no-x` for one declared that way. */
401
+ spelling(): string {
402
+ return this.negated ? `--no-${this.long}` : `--${this.long}`
403
+ }
404
+
405
+ /** @internal Called by `Cli`. Whether it answers to `--name`, as itself or, negatable, as its negation. */
406
+ answersTo(name: string): boolean {
407
+ return this.long === name || (this.negatable && `no-${this.long}` === name)
408
+ }
409
+ }
410
+
411
+ /**
412
+ * A positional argument as declared, answered by `Cli.tryArgument`:
413
+ * `ParseResult.readPositional` and `readPositionals` take it.
414
+ */
415
+ export class CliArgument {
416
+ /** @internal Used by `Cli` and `ParseResult`. */
417
+ name: string
418
+ /** @internal Used by `Cli`. */
419
+ description: string
420
+ /** The argument's handle, for `ParseResult.positional` and `positionals`. */
421
+ handle: i32
422
+ /** @internal Used by `ParseResult`. The owning command's handle. */
423
+ owner: i32
424
+ /** @internal Used by `ParseResult`. Its place among its command's positionals. */
425
+ index: i32
426
+ /** @internal Used by `Cli` and `ParseResult`. */
427
+ required: boolean
428
+ /** @internal Used by `Cli` and `ParseResult`. */
429
+ variadic: boolean
430
+
431
+ /** @internal Called by `Cli`. */
432
+ constructor(
433
+ handle: i32,
434
+ owner: i32,
435
+ name: string,
436
+ required: boolean,
437
+ variadic: boolean,
438
+ description: string,
439
+ index: i32
440
+ ) {
441
+ this.handle = handle
442
+ this.owner = owner
443
+ this.name = name
444
+ this.required = required
445
+ this.variadic = variadic
446
+ this.description = description
447
+ this.index = index
448
+ }
219
449
  }
220
450
 
221
451
  /**
@@ -230,63 +460,21 @@ export class Cli {
230
460
  version: string
231
461
  private description: string
232
462
 
233
- private cmdName: string[]
234
- private cmdParent: i32[]
235
- /** @internal Used by `ParseResult`. */
236
- cmdId: i32[]
237
- private cmdDesc: string[]
238
- /** @internal Used by `ParseResult`. */
239
- cmdGroup: boolean[]
240
- private cmdPath: string[]
241
- private cmdAliases: string[]
242
- private aliasOwner: i32[]
243
- private aliasName: string[]
244
- private cmdEpilog: string[]
245
- /** @internal Used by `ParseResult`. */
246
- cmdFirstArg: i32[]
247
- private cmdLastArg: i32[]
248
- private cmdVariadic: boolean[]
249
- private cmdOptionalArg: boolean[]
250
- private children: Map<string, i32>
251
-
252
- private flagOwner: i32[]
253
- private flagShort: string[]
254
- private flagLong: string[]
255
- private flagMeta: string[]
256
- /** @internal Used by `ParseResult`. */
257
- flagValue: i32[]
258
- /** @internal Used by `ParseResult`. */
259
- flagNegated: boolean[]
260
- private flagNegatable: boolean[]
261
- private flagDesc: string[]
262
- /** @internal Used by `ParseResult`. */
263
- flagDefault: string[]
264
- /** @internal Used by `ParseResult`. */
265
- flagHasDefault: boolean[]
266
- private flagRequired: boolean[]
463
+ // One record per declaration, at its handle's index: a handle is checked
464
+ // once, by `commandAt`, `flagAt` or `argumentAt`, and the record it finds
465
+ // carries every field, so nothing after that is read by an index.
267
466
  /** @internal Used by `ParseResult`. */
268
- flagRepeatable: boolean[]
269
- private flags: Map<string, i32>
270
- private negations: Map<string, i32>
271
- /** @internal Used by `ParseResult`. */
272
- cmdRequired: i32[][]
273
- /** @internal Used by `ParseResult`. */
274
- globalRequired: i32[]
275
- private ids: Map<string, i32>
276
-
277
- /** @internal Used by `ParseResult`. */
278
- argOwner: i32[]
279
- /** @internal Used by `ParseResult`. */
280
- argName: string[]
281
- /** @internal Used by `ParseResult`. */
282
- argRequired: boolean[]
283
- /** @internal Used by `ParseResult`. */
284
- argVariadic: boolean[]
285
- private argDesc: string[]
286
- /** @internal Used by `ParseResult`. */
287
- argIndex: i32[]
288
- /** @internal Used by `ParseResult`. */
289
- argNext: i32[]
467
+ root: CommandRec
468
+ private cmds: CommandRec[]
469
+ private aliasList: AliasRec[]
470
+ private children: Map<string, CommandRec>
471
+ private ids: Map<string, CommandRec>
472
+ private flagList: CliFlag[]
473
+ private flags: Map<string, CliFlag>
474
+ private negations: Map<string, CliFlag>
475
+ /** @internal Used by `ParseResult`. Every required flag, in the order `required` made it so. */
476
+ requiredFlags: CliFlag[]
477
+ private argList: CliArgument[]
290
478
 
291
479
  /**
292
480
  * A tree with only its root, the program `name` at `version`, for
@@ -302,83 +490,54 @@ export class Cli {
302
490
  this.name = name
303
491
  this.version = version
304
492
  this.description = description
305
- this.cmdName = [name]
306
- this.cmdParent = [-1]
307
- this.cmdId = [-1]
308
- this.cmdDesc = [description]
309
- this.cmdGroup = [false]
310
- this.cmdPath = [name]
311
- this.cmdAliases = [""]
312
- this.aliasOwner = []
313
- this.aliasName = []
314
- this.cmdEpilog = [""]
315
- this.cmdFirstArg = [-1]
316
- this.cmdLastArg = [-1]
317
- this.cmdVariadic = [false]
318
- this.cmdOptionalArg = [false]
319
- this.cmdRequired = [[]]
320
- this.children = new Map<string, i32>()
321
- this.flagOwner = []
322
- this.flagShort = []
323
- this.flagLong = []
324
- this.flagMeta = []
325
- this.flagValue = []
326
- this.flagNegated = []
327
- this.flagNegatable = []
328
- this.flagDesc = []
329
- this.flagDefault = []
330
- this.flagHasDefault = []
331
- this.flagRequired = []
332
- this.flagRepeatable = []
333
- this.flags = new Map<string, i32>()
334
- this.negations = new Map<string, i32>()
335
- this.globalRequired = []
336
- this.ids = new Map<string, i32>()
337
- this.argOwner = []
338
- this.argName = []
339
- this.argRequired = []
340
- this.argVariadic = []
341
- this.argDesc = []
342
- this.argIndex = []
343
- this.argNext = []
344
- }
345
-
346
- /** The command `handle`, or a panic naming `call` when there is none. */
347
- private checkCommand(call: string, handle: i32): i32 {
348
- if (!(handle >= 0 && handle < toI32(this.cmdName.length))) {
349
- panic(`cli-args: ${call}: ${handle} is not a command handle`)
350
- }
351
- return handle
493
+ this.root = new CommandRec(ROOT, name, NO_PARENT, "", GROUP_ID, description, false, name)
494
+ this.cmds = [this.root]
495
+ this.aliasList = []
496
+ this.children = new Map<string, CommandRec>()
497
+ this.ids = new Map<string, CommandRec>()
498
+ this.flagList = []
499
+ this.flags = new Map<string, CliFlag>()
500
+ this.negations = new Map<string, CliFlag>()
501
+ this.requiredFlags = []
502
+ this.argList = []
352
503
  }
353
504
 
354
- /** @internal Called by `ParseResult`. The flag `handle`, or a panic naming `call` when there is none. */
355
- checkFlag(call: string, handle: i32): i32 {
356
- if (!(handle >= 0 && handle < toI32(this.flagLong.length))) {
357
- panic(`cli-args: ${call}: ${handle} is not a flag handle`)
505
+ /** The command `handle`, or why it is none; `call` names the declaration in the error. */
506
+ private commandAt(call: string, handle: i32): Result<CommandRec, string> {
507
+ if (handle >= 0 && handle < toI32(this.cmds.length)) {
508
+ return Ok(this.cmds[handle])
358
509
  }
359
- return handle
510
+ return Err(`cli-args: ${call}: ${handle} is not a command handle`)
360
511
  }
361
512
 
362
- /** @internal Called by `ParseResult`. The argument `handle`, or a panic naming `call` when there is none. */
363
- checkArgument(call: string, handle: i32): i32 {
364
- if (!(handle >= 0 && handle < toI32(this.argName.length))) {
365
- panic(`cli-args: ${call}: ${handle} is not an argument handle`)
513
+ /** The flag `handle`, or why it is none; `call` names the declaration in the error. */
514
+ private flagAt(call: string, handle: i32): Result<CliFlag, string> {
515
+ if (handle >= 0 && handle < toI32(this.flagList.length)) {
516
+ return Ok(this.flagList[handle])
366
517
  }
367
- return handle
518
+ return Err(`cli-args: ${call}: ${handle} is not a flag handle`)
368
519
  }
369
520
 
370
- /** @internal Called by `ParseResult`. The command line that names `handle`: the program, then each command down to it. */
371
- pathOf(handle: i32): string {
372
- return this.cmdPath[this.checkCommand("path", handle)]
521
+ /** @internal Called by `ParseResult`. The flag `handle`, or a panic naming `call` when there is none. */
522
+ checkFlag(call: string, handle: i32): CliFlag {
523
+ const f = this.flagAt(call, handle)
524
+ if (f.isErr()) {
525
+ // A handle no declaration answered: the program's own mistake.
526
+ panic(f.error)
527
+ }
528
+ return f.value
373
529
  }
374
530
 
375
- /** @internal Called by nothing. Whether `handle` holds commands rather than running: a group, or a root given children. */
376
- isGroup(handle: i32): boolean {
377
- const h = this.checkCommand("isGroup", handle)
378
- return this.cmdGroup[h]
531
+ /** @internal Called by `ParseResult`. The argument `handle`, or a panic naming `call` when there is none. */
532
+ checkArgument(call: string, handle: i32): CliArgument {
533
+ if (!(handle >= 0 && handle < toI32(this.argList.length))) {
534
+ // A handle no declaration answered: the program's own mistake.
535
+ panic(`cli-args: ${call}: ${handle} is not an argument handle`)
536
+ }
537
+ return this.argList[handle]
379
538
  }
380
539
 
381
- /** A new child of `parent`; `call` names the declaration in a panic. */
540
+ /** A new child of `parent`, or why it cannot be; `call` names the declaration in the error. */
382
541
  private addCommand(
383
542
  call: string,
384
543
  parent: i32,
@@ -386,41 +545,59 @@ export class Cli {
386
545
  id: i32,
387
546
  description: string,
388
547
  group: boolean
389
- ): i32 {
390
- const p = this.checkCommand(call, parent)
548
+ ): Result<CommandRec, string> {
549
+ const at = this.commandAt(call, parent)
550
+ if (at.isErr()) {
551
+ return Err(at.error)
552
+ }
553
+ const p = at.value
391
554
  if (!isWord(name)) {
392
- panic(`cli-args: ${call}: '${name}' is not a command name`)
555
+ return Err(`cli-args: ${call}: '${name}' is not a command name`)
393
556
  }
394
- if (p !== ROOT && !this.cmdGroup[p]) {
395
- panic(`cli-args: ${call}: ${this.pathOf(p)} is a command, not a group`)
557
+ if (p.handle !== ROOT && !p.group) {
558
+ return Err(`cli-args: ${call}: ${p.path} is a command, not a group`)
396
559
  }
397
- if (this.cmdFirstArg[p] >= 0) {
398
- panic(`cli-args: ${call}: ${this.pathOf(p)} takes arguments, so it cannot hold commands`)
560
+ if (p.args.length > 0) {
561
+ return Err(`cli-args: ${call}: ${p.path} takes arguments, so it cannot hold commands`)
399
562
  }
400
- if (toI32(this.cmdRequired[p].length) > 0) {
401
- panic(`cli-args: ${call}: ${this.pathOf(p)} has a required flag, so it cannot hold commands`)
563
+ if (p.hasRequired) {
564
+ return Err(`cli-args: ${call}: ${p.path} has a required flag, so it cannot hold commands`)
402
565
  }
403
- const key = scopeKey(p, name)
566
+ const key = scopeKey(p.handle, name)
404
567
  if (this.children.has(key)) {
405
- panic(`cli-args: ${call}: ${this.pathOf(p)} already has a command '${name}'`)
406
- }
407
- const handle: i32 = toI32(this.cmdName.length)
408
- this.children.set(key, handle)
409
- this.cmdGroup[p] = true
410
- this.cmdName.push(name)
411
- this.cmdParent.push(p)
412
- this.cmdPath.push(`${this.cmdPath[p]} ${name}`)
413
- this.cmdId.push(id)
414
- this.cmdDesc.push(description)
415
- this.cmdGroup.push(group)
416
- this.cmdAliases.push("")
417
- this.cmdEpilog.push("")
418
- this.cmdFirstArg.push(NONE)
419
- this.cmdLastArg.push(NONE)
420
- this.cmdVariadic.push(false)
421
- this.cmdOptionalArg.push(false)
422
- this.cmdRequired.push(new Array<i32>(0))
423
- return handle
568
+ return Err(`cli-args: ${call}: ${p.path} already has a command '${name}'`)
569
+ }
570
+ p.group = true
571
+ const c = new CommandRec(
572
+ toI32(this.cmds.length),
573
+ name,
574
+ p.handle,
575
+ p.path,
576
+ id,
577
+ description,
578
+ group,
579
+ `${p.path} ${name}`
580
+ )
581
+ this.children.set(key, c)
582
+ this.cmds.push(c)
583
+ return Ok(c)
584
+ }
585
+
586
+ /**
587
+ * `group`, answering a mistake rather than panicking on it.
588
+ *
589
+ * @param parent the handle of the group (or `ROOT`) the group goes in
590
+ * @param name the word that names the group on the command line
591
+ * @param description the group's line in its parent's help, and in its own
592
+ * @returns the group's handle, or the error `group` would panic with, and
593
+ * then the tree is unchanged
594
+ */
595
+ tryGroup(parent: i32, name: string, description: string): Result<i32, string> {
596
+ const c = this.addCommand(`group(${name})`, parent, name, GROUP_ID, description, true)
597
+ if (c.isErr()) {
598
+ return Err(c.error)
599
+ }
600
+ return Ok(c.value.handle)
424
601
  }
425
602
 
426
603
  /**
@@ -437,7 +614,42 @@ export class Cli {
437
614
  * `epilog`
438
615
  */
439
616
  group(parent: i32, name: string, description: string): i32 {
440
- return this.addCommand(`group(${name})`, parent, name, NONE, description, true)
617
+ const c = this.tryGroup(parent, name, description)
618
+ if (c.isErr()) {
619
+ // A declaration mistake, which the program's own code makes.
620
+ panic(c.error)
621
+ }
622
+ return c.value
623
+ }
624
+
625
+ /**
626
+ * `command`, answering a mistake rather than panicking on it.
627
+ *
628
+ * @param parent the handle of the group (or `ROOT`) the command goes in
629
+ * @param name the word that names the command on the command line
630
+ * @param id what `ParseResult.id` answers when the arguments name this
631
+ * command: not negative, and no other command's
632
+ * @param description the command's line in its parent's help, and in its
633
+ * own usage line
634
+ * @returns the command's handle, or the error `command` would panic with,
635
+ * and then the tree is unchanged
636
+ */
637
+ tryCommand(parent: i32, name: string, id: i32, description: string): Result<i32, string> {
638
+ const call = `command(${name})`
639
+ if (id < 0) {
640
+ return Err(`cli-args: ${call}: the id ${id} is negative, which a group answers`)
641
+ }
642
+ const key = `${id}`
643
+ const other = this.ids.get(key)
644
+ if (other !== undefined) {
645
+ return Err(`cli-args: ${call}: ${other.path} already has the id ${id}`)
646
+ }
647
+ const c = this.addCommand(call, parent, name, id, description, false)
648
+ if (c.isErr()) {
649
+ return Err(c.error)
650
+ }
651
+ this.ids.set(key, c.value)
652
+ return Ok(c.value.handle)
441
653
  }
442
654
 
443
655
  /**
@@ -458,18 +670,44 @@ export class Cli {
458
670
  * `epilog`
459
671
  */
460
672
  command(parent: i32, name: string, id: i32, description: string): i32 {
461
- const call = `command(${name})`
462
- if (id < 0) {
463
- panic(`cli-args: ${call}: the id ${id} is negative, which a group answers`)
673
+ const c = this.tryCommand(parent, name, id, description)
674
+ if (c.isErr()) {
675
+ // A declaration mistake, which the program's own code makes.
676
+ panic(c.error)
464
677
  }
465
- const key = `${id}`
466
- const other = this.ids.get(key) ?? NONE
467
- if (other >= 0) {
468
- panic(`cli-args: ${call}: ${this.pathOf(other)} already has the id ${id}`)
678
+ return c.value
679
+ }
680
+
681
+ /**
682
+ * `alias`, answering a mistake rather than panicking on it.
683
+ *
684
+ * @param handle the command or group the alias names
685
+ * @param name the other word, which the parent's help lists beside the
686
+ * first
687
+ * @returns nothing, or the error `alias` would panic with, and then the
688
+ * tree is unchanged
689
+ */
690
+ tryAlias(handle: i32, name: string): Result<void, string> {
691
+ const call = `alias(${name})`
692
+ const at = this.commandAt(call, handle)
693
+ if (at.isErr()) {
694
+ return Err(at.error)
695
+ }
696
+ const c = at.value
697
+ if (c.handle === ROOT) {
698
+ return Err(`cli-args: ${call}: the root has no alias`)
699
+ }
700
+ if (!isWord(name)) {
701
+ return Err(`cli-args: ${call}: '${name}' is not a command name`)
702
+ }
703
+ const key = scopeKey(c.parent, name)
704
+ if (this.children.has(key)) {
705
+ return Err(`cli-args: ${call}: ${c.parentPath} already has a command '${name}'`)
469
706
  }
470
- const handle = this.addCommand(call, parent, name, id, description, false)
471
- this.ids.set(key, handle)
472
- return handle
707
+ c.aliases = c.aliases.length > 0 ? `${c.aliases}, ${name}` : name
708
+ this.children.set(key, c)
709
+ this.aliasList.push(new AliasRec(name, c.parent))
710
+ return Ok()
473
711
  }
474
712
 
475
713
  /**
@@ -482,22 +720,11 @@ export class Cli {
482
720
  * that scope
483
721
  */
484
722
  alias(handle: i32, name: string): void {
485
- const call = `alias(${name})`
486
- const h = this.checkCommand(call, handle)
487
- if (h === ROOT) {
488
- panic(`cli-args: ${call}: the root has no alias`)
489
- }
490
- if (!isWord(name)) {
491
- panic(`cli-args: ${call}: '${name}' is not a command name`)
723
+ const r = this.tryAlias(handle, name)
724
+ if (r.isErr()) {
725
+ // A declaration mistake, which the program's own code makes.
726
+ panic(r.error)
492
727
  }
493
- const key = scopeKey(this.cmdParent[h], name)
494
- if (this.children.has(key)) {
495
- panic(`cli-args: ${call}: ${this.pathOf(this.cmdParent[h])} already has a command '${name}'`)
496
- }
497
- this.children.set(key, h)
498
- this.aliasOwner.push(h)
499
- this.aliasName.push(name)
500
- this.cmdAliases[h] = this.cmdAliases[h].length > 0 ? `${this.cmdAliases[h]}, ${name}` : name
501
728
  }
502
729
 
503
730
  /** Whether a flag of `scope` (a command, or `GLOBAL`) answers to `key`, as itself or as a negation. */
@@ -514,59 +741,63 @@ export class Cli {
514
741
  return spec.short.length > 0 && this.taken(scope, `-${spec.short}`)
515
742
  }
516
743
 
517
- /** Whether flag `f` answers to `--name`, as itself or, negatable, as its negation. */
518
- private answersTo(f: i32, name: string): boolean {
519
- return this.flagLong[f] === name || (this.flagNegatable[f] && `no-${this.flagLong[f]}` === name)
520
- }
521
-
522
- /** A new flag in `scope` from `spec`; `call` names the declaration in a panic. */
523
- private addFlag(call: string, scope: i32, spec: string, description: string): i32 {
524
- const s = new FlagSpec(call, spec)
744
+ /** A new flag of `owner` (`scope`'s handle, or `GLOBAL`) from `spec`, or why it cannot be; `call` names the declaration in the error. */
745
+ private addFlag(
746
+ call: string,
747
+ owner: i32,
748
+ scope: CommandRec,
749
+ spec: string,
750
+ description: string
751
+ ): Result<CliFlag, string> {
752
+ const parsed = parseFlagSpec(call, spec)
753
+ if (parsed.isErr()) {
754
+ return Err(parsed.error)
755
+ }
756
+ const s = parsed.value
525
757
  if (s.long === "help" || s.long === "version" || s.short === "h" || s.short === "v") {
526
- panic(`cli-args: ${call}: -h, --help, -v and --version are taken`)
758
+ return Err(`cli-args: ${call}: -h, --help, -v and --version are taken`)
527
759
  }
528
- if (this.scopeHas(scope, s)) {
529
- const where = scope === GLOBAL ? "the global flags" : this.pathOf(scope)
530
- panic(`cli-args: ${call}: ${where} already has a flag of that name`)
760
+ if (this.scopeHas(owner, s)) {
761
+ const where = owner === GLOBAL ? "the global flags" : scope.path
762
+ return Err(`cli-args: ${call}: ${where} already has a flag of that name`)
531
763
  }
532
- if (scope === GLOBAL) {
533
- let clash: i32 = -1
534
- for (let f: i32 = 0; f < toI32(this.flagLong.length) && clash < 0; f++) {
764
+ if (owner === GLOBAL) {
765
+ for (let i: i32 = 0; i < toI32(this.flagList.length); i++) {
766
+ const f = this.flagList[i]
535
767
  if (
536
- this.answersTo(f, s.long) ||
537
- (s.negated && this.answersTo(f, `no-${s.long}`)) ||
538
- (s.short.length > 0 && this.flagShort[f] === s.short)
768
+ f.answersTo(s.long) ||
769
+ (s.negated && f.answersTo(`no-${s.long}`)) ||
770
+ (s.short.length > 0 && f.short === s.short)
539
771
  ) {
540
- clash = f
772
+ return Err(`cli-args: ${call}: ${f.scope.path} already has a flag of that name`)
541
773
  }
542
774
  }
543
- if (clash >= 0) {
544
- panic(`cli-args: ${call}: ${this.pathOf(this.flagOwner[clash])} already has a flag of that name`)
545
- }
546
775
  } else if (this.scopeHas(GLOBAL, s)) {
547
- panic(`cli-args: ${call}: a global flag of that name is already declared`)
776
+ return Err(`cli-args: ${call}: a global flag of that name is already declared`)
548
777
  }
549
- const handle: i32 = toI32(this.flagLong.length)
550
- this.flags.set(scopeKey(scope, `--${s.long}`), handle)
778
+ const f = new CliFlag(toI32(this.flagList.length), owner, scope, s, description)
779
+ this.flags.set(scopeKey(owner, `--${s.long}`), f)
551
780
  if (s.negated) {
552
- this.negations.set(scopeKey(scope, `--no-${s.long}`), handle)
781
+ this.negations.set(scopeKey(owner, `--no-${s.long}`), f)
553
782
  }
554
783
  if (s.short.length > 0) {
555
- this.flags.set(scopeKey(scope, `-${s.short}`), handle)
556
- }
557
- this.flagOwner.push(scope)
558
- this.flagShort.push(s.short)
559
- this.flagLong.push(s.long)
560
- this.flagMeta.push(s.meta)
561
- this.flagValue.push(s.value)
562
- this.flagNegated.push(s.negated)
563
- this.flagNegatable.push(s.negated)
564
- this.flagDesc.push(description)
565
- this.flagDefault.push("")
566
- this.flagHasDefault.push(false)
567
- this.flagRequired.push(false)
568
- this.flagRepeatable.push(false)
569
- return handle
784
+ this.flags.set(scopeKey(owner, `-${s.short}`), f)
785
+ }
786
+ this.flagList.push(f)
787
+ return Ok(f)
788
+ }
789
+
790
+ /**
791
+ * `globalFlag`, answering a mistake rather than panicking on it.
792
+ *
793
+ * @param spec the flag as the help writes it, in `globalFlag`'s syntax
794
+ * @param description the flag's line in the `Global flags` help section
795
+ * @returns the flag, for `ParseResult`'s `read` methods and, by its
796
+ * `handle`, for the methods that take one; or the error `globalFlag`
797
+ * would panic with, and then the tree is unchanged
798
+ */
799
+ tryGlobalFlag(spec: string, description: string): Result<CliFlag, string> {
800
+ return this.addFlag(`globalFlag("${spec}")`, GLOBAL, this.root, spec, description)
570
801
  }
571
802
 
572
803
  /**
@@ -583,7 +814,32 @@ export class Cli {
583
814
  * `negatable`
584
815
  */
585
816
  globalFlag(spec: string, description: string): i32 {
586
- return this.addFlag(`globalFlag("${spec}")`, GLOBAL, spec, description)
817
+ const f = this.tryGlobalFlag(spec, description)
818
+ if (f.isErr()) {
819
+ // A declaration mistake, which the program's own code makes.
820
+ panic(f.error)
821
+ }
822
+ return f.value.handle
823
+ }
824
+
825
+ /**
826
+ * `flag`, answering a mistake rather than panicking on it.
827
+ *
828
+ * @param cmd the handle of the command or group (or `ROOT`) that owns the
829
+ * flag
830
+ * @param spec the flag as the help writes it, in `globalFlag`'s syntax
831
+ * @param description the flag's line in `cmd`'s `Flags` help section
832
+ * @returns the flag, for `ParseResult`'s `read` methods and, by its
833
+ * `handle`, for the methods that take one; or the error `flag` would
834
+ * panic with, and then the tree is unchanged
835
+ */
836
+ tryFlag(cmd: i32, spec: string, description: string): Result<CliFlag, string> {
837
+ const call = `flag("${spec}")`
838
+ const at = this.commandAt(call, cmd)
839
+ if (at.isErr()) {
840
+ return Err(at.error)
841
+ }
842
+ return this.addFlag(call, at.value.handle, at.value, spec, description)
587
843
  }
588
844
 
589
845
  /**
@@ -600,8 +856,39 @@ export class Cli {
600
856
  * `negatable`
601
857
  */
602
858
  flag(cmd: i32, spec: string, description: string): i32 {
603
- const call = `flag("${spec}")`
604
- return this.addFlag(call, this.checkCommand(call, cmd), spec, description)
859
+ const f = this.tryFlag(cmd, spec, description)
860
+ if (f.isErr()) {
861
+ // A declaration mistake, which the program's own code makes.
862
+ panic(f.error)
863
+ }
864
+ return f.value.handle
865
+ }
866
+
867
+ /**
868
+ * `defaultValue`, answering a mistake rather than panicking on it.
869
+ *
870
+ * @param f the handle of a flag that takes a value and is not required
871
+ * @param value what `value` and `values` answer when the arguments do not
872
+ * give the flag
873
+ * @returns nothing, or the error `defaultValue` would panic with, and then
874
+ * the flag is unchanged
875
+ */
876
+ tryDefaultValue(f: i32, value: string): Result<void, string> {
877
+ const call = `defaultValue(${value})`
878
+ const at = this.flagAt(call, f)
879
+ if (at.isErr()) {
880
+ return Err(at.error)
881
+ }
882
+ const fl = at.value
883
+ if (fl.value === VALUE_NONE) {
884
+ return Err(`cli-args: ${call}: --${fl.long} takes no value`)
885
+ }
886
+ if (fl.required) {
887
+ return Err(`cli-args: ${call}: --${fl.long} is required, so a default would never be read`)
888
+ }
889
+ fl.fallback = value
890
+ fl.hasDefault = true
891
+ return Ok()
605
892
  }
606
893
 
607
894
  /**
@@ -614,16 +901,40 @@ export class Cli {
614
901
  * call replaces an earlier one
615
902
  */
616
903
  defaultValue(f: i32, value: string): void {
617
- const call = `defaultValue(${value})`
618
- const h = this.checkFlag(call, f)
619
- if (this.flagValue[h] === VALUE_NONE) {
620
- panic(`cli-args: ${call}: --${this.flagLong[h]} takes no value`)
904
+ const r = this.tryDefaultValue(f, value)
905
+ if (r.isErr()) {
906
+ // A declaration mistake, which the program's own code makes.
907
+ panic(r.error)
621
908
  }
622
- if (this.flagRequired[h]) {
623
- panic(`cli-args: ${call}: --${this.flagLong[h]} is required, so a default would never be read`)
909
+ }
910
+
911
+ /**
912
+ * `required`, answering a mistake rather than panicking on it.
913
+ *
914
+ * @param f the handle of a command's or a global flag without a default
915
+ * @returns nothing, or the error `required` would panic with, and then the
916
+ * flag is unchanged
917
+ */
918
+ tryRequired(f: i32): Result<void, string> {
919
+ const at = this.flagAt("required", f)
920
+ if (at.isErr()) {
921
+ return Err(at.error)
922
+ }
923
+ const fl = at.value
924
+ if (fl.owner !== GLOBAL && fl.scope.group) {
925
+ return Err(`cli-args: required: ${fl.scope.path} holds commands, so --${fl.long} can never be checked`)
926
+ }
927
+ if (fl.hasDefault) {
928
+ return Err(`cli-args: required: --${fl.long} has a default, so it can never be missing`)
929
+ }
930
+ if (!fl.required) {
931
+ fl.required = true
932
+ this.requiredFlags.push(fl)
933
+ if (fl.owner !== GLOBAL) {
934
+ fl.scope.hasRequired = true
935
+ }
624
936
  }
625
- this.flagDefault[h] = value
626
- this.flagHasDefault[h] = true
937
+ return Ok()
627
938
  }
628
939
 
629
940
  /**
@@ -634,24 +945,31 @@ export class Cli {
634
945
  * default. Calling it twice is the same as once
635
946
  */
636
947
  required(f: i32): void {
637
- const h = this.checkFlag("required", f)
638
- const owner: i32 = this.flagOwner[h]
639
- if (owner !== GLOBAL && this.cmdGroup[owner]) {
640
- panic(
641
- `cli-args: required: ${this.pathOf(owner)} holds commands, so --${this.flagLong[h]} can never be checked`
642
- )
948
+ const r = this.tryRequired(f)
949
+ if (r.isErr()) {
950
+ // A declaration mistake, which the program's own code makes.
951
+ panic(r.error)
643
952
  }
644
- if (this.flagHasDefault[h]) {
645
- panic(`cli-args: required: --${this.flagLong[h]} has a default, so it can never be missing`)
953
+ }
954
+
955
+ /**
956
+ * `repeatable`, answering a mistake rather than panicking on it.
957
+ *
958
+ * @param f the handle of a flag that takes a value
959
+ * @returns nothing, or the error `repeatable` would panic with, and then
960
+ * the flag is unchanged
961
+ */
962
+ tryRepeatable(f: i32): Result<void, string> {
963
+ const at = this.flagAt("repeatable", f)
964
+ if (at.isErr()) {
965
+ return Err(at.error)
646
966
  }
647
- if (!this.flagRequired[h]) {
648
- this.flagRequired[h] = true
649
- if (owner === GLOBAL) {
650
- this.globalRequired.push(h)
651
- } else {
652
- this.cmdRequired[owner].push(h)
653
- }
967
+ const fl = at.value
968
+ if (fl.value === VALUE_NONE) {
969
+ return Err(`cli-args: repeatable: --${fl.long} takes no value`)
654
970
  }
971
+ fl.repeatable = true
972
+ return Ok()
655
973
  }
656
974
 
657
975
  /**
@@ -662,11 +980,43 @@ export class Cli {
662
980
  * takes none
663
981
  */
664
982
  repeatable(f: i32): void {
665
- const h = this.checkFlag("repeatable", f)
666
- if (this.flagValue[h] === VALUE_NONE) {
667
- panic(`cli-args: repeatable: --${this.flagLong[h]} takes no value`)
983
+ const r = this.tryRepeatable(f)
984
+ if (r.isErr()) {
985
+ // A declaration mistake, which the program's own code makes.
986
+ panic(r.error)
987
+ }
988
+ }
989
+
990
+ /**
991
+ * `negatable`, answering a mistake rather than panicking on it.
992
+ *
993
+ * @param f the handle of a flag declared `--x` with no value
994
+ * @returns nothing, or the error `negatable` would panic with, and then
995
+ * the flag is unchanged
996
+ */
997
+ tryNegatable(f: i32): Result<void, string> {
998
+ const at = this.flagAt("negatable", f)
999
+ if (at.isErr()) {
1000
+ return Err(at.error)
1001
+ }
1002
+ const fl = at.value
1003
+ const call = `negatable(--${fl.long})`
1004
+ if (fl.value !== VALUE_NONE || fl.negated) {
1005
+ return Err(`cli-args: ${call}: only a boolean flag declared '--name' can be negated`)
1006
+ }
1007
+ const owner = fl.owner
1008
+ const name = `no-${fl.long}`
1009
+ let clash = this.taken(owner, `--${name}`) || (owner !== GLOBAL && this.taken(GLOBAL, `--${name}`))
1010
+ for (let g: i32 = 0; g < toI32(this.flagList.length) && owner === GLOBAL && !clash; g++) {
1011
+ clash = this.flagList[g].answersTo(name)
1012
+ }
1013
+ if (clash) {
1014
+ return Err(`cli-args: ${call}: --${name} is already declared`)
668
1015
  }
669
- this.flagRepeatable[h] = true
1016
+ this.negations.set(scopeKey(owner, `--${name}`), fl)
1017
+ // Marked last, or `answersTo` above would take `fl` for a clash with itself.
1018
+ fl.negatable = true
1019
+ return Ok()
670
1020
  }
671
1021
 
672
1022
  /**
@@ -677,47 +1027,38 @@ export class Cli {
677
1027
  * already a name a flag in its reach answers to
678
1028
  */
679
1029
  negatable(f: i32): void {
680
- const h = this.checkFlag("negatable", f)
681
- const call = `negatable(--${this.flagLong[h]})`
682
- if (this.flagValue[h] !== VALUE_NONE || this.flagNegated[h]) {
683
- panic(`cli-args: ${call}: only a boolean flag declared '--name' can be negated`)
1030
+ const r = this.tryNegatable(f)
1031
+ if (r.isErr()) {
1032
+ // A declaration mistake, which the program's own code makes.
1033
+ panic(r.error)
684
1034
  }
685
- const owner: i32 = this.flagOwner[h]
686
- const name = `no-${this.flagLong[h]}`
687
- let clash = this.taken(owner, `--${name}`) || (owner !== GLOBAL && this.taken(GLOBAL, `--${name}`))
688
- for (let g: i32 = 0; g < toI32(this.flagLong.length) && owner === GLOBAL && !clash; g++) {
689
- clash = this.answersTo(g, name)
690
- }
691
- if (clash) {
692
- panic(`cli-args: ${call}: --${name} is already declared`)
693
- }
694
- this.negations.set(scopeKey(owner, `--${name}`), h)
695
- this.flagNegatable[h] = true
696
1035
  }
697
1036
 
698
1037
  /**
699
- * A positional argument of the command `cmd`: `<name>` required, `[name]`
700
- * optional, `<name...>` or `[name...]` taking every one left, last only.
1038
+ * `argument`, answering a mistake rather than panicking on it.
701
1039
  *
702
- * @param cmd the handle of the command that takes the argument; panics on
703
- * a group, or on the root once it holds commands
704
- * @param spec the argument as the help writes it, one of the four forms
705
- * above; panics on a malformed one, on any argument after a variadic one,
706
- * and on a required one after an optional one
1040
+ * @param cmd the handle of the command that takes the argument
1041
+ * @param spec the argument as the help writes it, in `argument`'s forms
707
1042
  * @param description the argument's line in `cmd`'s `Arguments` help
708
1043
  * section
709
- * @returns the argument's handle, for `ParseResult.positional` and
710
- * `positionals`
1044
+ * @returns the argument, for `ParseResult.readPositional` and
1045
+ * `readPositionals` and, by its `handle`, for `positional` and
1046
+ * `positionals`; or the error `argument` would panic with, and then the
1047
+ * tree is unchanged
711
1048
  */
712
- argument(cmd: i32, spec: string, description: string): i32 {
1049
+ tryArgument(cmd: i32, spec: string, description: string): Result<CliArgument, string> {
713
1050
  const call = `argument("${spec}")`
714
- const c = this.checkCommand(call, cmd)
715
- if (this.cmdGroup[c]) {
716
- panic(`cli-args: ${call}: ${this.pathOf(c)} holds commands, so it takes no arguments`)
1051
+ const at = this.commandAt(call, cmd)
1052
+ if (at.isErr()) {
1053
+ return Err(at.error)
1054
+ }
1055
+ const c = at.value
1056
+ if (c.group) {
1057
+ return Err(`cli-args: ${call}: ${c.path} holds commands, so it takes no arguments`)
717
1058
  }
718
1059
  const required = spec.startsWith("<") && spec.endsWith(">")
719
1060
  if (!required && !(spec.startsWith("[") && spec.endsWith("]"))) {
720
- panic(`cli-args: ${call}: bad argument spec: an argument is written <name> or [name]`)
1061
+ return Err(`cli-args: ${call}: bad argument spec: an argument is written <name> or [name]`)
721
1062
  }
722
1063
  let name = spec.substring(1, spec.length - 1)
723
1064
  const variadic = name.endsWith("...")
@@ -725,34 +1066,70 @@ export class Cli {
725
1066
  name = name.substring(0, name.length - 3)
726
1067
  }
727
1068
  if (!isWord(name)) {
728
- panic(`cli-args: ${call}: bad argument spec: the name is empty or has a space, '=' or leading dash`)
1069
+ return Err(
1070
+ `cli-args: ${call}: bad argument spec: the name is empty or has a space, '=' or leading dash`
1071
+ )
729
1072
  }
730
- if (this.cmdVariadic[c]) {
731
- panic(`cli-args: ${call}: no argument may follow a variadic one`)
1073
+ if (c.variadic) {
1074
+ return Err(`cli-args: ${call}: no argument may follow a variadic one`)
732
1075
  }
733
- if (required && this.cmdOptionalArg[c]) {
734
- panic(`cli-args: ${call}: a required argument may not follow an optional one`)
1076
+ if (required && c.optionalArg) {
1077
+ return Err(`cli-args: ${call}: a required argument may not follow an optional one`)
735
1078
  }
736
- const handle: i32 = toI32(this.argName.length)
737
- const last: i32 = this.cmdLastArg[c]
738
- let index: i32 = 0
739
- if (last >= 0 && last < toI32(this.argNext.length)) {
740
- this.argNext[last] = handle
741
- index = this.argIndex[last] + 1
742
- } else {
743
- this.cmdFirstArg[c] = handle
1079
+ const a = new CliArgument(
1080
+ toI32(this.argList.length),
1081
+ c.handle,
1082
+ name,
1083
+ required,
1084
+ variadic,
1085
+ description,
1086
+ toI32(c.args.length)
1087
+ )
1088
+ c.args.push(a)
1089
+ c.variadic = variadic
1090
+ c.optionalArg = !required
1091
+ this.argList.push(a)
1092
+ return Ok(a)
1093
+ }
1094
+
1095
+ /**
1096
+ * A positional argument of the command `cmd`: `<name>` required, `[name]`
1097
+ * optional, `<name...>` or `[name...]` taking every one left, last only.
1098
+ *
1099
+ * @param cmd the handle of the command that takes the argument; panics on
1100
+ * a group, or on the root once it holds commands
1101
+ * @param spec the argument as the help writes it, one of the four forms
1102
+ * above; panics on a malformed one, on any argument after a variadic one,
1103
+ * and on a required one after an optional one
1104
+ * @param description the argument's line in `cmd`'s `Arguments` help
1105
+ * section
1106
+ * @returns the argument's handle, for `ParseResult.positional` and
1107
+ * `positionals`
1108
+ */
1109
+ argument(cmd: i32, spec: string, description: string): i32 {
1110
+ const a = this.tryArgument(cmd, spec, description)
1111
+ if (a.isErr()) {
1112
+ // A declaration mistake, which the program's own code makes.
1113
+ panic(a.error)
1114
+ }
1115
+ return a.value.handle
1116
+ }
1117
+
1118
+ /**
1119
+ * `epilog`, answering a mistake rather than panicking on it.
1120
+ *
1121
+ * @param handle the command or group (or `ROOT`) whose help ends with it
1122
+ * @param text what follows a blank line after the last row
1123
+ * @returns nothing, or the error `epilog` would panic with on a handle no
1124
+ * declaration answered
1125
+ */
1126
+ tryEpilog(handle: i32, text: string): Result<void, string> {
1127
+ const at = this.commandAt("epilog", handle)
1128
+ if (at.isErr()) {
1129
+ return Err(at.error)
744
1130
  }
745
- this.cmdLastArg[c] = handle
746
- this.cmdVariadic[c] = variadic
747
- this.cmdOptionalArg[c] = !required
748
- this.argOwner.push(c)
749
- this.argName.push(name)
750
- this.argRequired.push(required)
751
- this.argVariadic.push(variadic)
752
- this.argDesc.push(description)
753
- this.argIndex.push(index)
754
- this.argNext.push(NONE)
755
- return handle
1131
+ at.value.epilog = text
1132
+ return Ok()
756
1133
  }
757
1134
 
758
1135
  /**
@@ -764,33 +1141,35 @@ export class Cli {
764
1141
  * none, and a later call replaces an earlier one
765
1142
  */
766
1143
  epilog(handle: i32, text: string): void {
767
- const h = this.checkCommand("epilog", handle)
768
- this.cmdEpilog[h] = text
1144
+ const r = this.tryEpilog(handle, text)
1145
+ if (r.isErr()) {
1146
+ // A handle no declaration answered: the program's own mistake.
1147
+ panic(r.error)
1148
+ }
769
1149
  }
770
1150
 
771
1151
  /**
772
1152
  * The flag `name` (dashes included) names in `table` at `cmd`: its own, then
773
- * a global; -1 for none. `table` is `flags`, or `negations` for `--no-x`.
1153
+ * a global; null for none. `table` is `flags`, or `negations` for `--no-x`.
774
1154
  */
775
- private lookup(table: Map<string, i32>, cmd: i32, name: string): i32 {
776
- const own = table.get(scopeKey(cmd, name)) ?? -1
777
- return own >= 0 ? own : (table.get(scopeKey(GLOBAL, name)) ?? -1)
778
- }
779
-
780
- /** @internal Called by `ParseResult`. How `f` is spelled on the command line: its long name, or `--no-x` for one declared that way. */
781
- spelling(f: i32): string {
782
- const h = this.checkFlag("spelling", f)
783
- return this.flagNegated[h] ? `--no-${this.flagLong[h]}` : `--${this.flagLong[h]}`
1155
+ private lookup(table: Map<string, CliFlag>, cmd: i32, name: string): CliFlag | null {
1156
+ const own = table.get(scopeKey(cmd, name))
1157
+ if (own !== undefined) {
1158
+ return own
1159
+ }
1160
+ const global = table.get(scopeKey(GLOBAL, name))
1161
+ return global !== undefined ? global : null
784
1162
  }
785
1163
 
786
1164
  /** Every long flag `cmd` answers to, for a did-you-mean. */
787
1165
  private longNames(cmd: i32): string[] {
788
1166
  const names: string[] = []
789
- for (let f: i32 = 0; f < toI32(this.flagLong.length); f++) {
790
- if (this.flagOwner[f] === cmd || this.flagOwner[f] === GLOBAL) {
791
- names.push(`--${this.flagLong[f]}`)
792
- if (this.flagNegatable[f]) {
793
- names.push(`--no-${this.flagLong[f]}`)
1167
+ for (let i: i32 = 0; i < toI32(this.flagList.length); i++) {
1168
+ const f = this.flagList[i]
1169
+ if (f.owner === cmd || f.owner === GLOBAL) {
1170
+ names.push(`--${f.long}`)
1171
+ if (f.negatable) {
1172
+ names.push(`--no-${f.long}`)
794
1173
  }
795
1174
  }
796
1175
  }
@@ -804,19 +1183,16 @@ export class Cli {
804
1183
  /** @internal Called by `ParseResult`. The names `cmd`'s children answer to, in declaration order, then their aliases when `withAliases`. */
805
1184
  childNames(cmd: i32, withAliases: boolean): string[] {
806
1185
  const names: string[] = []
807
- for (let c: i32 = 0; c < toI32(this.cmdName.length); c++) {
808
- if (this.cmdParent[c] === cmd) {
809
- names.push(this.cmdName[c])
1186
+ for (let i: i32 = 0; i < toI32(this.cmds.length); i++) {
1187
+ const c = this.cmds[i]
1188
+ if (c.parent === cmd) {
1189
+ names.push(c.name)
810
1190
  }
811
1191
  }
812
- for (
813
- let i: i32 = 0;
814
- withAliases && i < toI32(this.aliasName.length) && i < toI32(this.aliasOwner.length);
815
- i++
816
- ) {
817
- const owner: i32 = this.aliasOwner[i]
818
- if (owner >= 0 && owner < toI32(this.cmdParent.length) && this.cmdParent[owner] === cmd) {
819
- names.push(this.aliasName[i])
1192
+ for (let i: i32 = 0; withAliases && i < toI32(this.aliasList.length); i++) {
1193
+ const al = this.aliasList[i]
1194
+ if (al.parent === cmd) {
1195
+ names.push(al.name)
820
1196
  }
821
1197
  }
822
1198
  return names
@@ -848,10 +1224,11 @@ export class Cli {
848
1224
  dashed = true
849
1225
  } else if (token.length > 1 && toI32(token.charCodeAt(0)) === DASH) {
850
1226
  i = token.startsWith("--") ? this.longFlag(r, argv, i, token) : this.shortFlags(r, argv, i, token)
851
- } else if (this.cmdGroup[r.command] && !r.badCommand) {
852
- const child = this.children.get(scopeKey(r.command, token)) ?? -1
853
- if (child >= 0) {
854
- r.command = child
1227
+ } else if (r.at.group && !r.badCommand) {
1228
+ const child = this.children.get(scopeKey(r.command, token))
1229
+ if (child !== undefined) {
1230
+ r.command = child.handle
1231
+ r.at = child
855
1232
  } else if (r.command === ROOT && token === "help") {
856
1233
  r.wantHelp = true
857
1234
  r.helpWord = true
@@ -871,7 +1248,7 @@ export class Cli {
871
1248
  const near = closest(token, this.childNames(r.command, true))
872
1249
  r.badCommand = true
873
1250
  r.fail(
874
- r.command,
1251
+ r.at,
875
1252
  near.length > 0 ? `unknown command '${token}' (did you mean '${near}'?)` : `unknown command '${token}'`
876
1253
  )
877
1254
  }
@@ -889,31 +1266,29 @@ export class Cli {
889
1266
  return next
890
1267
  }
891
1268
  const f = this.lookup(this.flags, r.command, name)
892
- if (f >= 0) {
1269
+ if (f !== null) {
893
1270
  if (eq >= 0) {
894
- if (this.flagValue[f] === VALUE_NONE) {
895
- r.fail(r.command, `${name} takes no value`)
1271
+ if (f.value === VALUE_NONE) {
1272
+ r.fail(r.at, `${name} takes no value`)
896
1273
  } else {
897
- r.set(f, token.substring(eq + 1, token.length))
1274
+ // From the `=` on, less the `=` itself: no index arithmetic.
1275
+ r.set(f, token.substring(eq).substring(1))
898
1276
  }
899
1277
  return next
900
1278
  }
901
1279
  return this.takeValue(r, argv, next, f, "")
902
1280
  }
903
1281
  const off = this.lookup(this.negations, r.command, name)
904
- if (off >= 0) {
1282
+ if (off !== null) {
905
1283
  if (eq >= 0) {
906
- r.fail(r.command, `${name} takes no value`)
1284
+ r.fail(r.at, `${name} takes no value`)
907
1285
  } else {
908
1286
  r.set(off, "false")
909
1287
  }
910
1288
  return next
911
1289
  }
912
1290
  const near = closest(name, this.longNames(r.command))
913
- r.fail(
914
- r.command,
915
- near.length > 0 ? `unknown flag ${name} (did you mean ${near}?)` : `unknown flag ${name}`
916
- )
1291
+ r.fail(r.at, near.length > 0 ? `unknown flag ${name} (did you mean ${near}?)` : `unknown flag ${name}`)
917
1292
  return next
918
1293
  }
919
1294
 
@@ -927,12 +1302,12 @@ export class Cli {
927
1302
  r.wantVersion = true
928
1303
  } else {
929
1304
  const f = this.lookup(this.flags, r.command, `-${letter}`)
930
- if (f < 0) {
931
- r.fail(r.command, `unknown flag -${letter}`)
1305
+ if (f === null) {
1306
+ r.fail(r.at, `unknown flag -${letter}`)
932
1307
  return next
933
1308
  }
934
1309
  const attached = token.substring(k + 1, token.length)
935
- if (this.flagValue[f] !== VALUE_NONE) {
1310
+ if (f.value !== VALUE_NONE) {
936
1311
  if (attached.startsWith("=")) {
937
1312
  r.set(f, attached.substring(1, attached.length))
938
1313
  return next
@@ -940,10 +1315,10 @@ export class Cli {
940
1315
  return this.takeValue(r, argv, next, f, attached)
941
1316
  }
942
1317
  if (attached.startsWith("=")) {
943
- r.fail(r.command, `-${letter} takes no value`)
1318
+ r.fail(r.at, `-${letter} takes no value`)
944
1319
  return next
945
1320
  }
946
- r.set(f, this.flagNegated[f] ? "false" : "true")
1321
+ r.set(f, f.negated ? "false" : "true")
947
1322
  }
948
1323
  }
949
1324
  return next
@@ -954,9 +1329,8 @@ export class Cli {
954
1329
  * not empty, or else the token at `next` when the flag's value takes it;
955
1330
  * answers the index after whatever it took.
956
1331
  */
957
- private takeValue(r: ParseResult, argv: string[], next: i32, f: i32, attached: string): i32 {
958
- const kind: i32 = this.flagValue[f]
959
- if (kind === VALUE_NONE) {
1332
+ private takeValue(r: ParseResult, argv: string[], next: i32, f: CliFlag, attached: string): i32 {
1333
+ if (f.value === VALUE_NONE) {
960
1334
  r.set(f, "true")
961
1335
  return next
962
1336
  }
@@ -964,39 +1338,37 @@ export class Cli {
964
1338
  r.set(f, attached)
965
1339
  return next
966
1340
  }
967
- const has = next >= 0 && next < toI32(argv.length)
968
- if (kind === VALUE_REQUIRED) {
969
- if (!has) {
970
- r.fail(r.command, `--${this.flagLong[f]} needs a value`)
971
- return next
1341
+ if (next >= 0 && next < toI32(argv.length)) {
1342
+ const word = argv[next]
1343
+ const after: i32 = next + 1
1344
+ if (f.value === VALUE_REQUIRED || !(word.length > 0 && toI32(word.charCodeAt(0)) === DASH)) {
1345
+ r.set(f, word)
1346
+ return after
972
1347
  }
973
- r.set(f, argv[next])
974
- return next + 1
975
- }
976
- if (has && (argv[next].length === 0 || toI32(argv[next].charCodeAt(0)) !== DASH)) {
977
- r.set(f, argv[next])
978
- return next + 1
1348
+ } else if (f.value === VALUE_REQUIRED) {
1349
+ r.fail(r.at, `--${f.long} needs a value`)
1350
+ return next
979
1351
  }
980
1352
  r.set(f, "")
981
1353
  return next
982
1354
  }
983
1355
 
984
1356
  /** A help row's flag column for `f`: `-s, --long`, with `--[no-]x` for a negatable one. */
985
- private flagLabel(f: i32): string {
986
- const long = this.flagNegatable[f] ? `--[no-]${this.flagLong[f]}` : this.spelling(f)
987
- return this.flagShort[f].length > 0 ? `-${this.flagShort[f]}, ${long}` : long
1357
+ private flagLabel(f: CliFlag): string {
1358
+ const long = f.negatable ? `--[no-]${f.long}` : f.spelling()
1359
+ return f.short.length > 0 ? `-${f.short}, ${long}` : long
988
1360
  }
989
1361
 
990
1362
  /** A help row's description for `f`, with what it is: repeatable, its default, required. */
991
- private flagText(f: i32): string {
992
- let text = this.flagDesc[f]
993
- if (this.flagRepeatable[f]) {
1363
+ private flagText(f: CliFlag): string {
1364
+ let text = f.description
1365
+ if (f.repeatable) {
994
1366
  text = `${text} (repeatable)`
995
1367
  }
996
- if (this.flagHasDefault[f]) {
997
- text = `${text} (default: ${this.flagDefault[f]})`
1368
+ if (f.hasDefault) {
1369
+ text = `${text} (default: ${f.fallback})`
998
1370
  }
999
- if (this.flagRequired[f]) {
1371
+ if (f.required) {
1000
1372
  text = `${text} (required)`
1001
1373
  }
1002
1374
  return text
@@ -1004,66 +1376,70 @@ export class Cli {
1004
1376
 
1005
1377
  /** Adds a `section` row to `rows` for every flag `owner` (a command, or `GLOBAL`) declares. */
1006
1378
  private flagRows(rows: HelpRow[], section: string, owner: i32): void {
1007
- for (let f: i32 = 0; f < toI32(this.flagLong.length); f++) {
1008
- if (this.flagOwner[f] === owner) {
1009
- rows.push(new HelpRow(section, this.flagLabel(f), this.flagMeta[f], this.flagText(f)))
1379
+ for (let i: i32 = 0; i < toI32(this.flagList.length); i++) {
1380
+ const f = this.flagList[i]
1381
+ if (f.owner === owner) {
1382
+ rows.push(new HelpRow(section, this.flagLabel(f), f.meta, this.flagText(f)))
1010
1383
  }
1011
1384
  }
1012
1385
  }
1013
1386
 
1014
- /**
1015
- * The help of the command or group `handle`, painted with `style`.
1016
- *
1017
- * @param handle the command or group (or `ROOT`) whose help it is; panics
1018
- * on a handle no declaration answered
1019
- * @param style how the help's names and headings are painted; a style
1020
- * that is off gives plain text
1021
- * @returns a fresh string, the whole page, built on each call
1022
- */
1023
- helpText(handle: i32, style: Style): string {
1024
- const cmd = this.checkCommand("help", handle)
1387
+ /** @internal Called by `ParseResult`. The help of the command or group `c`, painted with `style`. */
1388
+ helpOf(c: CommandRec, style: Style): string {
1025
1389
  const rows: HelpRow[] = []
1026
1390
  const shape: string[] = []
1027
- const path = this.pathOf(cmd)
1028
- if (path.length > this.name.length) {
1029
- shape.push(path.substring(this.name.length + 1, path.length))
1391
+ if (c.handle !== ROOT) {
1392
+ // The path past the program's name and the space after it.
1393
+ shape.push(c.path.substring(this.name.length).substring(1))
1030
1394
  }
1031
- if (this.cmdGroup[cmd]) {
1395
+ if (c.group) {
1032
1396
  shape.push("<command>")
1033
- for (let c: i32 = 0; c < toI32(this.cmdName.length); c++) {
1034
- if (this.cmdParent[c] === cmd) {
1035
- const aliases = this.cmdAliases[c]
1036
- const label = aliases.length > 0 ? `${this.cmdName[c]}, ${aliases}` : this.cmdName[c]
1037
- rows.push(new HelpRow("Commands", label, "", this.cmdDesc[c]))
1397
+ for (let i: i32 = 0; i < toI32(this.cmds.length); i++) {
1398
+ const child = this.cmds[i]
1399
+ if (child.parent === c.handle) {
1400
+ const label = child.aliases.length > 0 ? `${child.name}, ${child.aliases}` : child.name
1401
+ rows.push(new HelpRow("Commands", label, "", child.description))
1038
1402
  }
1039
1403
  }
1040
1404
  }
1041
- let a: i32 = this.cmdFirstArg[cmd]
1042
- while (a >= 0 && a < toI32(this.argName.length)) {
1043
- const dots = this.argVariadic[a] ? "..." : ""
1044
- const label = this.argRequired[a] ? `<${this.argName[a]}${dots}>` : `[${this.argName[a]}${dots}]`
1405
+ for (let i: i32 = 0; i < toI32(c.args.length); i++) {
1406
+ const a = c.args[i]
1407
+ const dots = a.variadic ? "..." : ""
1408
+ const label = a.required ? `<${a.name}${dots}>` : `[${a.name}${dots}]`
1045
1409
  shape.push(label)
1046
- rows.push(new HelpRow("Arguments", label, "", this.argDesc[a]))
1047
- a = this.argNext[a]
1410
+ rows.push(new HelpRow("Arguments", label, "", a.description))
1048
1411
  }
1049
1412
  shape.push("[flags]")
1050
- this.flagRows(rows, "Flags", cmd)
1413
+ this.flagRows(rows, "Flags", c.handle)
1051
1414
  rows.push(new HelpRow("Flags", "-h, --help", "", "show help"))
1052
- if (cmd === ROOT) {
1415
+ if (c.handle === ROOT) {
1053
1416
  rows.push(new HelpRow("Flags", "-v, --version", "", "show the version"))
1054
1417
  }
1055
1418
  this.flagRows(rows, "Global flags", GLOBAL)
1056
- let widest: i32 = 0
1057
- for (let i: i32 = 0; i < toI32(rows.length); i++) {
1419
+ // The description column: two past the widest row, at most `MAX_COLUMN`.
1420
+ // A row at least that wide sets it to the most, so only a narrower one's
1421
+ // width is added up, from lengths each below `MAX_COLUMN`.
1422
+ let column: i32 = 2
1423
+ for (let i: i32 = 0; i < toI32(rows.length) && column < MAX_COLUMN; i++) {
1058
1424
  const row = rows[i]
1059
- const width: i32 = 2 + toI32(row.label.length) + (row.meta.length > 0 ? 1 + toI32(row.meta.length) : 0)
1060
- widest = width > widest ? width : widest
1425
+ // Two lengths and a few columns fit an i64, which no row reaches.
1426
+ const width: i64 =
1427
+ row.meta.length > 0
1428
+ ? toI64(toI32(row.label.length)) + toI64(toI32(row.meta.length)) + toI64(5)
1429
+ : toI64(toI32(row.label.length)) + toI64(4)
1430
+ if (width >= toI64(MAX_COLUMN)) {
1431
+ column = MAX_COLUMN
1432
+ } else if (width > toI64(column)) {
1433
+ column = toI32(width)
1434
+ }
1061
1435
  }
1062
1436
  const usage = shape.join(" ")
1063
- const usageColumn: i32 = 8 + toI32(this.name.length) + toI32(usage.length) + 3
1064
- const menu = new HelpMenu(style, this.name, minI32(widest + 2, MAX_COLUMN), usageColumn)
1437
+ const menu = new HelpMenu(style, this.name, column, column)
1065
1438
  menu.header(this.version, this.description)
1066
- menu.usage(usage, cmd === ROOT ? "" : this.cmdDesc[cmd])
1439
+ // The usage line, its description three spaces after the shape: one
1440
+ // line, so it is laid out here rather than against a usage column.
1441
+ const said = c.handle !== ROOT && c.description.length > 0 ? ` ${style.dim(c.description)}` : ""
1442
+ menu.line(`${style.heading("usage:")} ${style.name(this.name)} ${style.flag(usage)}${said}`)
1067
1443
  let open = ""
1068
1444
  for (let i: i32 = 0; i < toI32(rows.length); i++) {
1069
1445
  const row = rows[i]
@@ -1073,12 +1449,30 @@ export class Cli {
1073
1449
  }
1074
1450
  menu.row(row.label, row.meta, row.text)
1075
1451
  }
1076
- if (this.cmdEpilog[cmd].length > 0) {
1452
+ if (c.epilog.length > 0) {
1077
1453
  menu.line("")
1078
- menu.line(this.cmdEpilog[cmd])
1454
+ menu.line(c.epilog)
1079
1455
  }
1080
1456
  return menu.text()
1081
1457
  }
1458
+
1459
+ /**
1460
+ * The help of the command or group `handle`, painted with `style`.
1461
+ *
1462
+ * @param handle the command or group (or `ROOT`) whose help it is; panics
1463
+ * on a handle no declaration answered
1464
+ * @param style how the help's names and headings are painted; a style
1465
+ * that is off gives plain text
1466
+ * @returns a fresh string, the whole page, built on each call
1467
+ */
1468
+ helpText(handle: i32, style: Style): string {
1469
+ const c = this.commandAt("help", handle)
1470
+ if (c.isErr()) {
1471
+ // A handle no declaration answered: the program's own mistake.
1472
+ panic(c.error)
1473
+ }
1474
+ return this.helpOf(c.value, style)
1475
+ }
1082
1476
  }
1083
1477
 
1084
1478
  /** One row of a help page, kept until the widest row sets the column. */
@@ -1100,10 +1494,24 @@ class HelpRow {
1100
1494
  }
1101
1495
  }
1102
1496
 
1497
+ /** One flag the arguments gave, and the value it was given. */
1498
+ class FlagSet {
1499
+ /** @internal Used by `ParseResult`. */
1500
+ flag: i32
1501
+ /** @internal Used by `ParseResult`. */
1502
+ value: string
1503
+
1504
+ constructor(flag: i32, value: string) {
1505
+ this.flag = flag
1506
+ this.value = value
1507
+ }
1508
+ }
1509
+
1103
1510
  /**
1104
1511
  * What `Cli.parse` found: the command the arguments name and every value
1105
1512
  * they set, or that they ask for help or the version, or what is wrong with
1106
- * them. Values are read by the handles the tree was declared with.
1513
+ * them. Values are read by the handles the tree was declared with, or by the
1514
+ * `CliFlag` and `CliArgument` its `try` twins answered.
1107
1515
  */
1108
1516
  export class ParseResult {
1109
1517
  private cli: Cli
@@ -1115,8 +1523,7 @@ export class ParseResult {
1115
1523
  hint: string
1116
1524
  /** The command line of the command an error was found at; empty without one. */
1117
1525
  errorPath: string
1118
- private setFlags: i32[]
1119
- private setValues: string[]
1526
+ private sets: FlagSet[]
1120
1527
  /** @internal Used by `Cli`. */
1121
1528
  positionalValues: string[]
1122
1529
  /** @internal Used by `Cli`. */
@@ -1125,6 +1532,8 @@ export class ParseResult {
1125
1532
  kind: i32
1126
1533
  /** The handle of the deepest command the arguments reached. */
1127
1534
  command: i32
1535
+ /** @internal Used by `Cli`. The record of `command`. */
1536
+ at: CommandRec
1128
1537
  /** That command's id, or -1 for a group. */
1129
1538
  id: i32
1130
1539
  /** The status to exit with: 2 for an error, 0 otherwise. */
@@ -1150,7 +1559,8 @@ export class ParseResult {
1150
1559
  this.cli = cli
1151
1560
  this.kind = PARSE_OK
1152
1561
  this.command = ROOT
1153
- this.id = -1
1562
+ this.at = cli.root
1563
+ this.id = GROUP_ID
1154
1564
  this.path = ""
1155
1565
  this.message = ""
1156
1566
  this.hint = ""
@@ -1160,26 +1570,23 @@ export class ParseResult {
1160
1570
  this.helpWord = false
1161
1571
  this.badCommand = false
1162
1572
  this.wantVersion = false
1163
- this.setFlags = []
1164
- this.setValues = []
1165
-
1573
+ this.sets = []
1166
1574
  this.positionalValues = []
1167
1575
  this.restValues = []
1168
1576
  }
1169
1577
 
1170
- /** @internal Called by `Cli`. Records `text` as the error found at `cmd`, unless one is already recorded: the first wins. */
1171
- fail(cmd: i32, text: string): void {
1578
+ /** @internal Called by `Cli`. Records `text` as the error found at `at`, unless one is already recorded: the first wins. */
1579
+ fail(at: CommandRec, text: string): void {
1172
1580
  if (this.message.length === 0) {
1173
- this.errorPath = this.cli.pathOf(cmd)
1581
+ this.errorPath = at.path
1174
1582
  this.message = `${this.errorPath}: ${text}`
1175
1583
  this.hint = usageHint(`${this.errorPath} --help`)
1176
1584
  }
1177
1585
  }
1178
1586
 
1179
1587
  /** @internal Called by `Cli`. Records flag `f` as given `value`. */
1180
- set(f: i32, value: string): void {
1181
- this.setFlags.push(f)
1182
- this.setValues.push(value)
1588
+ set(f: CliFlag, value: string): void {
1589
+ this.sets.push(new FlagSet(f.handle, value))
1183
1590
  }
1184
1591
 
1185
1592
  /**
@@ -1190,9 +1597,9 @@ export class ParseResult {
1190
1597
  */
1191
1598
  finishWalk(): void {
1192
1599
  const cli = this.cli
1193
- const cmd = this.command
1194
- this.id = cli.cmdId[cmd]
1195
- this.path = cli.pathOf(cmd)
1600
+ const at = this.at
1601
+ this.id = at.id
1602
+ this.path = at.path
1196
1603
  if (this.wantHelp && !(this.helpWord && this.badCommand)) {
1197
1604
  this.kind = PARSE_HELP
1198
1605
  this.message = ""
@@ -1205,32 +1612,28 @@ export class ParseResult {
1205
1612
  this.hint = ""
1206
1613
  return
1207
1614
  }
1208
- if (cli.cmdGroup[cmd]) {
1209
- this.fail(cmd, `missing command (one of: ${cli.childNames(cmd, false).join(", ")})`)
1615
+ if (at.group) {
1616
+ this.fail(at, `missing command (one of: ${cli.childNames(at.handle, false).join(", ")})`)
1210
1617
  }
1211
- let missing: i32 = this.firstMissing(cli.cmdRequired[cmd])
1212
- if (missing < 0) {
1213
- missing = this.firstMissing(cli.globalRequired)
1618
+ let missing = this.firstMissing(at.handle)
1619
+ if (missing === null) {
1620
+ missing = this.firstMissing(GLOBAL)
1214
1621
  }
1215
- if (missing >= 0) {
1216
- this.fail(cmd, `missing required flag ${cli.spelling(missing)}`)
1622
+ if (missing !== null) {
1623
+ this.fail(at, `missing required flag ${missing.spelling()}`)
1217
1624
  }
1218
- let a: i32 = cli.cmdFirstArg[cmd]
1219
- let last: i32 = -1
1220
- while (a >= 0 && a < toI32(cli.argName.length) && this.message.length === 0) {
1221
- if (cli.argRequired[a] && cli.argIndex[a] >= toI32(this.positionalValues.length)) {
1222
- const dots = cli.argVariadic[a] ? "..." : ""
1223
- this.fail(cmd, `missing argument <${cli.argName[a]}${dots}>`)
1625
+ for (let i: i32 = 0; i < toI32(at.args.length) && this.message.length === 0; i++) {
1626
+ const a = at.args[i]
1627
+ if (a.required && a.index >= toI32(this.positionalValues.length)) {
1628
+ const dots = a.variadic ? "..." : ""
1629
+ this.fail(at, `missing argument <${a.name}${dots}>`)
1224
1630
  }
1225
- last = a
1226
- a = cli.argNext[a]
1227
- }
1228
- let taken: i32 = 0
1229
- if (last >= 0) {
1230
- taken = cli.argVariadic[last] ? toI32(this.positionalValues.length) : cli.argIndex[last] + 1
1231
1631
  }
1232
- if (this.message.length === 0 && taken < toI32(this.positionalValues.length) && taken >= 0) {
1233
- this.fail(cmd, `unexpected argument '${this.positionalValues[taken]}'`)
1632
+ // The positionals the arguments take: every one for a variadic last
1633
+ // argument, else one each.
1634
+ const taken: i32 = at.variadic ? toI32(this.positionalValues.length) : toI32(at.args.length)
1635
+ if (this.message.length === 0 && taken >= 0 && taken < toI32(this.positionalValues.length)) {
1636
+ this.fail(at, `unexpected argument '${this.positionalValues[taken]}'`)
1234
1637
  }
1235
1638
  if (this.message.length > 0) {
1236
1639
  this.kind = PARSE_ERROR
@@ -1238,93 +1641,89 @@ export class ParseResult {
1238
1641
  }
1239
1642
  }
1240
1643
 
1241
- /** The first of the `required` flags the arguments did not set, else -1. */
1242
- private firstMissing(required: i32[]): i32 {
1644
+ /** The first required flag of `owner` (a command, or `GLOBAL`) the arguments did not set, else null. */
1645
+ private firstMissing(owner: i32): CliFlag | null {
1646
+ const required = this.cli.requiredFlags
1243
1647
  for (let i: i32 = 0; i < toI32(required.length); i++) {
1244
- if (this.lastSet(required[i]) < 0) {
1245
- return required[i]
1648
+ const f = required[i]
1649
+ if (f.owner === owner && this.lastValue(f.handle) === null) {
1650
+ return f
1246
1651
  }
1247
1652
  }
1248
- return -1
1653
+ return null
1249
1654
  }
1250
1655
 
1251
1656
  /**
1252
- * Where the last value of flag `f` is in `setValues`, or -1 when it was not
1253
- * given: a scan of the flags the arguments set, so bounded by their count.
1657
+ * The last value the arguments gave flag `f`, or null when they did not
1658
+ * give it: a scan of the flags they set, so bounded by their count.
1254
1659
  */
1255
- private lastSet(f: i32): i32 {
1256
- for (let i: i32 = toI32(this.setFlags.length) - 1; i >= 0 && i < toI32(this.setFlags.length); i--) {
1257
- if (this.setFlags[i] === f) {
1258
- return i
1660
+ private lastValue(f: i32): string | null {
1661
+ let found: string | null = null
1662
+ for (let i: i32 = 0; i < toI32(this.sets.length); i++) {
1663
+ const s = this.sets[i]
1664
+ if (s.flag === f) {
1665
+ found = s.value
1259
1666
  }
1260
1667
  }
1261
- return NONE
1668
+ return found
1262
1669
  }
1263
1670
 
1264
1671
  /**
1265
1672
  * Whether flag `f` is on: a boolean's value (true by default for one
1266
1673
  * declared `--no-x`), or for a flag with a value, whether it was given.
1267
1674
  *
1268
- * @param f the handle of a flag anywhere in the tree; panics on a handle
1269
- * no declaration answered
1675
+ * @param f a flag `Cli.tryFlag` or `Cli.tryGlobalFlag` answered
1270
1676
  * @returns the last of the arguments' settings for a boolean, so
1271
1677
  * `--x --no-x` is off
1272
1678
  */
1273
- flag(f: i32): boolean {
1274
- const h = this.cli.checkFlag("flag", f)
1275
- const at = this.lastSet(h)
1276
- if (this.cli.flagValue[h] !== VALUE_NONE) {
1277
- return at >= 0
1278
- }
1279
- if (at >= 0 && at < toI32(this.setValues.length)) {
1280
- return this.setValues[at] === "true"
1679
+ readFlag(f: CliFlag): boolean {
1680
+ const given = this.lastValue(f.handle)
1681
+ if (f.value !== VALUE_NONE) {
1682
+ return given !== null
1281
1683
  }
1282
- return this.cli.flagNegated[h]
1684
+ return given !== null ? given === "true" : f.negated
1283
1685
  }
1284
1686
 
1285
1687
  /**
1286
1688
  * The value of flag `f`: the last one given (empty for `[value]` given
1287
1689
  * none), else its default, else null.
1288
1690
  *
1289
- * @param f the handle of a flag anywhere in the tree; panics on a handle
1290
- * no declaration answered
1691
+ * @param f a flag `Cli.tryFlag` or `Cli.tryGlobalFlag` answered
1291
1692
  * @returns the value as written, or `"true"` or `"false"` for a boolean
1292
1693
  * that was given; null tells a flag never given and with no default
1293
1694
  */
1294
- value(f: i32): string | null {
1295
- const h = this.cli.checkFlag("value", f)
1296
- const at = this.lastSet(h)
1297
- if (at >= 0 && at < toI32(this.setValues.length)) {
1298
- return this.setValues[at]
1695
+ readValue(f: CliFlag): string | null {
1696
+ const given = this.lastValue(f.handle)
1697
+ if (given !== null) {
1698
+ return given
1299
1699
  }
1300
- return this.cli.flagHasDefault[h] ? this.cli.flagDefault[h] : null
1700
+ return f.hasDefault ? f.fallback : null
1301
1701
  }
1302
1702
 
1303
1703
  /**
1304
1704
  * Every value of flag `f` in order for a repeatable one, the last alone
1305
1705
  * for any other, else its default alone, else none.
1306
1706
  *
1307
- * @param f the handle of a flag anywhere in the tree; panics on a handle
1308
- * no declaration answered
1707
+ * @param f a flag `Cli.tryFlag` or `Cli.tryGlobalFlag` answered
1309
1708
  * @returns a fresh array the caller owns
1310
1709
  */
1311
- values(f: i32): string[] {
1312
- const h = this.cli.checkFlag("values", f)
1710
+ readValues(f: CliFlag): string[] {
1313
1711
  const out: string[] = []
1314
- if (this.cli.flagRepeatable[h]) {
1315
- for (let i: i32 = 0; i < toI32(this.setFlags.length) && i < toI32(this.setValues.length); i++) {
1316
- if (this.setFlags[i] === h) {
1317
- out.push(this.setValues[i])
1712
+ if (f.repeatable) {
1713
+ for (let i: i32 = 0; i < toI32(this.sets.length); i++) {
1714
+ const s = this.sets[i]
1715
+ if (s.flag === f.handle) {
1716
+ out.push(s.value)
1318
1717
  }
1319
1718
  }
1320
1719
  } else {
1321
- const at = this.lastSet(h)
1322
- if (at >= 0 && at < toI32(this.setValues.length)) {
1323
- out.push(this.setValues[at])
1720
+ const given = this.lastValue(f.handle)
1721
+ if (given !== null) {
1722
+ out.push(given)
1324
1723
  }
1325
1724
  }
1326
- if (out.length === 0 && this.cli.flagHasDefault[h]) {
1327
- out.push(this.cli.flagDefault[h])
1725
+ if (out.length === 0 && f.hasDefault) {
1726
+ out.push(f.fallback)
1328
1727
  }
1329
1728
  return out
1330
1729
  }
@@ -1333,61 +1732,128 @@ export class ParseResult {
1333
1732
  * Where flag `f`'s value came from: `SOURCE_ARGV`, `SOURCE_DEFAULT` or
1334
1733
  * `SOURCE_UNSET`.
1335
1734
  *
1336
- * @param f the handle of a flag anywhere in the tree; panics on a handle
1337
- * no declaration answered
1735
+ * @param f a flag `Cli.tryFlag` or `Cli.tryGlobalFlag` answered
1338
1736
  * @returns `SOURCE_ARGV` when the arguments gave it, `SOURCE_DEFAULT` when
1339
1737
  * it has a default or is declared `--no-x` (on by default), else
1340
1738
  * `SOURCE_UNSET`
1341
1739
  */
1342
- source(f: i32): i32 {
1343
- const h = this.cli.checkFlag("source", f)
1344
- if (this.lastSet(h) >= 0) {
1740
+ readSource(f: CliFlag): i32 {
1741
+ if (this.lastValue(f.handle) !== null) {
1345
1742
  return SOURCE_ARGV
1346
1743
  }
1347
- return this.cli.flagHasDefault[h] || this.cli.flagNegated[h] ? SOURCE_DEFAULT : SOURCE_UNSET
1744
+ return f.hasDefault || f.negated ? SOURCE_DEFAULT : SOURCE_UNSET
1348
1745
  }
1349
1746
 
1350
1747
  /**
1351
1748
  * The argument `a`'s value, or null when it was not given or belongs to
1352
1749
  * another command.
1353
1750
  *
1354
- * @param a the handle of an argument; panics on a handle no `argument`
1355
- * call answered
1751
+ * @param a an argument `Cli.tryArgument` answered
1356
1752
  * @returns the word at the argument's place among the positionals, which
1357
1753
  * for a variadic one is the first it took
1358
1754
  */
1359
- positional(a: i32): string | null {
1360
- const h = this.cli.checkArgument("positional", a)
1361
- const k: i32 = this.cli.argIndex[h]
1362
- if (this.cli.argOwner[h] !== this.command || !(k >= 0 && k < toI32(this.positionalValues.length))) {
1363
- return null
1755
+ readPositional(a: CliArgument): string | null {
1756
+ const k: i32 = a.index
1757
+ if (a.owner === this.command && k >= 0 && k < toI32(this.positionalValues.length)) {
1758
+ return this.positionalValues[k]
1364
1759
  }
1365
- return this.positionalValues[k]
1760
+ return null
1366
1761
  }
1367
1762
 
1368
1763
  /**
1369
1764
  * Every value from argument `a` on: all a variadic one took, or the one
1370
1765
  * value of any other.
1371
1766
  *
1372
- * @param a the handle of an argument; panics on a handle no `argument`
1373
- * call answered
1767
+ * @param a an argument `Cli.tryArgument` answered
1374
1768
  * @returns a fresh array the caller owns; empty when the argument was not
1375
1769
  * given or belongs to another command
1376
1770
  */
1377
- positionals(a: i32): string[] {
1378
- const h = this.cli.checkArgument("positionals", a)
1771
+ readPositionals(a: CliArgument): string[] {
1379
1772
  const out: string[] = []
1380
- if (this.cli.argOwner[h] !== this.command) {
1773
+ if (a.owner !== this.command) {
1381
1774
  return out
1382
1775
  }
1383
- const k: i32 = this.cli.argIndex[h]
1384
- const end: i32 = this.cli.argVariadic[h] ? toI32(this.positionalValues.length) : k + 1
1385
- for (let i: i32 = k; i < end && i >= 0 && i < toI32(this.positionalValues.length); i++) {
1776
+ for (let i: i32 = a.index; i >= 0 && i < toI32(this.positionalValues.length); i++) {
1386
1777
  out.push(this.positionalValues[i])
1778
+ if (!a.variadic) {
1779
+ break
1780
+ }
1387
1781
  }
1388
1782
  return out
1389
1783
  }
1390
1784
 
1785
+ /**
1786
+ * Whether flag `f` is on, as `readFlag` answers.
1787
+ *
1788
+ * @param f the handle of a flag anywhere in the tree; panics on a handle
1789
+ * no declaration answered
1790
+ * @returns the last of the arguments' settings for a boolean, so
1791
+ * `--x --no-x` is off
1792
+ */
1793
+ flag(f: i32): boolean {
1794
+ return this.readFlag(this.cli.checkFlag("flag", f))
1795
+ }
1796
+
1797
+ /**
1798
+ * The value of flag `f`, as `readValue` answers.
1799
+ *
1800
+ * @param f the handle of a flag anywhere in the tree; panics on a handle
1801
+ * no declaration answered
1802
+ * @returns the value as written, or `"true"` or `"false"` for a boolean
1803
+ * that was given; null tells a flag never given and with no default
1804
+ */
1805
+ value(f: i32): string | null {
1806
+ return this.readValue(this.cli.checkFlag("value", f))
1807
+ }
1808
+
1809
+ /**
1810
+ * Every value of flag `f`, as `readValues` answers.
1811
+ *
1812
+ * @param f the handle of a flag anywhere in the tree; panics on a handle
1813
+ * no declaration answered
1814
+ * @returns a fresh array the caller owns
1815
+ */
1816
+ values(f: i32): string[] {
1817
+ return this.readValues(this.cli.checkFlag("values", f))
1818
+ }
1819
+
1820
+ /**
1821
+ * Where flag `f`'s value came from, as `readSource` answers.
1822
+ *
1823
+ * @param f the handle of a flag anywhere in the tree; panics on a handle
1824
+ * no declaration answered
1825
+ * @returns `SOURCE_ARGV` when the arguments gave it, `SOURCE_DEFAULT` when
1826
+ * it has a default or is declared `--no-x` (on by default), else
1827
+ * `SOURCE_UNSET`
1828
+ */
1829
+ source(f: i32): i32 {
1830
+ return this.readSource(this.cli.checkFlag("source", f))
1831
+ }
1832
+
1833
+ /**
1834
+ * The argument `a`'s value, as `readPositional` answers.
1835
+ *
1836
+ * @param a the handle of an argument; panics on a handle no `argument`
1837
+ * call answered
1838
+ * @returns the word at the argument's place among the positionals, which
1839
+ * for a variadic one is the first it took
1840
+ */
1841
+ positional(a: i32): string | null {
1842
+ return this.readPositional(this.cli.checkArgument("positional", a))
1843
+ }
1844
+
1845
+ /**
1846
+ * Every value from argument `a` on, as `readPositionals` answers.
1847
+ *
1848
+ * @param a the handle of an argument; panics on a handle no `argument`
1849
+ * call answered
1850
+ * @returns a fresh array the caller owns; empty when the argument was not
1851
+ * given or belongs to another command
1852
+ */
1853
+ positionals(a: i32): string[] {
1854
+ return this.readPositionals(this.cli.checkArgument("positionals", a))
1855
+ }
1856
+
1391
1857
  /**
1392
1858
  * The tokens after `--`, in order. They are positionals too, so an
1393
1859
  * argument may also have taken them.
@@ -1407,7 +1873,7 @@ export class ParseResult {
1407
1873
  * @returns a fresh string, the whole page, built on each call
1408
1874
  */
1409
1875
  help(style: Style): string {
1410
- return this.cli.helpText(this.command, style)
1876
+ return this.cli.helpOf(this.at, style)
1411
1877
  }
1412
1878
  }
1413
1879