1use anyhow::{Result, anyhow};
7use streaming_iterator::StreamingIterator;
8use tree_sitter::{Language, Node, Parser, Query, QueryCursor};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum Visibility {
13 Public,
15 Restricted,
17 Private,
19}
20
21#[derive(Debug, Clone)]
23pub struct Declaration {
24 pub kind: String,
26 pub name: String,
29 pub visibility: Visibility,
31 pub parent: Option<usize>,
33 pub signature: String,
35 pub doc: String,
37 pub line: usize,
39 pub has_body: bool,
41 pub hidden: bool,
44 pub attach: Option<Attach>,
47}
48
49#[derive(Debug, Clone)]
51pub struct Attach {
52 pub to: String,
54 pub implements: Option<String>,
56}
57
58#[derive(Debug, Clone)]
60pub struct Reexport {
61 pub visibility: Visibility,
63 pub path: String,
65 pub parent: Option<usize>,
67}
68
69#[derive(Debug, Clone, Default)]
72pub struct Extracted {
73 pub doc: String,
75 pub declarations: Vec<Declaration>,
77 pub reexports: Vec<Reexport>,
79 pub errors: Vec<usize>,
82}
83
84pub struct Grammar {
87 language: Language,
89 query: Query,
91 docs: Docs,
93}
94
95#[derive(Clone, Copy)]
97pub enum Docs {
98 Rust,
100}
101
102impl Grammar {
103 pub fn new(language: Language, source: &str, docs: Docs) -> Result<Self> {
106 let query = Query::new(&language, source).map_err(|error| {
107 anyhow!(
108 "line {}: {:?} error: {}",
109 error.row + 1,
110 error.kind,
111 error.message
112 )
113 })?;
114 Ok(Self {
115 language,
116 query,
117 docs,
118 })
119 }
120
121 pub fn extract(&self, source: &str) -> Extracted {
123 let mut parser = Parser::new();
124 if parser.set_language(&self.language).is_err() {
125 return Extracted::default();
126 }
127 let Some(tree) = parser.parse(source, None) else {
128 return Extracted::default();
129 };
130 let root = tree.root_node();
131 let names = self.query.capture_names();
132 let mut cursor = QueryCursor::new();
133 let mut matches = cursor.matches(&self.query, root, source.as_bytes());
134 let mut found: Vec<(Node, Declaration)> = Vec::new();
136 let mut reexports: Vec<(Node, Reexport)> = Vec::new();
137 let text = |node: Node| source[node.byte_range()].to_string();
138 while let Some(found_match) = matches.next() {
139 let mut item = None;
140 let mut name = None;
141 let mut visibility = Visibility::Private;
142 let mut attach = None;
143 let mut to = None;
144 let mut implements = None;
145 let mut reexport = None;
146 let mut path = None;
147 for capture in found_match.captures() {
148 let capture_name = names[capture.index as usize];
149 let node = capture.node;
150 match capture_name {
151 "name" => name = Some(text(node)),
152 "visibility" => {
153 visibility = if text(node) == "pub" {
154 Visibility::Public
155 } else {
156 Visibility::Restricted
157 }
158 }
159 "attach" => attach = Some(node),
160 "attach.to" => to = Some(text(node)),
161 "attach.trait" => implements = Some(text(node)),
162 "reexport" => reexport = Some(node),
163 "reexport.path" => path = Some(text(node)),
164 other => {
165 if let Some(kind) = other.strip_prefix("item.") {
166 item = Some((node, kind.to_string()));
167 }
168 }
169 }
170 }
171 if let Some((node, kind)) = item
172 && let Some(name) = name
173 {
174 found.push((
175 node,
176 Declaration {
177 kind,
178 name,
179 visibility,
180 parent: None,
181 signature: signature(node, source),
182 doc: self.doc(node, source),
183 line: node.start_position().row + 1,
184 has_body: node.child_by_field_name("body").is_some(),
185 hidden: self.hidden(node, source),
186 attach: None,
187 },
188 ));
189 } else if let Some(node) = attach
190 && let Some(to) = to
191 {
192 found.push((
193 node,
194 Declaration {
195 kind: "attach".into(),
196 name: to.clone(),
197 visibility: Visibility::Public,
198 parent: None,
199 signature: signature(node, source),
200 doc: self.doc(node, source),
201 line: node.start_position().row + 1,
202 has_body: true,
203 hidden: self.hidden(node, source),
204 attach: Some(Attach { to, implements }),
205 },
206 ));
207 } else if let Some(node) = reexport
208 && let Some(path) = path
209 {
210 reexports.push((
211 node,
212 Reexport {
213 visibility,
214 path,
215 parent: None,
216 },
217 ));
218 }
219 }
220 found.sort_by_key(|(node, _)| node.start_byte());
221 found.dedup_by_key(|(node, _)| node.id());
222 let ids: Vec<usize> = found.iter().map(|(node, _)| node.id()).collect();
223 let enclosing = |node: Node| {
224 let mut at = node.parent();
225 while let Some(ancestor) = at {
226 if let Some(index) = ids.iter().position(|id| *id == ancestor.id()) {
227 return Some(index);
228 }
229 at = ancestor.parent();
230 }
231 None
232 };
233 let parents: Vec<Option<usize>> = found.iter().map(|(node, _)| enclosing(*node)).collect();
234 let reexports = reexports
235 .into_iter()
236 .map(|(node, mut reexport)| {
237 reexport.parent = enclosing(node);
238 reexport
239 })
240 .collect();
241 let declarations = found
242 .into_iter()
243 .zip(parents)
244 .map(|((_, mut declaration), parent)| {
245 declaration.parent = parent;
246 declaration
247 })
248 .collect();
249 let mut errors = Vec::new();
250 errors_in(root, &mut errors);
251 Extracted {
252 doc: self.file_doc(root, source),
253 declarations,
254 reexports,
255 errors,
256 }
257 }
258
259 fn doc(&self, node: Node, source: &str) -> String {
261 match self.docs {
262 Docs::Rust => {
263 let mut lines = Vec::new();
264 let mut at = node.prev_sibling();
265 while let Some(sibling) = at {
266 match sibling.kind() {
267 "attribute_item" => {}
268 "line_comment" if sibling.child_by_field_name("outer").is_some() => {
269 let doc = sibling
270 .child_by_field_name("doc")
271 .map(|doc| &source[doc.byte_range()])
272 .unwrap_or("");
273 lines.push(comment_line(doc));
274 }
275 "block_comment" if sibling.child_by_field_name("outer").is_some() => {
276 let doc = sibling
277 .child_by_field_name("doc")
278 .map(|doc| &source[doc.byte_range()])
279 .unwrap_or("");
280 lines.push(block_text(doc));
281 }
282 _ => break,
283 }
284 at = sibling.prev_sibling();
285 }
286 lines.reverse();
287 lines.join("\n").trim().to_string()
288 }
289 }
290 }
291
292 fn hidden(&self, node: Node, source: &str) -> bool {
295 match self.docs {
296 Docs::Rust => {
297 let mut at = node.prev_sibling();
298 while let Some(sibling) = at {
299 match sibling.kind() {
300 "attribute_item" => {
301 let text: String = source[sibling.byte_range()]
302 .chars()
303 .filter(|c| !c.is_whitespace())
304 .collect();
305 if text == "#[cfg(test)]" || text.contains("doc(hidden)") {
306 return true;
307 }
308 }
309 "line_comment" | "block_comment" => {}
310 _ => return false,
311 }
312 at = sibling.prev_sibling();
313 }
314 false
315 }
316 }
317 }
318
319 fn file_doc(&self, root: Node, source: &str) -> String {
321 match self.docs {
322 Docs::Rust => {
323 let mut lines = Vec::new();
324 let mut walk = root.walk();
325 for child in root.children(&mut walk) {
326 match child.kind() {
327 "line_comment" if child.child_by_field_name("inner").is_some() => {
328 let doc = child
329 .child_by_field_name("doc")
330 .map(|doc| &source[doc.byte_range()])
331 .unwrap_or("");
332 lines.push(comment_line(doc));
333 }
334 "line_comment" | "block_comment" | "inner_attribute_item" => {}
335 _ => break,
336 }
337 }
338 lines.join("\n").trim().to_string()
339 }
340 }
341 }
342}
343
344fn signature(node: Node, source: &str) -> String {
347 let end = node
348 .child_by_field_name("body")
349 .map_or(node.end_byte(), |body| body.start_byte());
350 let text = source[node.start_byte()..end].trim_end();
351 let text = text.strip_suffix(';').unwrap_or(text).trim_end();
352 dedent(text)
353}
354
355fn dedent(text: &str) -> String {
358 let mut lines = text.lines();
359 let first = lines.next().unwrap_or("").to_string();
360 let rest: Vec<&str> = lines.collect();
361 let indent = rest
362 .iter()
363 .filter(|line| !line.trim().is_empty())
364 .map(|line| line.len() - line.trim_start().len())
365 .min()
366 .unwrap_or(0);
367 let keep = indent.saturating_sub(4);
369 std::iter::once(first)
370 .chain(rest.iter().map(|line| {
371 line.get(indent - keep..)
372 .unwrap_or(line.trim_start())
373 .to_string()
374 }))
375 .collect::<Vec<_>>()
376 .join("\n")
377}
378
379fn comment_line(doc: &str) -> String {
381 let doc = doc.strip_suffix('\n').unwrap_or(doc);
382 let doc = doc.strip_suffix('\r').unwrap_or(doc);
383 doc.strip_prefix(' ').unwrap_or(doc).to_string()
384}
385
386fn block_text(doc: &str) -> String {
388 doc.lines()
389 .map(|line| {
390 let line = line.trim_start();
391 let line = line.strip_prefix('*').unwrap_or(line);
392 line.strip_prefix(' ').unwrap_or(line)
393 })
394 .collect::<Vec<_>>()
395 .join("\n")
396 .trim()
397 .to_string()
398}
399
400fn errors_in(node: Node, errors: &mut Vec<usize>) {
402 if node.is_error() || node.is_missing() {
403 errors.push(node.start_position().row + 1);
404 return;
405 }
406 if !node.has_error() {
407 return;
408 }
409 let mut walk = node.walk();
410 for child in node.children(&mut walk) {
411 errors_in(child, errors);
412 }
413}
414
415#[cfg(test)]
416mod tests {
417 use super::*;
418
419 fn rust() -> Grammar {
420 Grammar::new(
421 tree_sitter_rust::LANGUAGE.into(),
422 include_str!("rust.scm"),
423 Docs::Rust,
424 )
425 .unwrap()
426 }
427
428 #[test]
429 fn a_rust_file_says_what_it_declares_inside_what_with_its_docs() {
430 let extracted = rust().extract(
431 "//! The module.\n\n/// A thing.\n/// Two lines.\n#[derive(Debug)]\npub struct Foo<T> {\n /// The a.\n pub a: u8,\n b: T,\n}\n\nimpl<T> Foo<T> {\n /// Reads.\n pub fn read(&self, id: u32) -> u8 {\n fn local() {}\n 1\n }\n}\n\nimpl Display for Foo<u8> {}\n\npub(crate) mod inner;\npub use inner::Thing;\n",
432 );
433 assert_eq!(extracted.doc, "The module.");
434 let shown: Vec<_> = extracted
435 .declarations
436 .iter()
437 .map(|d| (d.kind.as_str(), d.name.as_str(), d.parent, d.visibility))
438 .collect();
439 assert_eq!(
440 shown,
441 [
442 ("struct", "Foo", None, Visibility::Public),
443 ("field", "a", Some(0), Visibility::Public),
444 ("field", "b", Some(0), Visibility::Private),
445 ("attach", "Foo<T>", None, Visibility::Public),
446 ("function", "read", Some(3), Visibility::Public),
447 ("function", "local", Some(4), Visibility::Private),
448 ("attach", "Foo<u8>", None, Visibility::Public),
449 ("module", "inner", None, Visibility::Restricted),
450 ]
451 );
452 let foo = &extracted.declarations[0];
453 assert_eq!(foo.doc, "A thing.\nTwo lines.");
454 assert_eq!(foo.signature, "pub struct Foo<T>");
455 assert_eq!(foo.line, 6);
456 assert_eq!(extracted.declarations[1].doc, "The a.");
457 assert_eq!(
458 extracted.declarations[4].signature,
459 "pub fn read(&self, id: u32) -> u8"
460 );
461 assert_eq!(
462 extracted.declarations[6]
463 .attach
464 .as_ref()
465 .unwrap()
466 .implements
467 .as_deref(),
468 Some("Display")
469 );
470 assert!(!extracted.declarations[7].has_body);
471 assert_eq!(extracted.reexports.len(), 1);
472 assert_eq!(extracted.reexports[0].path, "inner::Thing");
473 assert!(extracted.errors.is_empty());
474 }
475
476 #[test]
477 fn a_query_that_does_not_compile_names_its_line() {
478 let error = Grammar::new(
479 tree_sitter_rust::LANGUAGE.into(),
480 "(function_item) @item.function\n(no_such_node) @item.x\n",
481 Docs::Rust,
482 )
483 .err()
484 .unwrap();
485 assert!(error.to_string().starts_with("line 2:"), "{error}");
486 }
487
488 #[test]
489 fn a_file_that_does_not_parse_keeps_what_does() {
490 let extracted = rust().extract("pub fn ok() {}\npub fn broken( {\n");
491 assert_eq!(extracted.declarations[0].name, "ok");
492 assert!(!extracted.errors.is_empty());
493 }
494}