use brush_parser::ast::{self};
use crate::core::ShellCore;
impl<'os> ShellCore<'os> {
pub fn expand_word(&mut self, raw: &str) -> String {
self.expand_word_with_glob(raw).0
}
pub fn expand_word_fields(&mut self, raw: &str) -> Vec<String> {
let (text, splittable, _glob) = self.expand_word_masked(raw);
split_fields(&text, &splittable)
}
pub fn expand_word_with_glob(&mut self, raw: &str) -> (String, bool) {
let mut result = String::new();
let mut glob = false;
let mut index = 0;
let mut at_start = true;
let chars: Vec<char> = raw.chars().collect();
while index < chars.len() {
match chars[index] {
'\'' => {
index += 1;
while index < chars.len() && chars[index] != '\'' {
result.push(chars[index]);
index += 1;
}
index += 1;
}
'"' => {
index += 1;
while index < chars.len() && chars[index] != '"' {
if chars[index] == '\\'
&& index + 1 < chars.len()
&& matches!(chars[index + 1], '$' | '`' | '"' | '\\')
{
result.push(chars[index + 1]);
index += 2;
} else if chars[index] == '$' {
if let Some((value, consumed)) = self.expand_parameter(&chars[index..])
{
result.push_str(&value);
index += consumed;
} else {
result.push(chars[index]);
index += 1;
}
} else if chars[index] == '`'
&& let Some((value, consumed)) =
self.backtick_substitution(&chars, index)
{
result.push_str(&value);
index += consumed;
} else {
result.push(chars[index]);
index += 1;
}
}
index += 1;
}
'\\' if index + 1 < chars.len() => {
result.push(chars[index + 1]);
index += 2;
}
'~' if at_start && (index + 1 == chars.len() || chars[index + 1] == '/') => {
result.push_str(self.environment().get("HOME").unwrap_or("/"));
index += 1;
}
'$' => {
if let Some((value, consumed)) = self.expand_parameter(&chars[index..]) {
result.push_str(&value);
index += consumed;
} else {
result.push(chars[index]);
index += 1;
}
}
'`' => {
if let Some((value, consumed)) = self.backtick_substitution(&chars, index) {
result.push_str(&value);
index += consumed;
} else {
result.push(chars[index]);
index += 1;
}
}
'*' | '?' | '[' | ']' => {
glob = true;
result.push(chars[index]);
index += 1;
}
ch => {
result.push(ch);
index += 1;
}
}
at_start = false;
}
(result, glob)
}
#[allow(clippy::same_item_push)]
fn expand_word_masked(&mut self, raw: &str) -> (String, Vec<bool>, bool) {
let mut result = String::new();
let mut mask: Vec<bool> = Vec::new();
let mut glob = false;
let mut index = 0;
let mut at_start = true;
let chars: Vec<char> = raw.chars().collect();
while index < chars.len() {
match chars[index] {
'\'' => {
index += 1;
while index < chars.len() && chars[index] != '\'' {
result.push(chars[index]);
mask.push(false);
index += 1;
}
index += 1;
}
'"' => {
index += 1;
while index < chars.len() && chars[index] != '"' {
if chars[index] == '\\'
&& index + 1 < chars.len()
&& matches!(chars[index + 1], '$' | '`' | '"' | '\\')
{
result.push(chars[index + 1]);
mask.push(false);
index += 2;
} else if chars[index] == '$'
&& let Some((value, consumed)) = self.expand_parameter(&chars[index..])
{
result.push_str(&value);
for _ in value.chars() {
mask.push(false);
}
index += consumed;
} else if chars[index] == '`'
&& let Some((value, consumed)) =
self.backtick_substitution(&chars, index)
{
result.push_str(&value);
for _ in value.chars() {
mask.push(false);
}
index += consumed;
} else {
result.push(chars[index]);
mask.push(false);
index += 1;
}
}
index += 1;
}
'\\' if index + 1 < chars.len() => {
result.push(chars[index + 1]);
mask.push(false);
index += 2;
}
'~' if at_start && (index + 1 == chars.len() || chars[index + 1] == '/') => {
let home = self.environment().get("HOME").unwrap_or("/").to_owned();
result.push_str(&home);
for _ in home.chars() {
mask.push(false);
}
index += 1;
}
'$' => {
let mut value_text = String::new();
if let Some((value, consumed)) = self.expand_parameter(&chars[index..]) {
for ch in value.chars() {
value_text.push(ch);
mask.push(true);
}
index += consumed;
} else {
value_text.push(chars[index]);
mask.push(false);
index += 1;
}
result.push_str(&value_text);
}
'`' => {
if let Some((value, consumed)) = self.backtick_substitution(&chars, index) {
for ch in value.chars() {
result.push(ch);
mask.push(true);
}
index += consumed;
} else {
result.push(chars[index]);
mask.push(false);
index += 1;
}
}
'*' | '?' | '[' | ']' => {
glob = true;
result.push(chars[index]);
index += 1;
}
ch => {
result.push(ch);
mask.push(false);
index += 1;
}
}
at_start = false;
}
(result, mask, glob)
}
fn arithmetic_expansion(&mut self, chars: &[char]) -> Option<(String, usize)> {
let mut depth = 0i32;
let mut end = 2;
while end < chars.len() {
match chars[end] {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
break;
}
}
_ => {}
}
end += 1;
}
if depth != 0 || chars.get(end + 1) != Some(&')') || end < 4 {
return None;
}
let inner: String = chars[3..end].iter().collect();
let prepared = if inner.contains('$') || inner.contains('`') {
self.expand_word(&inner)
} else {
inner
};
let value = self.evaluate_arithmetic(&prepared)?;
Some((value.to_string(), end + 2))
}
pub(crate) fn evaluate_arithmetic(&mut self, raw: &str) -> Option<i64> {
let expr = brush_parser::arithmetic::parse(raw).ok()?;
self.arithmetic_value(&expr)
}
fn arithmetic_variable(&self, name: &str) -> i64 {
self.environment()
.get(name)
.and_then(|value| value.trim().parse::<i64>().ok())
.unwrap_or(0)
}
fn arithmetic_target_value(&mut self, target: &ast::ArithmeticTarget) -> Option<i64> {
match target {
ast::ArithmeticTarget::Variable(name) => Some(self.arithmetic_variable(name)),
ast::ArithmeticTarget::ArrayElement(..) => None,
}
}
fn arithmetic_assign(&mut self, target: &ast::ArithmeticTarget, value: i64) -> Option<()> {
match target {
ast::ArithmeticTarget::Variable(name) => {
self.environment_mut().set(name, value.to_string());
Some(())
}
ast::ArithmeticTarget::ArrayElement(..) => None,
}
}
fn arithmetic_binary(
&self,
operator: ast::BinaryOperator,
left: i64,
right: i64,
) -> Option<i64> {
use ast::BinaryOperator as Op;
match operator {
Op::Add => left.checked_add(right),
Op::Subtract => left.checked_sub(right),
Op::Multiply => left.checked_mul(right),
Op::Divide if right != 0 => left.checked_div(right),
Op::Modulo if right != 0 => left.checked_rem(right),
Op::Divide | Op::Modulo => None,
Op::Power => u32::try_from(right)
.ok()
.and_then(|exponent| pow(left, exponent)),
Op::ShiftLeft => u32::try_from(right)
.ok()
.and_then(|shift| left.checked_shl(shift)),
Op::ShiftRight => u32::try_from(right)
.ok()
.and_then(|shift| left.checked_shr(shift)),
Op::BitwiseAnd => Some(left & right),
Op::BitwiseOr => Some(left | right),
Op::BitwiseXor => Some(left ^ right),
Op::LessThan => Some(i64::from(left < right)),
Op::LessThanOrEqualTo => Some(i64::from(left <= right)),
Op::GreaterThan => Some(i64::from(left > right)),
Op::GreaterThanOrEqualTo => Some(i64::from(left >= right)),
Op::Equals => Some(i64::from(left == right)),
Op::NotEquals => Some(i64::from(left != right)),
Op::LogicalAnd | Op::LogicalOr | Op::Comma => None,
}
}
fn arithmetic_value(&mut self, expr: &ast::ArithmeticExpr) -> Option<i64> {
match expr {
ast::ArithmeticExpr::Literal(value) => Some(*value),
ast::ArithmeticExpr::Reference(target) => self.arithmetic_target_value(target),
ast::ArithmeticExpr::Conditional(condition, then, otherwise) => {
let choice = self.arithmetic_value(condition)?;
if choice == 0 {
self.arithmetic_value(otherwise)
} else {
self.arithmetic_value(then)
}
}
ast::ArithmeticExpr::UnaryOp(operator, operand) => {
let value = self.arithmetic_value(operand)?;
match operator {
ast::UnaryOperator::UnaryPlus => Some(value),
ast::UnaryOperator::UnaryMinus => value.checked_neg(),
ast::UnaryOperator::BitwiseNot => Some(!value),
ast::UnaryOperator::LogicalNot => Some(i64::from(value == 0)),
}
}
ast::ArithmeticExpr::BinaryOp(operator, left, right) => {
use ast::BinaryOperator as Op;
match operator {
Op::LogicalAnd => {
if self.arithmetic_value(left)? == 0 {
return Some(0);
}
Some(i64::from(self.arithmetic_value(right)? != 0))
}
Op::LogicalOr => {
if self.arithmetic_value(left)? != 0 {
return Some(1);
}
Some(i64::from(self.arithmetic_value(right)? != 0))
}
Op::Comma => {
self.arithmetic_value(left)?;
self.arithmetic_value(right)
}
_ => {
let left = self.arithmetic_value(left)?;
let right = self.arithmetic_value(right)?;
self.arithmetic_binary(*operator, left, right)
}
}
}
ast::ArithmeticExpr::Assignment(target, value) => {
let value = self.arithmetic_value(value)?;
self.arithmetic_assign(target, value)?;
Some(value)
}
ast::ArithmeticExpr::BinaryAssignment(operator, target, value) => {
let current = self.arithmetic_target_value(target)?;
let value = self.arithmetic_value(value)?;
let updated = self.arithmetic_binary(*operator, current, value)?;
self.arithmetic_assign(target, updated)?;
Some(updated)
}
ast::ArithmeticExpr::UnaryAssignment(operator, target) => {
let current = self.arithmetic_target_value(target)?;
let updated = match operator {
ast::UnaryAssignmentOperator::PrefixIncrement
| ast::UnaryAssignmentOperator::PostfixIncrement => current.checked_add(1)?,
ast::UnaryAssignmentOperator::PrefixDecrement
| ast::UnaryAssignmentOperator::PostfixDecrement => current.checked_sub(1)?,
};
self.arithmetic_assign(target, updated)?;
match operator {
ast::UnaryAssignmentOperator::PrefixIncrement
| ast::UnaryAssignmentOperator::PrefixDecrement => Some(updated),
ast::UnaryAssignmentOperator::PostfixIncrement
| ast::UnaryAssignmentOperator::PostfixDecrement => Some(current),
}
}
}
}
fn expand_parameter(&mut self, chars: &[char]) -> Option<(String, usize)> {
if chars.first() != Some(&'$') {
return None;
}
if chars.get(1) == Some(&'(') {
if chars.get(2) == Some(&'(')
&& let Some(expansion) = self.arithmetic_expansion(chars)
{
return Some(expansion);
}
return self.command_substitution(chars, 0);
}
if chars.get(1) == Some(&'{') {
let close = chars.iter().position(|ch| *ch == '}')?;
if close <= 2 {
return None;
}
let body: String = chars[2..close].iter().collect();
let consumed = close + 1;
if let Some(name) = body.strip_prefix('#') {
let length = self.environment().get(name).unwrap_or("").chars().count();
return Some((length.to_string(), consumed));
}
{
for operator in [":-", ":=", ":?", ":+"] {
if let Some((name, word)) = body.split_once(operator) {
let value = self.environment().get(name).unwrap_or("").to_owned();
let empty = value.is_empty();
let word = word.to_owned();
let result = match operator {
":-" => {
if empty {
word
} else {
value
}
}
":=" => {
if empty {
self.environment_mut().set(name, word.clone());
word
} else {
value
}
}
":?" => {
if empty {
format!("{name}: {word}")
} else {
value
}
}
":+" => {
if empty {
String::new()
} else {
word
}
}
_ => unreachable!(),
};
return Some((result, consumed));
}
}
}
for operator in ["##", "#", "%%", "%"] {
if let Some((name, pattern)) = body.split_once(operator) {
let value = self.environment().get(name).unwrap_or("").to_owned();
let stripped = strip_pattern(
&value,
pattern,
operator == "##" || operator == "%%",
operator == "%" || operator == "%%",
);
return Some((stripped, consumed));
}
}
let value = self
.positional_value(&body)
.unwrap_or_else(|| self.environment().get(&body).unwrap_or("").to_owned());
return Some((value, consumed));
}
if let Some(second) = chars.get(1)
&& matches!(second, '?' | '$' | '!' | '#' | '*' | '@' | '-' | '0'..='9')
{
if let Some(value) = self.positional_value(&second.to_string()) {
return Some((value, 2));
}
let name = second.to_string();
let value = self.environment().get(&name).unwrap_or("").to_owned();
return Some((value, 2));
}
let start = 1;
let mut end = start;
while end < chars.len() && (chars[end].is_alphanumeric() || chars[end] == '_') {
end += 1;
}
if end == start {
return None;
}
let name: String = chars[start..end].iter().collect();
let value = self.environment().get(&name).unwrap_or("").to_owned();
Some((value, end))
}
fn command_substitution(&mut self, chars: &[char], start: usize) -> Option<(String, usize)> {
if chars.get(start) != Some(&'$') || chars.get(start + 1) != Some(&'(') {
return None;
}
let mut depth = 0usize;
let mut end = start + 2;
while end < chars.len() {
match chars[end] {
'(' => depth += 1,
')' if depth == 0 => break,
')' => depth -= 1,
_ => {}
}
end += 1;
}
if end >= chars.len() {
return None;
}
let inner: String = chars[start + 2..end].iter().collect();
let output = self.execute_captured(&inner);
Some((output, end - start + 1))
}
fn backtick_substitution(&mut self, chars: &[char], start: usize) -> Option<(String, usize)> {
let mut end = start + 1;
while end < chars.len() && chars[end] != '`' {
end += 1;
}
if end >= chars.len() {
return None;
}
let inner: String = chars[start + 1..end].iter().collect();
let output = self.execute_captured(&inner);
Some((output, end - start + 1))
}
fn execute_captured(&mut self, source: &str) -> String {
let mut stdin = engine::BytesInput::new(Vec::new());
let mut stdout = engine::BytesOutput::new();
let mut stderr = engine::BytesOutput::new();
let _ = self.execute(source, &mut stdin, &mut stdout, &mut stderr);
let text = String::from_utf8_lossy(&stdout.into_bytes()).into_owned();
text.trim_end_matches('\n').to_owned()
}
}
fn pow(base: i64, exponent: u32) -> Option<i64> {
match base {
0 => Some(if exponent == 0 { 1 } else { 0 }),
1 => Some(1),
-1 => Some(if exponent.is_multiple_of(2) { 1 } else { -1 }),
base => base.checked_pow(exponent),
}
}
fn strip_pattern(value: &str, pattern: &str, longest: bool, suffix: bool) -> String {
let mut matches: Vec<usize> = Vec::new();
let count = value.chars().count();
for length in 0..=count {
let candidate: String = if suffix {
value.chars().skip(count - length).collect()
} else {
value.chars().take(length).collect()
};
if glob_match(&candidate, pattern) {
matches.push(length);
}
}
let chosen = if longest {
matches.last().copied().unwrap_or(0)
} else {
matches.first().copied().unwrap_or(0)
};
if suffix {
value.chars().take(count - chosen).collect()
} else {
value.chars().skip(chosen).collect()
}
}
pub(crate) fn glob_match(text: &str, pattern: &str) -> bool {
let text: Vec<char> = text.chars().collect();
let pattern: Vec<char> = pattern.chars().collect();
let rows = text.len() + 1;
let cols = pattern.len() + 1;
let mut dp = vec![false; rows * cols];
dp[0] = true;
for j in 1..=pattern.len() {
if pattern[j - 1] == '*' {
dp[j] = dp[j - 1];
}
}
for i in 1..=text.len() {
let mut jumps: Vec<(usize, bool)> = Vec::new();
for j in 1..=pattern.len() {
let at = i * cols + j;
let ch = pattern[j - 1];
match ch {
'*' => dp[at] = dp[at - cols] || dp[at - 1],
'?' => dp[at] = dp[at - cols - 1],
'[' => match parse_class(&pattern, j - 1) {
Some(class) => {
dp[at] = false;
let reached = dp[at - cols - 1] && class.matches(text[i - 1]);
jumps.push((class.end, reached));
}
None => dp[at] = dp[at - cols - 1] && text[i - 1] == '[',
},
c => dp[at] = dp[at - cols - 1] && text[i - 1] == c,
}
}
for (end, reached) in jumps {
if reached {
dp[i * cols + end] = true;
}
}
}
dp[rows * cols - 1]
}
struct CharacterClass {
members: Vec<(char, char)>,
negate: bool,
end: usize,
}
fn parse_class(pattern: &[char], start: usize) -> Option<CharacterClass> {
let mut index = start + 1;
let negate = matches!(pattern.get(index), Some('!') | Some('^'));
if negate {
index += 1;
}
let mut members = Vec::new();
let mut first = true;
while index < pattern.len() {
if pattern[index] == ']' && !first {
return Some(CharacterClass {
members,
negate,
end: index + 1,
});
}
first = false;
if index + 2 < pattern.len() && pattern[index + 1] == '-' && pattern[index + 2] != ']' {
members.push((pattern[index], pattern[index + 2]));
index += 3;
} else {
members.push((pattern[index], pattern[index]));
index += 1;
}
}
None
}
impl CharacterClass {
fn matches(&self, ch: char) -> bool {
let contained = self.members.iter().any(|(lo, hi)| ch >= *lo && ch <= *hi);
contained != self.negate
}
}
mod tests {
#[allow(unused_imports)]
use super::glob_match;
#[test]
fn stars_and_questions_match() {
assert!(glob_match("hello", "h*o"));
assert!(glob_match("hello", "h?llo"));
assert!(!glob_match("hello", "h?lo"));
assert!(glob_match("", "*"));
assert!(glob_match("anything", "*"));
}
#[test]
fn classes_match_members_ranges_and_negation() {
assert!(glob_match("a", "[abc]"));
assert!(!glob_match("d", "[abc]"));
assert!(glob_match("m", "[a-z]"));
assert!(glob_match("file1.txt", "file[0-9].txt"));
assert!(!glob_match("file12.txt", "file[0-9].txt"));
assert!(glob_match("d", "[!abc]"));
assert!(glob_match("q", "[^abc]"));
assert!(!glob_match("a", "[!abc]"));
}
#[test]
fn class_edge_cases_follow_posix() {
assert!(glob_match("]", "[]]"));
assert!(glob_match("-", "[a-]"));
assert!(glob_match("+", "[+-/]"));
assert!(glob_match("[", "["));
assert!(!glob_match("[x", "["));
assert!(glob_match("abc", "*[bc]"));
}
}
fn split_fields(text: &str, mask: &[bool]) -> Vec<String> {
let chars: Vec<char> = text.chars().collect();
let mut fields = Vec::new();
let mut current = String::new();
for (index, ch) in chars.iter().enumerate() {
let splittable = mask.get(index).copied().unwrap_or(false);
if splittable && matches!(ch, ' ' | '\t' | '\n') {
if !current.is_empty() {
fields.push(std::mem::take(&mut current));
}
} else {
current.push(*ch);
}
}
if !current.is_empty() {
fields.push(current);
}
fields
}