shuck-parser 0.0.41

A fast, safe bash parser library
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
use super::*;

#[test]
fn test_current_word_cache_tracks_token_changes() {
    let input = "\"$foo\" bar\n";
    let mut parser = Parser::new(input);

    let first = parser.current_word().unwrap();
    assert_eq!(first.render(input), "$foo");
    assert!(is_fully_quoted(&first));
    let [quoted_part] = parser.current_word_cache.as_ref().unwrap().parts.as_slice() else {
        panic!("expected one quoted part");
    };
    let WordPart::DoubleQuoted { parts, .. } = &quoted_part.kind else {
        panic!("expected double-quoted word");
    };
    assert!(matches!(
        parts.as_slice(),
        [part] if matches!(&part.kind, WordPart::Variable(_))
    ));

    let repeated = parser.current_word().unwrap();
    assert_eq!(repeated.span, first.span);

    parser.advance();
    assert!(parser.current_word_cache.is_none());

    let next = parser.current_word().unwrap();
    assert_eq!(next.render(input), "bar");
    assert!(parser.current_word_cache.is_none());
}

#[test]
fn test_checkpoint_restore_rebuilds_current_word_cache() {
    let input = "\"$foo\" bar\n";
    let mut parser = Parser::new(input);

    let first = parser.current_word().unwrap();
    assert_eq!(first.render(input), "$foo");
    assert!(parser.current_word_cache.is_some());

    let checkpoint = parser.checkpoint();
    parser.advance();
    assert_eq!(parser.current_word().unwrap().render(input), "bar");

    parser.restore(checkpoint);
    assert!(parser.current_word_cache.is_none());
    let restored = parser.current_word().unwrap();
    assert_eq!(restored.render(input), "$foo");
    assert_eq!(restored.span, first.span);
    assert!(parser.current_word_cache.is_some());
}

#[test]
fn test_parse_word_fragment_preserves_original_span_for_cooked_text() {
    let source = r#"foo\/bar"#;
    let span = Span::from_positions(Position::new(), Position::new().advanced_by(source));

    let word = Parser::parse_word_fragment(source, "foo/bar", span);

    assert_eq!(word.render(source), "foo/bar");
    assert_eq!(word.span, span);
    assert_eq!(word.span.slice(source), source);
    assert!(matches!(
        &word.parts[..],
        [WordPartNode {
            kind: WordPart::Literal(text),
            ..
        }] if !text.is_source_backed() && text == "foo/bar"
    ));
}

#[test]
fn test_parse_quoted_flow_control_name_stays_simple_command() {
    let input = "'break' 2";
    let parser = Parser::new(input);
    let script = parser.parse().unwrap().file;

    let AstCommand::Simple(command) = &script.body[0].command else {
        panic!("expected simple command");
    };

    assert!(is_fully_quoted(&command.name));
    assert_eq!(command.name.render(input), "break");
    assert_eq!(command.args[0].render(input), "2");
}

#[test]
fn test_parse_mixed_literal_word_consumes_segmented_token_directly() {
    let input = "printf foo\"bar\"'baz'";
    let parser = Parser::new(input);
    let script = parser.parse().unwrap().file;

    let AstCommand::Simple(command) = &script.body[0].command else {
        panic!("expected simple command");
    };

    let arg = &command.args[0];
    assert!(!is_fully_quoted(arg));
    assert_eq!(arg.render(input), "foobarbaz");
    assert_eq!(arg.parts.len(), 3);
    assert_eq!(arg.part_span(0).unwrap().slice(input), "foo");
    assert_eq!(arg.part_span(1).unwrap().slice(input), "\"bar\"");
    assert_eq!(arg.part_span(2).unwrap().slice(input), "'baz'");
    let WordPart::DoubleQuoted { parts, .. } = &arg.parts[1].kind else {
        panic!("expected double-quoted middle part");
    };
    assert_eq!(parts[0].span.slice(input), "bar");
    let WordPart::SingleQuoted { value, .. } = &arg.parts[2].kind else {
        panic!("expected single-quoted suffix part");
    };
    assert_eq!(value.slice(input), "baz");
}

