safe_chains/pathctx/
vars.rs1use std::borrow::Cow;
10use std::cell::{Cell, RefCell};
11
12struct LoopVar {
16 name: String,
17 read_repr: String,
18 write_repr: String,
19 seq: u64,
20}
21
22struct 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
44pub(super) enum Bound {
46 Loop { read_repr: String, write_repr: String },
47 Value(String),
48}
49
50pub(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
67pub(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
73pub(super) fn any_loop() -> bool {
75 LOOP_VARS.with(|v| !v.borrow().is_empty())
76}
77
78#[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#[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
108pub 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
119pub 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
162pub 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
181fn 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
198fn 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}