Skip to main content

milo_guards_code/
unit.rs

1//! What the readers are built from besides the grammars: the argument of a
2//! call as the code gives it, the limits, and two helpers that walk a tree.
3
4/// One value the code hands to a call, as far as the reader knows it.
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub enum Arg {
7    /// Its value is in the text: `'target'`, `'~/x'`.
8    Known(String),
9    /// Only known when the code runs (a name nothing sets, a call's result):
10    /// its source text.
11    Unknown(String),
12    /// A path that starts as the code says and ends in something only known
13    /// when it runs: somewhere in a folder (`'/home/me/.ssh/id_' + name` is a
14    /// file in `/home/me/.ssh/`). Not a value, but the folder is known, and a
15    /// caller judges a read of the path by it.
16    Below {
17        /// The folder, as the code spells it, with its closing `/`.
18        folder: String,
19        /// The value as written.
20        source: String,
21    },
22}
23
24impl Arg {
25    /// The value, when the code gives it whole.
26    pub fn known(&self) -> Option<&str> {
27        match self {
28            Self::Known(text) => Some(text),
29            Self::Unknown(_) | Self::Below { .. } => None,
30        }
31    }
32
33    /// The value, or the source text of what is only known when the code runs.
34    pub fn text(&self) -> &str {
35        match self {
36            Self::Known(text) | Self::Unknown(text) | Self::Below { source: text, .. } => text,
37        }
38    }
39}
40
41/// How deep code may run code (`exec("…")` inside `exec("…")`) before the
42/// reader stops following it.
43pub const MAX_DEPTH: usize = 8;
44
45/// How deep a parse tree is walked before the code is too nested to read:
46/// walking deeper would risk overflowing the stack.
47pub const MAX_TREE_DEPTH: usize = 400;
48
49/// The longest code a caller should hand the reader: it reads in time that
50/// grows with the code, and the strings it works out from names are held to a
51/// few times this. A caller refuses longer code before it reads (the shell
52/// guard's limit on a line is the same number).
53pub const MAX_LEN: usize = 64 * 1024;
54
55/// Visit every node under `root`, without recursion, so a deep tree cannot
56/// overflow the stack.
57pub(crate) fn for_each_node<'tree>(
58    root: tree_sitter::Node<'tree>,
59    mut visit: impl FnMut(tree_sitter::Node<'tree>),
60) {
61    let mut cursor = root.walk();
62    loop {
63        visit(cursor.node());
64        if cursor.goto_first_child() {
65            continue;
66        }
67        loop {
68            if cursor.goto_next_sibling() {
69                break;
70            }
71            if !cursor.goto_parent() {
72                return;
73            }
74        }
75    }
76}
77
78/// The source text of `node`.
79pub(crate) fn text<'s>(node: &tree_sitter::Node<'_>, source: &'s str) -> &'s str {
80    source.get(node.byte_range()).unwrap_or_default()
81}