Skip to main content

safe_chains/pathctx/
vars.rs

1//! Variables bound for one classification: `for`/`while read` loop variables, which stand for a
2//! set of items, and `VAR=value` assignments or function positionals, which hold one certain value.
3//!
4//! Both kinds share one precedence: the binding entered LAST wins, whichever kind it is. A loop
5//! variable reassigned in its own body (`for f in ./*; do f=/etc/shadow; cat "$f"; done`) holds
6//! the assigned value from then on, and an assignment rebound by an inner loop holds the loop's
7//! items. Looking loops up first let the stale loop binding answer for the assignment.
8
9use std::borrow::Cow;
10use std::cell::{Cell, RefCell};
11
12/// A bound `for` loop variable: `$name` in the body inherits the loop's `in`-list locus (the
13/// `find … {}`→path binding, one layer up). Read and write representatives can differ — a list
14/// like `/etc/hosts ~/notes` reads worst at `~/notes` but writes worst at `/etc/hosts`.
15struct LoopVar {
16    name: String,
17    read_repr: String,
18    write_repr: String,
19    seq: u64,
20}
21
22/// A bound `VAR=value` assignment or a function positional (`$1`). Unlike a loop var, a certain
23/// literal value has ONE representative for both read and write.
24struct VarBinding {
25    name: String,
26    value: String,
27    seq: u64,
28}
29
30thread_local! {
31    static LOOP_VARS: RefCell<Vec<LoopVar>> = const { RefCell::new(Vec::new()) };
32    static VARS: RefCell<Vec<VarBinding>> = const { RefCell::new(Vec::new()) };
33    static NEXT_SEQ: Cell<u64> = const { Cell::new(0) };
34}
35
36fn next_seq() -> u64 {
37    NEXT_SEQ.with(|n| {
38        let seq = n.get();
39        n.set(seq.wrapping_add(1));
40        seq
41    })
42}
43
44/// What the innermost binding of a name holds.
45pub(super) enum Bound {
46    Loop { read_repr: String, write_repr: String },
47    Value(String),
48}
49
50/// The binding of `name` entered last, of either kind.
51pub(super) fn lookup(name: &str) -> Option<Bound> {
52    let looped = LOOP_VARS.with(|v| {
53        v.borrow()
54            .iter()
55            .rev()
56            .find(|l| l.name == name)
57            .map(|l| (l.seq, Bound::Loop { read_repr: l.read_repr.clone(), write_repr: l.write_repr.clone() }))
58    });
59    let valued = VARS.with(|v| v.borrow().iter().rev().find(|b| b.name == name).map(|b| (b.seq, Bound::Value(b.value.clone()))));
60    match (looped, valued) {
61        (Some((l, loop_bound)), Some((v, value))) => Some(if l > v { loop_bound } else { value }),
62        (Some((_, b)), None) | (None, Some((_, b))) => Some(b),
63        (None, None) => None,
64    }
65}
66
67/// Every name bound so far, of either kind.
68pub(super) fn bound_names() -> Vec<String> {
69    let loops: Vec<String> = LOOP_VARS.with(|v| v.borrow().iter().map(|l| l.name.clone()).collect());
70    VARS.with(|v| loops.into_iter().chain(v.borrow().iter().map(|b| b.name.clone())).collect())
71}
72
73/// Whether any loop variable is bound.
74pub(super) fn any_loop() -> bool {
75    LOOP_VARS.with(|v| !v.borrow().is_empty())
76}
77
78/// Bind `name` to a CERTAIN literal `value` (a `VAR=/path` assignment, or `$1` at a function call)
79/// for the duration of the guard. The latest binding of a name wins, loop or not. The caller binds
80/// only values it is certain of — an uncertain value (`VAR=$(cmd)`, `VAR=$UNBOUND`) is bound to the
81/// unpinnable sentinel so `$VAR` still fail-closes rather than resolving to a stale or dropped value.
82#[must_use]
83pub fn enter_var(name: String, value: String) -> VarGuard {
84    let seq = next_seq();
85    VARS.with(|v| v.borrow_mut().push(VarBinding { name, value, seq }));
86    VarGuard
87}
88
89pub struct VarGuard;
90
91impl Drop for VarGuard {
92    fn drop(&mut self) {
93        VARS.with(|v| {
94            v.borrow_mut().pop();
95        });
96    }
97}
98
99/// Bind loop variable `name` to its list's representative items for the duration of the guard
100/// (the loop body's classification). Nested loops stack; the latest binding of a name wins.
101#[must_use]
102pub fn enter_loop_var(name: String, read_repr: String, write_repr: String) -> LoopGuard {
103    let seq = next_seq();
104    LOOP_VARS.with(|v| v.borrow_mut().push(LoopVar { name, read_repr, write_repr, seq }));
105    LoopGuard
106}
107
108/// Pops the loop binding when dropped.
109pub struct LoopGuard;
110
111impl Drop for LoopGuard {
112    fn drop(&mut self) {
113        LOOP_VARS.with(|v| {
114            v.borrow_mut().pop();
115        });
116    }
117}
118
119/// Expand any bound variable (`$name` / `${name}`) in `path` to its value, or a loop variable to
120/// its representative list item — the read representative when `want_write` is false, the write
121/// representative when true. Unbound `$…` is left untouched (so it still fail-closes to machine).
122/// Returns `path` unchanged when nothing is bound.
123pub fn expand_vars(path: &str, want_write: bool) -> Cow<'_, str> {
124    if !path.contains('$') || bound_names().is_empty() {
125        return Cow::Borrowed(path);
126    }
127    expand_with(path, want_write).map_or(Cow::Borrowed(path), Cow::Owned)
128}
129
130fn expand_with(path: &str, want_write: bool) -> Option<String> {
131    let mut out = String::with_capacity(path.len());
132    let mut rest = path;
133    let mut replaced = false;
134    while let Some(dollar) = rest.find('$') {
135        out.push_str(&rest[..dollar]);
136        let after = &rest[dollar + 1..];
137        match parse_var(after) {
138            Some((name, consumed)) => {
139                match lookup(name) {
140                    Some(Bound::Loop { read_repr, write_repr }) => out.push_str(if want_write { &write_repr } else { &read_repr }),
141                    Some(Bound::Value(value)) => out.push_str(&value),
142                    None => {
143                        out.push('$');
144                        out.push_str(&after[..consumed]);
145                        rest = &after[consumed..];
146                        continue;
147                    }
148                }
149                replaced = true;
150                rest = &after[consumed..];
151            }
152            None => {
153                out.push('$');
154                rest = after;
155            }
156        }
157    }
158    out.push_str(rest);
159    replaced.then_some(out)
160}
161
162/// Whether `text` refers to a loop variable whose items are not known: its representative stands in
163/// for a locus, not for the text the shell will hold, so a copy of it is not a known value.
164pub fn names_a_loop_var(text: &str) -> bool {
165    let mut rest = text;
166    while let Some(dollar) = rest.find('$') {
167        let after = &rest[dollar + 1..];
168        match parse_var(after) {
169            Some((name, consumed)) => {
170                if matches!(lookup(name), Some(Bound::Loop { .. })) {
171                    return true;
172                }
173                rest = &after[consumed..];
174            }
175            None => rest = after,
176        }
177    }
178    false
179}
180
181/// Parse a shell variable name immediately after a `$`: `name`, `{name}`, a single-digit positional
182/// (`$1`; bash reads `$12` as `$1` then `2`), or a braced positional (`${10}`). Returns the name and
183/// how many bytes of `after` it consumed, or `None` if it isn't a variable reference.
184fn parse_var(after: &str) -> Option<(&str, usize)> {
185    if let Some(braced) = after.strip_prefix('{') {
186        let close = braced.find('}')?;
187        let name = &braced[..close];
188        is_var_name(name).then_some((name, close + 2))
189    } else if after.as_bytes().first().is_some_and(u8::is_ascii_digit) {
190        Some((&after[..1], 1))
191    } else {
192        let len = after.bytes().take_while(|&b| b.is_ascii_alphanumeric() || b == b'_').count();
193        let name = &after[..len];
194        is_var_name(name).then_some((name, len))
195    }
196}
197
198/// A `${…}` interior is a variable name — an identifier (`[A-Za-z_][A-Za-z0-9_]*`) OR an all-digit
199/// positional (`${10}`).
200fn is_var_name(s: &str) -> bool {
201    if s.is_empty() {
202        return false;
203    }
204    if s.bytes().all(|b| b.is_ascii_digit()) {
205        return true;
206    }
207    let mut bytes = s.bytes();
208    matches!(bytes.next(), Some(b) if b.is_ascii_alphabetic() || b == b'_') && bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_')
209}
210
211#[cfg(test)]
212mod tests {
213    use super::*;
214
215    #[test]
216    fn the_latest_binding_wins_whichever_kind_it_is() {
217        let _loop = enter_loop_var("f".into(), "./a".into(), "./a".into());
218        {
219            let _assigned = enter_var("f".into(), "/etc/shadow".into());
220            assert_eq!(expand_vars("$f", false), "/etc/shadow");
221            assert!(matches!(lookup("f"), Some(Bound::Value(v)) if v == "/etc/shadow"));
222            {
223                let _inner = enter_loop_var("f".into(), "./b".into(), "./c".into());
224                assert_eq!(expand_vars("$f", true), "./c");
225                assert!(matches!(lookup("f"), Some(Bound::Loop { .. })));
226            }
227            assert_eq!(expand_vars("$f", false), "/etc/shadow");
228        }
229        assert_eq!(expand_vars("$f", false), "./a");
230    }
231}