pub fn shell_tokenize(input: &str) -> Vec<String> {
let mut tokens = Vec::new();
let mut current = String::new();
let mut chars = input.chars().peekable();
let mut in_single = false;
let mut in_double = false;
let mut parameter_depth: u32 = 0;
while let Some(c) = chars.next() {
match c {
'\'' if !in_double => in_single = !in_single,
'"' if !in_single => in_double = !in_double,
'\\' if !in_single => {
let escapes_next =
!in_double || matches!(chars.peek(), Some('$' | '`' | '"' | '\\' | '\n'));
if escapes_next {
if let Some(next) = chars.next() {
current.push(next);
}
} else {
current.push('\\');
}
}
'$' if !in_single && chars.peek() == Some(&'{') => {
parameter_depth += 1;
current.push(c);
}
'}' if !in_single && parameter_depth > 0 => {
parameter_depth -= 1;
current.push(c);
}
c if c.is_whitespace() && !in_single && !in_double && parameter_depth == 0 => {
if !current.is_empty() {
tokens.push(std::mem::take(&mut current));
}
}
_ => current.push(c),
}
}
if !current.is_empty() {
tokens.push(current);
}
tokens
}
pub(super) fn quote_aware_token_end(input: &str) -> usize {
let bytes = input.as_bytes();
let len = bytes.len();
let mut i = 0;
let mut in_single = false;
let mut in_double = false;
let mut paren_depth: u32 = 0;
let mut parameter_depth: u32 = 0;
while i < len {
let ch = bytes[i];
match ch {
b'\'' if !in_double => {
in_single = !in_single;
i += 1;
}
b'"' if !in_single => {
in_double = !in_double;
i += 1;
}
b'\\' if !in_single => {
i = (i + 2).min(len);
}
b'(' if !in_single && !in_double => {
paren_depth += 1;
i += 1;
}
b')' if !in_single && !in_double && paren_depth > 0 => {
paren_depth -= 1;
i += 1;
}
b'$' if !in_single && !in_double && bytes.get(i + 1) == Some(&b'{') => {
parameter_depth += 1;
i += 1;
}
b'}' if !in_single && parameter_depth > 0 => {
parameter_depth -= 1;
i += 1;
}
b if b.is_ascii_whitespace()
&& !in_single
&& !in_double
&& paren_depth == 0
&& parameter_depth == 0 =>
{
return i;
}
_ => i += 1,
}
}
len
}
pub(super) fn extract_all_commands(command: &str) -> Vec<String> {
split_on_operators(command)
.into_iter()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
}
#[derive(Clone, Copy)]
struct Frame {
in_single_quote: bool,
in_double_quote: bool,
paren_depth: u32,
brace_depth: u32,
kind: FrameKind,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum FrameKind {
Base,
DollarParen,
Backtick,
}
impl Frame {
const fn new(kind: FrameKind) -> Self {
Self {
in_single_quote: false,
in_double_quote: false,
paren_depth: 0,
brace_depth: 0,
kind,
}
}
const fn shields_operators(&self) -> bool {
self.in_single_quote || self.in_double_quote || self.paren_depth > 0 || self.brace_depth > 0
}
}
pub(super) fn split_on_operators(command: &str) -> Vec<&str> {
let mut segments = Vec::new();
let mut start = 0;
let bytes = command.as_bytes();
let len = bytes.len();
let mut i = 0;
let mut stack: Vec<Frame> = vec![Frame::new(FrameKind::Base)];
while i < len {
let ch = bytes[i];
let opens_substitution = |i: usize| -> Option<(FrameKind, usize)> {
match bytes[i] {
b'$' if i + 1 < len && bytes[i + 1] == b'(' => Some((FrameKind::DollarParen, 2)),
b'`' => Some((FrameKind::Backtick, 1)),
_ => None,
}
};
let frame = *stack.last().expect("base frame is never popped");
if frame.in_single_quote {
if ch == b'\'' {
stack.last_mut().expect("frame").in_single_quote = false;
}
i += 1;
continue;
}
if frame.in_double_quote {
match ch {
b'\\' => i = (i + 2).min(len),
b'"' => {
stack.last_mut().expect("frame").in_double_quote = false;
i += 1;
}
_ => {
if let Some((kind, width)) = opens_substitution(i) {
stack.push(Frame::new(kind));
i += width;
} else {
i += 1;
}
}
}
continue;
}
if let Some((kind, width)) = opens_substitution(i) {
if kind == FrameKind::Backtick && frame.kind == FrameKind::Backtick {
stack.pop();
} else {
stack.push(Frame::new(kind));
}
i += width;
continue;
}
let at_top = stack.len() == 1;
let unshielded = at_top && !frame.shields_operators();
match ch {
b'\\' => {
i = (i + 2).min(len);
}
b'\'' => {
stack.last_mut().expect("frame").in_single_quote = true;
i += 1;
}
b'"' => {
stack.last_mut().expect("frame").in_double_quote = true;
i += 1;
}
b'(' => {
stack.last_mut().expect("frame").paren_depth += 1;
i += 1;
}
b')' => {
let top = stack.last_mut().expect("frame");
if top.kind == FrameKind::DollarParen && top.paren_depth == 0 {
stack.pop();
} else {
top.paren_depth = top.paren_depth.saturating_sub(1);
}
i += 1;
}
b'{' => {
stack.last_mut().expect("frame").brace_depth += 1;
i += 1;
}
b'}' => {
let top = stack.last_mut().expect("frame");
top.brace_depth = top.brace_depth.saturating_sub(1);
i += 1;
}
b'\n' | b'\r' | b';' if unshielded => {
segments.push(&command[start..i]);
i += 1;
start = i;
}
b'&' if unshielded => {
if i + 1 < len && bytes[i + 1] == b'&' {
segments.push(&command[start..i]);
i += 2;
start = i;
} else if (i > 0 && bytes[i - 1] == b'>') || (i + 1 < len && bytes[i + 1] == b'>') {
i += 1;
} else {
segments.push(&command[start..i]);
i += 1;
start = i;
}
}
b'|' if unshielded => {
if i + 1 < len && bytes[i + 1] == b'|' {
segments.push(&command[start..i]);
i += 2;
start = i;
} else if i > 0 && bytes[i - 1] == b'>' {
i += 1;
} else {
segments.push(&command[start..i]);
i += 1;
start = i;
}
}
_ => {
i += 1;
}
}
}
if start < len {
segments.push(&command[start..]);
}
segments
}
pub(super) fn extract_base_from_segment(segment: &str) -> String {
let trimmed = segment.trim();
if trimmed.is_empty() {
return String::new();
}
let cmd_part = skip_powershell_assignment(skip_env_assignments(trimmed));
if cmd_part.is_empty() {
return String::new();
}
if is_powershell_value_expression(cmd_part) {
return String::new();
}
let tokens = shell_tokenize(cmd_part);
let mut token_iter = tokens.iter();
let first_token = match token_iter.next().map(String::as_str) {
Some("{") => token_iter.next().map_or("", String::as_str),
other => other.unwrap_or(""),
};
first_token
.rsplit('/')
.next()
.unwrap_or(first_token)
.to_string()
}
pub(super) fn skip_powershell_assignment(segment: &str) -> &str {
let trimmed = segment.trim_start();
let Some(variable_end) = powershell_local_variable_end(trimmed) else {
return trimmed;
};
let after_variable = trimmed[variable_end..].trim_start();
let Some(after_equals) = after_variable.strip_prefix('=') else {
return trimmed;
};
after_equals.trim_start()
}
fn powershell_local_variable_end(segment: &str) -> Option<usize> {
let bytes = segment.as_bytes();
if bytes.first() != Some(&b'$') {
return None;
}
let mut end = 1;
let first = *bytes.get(end)?;
if !(first.is_ascii_alphabetic() || first == b'_') {
return None;
}
end += 1;
while bytes
.get(end)
.is_some_and(|byte| byte.is_ascii_alphanumeric() || *byte == b'_')
{
end += 1;
}
(bytes.get(end) != Some(&b':')).then_some(end)
}
fn is_powershell_value_expression(segment: &str) -> bool {
let trimmed = segment.trim();
let Some(variable_end) = powershell_local_variable_end(trimmed) else {
return false;
};
let suffix = trimmed[variable_end..].trim();
suffix.is_empty()
|| (suffix.starts_with('[')
&& suffix.ends_with(']')
&& !suffix.contains(['(', ')', ';', '|', '&', '=']))
}
pub(super) fn detect_function_def(segment: &str) -> Option<String> {
let cmd_part = skip_env_assignments(segment.trim());
if cmd_part.is_empty() {
return None;
}
let tokens = shell_tokenize(cmd_part);
if tokens.len() < 2 {
return None;
}
if tokens[0].ends_with("()") && tokens.get(1).map(String::as_str) == Some("{") {
let name = tokens[0].trim_end_matches("()");
if !name.is_empty() && name.chars().all(|c| c.is_alphanumeric() || c == '_') {
return Some(name.to_string());
}
}
if tokens[0] == "function" && tokens.len() >= 3 {
let name_tok = &tokens[1];
let name = name_tok.trim_end_matches("()");
if tokens.get(2).map(String::as_str) == Some("{")
&& !name.is_empty()
&& name.chars().all(|c| c.is_alphanumeric() || c == '_')
{
return Some(name.to_string());
}
}
None
}
pub(super) fn extract_function_body_commands(segment: &str) -> Vec<String> {
let trimmed = segment.trim();
let Some(open) = trimmed.find('{') else {
return vec![];
};
let Some(close) = trimmed.rfind('}').filter(|&i| i > open) else {
return vec![];
};
let body = &trimmed[open + 1..close];
body.split(';')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
}
const ENV_SETTING_BUILTINS: &[&str] =
&["export", "unset", "readonly", "local", "declare", "typeset"];
pub(super) fn skip_env_assignments(segment: &str) -> &str {
let mut rest = segment;
loop {
let rest_trimmed = rest.trim_start();
if rest_trimmed.is_empty() {
return rest_trimmed;
}
let end = quote_aware_token_end(rest_trimmed);
if end == 0 {
return rest_trimmed;
}
let raw_token = &rest_trimmed[..end];
let unquoted: String = raw_token
.chars()
.filter(|c| *c != '"' && *c != '\'')
.collect();
let base_token = unquoted.rsplit('/').next().unwrap_or(unquoted.as_str());
if ENV_SETTING_BUILTINS.contains(&base_token) {
rest = &rest_trimmed[end..];
continue;
}
let is_posix_assignment = unquoted.split_once('=').is_some_and(|(name, _)| {
let mut bytes = name.bytes();
bytes
.next()
.is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
&& bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
});
if is_posix_assignment {
rest = &rest_trimmed[end..];
} else {
return rest_trimmed;
}
}
}
pub fn extract_all_commands_pub(command: &str) -> Vec<String> {
extract_all_commands(command)
}
pub fn extract_base_command(command: &str) -> String {
let first_seg = split_on_operators(command)
.into_iter()
.next()
.unwrap_or(command);
extract_base_from_segment(first_seg)
}