use std::collections::HashMap;
use super::Word;
const LEADING_KEYWORDS: &[&str] = &["do", "then", "else", "elif", "if", "while", "until", "!"];
const CLOSING_KEYWORDS: &[&str] = &["done", "fi"];
const MAX_EXPANSIONS: usize = 64;
fn is_name(s: &str, lowercase_only: bool) -> bool {
let mut cs = s.chars();
cs.next().is_some_and(|c| {
c == '_' || c.is_ascii_alphabetic() && (!lowercase_only || c.is_ascii_lowercase())
}) && cs.all(|c| {
c == '_'
|| c.is_ascii_digit()
|| c.is_ascii_alphabetic() && (!lowercase_only || c.is_ascii_lowercase())
})
}
fn visible_value(v: &str) -> bool {
!v.contains('$') && !v.starts_with(['-', '*', '?', '['])
}
fn var_ref(w: &str) -> Option<&str> {
let inner = w.strip_prefix('$')?;
let name = inner
.strip_prefix('{')
.and_then(|s| s.strip_suffix('}'))
.unwrap_or(inner);
is_name(name, false).then_some(name)
}
fn strip_keywords(seg: &[Word]) -> &[Word] {
let mut s = seg;
while let Some(first) = s.first()
&& !first.quoted
&& LEADING_KEYWORDS.contains(&first.text.as_str())
{
s = &s[1..];
}
s
}
fn binding(seg: &[Word]) -> Option<(String, Vec<String>)> {
let head = seg.first()?;
if head.quoted {
return None;
}
if head.text == "for" {
let name = seg.get(1)?;
if name.quoted || !is_name(&name.text, false) || seg.get(2)?.text != "in" {
return None;
}
let vals: Vec<String> = seg[3..].iter().map(|w| w.text.clone()).collect();
return vals
.iter()
.all(|v| visible_value(v))
.then(|| (name.text.clone(), vals));
}
let assign = match (head.text.as_str(), seg.len()) {
("export", 2) => &seg[1],
(_, 1) => head,
_ => return None,
};
let (k, v) = assign.text.split_once('=')?;
(is_name(k, true) && visible_value(v)).then(|| (k.to_string(), vec![v.to_string()]))
}
pub(super) fn expand(segs: Vec<Vec<Word>>) -> Option<Vec<Vec<Word>>> {
let mut vars: HashMap<String, Vec<String>> = HashMap::new();
let mut body: Vec<Vec<Word>> = Vec::new();
for seg in &segs {
let s = strip_keywords(seg);
if s.is_empty() {
continue;
}
if CLOSING_KEYWORDS.contains(&s[0].text.as_str()) && !s[0].quoted {
if s.len() > 1 {
return None; }
continue;
}
if let Some((name, vals)) = binding(s) {
vars.entry(name).or_default().extend(vals);
continue;
}
body.push(s.to_vec());
}
let mut out = Vec::new();
for seg in body {
let mut combos: Vec<Vec<Word>> = vec![Vec::new()];
for w in seg {
let vals = var_ref(&w.text).and_then(|n| vars.get(n));
match vals {
Some(vals) if !vals.is_empty() => {
if combos.len() * vals.len() > MAX_EXPANSIONS {
return None;
}
combos = combos
.into_iter()
.flat_map(|c| {
vals.iter().map(move |v| {
let mut c = c.clone();
c.push(Word {
text: v.clone(),
quoted: w.quoted,
});
c
})
})
.collect();
}
_ => combos.iter_mut().for_each(|c| c.push(w.clone())),
}
}
out.extend(combos);
}
Some(out)
}