Skip to main content

brush_parser/
tokenizer.rs

1use std::borrow::Cow;
2use std::sync::Arc;
3use utf8_chars::BufReadCharsExt;
4
5use crate::{SourcePosition, SourceSpan};
6
7mod char_reader;
8use char_reader::CharReader;
9
10#[derive(Clone, Debug)]
11pub(crate) enum TokenEndReason {
12    /// End of input was reached.
13    EndOfInput,
14    /// An unescaped newline char was reached.
15    UnescapedNewLine,
16    /// The next char (not yet consumed) closes the nested expansion being tokenized. Never
17    /// carries a token, so here-document bookkeeping can't hold it back.
18    ExpansionClosingChar,
19    /// A non-newline blank char was reached.
20    NonNewLineBlank,
21    /// A here-document's body is starting.
22    HereDocumentBodyStart,
23    /// A here-document's body was terminated.
24    HereDocumentBodyEnd,
25    /// A here-document's end tag was reached.
26    HereDocumentEndTag,
27    /// An operator was started.
28    OperatorStart,
29    /// An operator was terminated.
30    OperatorEnd,
31    /// Some other condition was reached.
32    Other,
33}
34
35/// Compatibility alias for `SourceSpan`.
36pub type TokenLocation = SourceSpan;
37
38/// Represents a token extracted from a shell script.
39#[derive(Clone, Debug)]
40#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
41#[cfg_attr(
42    any(test, feature = "serde"),
43    derive(PartialEq, Eq, serde::Serialize, serde::Deserialize)
44)]
45pub enum Token {
46    /// An operator token.
47    Operator(String, SourceSpan),
48    /// A word token.
49    Word(String, SourceSpan),
50}
51
52impl Token {
53    /// Returns the string value of the token.
54    pub fn to_str(&self) -> &str {
55        match self {
56            Self::Operator(s, _) => s,
57            Self::Word(s, _) => s,
58        }
59    }
60
61    /// Returns the location of the token in the source script.
62    pub const fn location(&self) -> &SourceSpan {
63        match self {
64            Self::Operator(_, l) => l,
65            Self::Word(_, l) => l,
66        }
67    }
68}
69
70#[cfg(feature = "diagnostics")]
71impl From<&Token> for miette::SourceSpan {
72    fn from(token: &Token) -> Self {
73        let start = token.location().start.as_ref();
74        Self::new(start.into(), token.location().len_bytes())
75    }
76}
77
78/// Encapsulates the result of tokenizing a shell script.
79#[derive(Clone, Debug)]
80pub(crate) struct TokenizeResult {
81    /// Reason for tokenization ending.
82    pub reason: TokenEndReason,
83    /// The token that was extracted, if any.
84    pub token: Option<Token>,
85}
86
87/// Represents an error that occurred during tokenization.
88#[derive(thiserror::Error, Debug)]
89#[non_exhaustive]
90pub enum TokenizerError {
91    /// An unterminated escape sequence was encountered at the end of the input stream.
92    #[error("unterminated escape sequence")]
93    UnterminatedEscapeSequence,
94
95    /// An unterminated single-quoted substring was encountered at the end of the input stream.
96    #[error("unterminated single quote at {0}")]
97    UnterminatedSingleQuote(SourcePosition),
98
99    /// An unterminated ANSI C-quoted substring was encountered at the end of the input stream.
100    #[error("unterminated ANSI C quote at {0}")]
101    UnterminatedAnsiCQuote(SourcePosition),
102
103    /// An unterminated double-quoted substring was encountered at the end of the input stream.
104    #[error("unterminated double quote at {0}")]
105    UnterminatedDoubleQuote(SourcePosition),
106
107    /// An unterminated back-quoted substring was encountered at the end of the input stream.
108    #[error("unterminated backquote near {0}")]
109    UnterminatedBackquote(SourcePosition),
110
111    /// An unterminated extended glob (extglob) pattern was encountered at the end of the input
112    /// stream.
113    #[error("unterminated extglob near {0}")]
114    UnterminatedExtendedGlob(SourcePosition),
115
116    /// An unterminated variable expression was encountered at the end of the input stream.
117    #[error("unterminated variable expression")]
118    UnterminatedVariable,
119
120    /// An unterminated command substitiion was encountered at the end of the input stream.
121    #[error("unterminated command substitution")]
122    UnterminatedCommandSubstitution,
123
124    /// An unterminated arithmetic or other expansion was encountered at the end of the input
125    /// stream.
126    #[error("unterminated expansion")]
127    UnterminatedExpansion,
128
129    /// An error occurred decoding UTF-8 characters in the input stream.
130    #[error("failed to decode UTF-8 characters")]
131    FailedDecoding,
132
133    /// A here-document body was due with no here tag recorded for it. This reflects an
134    /// inconsistency in the tokenizer's own state, not a problem with the input.
135    #[error("missing here tag for here document body")]
136    MissingHereTagForDocumentBody,
137
138    /// A here-document operator (`<<` or `<<-`) was followed by an operator (e.g., a newline,
139    /// `;` or `)`) where its tag belongs; the string is that operator.
140    #[error("missing here-document tag before {0:?}")]
141    MissingHereTag(String),
142
143    /// The input ended after a here-document operator (`<<` or `<<-`) and before its tag, but
144    /// not right at the operator (e.g., after blanks following it). Input ending right at the
145    /// operator (even after a line continuation, which is removed) tokenizes, leaving the parser
146    /// to report its end. Unlike [`TokenizerError::MissingHereTag`], more input could still
147    /// supply the tag.
148    #[error("missing here-document tag at end of input")]
149    MissingHereTagAtEndOfInput,
150
151    /// An unterminated here document sequence was encountered at the end of the input stream.
152    #[error("unterminated here document; tag(s) {0} declared at {1}")]
153    UnterminatedHereDocuments(String, String),
154
155    /// Expansions delimited by brackets (`$(...)`, `$((...))`, `$[...]` and `${...}`) were
156    /// nested in one another more deeply than the tokenizer supports.
157    #[error("expansions nested too deeply (limit: {})", MAX_EXPANSION_NESTING)]
158    ExpansionNestingTooDeep,
159
160    /// An I/O error occurred while reading from the input stream.
161    #[error("failed to read input")]
162    ReadError(#[from] std::io::Error),
163}
164
165impl TokenizerError {
166    /// Returns true if the error represents an error that could possibly be due
167    /// to an incomplete input stream.
168    pub const fn is_incomplete(&self) -> bool {
169        matches!(
170            self,
171            Self::UnterminatedEscapeSequence
172                | Self::UnterminatedAnsiCQuote(..)
173                | Self::UnterminatedSingleQuote(..)
174                | Self::UnterminatedDoubleQuote(..)
175                | Self::UnterminatedBackquote(..)
176                | Self::UnterminatedCommandSubstitution
177                | Self::UnterminatedExpansion
178                | Self::UnterminatedVariable
179                | Self::UnterminatedExtendedGlob(..)
180                | Self::UnterminatedHereDocuments(..)
181                | Self::MissingHereTagAtEndOfInput
182        )
183    }
184}
185
186/// Encapsulates a sequence of tokens.
187#[derive(Debug)]
188pub(crate) struct Tokens<'a> {
189    /// Sequence of tokens.
190    pub tokens: &'a [Token],
191}
192
193#[derive(Clone, Debug)]
194enum QuoteMode {
195    None,
196    AnsiC(SourcePosition),
197    Single(SourcePosition),
198    Double(SourcePosition),
199}
200
201#[derive(Clone, Debug, Default)]
202enum HereState {
203    /// In this state, we are not currently tracking any here-documents.
204    #[default]
205    None,
206    /// In this state, a here-document operator is being delimited, and the next token will be
207    /// its tag.
208    NextTokenIsHereTag { remove_tabs: bool },
209    /// In this state, the operator has been read, and the token now being read (once it ends)
210    /// will be its tag.
211    CurrentTokenIsHereTag {
212        remove_tabs: bool,
213        operator_token_result: TokenizeResult,
214    },
215    /// In this state, we expect that the *next line* will be the body of
216    /// a here-document.
217    NextLineIsHereDoc,
218    /// In this state, we are in the set of lines that comprise 1 or more
219    /// consecutive here-document bodies.
220    InHereDocs,
221}
222
223impl HereState {
224    /// Returns true if a here-document operator has been read but its tag hasn't (yet).
225    const fn awaiting_tag(&self) -> bool {
226        matches!(
227            self,
228            Self::NextTokenIsHereTag { .. } | Self::CurrentTokenIsHereTag { .. }
229        )
230    }
231}
232
233#[derive(Clone, Debug)]
234struct HereTag {
235    tag: String,
236    tag_was_escaped_or_quoted: bool,
237    remove_tabs: bool,
238    position: SourcePosition,
239    tokens: Vec<TokenizeResult>,
240    pending_tokens_after: Vec<TokenizeResult>,
241}
242
243#[derive(Clone, Debug)]
244struct CrossTokenParseState {
245    /// Cursor within the overall token stream; used for error reporting.
246    cursor: SourcePosition,
247    /// Tokens already tokenized that should be used first to serve requests for tokens.
248    queued_tokens: Vec<TokenizeResult>,
249    /// State of the expansion frame being tokenized; see [`ExpansionFrame`].
250    frame: ExpansionFrame,
251}
252
253/// An expansion delimited by brackets, whose contents are tokenized recursively (as a
254/// [`ExpansionFrame`] of their own) while it's consumed as part of a word.
255#[derive(Clone, Copy, Debug, PartialEq, Eq)]
256enum NestedExpansion {
257    /// `$(...)`
258    CommandSubstitution,
259    /// `$((...))`
260    ArithmeticExpansion,
261    /// `$[...]`
262    LegacyArithmeticExpansion,
263    /// `${...}`
264    ParameterExpansion,
265}
266
267impl NestedExpansion {
268    /// Returns the character that closes the expansion.
269    const fn closing_char(self) -> char {
270        match self {
271            Self::CommandSubstitution | Self::ArithmeticExpansion => ')',
272            Self::LegacyArithmeticExpansion => ']',
273            Self::ParameterExpansion => '}',
274        }
275    }
276
277    /// Returns whether the expansion's contents are arithmetic, where `<<` is a shift.
278    const fn is_arithmetic(self) -> bool {
279        matches!(
280            self,
281            Self::ArithmeticExpansion | Self::LegacyArithmeticExpansion
282        )
283    }
284
285    /// Returns the character that, in the expansion's contents, pairs with its closing char:
286    /// the `(` of `$( (a) )`, or the `[` of `$[ a[1] ]`. Bash doesn't pair braces in `${...}`.
287    const fn opening_char(self) -> Option<char> {
288        match self {
289            Self::CommandSubstitution | Self::ArithmeticExpansion => Some('('),
290            Self::LegacyArithmeticExpansion => Some('['),
291            Self::ParameterExpansion => None,
292        }
293    }
294
295    /// Returns how many closing chars end the expansion, counting from just after its
296    /// opening: two for `$((`, whose opening leaves two parens open, and one otherwise.
297    const fn closers_after_opening(self) -> usize {
298        match self {
299            Self::ArithmeticExpansion => 2,
300            _ => 1,
301        }
302    }
303
304    /// Returns the error for input that ends before the expansion is closed.
305    const fn unterminated_error(self) -> TokenizerError {
306        match self {
307            Self::ParameterExpansion => TokenizerError::UnterminatedVariable,
308            _ => TokenizerError::UnterminatedExpansion,
309        }
310    }
311}
312
313/// Tokenizer state belonging to one frame of the stack of nested expansions being tokenized;
314/// the bottom frame is the top level of the input, outside any expansion. Consuming a nested
315/// expansion pushes a fresh frame for its contents and pops it at the expansion's end, as
316/// bash saves and restores its parser state around a command substitution. The stack is the
317/// recursion itself: each enclosing frame is held by the call consuming the expansion nested
318/// in it.
319#[derive(Clone, Debug, Default)]
320struct ExpansionFrame {
321    /// The expansion whose contents this frame is, if any (none at the bottom).
322    expansion: Option<NestedExpansion>,
323    /// How many frames enclose this one; see [`MAX_EXPANSION_NESTING`].
324    depth: u32,
325    /// Current state of parsing here-documents.
326    here_state: HereState,
327    /// Ordered queue of here tags for which we're still looking for matching here-document bodies.
328    current_here_tags: Vec<HereTag>,
329    /// How many closing chars (see [`NestedExpansion::closing_char`]) the expansion needs
330    /// before it ends. Its contents may use the closing char too, paired with an opener of
331    /// their own (see [`NestedExpansion::opening_char`]); each opener read needs one more.
332    closers_needed: usize,
333    /// How many parens of the `((...))` command being read are still open, if any (zero
334    /// outside one). Within one, `<<` is a shift rather than a here-document operator. (In an
335    /// arithmetic expansion's contents, `<<` is always a shift; see
336    /// [`NestedExpansion::is_arithmetic`].)
337    arithmetic_command_parens: usize,
338}
339
340impl ExpansionFrame {
341    /// Notes that `c` was read unquoted from the frame's own contents (not from anything
342    /// nested in them), keeping count of the closing chars the expansion needs: an opener
343    /// needs one more, and a closing char that doesn't end the expansion closes an opener.
344    fn note_unquoted_char(&mut self, c: char) {
345        let Some(expansion) = self.expansion else {
346            return;
347        };
348        if expansion.opening_char() == Some(c) {
349            self.closers_needed += 1;
350        } else if expansion.closing_char() == c {
351            // A closing char that ends the expansion is taken as such before it's read as
352            // contents, so it never gets here.
353            debug_assert!(self.closers_needed > 1, "read the expansion's closing char");
354            self.closers_needed -= 1;
355        }
356    }
357}
358
359/// Options controlling how the tokenizer operates.
360#[derive(Clone, Debug, Hash, Eq, PartialEq)]
361pub struct TokenizerOptions {
362    /// Whether or not to enable extended globbing patterns (extglob).
363    pub enable_extended_globbing: bool,
364    /// Whether or not to operate in POSIX compliance mode.
365    pub posix_mode: bool,
366    /// Whether or not we're running in SH emulation mode.
367    pub sh_mode: bool,
368}
369
370impl Default for TokenizerOptions {
371    fn default() -> Self {
372        Self {
373            enable_extended_globbing: true,
374            posix_mode: false,
375            sh_mode: false,
376        }
377    }
378}
379
380/// Maximum depth of nested expansions (see [`NestedExpansion`]) the tokenizer will descend
381/// into, so deeply nested input can't overflow the stack while it's tokenized. Real scripts
382/// rarely nest more than a few levels: of ~2,900 surveyed (including bash-completion and
383/// ble.sh), none nested more than 4.
384///
385/// This bounds only the tokenizer's own recursion. Words keep their nesting, so later passes
386/// over them (e.g., expanding them) recurse as deeply, with stack frames of their own that may
387/// be far larger (in an unoptimized build, over 100 KiB per level of `${...}` expansion).
388pub(crate) const MAX_EXPANSION_NESTING: u32 = 32;
389
390/// A tokenizer for shell scripts.
391pub(crate) struct Tokenizer<'a, R: ?Sized + std::io::BufRead> {
392    char_reader: CharReader<utf8_chars::Chars<'a, R>>,
393    /// Chars read ahead and put back, to be read again before any further input; see
394    /// [`Tokenizer::read_here_doc_bodies_left_pending`].
395    unread: Option<UnreadChars>,
396    /// Whether to read the bodies of here-documents left pending when a nested expansion ends;
397    /// see [`Tokenizer::read_here_doc_bodies_left_pending`]. [`command_substitution_body`]
398    /// doesn't: it wants only the text before the `)`, and the bodies follow it.
399    read_bodies_left_pending: bool,
400    cross_state: CrossTokenParseState,
401    options: TokenizerOptions,
402}
403
404/// Chars read ahead of the tokenizer and put back.
405struct UnreadChars {
406    /// The chars, in reverse order (the next to be read last).
407    chars: Vec<char>,
408    /// Where the cursor resumes once they've all been read again: where it was after reading
409    /// ahead, not where it would be after the chars themselves.
410    resume_at: SourcePosition,
411}
412
413/// Encapsulates the current token parsing state.
414#[derive(Clone, Debug)]
415struct TokenParseState {
416    pub start_position: SourcePosition,
417    pub token_so_far: String,
418    pub token_is_operator: bool,
419    pub in_escape: bool,
420    pub quote_mode: QuoteMode,
421}
422
423impl TokenParseState {
424    pub fn new(start_position: &SourcePosition) -> Self {
425        Self {
426            start_position: start_position.to_owned(),
427            token_so_far: String::new(),
428            token_is_operator: false,
429            in_escape: false,
430            quote_mode: QuoteMode::None,
431        }
432    }
433
434    pub fn pop(&mut self, end_position: &SourcePosition) -> Token {
435        let end = Arc::new(end_position.to_owned());
436        let token_location = SourceSpan {
437            start: Arc::new(std::mem::take(&mut self.start_position)),
438            end,
439        };
440
441        let token = if std::mem::take(&mut self.token_is_operator) {
442            Token::Operator(std::mem::take(&mut self.token_so_far), token_location)
443        } else {
444            Token::Word(std::mem::take(&mut self.token_so_far), token_location)
445        };
446
447        end_position.clone_into(&mut self.start_position);
448        self.in_escape = false;
449        self.quote_mode = QuoteMode::None;
450
451        token
452    }
453
454    pub const fn started_token(&self) -> bool {
455        !self.token_so_far.is_empty()
456    }
457
458    /// Returns true if the token so far consists only of blanks.
459    ///
460    /// This can only happen when tokenizing with `include_space`, where blanks are accumulated
461    /// into the token so that the original text of a nested expansion can be reproduced. Such
462    /// blanks are not a word, so a `#` following them still begins a comment.
463    pub fn only_blanks_so_far(&self) -> bool {
464        !self.token_so_far.is_empty() && self.token_so_far.chars().all(is_blank)
465    }
466
467    pub fn append_char(&mut self, c: char) {
468        self.token_so_far.push(c);
469    }
470
471    pub fn append_str(&mut self, s: &str) {
472        self.token_so_far.push_str(s);
473    }
474
475    pub const fn unquoted(&self) -> bool {
476        !self.in_escape && matches!(self.quote_mode, QuoteMode::None)
477    }
478
479    pub fn current_token(&self) -> &str {
480        &self.token_so_far
481    }
482
483    pub fn is_specific_operator(&self, operator: &str) -> bool {
484        self.token_is_operator && self.current_token() == operator
485    }
486
487    pub const fn in_operator(&self) -> bool {
488        self.token_is_operator
489    }
490
491    fn is_newline(&self) -> bool {
492        self.token_so_far == "\n"
493    }
494
495    fn replace_with_here_doc(&mut self, s: String) {
496        self.token_so_far = s;
497    }
498
499    #[allow(clippy::too_many_lines)]
500    pub fn delimit_current_token(
501        &mut self,
502        reason: TokenEndReason,
503        cross_token_state: &mut CrossTokenParseState,
504    ) -> Result<Option<TokenizeResult>, TokenizerError> {
505        // If we don't have anything in the token, then don't yield an empty string token
506        // *unless* it's the body of a here document.
507        if !self.started_token() && !matches!(reason, TokenEndReason::HereDocumentBodyEnd) {
508            return Ok(Some(TokenizeResult {
509                reason,
510                token: None,
511            }));
512        }
513
514        let current_here_state = std::mem::take(&mut cross_token_state.frame.here_state);
515        match current_here_state {
516            HereState::NextTokenIsHereTag { remove_tabs } => {
517                // Don't yield the operator as a token yet. We need to make sure we collect
518                // up everything we need for all the here-documents with tags on this line.
519                let operator_token_result = TokenizeResult {
520                    reason,
521                    token: Some(self.pop(&cross_token_state.cursor)),
522                };
523
524                cross_token_state.frame.here_state = HereState::CurrentTokenIsHereTag {
525                    remove_tabs,
526                    operator_token_result,
527                };
528
529                return Ok(None);
530            }
531            HereState::CurrentTokenIsHereTag {
532                remove_tabs,
533                operator_token_result,
534            } => {
535                // A here tag must be a word; an operator in its place (e.g., a newline, `;`
536                // or `)`) means it's missing.
537                if self.token_is_operator {
538                    return Err(TokenizerError::MissingHereTag(
539                        self.current_token().to_owned(),
540                    ));
541                }
542
543                // Inside a nested expansion, where blanks are kept, blanks between the
544                // operator and the tag may be delimited as a token of their own (e.g., the
545                // first of the two blanks in `$(cat <<  EOF)`). They're not the tag; skip
546                // them and keep waiting for it.
547                if self.only_blanks_so_far() {
548                    self.pop(&cross_token_state.cursor);
549                    cross_token_state.frame.here_state = HereState::CurrentTokenIsHereTag {
550                        remove_tabs,
551                        operator_token_result,
552                    };
553                    return Ok(None);
554                }
555
556                cross_token_state.frame.here_state = HereState::NextLineIsHereDoc;
557
558                // Include the trailing \n in the here tag so it's easier to check against. Kept
559                // blanks may lead the token (e.g., `$(cat << EOF)`); strip only those, since
560                // anything else (even a carriage return) is part of the tag.
561                let tag = std::format!("{}\n", self.current_token().trim_start_matches(is_blank));
562                let tag_was_escaped_or_quoted = tag.contains(is_quoting_char);
563
564                let tag_token_result = TokenizeResult {
565                    reason,
566                    token: Some(self.pop(&cross_token_state.cursor)),
567                };
568
569                cross_token_state.frame.current_here_tags.push(HereTag {
570                    tag,
571                    tag_was_escaped_or_quoted,
572                    remove_tabs,
573                    position: cross_token_state.cursor.clone(),
574                    tokens: vec![operator_token_result, tag_token_result],
575                    pending_tokens_after: vec![],
576                });
577
578                return Ok(None);
579            }
580            HereState::NextLineIsHereDoc => {
581                if self.is_newline() {
582                    cross_token_state.frame.here_state = HereState::InHereDocs;
583                } else {
584                    cross_token_state.frame.here_state = HereState::NextLineIsHereDoc;
585                }
586
587                if let Some(last_here_tag) = cross_token_state.frame.current_here_tags.last_mut() {
588                    let token = self.pop(&cross_token_state.cursor);
589                    let result = TokenizeResult {
590                        reason,
591                        token: Some(token),
592                    };
593
594                    last_here_tag.pending_tokens_after.push(result);
595                } else {
596                    return Err(TokenizerError::MissingHereTagForDocumentBody);
597                }
598
599                return Ok(None);
600            }
601            HereState::InHereDocs => {
602                // We hit the end of the current here-document.
603                let completed_here_tag = cross_token_state.frame.current_here_tags.remove(0);
604
605                // First queue the redirection operator and (start) here-tag.
606                cross_token_state
607                    .queued_tokens
608                    .extend(completed_here_tag.tokens);
609
610                // Leave a hint that we are about to start a here-document.
611                cross_token_state.queued_tokens.push(TokenizeResult {
612                    reason: TokenEndReason::HereDocumentBodyStart,
613                    token: None,
614                });
615
616                // Then queue the body document we just finished.
617                cross_token_state.queued_tokens.push(TokenizeResult {
618                    reason,
619                    token: Some(self.pop(&cross_token_state.cursor)),
620                });
621
622                // Then queue up the (end) here-tag.
623                let end_tag = if completed_here_tag.tag_was_escaped_or_quoted {
624                    unquote_str(&completed_here_tag.tag)
625                } else {
626                    completed_here_tag.tag
627                };
628                self.append_str(end_tag.trim_end_matches('\n'));
629                cross_token_state.queued_tokens.push(TokenizeResult {
630                    reason: TokenEndReason::HereDocumentEndTag,
631                    token: Some(self.pop(&cross_token_state.cursor)),
632                });
633
634                // Now we're ready to queue up any tokens that came between the completed
635                // here tag and the next here tag (or newline after it if it was the last).
636                cross_token_state
637                    .queued_tokens
638                    .extend(completed_here_tag.pending_tokens_after);
639
640                if cross_token_state.frame.current_here_tags.is_empty() {
641                    cross_token_state.frame.here_state = HereState::None;
642                } else {
643                    cross_token_state.frame.here_state = HereState::InHereDocs;
644                }
645
646                return Ok(None);
647            }
648            HereState::None => (),
649        }
650
651        let token = self.pop(&cross_token_state.cursor);
652        let result = TokenizeResult {
653            reason,
654            token: Some(token),
655        };
656
657        Ok(Some(result))
658    }
659}
660
661/// Break the given input shell script string into tokens, returning the tokens.
662///
663/// # Arguments
664///
665/// * `input` - The shell script to tokenize.
666pub fn tokenize_str(input: &str) -> Result<Vec<Token>, TokenizerError> {
667    tokenize_str_with_options(input, &TokenizerOptions::default())
668}
669
670/// Break the given input shell script string into tokens, returning the tokens.
671///
672/// # Arguments
673///
674/// * `input` - The shell script to tokenize.
675/// * `options` - Options controlling how the tokenizer operates.
676pub fn tokenize_str_with_options(
677    input: &str,
678    options: &TokenizerOptions,
679) -> Result<Vec<Token>, TokenizerError> {
680    uncached_tokenize_string(input, options)
681}
682
683#[cached::macros::cached(
684    name = "TOKENIZE_CACHE",
685    max_size = 64,
686    key = "(String, TokenizerOptions)",
687    convert = r#"{ (input.to_owned(), options.to_owned()) }"#
688)]
689fn uncached_tokenize_string(
690    input: &str,
691    options: &TokenizerOptions,
692) -> Result<Vec<Token>, TokenizerError> {
693    uncached_tokenize_str(input, options)
694}
695
696/// Break the given input shell script string into tokens, returning the tokens.
697/// No caching is performed.
698///
699/// # Arguments
700///
701/// * `input` - The shell script to tokenize.
702pub fn uncached_tokenize_str(
703    input: &str,
704    options: &TokenizerOptions,
705) -> Result<Vec<Token>, TokenizerError> {
706    let mut reader = std::io::BufReader::new(input.as_bytes());
707    let mut tokenizer = crate::tokenizer::Tokenizer::new(&mut reader, options);
708
709    let mut tokens = vec![];
710    loop {
711        match tokenizer.next_token()? {
712            TokenizeResult {
713                token: Some(token), ..
714            } => tokens.push(token),
715            TokenizeResult {
716                reason: TokenEndReason::EndOfInput,
717                ..
718            } => break,
719            _ => (),
720        }
721    }
722
723    Ok(tokens)
724}
725
726/// Given the text following the `$(` that opens a command substitution, returns the
727/// command's text up to (but not including) the `)` that closes it. The command is
728/// tokenized to find that `)`, so quoting, nested expansions, and here-document bodies
729/// are skipped over exactly as they are when tokenizing a full script.
730///
731/// # Errors
732///
733/// Returns an error if the closing `)` can't be found: either the input ends first
734/// ([`TokenizerError::UnterminatedExpansion`]), or tokenizing the command fails before
735/// reaching it (e.g., an unterminated quote or here-document). This is not a syntax
736/// check of the command itself; it's parsed separately, when it is executed.
737pub(crate) fn command_substitution_body<'a>(
738    input: &'a str,
739    options: &TokenizerOptions,
740) -> Result<&'a str, TokenizerError> {
741    expansion_body(input, options, NestedExpansion::CommandSubstitution)
742}
743
744/// Given the text following `$[`, returns the arithmetic expression before its closing `]`.
745/// The tokenizer counts nested brackets without recursing and skips quoted brackets and
746/// nested expansions. Arithmetic syntax is checked separately when the expression is evaluated.
747pub(crate) fn legacy_arithmetic_expansion_body<'a>(
748    input: &'a str,
749    options: &TokenizerOptions,
750) -> Result<&'a str, TokenizerError> {
751    expansion_body(input, options, NestedExpansion::LegacyArithmeticExpansion)
752}
753
754fn expansion_body<'a>(
755    input: &'a str,
756    options: &TokenizerOptions,
757    expansion: NestedExpansion,
758) -> Result<&'a str, TokenizerError> {
759    let mut reader = input.as_bytes();
760    let mut tokenizer = Tokenizer::new(&mut reader, options);
761    tokenizer.read_bodies_left_pending = false;
762
763    // Consume tokens through the expansion's closing character. We don't need the token
764    // text collected in `state`: it's a normalized rendering, not a slice of `input`.
765    let mut state = TokenParseState::new(&tokenizer.cross_state.cursor);
766    tokenizer.consume_nested_expansion(&mut state, expansion)?;
767
768    // The cursor is past the closing character, which is a single byte. Slice with `get` so a
769    // cursor that ever disagreed with `input` would be a parse error, not a panic.
770    let body_len = tokenizer.cross_state.cursor.byte_offset.saturating_sub(1);
771    input
772        .get(..body_len)
773        .ok_or_else(|| expansion.unterminated_error())
774}
775
776impl<'a, R: ?Sized + std::io::BufRead> Tokenizer<'a, R> {
777    pub fn new(reader: &'a mut R, options: &TokenizerOptions) -> Self {
778        Tokenizer {
779            options: options.clone(),
780            char_reader: CharReader::new(reader.chars()),
781            unread: None,
782            read_bodies_left_pending: true,
783            cross_state: CrossTokenParseState {
784                cursor: SourcePosition {
785                    byte_offset: 0,
786                    line: 1,
787                    column: 1,
788                },
789                queued_tokens: vec![],
790                frame: ExpansionFrame::default(),
791            },
792        }
793    }
794
795    #[expect(clippy::unnecessary_wraps)]
796    pub fn current_location(&self) -> Option<SourcePosition> {
797        Some(self.cross_state.cursor.clone())
798    }
799
800    fn next_char(&mut self) -> Result<Option<char>, TokenizerError> {
801        let c = match self.unread.as_mut().and_then(|unread| unread.chars.pop()) {
802            Some(c) => Some(c),
803            None => self
804                .char_reader
805                .next()
806                .transpose()
807                .map_err(TokenizerError::ReadError)?,
808        };
809
810        if let Some(ch) = c {
811            if ch == '\n' {
812                self.cross_state.cursor.line += 1;
813                self.cross_state.cursor.column = 1;
814            } else {
815                self.cross_state.cursor.column += 1;
816            }
817            self.cross_state.cursor.byte_offset += ch.len_utf8();
818        }
819
820        if let Some(unread) = self.unread.take_if(|unread| unread.chars.is_empty()) {
821            self.cross_state.cursor = unread.resume_at;
822        }
823
824        Ok(c)
825    }
826
827    fn consume_char(&mut self) -> Result<(), TokenizerError> {
828        let _ = self.next_char()?;
829        Ok(())
830    }
831
832    fn peek_char(&mut self) -> Result<Option<char>, TokenizerError> {
833        if let Some(c) = self.unread.as_ref().and_then(|unread| unread.chars.last()) {
834            return Ok(Some(*c));
835        }
836
837        match self.char_reader.peek() {
838            Some(result) => match result {
839                Ok(c) => Ok(Some(*c)),
840                Err(_) => Err(TokenizerError::FailedDecoding),
841            },
842            None => Ok(None),
843        }
844    }
845
846    /// Returns the char after the next one, consuming neither.
847    fn peek_second_char(&mut self) -> Result<Option<char>, TokenizerError> {
848        // Any unread chars come first. They're kept in reverse order (the next one last).
849        let peeked = match self
850            .unread
851            .as_ref()
852            .map_or(&[][..], |unread| unread.chars.as_slice())
853        {
854            [.., second, _] => return Ok(Some(*second)),
855            [_] => self.char_reader.peek(),
856            [] => self.char_reader.peek_second(),
857        };
858
859        match peeked {
860            Some(Ok(c)) => Ok(Some(*c)),
861            Some(Err(_)) => Err(TokenizerError::FailedDecoding),
862            None => Ok(None),
863        }
864    }
865
866    /// Consumes any line continuations (backslash-newline pairs) next in the input. Bash removes
867    /// them as it reads input, before anything else sees it, except where a backslash is taken
868    /// literally: right after an escaping backslash, within single quotes (including `$'...'`),
869    /// in a comment, or in the body of a here-document whose tag is quoted. The tokenizer calls
870    /// this wherever it reads input in which they're removed.
871    fn skip_line_continuations(&mut self) -> Result<(), TokenizerError> {
872        while self.peek_char()? == Some('\\') && self.peek_second_char()? == Some('\n') {
873            self.consume_char()?;
874            self.consume_char()?;
875        }
876        Ok(())
877    }
878
879    /// Returns whether a backslash next in the input would be taken literally, given the state of
880    /// the token in progress, rather than possibly starting a line continuation; see
881    /// [`Tokenizer::skip_line_continuations`].
882    fn backslash_is_literal(&self, state: &TokenParseState) -> bool {
883        if state.in_escape || matches!(state.quote_mode, QuoteMode::Single(_) | QuoteMode::AnsiC(_))
884        {
885            return true;
886        }
887
888        // A here-document body follows the newline ending the line holding its tag.
889        let frame = &self.cross_state.frame;
890        let in_here_doc_body = match frame.here_state {
891            HereState::InHereDocs => true,
892            HereState::NextLineIsHereDoc => state.is_newline(),
893            _ => false,
894        };
895        if !in_here_doc_body {
896            return false;
897        }
898
899        // The whole body is literal if its tag was quoted. (Otherwise, a backslash escaping
900        // another is read along with it, so the next one is never escaped.)
901        frame
902            .current_here_tags
903            .first()
904            .is_some_and(|tag| tag.tag_was_escaped_or_quoted)
905    }
906
907    /// Consumes the rest of a nested expansion, whose opening (e.g., `$(`) has already been
908    /// appended to `state`'s token, appending the rest to it as well.
909    fn consume_nested_expansion(
910        &mut self,
911        state: &mut TokenParseState,
912        expansion: NestedExpansion,
913    ) -> Result<(), TokenizerError> {
914        // This function and `next_token` are mutually recursive, as deep as the *input* nests
915        // expansions; bound it so pathological input can't overflow the stack.
916        let depth = self.cross_state.frame.depth + 1;
917        if depth > MAX_EXPANSION_NESTING {
918            return Err(TokenizerError::ExpansionNestingTooDeep);
919        }
920
921        // Push a frame for the expansion's contents, where none of the enclosing frame's state
922        // applies: they're all part of one word, so none of their tokens can be (or end) a
923        // here tag pending before it, and they can't be in a `((...))` command. Pop it
924        // (restoring the enclosing frame) once they end.
925        let frame = ExpansionFrame {
926            expansion: Some(expansion),
927            depth,
928            closers_needed: expansion.closers_after_opening(),
929            ..ExpansionFrame::default()
930        };
931
932        // Frames share the queue of tokens, but none are queued across a push or pop: tokens
933        // are only read from the input (and so expansions only consumed) once the queue is
934        // empty, and consuming one leaves it empty.
935        debug_assert!(self.cross_state.queued_tokens.is_empty());
936        let enclosing = std::mem::replace(&mut self.cross_state.frame, frame);
937        let result = self.consume_expansion_contents(state, expansion);
938        debug_assert!(result.is_err() || self.cross_state.queued_tokens.is_empty());
939        self.cross_state.frame = enclosing;
940        result
941    }
942
943    /// Consumes the tokens of a nested expansion's contents, through its closing char,
944    /// appending their text to `state`'s token.
945    fn consume_expansion_contents(
946        &mut self,
947        state: &mut TokenParseState,
948        expansion: NestedExpansion,
949    ) -> Result<(), TokenizerError> {
950        let mut bodies = String::new();
951
952        loop {
953            let result = self.next_token()?;
954
955            match result.reason {
956                // The bodies set aside go after the rest of the line holding their tags.
957                TokenEndReason::UnescapedNewLine => state.append_str(&std::mem::take(&mut bodies)),
958                TokenEndReason::ExpansionClosingChar => {
959                    // The closing char comes next; consume it too.
960                    let closing_char = self
961                        .next_char()?
962                        .ok_or_else(|| expansion.unterminated_error())?;
963
964                    let here_state = &self.cross_state.frame.here_state;
965                    if here_state.awaiting_tag() {
966                        // The expansion ended right after a here-document operator, as in
967                        // `$(cat <<)`.
968                        return Err(TokenizerError::MissingHereTag(closing_char.to_string()));
969                    } else if matches!(here_state, HereState::NextLineIsHereDoc)
970                        && self.read_bodies_left_pending
971                    {
972                        self.read_here_doc_bodies_left_pending(state)?;
973                    }
974
975                    state.append_char(closing_char);
976                    return Ok(());
977                }
978                TokenEndReason::EndOfInput => return Err(expansion.unterminated_error()),
979                _ => (),
980            }
981
982            append_expansion_token(state, &mut bodies, &result);
983        }
984    }
985
986    /// Reads the bodies of here-documents still pending when a nested expansion's contents
987    /// end, as in `$(cat <<EOF)`, completing the expansion's text: appends to `state`'s token
988    /// the tokens held back for them, then the bodies, as though the line ended just before
989    /// the expansion's closing char (consumed, but not yet appended).
990    ///
991    /// Bash accepts this (with a warning), reading the bodies from the lines after the current
992    /// one, ahead of any other here-documents pending by then. So set the rest of the line
993    /// aside, read the bodies, and put it back to be tokenized as though they weren't there.
994    fn read_here_doc_bodies_left_pending(
995        &mut self,
996        state: &mut TokenParseState,
997    ) -> Result<(), TokenizerError> {
998        let rest_of_line_start = self.cross_state.cursor.clone();
999        let mut rest_of_line = vec![];
1000        while let Some(c) = self.next_char()? {
1001            rest_of_line.push(c);
1002            if c == '\n' {
1003                break;
1004            }
1005        }
1006
1007        // As when a line ends, the held tokens come out in order, with the bodies (and end
1008        // tags) interleaved; the bodies go after all of them.
1009        self.cross_state.frame.here_state = HereState::InHereDocs;
1010        let mut bodies = String::new();
1011        while !matches!(self.cross_state.frame.here_state, HereState::None)
1012            || !self.cross_state.queued_tokens.is_empty()
1013        {
1014            let result = self.next_token()?;
1015            append_expansion_token(state, &mut bodies, &result);
1016        }
1017        state.append_str(&bodies);
1018        state.append_char('\n');
1019
1020        if !rest_of_line.is_empty() {
1021            rest_of_line.reverse();
1022            let resume_at = std::mem::replace(&mut self.cross_state.cursor, rest_of_line_start);
1023            self.unread = Some(UnreadChars {
1024                chars: rest_of_line,
1025                resume_at,
1026            });
1027        }
1028
1029        Ok(())
1030    }
1031
1032    /// Consumes a `$` or backquote (`c`, the next char) and whatever expansion it begins
1033    /// (e.g., `$(...)`, `${...}`, `` `...` ``), appending all of it to `state`'s token.
1034    /// `in_double_quotes` says whether `c` is inside double quotes, which `state` doesn't
1035    /// always track (e.g., within an extglob pattern).
1036    #[allow(clippy::unwrap_in_result)]
1037    fn consume_dollar_or_backquote(
1038        &mut self,
1039        state: &mut TokenParseState,
1040        c: char,
1041        in_double_quotes: bool,
1042    ) -> Result<(), TokenizerError> {
1043        if c == '$' {
1044            // Consume the '$' so we can peek beyond.
1045            self.consume_char()?;
1046            self.skip_line_continuations()?;
1047
1048            // Now peek beyond to see what we have.
1049            let char_after_dollar_sign = self.peek_char()?;
1050            match char_after_dollar_sign {
1051                Some('(') => {
1052                    // Add the '$' we already consumed to the token.
1053                    state.append_char('$');
1054
1055                    // Consume the '(' and add it to the token.
1056                    state.append_char(self.next_char()?.unwrap());
1057
1058                    // Check to see if this is possibly an arithmetic expression
1059                    // (i.e., one that starts with `$((`).
1060                    self.skip_line_continuations()?;
1061                    let expansion = if matches!(self.peek_char()?, Some('(')) {
1062                        // Consume the second '(' and add it to the token.
1063                        state.append_char(self.next_char()?.unwrap());
1064                        NestedExpansion::ArithmeticExpansion
1065                    } else {
1066                        NestedExpansion::CommandSubstitution
1067                    };
1068
1069                    self.consume_nested_expansion(state, expansion)?;
1070                }
1071
1072                Some('[') => {
1073                    // Add the '$' we already consumed to the token.
1074                    state.append_char('$');
1075
1076                    // Consume the '[' and add it to the token.
1077                    state.append_char(self.next_char()?.unwrap());
1078
1079                    self.consume_nested_expansion(
1080                        state,
1081                        NestedExpansion::LegacyArithmeticExpansion,
1082                    )?;
1083                }
1084
1085                Some('{') => {
1086                    // Add the '$' we already consumed to the token.
1087                    state.append_char('$');
1088
1089                    // Consume the '{' and add it to the token.
1090                    state.append_char(self.next_char()?.unwrap());
1091
1092                    self.consume_nested_expansion(state, NestedExpansion::ParameterExpansion)?;
1093                }
1094                // `$$` is a parameter of its own; whatever follows it starts nothing.
1095                Some('$') => {
1096                    self.consume_char()?;
1097                    state.append_str("$$");
1098                }
1099
1100                // `$'...'` is ANSI-C quoting, but only outside double quotes.
1101                Some('\'') if !in_double_quotes => {
1102                    state.append_char('$');
1103                    state.quote_mode = QuoteMode::AnsiC(self.cross_state.cursor.clone());
1104                    state.append_char(self.next_char()?.unwrap());
1105                }
1106
1107                _ => {
1108                    // This is either a different character, or else the end of the string.
1109                    // Either way, add the '$' we already consumed to the token.
1110                    state.append_char('$');
1111                }
1112            }
1113        } else {
1114            // We look for the terminating backquote. First disable normal consumption and
1115            // consume the starting backquote.
1116            let backquote_pos = self.cross_state.cursor.clone();
1117            self.consume_char()?;
1118
1119            // Add the opening backquote to the token.
1120            state.append_char(c);
1121
1122            // Now continue until we see an unescaped backquote.
1123            let mut escaping_enabled = false;
1124            let mut done = false;
1125            while !done {
1126                // As in bash, line continuations are removed throughout (even within quotes in
1127                // the command), except right after an escaping backslash.
1128                if !escaping_enabled {
1129                    self.skip_line_continuations()?;
1130                }
1131
1132                // Read (and consume) the next char.
1133                let next_char_in_backquote = self.next_char()?;
1134                if let Some(cib) = next_char_in_backquote {
1135                    // Include it in the token no matter what.
1136                    state.append_char(cib);
1137
1138                    // Watch out for escaping.
1139                    if !escaping_enabled && cib == '\\' {
1140                        escaping_enabled = true;
1141                    } else {
1142                        // Look for an unescaped backquote to terminate.
1143                        if !escaping_enabled && cib == '`' {
1144                            done = true;
1145                        }
1146                        escaping_enabled = false;
1147                    }
1148                } else {
1149                    return Err(TokenizerError::UnterminatedBackquote(backquote_pos));
1150                }
1151            }
1152        }
1153
1154        Ok(())
1155    }
1156
1157    /// Returns the next token from the input stream.
1158    ///
1159    /// Within a nested expansion's contents, the closing char that ends the expansion ends the
1160    /// token in progress and is then reported on its own (see
1161    /// [`TokenEndReason::ExpansionClosingChar`]), and blanks are kept in tokens so that the
1162    /// expansion's original text can be reproduced.
1163    #[expect(clippy::cognitive_complexity)]
1164    #[expect(clippy::if_same_then_else)]
1165    #[expect(clippy::panic_in_result_fn)]
1166    #[expect(clippy::too_many_lines)]
1167    #[allow(clippy::unwrap_in_result)]
1168    pub fn next_token(&mut self) -> Result<TokenizeResult, TokenizerError> {
1169        let mut state = TokenParseState::new(&self.cross_state.cursor);
1170        let mut result: Option<TokenizeResult> = None;
1171
1172        let expansion = self.cross_state.frame.expansion;
1173        let closing_char = expansion.map(NestedExpansion::closing_char);
1174        let include_space = expansion.is_some();
1175        // Directly inside `${...}`, text is a word, not a command: bash recognizes no
1176        // here-documents, comments or extglobs there.
1177        let in_parameter_expansion = expansion == Some(NestedExpansion::ParameterExpansion);
1178        let in_arithmetic_expansion = expansion.is_some_and(NestedExpansion::is_arithmetic);
1179
1180        while result.is_none() {
1181            // First satisfy token results from our queue. Once we exhaust the queue then
1182            // we'll look at the input stream.
1183            if !self.cross_state.queued_tokens.is_empty() {
1184                return Ok(self.cross_state.queued_tokens.remove(0));
1185            }
1186
1187            // As bash does as it reads input, drop any line continuations before looking at the
1188            // next char, unless the backslash would be taken literally. A token not yet started
1189            // starts after them.
1190            let mut next = self.peek_char()?;
1191            if next == Some('\\')
1192                && self.peek_second_char()? == Some('\n')
1193                && !self.backslash_is_literal(&state)
1194            {
1195                self.skip_line_continuations()?;
1196                if !state.started_token() {
1197                    state.start_position = self.cross_state.cursor.clone();
1198                }
1199                next = self.peek_char()?;
1200            }
1201            let c = next.unwrap_or('\0');
1202
1203            // When we hit the end of the input, then we're done with the current token (if there is
1204            // one).
1205            if next.is_none() {
1206                // TODO(tokenizer): Verify we're not waiting on some terminating character?
1207                // Verify we're out of all quotes.
1208                if state.in_escape {
1209                    return Err(TokenizerError::UnterminatedEscapeSequence);
1210                }
1211                match state.quote_mode {
1212                    QuoteMode::None => (),
1213                    QuoteMode::AnsiC(pos) => {
1214                        return Err(TokenizerError::UnterminatedAnsiCQuote(pos));
1215                    }
1216                    QuoteMode::Single(pos) => {
1217                        return Err(TokenizerError::UnterminatedSingleQuote(pos));
1218                    }
1219                    QuoteMode::Double(pos) => {
1220                        return Err(TokenizerError::UnterminatedDoubleQuote(pos));
1221                    }
1222                }
1223
1224                // Verify we're not in a here document.
1225                if !matches!(self.cross_state.frame.here_state, HereState::None) {
1226                    // If the input ends while a here tag is expected, finish the tag in
1227                    // progress so it's recorded (and reported below); without one, the tag
1228                    // is missing.
1229                    if self.cross_state.frame.here_state.awaiting_tag() && state.started_token() {
1230                        state.delimit_current_token(
1231                            TokenEndReason::EndOfInput,
1232                            &mut self.cross_state,
1233                        )?;
1234                    }
1235                    if self.cross_state.frame.here_state.awaiting_tag() {
1236                        return Err(TokenizerError::MissingHereTagAtEndOfInput);
1237                    }
1238
1239                    // Only a body can end at an end tag. Outside one, an empty tag would
1240                    // "match" on every pass without making progress, looping forever.
1241                    if matches!(self.cross_state.frame.here_state, HereState::InHereDocs)
1242                        && self.remove_here_end_tag(&mut state, &mut result, false)?
1243                    {
1244                        // If we hit end tag without a trailing newline, try to get next token.
1245                        continue;
1246                    }
1247
1248                    let tag_names = self
1249                        .cross_state
1250                        .frame
1251                        .current_here_tags
1252                        .iter()
1253                        .map(|tag| std::format!("`{}`", tag.tag.trim_end_matches('\n')))
1254                        .collect::<Vec<_>>()
1255                        .join(", ");
1256                    let tag_positions = self
1257                        .cross_state
1258                        .frame
1259                        .current_here_tags
1260                        .iter()
1261                        .map(|tag| std::format!("{}", tag.position))
1262                        .collect::<Vec<_>>()
1263                        .join(", ");
1264                    return Err(TokenizerError::UnterminatedHereDocuments(
1265                        tag_names,
1266                        tag_positions,
1267                    ));
1268                }
1269
1270                result = state
1271                    .delimit_current_token(TokenEndReason::EndOfInput, &mut self.cross_state)?;
1272            //
1273            // Handle being in a here document.
1274            //
1275            } else if matches!(self.cross_state.frame.here_state, HereState::InHereDocs) {
1276                //
1277                // For now, just include the character in the current token. We also check
1278                // if there are leading tabs to be removed.
1279                //
1280                if !self.cross_state.frame.current_here_tags.is_empty()
1281                    && self.cross_state.frame.current_here_tags[0].remove_tabs
1282                    && (!state.started_token() || state.current_token().ends_with('\n'))
1283                    && c == '\t'
1284                {
1285                    // Consume it but don't include it.
1286                    self.consume_char()?;
1287                } else {
1288                    self.consume_char()?;
1289                    state.append_char(c);
1290
1291                    // See if this was a newline character following the terminating here tag.
1292                    if c == '\n' {
1293                        self.remove_here_end_tag(&mut state, &mut result, true)?;
1294                    } else if c == '\\'
1295                        && self
1296                            .cross_state
1297                            .frame
1298                            .current_here_tags
1299                            .first()
1300                            .is_some_and(|tag| !tag.tag_was_escaped_or_quoted)
1301                    {
1302                        // In the body of a here-document whose tag isn't quoted, a backslash
1303                        // escapes the next char; take that as-is too. (It isn't a newline: that
1304                        // would have been a line continuation, already removed.)
1305                        if let Some(escaped) = self.next_char()? {
1306                            state.append_char(escaped);
1307                        }
1308                    }
1309                }
1310            //
1311            // Look for the closing char that ends the nested expansion being consumed (one that
1312            // closes an opener in its contents is read like any other char, below). An operator
1313            // in progress is delimited first, below, so that it takes effect: a newline may start
1314            // a here-doc body, and a `<<` expects its tag (and reports it missing). Any other
1315            // token in progress is delimited here, leaving the closing char to be reported on
1316            // its own next time around.
1317            //
1318            } else if state.unquoted()
1319                && !state.in_operator()
1320                && closing_char == Some(c)
1321                && self.cross_state.frame.closers_needed == 1
1322            {
1323                let reason = if state.started_token() {
1324                    TokenEndReason::Other
1325                } else {
1326                    TokenEndReason::ExpansionClosingChar
1327                };
1328                result = state.delimit_current_token(reason, &mut self.cross_state)?;
1329            } else if state.in_operator() {
1330                //
1331                // We're in an operator. See if this character continues an operator, or if it
1332                // must be a separate token (because it wouldn't make a prefix of an operator).
1333                //
1334
1335                let mut hypothetical_token = state.current_token().to_owned();
1336                hypothetical_token.push(c);
1337
1338                if state.unquoted() && self.is_operator(hypothetical_token.as_ref()) {
1339                    self.consume_char()?;
1340                    state.append_char(c);
1341                } else {
1342                    assert!(state.started_token());
1343
1344                    //
1345                    // N.B. If the completed operator indicates a here-document, then keep
1346                    // track that the *next* token should be the here-tag.
1347                    //
1348                    // In an arithmetic context, don't consider << and <<- special. They're
1349                    // not here-docs, they're either a left-shift operator or a left-shift
1350                    // operator followed by a unary minus operator.
1351                    //
1352                    if in_arithmetic_expansion || in_parameter_expansion {
1353                        // Operators have no effect here: arithmetic contents are arithmetic
1354                        // throughout, and `${...}` contents are a word, not a command.
1355                    } else if self.cross_state.frame.arithmetic_command_parens > 0 {
1356                        // A `((...))` command ends at the `)` that balances its first `(`.
1357                        let parens = &mut self.cross_state.frame.arithmetic_command_parens;
1358                        if state.is_specific_operator("(") {
1359                            *parens += 1;
1360                        } else if state.is_specific_operator(")") {
1361                            *parens -= 1;
1362                        }
1363                    } else if state.is_specific_operator("<<") {
1364                        self.cross_state.frame.here_state =
1365                            HereState::NextTokenIsHereTag { remove_tabs: false };
1366                    } else if state.is_specific_operator("<<-") {
1367                        self.cross_state.frame.here_state =
1368                            HereState::NextTokenIsHereTag { remove_tabs: true };
1369                    } else if state.is_specific_operator("(") && c == '(' {
1370                        // A `((...))` command starts with this `(`.
1371                        self.cross_state.frame.arithmetic_command_parens = 1;
1372                    }
1373
1374                    let reason = if state.current_token() == "\n" {
1375                        TokenEndReason::UnescapedNewLine
1376                    } else {
1377                        TokenEndReason::OperatorEnd
1378                    };
1379
1380                    result = state.delimit_current_token(reason, &mut self.cross_state)?;
1381                }
1382            //
1383            // See if this is a character that changes the current escaping/quoting state.
1384            //
1385            } else if does_char_newly_affect_quoting(&state, c) {
1386                if c == '\\' {
1387                    self.consume_char()?;
1388                    state.in_escape = true;
1389                    state.append_char(c);
1390                } else if c == '\'' {
1391                    // (A `$'` was already taken as ANSI-C quoting where its `$` was read.)
1392                    state.quote_mode = QuoteMode::Single(self.cross_state.cursor.clone());
1393                    self.consume_char()?;
1394                    state.append_char(c);
1395                } else if c == '\"' {
1396                    state.quote_mode = QuoteMode::Double(self.cross_state.cursor.clone());
1397                    self.consume_char()?;
1398                    state.append_char(c);
1399                }
1400            }
1401            //
1402            // Handle end of single-quote, double-quote, or ANSI-C quote.
1403            else if !state.in_escape
1404                && matches!(
1405                    state.quote_mode,
1406                    QuoteMode::Single(..) | QuoteMode::AnsiC(..)
1407                )
1408                && c == '\''
1409            {
1410                state.quote_mode = QuoteMode::None;
1411                self.consume_char()?;
1412                state.append_char(c);
1413            } else if !state.in_escape
1414                && matches!(state.quote_mode, QuoteMode::Double(..))
1415                && c == '\"'
1416            {
1417                state.quote_mode = QuoteMode::None;
1418                self.consume_char()?;
1419                state.append_char(c);
1420            }
1421            //
1422            // Handle end of escape sequence.
1423            // TODO(tokenizer): Handle double-quote specific escape sequences.
1424            else if state.in_escape {
1425                state.in_escape = false;
1426                self.consume_char()?;
1427                state.append_char(c);
1428            } else if (state.unquoted()
1429                || (matches!(state.quote_mode, QuoteMode::Double(_)) && !state.in_escape))
1430                && (c == '$' || c == '`')
1431            {
1432                // TODO(tokenizer): handle quoted $ or ` in a double quote
1433                let in_double_quotes = matches!(state.quote_mode, QuoteMode::Double(_));
1434                self.consume_dollar_or_backquote(&mut state, c, in_double_quotes)?;
1435            }
1436            //
1437            // [Extension]
1438            // If extended globbing is enabled, the last consumed character is an
1439            // unquoted start of an extglob pattern, *and* if the current character
1440            // is an open parenthesis, then this begins an extglob pattern.
1441            else if c == '('
1442                && self.options.enable_extended_globbing
1443                && !in_parameter_expansion
1444                && state.unquoted()
1445                && !state.in_operator()
1446                && state
1447                    .current_token()
1448                    .ends_with(|x| Self::can_start_extglob(x))
1449            {
1450                // Consume the '(' and append it.
1451                self.consume_char()?;
1452                state.append_char(c);
1453
1454                let mut paren_depth = 1;
1455                // The char that closes the current quote, and whether backslash
1456                // escapes within it (it doesn't in '...', but does in "..." and $'...').
1457                let mut quote: Option<(char, bool)> = None;
1458                let mut after_dollar = false;
1459
1460                // Keep consuming until we see the matching end ')'. Parens inside
1461                // quotes are literal pattern characters, not delimiters. As in bash,
1462                // `$(...)` and `${...}` are only nested constructs inside double
1463                // quotes; elsewhere their parens simply count toward the nesting.
1464                while paren_depth > 0 {
1465                    // Only single quotes (including `$'...'`) keep line continuations; double
1466                    // quotes don't.
1467                    if !matches!(quote, Some(('\'', _))) {
1468                        self.skip_line_continuations()?;
1469                    }
1470                    let Some(extglob_char) = self.peek_char()? else {
1471                        return Err(TokenizerError::UnterminatedExtendedGlob(
1472                            self.cross_state.cursor.clone(),
1473                        ));
1474                    };
1475                    let was_after_dollar = std::mem::take(&mut after_dollar);
1476
1477                    let starts_nested_construct = match quote {
1478                        None => extglob_char == '`',
1479                        Some(('"', _)) => matches!(extglob_char, '`' | '$'),
1480                        Some(_) => false,
1481                    };
1482                    if starts_nested_construct {
1483                        // A `$` only gets here inside double quotes, so it's never taken as
1484                        // starting `$'...'`, which would set `state`'s quote mode rather than
1485                        // this loop's own `quote`.
1486                        let in_double_quotes = quote.is_some();
1487                        self.consume_dollar_or_backquote(
1488                            &mut state,
1489                            extglob_char,
1490                            in_double_quotes,
1491                        )?;
1492                        continue;
1493                    }
1494
1495                    // Include it in the token.
1496                    self.consume_char()?;
1497                    state.append_char(extglob_char);
1498
1499                    match extglob_char {
1500                        // Take the escaped char as-is. If the input ends instead, the next
1501                        // iteration reports the unterminated extglob.
1502                        '\\' if quote.is_none_or(|(_, escapes)| escapes) => {
1503                            if let Some(escaped_char) = self.next_char()? {
1504                                state.append_char(escaped_char);
1505                            }
1506                        }
1507                        c if quote.is_some_and(|(close, _)| close == c) => quote = None,
1508                        _ if quote.is_some() => (),
1509                        '\'' => quote = Some(('\'', was_after_dollar)),
1510                        '"' => quote = Some(('"', true)),
1511                        // `$$` is a parameter, not a `$` that could start `$'`.
1512                        '$' => after_dollar = !was_after_dollar,
1513                        '(' => paren_depth += 1,
1514                        ')' => paren_depth -= 1,
1515                        _ => (),
1516                    }
1517                }
1518            //
1519            // If the character *can* start an operator, then it will.
1520            //
1521            } else if state.unquoted() && Self::can_start_operator(c) {
1522                if state.started_token() {
1523                    result = state.delimit_current_token(
1524                        TokenEndReason::OperatorStart,
1525                        &mut self.cross_state,
1526                    )?;
1527                } else {
1528                    state.token_is_operator = true;
1529                    self.consume_char()?;
1530                    state.append_char(c);
1531                    self.cross_state.frame.note_unquoted_char(c);
1532                }
1533            //
1534            // Whitespace gets discarded (and delimits tokens).
1535            //
1536            } else if state.unquoted() && is_blank(c) {
1537                if state.started_token() {
1538                    result = state.delimit_current_token(
1539                        TokenEndReason::NonNewLineBlank,
1540                        &mut self.cross_state,
1541                    )?;
1542
1543                    // Where blanks are kept, this one begins the next token, as written.
1544                    if include_space {
1545                        continue;
1546                    }
1547                } else if include_space {
1548                    state.append_char(c);
1549                } else {
1550                    // Make sure we don't include this char in the token range.
1551                    state.start_position.column += 1;
1552                    state.start_position.byte_offset += c.len_utf8();
1553                }
1554
1555                self.consume_char()?;
1556            }
1557            //
1558            // N.B. Inside a parameter expansion, everything left belongs to the word, even
1559            // where no token was started: a `#` there never starts a comment (e.g., `${#x}`).
1560            //
1561            // Elsewhere, the `!only_blanks_so_far` clause keeps a comment recognizable inside a
1562            // nested expansion. Blanks are kept in tokens there, so a `#` after them follows a
1563            // token in progress; being only blanks, that token isn't a word, and the `#` still
1564            // starts a comment (e.g., in `$( #'<newline>)`).
1565            //
1566            else if !state.token_is_operator
1567                && (in_parameter_expansion
1568                    || (state.started_token() && !(c == '#' && state.only_blanks_so_far())))
1569            {
1570                self.consume_char()?;
1571                state.append_char(c);
1572                if state.unquoted() {
1573                    self.cross_state.frame.note_unquoted_char(c);
1574                }
1575            } else if c == '#' {
1576                // Consume the '#'.
1577                self.consume_char()?;
1578
1579                let mut done = false;
1580                while !done {
1581                    done = match self.peek_char()? {
1582                        Some('\n') => true,
1583                        None => true,
1584                        _ => {
1585                            // Consume the peeked char; it's part of the comment.
1586                            self.consume_char()?;
1587                            false
1588                        }
1589                    };
1590                }
1591                // Re-start loop as if the comment never happened.
1592            } else if state.started_token() {
1593                // In all other cases where we have an in-progress token, we delimit here.
1594                result =
1595                    state.delimit_current_token(TokenEndReason::Other, &mut self.cross_state)?;
1596            } else {
1597                // If we got here, then we don't have a token in progress and we're not starting an
1598                // operator. Add the character to a new token.
1599                self.consume_char()?;
1600                state.append_char(c);
1601                self.cross_state.frame.note_unquoted_char(c);
1602            }
1603        }
1604
1605        let result = result.unwrap();
1606
1607        Ok(result)
1608    }
1609
1610    fn remove_here_end_tag(
1611        &mut self,
1612        state: &mut TokenParseState,
1613        result: &mut Option<TokenizeResult>,
1614        ends_with_newline: bool,
1615    ) -> Result<bool, TokenizerError> {
1616        // Bail immediately if we don't even have a *starting* here tag.
1617        if self.cross_state.frame.current_here_tags.is_empty() {
1618            return Ok(false);
1619        }
1620
1621        let next_here_tag = &self.cross_state.frame.current_here_tags[0];
1622
1623        let tag_str: Cow<'_, str> = if next_here_tag.tag_was_escaped_or_quoted {
1624            unquote_str(next_here_tag.tag.as_str()).into()
1625        } else {
1626            next_here_tag.tag.as_str().into()
1627        };
1628
1629        let tag_str = if !ends_with_newline {
1630            tag_str
1631                .strip_suffix('\n')
1632                .unwrap_or_else(|| tag_str.as_ref())
1633        } else {
1634            tag_str.as_ref()
1635        };
1636
1637        // At the end of input, the tag's line may lack its newline (`cat <<EOF⏎body⏎EOF`). An
1638        // empty tag would then match the nothing after the last newline, which isn't a line: as
1639        // in bash, its body only ends at an empty line.
1640        if tag_str.is_empty() {
1641            return Ok(false);
1642        }
1643
1644        if let Some(current_token_without_here_tag) = state.current_token().strip_suffix(tag_str) {
1645            // Make sure that was either the start of the here document, or there
1646            // was a newline between the preceding part
1647            // and the tag.
1648            if current_token_without_here_tag.is_empty()
1649                || current_token_without_here_tag.ends_with('\n')
1650            {
1651                state.replace_with_here_doc(current_token_without_here_tag.to_owned());
1652
1653                // Delimit the end of the here-document body.
1654                *result = state.delimit_current_token(
1655                    TokenEndReason::HereDocumentBodyEnd,
1656                    &mut self.cross_state,
1657                )?;
1658
1659                return Ok(true);
1660            }
1661        }
1662        Ok(false)
1663    }
1664
1665    const fn can_start_extglob(c: char) -> bool {
1666        matches!(c, '@' | '!' | '?' | '+' | '*')
1667    }
1668
1669    const fn can_start_operator(c: char) -> bool {
1670        matches!(c, '&' | '(' | ')' | ';' | '\n' | '|' | '<' | '>')
1671    }
1672
1673    fn is_operator(&self, s: &str) -> bool {
1674        // Handle non-POSIX operators.
1675        if !self.options.sh_mode && matches!(s, "<<<" | "&>" | "&>>" | ";;&" | ";&" | "|&") {
1676            return true;
1677        }
1678
1679        matches!(
1680            s,
1681            "&" | "&&"
1682                | "("
1683                | ")"
1684                | ";"
1685                | ";;"
1686                | "\n"
1687                | "|"
1688                | "||"
1689                | "<"
1690                | ">"
1691                | ">|"
1692                | "<<"
1693                | ">>"
1694                | "<&"
1695                | ">&"
1696                | "<<-"
1697                | "<>"
1698        )
1699    }
1700}
1701
1702impl<R: ?Sized + std::io::BufRead> Iterator for Tokenizer<'_, R> {
1703    type Item = Result<TokenizeResult, TokenizerError>;
1704
1705    fn next(&mut self) -> Option<Self::Item> {
1706        match self.next_token() {
1707            #[expect(clippy::manual_map)]
1708            Ok(result) => match result.token {
1709                Some(_) => Some(Ok(result)),
1710                None => None,
1711            },
1712            Err(e) => Some(Err(e)),
1713        }
1714    }
1715}
1716
1717/// Appends the text of a token from a nested expansion's contents to the expansion's text in
1718/// `state`'s token, except for here-document bodies (and end tags): they come out ahead of the
1719/// rest of the line holding their tags, so they're set aside in `bodies`, to follow it.
1720fn append_expansion_token(
1721    state: &mut TokenParseState,
1722    bodies: &mut String,
1723    result: &TokenizeResult,
1724) {
1725    let text = result.token.as_ref().map_or("", Token::to_str);
1726    match result.reason {
1727        TokenEndReason::HereDocumentBodyStart => bodies.push('\n'),
1728        TokenEndReason::HereDocumentBodyEnd | TokenEndReason::HereDocumentEndTag => {
1729            bodies.push_str(text);
1730        }
1731        _ => state.append_str(text),
1732    }
1733}
1734
1735const fn is_blank(c: char) -> bool {
1736    c == ' ' || c == '\t'
1737}
1738
1739const fn does_char_newly_affect_quoting(state: &TokenParseState, c: char) -> bool {
1740    // If we're currently escaped, then nothing affects quoting.
1741    if state.in_escape {
1742        return false;
1743    }
1744
1745    match state.quote_mode {
1746        // When we're in a double quote or ANSI-C quote, only a subset of escape
1747        // sequences are recognized.
1748        QuoteMode::Double(_) | QuoteMode::AnsiC(_) => {
1749            if c == '\\' {
1750                // TODO(tokenizer): handle backslash in double quote
1751                true
1752            } else {
1753                false
1754            }
1755        }
1756        // When we're in a single quote, nothing affects quoting.
1757        QuoteMode::Single(_) => false,
1758        // When we're not already in a quote, then we can straightforwardly look for a
1759        // quote mark or backslash.
1760        QuoteMode::None => is_quoting_char(c),
1761    }
1762}
1763
1764const fn is_quoting_char(c: char) -> bool {
1765    matches!(c, '\\' | '\'' | '\"')
1766}
1767
1768/// Returns `s` with its quoting removed, as the shell's quote removal does.
1769///
1770/// Removes quote chars that open or close a quote, and backslashes that escape the char
1771/// after them. As in the shell, a backslash is literal in single quotes, and in double
1772/// quotes it escapes only `$`, `` ` ``, `"`, `\`, and newline. Unlike the shell's line
1773/// continuation, an escaped newline is kept. Nothing is expanded, and `$'...'` and
1774/// `$"..."` aren't treated specially.
1775///
1776/// # Arguments
1777///
1778/// * `s` - The string to unquote.
1779pub fn unquote_str(s: &str) -> String {
1780    let mut result = String::with_capacity(s.len());
1781    // The quote (`'` or `"`) the next char is in, if any.
1782    let mut quote = None;
1783    let mut chars = s.chars().peekable();
1784
1785    while let Some(c) = chars.next() {
1786        match (c, quote) {
1787            ('\\', None) => result.extend(chars.next()),
1788            ('\\', Some('"')) => {
1789                if !matches!(chars.peek(), Some('$' | '`' | '"' | '\\' | '\n')) {
1790                    result.push(c);
1791                }
1792                result.extend(chars.next());
1793            }
1794            (_, Some(q)) if c == q => quote = None,
1795            ('\'' | '"', None) => quote = Some(c),
1796            _ => result.push(c),
1797        }
1798    }
1799
1800    result
1801}
1802
1803#[cfg(test)]
1804mod tests {
1805
1806    use super::*;
1807    use anyhow::Result;
1808    use insta::assert_ron_snapshot;
1809    use pretty_assertions::{assert_eq, assert_matches};
1810
1811    #[derive(serde::Serialize, serde::Deserialize)]
1812    struct TokenizerResult<'a> {
1813        input: &'a str,
1814        result: Vec<Token>,
1815    }
1816
1817    fn test_tokenizer(input: &str) -> Result<TokenizerResult<'_>> {
1818        Ok(TokenizerResult {
1819            input,
1820            result: tokenize_str(input)?,
1821        })
1822    }
1823
1824    #[test]
1825    fn tokenize_empty() -> Result<()> {
1826        let tokens = tokenize_str("")?;
1827        assert_eq!(tokens.len(), 0);
1828        Ok(())
1829    }
1830
1831    #[test]
1832    fn tokenize_line_continuation() -> Result<()> {
1833        assert_ron_snapshot!(test_tokenizer(
1834            r"a\
1835bc"
1836        )?);
1837        Ok(())
1838    }
1839
1840    #[test]
1841    fn tokenize_operators() -> Result<()> {
1842        assert_ron_snapshot!(test_tokenizer("a>>b")?);
1843        Ok(())
1844    }
1845
1846    #[test]
1847    fn tokenize_line_continuations() -> Result<()> {
1848        // As in bash, a line continuation is removed wherever the backslash isn't quoted, even
1849        // splitting an operator or following a `$`.
1850        for (input, expected) in [
1851            ("a&\\\n&b", &["a", "&&", "b"][..]),
1852            ("a|\\\n&b", &["a", "|&", "b"]),
1853            ("a&&\\\n", &["a", "&&"]),
1854            // At the end of input, it's as though the input ended right at the operator.
1855            ("a <<\\\n", &["a", "<<"]),
1856            ("a&&\\b", &["a", "&&", "\\b"]),
1857            ("a<\\\n<b\nx\nb\n", &["a", "<<", "b", "x\n", "b", "\n"]),
1858            ("a<<\\b\n$x\nb\n", &["a", "<<", "\\b", "$x\n", "b", "\n"]),
1859            ("$\\\n(a) $\\\n{a}", &["$(a)", "${a}"]),
1860            ("$(\\\n(1))", &["$((1))"]),
1861            (
1862                "$(a\\\nb) ${a\\\nb} $((1+\\\n1))",
1863                &["$(ab)", "${ab}", "$((1+1))"],
1864            ),
1865            ("\"a\\\nb\" `'a\\\nb'`", &["\"ab\"", "`'ab'`"]),
1866            ("@(a\\\nb|\"a\\\nb\")", &["@(ab|\"ab\")"]),
1867            // Kept after an escaping backslash, in single quotes, and in a comment.
1868            ("a\\\\\n", &["a\\\\", "\n"]),
1869            ("'a\\\nb' $'a\\\nb'", &["'a\\\nb'", "$'a\\\nb'"]),
1870            ("`\\\\\n`", &["`\\\\\n`"]),
1871            ("@('a\\\nb')", &["@('a\\\nb')"]),
1872            ("a #b\\\nc", &["a", "\n", "c"]),
1873            // In a here-document's body, they're kept only if its tag is quoted.
1874            (
1875                "<<a\nb\\\nc\\\\\nd\na\n",
1876                &["<<", "a", "bc\\\\\nd\n", "a", "\n"],
1877            ),
1878            ("<<a\nb\\\na\na\n", &["<<", "a", "ba\n", "a", "\n"]),
1879            ("<<'a'\n\\\nb\na\n", &["<<", "'a'", "\\\nb\n", "a", "\n"]),
1880        ] {
1881            let tokens = tokenize_str(input)?;
1882            let token_strs: Vec<_> = tokens.iter().map(Token::to_str).collect();
1883            assert_eq!(token_strs, expected, "tokenizing {input:?}");
1884        }
1885        Ok(())
1886    }
1887
1888    #[test]
1889    fn tokenize_token_after_blanks_and_line_continuation() -> Result<()> {
1890        // The blanks before the line continuation don't count toward where `c` starts.
1891        assert_matches!(
1892            &tokenize_str("a; \\\n  c")?[..],
1893            [_, _, Token::Word(word, span)]
1894                if word == "c" && (span.start.line, span.start.column, span.start.byte_offset) == (2, 3, 7)
1895        );
1896        Ok(())
1897    }
1898
1899    /// Returns the source text each token's span covers, checking that each position's
1900    /// byte offset lands on a char boundary and agrees with its (char-based) line and column.
1901    fn token_source_slices<'a>(input: &'a str, tokens: &[Token]) -> Result<Vec<&'a str>> {
1902        let source = |start: usize, end: usize| {
1903            input
1904                .get(start..end)
1905                .ok_or_else(|| anyhow::anyhow!("{start}..{end} not on char boundaries: {input:?}"))
1906        };
1907        tokens
1908            .iter()
1909            .map(|token| {
1910                let loc = token.location();
1911                for pos in [&loc.start, &loc.end] {
1912                    let before = source(0, pos.byte_offset)?;
1913                    assert_eq!(
1914                        (pos.line, pos.column),
1915                        (
1916                            before.matches('\n').count() + 1,
1917                            before.chars().rev().take_while(|&c| c != '\n').count() + 1
1918                        ),
1919                        "{pos:?} in {input:?}"
1920                    );
1921                }
1922                let text = source(loc.start.byte_offset, loc.end.byte_offset)?;
1923                assert_eq!(loc.len_bytes(), text.len());
1924                Ok(text)
1925            })
1926            .collect()
1927    }
1928
1929    #[test]
1930    #[allow(clippy::literal_string_with_formatting_args)]
1931    fn tokenize_multibyte_token_spans() -> Result<()> {
1932        // Multibyte chars inside words, quotes and expansions: each span slices its token.
1933        for input in [
1934            "echo héllo \"wörld ü\" 'ç' $'ß'\n",
1935            "x=$(echo “é”) y=`echo ü` z=$[ü+1] w=${v:-ü} é\n",
1936            "echo $(echo $(echo ü) “é”) ö\n",
1937            "case ü in é) echo ö;; esac\n",
1938            "f() { echo ✓; }; [[ é == ü* ]] && echo 日本語\n",
1939        ] {
1940            let tokens = tokenize_str(input)?;
1941            let token_strs: Vec<_> = tokens.iter().map(Token::to_str).collect();
1942            assert_eq!(
1943                token_source_slices(input, &tokens)?,
1944                token_strs,
1945                "{input:?}"
1946            );
1947        }
1948
1949        // Where a token's text isn't its source: a here-doc body's span runs through its end
1950        // tag (whose own span is empty), a comment is folded into the newline after it, and a
1951        // line continuation is dropped from its word. The second here-doc's body is read ahead
1952        // of `é tail` and then replayed, so the tokens after it check that replay.
1953        for (input, expected) in [
1954            (
1955                "cat <<EOF\nbödy ü\nEOF\necho é\n",
1956                &[
1957                    "cat",
1958                    "<<",
1959                    "EOF",
1960                    "bödy ü\nEOF\n",
1961                    "",
1962                    "\n",
1963                    "echo",
1964                    "é",
1965                    "\n",
1966                ][..],
1967            ),
1968            (
1969                "echo $(cat <<EOF) é tail\nbödy\nEOF\necho ü\n",
1970                &[
1971                    "echo",
1972                    "$(cat <<EOF)",
1973                    "é",
1974                    "tail",
1975                    "\nbödy\nEOF\n",
1976                    "echo",
1977                    "ü",
1978                    "\n",
1979                ],
1980            ),
1981            (
1982                "# café\necho é\\\nü\n",
1983                &["# café\n", "echo", "é\\\nü", "\n"],
1984            ),
1985        ] {
1986            assert_eq!(
1987                token_source_slices(input, &tokenize_str(input)?)?,
1988                expected,
1989                "{input:?}"
1990            );
1991        }
1992        Ok(())
1993    }
1994
1995    #[test]
1996    fn tokenize_operator_followed_by_backslash() -> Result<()> {
1997        // The `;` ends before the escaped `b`. The `|` ends after the line continuation following
1998        // it (as a word would), and the `c` starts on the next line.
1999        assert_ron_snapshot!(test_tokenizer("a;\\b|\\\n  c")?);
2000        Ok(())
2001    }
2002
2003    #[test]
2004    fn tokenize_comment() -> Result<()> {
2005        assert_ron_snapshot!(test_tokenizer(
2006            r"a #comment
2007"
2008        )?);
2009        Ok(())
2010    }
2011
2012    #[test]
2013    fn tokenize_comment_in_command_substitution() {
2014        // A comment inside `$( )` is a comment however many blanks precede its `#`, even though
2015        // blanks are kept in tokens there, so the apostrophe in its text doesn't open a quote.
2016        // The comment is dropped from the text reconstructed for the substitution, leaving just
2017        // the blanks that preceded it, as written.
2018        for prefix in ["", " ", "  ", "   ", "\t", "\t\t", " \t", "\t "] {
2019            let input = format!("$({prefix}# it's a comment\n)\n");
2020            let tokens = tokenize_str(input.as_str()).unwrap();
2021            let token_strs: Vec<_> = tokens.iter().map(Token::to_str).collect();
2022            assert_eq!(
2023                token_strs,
2024                [format!("$({prefix}\n)").as_str(), "\n"],
2025                "tokenizing {input:?}"
2026            );
2027        }
2028    }
2029
2030    #[test]
2031    fn tokenize_comment_at_eof() -> Result<()> {
2032        assert_ron_snapshot!(test_tokenizer(r"a #comment")?);
2033        Ok(())
2034    }
2035
2036    #[test]
2037    fn tokenize_empty_here_doc() -> Result<()> {
2038        assert_ron_snapshot!(test_tokenizer(
2039            r"cat <<HERE
2040HERE
2041"
2042        )?);
2043        Ok(())
2044    }
2045
2046    #[test]
2047    fn tokenize_here_doc() -> Result<()> {
2048        assert_ron_snapshot!(test_tokenizer(
2049            r"cat <<HERE
2050SOMETHING
2051HERE
2052echo after
2053"
2054        )?);
2055        assert_ron_snapshot!(test_tokenizer(
2056            r"cat <<HERE
2057SOMETHING
2058HERE
2059"
2060        )?);
2061        assert_ron_snapshot!(test_tokenizer(
2062            r"cat <<HERE
2063SOMETHING
2064HERE
2065
2066"
2067        )?);
2068        assert_ron_snapshot!(test_tokenizer(
2069            r"cat <<HERE
2070SOMETHING
2071HERE"
2072        )?);
2073        Ok(())
2074    }
2075
2076    #[test]
2077    fn tokenize_here_doc_with_tab_removal() -> Result<()> {
2078        assert_ron_snapshot!(test_tokenizer(
2079            r"cat <<-HERE
2080	SOMETHING
2081	HERE
2082"
2083        )?);
2084        Ok(())
2085    }
2086
2087    #[test]
2088    fn tokenize_here_doc_with_other_tokens() -> Result<()> {
2089        assert_ron_snapshot!(test_tokenizer(
2090            r"cat <<EOF | wc -l
2091A B C
20921 2 3
2093D E F
2094EOF
2095"
2096        )?);
2097        Ok(())
2098    }
2099
2100    #[test]
2101    fn tokenize_multiple_here_docs() -> Result<()> {
2102        assert_ron_snapshot!(test_tokenizer(
2103            r"cat <<HERE1 <<HERE2
2104SOMETHING
2105HERE1
2106OTHER
2107HERE2
2108echo after
2109"
2110        )?);
2111        Ok(())
2112    }
2113
2114    #[test]
2115    fn tokenize_unterminated_here_doc() {
2116        let result = tokenize_str(
2117            r"cat <<HERE
2118SOMETHING
2119",
2120        );
2121        assert!(result.is_err());
2122    }
2123
2124    #[test]
2125    fn tokenize_here_tag_with_unterminated_expansion() {
2126        // An expansion in a here tag, left open at the end of the input. What's inside it (often
2127        // just blanks here) is part of the tag's word, not a tag of its own, so the input simply
2128        // ends mid-expansion.
2129        for input in [
2130            "<<E$[\t\t",
2131            "<<-E$[\t\t",
2132            "<<E$(\t\t",
2133            "<<E$((\t\t",
2134            "<<E\"$[\t\t",
2135            "x <<$(( )",
2136            "cat <<'' $(",
2137        ] {
2138            assert_matches!(
2139                tokenize_str(input),
2140                Err(TokenizerError::UnterminatedExpansion),
2141                "for {input:?}"
2142            );
2143        }
2144    }
2145
2146    #[test]
2147    fn tokenize_here_doc_with_empty_quoted_tag_at_end_of_input() {
2148        // Tags that are empty once unquoted, with the input ending before any body. An empty tag
2149        // matches anywhere, but only a body can end at it, and none has started.
2150        for input in ["cat <<'' ", "cat <<\"\" "] {
2151            assert_matches!(
2152                tokenize_str(input),
2153                Err(TokenizerError::UnterminatedHereDocuments(..)),
2154                "for {input:?}"
2155            );
2156        }
2157    }
2158
2159    #[test]
2160    fn tokenize_here_tag_containing_expansions() {
2161        for tag in ["$(x)", "E${x}", "$((1 + 2))", "$[1]", "$(echo  a)", "\r"] {
2162            let input = std::format!("cat <<{tag}\nbody\n{tag}\n");
2163            assert_matches!(
2164                tokenize_str(input.as_str()),
2165                Ok(tokens) if tokens.iter().any(|t| matches!(t, Token::Word(w, _) if w == "body\n")),
2166                "for {input:?}"
2167            );
2168        }
2169    }
2170
2171    #[test]
2172    fn tokenize_missing_here_tag_reports_what_was_found() {
2173        for (input, found) in [
2174            ("cat <<\n", "\n"),
2175            ("cat <<;", ";"),
2176            ("cat <<)|$(\n)", ")"),
2177            ("echo $(cat <<  )", ")"),
2178            ("echo $(cat <<)", ")"),
2179            ("echo \"$(cat <<-)\"", ")"),
2180        ] {
2181            assert_matches!(
2182                tokenize_str(input),
2183                Err(TokenizerError::MissingHereTag(actual)) if actual == found,
2184                "for {input:?}"
2185            );
2186        }
2187    }
2188
2189    #[test]
2190    fn tokenize_input_ending_where_here_tag_expected_is_incomplete() {
2191        // More input could still supply the tag, as after a line continuation. (Input ending
2192        // right at the operator, even after a line continuation, is left to the parser.)
2193        for input in ["cat << ", "cat << \\\n"] {
2194            assert_matches!(
2195                tokenize_str(input),
2196                Err(e) if e.is_incomplete(),
2197                "for {input:?}"
2198            );
2199        }
2200    }
2201
2202    #[test]
2203    fn tokenize_here_doc_operator_in_parameter_expansion_is_literal() {
2204        // Bash recognizes no operators directly inside `${...}`.
2205        for word in ["${x:-<<}", "${x:-<< foo}", "${x:-a<<b}", "${x:-<<-EOF}"] {
2206            let input = std::format!("echo {word}\n");
2207            assert_matches!(
2208                tokenize_str(input.as_str()),
2209                Ok(tokens) if tokens.iter().any(|t| matches!(t, Token::Word(w, _) if w == word)),
2210                "for {input:?}"
2211            );
2212        }
2213    }
2214
2215    #[test]
2216    fn tokenize_words_verbatim() {
2217        for word in [
2218            // Extglob-like text inside `${...}` is just text.
2219            "${u:-a@(}",
2220            // `$$` is a parameter; neither a `{` nor a `'` after it starts anything.
2221            "$${u",
2222            "$$'a\\'x",
2223            // Nor does a `'` after an escaped `$`.
2224            "\\$'a\\'x",
2225            // Brackets nest in `$[...]`, as in array subscripts, but not those in quotes or
2226            // nested expansions.
2227            "$[ a[1] + 1 ]",
2228            "$[ a[ a[0] ] ]",
2229            "$[ ${a[1]} + 1 ]",
2230            "$[ $[1] + a[$[0]] ]",
2231            "$[ \"[\" ]",
2232            // A `$'` in double quotes starts nothing, even in an extglob.
2233            "@(\"$'x'\")",
2234            // Blanks inside `${...}` are kept as they are.
2235            "\"${x:-a\tb}\"",
2236        ] {
2237            assert_matches!(
2238                tokenize_str(word),
2239                Ok(tokens) if matches!(tokens.as_slice(), [Token::Word(w, _)] if w == word),
2240                "for {word:?}"
2241            );
2242        }
2243    }
2244
2245    #[test]
2246    fn tokenize_here_doc_left_open_by_command_substitution() -> Result<()> {
2247        // The body is read from the lines after the substitution's, ahead of any other
2248        // here-documents pending by then, and becomes part of the substitution's text.
2249        for (input, expected) in [
2250            (
2251                "x=\"$(cat <<EOF)\"\nbody\nEOF\n",
2252                &["x=\"$(cat <<EOF\nbody\nEOF\n)\"", "\n"][..],
2253            ),
2254            (
2255                "echo \"[$(cat <<EOF | tr a-z A-Z)]\"\nbody\nEOF\n",
2256                &["echo", "\"[$(cat <<EOF | tr a-z A-Z\nbody\nEOF\n)]\"", "\n"],
2257            ),
2258            (
2259                "echo \"[$(cat <<A; cat <<-B)]\"\na\nA\n\tb\n\tB\n",
2260                &["echo", "\"[$(cat <<A; cat <<-B\na\nA\nb\nB\n)]\"", "\n"],
2261            ),
2262            (
2263                "echo \"[$(echo $(cat <<EOF))]\"\nbody\nEOF\n",
2264                &["echo", "\"[$(echo $(cat <<EOF\nbody\nEOF\n))]\"", "\n"],
2265            ),
2266            (
2267                "echo \"[${x:-$(cat <<EOF)}]\"\nbody\nEOF\n",
2268                &["echo", "\"[${x:-$(cat <<EOF\nbody\nEOF\n)}]\"", "\n"],
2269            ),
2270            (
2271                "cat <<A; echo \"[$(cat <<B)]\"\nb\nB\na\nA\n",
2272                &[
2273                    "cat",
2274                    "<<",
2275                    "A",
2276                    "a\n",
2277                    "A",
2278                    ";",
2279                    "echo",
2280                    "\"[$(cat <<B\nb\nB\n)]\"",
2281                    "\n",
2282                ],
2283            ),
2284            (
2285                "echo \"[$(cat <<A)]\" \"[$(cat <<B)]\"\na\nA\nb\nB\n",
2286                &[
2287                    "echo",
2288                    "\"[$(cat <<A\na\nA\n)]\"",
2289                    "\"[$(cat <<B\nb\nB\n)]\"",
2290                    "\n",
2291                ],
2292            ),
2293        ] {
2294            let tokens = tokenize_str(input)?;
2295            let token_strs: Vec<_> = tokens.iter().map(Token::to_str).collect();
2296            assert_eq!(token_strs, expected, "for {input:?}");
2297        }
2298
2299        // The rest of the line keeps its place in the input, and the next line follows the body.
2300        let tokens = tokenize_str("echo \"$(cat <<EOF)\" x\nbody\nEOF\ny\n")?;
2301        let positions: Vec<_> = tokens
2302            .iter()
2303            .map(|t| {
2304                (
2305                    t.to_str(),
2306                    t.location().start.line,
2307                    t.location().start.column,
2308                )
2309            })
2310            .collect();
2311        assert_eq!(
2312            positions,
2313            [
2314                ("echo", 1, 1),
2315                ("\"$(cat <<EOF\nbody\nEOF\n)\"", 1, 6),
2316                ("x", 1, 21),
2317                ("\n", 1, 22),
2318                ("y", 4, 1),
2319                ("\n", 4, 2),
2320            ]
2321        );
2322
2323        Ok(())
2324    }
2325
2326    #[test]
2327    fn tokenize_unterminated_here_doc_names_its_tag() {
2328        assert_matches!(
2329            tokenize_str("cat <<]|$[\n]"),
2330            Err(TokenizerError::UnterminatedHereDocuments(tags, _)) if tags == "`]`"
2331        );
2332    }
2333
2334    #[test]
2335    fn tokenize_deeply_nested_expansions_is_bounded() {
2336        // The input chooses how deeply expansions nest, and consuming them recurses, so the
2337        // nesting must be bounded rather than overflow the stack.
2338        for (open, close) in [("$(", ")"), ("\"$(", ")\""), ("${x:-", "}"), ("$[", "]")] {
2339            let input = std::format!("echo {}x{}", open.repeat(10_000), close.repeat(10_000));
2340            assert_matches!(
2341                tokenize_str(input.as_str()),
2342                Err(TokenizerError::ExpansionNestingTooDeep),
2343                "for {open:?}"
2344            );
2345        }
2346    }
2347
2348    #[test]
2349    fn tokenize_nesting_up_to_limit() {
2350        let nested = |depth: u32| {
2351            let depth = depth as usize;
2352            tokenize_str(&std::format!(
2353                "echo {}x{}",
2354                "$(".repeat(depth),
2355                ")".repeat(depth)
2356            ))
2357        };
2358        assert!(nested(MAX_EXPANSION_NESTING).is_ok());
2359        assert_matches!(
2360            nested(MAX_EXPANSION_NESTING + 1),
2361            Err(TokenizerError::ExpansionNestingTooDeep)
2362        );
2363    }
2364
2365    #[test]
2366    fn tokenize_missing_here_tag() {
2367        let result = tokenize_str(
2368            r"cat <<
2369",
2370        );
2371        assert!(result.is_err());
2372    }
2373
2374    #[test]
2375    fn tokenize_here_doc_in_command_substitution() -> Result<()> {
2376        assert_ron_snapshot!(test_tokenizer(
2377            r"echo $(cat <<HERE
2378TEXT
2379HERE
2380)"
2381        )?);
2382        Ok(())
2383    }
2384
2385    #[test]
2386    fn tokenize_here_doc_in_double_quoted_command_substitution() -> Result<()> {
2387        assert_ron_snapshot!(test_tokenizer(
2388            r#"echo "$(cat <<HERE
2389TEXT
2390HERE
2391)""#
2392        )?);
2393        Ok(())
2394    }
2395
2396    #[test]
2397    fn tokenize_here_doc_in_double_quoted_command_substitution_with_space() -> Result<()> {
2398        assert_ron_snapshot!(test_tokenizer(
2399            r#"echo "$(cat << HERE
2400TEXT
2401HERE
2402)""#
2403        )?);
2404        Ok(())
2405    }
2406
2407    #[test]
2408    fn tokenize_complex_here_docs_in_command_substitution() -> Result<()> {
2409        assert_ron_snapshot!(test_tokenizer(
2410            r"echo $(cat <<HERE1 <<HERE2 | wc -l
2411TEXT
2412HERE1
2413OTHER
2414HERE2
2415)"
2416        )?);
2417        Ok(())
2418    }
2419
2420    #[test]
2421    fn tokenize_simple_backquote() -> Result<()> {
2422        assert_ron_snapshot!(test_tokenizer(r"echo `echo hi`")?);
2423        Ok(())
2424    }
2425
2426    #[test]
2427    fn tokenize_backquote_with_escape() -> Result<()> {
2428        assert_ron_snapshot!(test_tokenizer(r"echo `echo\`hi`")?);
2429        Ok(())
2430    }
2431
2432    #[test]
2433    fn tokenize_unterminated_backquote() {
2434        assert_matches!(
2435            tokenize_str("`"),
2436            Err(TokenizerError::UnterminatedBackquote(_))
2437        );
2438    }
2439
2440    #[test]
2441    fn tokenize_unterminated_command_substitution() {
2442        // $( is consumed before the tokenizer knows whether it's $( or $((,
2443        // so it goes through consume_nested_expansion and yields UnterminatedExpansion.
2444        assert_matches!(
2445            tokenize_str("$("),
2446            Err(TokenizerError::UnterminatedExpansion)
2447        );
2448    }
2449
2450    #[test]
2451    fn command_substitution_body_stops_at_closing_paren() -> Result<()> {
2452        let options = TokenizerOptions::default();
2453        assert_eq!(
2454            command_substitution_body("echo hi) rest", &options)?,
2455            "echo hi"
2456        );
2457        assert_eq!(
2458            command_substitution_body(r#"echo ")" (a)) rest"#, &options)?,
2459            r#"echo ")" (a)"#
2460        );
2461        assert_eq!(
2462            command_substitution_body("cat <<'EOF'\n\"it's ) `\nEOF\n) rest", &options)?,
2463            "cat <<'EOF'\n\"it's ) `\nEOF\n"
2464        );
2465        // A `)` right after the newline that starts a here-doc body belongs to the body.
2466        assert_eq!(
2467            command_substitution_body("cat <<E\n)\nE\n) rest", &options)?,
2468            "cat <<E\n)\nE\n"
2469        );
2470        assert_eq!(
2471            command_substitution_body("cat <<E\n)\nE\necho after) rest", &options)?,
2472            "cat <<E\n)\nE\necho after"
2473        );
2474        // A here-doc left open by the command (or by a substitution nested in it) doesn't
2475        // matter: only the text before the `)` is wanted, and any body would follow it.
2476        assert_eq!(
2477            command_substitution_body("cat <<EOF) rest\n", &options)?,
2478            "cat <<EOF"
2479        );
2480        assert_eq!(
2481            command_substitution_body("echo $(cat <<EOF)) rest\n", &options)?,
2482            "echo $(cat <<EOF)"
2483        );
2484        // A quoted `)` in an extglob closes neither the pattern nor the command.
2485        assert_eq!(
2486            command_substitution_body(r#"printf "%s" @(")")) rest"#, &options)?,
2487            r#"printf "%s" @(")")"#
2488        );
2489        // Multi-byte characters inside and after the command.
2490        assert_eq!(
2491            command_substitution_body("echo “é”) ü", &options)?,
2492            "echo “é”"
2493        );
2494        Ok(())
2495    }
2496
2497    #[test]
2498    fn command_substitution_body_unterminated() {
2499        let options = TokenizerOptions::default();
2500        assert_matches!(
2501            command_substitution_body("echo hi", &options),
2502            Err(TokenizerError::UnterminatedExpansion)
2503        );
2504        assert_matches!(
2505            command_substitution_body("echo 'hi)", &options),
2506            Err(TokenizerError::UnterminatedSingleQuote(_))
2507        );
2508    }
2509
2510    #[test]
2511    fn tokenize_unterminated_arithmetic_expansion() {
2512        assert_matches!(
2513            tokenize_str("$(("),
2514            Err(TokenizerError::UnterminatedExpansion)
2515        );
2516    }
2517
2518    #[test]
2519    fn tokenize_unterminated_legacy_arithmetic_expansion() {
2520        assert_matches!(
2521            tokenize_str("$["),
2522            Err(TokenizerError::UnterminatedExpansion)
2523        );
2524    }
2525
2526    #[test]
2527    fn tokenize_command_substitution() -> Result<()> {
2528        assert_ron_snapshot!(test_tokenizer("a$(echo hi)b c")?);
2529        Ok(())
2530    }
2531
2532    #[test]
2533    fn tokenize_command_substitution_with_subshell() -> Result<()> {
2534        assert_ron_snapshot!(test_tokenizer("$( (:) )")?);
2535        Ok(())
2536    }
2537
2538    #[test]
2539    fn tokenize_command_substitution_containing_extglob() -> Result<()> {
2540        assert_ron_snapshot!(test_tokenizer("echo $(echo !(x))")?);
2541        Ok(())
2542    }
2543
2544    #[test]
2545    fn tokenize_extglob_with_quotes_and_escapes() -> Result<()> {
2546        for (input, expected) in [
2547            // Quoted parens don't close the pattern.
2548            (r#"@(")") y"#, [r#"@(")")"#, "y"]),
2549            (r"@(a|')'|b)x y", [r"@(a|')'|b)x", "y"]),
2550            (r#"@("(") y"#, [r#"@("(")"#, "y"]),
2551            // Escaped quote inside double quotes doesn't end the quoting.
2552            (r#"@("\")") y"#, [r#"@("\")")"#, "y"]),
2553            // Backslash is literal inside single quotes.
2554            (r"@('\')x y", [r"@('\')x", "y"]),
2555            // Escaped quote outside quotes doesn't start quoting.
2556            (r#"@(\") y"#, [r#"@(\")"#, "y"]),
2557            (r"@(\)) y", [r"@(\))", "y"]),
2558            // Backslash escapes a quote inside ANSI-C quotes, but not inside `\$'...'`.
2559            (r"@($'\'')x y", [r"@($'\'')x", "y"]),
2560            (r"@($'a\')'|b) y", [r"@($'a\')'|b)", "y"]),
2561            (r"@(\$'a\')x y", [r"@(\$'a\')x", "y"]),
2562            // `$$` is a parameter, so a quote after it is ANSI-C only if a third `$` follows.
2563            (r"@($$'a\')x y", [r"@($$'a\')x", "y"]),
2564            (r"@($$$'\'')x y", [r"@($$$'\'')x", "y"]),
2565            // Backquotes are a region of their own: quotes inside them don't nest.
2566            (r"@(}`'`)x y", [r"@(}`'`)x", "y"]),
2567            (r#"@(`echo \\"`)x y"#, [r#"@(`echo \\"`)x"#, "y"]),
2568            (r"@(`$'\'`)x y", [r"@(`$'\'`)x", "y"]),
2569            (r#"@(`echo ")"`)x y"#, [r#"@(`echo ")"`)x"#, "y"]),
2570            // Inside double quotes, `$(...)` and backquotes are nested constructs.
2571            (r#"@("$(echo ")")")x y"#, [r#"@("$(echo ")")")x"#, "y"]),
2572            (r#"@("`echo "\)"`")x y"#, [r#"@("`echo "\)"`")x"#, "y"]),
2573            (r#"@("${u:-"}"}")x y"#, [r#"@("${u:-"}"}")x"#, "y"]),
2574            (r#"@($")")x y"#, [r#"@($")")x"#, "y"]),
2575            // Nesting still counts unquoted parens; each quote kind hides the other.
2576            (r#"+(a|@(b|")")|'"') y"#, [r#"+(a|@(b|")")|'"')"#, "y"]),
2577        ] {
2578            let tokens = tokenize_str(input)?;
2579            let token_strs: Vec<_> = tokens.iter().map(Token::to_str).collect();
2580            assert_eq!(token_strs, expected, "input: {input}");
2581        }
2582        Ok(())
2583    }
2584
2585    #[test]
2586    fn tokenize_unterminated_construct_in_extglob() {
2587        // Each of these leaves a quote, backquote, or `$(` inside the extglob open.
2588        for input in [r#"@("$(\$"\))x"#, r#"@($"$(\)")x"#, r"@(`)x", r#"@("`)")x"#] {
2589            assert!(tokenize_str(input).is_err(), "input: {input}");
2590        }
2591    }
2592
2593    #[test]
2594    fn tokenize_unterminated_extglob() {
2595        for input in [r"@(a", r#"@(")""#, r"@(')'", r"@(\)"] {
2596            assert_matches!(
2597                tokenize_str(input),
2598                Err(TokenizerError::UnterminatedExtendedGlob(_)),
2599                "input: {input}"
2600            );
2601        }
2602    }
2603
2604    #[test]
2605    fn tokenize_arithmetic_expression() -> Result<()> {
2606        assert_ron_snapshot!(test_tokenizer("a$((1+2))b c")?);
2607        Ok(())
2608    }
2609
2610    #[test]
2611    fn tokenize_arithmetic_expression_with_space() -> Result<()> {
2612        // N.B. The spacing comes out a bit odd, but it gets processed okay
2613        // by later stages.
2614        assert_ron_snapshot!(test_tokenizer("$(( 1 ))")?);
2615        Ok(())
2616    }
2617    #[test]
2618    fn tokenize_arithmetic_expression_with_parens() -> Result<()> {
2619        assert_ron_snapshot!(test_tokenizer("$(( (0) ))")?);
2620        Ok(())
2621    }
2622
2623    #[test]
2624    fn tokenize_special_parameters() -> Result<()> {
2625        assert_ron_snapshot!(test_tokenizer("$$")?);
2626        assert_ron_snapshot!(test_tokenizer("$@")?);
2627        assert_ron_snapshot!(test_tokenizer("$!")?);
2628        assert_ron_snapshot!(test_tokenizer("$?")?);
2629        assert_ron_snapshot!(test_tokenizer("$*")?);
2630        Ok(())
2631    }
2632
2633    #[test]
2634    fn tokenize_unbraced_parameter_expansion() -> Result<()> {
2635        assert_ron_snapshot!(test_tokenizer("$x")?);
2636        assert_ron_snapshot!(test_tokenizer("a$x")?);
2637        Ok(())
2638    }
2639
2640    #[test]
2641    fn tokenize_unterminated_parameter_expansion() {
2642        assert_matches!(
2643            tokenize_str("${x"),
2644            Err(TokenizerError::UnterminatedVariable)
2645        );
2646    }
2647
2648    #[test]
2649    fn tokenize_braced_parameter_expansion() -> Result<()> {
2650        assert_ron_snapshot!(test_tokenizer("${x}")?);
2651        assert_ron_snapshot!(test_tokenizer("a${x}b")?);
2652        Ok(())
2653    }
2654
2655    #[test]
2656    fn tokenize_braced_parameter_expansion_with_escaping() -> Result<()> {
2657        assert_ron_snapshot!(test_tokenizer(r"a${x\}}b")?);
2658        Ok(())
2659    }
2660
2661    #[test]
2662    fn tokenize_whitespace() -> Result<()> {
2663        assert_ron_snapshot!(test_tokenizer("1 2 3")?);
2664        Ok(())
2665    }
2666
2667    #[test]
2668    fn tokenize_escaped_whitespace() -> Result<()> {
2669        assert_ron_snapshot!(test_tokenizer(r"1\ 2 3")?);
2670        Ok(())
2671    }
2672
2673    #[test]
2674    fn tokenize_single_quote() -> Result<()> {
2675        assert_ron_snapshot!(test_tokenizer(r"x'a b'y")?);
2676        Ok(())
2677    }
2678
2679    #[test]
2680    fn tokenize_double_quote() -> Result<()> {
2681        assert_ron_snapshot!(test_tokenizer(r#"x"a b"y"#)?);
2682        Ok(())
2683    }
2684
2685    #[test]
2686    fn tokenize_double_quoted_command_substitution() -> Result<()> {
2687        assert_ron_snapshot!(test_tokenizer(r#"x"$(echo hi)"y"#)?);
2688        Ok(())
2689    }
2690
2691    #[test]
2692    fn tokenize_double_quoted_arithmetic_expression() -> Result<()> {
2693        assert_ron_snapshot!(test_tokenizer(r#"x"$((1+2))"y"#)?);
2694        Ok(())
2695    }
2696
2697    #[test]
2698    fn test_quote_removal() {
2699        assert_eq!(unquote_str(r#""hello""#), "hello");
2700        assert_eq!(unquote_str(r"'hello'"), "hello");
2701        assert_eq!(unquote_str(r#""hel\"lo""#), r#"hel"lo"#);
2702        assert_eq!(unquote_str(r"hel\'lo"), r"hel'lo");
2703        assert_eq!(unquote_str(r"a\ b\\c"), r"a b\c");
2704
2705        // Quotes open and close anywhere, and each kind is literal in the other.
2706        assert_eq!(unquote_str(r#"a'b c'd"e f"g"#), "ab cde fg");
2707        assert_eq!(unquote_str(r#"'a"b'"c'd""#), r#"a"bc'd"#);
2708
2709        // A backslash is literal in single quotes, so it can't escape the closing quote.
2710        assert_eq!(unquote_str(r"'a\b'"), r"a\b");
2711        assert_eq!(unquote_str(r"'a\'b"), r"a\b");
2712
2713        // In double quotes, a backslash escapes only chars that are special there.
2714        assert_eq!(unquote_str(r#""a\$b\`c\"d\\e""#), r#"a$b`c"d\e"#);
2715        assert_eq!(unquote_str(r#""a\b\'c""#), r"a\b\'c");
2716        assert_eq!(unquote_str("\"a\\\nb\""), "a\nb");
2717        assert_eq!(unquote_str("a\\\nb"), "a\nb");
2718
2719        // A trailing backslash is removed, unless it's literal (in quotes).
2720        assert_eq!(unquote_str(r"a\"), "a");
2721        assert_eq!(unquote_str(r#""a\"#), r"a\");
2722        assert_eq!(unquote_str(r"'a\"), r"a\");
2723
2724        // An unclosed quote is removed; nothing is expanded.
2725        assert_eq!(unquote_str(r#""a b"#), "a b");
2726        assert_eq!(unquote_str(r#"$HOME'~'"$x""#), "$HOME~$x");
2727        assert_eq!(unquote_str(""), "");
2728    }
2729}