#[test]
fn test_parse_single_quoted_prefix_word_consumes_segmented_token_directly() {
    let input = "printf 'foo'bar";
    let parser = Parser::new(input);
    let script = parser.parse().unwrap().file;

    let AstCommand::Simple(command) = &script.body[0].command else {
        panic!("expected simple command");
    };

    let arg = &command.args[0];
    assert!(!is_fully_quoted(arg));
    assert_eq!(arg.render(input), "foobar");
    assert_eq!(arg.parts.len(), 2);
    assert_eq!(arg.part_span(0).unwrap().slice(input), "'foo'");
    assert_eq!(arg.part_span(1).unwrap().slice(input), "bar");
}

#[test]
fn test_parse_word_string_keeps_escaped_dollar_literal() {
    let input = r#"\$HOME"#;
    let word = Parser::parse_word_string(input);

    assert_eq!(word.render(input), "$HOME");
    assert_eq!(word.render_syntax(input), input);
    assert!(matches!(
        word.parts.as_slice(),
        [WordPartNode {
            kind: WordPart::Literal(text),
            ..
        }] if text.is_source_backed() && text.as_str(input, word.parts[0].span) == "$HOME"
    ));
}

#[test]
fn test_function_keyword_without_parens_preserves_surface_form() {
    let input = "function inc { :; }\n";
    let script = Parser::new(input).parse().unwrap().file;

    let function = expect_function(&script.body[0]);
    let (compound, redirects) = expect_compound(function.body.as_ref());
    let AstCompoundCommand::BraceGroup(body) = compound else {
        panic!("expected brace-group function body");
    };

    assert!(function.uses_function_keyword());
    assert!(!function.has_name_parens());
    assert_eq!(
        function
            .header
            .function_keyword_span
            .map(|span| span.slice(input)),
        Some("function")
    );
    assert_eq!(function.header.trailing_parens_span, None);
    assert!(redirects.is_empty());
    assert_eq!(body.len(), 1);
}

#[test]
fn test_posix_function_keyword_without_parens_preserves_surface_form() {
    let input = "function inc { :; }\n";
    let script = Parser::with_dialect(input, ShellDialect::Posix)
        .parse()
        .unwrap()
        .file;

    let function = expect_function(&script.body[0]);
    let (compound, redirects) = expect_compound(function.body.as_ref());
    let AstCompoundCommand::BraceGroup(body) = compound else {
        panic!("expected brace-group function body");
    };

    assert!(function.uses_function_keyword());
    assert!(!function.has_name_parens());
    assert_eq!(
        function
            .header
            .function_keyword_span
            .map(|span| span.slice(input)),
        Some("function")
    );
    assert_eq!(function.header.trailing_parens_span, None);
    assert!(redirects.is_empty());
    assert_eq!(body.len(), 1);
}

#[test]
fn test_function_keyword_with_parens_preserves_surface_form() {
    let input = "function inc() { :; }\n";
    let script = Parser::new(input).parse().unwrap().file;

    let function = expect_function(&script.body[0]);
    let (compound, redirects) = expect_compound(function.body.as_ref());

    assert!(function.uses_function_keyword());
    assert!(function.has_name_parens());
    assert_eq!(
        function
            .header
            .function_keyword_span
            .map(|span| span.slice(input)),
        Some("function")
    );
    assert_eq!(
        function
            .header
            .trailing_parens_span
            .map(|span| span.slice(input)),
        Some("()")
    );
    assert!(matches!(compound, AstCompoundCommand::BraceGroup(_)));
    assert!(redirects.is_empty());
}

