frost-parser 0.1.19

Zsh-compatible recursive descent parser
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
use compact_str::CompactString;
use frost_lexer::Span;

#[derive(Debug, Clone, PartialEq, Default)]
pub struct Program {
    pub commands: Vec<CompleteCommand>,
    /// Syntax errors the parser recovered from, in source order.
    ///
    /// ## Why this exists, and why it is not `Result`
    ///
    /// `Parser::expect` recovers from a token mismatch by skipping and
    /// carrying on, which is right for an interactive shell — it lets a
    /// half-typed line still produce a usable AST. What was wrong is that the
    /// recovery was SILENT: the `ParseError` type existed and was never once
    /// constructed, so a syntax error and a correct parse were indistinguishable
    /// to every caller.
    ///
    /// That is not a cosmetic gap. `while true` with no `do` recovered into
    /// `While { condition: [true], body: [] }` — a syntactically-valid infinite
    /// loop with an empty body — and the executor ran it forever. zsh 5.9, bash
    /// and dash all reject that input outright. It was found by
    /// `tools/hang-sweep.tlisp`, which looks for non-termination as a property
    /// distinct from wrongness.
    ///
    /// So recovery is kept and the evidence is recorded alongside it: a
    /// non-empty vec means the program is not what the author wrote, and a
    /// non-interactive caller refuses to run it (POSIX puts a shell script's
    /// syntax-error exit at 2, which is what `frost_exec::execute` returns).
    pub syntax_errors: Vec<String>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct CompleteCommand {
    pub list: List,
    pub is_async: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub struct List {
    pub first: Pipeline,
    pub rest: Vec<(ListOp, Pipeline)>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ListOp {
    And,
    Or,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Pipeline {
    pub bang: bool,
    pub commands: Vec<Command>,
    pub pipe_stderr: Vec<bool>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Command {
    Simple(SimpleCommand),
    Subshell(Subshell),
    BraceGroup(BraceGroup),
    If(Box<IfClause>),
    For(Box<ForClause>),
    While(Box<WhileClause>),
    Until(Box<UntilClause>),
    Case(Box<CaseClause>),
    Select(Box<SelectClause>),
    FunctionDef(Box<FunctionDef>),
    Coproc(Box<Coproc>),
    Time(Box<TimeClause>),
    /// `(( expr ))` — arithmetic evaluation command.
    ArithCmd(CompactString),
    /// `[[ expr ]]` — conditional expression.
    Cond(Box<CondExpr>),
    /// `for (( init; cond; step )) { body }` — C-style for loop.
    CFor(Box<CForClause>),
    /// `repeat N { body }` — repeat loop.
    Repeat(Box<RepeatClause>),
    /// `{ try } always { always }` — try-always block.
    TryAlways(Box<TryAlwaysClause>),
}

/// Conditional expression inside `[[ … ]]`.
#[derive(Debug, Clone, PartialEq)]
pub enum CondExpr {
    Unary(CondOp, Word),
    Binary(Word, CondOp, Word),
    Not(Box<CondExpr>),
    And(Box<CondExpr>, Box<CondExpr>),
    Or(Box<CondExpr>, Box<CondExpr>),
}

/// Operators for `[[ … ]]` conditions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CondOp {
    // File tests
    FileExists,        // -e, -a
    IsFile,            // -f
    IsDir,             // -d
    IsSymlink,         // -L, -h
    IsReadable,        // -r
    IsWritable,        // -w
    IsExecutable,      // -x
    IsNonEmpty,        // -s
    IsBlockDev,        // -b
    IsCharDev,         // -c
    IsFifo,            // -p
    IsSocket,          // -S
    IsSetuid,          // -u
    IsSetgid,          // -g
    IsSticky,          // -k
    OwnedByUser,       // -O
    OwnedByGroup,      // -G
    ModifiedSinceRead, // -N
    IsTty,             // -t
    OptionSet,         // -o
    VarIsSet,          // -v
    // String tests
    StrEmpty,    // -z
    StrNonEmpty, // -n
    StrEq,       // == or =
    StrNeq,      // !=
    StrLt,       // <
    StrGt,       // >
    StrMatch,    // =~
    // Integer tests
    IntEq,
    IntNe,
    IntLt,
    IntLe,
    IntGt,
    IntGe,
    // File comparisons
    NewerThan, // -nt
    OlderThan, // -ot
    SameFile,  // -ef
}

/// C-style for loop: `for (( init; cond; step )) { body }`.
#[derive(Debug, Clone, PartialEq)]
pub struct CForClause {
    pub init: CompactString,
    pub condition: CompactString,
    pub step: CompactString,
    pub body: Vec<CompleteCommand>,
    pub redirects: Vec<Redirect>,
}

/// `repeat N { body }` loop.
#[derive(Debug, Clone, PartialEq)]
pub struct RepeatClause {
    pub count: Word,
    pub body: Vec<CompleteCommand>,
    pub redirects: Vec<Redirect>,
}

/// `{ try } always { always }` block.
#[derive(Debug, Clone, PartialEq)]
pub struct TryAlwaysClause {
    pub try_body: Vec<CompleteCommand>,
    pub always_body: Vec<CompleteCommand>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct SimpleCommand {
    pub assignments: Vec<Assignment>,
    pub words: Vec<Word>,
    pub redirects: Vec<Redirect>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Word {
    pub parts: Vec<WordPart>,
    pub span: Span,
}

#[derive(Debug, Clone, PartialEq)]
pub enum WordPart {
    Literal(CompactString),
    SingleQuoted(CompactString),
    DoubleQuoted(Vec<WordPart>),
    /// `$'…'` — ANSI-C quoting. Carries the RAW body with escapes still
    /// encoded; `frost_expand::expand_ansi_c` decodes them.
    ///
    /// A distinct variant rather than a pre-decoded `SingleQuoted` because
    /// the two differ where it matters: this one is the only quoted form
    /// whose *value* is a function of its text, and keeping the decode on
    /// the expansion side keeps the parser purely syntactic. It behaves like
    /// `SingleQuoted` everywhere else — one field, no expansion inside, no
    /// splitting or globbing after.
    AnsiCQuoted(CompactString),
    DollarVar(CompactString),
    DollarBrace {
        param: CompactString,
        operator: Option<CompactString>,
        arg: Option<Box<Word>>,
    },
    /// Structured parameter expansion — rich `${...}` forms.
    ParamExp(Box<ParamExpansion>),
    CommandSub(Box<Program>),
    ArithSub(CompactString),
    Glob(GlobKind),
    Tilde(CompactString),
    /// Brace expansion: `{a,b,c}` or `{1..10}`.
    BraceExp(BraceExpansion),
    /// Process substitution: `<(cmd)` or `>(cmd)`.
    ProcessSub {
        kind: ProcessSubKind,
        body: Box<Program>,
    },
    /// Extended glob: `*(pat)`, `+(pat)`, `?(pat)`, `@(pat)`, `!(pat)`.
    ExtGlob {
        op: ExtGlobOp,
        pattern: CompactString,
    },
}

// ── Structured parameter expansion ────────────────────────────────

/// Rich parameter expansion: `${(flags)#name[subscript]modifier}`.
///
/// Follows the 14-field model from mvdan/sh:
/// flags → length → nested → name → subscript → modifier.
#[derive(Debug, Clone, PartialEq)]
pub struct ParamExpansion {
    /// `${(flags)name}` — processing flags like `(L)`, `(U)`, `(f)`, etc.
    pub flags: Vec<ParamFlag>,
    /// `${#name}` — length operator.
    pub length: bool,
    /// `${+name}` — is-set test.
    pub is_set_test: bool,
    /// The parameter name (or special: `?`, `$`, `#`, `*`, `@`, digits).
    pub name: CompactString,
    /// `${${inner}}` — nested expansion (indirect).
    pub nested: Option<Box<ParamExpansion>>,
    /// `${name[subscript]}` — array subscript.
    pub subscript: Option<Subscript>,
    /// The operation to apply: default, trim, replace, case, substring, etc.
    pub modifier: Option<ParamModifier>,
}

/// Array subscript expressions.
#[derive(Debug, Clone, PartialEq)]
pub enum Subscript {
    /// Numeric index (possibly negative): `${arr[3]}`, `${arr[-1]}`.
    Index(CompactString),
    /// `${arr[@]}` — all elements as separate words.
    All,
    /// `${arr[*]}` — all elements joined.
    Star,
    /// Pattern search: `${arr[(r)pat]}` or `${arr[(i)idx]}`.
    Pattern {
        reverse: bool,
        pattern: CompactString,
    },
}

/// Modifier operations on parameter values.
#[derive(Debug, Clone, PartialEq)]
pub enum ParamModifier {
    /// `${name:-word}` or `${name-word}` — use default.
    Default { colon: bool, word: Box<Word> },
    /// `${name:=word}` or `${name=word}` — assign default.
    Assign { colon: bool, word: Box<Word> },
    /// `${name:+word}` or `${name+word}` — use alternative.
    Alternative { colon: bool, word: Box<Word> },
    /// `${name:?word}` or `${name?word}` — error if unset.
    Error { colon: bool, word: Box<Word> },
    /// `${name#pat}` or `${name##pat}` — remove prefix.
    TrimPrefix { longest: bool, pattern: Box<Word> },
    /// `${name%pat}` or `${name%%pat}` — remove suffix.
    TrimSuffix { longest: bool, pattern: Box<Word> },
    /// `${name/pat/rep}` or `${name//pat/rep}` — substitution.
    Substitute {
        anchor: SubAnchor,
        pattern: Box<Word>,
        replacement: Option<Box<Word>>,
    },
    /// `${name:offset}` or `${name:offset:length}` — substring.
    Substring {
        offset: Box<Word>,
        length: Option<Box<Word>>,
    },
    /// `${name^pat}`, `${name^^pat}`, `${name,pat}`, `${name,,pat}`.
    Case(CaseOp),
}

/// Anchor mode for `${name/pat/rep}`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SubAnchor {
    /// `${name/pat/rep}` — first match.
    First,
    /// `${name//pat/rep}` — all matches.
    All,
    /// `${name/#pat/rep}` — anchored at start.
    Start,
    /// `${name/%pat/rep}` — anchored at end.
    End,
}

/// Case transformation in `${name^}`, `${name^^}`, etc.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CaseOp {
    /// `${name^}` — uppercase first char.
    UpperFirst,
    /// `${name^^}` — uppercase all.
    UpperAll,
    /// `${name,}` — lowercase first char.
    LowerFirst,
    /// `${name,,}` — lowercase all.
    LowerAll,
}

/// Flags in `${(flags)name}`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParamFlag {
    Lower,          // (L)
    Upper,          // (U)
    Capitalize,     // (C)
    Split,          // (f) — split on newlines
    Join,           // (F) — join with newlines
    SplitSep(char), // (s:sep:)
    JoinSep(char),  // (j:sep:)
    SortAsc,        // (o)
    SortDesc,       // (O)
    Unique,         // (u)
    Keys,           // (k)
    Values,         // (v)
    TypeFlag,       // (t) — type of variable
    Prompt,         // (P) — prompt expansion
    Quote,          // (q)
    Unquote,        // (Q)
    Expand,         // (e) — perform expansion
    Words,          // (z) — split into words
    Visible,        // (V) — make special chars visible
}

// ── Brace expansion ────────────────────────────────────────────────

/// Brace expansion: `{a,b,c}` or `{1..10..2}`.
#[derive(Debug, Clone, PartialEq)]
pub enum BraceExpansion {
    /// `{a,b,c}` — list of alternatives.
    List(Vec<CompactString>),
    /// `{start..end[..step]}` — range (numeric or char).
    Range {
        start: CompactString,
        end: CompactString,
        step: Option<CompactString>,
    },
}

/// Process substitution direction.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessSubKind {
    /// `<(cmd)` — read from process.
    Input,
    /// `>(cmd)` — write to process.
    Output,
}

/// Extended glob operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExtGlobOp {
    /// `*(pat)` — zero or more.
    Star,
    /// `+(pat)` — one or more.
    Plus,
    /// `?(pat)` — zero or one.
    Question,
    /// `@(pat)` — exactly one.
    At,
    /// `!(pat)` — anything except.
    Not,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GlobKind {
    Star,
    Question,
    At,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Redirect {
    pub fd: Option<u32>,
    pub op: RedirectOp,
    pub target: Word,
    pub span: Span,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RedirectOp {
    Less,
    Greater,
    DoubleGreater,
    GreaterPipe,
    GreaterBang,
    AmpGreater,
    AmpDoubleGreater,
    DoubleLess,
    TripleLess,
    DoubleLessDash,
    LessGreater,
    FdDup,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Assignment {
    pub name: CompactString,
    /// Optional subscript for `name[sub]=value`.
    pub subscript: Option<CompactString>,
    pub op: AssignOp,
    pub value: Option<Word>,
    /// Array literal: `name=(word1 word2 ...)`.
    pub array_value: Option<Vec<Word>>,
    pub span: Span,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssignOp {
    Assign,
    Append,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Subshell {
    pub body: Vec<CompleteCommand>,
    pub redirects: Vec<Redirect>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct BraceGroup {
    pub body: Vec<CompleteCommand>,
    pub redirects: Vec<Redirect>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct IfClause {
    pub condition: Vec<CompleteCommand>,
    pub then_body: Vec<CompleteCommand>,
    pub elifs: Vec<(Vec<CompleteCommand>, Vec<CompleteCommand>)>,
    pub else_body: Option<Vec<CompleteCommand>>,
    pub redirects: Vec<Redirect>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct ForClause {
    pub var: CompactString,
    pub words: Option<Vec<Word>>,
    pub body: Vec<CompleteCommand>,
    pub redirects: Vec<Redirect>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct WhileClause {
    pub condition: Vec<CompleteCommand>,
    pub body: Vec<CompleteCommand>,
    pub redirects: Vec<Redirect>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct UntilClause {
    pub condition: Vec<CompleteCommand>,
    pub body: Vec<CompleteCommand>,
    pub redirects: Vec<Redirect>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct CaseClause {
    pub word: Word,
    pub items: Vec<CaseItem>,
    pub redirects: Vec<Redirect>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct CaseItem {
    pub patterns: Vec<Word>,
    pub body: Vec<CompleteCommand>,
    pub terminator: CaseTerminator,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CaseTerminator {
    DoubleSemi,
    SemiAnd,
    SemiPipe,
}

#[derive(Debug, Clone, PartialEq)]
pub struct SelectClause {
    pub var: CompactString,
    pub words: Option<Vec<Word>>,
    pub body: Vec<CompleteCommand>,
    pub redirects: Vec<Redirect>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct FunctionDef {
    pub name: CompactString,
    pub body: Command,
    pub redirects: Vec<Redirect>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Coproc {
    pub name: Option<CompactString>,
    pub command: Command,
}

#[derive(Debug, Clone, PartialEq)]
pub struct TimeClause {
    pub pipeline: Pipeline,
}