use std::borrow::Cow;
use std::cell::{Cell, RefCell};
struct LoopVar {
name: String,
read_repr: String,
write_repr: String,
seq: u64,
}
struct VarBinding {
name: String,
value: String,
seq: u64,
}
thread_local! {
static LOOP_VARS: RefCell<Vec<LoopVar>> = const { RefCell::new(Vec::new()) };
static VARS: RefCell<Vec<VarBinding>> = const { RefCell::new(Vec::new()) };
static NEXT_SEQ: Cell<u64> = const { Cell::new(0) };
}
fn next_seq() -> u64 {
NEXT_SEQ.with(|n| {
let seq = n.get();
n.set(seq.wrapping_add(1));
seq
})
}
pub(super) enum Bound {
Loop { read_repr: String, write_repr: String },
Value(String),
}
pub(super) fn lookup(name: &str) -> Option<Bound> {
let looped = LOOP_VARS.with(|v| {
v.borrow()
.iter()
.rev()
.find(|l| l.name == name)
.map(|l| (l.seq, Bound::Loop { read_repr: l.read_repr.clone(), write_repr: l.write_repr.clone() }))
});
let valued = VARS.with(|v| v.borrow().iter().rev().find(|b| b.name == name).map(|b| (b.seq, Bound::Value(b.value.clone()))));
match (looped, valued) {
(Some((l, loop_bound)), Some((v, value))) => Some(if l > v { loop_bound } else { value }),
(Some((_, b)), None) | (None, Some((_, b))) => Some(b),
(None, None) => None,
}
}
pub(super) fn bound_names() -> Vec<String> {
let loops: Vec<String> = LOOP_VARS.with(|v| v.borrow().iter().map(|l| l.name.clone()).collect());
VARS.with(|v| loops.into_iter().chain(v.borrow().iter().map(|b| b.name.clone())).collect())
}
pub(super) fn any_loop() -> bool {
LOOP_VARS.with(|v| !v.borrow().is_empty())
}
#[must_use]
pub fn enter_var(name: String, value: String) -> VarGuard {
let seq = next_seq();
VARS.with(|v| v.borrow_mut().push(VarBinding { name, value, seq }));
VarGuard
}
pub struct VarGuard;
impl Drop for VarGuard {
fn drop(&mut self) {
VARS.with(|v| {
v.borrow_mut().pop();
});
}
}
#[must_use]
pub fn enter_loop_var(name: String, read_repr: String, write_repr: String) -> LoopGuard {
let seq = next_seq();
LOOP_VARS.with(|v| v.borrow_mut().push(LoopVar { name, read_repr, write_repr, seq }));
LoopGuard
}
pub struct LoopGuard;
impl Drop for LoopGuard {
fn drop(&mut self) {
LOOP_VARS.with(|v| {
v.borrow_mut().pop();
});
}
}
pub fn expand_vars(path: &str, want_write: bool) -> Cow<'_, str> {
if !path.contains('$') || bound_names().is_empty() {
return Cow::Borrowed(path);
}
expand_with(path, want_write).map_or(Cow::Borrowed(path), Cow::Owned)
}
fn expand_with(path: &str, want_write: bool) -> Option<String> {
let mut out = String::with_capacity(path.len());
let mut rest = path;
let mut replaced = false;
while let Some(dollar) = rest.find('$') {
out.push_str(&rest[..dollar]);
let after = &rest[dollar + 1..];
match parse_var(after) {
Some((name, consumed)) => {
match lookup(name) {
Some(Bound::Loop { read_repr, write_repr }) => out.push_str(if want_write { &write_repr } else { &read_repr }),
Some(Bound::Value(value)) => out.push_str(&value),
None => {
out.push('$');
out.push_str(&after[..consumed]);
rest = &after[consumed..];
continue;
}
}
replaced = true;
rest = &after[consumed..];
}
None => {
out.push('$');
rest = after;
}
}
}
out.push_str(rest);
replaced.then_some(out)
}
pub fn names_a_loop_var(text: &str) -> bool {
let mut rest = text;
while let Some(dollar) = rest.find('$') {
let after = &rest[dollar + 1..];
match parse_var(after) {
Some((name, consumed)) => {
if matches!(lookup(name), Some(Bound::Loop { .. })) {
return true;
}
rest = &after[consumed..];
}
None => rest = after,
}
}
false
}
fn parse_var(after: &str) -> Option<(&str, usize)> {
if let Some(braced) = after.strip_prefix('{') {
let close = braced.find('}')?;
let name = &braced[..close];
is_var_name(name).then_some((name, close + 2))
} else if after.as_bytes().first().is_some_and(u8::is_ascii_digit) {
Some((&after[..1], 1))
} else {
let len = after.bytes().take_while(|&b| b.is_ascii_alphanumeric() || b == b'_').count();
let name = &after[..len];
is_var_name(name).then_some((name, len))
}
}
fn is_var_name(s: &str) -> bool {
if s.is_empty() {
return false;
}
if s.bytes().all(|b| b.is_ascii_digit()) {
return true;
}
let mut bytes = s.bytes();
matches!(bytes.next(), Some(b) if b.is_ascii_alphabetic() || b == b'_') && bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_latest_binding_wins_whichever_kind_it_is() {
let _loop = enter_loop_var("f".into(), "./a".into(), "./a".into());
{
let _assigned = enter_var("f".into(), "/etc/shadow".into());
assert_eq!(expand_vars("$f", false), "/etc/shadow");
assert!(matches!(lookup("f"), Some(Bound::Value(v)) if v == "/etc/shadow"));
{
let _inner = enter_loop_var("f".into(), "./b".into(), "./c".into());
assert_eq!(expand_vars("$f", true), "./c");
assert!(matches!(lookup("f"), Some(Bound::Loop { .. })));
}
assert_eq!(expand_vars("$f", false), "/etc/shadow");
}
assert_eq!(expand_vars("$f", false), "./a");
}
}