use super::WordPart;
use std::cell::{Cell, RefCell};
use winnow::ModalResult;
use winnow::combinator::{alt, preceded};
use winnow::error::{ContextError, ErrMode};
use winnow::prelude::*;
use winnow::token::{any, take_while};
thread_local! {
static INPUT: RefCell<(usize, String)> = const { RefCell::new((0, String::new())) };
static REFUSED: Cell<bool> = const { Cell::new(false) };
}
pub(super) fn begin(input: &str) {
INPUT.with(|i| *i.borrow_mut() = (input.as_ptr() as usize, input.to_string()));
REFUSED.with(|r| r.set(false));
}
pub(super) fn all_plain() -> bool {
!REFUSED.with(Cell::get)
}
pub(super) fn refuse() {
REFUSED.with(|r| r.set(true));
}
pub(crate) fn backtick_command(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
let mut chars = raw.chars().peekable();
while let Some(c) = chars.next() {
match chars.peek() {
Some(&next @ ('\\' | '$' | '`')) if c == '\\' => {
out.push(next);
chars.next();
}
Some('\n') if c == '\\' => {
chars.next();
}
_ => out.push(c),
}
}
out
}
pub(super) fn backtick(raw: String) -> WordPart {
if raw.contains("\\\"") {
refuse();
}
WordPart::Backtick(raw)
}
fn judge(at: &str) {
let plain = INPUT.with(|i| {
let (base, text) = &*i.borrow();
(at.as_ptr() as usize)
.checked_sub(*base)
.filter(|&o| o < text.len())
.is_some_and(|o| plain_at(text.as_bytes(), o))
});
if !plain {
refuse();
}
}
fn joins_word_here(at: &str) -> bool {
INPUT.with(|i| {
let (base, text) = &*i.borrow();
(at.as_ptr() as usize)
.checked_sub(*base)
.filter(|&o| o < text.len())
.is_some_and(|o| plain_at(text.as_bytes(), o) && !touches_blank(text.as_bytes(), o))
})
}
pub(super) fn plain_at(b: &[u8], at: usize) -> bool {
let (start, end, before, after) = span_around(b, at);
let blank = |c: Option<u8>| c.is_none_or(|c| matches!(c, b' ' | b'\t' | b'\n'));
let plain = |c: Option<u8>| c.is_some_and(|c| c.is_ascii_alphanumeric() || b"_./-,:".contains(&c));
!splits_syntax_token(b, start, end) && (blank(before) || blank(after) || (plain(before) && plain(after)))
}
fn touches_blank(b: &[u8], at: usize) -> bool {
let (_, _, before, after) = span_around(b, at);
let blank = |c: Option<u8>| c.is_none_or(|c| matches!(c, b' ' | b'\t' | b'\n'));
blank(before) || blank(after)
}
fn span_around(b: &[u8], at: usize) -> (usize, usize, Option<u8>, Option<u8>) {
let mut start = at;
while start >= 2 && b[start - 2] == b'\\' && b[start - 1] == b'\n' {
start -= 2;
}
let mut end = at + 2;
while b.get(end) == Some(&b'\\') && b.get(end + 1) == Some(&b'\n') {
end += 2;
}
(start, end, start.checked_sub(1).map(|j| b[j]), b.get(end).copied())
}
fn splits_syntax_token(b: &[u8], start: usize, end: usize) -> bool {
let is_plain = |c: u8| c.is_ascii_alphanumeric() || b"_./-,:".contains(&c);
let mut left = start;
while left > 0 {
if is_plain(b[left - 1]) {
left -= 1;
} else if left >= 2 && b[left - 2] == b'\\' && b[left - 1] == b'\n' {
left -= 2;
} else {
break;
}
}
let mut right = end;
while right < b.len() {
if is_plain(b[right]) {
right += 1;
} else if b.get(right) == Some(&b'\\') && b.get(right + 1) == Some(&b'\n') {
right += 2;
} else {
break;
}
}
if left == start && right == end {
return false;
}
if left > 0 && matches!(b[left - 1], b'$' | b'{' | b'>' | b'<' | b'&') {
return true;
}
if left < start && b.get(right).is_some_and(|c| matches!(c, b'=' | b'(' | b'>' | b'<')) {
return true;
}
let mut word = Vec::with_capacity(right - left);
let mut i = left;
while i < right {
if b[i] == b'\\' && b.get(i + 1) == Some(&b'\n') {
i += 2;
} else {
word.push(b[i]);
i += 1;
}
}
matches!(
word.as_slice(),
b"if"
| b"then"
| b"elif"
| b"else"
| b"fi"
| b"for"
| b"in"
| b"do"
| b"done"
| b"while"
| b"until"
| b"case"
| b"esac"
| b"function"
| b"select"
| b"time"
| b"coproc"
)
}
pub(super) fn heredoc_line(s: &str, start: usize, joins: bool) -> (usize, String) {
let mut text = String::new();
let mut at = start;
loop {
let end = s[at..].find('\n').map_or(s.len(), |rel| at + rel);
let line = &s[at..end];
let slashes = line.len() - line.trim_end_matches('\\').len();
if !(joins && slashes % 2 == 1 && end < s.len()) {
text.push_str(line);
return (end, text);
}
text.push_str(&line[..line.len() - 1]);
at = end + 1;
}
}
pub(super) fn skip_continuation(input: &mut &str) -> bool {
if !input.starts_with("\\\n") || joins_word_here(input) {
return false;
}
judge(input);
*input = &input[2..];
true
}
pub(super) fn join_continuation(input: &mut &str) -> bool {
let found = judged(input);
if found {
*input = &input[2..];
}
found
}
pub(super) fn fd_target(input: &mut &str) -> ModalResult<String> {
let dst: &str = alt(("-", take_while(1.., |c: char| c.is_ascii_digit()))).parse_next(input)?;
if !input.is_empty() && !matches!(input.as_bytes()[0], b' ' | b'\t' | b'\n' | b';' | b'&' | b'|' | b'(' | b')' | b'<' | b'>') {
return Err(ErrMode::Backtrack(ContextError::new()));
}
Ok(dst.to_string())
}
fn judged(input: &str) -> bool {
let found = input.starts_with("\\\n");
if found {
judge(input);
}
found
}
pub(super) fn only_continuations(parts: &[WordPart]) -> bool {
parts.iter().all(|p| matches!(p, WordPart::Lit(s) if s.is_empty()))
}
pub(super) fn escaped(input: &mut &str) -> ModalResult<WordPart> {
judged(input);
preceded('\\', any)
.map(|c: char| if c == '\n' { WordPart::Lit(String::new()) } else { WordPart::Escape(c) })
.parse_next(input)
}
pub(super) fn dq_escape(input: &mut &str) -> ModalResult<WordPart> {
judged(input);
preceded('\\', any)
.map(|c: char| match c {
'"' | '\\' | '$' | '`' => WordPart::Escape(c),
'\n' => WordPart::Lit(String::new()),
_ => WordPart::Lit(format!("\\{c}")),
})
.parse_next(input)
}
#[cfg(test)]
#[path = "escape_tests.rs"]
mod tests;