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 EndOfInput,
14 UnescapedNewLine,
16 ExpansionClosingChar,
19 NonNewLineBlank,
21 HereDocumentBodyStart,
23 HereDocumentBodyEnd,
25 HereDocumentEndTag,
27 OperatorStart,
29 OperatorEnd,
31 Other,
33}
34
35pub type TokenLocation = SourceSpan;
37
38#[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 Operator(String, SourceSpan),
48 Word(String, SourceSpan),
50}
51
52impl Token {
53 pub fn to_str(&self) -> &str {
55 match self {
56 Self::Operator(s, _) => s,
57 Self::Word(s, _) => s,
58 }
59 }
60
61 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#[derive(Clone, Debug)]
80pub(crate) struct TokenizeResult {
81 pub reason: TokenEndReason,
83 pub token: Option<Token>,
85}
86
87#[derive(thiserror::Error, Debug)]
89#[non_exhaustive]
90pub enum TokenizerError {
91 #[error("unterminated escape sequence")]
93 UnterminatedEscapeSequence,
94
95 #[error("unterminated single quote at {0}")]
97 UnterminatedSingleQuote(SourcePosition),
98
99 #[error("unterminated ANSI C quote at {0}")]
101 UnterminatedAnsiCQuote(SourcePosition),
102
103 #[error("unterminated double quote at {0}")]
105 UnterminatedDoubleQuote(SourcePosition),
106
107 #[error("unterminated backquote near {0}")]
109 UnterminatedBackquote(SourcePosition),
110
111 #[error("unterminated extglob near {0}")]
114 UnterminatedExtendedGlob(SourcePosition),
115
116 #[error("unterminated variable expression")]
118 UnterminatedVariable,
119
120 #[error("unterminated command substitution")]
122 UnterminatedCommandSubstitution,
123
124 #[error("unterminated expansion")]
127 UnterminatedExpansion,
128
129 #[error("failed to decode UTF-8 characters")]
131 FailedDecoding,
132
133 #[error("missing here tag for here document body")]
136 MissingHereTagForDocumentBody,
137
138 #[error("missing here-document tag before {0:?}")]
141 MissingHereTag(String),
142
143 #[error("missing here-document tag at end of input")]
149 MissingHereTagAtEndOfInput,
150
151 #[error("unterminated here document; tag(s) {0} declared at {1}")]
153 UnterminatedHereDocuments(String, String),
154
155 #[error("expansions nested too deeply (limit: {})", MAX_EXPANSION_NESTING)]
158 ExpansionNestingTooDeep,
159
160 #[error("failed to read input")]
162 ReadError(#[from] std::io::Error),
163}
164
165impl TokenizerError {
166 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#[derive(Debug)]
188pub(crate) struct Tokens<'a> {
189 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 #[default]
205 None,
206 NextTokenIsHereTag { remove_tabs: bool },
209 CurrentTokenIsHereTag {
212 remove_tabs: bool,
213 operator_token_result: TokenizeResult,
214 },
215 NextLineIsHereDoc,
218 InHereDocs,
221}
222
223impl HereState {
224 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: SourcePosition,
247 queued_tokens: Vec<TokenizeResult>,
249 frame: ExpansionFrame,
251}
252
253#[derive(Clone, Copy, Debug, PartialEq, Eq)]
256enum NestedExpansion {
257 CommandSubstitution,
259 ArithmeticExpansion,
261 LegacyArithmeticExpansion,
263 ParameterExpansion,
265}
266
267impl NestedExpansion {
268 const fn closing_char(self) -> char {
270 match self {
271 Self::CommandSubstitution | Self::ArithmeticExpansion => ')',
272 Self::LegacyArithmeticExpansion => ']',
273 Self::ParameterExpansion => '}',
274 }
275 }
276
277 const fn is_arithmetic(self) -> bool {
279 matches!(
280 self,
281 Self::ArithmeticExpansion | Self::LegacyArithmeticExpansion
282 )
283 }
284
285 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 const fn closers_after_opening(self) -> usize {
298 match self {
299 Self::ArithmeticExpansion => 2,
300 _ => 1,
301 }
302 }
303
304 const fn unterminated_error(self) -> TokenizerError {
306 match self {
307 Self::ParameterExpansion => TokenizerError::UnterminatedVariable,
308 _ => TokenizerError::UnterminatedExpansion,
309 }
310 }
311}
312
313#[derive(Clone, Debug, Default)]
320struct ExpansionFrame {
321 expansion: Option<NestedExpansion>,
323 depth: u32,
325 here_state: HereState,
327 current_here_tags: Vec<HereTag>,
329 closers_needed: usize,
333 arithmetic_command_parens: usize,
338}
339
340impl ExpansionFrame {
341 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 debug_assert!(self.closers_needed > 1, "read the expansion's closing char");
354 self.closers_needed -= 1;
355 }
356 }
357}
358
359#[derive(Clone, Debug, Hash, Eq, PartialEq)]
361pub struct TokenizerOptions {
362 pub enable_extended_globbing: bool,
364 pub posix_mode: bool,
366 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
380pub(crate) const MAX_EXPANSION_NESTING: u32 = 32;
389
390pub(crate) struct Tokenizer<'a, R: ?Sized + std::io::BufRead> {
392 char_reader: CharReader<utf8_chars::Chars<'a, R>>,
393 unread: Option<UnreadChars>,
396 read_bodies_left_pending: bool,
400 cross_state: CrossTokenParseState,
401 options: TokenizerOptions,
402}
403
404struct UnreadChars {
406 chars: Vec<char>,
408 resume_at: SourcePosition,
411}
412
413#[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 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 !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 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 if self.token_is_operator {
538 return Err(TokenizerError::MissingHereTag(
539 self.current_token().to_owned(),
540 ));
541 }
542
543 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 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 let completed_here_tag = cross_token_state.frame.current_here_tags.remove(0);
604
605 cross_token_state
607 .queued_tokens
608 .extend(completed_here_tag.tokens);
609
610 cross_token_state.queued_tokens.push(TokenizeResult {
612 reason: TokenEndReason::HereDocumentBodyStart,
613 token: None,
614 });
615
616 cross_token_state.queued_tokens.push(TokenizeResult {
618 reason,
619 token: Some(self.pop(&cross_token_state.cursor)),
620 });
621
622 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 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
661pub fn tokenize_str(input: &str) -> Result<Vec<Token>, TokenizerError> {
667 tokenize_str_with_options(input, &TokenizerOptions::default())
668}
669
670pub 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
696pub 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
726pub(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
744pub(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 let mut state = TokenParseState::new(&tokenizer.cross_state.cursor);
766 tokenizer.consume_nested_expansion(&mut state, expansion)?;
767
768 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 fn peek_second_char(&mut self) -> Result<Option<char>, TokenizerError> {
848 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 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 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 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 frame
902 .current_here_tags
903 .first()
904 .is_some_and(|tag| tag.tag_was_escaped_or_quoted)
905 }
906
907 fn consume_nested_expansion(
910 &mut self,
911 state: &mut TokenParseState,
912 expansion: NestedExpansion,
913 ) -> Result<(), TokenizerError> {
914 let depth = self.cross_state.frame.depth + 1;
917 if depth > MAX_EXPANSION_NESTING {
918 return Err(TokenizerError::ExpansionNestingTooDeep);
919 }
920
921 let frame = ExpansionFrame {
926 expansion: Some(expansion),
927 depth,
928 closers_needed: expansion.closers_after_opening(),
929 ..ExpansionFrame::default()
930 };
931
932 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 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 TokenEndReason::UnescapedNewLine => state.append_str(&std::mem::take(&mut bodies)),
958 TokenEndReason::ExpansionClosingChar => {
959 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 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 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 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 #[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 self.consume_char()?;
1046 self.skip_line_continuations()?;
1047
1048 let char_after_dollar_sign = self.peek_char()?;
1050 match char_after_dollar_sign {
1051 Some('(') => {
1052 state.append_char('$');
1054
1055 state.append_char(self.next_char()?.unwrap());
1057
1058 self.skip_line_continuations()?;
1061 let expansion = if matches!(self.peek_char()?, Some('(')) {
1062 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 state.append_char('$');
1075
1076 state.append_char(self.next_char()?.unwrap());
1078
1079 self.consume_nested_expansion(
1080 state,
1081 NestedExpansion::LegacyArithmeticExpansion,
1082 )?;
1083 }
1084
1085 Some('{') => {
1086 state.append_char('$');
1088
1089 state.append_char(self.next_char()?.unwrap());
1091
1092 self.consume_nested_expansion(state, NestedExpansion::ParameterExpansion)?;
1093 }
1094 Some('$') => {
1096 self.consume_char()?;
1097 state.append_str("$$");
1098 }
1099
1100 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 state.append_char('$');
1111 }
1112 }
1113 } else {
1114 let backquote_pos = self.cross_state.cursor.clone();
1117 self.consume_char()?;
1118
1119 state.append_char(c);
1121
1122 let mut escaping_enabled = false;
1124 let mut done = false;
1125 while !done {
1126 if !escaping_enabled {
1129 self.skip_line_continuations()?;
1130 }
1131
1132 let next_char_in_backquote = self.next_char()?;
1134 if let Some(cib) = next_char_in_backquote {
1135 state.append_char(cib);
1137
1138 if !escaping_enabled && cib == '\\' {
1140 escaping_enabled = true;
1141 } else {
1142 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 #[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 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 if !self.cross_state.queued_tokens.is_empty() {
1184 return Ok(self.cross_state.queued_tokens.remove(0));
1185 }
1186
1187 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 if next.is_none() {
1206 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 if !matches!(self.cross_state.frame.here_state, HereState::None) {
1226 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 if matches!(self.cross_state.frame.here_state, HereState::InHereDocs)
1242 && self.remove_here_end_tag(&mut state, &mut result, false)?
1243 {
1244 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 } else if matches!(self.cross_state.frame.here_state, HereState::InHereDocs) {
1276 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 self.consume_char()?;
1287 } else {
1288 self.consume_char()?;
1289 state.append_char(c);
1290
1291 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 if let Some(escaped) = self.next_char()? {
1306 state.append_char(escaped);
1307 }
1308 }
1309 }
1310 } 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 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 if in_arithmetic_expansion || in_parameter_expansion {
1353 } else if self.cross_state.frame.arithmetic_command_parens > 0 {
1356 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 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 } 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 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 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 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 let in_double_quotes = matches!(state.quote_mode, QuoteMode::Double(_));
1434 self.consume_dollar_or_backquote(&mut state, c, in_double_quotes)?;
1435 }
1436 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 self.consume_char()?;
1452 state.append_char(c);
1453
1454 let mut paren_depth = 1;
1455 let mut quote: Option<(char, bool)> = None;
1458 let mut after_dollar = false;
1459
1460 while paren_depth > 0 {
1465 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 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 self.consume_char()?;
1497 state.append_char(extglob_char);
1498
1499 match extglob_char {
1500 '\\' 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 '$' => after_dollar = !was_after_dollar,
1513 '(' => paren_depth += 1,
1514 ')' => paren_depth -= 1,
1515 _ => (),
1516 }
1517 }
1518 } 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 } 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 if include_space {
1545 continue;
1546 }
1547 } else if include_space {
1548 state.append_char(c);
1549 } else {
1550 state.start_position.column += 1;
1552 state.start_position.byte_offset += c.len_utf8();
1553 }
1554
1555 self.consume_char()?;
1556 }
1557 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 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 self.consume_char()?;
1587 false
1588 }
1589 };
1590 }
1591 } else if state.started_token() {
1593 result =
1595 state.delimit_current_token(TokenEndReason::Other, &mut self.cross_state)?;
1596 } else {
1597 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 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 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 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 *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 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
1717fn 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 state.in_escape {
1742 return false;
1743 }
1744
1745 match state.quote_mode {
1746 QuoteMode::Double(_) | QuoteMode::AnsiC(_) => {
1749 if c == '\\' {
1750 true
1752 } else {
1753 false
1754 }
1755 }
1756 QuoteMode::Single(_) => false,
1758 QuoteMode::None => is_quoting_char(c),
1761 }
1762}
1763
1764const fn is_quoting_char(c: char) -> bool {
1765 matches!(c, '\\' | '\'' | '\"')
1766}
1767
1768pub fn unquote_str(s: &str) -> String {
1780 let mut result = String::with_capacity(s.len());
1781 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 for (input, expected) in [
1851 ("a&\\\n&b", &["a", "&&", "b"][..]),
1852 ("a|\\\n&b", &["a", "|&", "b"]),
1853 ("a&&\\\n", &["a", "&&"]),
1854 ("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 ("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 (
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 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 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 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 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 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 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 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 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 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 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 "${u:-a@(}",
2220 "$${u",
2222 "$$'a\\'x",
2223 "\\$'a\\'x",
2225 "$[ a[1] + 1 ]",
2228 "$[ a[ a[0] ] ]",
2229 "$[ ${a[1]} + 1 ]",
2230 "$[ $[1] + a[$[0]] ]",
2231 "$[ \"[\" ]",
2232 "@(\"$'x'\")",
2234 "\"${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 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 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 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 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 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 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 assert_eq!(
2486 command_substitution_body(r#"printf "%s" @(")")) rest"#, &options)?,
2487 r#"printf "%s" @(")")"#
2488 );
2489 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 (r#"@(")") y"#, [r#"@(")")"#, "y"]),
2549 (r"@(a|')'|b)x y", [r"@(a|')'|b)x", "y"]),
2550 (r#"@("(") y"#, [r#"@("(")"#, "y"]),
2551 (r#"@("\")") y"#, [r#"@("\")")"#, "y"]),
2553 (r"@('\')x y", [r"@('\')x", "y"]),
2555 (r#"@(\") y"#, [r#"@(\")"#, "y"]),
2557 (r"@(\)) y", [r"@(\))", "y"]),
2558 (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 (r"@($$'a\')x y", [r"@($$'a\')x", "y"]),
2564 (r"@($$$'\'')x y", [r"@($$$'\'')x", "y"]),
2565 (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 (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 (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 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 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 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 assert_eq!(unquote_str(r"'a\b'"), r"a\b");
2711 assert_eq!(unquote_str(r"'a\'b"), r"a\b");
2712
2713 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 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 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}