#[test]
fn test_function_keyword_allows_subshell_body() {
    let input = "function inc_subshell() ( j=$((j+5)); )\n";
    let script = Parser::new(input).parse().unwrap().file;

    let function = expect_function(&script.body[0]);
    let (compound, redirects) = expect_compound(function.body.as_ref());
    let AstCompoundCommand::Subshell(body) = compound else {
        panic!("expected subshell function body");
    };
    assert!(function.uses_function_keyword());
    assert!(function.has_name_parens());
    assert!(redirects.is_empty());
    assert_eq!(body.len(), 1);
}

#[test]
fn test_function_keyword_allows_newline_conditional_body() {
    let input = "function f()\n[[ -n x ]]\n";
    let script = Parser::new(input).parse().unwrap().file;

    let function = expect_function(&script.body[0]);
    let (compound, redirects) = expect_compound(function.body.as_ref());
    let AstCompoundCommand::Conditional(command) = compound else {
        panic!("expected conditional function body");
    };

    assert!(function.uses_function_keyword());
    assert!(function.has_name_parens());
    assert!(redirects.is_empty());
    assert_eq!(command.span.slice(input), "[[ -n x ]]");
}

#[test]
fn test_function_keyword_rejects_same_line_conditional_body() {
    let parser = Parser::new("function f() [[ -n x ]]\n");
    assert!(
        parser.parse().is_err(),
        "same-line conditional body should be rejected for function keyword definitions"
    );
}

#[test]
fn test_function_keyword_accepts_bash_reserved_name_tokens() {
    let input = "\
function [[ { :; }
function ]] { :; }
function { { :; }
function } { :; }
";
    let script = Parser::new(input).parse().unwrap().file;

    let names = script
        .body
        .iter()
        .map(expect_function)
        .map(|function| function.header.entries[0].word.span.slice(input))
        .collect::<Vec<_>>();

    assert_eq!(names, vec!["[[", "]]", "{", "}"]);
}

#[test]
fn test_adjacent_left_paren_after_command_word_is_a_parse_error() {
    let parser = Parser::new("foo$identity('z')\n");
    assert!(
        parser.parse().is_err(),
        "a command word followed immediately by '(' should be rejected"
    );
}

#[test]
fn test_parse_word_fragment_rebases_indirect_operator_spans() {
    let source = "echo ${!var//$'\\n'/' '}";
    let start = Position::new().advanced_by("echo ");
    let span = Span::from_positions(start, start.advanced_by("${!var//$'\\n'/' '}"));

    let word = Parser::parse_word_fragment(source, span.slice(source), span);
    let parameter = expect_parameter(&word);

    let ParameterExpansionSyntax::Bourne(BourneParameterExpansion::Indirect {
        operator: Some(operator),
        ..
    }) = &parameter.syntax
    else {
        panic!("expected indirect replacement operator");
    };
    let ParameterOp::ReplaceAll {
        replacement,
        replacement_word_ast,
        ..
    } = operator.as_ref()
    else {
        panic!("expected indirect replacement operator");
    };

    assert_eq!(replacement.slice(source), "' '");
    assert_eq!(replacement_word_ast.render_syntax(source), "' '");
    assert_eq!(replacement_word_ast.span.slice(source), "' '");
}

#[test]
fn test_escaped_backticks_inside_double_quotes_stay_literal() {
    let input = "echo \"pre \\`pwd\\` post\"\n";
    let script = Parser::new(input).parse().unwrap().file;

    let AstCommand::Simple(command) = &script.body[0].command else {
        panic!("expected simple command");
    };
    let word = &command.args[0];

    assert_eq!(word.render(input), "pre `pwd` post");

    let WordPart::DoubleQuoted { parts, .. } = &word.parts[0].kind else {
        panic!("expected double-quoted word");
    };
    assert!(
        !parts
            .iter()
            .any(|part| matches!(part.kind, WordPart::CommandSubstitution { .. }))
    );
}

