rust_anything/lang/
syntax.rs1use tree_sitter::{Language, Node, Parser, Tree};
4
5pub 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
16pub fn line(node: Node) -> u32 {
18 u32::try_from(node.start_position().row + 1).unwrap_or(u32::MAX)
19}
20
21pub 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
37pub fn loc(text: &str, lang: crate::lang::Lang) -> usize {
40 code_lines(text, lang.comment_prefixes())
41}
42
43pub fn code_lines(text: &str, comment: &[&str]) -> usize {
45 text.lines()
46 .map(str::trim)
47 .filter(|l| {
48 !l.is_empty()
49 && !comment
50 .iter()
51 .any(|c| l.starts_with(c) || *l == c.trim_end())
52 })
53 .count()
54}
55
56pub fn without_xml_comments(text: &str) -> String {
58 let mut out = String::with_capacity(text.len());
59 let mut rest = text;
60 while let Some(start) = rest.find("<!--") {
61 out.push_str(&rest[..start]);
62 match rest[start..].find("-->") {
63 Some(end) => rest = &rest[start + end + 3..],
64 None => {
65 rest = "";
66 break;
67 }
68 }
69 }
70 out.push_str(rest);
71 out
72}
73
74pub fn without_slash_comments(text: &str) -> String {
78 let mut unblocked = String::with_capacity(text.len());
79 let mut chars = text.chars().peekable();
80 let mut quote = None;
81 while let Some(c) = chars.next() {
82 match quote {
83 Some(q) => {
84 unblocked.push(c);
85 if c == '\\' {
86 if let Some(escaped) = chars.next() {
87 unblocked.push(escaped);
88 }
89 } else if c == q || c == '\n' {
90 quote = None;
91 }
92 }
93 None if c == '"' || c == '\'' => {
94 quote = Some(c);
95 unblocked.push(c);
96 }
97 None if c == '/' && chars.peek() == Some(&'*') => {
98 chars.next();
99 let mut last = ' ';
100 for c in chars.by_ref() {
101 if last == '*' && c == '/' {
102 break;
103 }
104 last = c;
105 }
106 }
107 None if c == '/' && chars.peek() == Some(&'/') => {
108 chars.next();
111 for c in chars.by_ref() {
112 if c == '\n' {
113 unblocked.push('\n');
114 break;
115 }
116 }
117 }
118 None => unblocked.push(c),
119 }
120 }
121 unblocked
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127
128 #[test]
129 fn a_line_starting_with_a_dereference_is_code() {
130 let c = "/*\n * Doubles it.\n *\n */\nvoid twice(int *p) {\n *p *= 2;\n}\n";
131 assert_eq!(loc(c, crate::lang::Lang::C), 3);
132 }
133
134 #[test]
135 fn a_block_comment_marker_inside_a_line_comment_does_not_swallow_the_next_lines() {
136 let gradle = "// generated into build/*.jar\n\
138 implementation(\"a:b:1\")\n\
139 implementation(\"c:d:2\")\n";
140 let out = without_slash_comments(gradle);
141 assert!(out.contains("implementation(\"a:b:1\")"), "{out}");
142 assert!(out.contains("implementation(\"c:d:2\")"), "{out}");
143 }
144
145 #[test]
146 fn slash_comments_are_removed_and_block_comments_still_are() {
147 let text = "// implementation(\"old:one:1\")\n\
148 implementation(\"a:b:1\") // trailing note\n\
149 /* implementation(\"gone:two:2\") */\n\
150 implementation(\"c:d:2\")";
151 let out = without_slash_comments(text);
152 assert!(!out.contains("old:one"), "{out}");
153 assert!(!out.contains("trailing note"), "{out}");
154 assert!(!out.contains("gone:two"), "{out}");
155 assert!(out.contains("a:b:1") && out.contains("c:d:2"), "{out}");
156 }
157
158 #[test]
159 fn a_slash_pair_inside_a_string_stays() {
160 let text = "implementation(\"a:b:1\")\nval url = \"https://example.test/x\"\n";
161 let out = without_slash_comments(text);
162 assert!(out.contains("https://example.test/x"), "{out}");
163 assert!(out.contains("a:b:1"), "{out}");
164 }
165}