Skip to main content

rust_anything/lang/
syntax.rs

1//! Small helpers over tree-sitter syntax trees, shared by the language plugins.
2
3use tree_sitter::{Language, Node, Parser, Tree};
4
5/// Parses `text`; `None` only when the grammar cannot be loaded.
6pub fn parse(language: &Language, text: &str) -> Option<Tree> {
7    let mut parser = Parser::new();
8    parser.set_language(language).ok()?;
9    parser.parse(text, None)
10}
11
12pub fn text<'t>(node: Node, source: &'t str) -> &'t str {
13    node.utf8_text(source.as_bytes()).unwrap_or("")
14}
15
16/// 1-based line of a node.
17pub fn line(node: Node) -> u32 {
18    u32::try_from(node.start_position().row + 1).unwrap_or(u32::MAX)
19}
20
21/// Every node in the tree, depth first.
22pub fn walk<'t>(root: Node<'t>, mut visit: impl FnMut(Node<'t>)) {
23    let mut cursor = root.walk();
24    let mut stack = vec![root];
25    while let Some(node) = stack.pop() {
26        visit(node);
27        let children: Vec<Node> = node.children(&mut cursor).collect();
28        stack.extend(children.into_iter().rev());
29    }
30}
31
32pub fn named_children<'t>(node: Node<'t>) -> Vec<Node<'t>> {
33    let mut cursor = node.walk();
34    node.named_children(&mut cursor).collect()
35}
36
37/// Non-blank lines.
38pub fn loc(text: &str) -> usize {
39    text.lines().filter(|l| !l.trim().is_empty()).count()
40}
41
42/// `text` with its `<!-- -->` comments removed (a `pom.xml`, a project file).
43pub fn without_xml_comments(text: &str) -> String {
44    let mut out = String::with_capacity(text.len());
45    let mut rest = text;
46    while let Some(start) = rest.find("<!--") {
47        out.push_str(&rest[..start]);
48        match rest[start..].find("-->") {
49            Some(end) => rest = &rest[start + end + 3..],
50            None => {
51                rest = "";
52                break;
53            }
54        }
55    }
56    out.push_str(rest);
57    out
58}
59
60/// A build file with its comments removed, so a commented-out `implementation("a:b:1")` is not
61/// read as a dependency the project declares. `//` counts only at the start of a line: a trailing
62/// one follows code the project does declare.
63pub fn without_slash_comments(text: &str) -> String {
64    let mut unblocked = String::with_capacity(text.len());
65    let mut chars = text.chars().peekable();
66    let mut quote = None;
67    while let Some(c) = chars.next() {
68        match quote {
69            Some(q) => {
70                unblocked.push(c);
71                if c == '\\' {
72                    if let Some(escaped) = chars.next() {
73                        unblocked.push(escaped);
74                    }
75                } else if c == q || c == '\n' {
76                    quote = None;
77                }
78            }
79            None if c == '"' || c == '\'' => {
80                quote = Some(c);
81                unblocked.push(c);
82            }
83            None if c == '/' && chars.peek() == Some(&'*') => {
84                chars.next();
85                let mut last = ' ';
86                for c in chars.by_ref() {
87                    if last == '*' && c == '/' {
88                        break;
89                    }
90                    last = c;
91                }
92            }
93            None if c == '/' && chars.peek() == Some(&'/') => {
94                // `//` ends the line: a `/*` inside it is text, not the start of a block comment,
95                // so the declarations on the lines after it stay visible.
96                chars.next();
97                for c in chars.by_ref() {
98                    if c == '\n' {
99                        unblocked.push('\n');
100                        break;
101                    }
102                }
103            }
104            None => unblocked.push(c),
105        }
106    }
107    unblocked
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn a_block_comment_marker_inside_a_line_comment_does_not_swallow_the_next_lines() {
116        // `build/*.jar` in a `//` comment used to open a block comment, hiding both dependencies.
117        let gradle = "// generated into build/*.jar\n\
118                      implementation(\"a:b:1\")\n\
119                      implementation(\"c:d:2\")\n";
120        let out = without_slash_comments(gradle);
121        assert!(out.contains("implementation(\"a:b:1\")"), "{out}");
122        assert!(out.contains("implementation(\"c:d:2\")"), "{out}");
123    }
124
125    #[test]
126    fn slash_comments_are_removed_and_block_comments_still_are() {
127        let text = "// implementation(\"old:one:1\")\n\
128                    implementation(\"a:b:1\") // trailing note\n\
129                    /* implementation(\"gone:two:2\") */\n\
130                    implementation(\"c:d:2\")";
131        let out = without_slash_comments(text);
132        assert!(!out.contains("old:one"), "{out}");
133        assert!(!out.contains("trailing note"), "{out}");
134        assert!(!out.contains("gone:two"), "{out}");
135        assert!(out.contains("a:b:1") && out.contains("c:d:2"), "{out}");
136    }
137
138    #[test]
139    fn a_slash_pair_inside_a_string_stays() {
140        let text = "implementation(\"a:b:1\")\nval url = \"https://example.test/x\"\n";
141        let out = without_slash_comments(text);
142        assert!(out.contains("https://example.test/x"), "{out}");
143        assert!(out.contains("a:b:1"), "{out}");
144    }
145}