Skip to main content

safe_chains/pathctx/
item_shape.rs

1//! What the values behind a loop variable or a piped stream can look like, as far as flags go.
2//!
3//! The locus bindings beside this one say WHERE such a value points. They cannot say whether the
4//! value is a flag: `for f in -delete` and `echo -delete | xargs` both bind something that reads
5//! as a worktree path while the command receives `-delete`.
6
7use std::cell::RefCell;
8use std::marker::PhantomData;
9use std::ops::BitOr;
10
11/// A small set of yes/no facts, one bit each. `T` names what they are facts about, so a bit that
12/// means one thing in one set cannot be tested in another.
13#[derive(Debug, PartialEq, Eq)]
14pub struct Facts<T>(u8, PhantomData<T>);
15
16impl<T> Clone for Facts<T> {
17    fn clone(&self) -> Self {
18        *self
19    }
20}
21
22impl<T> Copy for Facts<T> {}
23
24impl<T> Default for Facts<T> {
25    fn default() -> Self {
26        Self::NONE
27    }
28}
29
30impl<T> Facts<T> {
31    pub const NONE: Self = Self(0, PhantomData);
32
33    #[must_use]
34    pub const fn bit(n: u8) -> Self {
35        Self(1 << n, PhantomData)
36    }
37
38    #[must_use]
39    pub const fn union(self, other: Self) -> Self {
40        Self(self.0 | other.0, PhantomData)
41    }
42
43    pub fn has(self, fact: Self) -> bool {
44        self.0 & fact.0 != 0
45    }
46
47    pub fn set(&mut self, fact: Self, on: bool) {
48        if on {
49            self.0 |= fact.0;
50        }
51    }
52
53    pub fn clear(&mut self, fact: Self) {
54        self.0 &= !fact.0;
55    }
56
57    #[must_use]
58    pub fn when(fact: Self, on: bool) -> Self {
59        if on { fact } else { Self::NONE }
60    }
61}
62
63impl<T> BitOr for Facts<T> {
64    type Output = Self;
65    fn bitor(self, other: Self) -> Self {
66        self.union(other)
67    }
68}
69
70/// Marks the facts about a set of values a variable or stream may take.
71#[derive(Debug, PartialEq, Eq)]
72pub enum Items {}
73
74pub type ItemShape = Facts<Items>;
75
76/// Some value may begin with `-`.
77pub const LEAD: ItemShape = Facts::bit(0);
78/// Some value may hold a blank, so an unquoted use becomes several words.
79pub const SPLIT: ItemShape = Facts::bit(1);
80/// Some value may be empty, so an unquoted use becomes none.
81pub const EMPTY: ItemShape = Facts::bit(2);
82/// Some value is text nobody has seen (a file name `find` will meet), so a command that reads it as
83/// a program could be reading anything.
84pub const TEXT: ItemShape = Facts::bit(3);
85/// Nothing is known about the values.
86pub const UNKNOWN: ItemShape = LEAD.union(SPLIT).union(EMPTY).union(TEXT);
87
88thread_local! {
89    static LOOP_SHAPES: RefCell<Vec<(String, ItemShape)>> = const { RefCell::new(Vec::new()) };
90    static STDIN_SHAPES: RefCell<Vec<ItemShape>> = const { RefCell::new(Vec::new()) };
91}
92
93pub struct ItemShapeGuard(bool);
94
95impl Drop for ItemShapeGuard {
96    fn drop(&mut self) {
97        if self.0 {
98            LOOP_SHAPES.with(|v| v.borrow_mut().pop());
99        } else {
100            STDIN_SHAPES.with(|v| v.borrow_mut().pop());
101        }
102    }
103}
104
105#[must_use]
106pub fn enter_loop_shape(name: String, shape: ItemShape) -> ItemShapeGuard {
107    LOOP_SHAPES.with(|v| v.borrow_mut().push((name, shape)));
108    ItemShapeGuard(true)
109}
110
111/// The innermost shape bound to `name`; [`UNKNOWN`] when none is.
112pub fn loop_shape(name: &str) -> ItemShape {
113    LOOP_SHAPES.with(|v| v.borrow().iter().rev().find(|(n, _)| n == name).map_or(UNKNOWN, |(_, s)| *s))
114}
115
116#[must_use]
117pub fn enter_stdin_shape(shape: ItemShape) -> ItemShapeGuard {
118    STDIN_SHAPES.with(|v| v.borrow_mut().push(shape));
119    ItemShapeGuard(false)
120}
121
122/// The shape of the items on stdin; [`UNKNOWN`] when no stage set one.
123pub fn stdin_shape() -> ItemShape {
124    STDIN_SHAPES.with(|v| v.borrow().last().copied().unwrap_or(UNKNOWN))
125}
126
127/// What `$name` is bound to, by [`super::expand_vars`]' precedence (the latest binding of either
128/// kind): a loop (unknown items) or a certain value.
129pub enum Binding {
130    Loop,
131    Value(String),
132    Unbound,
133}
134
135pub fn binding(name: &str) -> Binding {
136    match super::vars::lookup(name) {
137        Some(super::vars::Bound::Loop { .. }) => Binding::Loop,
138        Some(super::vars::Bound::Value(value)) => Binding::Value(value),
139        None => Binding::Unbound,
140    }
141}
142
143/// Every name a loop or an assignment has bound so far.
144pub fn bound_names() -> Vec<String> {
145    super::vars::bound_names()
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    #[test]
153    fn unbound_shapes_are_unknown_and_guards_unwind() {
154        let safe = ItemShape::NONE;
155        assert_eq!(loop_shape("f"), UNKNOWN);
156        assert_eq!(stdin_shape(), UNKNOWN);
157        {
158            let _outer = enter_loop_shape("f".into(), safe);
159            let _stdin = enter_stdin_shape(safe);
160            assert_eq!(loop_shape("f"), safe);
161            assert_eq!(loop_shape("g"), UNKNOWN);
162            assert_eq!(stdin_shape(), safe);
163            {
164                let _inner = enter_loop_shape("f".into(), UNKNOWN);
165                assert_eq!(loop_shape("f"), UNKNOWN);
166            }
167            assert_eq!(loop_shape("f"), safe);
168        }
169        assert_eq!(loop_shape("f"), UNKNOWN);
170        assert_eq!(stdin_shape(), UNKNOWN);
171    }
172
173    #[test]
174    fn facts_combine_and_clear() {
175        let mut f = ItemShape::NONE;
176        assert!(!f.has(LEAD));
177        f.set(LEAD, false);
178        assert_eq!(f, ItemShape::NONE);
179        f.set(LEAD, true);
180        assert!(f.has(LEAD) && !f.has(SPLIT));
181        assert_eq!(LEAD | SPLIT | EMPTY | TEXT, UNKNOWN);
182        f.clear(LEAD);
183        assert_eq!(f, ItemShape::NONE);
184        assert_eq!(ItemShape::when(SPLIT, true), SPLIT);
185        assert_eq!(ItemShape::when(SPLIT, false), ItemShape::NONE);
186    }
187}