Skip to main content

normalize_languages/
capnp.rs

1//! Cap'n Proto schema support.
2
3use crate::external_packages::ResolvedPackage;
4use crate::{Export, Import, Language, Symbol, SymbolKind, Visibility, VisibilityMechanism};
5use std::path::{Path, PathBuf};
6use tree_sitter::Node;
7
8/// Cap'n Proto language support.
9pub struct Capnp;
10
11impl Language for Capnp {
12    fn name(&self) -> &'static str {
13        "Cap'n Proto"
14    }
15    fn extensions(&self) -> &'static [&'static str] {
16        &["capnp"]
17    }
18    fn grammar_name(&self) -> &'static str {
19        "capnp"
20    }
21
22    fn has_symbols(&self) -> bool {
23        true
24    }
25
26    fn container_kinds(&self) -> &'static [&'static str] {
27        &["struct", "interface", "enum"]
28    }
29
30    fn function_kinds(&self) -> &'static [&'static str] {
31        &["method"]
32    }
33
34    fn type_kinds(&self) -> &'static [&'static str] {
35        &["struct", "interface", "enum"]
36    }
37
38    fn import_kinds(&self) -> &'static [&'static str] {
39        &["import"]
40    }
41
42    fn public_symbol_kinds(&self) -> &'static [&'static str] {
43        &["struct", "interface", "enum"]
44    }
45
46    fn visibility_mechanism(&self) -> VisibilityMechanism {
47        VisibilityMechanism::AllPublic
48    }
49
50    fn extract_public_symbols(&self, node: &Node, content: &str) -> Vec<Export> {
51        let kind = match node.kind() {
52            "struct" => SymbolKind::Struct,
53            "interface" => SymbolKind::Interface,
54            "enum" => SymbolKind::Enum,
55            _ => return Vec::new(),
56        };
57
58        if let Some(name) = self.node_name(node, content) {
59            return vec![Export {
60                name: name.to_string(),
61                kind,
62                line: node.start_position().row + 1,
63            }];
64        }
65        Vec::new()
66    }
67
68    fn scope_creating_kinds(&self) -> &'static [&'static str] {
69        &["struct", "interface"]
70    }
71
72    fn control_flow_kinds(&self) -> &'static [&'static str] {
73        &[]
74    }
75    fn complexity_nodes(&self) -> &'static [&'static str] {
76        &[]
77    }
78    fn nesting_nodes(&self) -> &'static [&'static str] {
79        &["struct", "interface"]
80    }
81
82    fn signature_suffix(&self) -> &'static str {
83        ""
84    }
85
86    fn extract_function(&self, node: &Node, content: &str, _in_container: bool) -> Option<Symbol> {
87        if node.kind() != "method" {
88            return None;
89        }
90
91        let name = self.node_name(node, content)?;
92        let text = &content[node.byte_range()];
93
94        Some(Symbol {
95            name: name.to_string(),
96            kind: SymbolKind::Function,
97            signature: text.trim().to_string(),
98            docstring: None,
99            attributes: Vec::new(),
100            start_line: node.start_position().row + 1,
101            end_line: node.end_position().row + 1,
102            visibility: Visibility::Public,
103            children: Vec::new(),
104            is_interface_impl: false,
105            implements: Vec::new(),
106        })
107    }
108
109    fn extract_container(&self, node: &Node, content: &str) -> Option<Symbol> {
110        let kind = match node.kind() {
111            "struct" => SymbolKind::Struct,
112            "interface" => SymbolKind::Interface,
113            "enum" => SymbolKind::Enum,
114            _ => return None,
115        };
116
117        let name = self.node_name(node, content)?;
118        let text = &content[node.byte_range()];
119        let first_line = text.lines().next().unwrap_or(text);
120
121        Some(Symbol {
122            name: name.to_string(),
123            kind,
124            signature: first_line.trim().to_string(),
125            docstring: None,
126            attributes: Vec::new(),
127            start_line: node.start_position().row + 1,
128            end_line: node.end_position().row + 1,
129            visibility: Visibility::Public,
130            children: Vec::new(),
131            is_interface_impl: false,
132            implements: Vec::new(),
133        })
134    }
135
136    fn extract_type(&self, node: &Node, content: &str) -> Option<Symbol> {
137        self.extract_container(node, content)
138    }
139
140    fn extract_docstring(&self, _node: &Node, _content: &str) -> Option<String> {
141        None
142    }
143
144    fn extract_attributes(&self, _node: &Node, _content: &str) -> Vec<String> {
145        Vec::new()
146    }
147
148    fn extract_imports(&self, node: &Node, content: &str) -> Vec<Import> {
149        if node.kind() != "import" {
150            return Vec::new();
151        }
152
153        let text = &content[node.byte_range()];
154        vec![Import {
155            module: text.trim().to_string(),
156            names: Vec::new(),
157            alias: None,
158            is_wildcard: false,
159            is_relative: false,
160            line: node.start_position().row + 1,
161        }]
162    }
163
164    fn format_import(&self, import: &Import, _names: Option<&[&str]>) -> String {
165        // Cap'n Proto: using import "file.capnp"
166        format!("using import \"{}\"", import.module)
167    }
168
169    fn is_public(&self, _node: &Node, _content: &str) -> bool {
170        true
171    }
172    fn get_visibility(&self, _node: &Node, _content: &str) -> Visibility {
173        Visibility::Public
174    }
175
176    fn is_test_symbol(&self, _symbol: &crate::Symbol) -> bool {
177        false
178    }
179
180    fn embedded_content(&self, _node: &Node, _content: &str) -> Option<crate::EmbeddedBlock> {
181        None
182    }
183
184    fn container_body<'a>(&self, node: &'a Node<'a>) -> Option<Node<'a>> {
185        node.child_by_field_name("body")
186    }
187
188    fn body_has_docstring(&self, _body: &Node, _content: &str) -> bool {
189        false
190    }
191
192    fn node_name<'a>(&self, node: &Node, content: &'a str) -> Option<&'a str> {
193        node.child_by_field_name("name")
194            .map(|n| &content[n.byte_range()])
195    }
196
197    fn file_path_to_module_name(&self, path: &Path) -> Option<String> {
198        let ext = path.extension()?.to_str()?;
199        if ext != "capnp" {
200            return None;
201        }
202        let stem = path.file_stem()?.to_str()?;
203        Some(stem.to_string())
204    }
205
206    fn module_name_to_paths(&self, module: &str) -> Vec<String> {
207        vec![format!("{}.capnp", module)]
208    }
209
210    fn lang_key(&self) -> &'static str {
211        "capnp"
212    }
213
214    fn is_stdlib_import(&self, _: &str, _: &Path) -> bool {
215        false
216    }
217    fn find_stdlib(&self, _: &Path) -> Option<PathBuf> {
218        None
219    }
220    fn resolve_local_import(&self, _: &str, _: &Path, _: &Path) -> Option<PathBuf> {
221        None
222    }
223    fn resolve_external_import(&self, _: &str, _: &Path) -> Option<ResolvedPackage> {
224        None
225    }
226    fn get_version(&self, _: &Path) -> Option<String> {
227        None
228    }
229    fn find_package_cache(&self, _: &Path) -> Option<PathBuf> {
230        None
231    }
232    fn indexable_extensions(&self) -> &'static [&'static str] {
233        &["capnp"]
234    }
235    fn package_sources(&self, _: &Path) -> Vec<crate::PackageSource> {
236        Vec::new()
237    }
238
239    fn should_skip_package_entry(&self, name: &str, is_dir: bool) -> bool {
240        use crate::traits::{has_extension, skip_dotfiles};
241        if skip_dotfiles(name) {
242            return true;
243        }
244        !is_dir && !has_extension(name, self.indexable_extensions())
245    }
246
247    fn discover_packages(&self, _: &crate::PackageSource) -> Vec<(String, PathBuf)> {
248        Vec::new()
249    }
250
251    fn package_module_name(&self, entry_name: &str) -> String {
252        entry_name
253            .strip_suffix(".capnp")
254            .unwrap_or(entry_name)
255            .to_string()
256    }
257
258    fn find_package_entry(&self, path: &Path) -> Option<PathBuf> {
259        if path.is_file() {
260            Some(path.to_path_buf())
261        } else {
262            None
263        }
264    }
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270    use crate::validate_unused_kinds_audit;
271
272    #[test]
273    fn unused_node_kinds_audit() {
274        #[rustfmt::skip]
275        let documented_unused: &[&str] = &[
276            // Type-related
277            "type_identifier", "type_definition", "primitive_type", "list_type",
278            "custom_type", "field_type", "extend_type",
279            // Method-related
280            "method_identifier", "method_parameters", "return_type", "return_identifier",
281            "named_return_type", "named_return_types", "unnamed_return_type", "param_identifier",
282            // Struct/enum-related
283            "nested_struct", "nested_enum", "enum_field", "enum_member", "enum_identifier",
284            "field_identifier", "struct_shorthand",
285            // Import-related
286            "import_path", "import_using",
287            // Other
288            "const_identifier", "generic_identifier", "annotation_identifier",
289            "annotation_definition_identifier", "unique_id_statement",
290            "top_level_annotation_body", "block_text",
291        ];
292        validate_unused_kinds_audit(&Capnp, documented_unused)
293            .expect("Cap'n Proto unused node kinds audit failed");
294    }
295}