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
9pub 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 #[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 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 fn arity(&self, tag: &str) -> Arity {
68 Arity::from_table(crate::langs::arity::RUST, tag)
69 }
70
71 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" => 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 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 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
167fn 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 const HEADER: Option<&'static str> = Some("//!");
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194 use crate::qterm::tb;
195
196 #[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 #[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}