#[test]
fn test_escaped_backticks_after_escaped_backslashes_inside_double_quotes_stay_literal() {
    let input = "echo \"  echo Remember to run \\\\\\`updatedb\\\\'.\"\n";
    let script = Parser::new(input).parse().unwrap().file;

    let AstCommand::Simple(command) = &script.body[0].command else {
        panic!("expected simple command");
    };
    let word = &command.args[0];

    assert_eq!(word.render(input), "  echo Remember to run \\`updatedb\\'.");

    let WordPart::DoubleQuoted { parts, .. } = &word.parts[0].kind else {
        panic!("expected double-quoted word");
    };
    assert!(
        !parts
            .iter()
            .any(|part| matches!(part.kind, WordPart::CommandSubstitution { .. }))
    );
}

#[test]
fn test_process_substitution_like_text_inside_double_quotes_stays_literal() {
    let input = "echo \"<(printf hi)\" \" >(printf bye)\"\n";
    let script = Parser::new(input).parse().unwrap().file;

    let AstCommand::Simple(command) = &script.body[0].command else {
        panic!("expected simple command");
    };

    for word in &command.args {
        let WordPart::DoubleQuoted { parts, .. } = &word.parts[0].kind else {
            panic!("expected double-quoted word");
        };
        assert!(
            !parts
                .iter()
                .any(|part| matches!(part.kind, WordPart::ProcessSubstitution { .. })),
            "{:#?}",
            parts
        );
    }
}

#[test]
fn test_escaped_process_substitution_like_text_stays_literal() {
    let input = "echo \\<(printf hi) \\>(printf bye)\n";
    let script = Parser::new(input).parse().unwrap().file;

    let AstCommand::Simple(command) = &script.body[0].command else {
        panic!("expected simple command");
    };

    for word in &command.args {
        assert!(
            !word
                .parts
                .iter()
                .any(|part| matches!(part.kind, WordPart::ProcessSubstitution { .. })),
            "{:#?}",
            word.parts
        );
    }
}

#[test]
fn test_escaped_backticks_stay_literal_unquoted() {
    let input = "echo \\`pwd\\`\n";
    let script = Parser::new(input).parse().unwrap().file;

    let AstCommand::Simple(command) = &script.body[0].command else {
        panic!("expected simple command");
    };
    let word = &command.args[0];

    assert_eq!(word.render(input), "`pwd`");
    assert_eq!(word.render_syntax(input), "\\`pwd\\`");
    assert!(matches!(
        word.parts.as_slice(),
        [WordPartNode {
            kind: WordPart::Literal(text),
            ..
        }] if text.is_source_backed() && text.as_str(input, word.parts[0].span) == "`pwd`"
    ));
}

#[test]
fn test_unquoted_backtick_substitution_can_contain_spaces() {
    let input = "commands=(`pyenv-commands --sh`)\n";
    let script = Parser::new(input).parse().unwrap().file;

    let AstCommand::Simple(command) = &script.body[0].command else {
        panic!("expected simple command");
    };

    let AssignmentValue::Compound(array) = &command.assignments[0].value else {
        panic!("expected compound assignment");
    };

    assert_eq!(array.elements.len(), 1);
    let ArrayElem::Sequential(word) = &array.elements[0] else {
        panic!("expected sequential element");
    };

    assert_eq!(word.render(input), "`pyenv-commands --sh`");
    let WordPart::CommandSubstitution { body, syntax } = &word.parts[0].kind else {
        panic!("expected backtick substitution");
    };
    assert_eq!(*syntax, CommandSubstitutionSyntax::Backtick);
    assert_eq!(body.len(), 1);
    let inner = expect_simple(&body[0]);
    assert_eq!(inner.name.render(input), "pyenv-commands");
    assert_eq!(inner.args[0].render(input), "--sh");
}

