Skip to main content

brush_parser/
word.rs

1//! Parser for shell words, used in expansion and other contexts.
2//!
3//! Implements support for:
4//!
5//! - Text quoting (single, double, ANSI C).
6//! - Escape sequences.
7//! - Tilde prefixes.
8//! - Parameter expansion expressions.
9//! - Command substitution expressions.
10//! - Arithmetic expansion expressions.
11
12use std::fmt::Debug;
13use std::fmt::Display;
14
15use crate::ParserOptions;
16use crate::SourceSpan;
17use crate::ast;
18use crate::error;
19
20/// Encapsulates a `WordPiece` together with its position in the string it came from.
21#[derive(Clone, Debug)]
22#[cfg_attr(
23    any(test, feature = "serde"),
24    derive(PartialEq, Eq, serde::Serialize, serde::Deserialize)
25)]
26pub struct WordPieceWithSource {
27    /// The word piece.
28    pub piece: WordPiece,
29    /// The start index of the piece in the source string.
30    pub start_index: usize,
31    /// The end index of the piece in the source string.
32    pub end_index: usize,
33}
34
35/// Represents a piece of a word.
36#[derive(Clone, Debug)]
37#[cfg_attr(
38    any(test, feature = "serde"),
39    derive(PartialEq, Eq, serde::Serialize, serde::Deserialize)
40)]
41pub enum WordPiece {
42    /// A simple unquoted, unescaped string.
43    Text(String),
44    /// A string that is single-quoted.
45    SingleQuotedText(String),
46    /// A string that is ANSI-C quoted.
47    AnsiCQuotedText(String),
48    /// A sequence of pieces that are embedded in double quotes.
49    DoubleQuotedSequence(Vec<WordPieceWithSource>),
50    /// Gettext enabled variant of [`WordPiece::DoubleQuotedSequence`].
51    GettextDoubleQuotedSequence(Vec<WordPieceWithSource>),
52    /// A tilde expansion.
53    TildeExpansion(TildeExpr),
54    /// A parameter expansion.
55    ParameterExpansion(ParameterExpr),
56    /// A command substitution.
57    CommandSubstitution(String),
58    /// A backquoted command substitution.
59    BackquotedCommandSubstitution(String),
60    /// An escape sequence.
61    EscapeSequence(String),
62    /// An arithmetic expression.
63    ArithmeticExpression(ast::UnexpandedArithmeticExpr),
64}
65
66/// Represents an expandable tilde expression (e.g., ~).
67#[derive(Clone, Debug)]
68#[cfg_attr(
69    any(test, feature = "serde"),
70    derive(PartialEq, Eq, serde::Serialize, serde::Deserialize)
71)]
72pub enum TildeExpr {
73    /// `~`
74    Home,
75    /// `~<user>`
76    UserHome(String),
77    /// `~+`
78    WorkingDir,
79    /// `~-`
80    OldWorkingDir,
81    /// Represents a tilde expansion of the form `~+N`, referring to the Nth directory in
82    /// the shell's directory stack, starting at the top of the stack. Note that the directory
83    /// stack is expected to contains the current working directory as its topmost entry.
84    NthDirFromTopOfDirStack {
85        /// Index into the directory stack (zero-based: 0 is the top of the stack).
86        n: usize,
87        /// Whether the '+' prefix was explicitly used.
88        plus_used: bool,
89    },
90    /// Represents a tilde expansion of the form `~-N`, referring to the Nth directory in
91    /// the shell's directory stack, starting at the bottom of the stack.
92    NthDirFromBottomOfDirStack {
93        /// Index into the directory stack (zero-based: 0 is the bottom of the stack).
94        n: usize,
95    },
96}
97
98/// Type of a parameter test.
99#[derive(Clone, Debug)]
100#[cfg_attr(
101    any(test, feature = "serde"),
102    derive(PartialEq, Eq, serde::Serialize, serde::Deserialize)
103)]
104pub enum ParameterTestType {
105    /// Check for unset or null.
106    UnsetOrNull,
107    /// Check for unset.
108    Unset,
109}
110
111/// A parameter, used in a parameter expansion.
112#[derive(Clone, Debug)]
113#[cfg_attr(
114    any(test, feature = "serde"),
115    derive(PartialEq, Eq, serde::Serialize, serde::Deserialize)
116)]
117pub enum Parameter {
118    /// A 0-indexed positional parameter.
119    Positional(u32),
120    /// A special parameter.
121    Special(SpecialParameter),
122    /// A named variable.
123    Named(String),
124    /// An index into a named variable.
125    NamedWithIndex {
126        /// Variable name.
127        name: String,
128        /// Index.
129        index: String,
130    },
131    /// A named array variable with all indices.
132    NamedWithAllIndices {
133        /// Variable name.
134        name: String,
135        /// Whether to concatenate the values.
136        concatenate: bool,
137    },
138}
139
140impl Display for Parameter {
141    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142        match self {
143            Self::Positional(n) => write!(f, "${n}"),
144            Self::Special(s) => write!(f, "${s}"),
145            Self::Named(name) => write!(f, "${{{name}}}"),
146            Self::NamedWithIndex { name, index } => {
147                write!(f, "${{{name}[{index}]}}")
148            }
149            Self::NamedWithAllIndices { name, concatenate } => {
150                if *concatenate {
151                    write!(f, "${{{name}[*]}}")
152                } else {
153                    write!(f, "${{{name}[@]}}")
154                }
155            }
156        }
157    }
158}
159
160/// A special parameter, used in a parameter expansion.
161#[derive(Clone, Debug)]
162#[cfg_attr(
163    any(test, feature = "serde"),
164    derive(PartialEq, Eq, serde::Serialize, serde::Deserialize)
165)]
166pub enum SpecialParameter {
167    /// All positional parameters.
168    AllPositionalParameters {
169        /// Whether to concatenate the values.
170        concatenate: bool,
171    },
172    /// The count of positional parameters.
173    PositionalParameterCount,
174    /// The last exit status in the shell.
175    LastExitStatus,
176    /// The current shell option flags.
177    CurrentOptionFlags,
178    /// The current shell process ID.
179    ProcessId,
180    /// The last background process ID managed by the shell.
181    LastBackgroundProcessId,
182    /// The name of the shell.
183    ShellName,
184}
185
186impl Display for SpecialParameter {
187    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188        match self {
189            Self::AllPositionalParameters { concatenate } => {
190                if *concatenate {
191                    write!(f, "*")
192                } else {
193                    write!(f, "@")
194                }
195            }
196            Self::PositionalParameterCount => write!(f, "#"),
197            Self::LastExitStatus => write!(f, "?"),
198            Self::CurrentOptionFlags => write!(f, "-"),
199            Self::ProcessId => write!(f, "$"),
200            Self::LastBackgroundProcessId => write!(f, "!"),
201            Self::ShellName => write!(f, "0"),
202        }
203    }
204}
205
206/// A parameter expression, used in a parameter expansion.
207#[derive(Clone, Debug)]
208#[cfg_attr(
209    any(test, feature = "serde"),
210    derive(PartialEq, Eq, serde::Serialize, serde::Deserialize)
211)]
212pub enum ParameterExpr {
213    /// A parameter, with optional indirection.
214    Parameter {
215        /// The parameter.
216        parameter: Parameter,
217        /// Whether to treat the expanded parameter as an indirect
218        /// reference, which should be subsequently dereferenced
219        /// for the expansion.
220        indirect: bool,
221    },
222    /// Conditionally use default values.
223    UseDefaultValues {
224        /// The parameter.
225        parameter: Parameter,
226        /// Whether to treat the expanded parameter as an indirect
227        /// reference, which should be subsequently dereferenced
228        /// for the expansion.
229        indirect: bool,
230        /// The type of test to perform.
231        test_type: ParameterTestType,
232        /// Default value to conditionally use.
233        default_value: Option<String>,
234    },
235    /// Conditionally assign default values.
236    AssignDefaultValues {
237        /// The parameter.
238        parameter: Parameter,
239        /// Whether to treat the expanded parameter as an indirect
240        /// reference, which should be subsequently dereferenced
241        /// for the expansion.
242        indirect: bool,
243        /// The type of test to perform.
244        test_type: ParameterTestType,
245        /// Default value to conditionally assign.
246        default_value: Option<String>,
247    },
248    /// Indicate error if null or unset.
249    IndicateErrorIfNullOrUnset {
250        /// The parameter.
251        parameter: Parameter,
252        /// Whether to treat the expanded parameter as an indirect
253        /// reference, which should be subsequently dereferenced
254        /// for the expansion.
255        indirect: bool,
256        /// The type of test to perform.
257        test_type: ParameterTestType,
258        /// Error message to conditionally yield.
259        error_message: Option<String>,
260    },
261    /// Conditionally use an alternative value.
262    UseAlternativeValue {
263        /// The parameter.
264        parameter: Parameter,
265        /// Whether to treat the expanded parameter as an indirect
266        /// reference, which should be subsequently dereferenced
267        /// for the expansion.
268        indirect: bool,
269        /// The type of test to perform.
270        test_type: ParameterTestType,
271        /// Alternative value to conditionally use.
272        alternative_value: Option<String>,
273    },
274    /// Compute the length of the given parameter.
275    ParameterLength {
276        /// The parameter.
277        parameter: Parameter,
278        /// Whether to treat the expanded parameter as an indirect
279        /// reference, which should be subsequently dereferenced
280        /// for the expansion.
281        indirect: bool,
282    },
283    /// Remove the smallest suffix from the given string matching the given pattern.
284    RemoveSmallestSuffixPattern {
285        /// The parameter.
286        parameter: Parameter,
287        /// Whether to treat the expanded parameter as an indirect
288        /// reference, which should be subsequently dereferenced
289        /// for the expansion.
290        indirect: bool,
291        /// Optionally provides a pattern to match.
292        pattern: Option<String>,
293    },
294    /// Remove the largest suffix from the given string matching the given pattern.
295    RemoveLargestSuffixPattern {
296        /// The parameter.
297        parameter: Parameter,
298        /// Whether to treat the expanded parameter as an indirect
299        /// reference, which should be subsequently dereferenced
300        /// for the expansion.
301        indirect: bool,
302        /// Optionally provides a pattern to match.
303        pattern: Option<String>,
304    },
305    /// Remove the smallest prefix from the given string matching the given pattern.
306    RemoveSmallestPrefixPattern {
307        /// The parameter.
308        parameter: Parameter,
309        /// Whether to treat the expanded parameter as an indirect
310        /// reference, which should be subsequently dereferenced
311        /// for the expansion.
312        indirect: bool,
313        /// Optionally provides a pattern to match.
314        pattern: Option<String>,
315    },
316    /// Remove the largest prefix from the given string matching the given pattern.
317    RemoveLargestPrefixPattern {
318        /// The parameter.
319        parameter: Parameter,
320        /// Whether to treat the expanded parameter as an indirect
321        /// reference, which should be subsequently dereferenced
322        /// for the expansion.
323        indirect: bool,
324        /// Optionally provides a pattern to match.
325        pattern: Option<String>,
326    },
327    /// Extract a substring from the given parameter.
328    Substring {
329        /// The parameter.
330        parameter: Parameter,
331        /// Whether to treat the expanded parameter as an indirect
332        /// reference, which should be subsequently dereferenced
333        /// for the expansion.
334        indirect: bool,
335        /// Arithmetic expression that will be expanded to compute the offset
336        /// at which the substring should be extracted.
337        offset: ast::UnexpandedArithmeticExpr,
338        /// Optionally provides an arithmetic expression that will be expanded
339        /// to compute the length of substring to be extracted; if left
340        /// unspecified, the remainder of the string will be extracted.
341        length: Option<ast::UnexpandedArithmeticExpr>,
342    },
343    /// Transform the given parameter.
344    Transform {
345        /// The parameter.
346        parameter: Parameter,
347        /// Whether to treat the expanded parameter as an indirect
348        /// reference, which should be subsequently dereferenced
349        /// for the expansion.
350        indirect: bool,
351        /// Type of transformation to apply.
352        op: ParameterTransformOp,
353    },
354    /// Uppercase the first character of the given parameter.
355    UppercaseFirstChar {
356        /// The parameter.
357        parameter: Parameter,
358        /// Whether to treat the expanded parameter as an indirect
359        /// reference, which should be subsequently dereferenced
360        /// for the expansion.
361        indirect: bool,
362        /// Optionally provides a pattern to match.
363        pattern: Option<String>,
364    },
365    /// Uppercase the portion of the given parameter matching the given pattern.
366    UppercasePattern {
367        /// The parameter.
368        parameter: Parameter,
369        /// Whether to treat the expanded parameter as an indirect
370        /// reference, which should be subsequently dereferenced
371        /// for the expansion.
372        indirect: bool,
373        /// Optionally provides a pattern to match.
374        pattern: Option<String>,
375    },
376    /// Lowercase the first character of the given parameter.
377    LowercaseFirstChar {
378        /// The parameter.
379        parameter: Parameter,
380        /// Whether to treat the expanded parameter as an indirect
381        /// reference, which should be subsequently dereferenced
382        /// for the expansion.
383        indirect: bool,
384        /// Optionally provides a pattern to match.
385        pattern: Option<String>,
386    },
387    /// Lowercase the portion of the given parameter matching the given pattern.
388    LowercasePattern {
389        /// The parameter.
390        parameter: Parameter,
391        /// Whether to treat the expanded parameter as an indirect
392        /// reference, which should be subsequently dereferenced
393        /// for the expansion.
394        indirect: bool,
395        /// Optionally provides a pattern to match.
396        pattern: Option<String>,
397    },
398    /// Replace occurrences of the given pattern in the given parameter.
399    ReplaceSubstring {
400        /// The parameter.
401        parameter: Parameter,
402        /// Whether to treat the expanded parameter as an indirect
403        /// reference, which should be subsequently dereferenced
404        /// for the expansion.
405        indirect: bool,
406        /// Pattern to match.
407        pattern: String,
408        /// Replacement string.
409        replacement: Option<String>,
410        /// Kind of match to perform.
411        match_kind: SubstringMatchKind,
412    },
413    /// Select variable names from the environment with a given prefix.
414    VariableNames {
415        /// The prefix to match.
416        prefix: String,
417        /// Whether to concatenate the results.
418        concatenate: bool,
419    },
420    /// Select member keys from the named array.
421    MemberKeys {
422        /// Name of the array variable.
423        variable_name: String,
424        /// Whether to concatenate the results.
425        concatenate: bool,
426    },
427}
428
429/// Kind of substring match.
430#[derive(Clone, Debug)]
431#[cfg_attr(
432    any(test, feature = "serde"),
433    derive(PartialEq, Eq, serde::Serialize, serde::Deserialize)
434)]
435pub enum SubstringMatchKind {
436    /// Match the prefix of the string.
437    Prefix,
438    /// Match the suffix of the string.
439    Suffix,
440    /// Match the first occurrence in the string.
441    FirstOccurrence,
442    /// Match all instances in the string.
443    Anywhere,
444}
445
446/// Kind of operation to apply to a parameter.
447#[derive(Clone, Debug)]
448#[cfg_attr(
449    any(test, feature = "serde"),
450    derive(PartialEq, Eq, serde::Serialize, serde::Deserialize)
451)]
452pub enum ParameterTransformOp {
453    /// Capitalizate initials.
454    CapitalizeInitial,
455    /// Expand escape sequences.
456    ExpandEscapeSequences,
457    /// Possibly quote with arrays expanded.
458    PossiblyQuoteWithArraysExpanded {
459        /// Whether or not to yield separate words.
460        separate_words: bool,
461    },
462    /// Apply prompt expansion.
463    PromptExpand,
464    /// Quote the parameter.
465    Quoted,
466    /// Translate to a format usable in an assignment/declaration.
467    ToAssignmentLogic,
468    /// Translate to the parameter's attribute flags.
469    ToAttributeFlags,
470    /// Translate to lowercase.
471    ToLowerCase,
472    /// Translate to uppercase.
473    ToUpperCase,
474}
475
476/// Represents a sub-word that is either a brace expression or some other word text.
477#[derive(Clone, Debug)]
478#[cfg_attr(
479    any(test, feature = "serde"),
480    derive(PartialEq, Eq, serde::Serialize, serde::Deserialize)
481)]
482pub enum BraceExpressionOrText {
483    /// A brace expression.
484    Expr(BraceExpression),
485    /// Other word text.
486    Text(String),
487}
488
489/// Represents a brace expression to be expanded.
490pub type BraceExpression = Vec<BraceExpressionMember>;
491
492/// Member of a brace expression.
493#[derive(Clone, Debug)]
494#[cfg_attr(
495    any(test, feature = "serde"),
496    derive(PartialEq, Eq, serde::Serialize, serde::Deserialize)
497)]
498pub enum BraceExpressionMember {
499    /// An inclusive numerical sequence.
500    NumberSequence {
501        /// Start of the sequence.
502        start: i64,
503        /// Inclusive end of the sequence.
504        end: i64,
505        /// Increment value.
506        increment: i64,
507        /// Width to zero pad each member out to, set when either bound was
508        /// written with a leading zero.
509        zero_padded_width: Option<usize>,
510    },
511    /// An inclusive character sequence.
512    CharSequence {
513        /// Start of the sequence.
514        start: char,
515        /// Inclusive end of the sequence.
516        end: char,
517        /// Increment value.
518        increment: i64,
519    },
520    /// Child text or expressions.
521    Child(Vec<BraceExpressionOrText>),
522}
523
524/// Parse a word into its constituent pieces.
525///
526/// # Arguments
527///
528/// * `word` - The word to parse.
529/// * `options` - The parser options to use.
530pub fn parse(
531    word: &str,
532    options: &ParserOptions,
533) -> Result<Vec<WordPieceWithSource>, error::WordParseError> {
534    cacheable_parse(word, options)
535}
536
537#[cached::macros::cached(
538    max_size = 64,
539    key = "(String, ParserOptions)",
540    convert = r#"{ (word.to_owned(), options.to_owned()) }"#
541)]
542fn cacheable_parse(
543    word: &str,
544    options: &ParserOptions,
545) -> Result<Vec<WordPieceWithSource>, error::WordParseError> {
546    tracing::debug!(target: "expansion", "Parsing word '{}'", word);
547
548    let pieces = expansion_parser::unexpanded_word(word, options)
549        .map_err(|err| error::WordParseError::Word(word.to_owned(), err.into()))?;
550
551    tracing::debug!(target: "expansion", "Parsed word '{}' => {{{:?}}}", word, pieces);
552
553    Ok(pieces)
554}
555
556/// Parse a heredoc body, treating `"` and `'` as literal characters. The same as
557/// [`parse_double_quoted_text`] with [`DoubleQuotedTextKind::HereDoc`].
558///
559/// # Arguments
560///
561/// * `word` - The heredoc body to parse.
562/// * `options` - The parser options to use.
563pub fn parse_heredoc(
564    word: &str,
565    options: &ParserOptions,
566) -> Result<Vec<WordPieceWithSource>, error::WordParseError> {
567    parse_double_quoted_text(word, DoubleQuotedTextKind::HereDoc, options)
568}
569
570/// A kind of double-quoted text whose quotes are elsewhere.
571///
572/// See [`parse_double_quoted_text`]. In all of them only `$`, `` ` `` and `\` are
573/// special and `'` is an ordinary character. They differ in what else a backslash
574/// escapes, whether `"` is text, and whether `$'...'` and `$"..."` are quotes.
575#[derive(Clone, Copy, Debug, Eq, PartialEq)]
576#[non_exhaustive]
577pub enum DoubleQuotedTextKind {
578    /// The body of a here document: a backslash escapes only `$`, `` ` `` and `\`, and
579    /// `"`, `$'...'` and `$"..."` are text.
580    HereDoc,
581    /// A prompt string (`PS1` and its like): as a here document body, except that `\"`
582    /// stands for `"` and a backslash and the newline after it yield nothing.
583    Prompt,
584    /// The word of a parameter expansion (`${param:-word}` and its like) within a here
585    /// document body or a prompt: as a prompt, except that its own `"` are removed
586    /// rather than being text, `\}` stands for `}`, and between a pair of its quotes a
587    /// backslash escapes any character.
588    WordInHereDocOrPrompt,
589    /// The word of such a parameter expansion within double quotes
590    /// (`"${param:-word}"`): as [`Self::WordInHereDocOrPrompt`], except that outside
591    /// the word's own quotes `$'...'` is ANSI-C quoted text and `$"..."` a
592    /// double-quoted string to translate.
593    WordInDoubleQuotes,
594}
595
596/// The rules the grammar applies to a kind of double-quoted text; see
597/// [`DoubleQuotedTextKind`].
598#[derive(Clone, Copy, Debug, Eq, PartialEq)]
599pub(crate) struct DoubleQuotedTextRules {
600    /// Whether `\"` stands for `"`.
601    escaped_quotes: bool,
602    /// Whether a backslash and the newline after it yield nothing.
603    line_continuations: bool,
604    /// Whether an unescaped `"` is removed instead of being text, `\}` stands for `}`,
605    /// and between a pair of quotes a backslash escapes any character.
606    quotes_removed: bool,
607    /// Whether, outside a pair of quotes, `$'...'` is ANSI-C quoted text and `$"..."`
608    /// a double-quoted string to translate.
609    dollar_quotes: bool,
610}
611
612impl DoubleQuotedTextKind {
613    pub(crate) const fn rules(self) -> DoubleQuotedTextRules {
614        match self {
615            Self::HereDoc => DoubleQuotedTextRules {
616                escaped_quotes: false,
617                line_continuations: false,
618                quotes_removed: false,
619                dollar_quotes: false,
620            },
621            Self::Prompt => DoubleQuotedTextRules {
622                escaped_quotes: true,
623                line_continuations: true,
624                quotes_removed: false,
625                dollar_quotes: false,
626            },
627            Self::WordInHereDocOrPrompt => DoubleQuotedTextRules {
628                escaped_quotes: true,
629                line_continuations: true,
630                quotes_removed: true,
631                dollar_quotes: false,
632            },
633            Self::WordInDoubleQuotes => DoubleQuotedTextRules {
634                escaped_quotes: true,
635                line_continuations: true,
636                quotes_removed: true,
637                dollar_quotes: true,
638            },
639        }
640    }
641}
642
643/// Parse double-quoted text that doesn't include the quotes enclosing it.
644///
645/// Such text is a here document body, a prompt, or the word of a parameter expansion
646/// nested in either of those or in double quotes. The kind says how its backslashes
647/// and quotes are read.
648///
649/// The pieces returned are of the kinds [`parse`] finds between a pair of double quotes.
650///
651/// # Arguments
652///
653/// * `text` - The text to parse.
654/// * `kind` - The kind of text.
655/// * `options` - The parser options to use.
656pub fn parse_double_quoted_text(
657    text: &str,
658    kind: DoubleQuotedTextKind,
659    options: &ParserOptions,
660) -> Result<Vec<WordPieceWithSource>, error::WordParseError> {
661    expansion_parser::unexpanded_double_quoted_text(text, options, &kind.rules())
662        .map_err(|err| error::WordParseError::Word(text.to_owned(), err.into()))
663}
664
665impl DoubleQuotedTextKind {
666    /// Quotes text so that [`parse_double_quoted_text`] reads it, as text of this kind,
667    /// as exactly the text given: a backslash goes before each character that is
668    /// special in text of this kind.
669    ///
670    /// # Arguments
671    ///
672    /// * `text` - The text to quote.
673    pub fn quote(self, text: &str) -> String {
674        let rules = self.rules();
675        let mut quoted = String::with_capacity(text.len());
676        for c in text.chars() {
677            if matches!(c, '$' | '`' | '\\') || (c == '"' && rules.escaped_quotes) {
678                quoted.push('\\');
679            }
680            quoted.push(c);
681        }
682        quoted
683    }
684}
685
686/// Parse the given word into a parameter expression.
687///
688/// # Arguments
689///
690/// * `word` - The word to parse.
691/// * `options` - The parser options to use.
692pub fn parse_parameter(
693    word: &str,
694    options: &ParserOptions,
695) -> Result<Parameter, error::WordParseError> {
696    expansion_parser::parameter(word, options)
697        .map_err(|err| error::WordParseError::Parameter(word.to_owned(), err.into()))
698}
699
700/// Parse brace expansion from a given word .
701///
702/// # Arguments
703///
704/// * `word` - The word to parse.
705/// * `options` - The parser options to use.
706pub fn parse_brace_expansions(
707    word: &str,
708    options: &ParserOptions,
709) -> Result<Option<Vec<BraceExpressionOrText>>, error::WordParseError> {
710    expansion_parser::brace_expansions(word, options)
711        .map_err(|err| error::WordParseError::BraceExpansion(word.to_owned(), err.into()))
712}
713
714/// Parses a scalar assignment from a given word.
715///
716/// A parenthesized value is treated as scalar text.
717///
718/// # Arguments
719///
720/// * `word` - The word to parse.
721/// * `options` - The parser options to use.
722pub fn parse_scalar_assignment(
723    word: &str,
724    options: &ParserOptions,
725) -> Result<ast::Assignment, error::WordParseError> {
726    expansion_parser::name_equals_scalar_value(word, options)
727        .map_err(|err| error::WordParseError::Word(word.to_owned(), err.into()))
728}
729
730/// Parses text as a compound assignment value, returning its optionally-keyed element words.
731/// Returns `None` if the text is not a well-formed compound value.
732///
733/// This exists so that text which only becomes recognizable as a compound value *after* expansion
734/// can be reinterpreted without reconstructing and re-parsing a whole assignment word.
735///
736/// # Arguments
737///
738/// * `value` - The candidate compound value text, including its enclosing parentheses.
739/// * `options` - The parser options to use.
740#[must_use]
741#[allow(
742    dead_code,
743    reason = "kept for upcoming callers; crate-private until its error handling is settled"
744)]
745pub(crate) fn parse_compound_assignment_value(
746    value: &str,
747    options: &ParserOptions,
748) -> Option<Vec<(Option<ast::Word>, ast::Word)>> {
749    let elements = crate::parser::parse_compound_assignment_value(value, options)?;
750    parse_array_elements(elements.iter(), options).ok()
751}
752
753/// Parses an array assignment from a given word and its array elements.
754///
755/// # Arguments
756///
757/// * `word` - The assignment name and equals sign to parse.
758/// * `elements` - The array element words to parse.
759/// * `options` - The parser options to use.
760pub(crate) fn parse_array_assignment(
761    word: &str,
762    elements: &[&String],
763    options: &ParserOptions,
764) -> Result<ast::Assignment, &'static str> {
765    let (assignment_name, append) =
766        expansion_parser::name_equals(word, options).map_err(|_| "not array assignment word")?;
767
768    Ok(ast::Assignment {
769        name: assignment_name,
770        value: ast::AssignmentValue::Array(parse_array_elements(
771            elements.iter().copied(),
772            options,
773        )?),
774        append,
775        loc: SourceSpan::default(),
776    })
777}
778
779/// Parses one bound of a numeric brace sequence, e.g. `-007`, or its increment.
780///
781/// Returns `None` when the number does not fit in an `i64`, which lets the sequence
782/// rule decline rather than panic on something like `{99999999999999999999..1}`.
783///
784/// The sign goes to the parser along with the digits, so `i64::MIN` is accepted even
785/// though its digits alone are one past `i64::MAX`.
786///
787/// # Arguments
788///
789/// * `text` - The bound as it was written, sign included.
790fn parse_sequence_bound(text: &str) -> Option<i64> {
791    text.parse().ok()
792}
793
794/// Returns the width the members of a numeric brace sequence should be zero
795/// padded out to, or `None` if they should be written as plain numbers.
796///
797/// A leading zero in either bound asks for padding, and the width is then the
798/// longer of the two bounds as they were written, sign included. A lone `0` is
799/// not a leading zero, and neither is a zero that follows a `+`.
800///
801/// # Arguments
802///
803/// * `start` - The start bound as it was written.
804/// * `end` - The end bound as it was written.
805fn zero_padded_width(start: &str, end: &str) -> Option<usize> {
806    fn has_leading_zero(bound: &str) -> bool {
807        let digits = bound.strip_prefix('-').unwrap_or(bound);
808        digits.len() > 1 && digits.starts_with('0')
809    }
810
811    (has_leading_zero(start) || has_leading_zero(end)).then(|| start.len().max(end.len()))
812}
813
814/// Parses literal array element text into optionally-keyed element words.
815///
816/// # Arguments
817///
818/// * `elements` - The array element texts to parse.
819/// * `options` - The parser options to use.
820fn parse_array_elements<'a>(
821    elements: impl IntoIterator<Item = &'a String>,
822    options: &ParserOptions,
823) -> Result<Vec<(Option<ast::Word>, ast::Word)>, &'static str> {
824    elements
825        .into_iter()
826        .map(|element| {
827            let (key, value) = expansion_parser::literal_array_element(element, options)
828                .map_err(|_| "invalid array element in literal")?;
829            Ok((
830                key.map(|key| ast::Word::new(key.as_str())),
831                ast::Word::new(value.as_str()),
832            ))
833        })
834        .collect()
835}
836
837peg::parser! {
838    grammar expansion_parser(parser_options: &ParserOptions) for str {
839        // Helper rule that enables pegviz to be used to visualize debug peg traces.
840        rule traced<T>(e: rule<T>) -> T =
841            &(input:$([_]*) {
842                #[cfg(feature = "debug-tracing")]
843                println!("[PEG_INPUT_START]\n{input}\n[PEG_TRACE_START]");
844            })
845            e:e()? {?
846                #[cfg(feature = "debug-tracing")]
847                println!("[PEG_TRACE_STOP]");
848                e.ok_or("")
849            }
850
851        pub(crate) rule unexpanded_word() -> Vec<WordPieceWithSource> = traced(<word(<![_]>)>)
852
853        rule word<T>(stop_condition: rule<T>) -> Vec<WordPieceWithSource> =
854            tilde:tilde_expr_prefix_with_source()? pieces:word_piece_with_source(<stop_condition()>)* {
855                let mut all_pieces = Vec::new();
856                if let Some(tilde) = tilde {
857                    all_pieces.push(tilde);
858                }
859                all_pieces.extend(pieces);
860                all_pieces
861            }
862
863        // Takes a word as input.
864        pub(crate) rule brace_expansions() -> Option<Vec<BraceExpressionOrText>> =
865            pieces:(brace_expansion_piece(<![_]>)+) { Some(pieces) } /
866            [_]* { None }
867
868        // Returns either a complete brace expression (without any prefix or suffix), or a
869        // non-brace-expression string.
870        rule brace_expansion_piece<T>(stop_condition: rule<T>) -> BraceExpressionOrText =
871            expr:brace_expr() {
872                BraceExpressionOrText::Expr(expr)
873            } /
874            text:$(non_brace_expr_text(<stop_condition()>)+) { BraceExpressionOrText::Text(text.to_owned()) }
875
876        // Parses text that is not considered to contain a brace expression.
877        rule non_brace_expr_text<T>(stop_condition: rule<T>) -> () =
878            !"{" word_piece(<['{'] {} / stop_condition() {}>) {} /
879            !brace_expr() !stop_condition() "{" {}
880
881        // Parses a complete brace expression, with no prefix or suffix.
882        // Cached: each `{` is tried both as the start of a brace expression and as plain text,
883        // and every attempt re-parses the rest of the word, so a run of unterminated `{`
884        // would otherwise take time exponential in its length.
885        #[cache]
886        pub(crate) rule brace_expr() -> BraceExpression =
887            "{" inner:brace_expr_inner() "}" { inner }
888
889        // Parses the text inside a complete brace expression; basically the complete brace
890        // expression without the opening and closing brace characters.
891        pub(crate) rule brace_expr_inner() -> BraceExpression =
892            brace_text_list_expr() /
893            seq:brace_sequence_expr() { vec![seq] }
894
895        // Parses a list of brace expression members, including the separating commas; does
896        // not include the opening and closing braces.
897        pub(crate) rule brace_text_list_expr() -> BraceExpression =
898            brace_text_list_member() **<2,> ","
899
900        // Parses an element that can occur in a brace expression member list, not including the
901        // terminating comma or closing brace.
902        pub(crate) rule brace_text_list_member() -> BraceExpressionMember =
903            // Matches an empty-string member, without consuming the comma or closing brace that terminates it.
904            &[',' | '}'] { BraceExpressionMember::Child(vec![BraceExpressionOrText::Text(String::new())]) } /
905            // Matches a nested string that may include some combination of concatenated textual strings
906            // and brace expressions.
907            child_pieces:(brace_expansion_piece(<[',' | '}']>)+) {
908                BraceExpressionMember::Child(child_pieces)
909            }
910
911        // As in bash 5.3, a sequence with an increment of `i64::MIN` is left as text,
912        // whichever way it goes: its magnitude can't be taken without overflowing.
913        pub(crate) rule brace_sequence_expr() -> BraceExpressionMember =
914            start:sequence_bound() ".." end:sequence_bound() increment:(".." n:number() { n })? {?
915                if increment == Some(i64::MIN) {
916                    Err("increment out of range")
917                } else {
918                    Ok(BraceExpressionMember::NumberSequence {
919                        start: start.0,
920                        end: end.0,
921                        increment: increment.unwrap_or(1),
922                        zero_padded_width: zero_padded_width(start.1, end.1),
923                    })
924                }
925            } /
926            start:character() ".." end:character() increment:(".." n:number() { n })? {?
927                if increment == Some(i64::MIN) {
928                    Err("increment out of range")
929                } else {
930                    Ok(BraceExpressionMember::CharSequence { start, end, increment: increment.unwrap_or(1) })
931                }
932            }
933
934        // A bound of a numeric sequence, kept alongside the text it was written as.
935        // Whether the members come out zero padded is decided by that text and not
936        // by the value, so `{01..3}` and `{1..3}` have to stay distinguishable.
937        rule sequence_bound() -> (i64, &'input str) = text:$(number_sign()? ['0'..='9']+) {?
938            parse_sequence_bound(text).map(|n| (n, text)).ok_or("number out of range")
939        }
940
941        // The increment of a brace sequence. One that does not fit in an `i64` makes
942        // the sequence rule decline, so the expression is left as text, as bash does.
943        rule number() -> i64 = text:$(number_sign()? ['0'..='9']+) {?
944            parse_sequence_bound(text).ok_or("number out of range")
945        }
946
947        rule number_sign() -> i64 =
948            ['-'] { -1 } /
949            ['+'] { 1 }
950
951        rule character() -> char = ['a'..='z' | 'A'..='Z']
952
953        pub(crate) rule is_arithmetic_word() =
954            arithmetic_word(<![_]>)
955
956        // N.B. We don't bother returning the word pieces, as all users of this rule
957        // only try to extract the consumed input string and not the parse result.
958        rule arithmetic_word<T>(stop_condition: rule<T>) =
959            arithmetic_word_piece(<stop_condition()>)* {}
960
961        pub(crate) rule is_arithmetic_word_piece() =
962            arithmetic_word_piece(<![_]>)
963
964        // This rule matches an individual "piece" of an arithmetic expression. It needs to handle
965        // matching nested parenthesized expressions as well. We stop consuming the input when
966        // we reach the provided stop condition, which typically denotes the end of the containing
967        // arithmetic expression.
968        rule arithmetic_word_piece<T>(stop_condition: rule<T>) =
969            // This branch matches a parenthesized piece; we consume the opening parenthesis and
970            // delegate the rest to a helper rule. We don't worry about the stop condition passed
971            // into us, because if we see an opening parenthesis then we *must* find its closing
972            // partner.
973            "(" arithmetic_word_plus_right_paren() {} /
974            // An array subscript may contain the stop condition. Other brackets are left
975            // as text, so malformed arithmetic doesn't fall back to command substitution.
976            array_element_name() {} /
977            // This branch matches any standard piece of a word, stopping as soon as we reach
978            // either the overall stop condition *OR* an opening parenthesis. We add this latter
979            // condition to ensure that *we* handle matching parentheses.
980            !"(" word_piece(<param_rule_or_open_paren(<stop_condition()>)>) {}
981
982        // This is a helper rule that matches either the provided stop condition or an opening parenthesis.
983        rule param_rule_or_open_paren<T>(stop_condition: rule<T>) -> () =
984            stop_condition() {} /
985            "(" {}
986
987        // This rule matches an arithmetic word followed by a right parenthesis. It must consume the right parenthesis.
988        rule arithmetic_word_plus_right_paren() =
989            arithmetic_word(<[')']>) ")"
990
991        rule word_piece_with_source<T>(stop_condition: rule<T>) -> WordPieceWithSource =
992            start_index:position!() piece:word_piece(<stop_condition()>) end_index:position!() {
993                WordPieceWithSource { piece, start_index, end_index }
994            }
995
996        rule word_piece<T>(stop_condition: rule<T>) -> WordPiece =
997            // Rules that match quoted text.
998            s:double_quoted_sequence() { WordPiece::DoubleQuotedSequence(s) } /
999            s:single_quoted_literal_text() { WordPiece::SingleQuotedText(s.to_owned()) } /
1000            s:ansi_c_quoted_text() { WordPiece::AnsiCQuotedText(s.to_owned()) } /
1001            s:gettext_double_quoted_sequence() { WordPiece::GettextDoubleQuotedSequence(s) } /
1002            // Rules that match pieces starting with a dollar sign ('$').
1003            dollar_sign_word_piece() /
1004            // Rules that match unquoted text that doesn't start with an unescaped dollar sign.
1005            normal_escape_sequence() /
1006            // Allow tilde expression to be matched as a word piece (for tilde-after-colon expansion)
1007            enabled_tilde_expr_after_colon() /
1008            // Finally, match unquoted literal text.
1009            unquoted_literal_text(<stop_condition()>)
1010
1011        rule dollar_sign_word_piece() -> WordPiece =
1012            arithmetic_expansion() /
1013            legacy_arithmetic_expansion() /
1014            command_substitution() /
1015            parameter_expansion()
1016
1017        rule double_quoted_word_piece() -> WordPiece =
1018            arithmetic_expansion() /
1019            legacy_arithmetic_expansion() /
1020            command_substitution() /
1021            parameter_expansion() /
1022            double_quoted_escape_sequence() /
1023            double_quoted_text()
1024
1025        rule double_quoted_sequence() -> Vec<WordPieceWithSource> =
1026            "\"" i:double_quoted_sequence_inner()* "\"" { i }
1027
1028        rule gettext_double_quoted_sequence() -> Vec<WordPieceWithSource> =
1029            "$\"" i:double_quoted_sequence_inner()* "\"" { i }
1030
1031        rule double_quoted_sequence_inner() -> WordPieceWithSource =
1032            start_index:position!() piece:double_quoted_word_piece() end_index:position!() {
1033                WordPieceWithSource {
1034                    piece,
1035                    start_index,
1036                    end_index
1037                }
1038            }
1039
1040        rule single_quoted_literal_text() -> &'input str =
1041            "\'" inner:$([^'\'']*) "\'" { inner }
1042
1043        rule ansi_c_quoted_text() -> &'input str =
1044            r"$'" inner:$((r"\\" / r"\'" / [^'\''])*) r"'" { inner }
1045
1046        rule unquoted_literal_text<T>(stop_condition: rule<T>) -> WordPiece =
1047            s:$(unquoted_literal_text_piece(<stop_condition()>)+) { WordPiece::Text(s.to_owned()) }
1048
1049        rule unquoted_literal_text_piece<T>(stop_condition: rule<T>) =
1050            !stop_condition() !normal_escape_sequence() !enabled_tilde_expr_after_colon() [^'\'' | '\"' | '$' | '`'] {}
1051
1052        rule enabled_tilde_expr_after_colon() -> WordPiece =
1053            tilde_exprs_after_colon_enabled() last_char_is_colon() piece:tilde_expression_piece() { piece }
1054
1055        rule last_char_is_colon() = #{|input, pos| {
1056            if pos == 0 {
1057                // No preceding character - can't be preceded by ':'
1058                peg::RuleResult::Failed
1059            } else {
1060                // Check the byte directly (`:` is ASCII, single byte)
1061                if input.as_bytes()[pos - 1] == b':' {
1062                    peg::RuleResult::Matched(pos, ())
1063                } else {
1064                    peg::RuleResult::Failed
1065                }
1066            }
1067        }}
1068
1069        rule double_quoted_text() -> WordPiece =
1070            s:double_quote_body_text() { WordPiece::Text(s.to_owned()) }
1071
1072        rule double_quote_body_text() -> &'input str =
1073            $((!double_quoted_escape_sequence() !dollar_sign_word_piece() !expansion_opener() [^'\"'])+)
1074
1075        // Double-quoted text that doesn't include the quotes enclosing it (a heredoc body, a
1076        // prompt, a word nested in a parameter expansion that is itself double-quoted).
1077        pub(crate) rule unexpanded_double_quoted_text(o: &DoubleQuotedTextRules) -> Vec<WordPieceWithSource> =
1078            runs:quoted_text_run(o)* ![_] { runs.into_iter().flatten().collect() }
1079
1080        // Either the text between a pair of quotes that are themselves removed, or one piece.
1081        // (A pair left open runs to the end of the text.)
1082        rule quoted_text_run(o: &DoubleQuotedTextRules) -> Vec<WordPieceWithSource> =
1083            quotes_removed(o) "\"" pieces:quoted_text_piece_with_source(o, true)* "\""? {
1084                pieces.into_iter().flatten().collect()
1085            } /
1086            piece:quoted_text_piece_with_source(o, false) { piece.into_iter().collect() }
1087
1088        rule quoted_text_piece_with_source(o: &DoubleQuotedTextRules, between_quotes: bool) -> Option<WordPieceWithSource> =
1089            start_index:position!() piece:quoted_text_piece(o, between_quotes) end_index:position!() {
1090                piece.map(|piece| WordPieceWithSource { piece, start_index, end_index })
1091            }
1092
1093        // Yields `None` for text that is consumed without contributing a piece.
1094        rule quoted_text_piece(o: &DoubleQuotedTextRules, between_quotes: bool) -> Option<WordPiece> =
1095            line_continuation(o) { None } /
1096            piece:arithmetic_expansion() { Some(piece) } /
1097            piece:legacy_arithmetic_expansion() { Some(piece) } /
1098            piece:command_substitution() { Some(piece) } /
1099            piece:quoted_text_dollar_quoted(o, between_quotes) { Some(piece) } /
1100            piece:parameter_expansion() { Some(piece) } /
1101            piece:quoted_text_escape_sequence(o, between_quotes) { Some(piece) } /
1102            piece:quoted_text_literal(o, between_quotes) { Some(piece) }
1103
1104        rule quoted_text_escape_sequence(o: &DoubleQuotedTextRules, between_quotes: bool) -> WordPiece =
1105            s:$("\\" ['$' | '`' | '\\']) { WordPiece::EscapeSequence(s.to_owned()) } /
1106            escaped_quotes(o) s:$("\\\"") { WordPiece::EscapeSequence(s.to_owned()) } /
1107            quotes_removed(o) s:$("\\}") { WordPiece::EscapeSequence(s.to_owned()) } /
1108            s:$("\\" [_]) {? if between_quotes { Ok(WordPiece::EscapeSequence(s.to_owned())) } else { Err("escape between quotes") } }
1109
1110        rule quoted_text_dollar_quoted(o: &DoubleQuotedTextRules, between_quotes: bool) -> WordPiece =
1111            dollar_quotes(o, between_quotes) s:ansi_c_quoted_text() { WordPiece::AnsiCQuotedText(s.to_owned()) } /
1112            dollar_quotes(o, between_quotes) s:gettext_double_quoted_sequence() { WordPiece::GettextDoubleQuotedSequence(s) }
1113
1114        rule quoted_text_literal(o: &DoubleQuotedTextRules, between_quotes: bool) -> WordPiece =
1115            s:$((!quoted_text_special(o, between_quotes) [^'`'])+) { WordPiece::Text(s.to_owned()) }
1116
1117        // What ends a run of literal text.
1118        rule quoted_text_special(o: &DoubleQuotedTextRules, between_quotes: bool) =
1119            line_continuation(o) {} /
1120            quoted_text_escape_sequence(o, between_quotes) {} /
1121            quoted_text_dollar_quoted(o, between_quotes) {} /
1122            dollar_sign_word_piece() {} /
1123            expansion_opener() {} /
1124            quotes_removed(o) "\"" {}
1125
1126        rule line_continuation(o: &DoubleQuotedTextRules) =
1127            line_continuations(o) "\\\n"
1128
1129        rule line_continuations(o: &DoubleQuotedTextRules) =
1130            &[_] {? if o.line_continuations { Ok(()) } else { Err("no line continuations") } }
1131
1132        rule escaped_quotes(o: &DoubleQuotedTextRules) =
1133            &[_] {? if o.escaped_quotes { Ok(()) } else { Err("no escaped quotes") } }
1134
1135        rule quotes_removed(o: &DoubleQuotedTextRules) =
1136            &[_] {? if o.quotes_removed { Ok(()) } else { Err("quotes are text") } }
1137
1138        rule dollar_quotes(o: &DoubleQuotedTextRules, between_quotes: bool) =
1139            &[_] {? if o.dollar_quotes && !between_quotes { Ok(()) } else { Err("no dollar quotes") } }
1140
1141        rule normal_escape_sequence() -> WordPiece =
1142            s:$("\\" [c]) { WordPiece::EscapeSequence(s.to_owned()) }
1143
1144        rule double_quoted_escape_sequence() -> WordPiece =
1145            s:$("\\" ['$' | '`' | '\"' | '\\']) { WordPiece::EscapeSequence(s.to_owned()) }
1146
1147        rule tilde_expr_prefix_with_source() -> WordPieceWithSource =
1148            start_index:position!() piece:tilde_expr_prefix() end_index:position!() {
1149                WordPieceWithSource {
1150                    piece,
1151                    start_index,
1152                    end_index
1153                }
1154            }
1155
1156        rule tilde_expr_prefix() -> WordPiece =
1157            tilde_exprs_at_word_start_enabled() piece:tilde_expression_piece() { piece }
1158
1159        rule tilde_expr_after_colon() -> WordPiece =
1160            tilde_exprs_after_colon_enabled() piece:tilde_expression_piece() { piece }
1161
1162        rule tilde_expression_piece() -> WordPiece =
1163            "~" expr:tilde_expression() { WordPiece::TildeExpansion(expr) }
1164
1165        rule tilde_expression() -> TildeExpr =
1166            &tilde_terminator() { TildeExpr::Home } /
1167            "+" &tilde_terminator() { TildeExpr::WorkingDir } /
1168            // N.B. A run of digits need not fit in a `usize`; decline the rule
1169            // when it does not, so the word falls through to being treated as a
1170            // (non-existent) user name instead of panicking the parser.
1171            plus:("+"?) n:$(['0'..='9']*) &tilde_terminator() {? n.parse().map_or_else(|_| Err("dir stack index out of range"), |n| Ok(TildeExpr::NthDirFromTopOfDirStack { n, plus_used: plus.is_some() })) } /
1172            "-" &tilde_terminator() { TildeExpr::OldWorkingDir } /
1173            "-" n:$(['0'..='9']*) &tilde_terminator() {? n.parse().map_or_else(|_| Err("dir stack index out of range"), |n| Ok(TildeExpr::NthDirFromBottomOfDirStack { n })) } /
1174            user:$(portable_filename_char()*) &tilde_terminator() { TildeExpr::UserHome(user.to_owned()) }
1175
1176        rule tilde_terminator() = ['/' | ':' | ';' | '}'] / ![_]
1177
1178        rule portable_filename_char() = ['A'..='Z' | 'a'..='z' | '0'..='9' | '.' | '_' | '-']
1179
1180        // TODO(parser): Deal with fact that there may be a quoted word or escaped closing brace chars.
1181        // TODO(parser): Improve on how we handle a '$' not followed by a valid variable name or parameter.
1182        // Cached: each `${...}` can match any of ~20 parameter expression forms, and a failure
1183        // within one (e.g., an unterminated `$(`) would otherwise be re-discovered by every form
1184        // at every enclosing level, taking time exponential in the nesting depth.
1185        #[cache]
1186        rule parameter_expansion() -> WordPiece =
1187            "${" e:parameter_expression() "}" {
1188                WordPiece::ParameterExpansion(e)
1189            } /
1190            "$" parameter:unbraced_parameter() {
1191                WordPiece::ParameterExpansion(ParameterExpr::Parameter { parameter, indirect: false })
1192            } /
1193            !expansion_opener() "$" !['\''] {
1194                WordPiece::Text("$".to_owned())
1195            }
1196
1197        // As in bash, these always start an expansion, whose end the tokenizer finds (so it
1198        // always does, in a word the tokenizer accepted). If none parses, the text is malformed
1199        // (e.g., unterminated, or nested too deeply), so its `$` mustn't be taken as literal text.
1200        // TODO(expansion): #540: the same holds for `${`, which is still taken as text.
1201        rule expansion_opener() = "$" ['(' | '[']
1202
1203        rule parameter_expression() -> ParameterExpr =
1204            indirect:parameter_indirection() parameter:parameter() test_type:parameter_test_type() "-" default_value:parameter_expression_word()? {
1205                ParameterExpr::UseDefaultValues { parameter, indirect, test_type, default_value }
1206            } /
1207            indirect:parameter_indirection() parameter:parameter() test_type:parameter_test_type() "=" default_value:parameter_expression_word()? {
1208                ParameterExpr::AssignDefaultValues { parameter, indirect, test_type, default_value }
1209            } /
1210            indirect:parameter_indirection() parameter:parameter() test_type:parameter_test_type() "?" error_message:parameter_expression_word()? {
1211                ParameterExpr::IndicateErrorIfNullOrUnset { parameter, indirect, test_type, error_message }
1212            } /
1213            indirect:parameter_indirection() parameter:parameter() test_type:parameter_test_type() "+" alternative_value:parameter_expression_word()? {
1214                ParameterExpr::UseAlternativeValue { parameter, indirect, test_type, alternative_value }
1215            } /
1216            "#" parameter:parameter() {
1217                ParameterExpr::ParameterLength { parameter, indirect: false }
1218            } /
1219            indirect:parameter_indirection() parameter:parameter() "%%" pattern:parameter_expression_word()? {
1220                ParameterExpr::RemoveLargestSuffixPattern { parameter, indirect, pattern }
1221            } /
1222            indirect:parameter_indirection() parameter:parameter() "%" pattern:parameter_expression_word()? {
1223                ParameterExpr::RemoveSmallestSuffixPattern { parameter, indirect, pattern }
1224            } /
1225            indirect:parameter_indirection() parameter:parameter() "##" pattern:parameter_expression_word()? {
1226                ParameterExpr::RemoveLargestPrefixPattern { parameter, indirect, pattern }
1227            } /
1228            indirect:parameter_indirection() parameter:parameter() "#" pattern:parameter_expression_word()? {
1229                ParameterExpr::RemoveSmallestPrefixPattern { parameter, indirect, pattern }
1230            } /
1231            // N.B. The following case is for non-sh extensions.
1232            non_posix_extensions_enabled() e:non_posix_parameter_expression() { e } /
1233            indirect:parameter_indirection() parameter:parameter() {
1234                ParameterExpr::Parameter { parameter, indirect }
1235            }
1236
1237        rule parameter_test_type() -> ParameterTestType =
1238            colon:":"? {
1239                if colon.is_some() {
1240                    ParameterTestType::UnsetOrNull
1241                } else {
1242                    ParameterTestType::Unset
1243                }
1244            }
1245
1246        rule non_posix_parameter_expression() -> ParameterExpr =
1247            "!" variable_name:variable_name() "[*]" {
1248                ParameterExpr::MemberKeys { variable_name: variable_name.to_owned(), concatenate: true }
1249            } /
1250            "!" variable_name:variable_name() "[@]" {
1251                ParameterExpr::MemberKeys { variable_name: variable_name.to_owned(), concatenate: false }
1252            } /
1253            indirect:parameter_indirection() parameter:parameter() ":" offset:substring_offset() length:(":" l:substring_length() { l })? {
1254                ParameterExpr::Substring { parameter, indirect, offset, length }
1255            } /
1256            indirect:parameter_indirection() parameter:parameter() "@" op:non_posix_parameter_transformation_op() {
1257                ParameterExpr::Transform { parameter, indirect, op }
1258            } /
1259            "!" prefix:variable_name() "*" {
1260                ParameterExpr::VariableNames { prefix: prefix.to_owned(), concatenate: true }
1261            } /
1262            "!" prefix:variable_name() "@" {
1263                ParameterExpr::VariableNames { prefix: prefix.to_owned(), concatenate: false }
1264            } /
1265            indirect:parameter_indirection() parameter:parameter() "/#" pattern:parameter_search_pattern() replacement:parameter_replacement_str()? {
1266                ParameterExpr::ReplaceSubstring { parameter, indirect, pattern, replacement, match_kind: SubstringMatchKind::Prefix }
1267            } /
1268            indirect:parameter_indirection() parameter:parameter() "/%" pattern:parameter_search_pattern() replacement:parameter_replacement_str()? {
1269                ParameterExpr::ReplaceSubstring { parameter, indirect, pattern, replacement, match_kind: SubstringMatchKind::Suffix }
1270            } /
1271            indirect:parameter_indirection() parameter:parameter() "//" pattern:parameter_search_pattern() replacement:parameter_replacement_str()? {
1272                ParameterExpr::ReplaceSubstring { parameter, indirect, pattern, replacement, match_kind: SubstringMatchKind::Anywhere }
1273            } /
1274            indirect:parameter_indirection() parameter:parameter() "/" pattern:parameter_search_pattern() replacement:parameter_replacement_str()? {
1275                ParameterExpr::ReplaceSubstring { parameter, indirect, pattern, replacement, match_kind: SubstringMatchKind::FirstOccurrence }
1276            } /
1277            indirect:parameter_indirection() parameter:parameter() "^^" pattern:parameter_expression_word()? {
1278                ParameterExpr::UppercasePattern { parameter, indirect, pattern }
1279            } /
1280            indirect:parameter_indirection() parameter:parameter() "^" pattern:parameter_expression_word()? {
1281                ParameterExpr::UppercaseFirstChar { parameter, indirect, pattern }
1282            } /
1283            indirect:parameter_indirection() parameter:parameter() ",," pattern:parameter_expression_word()? {
1284                ParameterExpr::LowercasePattern { parameter, indirect, pattern }
1285            } /
1286            indirect:parameter_indirection() parameter:parameter() "," pattern:parameter_expression_word()? {
1287                ParameterExpr::LowercaseFirstChar { parameter, indirect, pattern }
1288            }
1289
1290        rule parameter_indirection() -> bool =
1291            non_posix_extensions_enabled() "!" { true } /
1292            { false }
1293
1294        rule non_posix_parameter_transformation_op() -> ParameterTransformOp =
1295            "U" { ParameterTransformOp::ToUpperCase } /
1296            "u" { ParameterTransformOp::CapitalizeInitial } /
1297            "L" { ParameterTransformOp::ToLowerCase } /
1298            "Q" { ParameterTransformOp::Quoted } /
1299            "E" { ParameterTransformOp::ExpandEscapeSequences } /
1300            "P" { ParameterTransformOp::PromptExpand } /
1301            "A" { ParameterTransformOp::ToAssignmentLogic } /
1302            "K" { ParameterTransformOp::PossiblyQuoteWithArraysExpanded { separate_words: false } } /
1303            "a" { ParameterTransformOp::ToAttributeFlags } /
1304            "k" { ParameterTransformOp::PossiblyQuoteWithArraysExpanded { separate_words: true } }
1305
1306
1307        rule unbraced_parameter() -> Parameter =
1308            p:unbraced_positional_parameter() { Parameter::Positional(p) } /
1309            p:special_parameter() { Parameter::Special(p) } /
1310            p:variable_name() { Parameter::Named(p.to_owned()) }
1311
1312        // N.B. The indexing syntax is not a standard sh-ism.
1313        pub(crate) rule parameter() -> Parameter =
1314            p:positional_parameter() { Parameter::Positional(p) } /
1315            p:special_parameter() { Parameter::Special(p) } /
1316            non_posix_extensions_enabled() p:variable_name() "[@]" { Parameter::NamedWithAllIndices { name: p.to_owned(), concatenate: false } } /
1317            non_posix_extensions_enabled() p:variable_name() "[*]" { Parameter::NamedWithAllIndices { name: p.to_owned(), concatenate: true } } /
1318            non_posix_extensions_enabled() p:variable_name() "[" index:array_index() "]" {?
1319                Ok(Parameter::NamedWithIndex { name: p.to_owned(), index: index.to_owned() })
1320            } /
1321            p:variable_name() { Parameter::Named(p.to_owned()) }
1322
1323        rule positional_parameter() -> u32 =
1324            n:$(['1'..='9'](['0'..='9']*)) {? n.parse().or(Err("u32")) }
1325        rule unbraced_positional_parameter() -> u32 =
1326            n:$(['1'..='9']) {? n.parse().or(Err("u32")) }
1327
1328        rule special_parameter() -> SpecialParameter =
1329            "@" { SpecialParameter::AllPositionalParameters { concatenate: false } } /
1330            "*" { SpecialParameter::AllPositionalParameters { concatenate: true } } /
1331            "#" { SpecialParameter::PositionalParameterCount } /
1332            "?" { SpecialParameter::LastExitStatus } /
1333            "-" { SpecialParameter::CurrentOptionFlags } /
1334            "$" { SpecialParameter::ProcessId } /
1335            "!" { SpecialParameter::LastBackgroundProcessId } /
1336            "0" { SpecialParameter::ShellName }
1337
1338        rule variable_name() -> &'input str =
1339            $(!['0'..='9'] ['_' | '0'..='9' | 'a'..='z' | 'A'..='Z']+)
1340
1341        pub(crate) rule command_substitution() -> WordPiece =
1342            "$(" c:command_substitution_body() ")" { WordPiece::CommandSubstitution(c.to_owned()) } /
1343            "`" c:backquoted_command() "`" { WordPiece::BackquotedCommandSubstitution(c) }
1344
1345        // The tokenizer already has the logic to find where the command ends (e.g., skipping
1346        // over here-doc bodies), so we leverage it here. `pos` and `body.len()` are both
1347        // byte offsets.
1348        rule command_substitution_body() -> &'input str = #{|input, pos| {
1349            let rest = input.split_at(pos).1;
1350            match crate::tokenizer::command_substitution_body(rest, &parser_options.tokenizer_options()) {
1351                Ok(body) => peg::RuleResult::Matched(pos + body.len(), body),
1352                Err(_) => peg::RuleResult::Failed,
1353            }
1354        }}
1355
1356        rule backquoted_command() -> String =
1357            chars:(backquoted_char()*) {
1358                let mut command: String = chars.into_iter().collect();
1359                // TODO(tokenizer): A backslash ending the input is reported as an unterminated
1360                // escape, where bash takes it literally; escape it so it stays literal.
1361                if command.chars().rev().take_while(|c| *c == '\\').count() % 2 == 1 {
1362                    command.push('\\');
1363                }
1364                command
1365            }
1366
1367        // As in bash, a backslash is removed only before `$`, `` ` ``, or `\`. (The tokenizer
1368        // already removed line continuations.)
1369        rule backquoted_char() -> &'input str =
1370            "\\" s:$(['$' | '`' | '\\']) { s } /
1371            s:$([^'`']) { s }
1372
1373        rule arithmetic_expansion() -> WordPiece =
1374            "$((" e:$(arithmetic_word(<"))">)) "))" { WordPiece::ArithmeticExpression(ast::UnexpandedArithmeticExpr { value: e.to_owned() } ) }
1375
1376        rule legacy_arithmetic_expansion() -> WordPiece =
1377            "$[" e:legacy_arithmetic_expansion_body() "]" { WordPiece::ArithmeticExpression(ast::UnexpandedArithmeticExpr { value: e.to_owned() } ) }
1378
1379        // Reuse the tokenizer's iterative bracket counting rather than recursively parsing
1380        // each bracket in the expression. As with command substitutions, preserve the source.
1381        rule legacy_arithmetic_expansion_body() -> &'input str = #{|input, pos| {
1382            let rest = input.split_at(pos).1;
1383            match crate::tokenizer::legacy_arithmetic_expansion_body(rest, &parser_options.tokenizer_options()) {
1384                Ok(body) => peg::RuleResult::Matched(pos + body.len(), body),
1385                Err(_) => peg::RuleResult::Failed,
1386            }
1387        }}
1388
1389        rule substring_offset() -> ast::UnexpandedArithmeticExpr =
1390            s:$(arithmetic_word(<[':' | '}']>)) { ast::UnexpandedArithmeticExpr { value: s.to_owned() } }
1391
1392        rule substring_length() -> ast::UnexpandedArithmeticExpr =
1393            s:$(arithmetic_word(<[':' | '}']>)) { ast::UnexpandedArithmeticExpr { value: s.to_owned() } }
1394
1395        rule parameter_replacement_str() -> String =
1396            "/" s:$(word(<['}']>)) { s.to_owned() }
1397
1398        rule parameter_search_pattern() -> String =
1399            s:$(word(<['}' | '/']>)) { s.to_owned() }
1400
1401        rule parameter_expression_word() -> String =
1402            s:$(word(<['}']>)) { s.to_owned() }
1403
1404        rule extglob_enabled() -> () =
1405            &[_] {? if parser_options.enable_extended_globbing { Ok(()) } else { Err("no extglob") } }
1406
1407        rule non_posix_extensions_enabled() -> () =
1408            &[_] {? if !parser_options.sh_mode { Ok(()) } else { Err("posix") } }
1409
1410        rule tilde_exprs_at_word_start_enabled() -> () =
1411            &[_] {? if parser_options.tilde_expansion_at_word_start { Ok(()) } else { Err("no tilde expansion at word start") } }
1412
1413        rule tilde_exprs_after_colon_enabled() -> () =
1414            &[_] {? if parser_options.tilde_expansion_after_colon { Ok(()) } else { Err("no tilde expansion after colon") } }
1415
1416        // Assignment rules.
1417
1418        pub(crate) rule name_equals_scalar_value() -> ast::Assignment =
1419            nae:name_equals() value:assigned_scalar_value() {
1420                let (name, append) = nae;
1421                ast::Assignment { name, value, append, loc: SourceSpan::default() }
1422            }
1423
1424        pub(crate) rule name_equals() -> (ast::AssignmentName, bool) =
1425            name:assignment_name() append:("+"?) "=" {
1426                (name, append.is_some())
1427            }
1428
1429        pub(crate) rule literal_array_element() -> (Option<String>, String) =
1430            "[" inner:$((!"]" [_])*) "]=" value:$([_]*) {
1431                (Some(inner.to_owned()), value.to_owned())
1432            } /
1433            value:$([_]+) {
1434                (None, value.to_owned())
1435            }
1436
1437        rule assignment_name() -> ast::AssignmentName =
1438            aen:array_element_name() {
1439                let (name, index) = aen;
1440                ast::AssignmentName::ArrayElementName(name.to_owned(), index.to_owned())
1441            } /
1442            name:assigned_scalar_name() {
1443                ast::AssignmentName::VariableName(name.to_owned())
1444            }
1445
1446        rule array_element_name() -> (&'input str, &'input str) =
1447            name:assigned_scalar_name() "[" ai:array_index() "]" { (name, ai) }
1448
1449        rule array_index() -> &'input str =
1450            $(arithmetic_word(<"]">))
1451
1452        rule assigned_scalar_name() -> &'input str =
1453            $(alpha_or_underscore() non_first_variable_char()*)
1454
1455        rule non_first_variable_char() -> () =
1456            ['_' | '0'..='9' | 'a'..='z' | 'A'..='Z'] {}
1457
1458        rule alpha_or_underscore() -> () =
1459            ['_' | 'a'..='z' | 'A'..='Z'] {}
1460
1461        rule assigned_scalar_value() -> ast::AssignmentValue =
1462            v:$([_]*) { ast::AssignmentValue::Scalar(ast::Word::from(v.to_owned())) }
1463    }
1464}
1465
1466#[cfg(test)]
1467#[allow(clippy::panic_in_result_fn)]
1468mod tests {
1469    use super::*;
1470    use anyhow::Result;
1471    use insta::assert_ron_snapshot;
1472    use pretty_assertions::assert_matches;
1473
1474    #[derive(serde::Serialize, serde::Deserialize)]
1475    struct ParseTestResults<'a> {
1476        input: &'a str,
1477        result: Vec<WordPieceWithSource>,
1478    }
1479
1480    fn test_parse(word: &str) -> Result<ParseTestResults<'_>> {
1481        let parsed = super::parse(word, &ParserOptions::default())?;
1482        Ok(ParseTestResults {
1483            input: word,
1484            result: parsed,
1485        })
1486    }
1487
1488    #[test]
1489    fn parse_ansi_c_quoted_text() -> Result<()> {
1490        assert_ron_snapshot!(test_parse(r"$'hi\nthere\t'")?);
1491        Ok(())
1492    }
1493
1494    #[test]
1495    fn parse_ansi_c_quoted_escape_seq() -> Result<()> {
1496        assert_ron_snapshot!(test_parse(r"$'\\'")?);
1497        Ok(())
1498    }
1499
1500    #[test]
1501    fn parse_tilde_with_out_of_range_dir_stack_index() -> Result<()> {
1502        // Regression: the dir-stack index was unwrapped, so a run of digits too
1503        // large for a `usize` panicked the parser. It should fall through to
1504        // being treated as a user name, which is what bash does with it.
1505        // `~N` and `~-N` fall through to a user name; `~+N` cannot, because '+'
1506        // is not a valid user-name character, so it stays literal text. Both
1507        // match what bash does with an out-of-range index.
1508        let parsed = super::parse("~99999999999999999999", &ParserOptions::default())?;
1509        assert_eq!(parsed.len(), 1);
1510        assert_matches!(
1511            parsed[0].piece,
1512            WordPiece::TildeExpansion(TildeExpr::UserHome(_))
1513        );
1514
1515        let parsed = super::parse("~-99999999999999999999", &ParserOptions::default())?;
1516        assert_eq!(parsed.len(), 1);
1517        assert_matches!(
1518            parsed[0].piece,
1519            WordPiece::TildeExpansion(TildeExpr::UserHome(_))
1520        );
1521
1522        let parsed = super::parse("~+99999999999999999999", &ParserOptions::default())?;
1523        assert_eq!(parsed.len(), 1);
1524        assert_matches!(parsed[0].piece, WordPiece::Text(_));
1525
1526        Ok(())
1527    }
1528
1529    #[test]
1530    fn parse_tilde_with_in_range_dir_stack_index() -> Result<()> {
1531        let parsed = super::parse("~+2", &ParserOptions::default())?;
1532        assert_eq!(parsed.len(), 1);
1533        assert_matches!(
1534            parsed[0].piece,
1535            WordPiece::TildeExpansion(TildeExpr::NthDirFromTopOfDirStack { n: 2, .. })
1536        );
1537
1538        Ok(())
1539    }
1540
1541    #[test]
1542    fn parse_tilde_after_colon() -> Result<()> {
1543        let opts = ParserOptions {
1544            tilde_expansion_after_colon: true,
1545            ..ParserOptions::default()
1546        };
1547
1548        let parsed = super::parse("a:~", &opts)?;
1549
1550        // Should have: Text("a:"), TildeExpansion("")
1551        assert_eq!(parsed.len(), 2);
1552        assert_matches!(parsed[0].piece, WordPiece::Text(_));
1553        assert_matches!(parsed[1].piece, WordPiece::TildeExpansion(_));
1554
1555        Ok(())
1556    }
1557
1558    #[test]
1559    fn parse_double_quoted_text() -> Result<()> {
1560        assert_ron_snapshot!(test_parse(r#""a ${b} c""#)?);
1561        Ok(())
1562    }
1563
1564    #[test]
1565    fn parse_gettext_double_quoted_text() -> Result<()> {
1566        assert_ron_snapshot!(test_parse(r#"$"a ${b} c""#)?);
1567        Ok(())
1568    }
1569
1570    #[test]
1571    fn parse_command_substitution() -> Result<()> {
1572        super::expansion_parser::command_substitution("$(echo hi)", &ParserOptions::default())?;
1573
1574        assert_ron_snapshot!(test_parse("$(echo hi)")?);
1575
1576        Ok(())
1577    }
1578
1579    #[test]
1580    fn parse_command_substitution_with_embedded_quotes() -> Result<()> {
1581        super::expansion_parser::command_substitution(
1582            r#"$(echo "hi")"#,
1583            &ParserOptions::default(),
1584        )?;
1585
1586        assert_ron_snapshot!(test_parse(r#"$(echo "hi")"#)?);
1587        Ok(())
1588    }
1589
1590    #[test]
1591    fn parse_command_substitution_with_multibyte_chars() -> Result<()> {
1592        assert_ron_snapshot!(test_parse("é$(echo “ü”)ñ")?);
1593        Ok(())
1594    }
1595
1596    #[test]
1597    fn parse_command_substitution_with_embedded_extglob() -> Result<()> {
1598        assert_ron_snapshot!(test_parse("$(echo !(x))")?);
1599        Ok(())
1600    }
1601
1602    #[test]
1603    fn parse_command_sub_with_unbalanced_single_quote() -> Result<()> {
1604        assert_ron_snapshot!(test_parse("\"$(cat <<'EOF'\nit's here\nEOF\n)\"")?);
1605        Ok(())
1606    }
1607
1608    #[test]
1609    fn parse_command_sub_with_unbalanced_backtick() -> Result<()> {
1610        assert_ron_snapshot!(test_parse("\"$(cat <<'EOF'\na ` b\nEOF\n)\"")?);
1611        Ok(())
1612    }
1613
1614    #[test]
1615    fn parse_command_sub_with_balanced_double_quotes() -> Result<()> {
1616        assert_ron_snapshot!(test_parse("\"$(cat <<'EOF'\n\"hello\"\nEOF\n)\"")?);
1617        Ok(())
1618    }
1619
1620    #[test]
1621    fn parse_command_sub_with_balanced_single_quotes() -> Result<()> {
1622        assert_ron_snapshot!(test_parse("\"$(cat <<'EOF'\n'hello'\nEOF\n)\"")?);
1623        Ok(())
1624    }
1625
1626    #[test]
1627    fn parse_command_sub_with_balanced_backticks() -> Result<()> {
1628        assert_ron_snapshot!(test_parse("\"$(cat <<'EOF'\n`hello`\nEOF\n)\"")?);
1629        Ok(())
1630    }
1631
1632    #[test]
1633    fn parse_backquoted_command() -> Result<()> {
1634        assert_ron_snapshot!(test_parse("`echo hi`")?);
1635        Ok(())
1636    }
1637
1638    #[test]
1639    fn parse_backquoted_command_in_double_quotes() -> Result<()> {
1640        assert_ron_snapshot!(test_parse(r#""`echo hi`""#)?);
1641        Ok(())
1642    }
1643
1644    #[test]
1645    fn parse_backquoted_command_escapes() -> Result<()> {
1646        for (input, expected) in [
1647            (r"`printf \\2`", r"printf \2"),
1648            (r"`printf \\\\2`", r"printf \\2"),
1649            (r#"`echo \$x \` \" \a`"#, r#"echo $x ` \" \a"#),
1650            // A backslash left ending the command is escaped to keep it literal.
1651            (r"`printf \\`", r"printf \\"),
1652            (r"`printf \\\\`", r"printf \\"),
1653            (r"`printf \\\\\\`", r"printf \\\\"),
1654        ] {
1655            let parsed = super::parse(input, &ParserOptions::default())?;
1656            assert_matches!(
1657                &parsed[..],
1658                [WordPieceWithSource { piece: WordPiece::BackquotedCommandSubstitution(command), .. }]
1659                    if command == expected,
1660                "parsing {input:?}"
1661            );
1662        }
1663        Ok(())
1664    }
1665
1666    #[test]
1667    fn parse_extglob_with_embedded_parameter() -> Result<()> {
1668        assert_ron_snapshot!(test_parse("+([$var])")?);
1669        Ok(())
1670    }
1671
1672    #[test]
1673    fn parse_arithmetic_expansion() -> Result<()> {
1674        assert_ron_snapshot!(test_parse("$((0))")?);
1675        Ok(())
1676    }
1677
1678    #[test]
1679    fn parse_arithmetic_expansion_with_parens() -> Result<()> {
1680        assert_ron_snapshot!(test_parse("$((((1+2)*3)))")?);
1681        Ok(())
1682    }
1683
1684    #[test]
1685    fn parse_arithmetic_expansion_with_unmatched_brackets() -> Result<()> {
1686        // Invalid arithmetic must stay arithmetic, rather than fall back to executing
1687        // the expression as a command substitution.
1688        for expr in ["echo unexpected [", "1[", "a[1", "[ ["] {
1689            let word = std::format!("$(({expr}))");
1690            let parsed = super::parse(&word, &ParserOptions::default())?;
1691            assert_matches!(
1692                parsed.as_slice(),
1693                [WordPieceWithSource { piece: WordPiece::ArithmeticExpression(e), .. }] if e.value == expr,
1694                "for {word:?}"
1695            );
1696        }
1697        Ok(())
1698    }
1699
1700    #[test]
1701    fn parse_arithmetic_expansion_with_deep_brackets() -> Result<()> {
1702        // Brackets in the expression must not grow the word parser's call stack.
1703        // Arithmetic evaluation can reject this expression after its boundaries are found.
1704        let expr = std::format!("{}1{}", "[".repeat(15_000), "]".repeat(15_000));
1705        for (open, close) in [("$((", "))"), ("$[", "]")] {
1706            let word = std::format!("{open}{expr}{close}");
1707            let parsed = super::parse(&word, &ParserOptions::default())?;
1708            assert_matches!(
1709                parsed.as_slice(),
1710                [WordPieceWithSource { piece: WordPiece::ArithmeticExpression(e), .. }] if e.value == expr
1711            );
1712        }
1713        Ok(())
1714    }
1715
1716    #[test]
1717    fn parse_legacy_arithmetic_expansion_with_array_subscripts() -> Result<()> {
1718        for (word, expr) in [
1719            ("$[a[1]]", "a[1]"),
1720            ("$[ a[1] + 1 ]", " a[1] + 1 "),
1721            ("$[ a[ a[0] ] ]", " a[ a[0] ] "),
1722            ("$[ a[$[1]] + $(printf 2) ]", " a[$[1]] + $(printf 2) "),
1723            ("$[ 'é]' ]", " 'é]' "),
1724            ("$[ \\] ]", " \\] "),
1725        ] {
1726            let parsed = super::parse(word, &ParserOptions::default())?;
1727            assert_matches!(
1728                parsed.as_slice(),
1729                [WordPieceWithSource { piece: WordPiece::ArithmeticExpression(e), .. }] if e.value == expr,
1730                "for {word:?}"
1731            );
1732        }
1733        Ok(())
1734    }
1735
1736    #[test]
1737    fn parse_malformed_expansions_as_errors() {
1738        // As in bash, a `$` before `(` or `[` always starts an expansion; if none parses, the
1739        // text is malformed, not literal text.
1740        let options = ParserOptions::default();
1741        for word in ["a$(echo", "\"$(echo\"", "$((1 +", "$[1 +", "\"a $[1 + b\""] {
1742            assert!(super::parse(word, &options).is_err(), "for {word:?}");
1743        }
1744        for body in [
1745            "a $(echo hi\n",
1746            "a $(echo 'b) c\n",
1747            "a $((1 + b\n",
1748            "a $[1 + b\n",
1749        ] {
1750            assert!(
1751                super::parse_heredoc(body, &options).is_err(),
1752                "for {body:?}"
1753            );
1754        }
1755    }
1756
1757    #[test]
1758    fn parse_malformed_expansions_nested_in_parameter_expansions_quickly() {
1759        // Each `${...}` can match any of ~20 parameter expression forms; unless its parse is
1760        // memoized, a failure within (e.g., an unterminated `$(`) is re-discovered by each form,
1761        // taking time exponential in the nesting depth.
1762        let options = ParserOptions::default();
1763        let nested =
1764            |inner: &str| std::format!("{}{inner}{}\n", "${x:-".repeat(30), "}".repeat(30));
1765        assert!(super::parse_heredoc(&nested("$(echo"), &options).is_err());
1766        assert!(super::parse_heredoc(&nested("$((1 +"), &options).is_err());
1767        assert!(super::parse(&std::format!("\"{}\"", nested("$[1").trim_end()), &options).is_err());
1768    }
1769
1770    #[test]
1771    fn parse_lone_dollar_signs_as_text() -> Result<()> {
1772        let options = ParserOptions::default();
1773        for word in [
1774            "$", "a$", "$ b", "$%", "\"$\"", "\"a$ b\"", "\"$'x'\"", "${x}$",
1775        ] {
1776            super::parse(word, &options)?;
1777        }
1778        super::parse_heredoc("cost: $5 $ $% \"$'x'\" a$\n", &options)?;
1779        Ok(())
1780    }
1781
1782    fn quoted_text(text: &str, kind: DoubleQuotedTextKind) -> Result<Vec<WordPiece>> {
1783        let pieces = super::parse_double_quoted_text(text, kind, &ParserOptions::default())?;
1784        Ok(pieces.into_iter().map(|piece| piece.piece).collect())
1785    }
1786
1787    fn text(s: &str) -> WordPiece {
1788        WordPiece::Text(s.to_owned())
1789    }
1790
1791    fn escape(s: &str) -> WordPiece {
1792        WordPiece::EscapeSequence(s.to_owned())
1793    }
1794
1795    #[test]
1796    fn parse_double_quoted_text_as_heredoc_body() -> Result<()> {
1797        use DoubleQuotedTextKind::HereDoc;
1798
1799        // Quotes are text, and a backslash is an escape only before `$`, `` ` `` and `\`.
1800        assert_eq!(
1801            quoted_text(r#"a "b" 'c' \" \$ \z \\ $'d'"#, HereDoc)?,
1802            [
1803                text(r#"a "b" 'c' \" "#),
1804                escape(r"\$"),
1805                text(r" \z "),
1806                escape(r"\\"),
1807                text(" $'d'"),
1808            ]
1809        );
1810        assert_eq!(quoted_text("a\\\nb", HereDoc)?, [text("a\\\nb")]);
1811        assert_eq!(quoted_text(r"a\}b", HereDoc)?, [text(r"a\}b")]);
1812        assert_eq!(
1813            super::parse_heredoc("a \"$x\" b\n", &ParserOptions::default())?,
1814            super::parse_double_quoted_text("a \"$x\" b\n", HereDoc, &ParserOptions::default())?
1815        );
1816        Ok(())
1817    }
1818
1819    #[test]
1820    fn parse_double_quoted_text_as_prompt() -> Result<()> {
1821        use DoubleQuotedTextKind::Prompt;
1822
1823        // `\"` is an escape; a quote is still text.
1824        assert_eq!(
1825            quoted_text(r#"a\"b"c"#, Prompt)?,
1826            [text("a"), escape(r#"\""#), text(r#"b"c"#)]
1827        );
1828        // `\\` is split off first, so the quote after it is not escaped.
1829        assert_eq!(
1830            quoted_text(r#"a\\"b"#, Prompt)?,
1831            [text("a"), escape(r"\\"), text(r#""b"#)]
1832        );
1833
1834        // A backslash and the newline after it yield nothing.
1835        assert_eq!(quoted_text("a\\\nb", Prompt)?, [text("a"), text("b")]);
1836        assert_eq!(quoted_text("\\\n", Prompt)?, []);
1837        // An escaped backslash doesn't continue the line.
1838        assert_eq!(
1839            quoted_text("a\\\\\nb", Prompt)?,
1840            [text("a"), escape(r"\\"), text("\nb")]
1841        );
1842        Ok(())
1843    }
1844
1845    #[test]
1846    fn parse_double_quoted_text_as_word_in_heredoc_or_prompt() -> Result<()> {
1847        use DoubleQuotedTextKind::WordInHereDocOrPrompt as Word;
1848
1849        // The word's own quotes are removed.
1850        assert_eq!(
1851            quoted_text(r#"a"b c"d"#, Word)?,
1852            [text("a"), text("b c"), text("d")]
1853        );
1854        assert_eq!(quoted_text(r#""it's""#, Word)?, [text("it's")]);
1855        assert_eq!(quoted_text(r#""""#, Word)?, []);
1856        assert_eq!(quoted_text("", Word)?, []);
1857
1858        // Outside the quotes a backslash also escapes `"` and `}`; between them, anything.
1859        assert_eq!(
1860            quoted_text(r#"a\zb\}c\"d"#, Word)?,
1861            [
1862                text(r"a\zb"),
1863                escape(r"\}"),
1864                text("c"),
1865                escape(r#"\""#),
1866                text("d")
1867            ]
1868        );
1869        assert_eq!(
1870            quoted_text(r#""a\zb\'c""#, Word)?,
1871            [
1872                text("a"),
1873                escape(r"\z"),
1874                text("b"),
1875                escape(r"\'"),
1876                text("c")
1877            ]
1878        );
1879
1880        // A pair of quotes may enclose expansions, and a pair left open runs to the end.
1881        let pieces = quoted_text(r#"x"a $y b"z"#, Word)?;
1882        assert_eq!(pieces.len(), 5);
1883        assert_eq!(pieces[1], text("a "));
1884        assert_matches!(pieces[2], WordPiece::ParameterExpansion(_));
1885        assert_eq!(pieces[3], text(" b"));
1886        assert_eq!(quoted_text(r#"a"b"#, Word)?, [text("a"), text("b")]);
1887
1888        // `$'...'` is text, as in the body.
1889        assert_eq!(quoted_text(r"a$'b\tc'd", Word)?, [text(r"a$'b\tc'd")]);
1890        Ok(())
1891    }
1892
1893    #[test]
1894    fn parse_double_quoted_text_as_word_in_double_quotes() -> Result<()> {
1895        use DoubleQuotedTextKind::WordInDoubleQuotes as Word;
1896
1897        // As a word in a here doc, except that `$'...'` and `$"..."` are quotes.
1898        assert_eq!(
1899            quoted_text(r"a$'b\tc'd", Word)?,
1900            [
1901                text("a"),
1902                WordPiece::AnsiCQuotedText(r"b\tc".to_owned()),
1903                text("d")
1904            ]
1905        );
1906        let pieces = quoted_text(r#"a$"b"c"#, Word)?;
1907        assert_eq!(pieces.len(), 3);
1908        assert_matches!(&pieces[1], WordPiece::GettextDoubleQuotedSequence(inner) if inner.len() == 1);
1909        // Not between the word's own quotes, though, where a backslash escapes anything.
1910        assert_eq!(
1911            quoted_text(r#""$'a\x41b'""#, Word)?,
1912            [text("$'a"), escape(r"\x"), text("41b'")]
1913        );
1914        assert_eq!(quoted_text(r#""it's""#, Word)?, [text("it's")]);
1915        assert_eq!(
1916            quoted_text(r#"a\}b\"c"#, Word)?,
1917            [
1918                text("a"),
1919                escape(r"\}"),
1920                text("b"),
1921                escape(r#"\""#),
1922                text("c")
1923            ]
1924        );
1925        Ok(())
1926    }
1927
1928    #[test]
1929    fn quote_double_quoted_text_round_trips() -> Result<()> {
1930        use DoubleQuotedTextKind::{HereDoc, Prompt, WordInDoubleQuotes, WordInHereDocOrPrompt};
1931
1932        // Every character the kind treats as special, and every one it doesn't, comes
1933        // back as the text it was.
1934        let text: String = (b' '..=b'~').map(char::from).chain(['\t', '\n']).collect();
1935        let text = text + r#"$'a\x41b' $"loc" \" \} \\" "#;
1936        for kind in [HereDoc, Prompt, WordInHereDocOrPrompt, WordInDoubleQuotes] {
1937            let mut read_back = String::new();
1938            for piece in super::parse_double_quoted_text(
1939                &kind.quote(&text),
1940                kind,
1941                &ParserOptions::default(),
1942            )? {
1943                match piece.piece {
1944                    WordPiece::Text(s) => read_back.push_str(&s),
1945                    WordPiece::EscapeSequence(s) => read_back.push_str(
1946                        s.strip_prefix('\\')
1947                            .ok_or_else(|| anyhow::anyhow!("{kind:?}: bad escape {s:?}"))?,
1948                    ),
1949                    other => anyhow::bail!("{kind:?}: {other:?} is not literal text"),
1950                }
1951            }
1952            assert_eq!(read_back, text, "{kind:?}");
1953        }
1954        Ok(())
1955    }
1956
1957    #[test]
1958    fn parse_heredoc_with_command_substitutions_nested_too_deeply() -> Result<()> {
1959        // Here-doc bodies aren't tokenized along with the script, so the word parser is the
1960        // first to find nesting past the tokenizer's limit; that's an error, not literal text.
1961        let nested = |depth: u32| {
1962            let depth = depth as usize;
1963            std::format!("{}:{}\n", "$(".repeat(depth), ")".repeat(depth))
1964        };
1965        let limit = crate::tokenizer::MAX_EXPANSION_NESTING;
1966        let options = ParserOptions::default();
1967        super::parse_heredoc(&nested(limit), &options)?;
1968        assert!(super::parse_heredoc(&nested(limit + 1), &options).is_err());
1969        Ok(())
1970    }
1971
1972    #[test]
1973    fn test_arithmetic_word_parsing() {
1974        let options = ParserOptions::default();
1975
1976        assert!(super::expansion_parser::is_arithmetic_word("a", &options).is_ok());
1977        assert!(super::expansion_parser::is_arithmetic_word("b", &options).is_ok());
1978        assert!(super::expansion_parser::is_arithmetic_word(" a + b ", &options).is_ok());
1979        assert!(super::expansion_parser::is_arithmetic_word("(a)", &options).is_ok());
1980        assert!(super::expansion_parser::is_arithmetic_word("((a))", &options).is_ok());
1981        assert!(super::expansion_parser::is_arithmetic_word("(((a)))", &options).is_ok());
1982        assert!(super::expansion_parser::is_arithmetic_word("(1+2)", &options).is_ok());
1983        assert!(super::expansion_parser::is_arithmetic_word("(1+2)*3", &options).is_ok());
1984        assert!(super::expansion_parser::is_arithmetic_word("((1+2)*3)", &options).is_ok());
1985    }
1986
1987    #[test]
1988    fn test_arithmetic_word_piece_parsing() {
1989        let options = ParserOptions::default();
1990
1991        assert!(super::expansion_parser::is_arithmetic_word_piece("a", &options).is_ok());
1992        assert!(super::expansion_parser::is_arithmetic_word_piece("b", &options).is_ok());
1993        assert!(super::expansion_parser::is_arithmetic_word_piece(" a + b ", &options).is_ok());
1994        assert!(super::expansion_parser::is_arithmetic_word_piece("(a)", &options).is_ok());
1995        assert!(super::expansion_parser::is_arithmetic_word_piece("((a))", &options).is_ok());
1996        assert!(super::expansion_parser::is_arithmetic_word_piece("(((a)))", &options).is_ok());
1997        assert!(super::expansion_parser::is_arithmetic_word_piece("(1+2)", &options).is_ok());
1998        assert!(super::expansion_parser::is_arithmetic_word_piece("((1+2))", &options).is_ok());
1999        assert!(super::expansion_parser::is_arithmetic_word_piece("((1+2)*3)", &options).is_ok());
2000        assert!(super::expansion_parser::is_arithmetic_word_piece("(a", &options).is_err());
2001        assert!(super::expansion_parser::is_arithmetic_word_piece("(a))", &options).is_err());
2002        assert!(super::expansion_parser::is_arithmetic_word_piece("((a)", &options).is_err());
2003    }
2004
2005    #[test]
2006    fn test_brace_expansion_parsing() -> Result<()> {
2007        let options = ParserOptions::default();
2008
2009        let inputs = ["x{a,b}y", "{a,b{1,2}}"];
2010
2011        for input in inputs {
2012            assert_ron_snapshot!(super::parse_brace_expansions(input, &options)?.ok_or_else(
2013                || anyhow::anyhow!("Expected brace expansion to be parsed successfully")
2014            )?);
2015        }
2016
2017        Ok(())
2018    }
2019
2020    #[test]
2021    fn brace_sequence_with_out_of_range_increment_is_text() -> Result<()> {
2022        let options = ParserOptions::default();
2023
2024        for input in [
2025            "{1..5..99999999999999999999}",
2026            "{1..5..-99999999999999999999}",
2027            "{a..e..99999999999999999999}",
2028            // No sequence steps by `i64::MIN`, whose magnitude overflows.
2029            "{1..5..-9223372036854775808}",
2030            "{5..1..-9223372036854775808}",
2031            "{3..3..-9223372036854775808}",
2032            "{a..e..-9223372036854775808}",
2033            "{e..a..-9223372036854775808}",
2034        ] {
2035            let pieces = super::parse_brace_expansions(input, &options)?.unwrap_or_default();
2036            assert!(
2037                pieces
2038                    .iter()
2039                    .all(|piece| matches!(piece, BraceExpressionOrText::Text(_))),
2040                "{input} should not parse as a brace sequence: {pieces:?}"
2041            );
2042        }
2043
2044        Ok(())
2045    }
2046
2047    #[test]
2048    fn parse_runs_of_unterminated_braces_quickly() -> Result<()> {
2049        // Each `{` is tried both as the start of a brace expression and as plain text; unless
2050        // the brace expression parse is memoized, that takes time exponential in the length
2051        // of the run.
2052        let options = ParserOptions::default();
2053        let run = "{".repeat(30);
2054
2055        let word = std::format!("{run}.");
2056        let pieces = super::parse_brace_expansions(&word, &options)?.unwrap_or_default();
2057        assert_eq!(pieces, vec![BraceExpressionOrText::Text(word)]);
2058
2059        // A complete brace expression after the run is still found.
2060        let word = std::format!("{run}{{a,b}}");
2061        let pieces = super::parse_brace_expansions(&word, &options)?.unwrap_or_default();
2062        assert_eq!(
2063            pieces,
2064            vec![
2065                BraceExpressionOrText::Text(run.clone()),
2066                BraceExpressionOrText::Expr(vec![
2067                    BraceExpressionMember::Child(vec![BraceExpressionOrText::Text("a".into())]),
2068                    BraceExpressionMember::Child(vec![BraceExpressionOrText::Text("b".into())]),
2069                ]),
2070            ]
2071        );
2072
2073        // So is one that encloses the run.
2074        let word = std::format!("{{a,{run}b}}");
2075        let pieces = super::parse_brace_expansions(&word, &options)?.unwrap_or_default();
2076        assert_eq!(
2077            pieces,
2078            vec![BraceExpressionOrText::Expr(vec![
2079                BraceExpressionMember::Child(vec![BraceExpressionOrText::Text("a".into())]),
2080                BraceExpressionMember::Child(vec![BraceExpressionOrText::Text(std::format!(
2081                    "{run}b"
2082                ))]),
2083            ])]
2084        );
2085
2086        Ok(())
2087    }
2088
2089    #[test]
2090    fn test_scalar_assignment_parsing() -> Result<()> {
2091        let options = ParserOptions::default();
2092
2093        super::parse_scalar_assignment("x=3", &options)?;
2094        super::parse_scalar_assignment("x=", &options)?;
2095        super::parse_scalar_assignment("x[3]=a", &options)?;
2096        super::parse_scalar_assignment("x[${y[3]}]=a", &options)?;
2097        super::parse_scalar_assignment("x[y[3]]=a", &options)?;
2098        Ok(())
2099    }
2100
2101    #[test]
2102    fn parse_compound_assignment_value() {
2103        let options = ParserOptions::default();
2104        let parse = |value| super::parse_compound_assignment_value(value, &options);
2105
2106        assert_matches!(parse("()").as_deref(), Some([]));
2107
2108        assert_matches!(parse("(1 2)").as_deref(), Some([(None, first), (None, second)])
2109            if first.value == "1" && second.value == "2");
2110
2111        assert_matches!(
2112            parse(r#"([key]=value "other one")"#).as_deref(),
2113            Some([(Some(key), value), (None, other)])
2114                if key.value == "key"
2115                    && value.value == "value"
2116                    && other.value == r#""other one""#);
2117
2118        // Text that is not exclusively a compound value must not be accepted; otherwise trailing
2119        // shell syntax hidden in an expanded value would be silently dropped.
2120        assert!(parse(r#"(x); printf "INJECTED\n"; #"#).is_none());
2121        assert!(parse("(unterminated").is_none());
2122        assert!(parse("plain text").is_none());
2123        assert!(parse("").is_none());
2124    }
2125
2126    #[test]
2127    fn parse_sequence_bound() {
2128        assert_eq!(super::parse_sequence_bound("3"), Some(3));
2129        assert_eq!(super::parse_sequence_bound("007"), Some(7));
2130        assert_eq!(super::parse_sequence_bound("+7"), Some(7));
2131        assert_eq!(super::parse_sequence_bound("-007"), Some(-7));
2132        assert_eq!(super::parse_sequence_bound("0"), Some(0));
2133        assert_eq!(super::parse_sequence_bound("-0"), Some(0));
2134        assert_eq!(super::parse_sequence_bound("99999999999999999999"), None);
2135
2136        // The digits of `i64::MIN` are one past `i64::MAX`, so the sign has to be parsed with them.
2137        assert_eq!(
2138            super::parse_sequence_bound("-9223372036854775808"),
2139            Some(i64::MIN)
2140        );
2141        assert_eq!(
2142            super::parse_sequence_bound("9223372036854775807"),
2143            Some(i64::MAX)
2144        );
2145        assert_eq!(super::parse_sequence_bound("-9223372036854775809"), None);
2146    }
2147
2148    #[test]
2149    fn zero_padded_width() {
2150        let width = super::zero_padded_width;
2151
2152        // Neither bound was written with a leading zero.
2153        assert_eq!(width("1", "5"), None);
2154        assert_eq!(width("0", "10"), None);
2155        assert_eq!(width("-0", "3"), None);
2156
2157        // The width is the longer bound as written, whichever one asked for padding.
2158        assert_eq!(width("01", "5"), Some(2));
2159        assert_eq!(width("1", "005"), Some(3));
2160        assert_eq!(width("0009", "11"), Some(4));
2161
2162        // A sign takes one of the columns.
2163        assert_eq!(width("-01", "01"), Some(3));
2164        assert_eq!(width("00", "-3"), Some(2));
2165
2166        // A zero after a plus does not ask for padding, though the text still
2167        // counts toward the width once the other bound has asked.
2168        assert_eq!(width("+01", "3"), None);
2169        assert_eq!(width("+01", "05"), Some(3));
2170    }
2171}