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 => unblocked.push(c),
94        }
95    }
96    unblocked
97        .lines()
98        .filter(|line| !line.trim_start().starts_with("//"))
99        .collect::<Vec<_>>()
100        .join("\n")
101}