Skip to main content

quilt/langs/rust/
lang.rs

1use crate::{
2    lang::{Arity, Comments, InnerKind},
3    qterm::QTerm,
4    treesitter::{DynTSLanguage, FragmentWrapper, TSLanguage, TSProvider},
5};
6use miette::{miette, Result};
7use tree_sitter::Parser;
8
9/**************************************************************/
10
11pub struct RustProvider(tree_sitter::Parser);
12
13impl Default for RustProvider {
14    fn default() -> Self {
15        let mut parser = Parser::new();
16        parser
17            .set_language(&crate::grammars::rust::LANGUAGE.into())
18            .expect("Error loading Rust parser");
19        Self(parser)
20    }
21}
22
23impl TSProvider for RustProvider {
24    fn parser(&mut self) -> &mut tree_sitter::Parser {
25        &mut self.0
26    }
27
28    fn hole_str(&self) -> &'static str {
29        "{}"
30    }
31
32    fn unwrap(&self, qterm: QTerm, ikind: Option<InnerKind>) -> Result<(QTerm, InnerKind)> {
33        // dbg!(&qterm);
34        #[allow(clippy::single_match)]
35        Ok(match &qterm {
36            QTerm::Tuple { tag, terms, .. } => match &**tag {
37                "source_file" => {
38                    if terms.len() == 1 {
39                        let q0 = &terms[0];
40                        match &**q0 {
41                            QTerm::Tuple { tag, .. } => {
42                                // The hole's position (when known) settles
43                                // ambiguous bodies like a bare `{ }`; otherwise
44                                // guess from the tag.
45                                let kind = match ikind {
46                                    Some(k) if k != InnerKind::File => k,
47                                    _ if **tag == *"{}" => InnerKind::Stmt,
48                                    _ => self.typ(tag),
49                                };
50                                (qterm.squash(), kind)
51                            }
52                            _ => return Err(unsupported_shape(&qterm)),
53                        }
54                    } else {
55                        (qterm, InnerKind::File)
56                    }
57                }
58                "{}" => (qterm, InnerKind::Expr),
59                _ => return Err(unsupported_shape(&qterm)),
60            },
61            _ => return Err(unsupported_shape(&qterm)),
62        })
63    }
64
65    /// Derived from the grammar's `REPEAT` rules by `bin/gen-arity`, not
66    /// hand-curated — see `quilt/src/langs/arity.rs` (#202).
67    fn arity(&self, tag: &str) -> Arity {
68        Arity::from_table(crate::langs::arity::RUST, tag)
69    }
70
71    /// `,` for the kinds `bin/gen-arity` finds comma-separated (#293).
72    fn separator(&self, tag: &str) -> Option<&'static str> {
73        crate::lang::comma_separator(crate::langs::arity::RUST_COMMA_SEPARATED, tag)
74    }
75
76    fn typ(&self, tag: &str) -> InnerKind {
77        match tag {
78            "source_file" => InnerKind::File,
79            // `let_declaration` ends with "declaration" but is a statement, not
80            // an item — match it before the item rule below.
81            "let_declaration" => InnerKind::Stmt,
82            _ if tag.ends_with("item") || tag.ends_with("declaration") => InnerKind::Item,
83            _ if tag.ends_with("statement") => InnerKind::Stmt,
84            _ => InnerKind::Expr,
85        }
86    }
87
88    fn hole_kind(&self, node: tree_sitter::Node) -> InnerKind {
89        // A `block` is a value (expression) by tag, but in body/branch
90        // position it is a block body. Read the parent to tell the two apart:
91        // `fn f() {…}` / `loop {…}` use the `body` field, `if c {…}` uses
92        // `consequence`, and the `else {…}` block hangs off an `else_clause`.
93        // (A `block` in `value` position — `let x = {…}` — stays `Expr`.)
94        // A hole among the items of an `impl`, `mod` or `trait` body stands
95        // for items. Its tag is the grammar's `quilt_hole`, which says nothing
96        // about position on its own (#302).
97        if node.kind() == "quilt_hole"
98            && node
99                .parent()
100                .is_some_and(|p| p.kind() == "declaration_list")
101        {
102            return InnerKind::Item;
103        }
104        if node.kind() == "block" {
105            if let Some(parent) = node.parent() {
106                let is_body = parent.kind() == "else_clause"
107                    || ["body", "consequence"]
108                        .iter()
109                        .any(|field| parent.child_by_field_name(field) == Some(node));
110                if is_body {
111                    return InnerKind::Block;
112                }
113            }
114        }
115        self.typ(node.kind())
116    }
117
118    fn hashbang(&self) -> Option<&'static str> {
119        Some("#!/usr/bin/env rust-script")
120    }
121
122    /// A match arm, an enum variant, a struct field, a function parameter or
123    /// a field pattern, quoted on its own (`rs↖A(u64)↗`), parses inside the
124    /// construct it belongs to. Order settles the one overlap: `a: u64` is a
125    /// struct field before it is a parameter, and both write back the same.
126    fn fragment_wrappers(&self) -> &'static [FragmentWrapper] {
127        &[
128            FragmentWrapper {
129                before: "match q {",
130                after: "}",
131                container: "match_block",
132                fragments: &["match_arm"],
133                leading: &[],
134            },
135            FragmentWrapper {
136                before: "enum Q {",
137                after: "}",
138                container: "enum_variant_list",
139                fragments: &["enum_variant"],
140                leading: &["attribute_item"],
141            },
142            FragmentWrapper {
143                before: "struct Q {",
144                after: "}",
145                container: "field_declaration_list",
146                fragments: &["field_declaration"],
147                leading: &["attribute_item"],
148            },
149            FragmentWrapper {
150                before: "fn q(",
151                after: ") {}",
152                container: "parameters",
153                fragments: &["parameter", "self_parameter"],
154                leading: &["attribute_item"],
155            },
156            FragmentWrapper {
157                before: "let Q {",
158                after: "} = q;",
159                container: "struct_pattern",
160                fragments: &["field_pattern", "remaining_field_pattern"],
161                leading: &[],
162            },
163        ]
164    }
165}
166
167/// Diagnostic for a Rust fragment whose tree-sitter parse shape the provider
168/// doesn't know how to unwrap. Replaces the `unimplemented!` panics that used
169/// to crash the expander on unusual-but-valid Rust (issue #11); the parse's
170/// s-expression is included so the gap can be reported and reproduced.
171fn unsupported_shape(qterm: &QTerm) -> miette::Report {
172    miette!(
173        "Quilt can't place this Rust fragment — unsupported parse shape: {}.\n\
174         This is a gap in Quilt's Rust support; please report it along with the \
175         fragment that triggered it.",
176        qterm.sexp()
177    )
178}
179
180pub type RustLanguage = TSLanguage<RustProvider>;
181pub type DynRustLanguage = DynTSLanguage<RustProvider>;
182
183impl Comments for RustLanguage {
184    const LINE: Option<&'static str> = Some("//");
185    /// Rust is the one language whose header is not its plain line comment.
186    /// `//!` is an inner doc comment, so the `DO NOT EDIT` banner documents the
187    /// generated module rather than whatever item happens to follow it.
188    const HEADER: Option<&'static str> = Some("//!");
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    use crate::qterm::tb;
195
196    /// A parse shape the provider can't place (here, a root tag that is neither
197    /// `source_file` nor the `{}` hole) now surfaces a diagnostic instead of
198    /// panicking via `unimplemented!` (issue #11).
199    #[test]
200    fn unsupported_shape_returns_err_not_panic() {
201        let provider = RustProvider::default();
202        let err = provider
203            .unwrap(tb("not_a_real_node_kind").build(), None)
204            .expect_err("an unrecognised parse shape should be an error");
205        assert!(
206            err.to_string().contains("unsupported parse shape"),
207            "diagnostic should name the unsupported shape, got: {err}"
208        );
209    }
210
211    /// A well-formed single-node `source_file` still unwraps successfully.
212    #[test]
213    fn source_file_single_node_unwraps_ok() {
214        let provider = RustProvider::default();
215        let qterm = tb("source_file").c(&tb("expression_statement").b()).build();
216        assert!(provider.unwrap(qterm, None).is_ok());
217    }
218}