Skip to main content

devpage_core/code/
extract.rs

1//! Extract: one file's declarations, as its grammar's query captures them.
2//! Pure and per file: what one file says, before any name is resolved
3//! against another file. The query decides what is a declaration; the
4//! grammar's language decides how its doc comments read.
5
6use anyhow::{Result, anyhow};
7use streaming_iterator::StreamingIterator;
8use tree_sitter::{Language, Node, Parser, Query, QueryCursor};
9
10/// How a declaration is visible where it is written.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum Visibility {
13    /// Visible to anyone that sees its container: `pub`.
14    Public,
15    /// Visible to part of the code only: `pub(crate)`, `pub(super)`.
16    Restricted,
17    /// Written without a visibility.
18    Private,
19}
20
21/// What one file says about one thing.
22#[derive(Debug, Clone)]
23pub struct Declaration {
24    /// The query's kind: `function`, `struct`, `field`…
25    pub kind: String,
26    /// Its name, as the query's `@name` captures it; for an `impl`, the type
27    /// it names.
28    pub name: String,
29    /// How it is visible where it is written.
30    pub visibility: Visibility,
31    /// The declaration it is written inside, by index in the file's list.
32    pub parent: Option<usize>,
33    /// The declaration as written, without its body.
34    pub signature: String,
35    /// Its doc comment, as Markdown.
36    pub doc: String,
37    /// Its first line, from 1.
38    pub line: usize,
39    /// Whether it has a body of its own: a `mod x { … }`, not a `mod x;`.
40    pub has_body: bool,
41    /// Whether its attributes keep it out of the reference:
42    /// `#[cfg(test)]`, `#[doc(hidden)]`.
43    pub hidden: bool,
44    /// For a block whose members belong to another declaration — an
45    /// `impl` — what they belong to.
46    pub attach: Option<Attach>,
47}
48
49/// A block whose members belong to the type it names.
50#[derive(Debug, Clone)]
51pub struct Attach {
52    /// The type, as written: `Foo<T>`, `crate::a::Foo`.
53    pub to: String,
54    /// The trait it implements, as written, when it implements one.
55    pub implements: Option<String>,
56}
57
58/// A statement making a name reachable where it is written: `pub use`.
59#[derive(Debug, Clone)]
60pub struct Reexport {
61    /// How the `use` is visible where it is written.
62    pub visibility: Visibility,
63    /// The path as written: `a::b::C`, `crate::a::{B, C as D}`.
64    pub path: String,
65    /// The declaration it is written inside — an inline module — if any.
66    pub parent: Option<usize>,
67}
68
69/// What one file says: its own doc comment and its declarations, in the
70/// order they are written.
71#[derive(Debug, Clone, Default)]
72pub struct Extracted {
73    /// The file's own doc comment, as Markdown.
74    pub doc: String,
75    /// Its declarations, in the order they are written.
76    pub declarations: Vec<Declaration>,
77    /// Its `pub use` statements, in the order they are written.
78    pub reexports: Vec<Reexport>,
79    /// The lines where the file doesn't parse; declarations elsewhere are
80    /// kept.
81    pub errors: Vec<usize>,
82}
83
84/// A language's parser: its grammar, the query that finds declarations, and
85/// how its doc comments read.
86pub struct Grammar {
87    /// The tree-sitter language files are parsed with.
88    language: Language,
89    /// The query that captures declarations and reexports.
90    query: Query,
91    /// How the language's doc comments read.
92    docs: Docs,
93}
94
95/// How a language writes doc comments.
96#[derive(Clone, Copy)]
97pub enum Docs {
98    /// `///` and `/** */` before a declaration; `//!` at the top of a file.
99    Rust,
100}
101
102impl Grammar {
103    /// The grammar of `language` with the query `source`: an error naming the
104    /// query's line when it doesn't compile against the grammar.
105    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    /// The declarations of `source`.
122    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        // Each declaration's node, to find the one it is written inside.
135        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    /// The doc comment written just before `node`, attributes skipped.
260    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    /// Whether an attribute just before `node` keeps it out of the
293    /// reference: code only tests build, or code its author hid.
294    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    /// The doc comment of the file itself: `//!` lines at its top.
320    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
344/// A declaration as written without its body: everything before the node's
345/// `body` field, or the whole node when it has none.
346fn 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
355/// `text` with the indentation its later lines share taken off, so a
356/// signature split over lines reads as written at the top level.
357fn 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    // Later lines keep the indent they have beyond the first line's.
368    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
379/// One `///` or `//!` line's text: the space after the marker taken off.
380fn 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
386/// A `/** */` comment's text: each line's leading `*` taken off.
387fn 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
400/// The lines of every part of the tree that doesn't parse.
401fn 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}