#[test]
fn test_dollar_quoted_words_preserve_quote_variants() {
    let input = "printf $'line\\n' $\"prefix $HOME\"\n";
    let script = Parser::new(input).parse().unwrap().file;

    let AstCommand::Simple(command) = &script.body[0].command else {
        panic!("expected simple command");
    };
    assert_eq!(command.args.len(), 2);

    let ansi = &command.args[0];
    assert!(is_fully_quoted(ansi));
    assert_eq!(top_level_part_slices(ansi, input), vec!["$'line\\n'"]);
    let WordPart::SingleQuoted { value, dollar } = &ansi.parts[0].kind else {
        panic!("expected single-quoted word");
    };
    assert!(*dollar);
    assert_eq!(value.slice(input), "line\n");

    let translated = &command.args[1];
    assert!(is_fully_quoted(translated));
    assert_eq!(
        top_level_part_slices(translated, input),
        vec!["$\"prefix $HOME\""]
    );
    let WordPart::DoubleQuoted { parts, dollar } = &translated.parts[0].kind else {
        panic!("expected double-quoted word");
    };
    assert!(*dollar);
    let slices: Vec<&str> = parts.iter().map(|part| part.span.slice(input)).collect();
    assert_eq!(slices, vec!["prefix ", "$HOME"]);
    assert!(matches!(parts[1].kind, WordPart::Variable(ref name) if name == "HOME"));
}

#[test]
fn test_dollar_quotes_stay_literal_inside_double_quotes() {
    let input = "printf \"%s\" \"$'inner'\" \"$\\\"inner\\\"\"\n";
    let script = Parser::new(input).parse().unwrap().file;

    let AstCommand::Simple(command) = &script.body[0].command else {
        panic!("expected simple command");
    };
    assert_eq!(command.args.len(), 3);

    for arg in &command.args[1..] {
        let WordPart::DoubleQuoted { parts, .. } = &arg.parts[0].kind else {
            panic!("expected double-quoted word");
        };
        assert_eq!(arg.render_syntax(input), arg.span.slice(input));
        assert!(
            !parts.iter().any(|part| matches!(
                part.kind,
                WordPart::SingleQuoted { .. } | WordPart::DoubleQuoted { dollar: true, .. }
            )),
            "double-quoted contents should keep nested dollar-quote syntax literal: {parts:#?}"
        );
    }
}

#[test]
fn test_for_loop_words_consume_segmented_tokens_directly() {
    let input = "for item in foo\"bar\" 'baz'qux; do echo \"$item\"; done";
    let script = Parser::new(input).parse().unwrap().file;

    let (compound, _) = expect_compound(&script.body[0]);
    let AstCompoundCommand::For(command) = compound else {
        panic!("expected for loop");
    };

    let words = command.words.as_ref().expect("expected explicit for words");
    assert_eq!(words.len(), 2);
    assert_eq!(words[0].render(input), "foobar");
    assert_eq!(words[0].parts.len(), 2);
    assert_eq!(words[0].part_span(0).unwrap().slice(input), "foo");
    assert_eq!(words[0].part_span(1).unwrap().slice(input), "\"bar\"");

    assert_eq!(words[1].render(input), "bazqux");
    assert!(!is_fully_quoted(&words[1]));
    assert_eq!(words[1].parts.len(), 2);
    assert_eq!(words[1].part_span(0).unwrap().slice(input), "'baz'");
    assert_eq!(words[1].part_span(1).unwrap().slice(input), "qux");
}

#[test]
fn test_parse_conditional_non_direct_var_ref_falls_back_to_word() {
    let input = "[[ -v prefix$var ]]\n";
    let script = Parser::new(input).parse().unwrap().file;

    let (compound, _) = expect_compound(&script.body[0]);
    let AstCompoundCommand::Conditional(command) = compound else {
        panic!("expected conditional compound command");
    };

    let ConditionalExpr::Unary(unary) = &command.expression else {
        panic!("expected unary conditional");
    };
    let ConditionalExpr::Word(word) = unary.expr.as_ref() else {
        panic!("expected word fallback");
    };
    assert_eq!(word.render(input), "prefix$var");
}