Skip to main content

panproto_parse/
registry.rs

1//! Parser registry mapping protocol names to full-AST parser implementations.
2
3use std::path::Path;
4
5use panproto_schema::Schema;
6use rustc_hash::FxHashMap;
7
8use crate::error::ParseError;
9use crate::theory_extract::ExtractedTheoryMeta;
10
11/// A full-AST parser and emitter for a specific programming language.
12///
13/// Each implementation wraps a tree-sitter grammar and its auto-derived theory,
14/// providing parse (source → Schema) and emit (Schema → source) operations.
15pub trait AstParser: Send + Sync {
16    /// The panproto protocol name (e.g. `"typescript"`, `"python"`).
17    fn protocol_name(&self) -> &str;
18
19    /// Parse source code into a full-AST [`Schema`].
20    ///
21    /// # Errors
22    ///
23    /// Returns [`ParseError`] if tree-sitter parsing fails or schema construction fails.
24    fn parse(&self, source: &[u8], file_path: &str) -> Result<Schema, ParseError>;
25
26    /// Emit a [`Schema`] back to source code bytes.
27    ///
28    /// The emitter walks the schema graph top-down, using formatting constraints
29    /// (comment, indent, blank-lines-before) to reproduce the original formatting.
30    ///
31    /// # Errors
32    ///
33    /// Returns [`ParseError::EmitFailed`] if emission fails.
34    fn emit(&self, schema: &Schema) -> Result<Vec<u8>, ParseError>;
35
36    /// File extensions this parser handles (e.g. `["ts", "tsx"]`).
37    fn supported_extensions(&self) -> &[&str];
38
39    /// The auto-derived theory metadata for this language.
40    fn theory_meta(&self) -> &ExtractedTheoryMeta;
41
42    /// Render a by-construction [`Schema`] (one with no parse-recovered
43    /// byte positions or interstitials) to source bytes.
44    ///
45    /// Unlike [`emit`](Self::emit), which reconstructs source from
46    /// byte-position fragments stored on the schema during `parse`,
47    /// `emit_pretty` walks tree-sitter `grammar.json` production rules
48    /// to render schemas built from scratch via `SchemaBuilder`.
49    ///
50    /// # Errors
51    ///
52    /// Returns [`ParseError::EmitFailed`] when the language has no
53    /// vendored `grammar.json`, when a vertex's kind is not a grammar
54    /// rule, or when a required field has no corresponding schema edge.
55    fn emit_pretty(&self, schema: &Schema) -> Result<Vec<u8>, ParseError> {
56        let _ = schema;
57        Err(ParseError::EmitFailed {
58            protocol: self.protocol_name().to_owned(),
59            reason: format!(
60                "emit_pretty not implemented for protocol '{}'",
61                self.protocol_name()
62            ),
63        })
64    }
65}
66
67/// Registry of all full-AST parsers, keyed by protocol name.
68///
69/// Provides language detection by file extension and dispatches parse/emit
70/// operations to the appropriate language parser.
71pub struct ParserRegistry {
72    /// Parsers keyed by protocol name.
73    parsers: FxHashMap<String, Box<dyn AstParser>>,
74    /// Extension → protocol name mapping.
75    extension_map: FxHashMap<String, String>,
76}
77
78impl ParserRegistry {
79    /// Create a new registry populated with all enabled language parsers.
80    ///
81    /// With the `grammars` feature (default), this populates the registry from
82    /// `panproto-grammars`, which provides up to 248 tree-sitter languages.
83    /// Without the `grammars` feature, this returns an empty registry; call
84    /// [`register`](Self::register) to add parsers manually using individual
85    /// grammar crates.
86    #[must_use]
87    pub fn new() -> Self {
88        let mut registry = Self {
89            parsers: FxHashMap::default(),
90            extension_map: FxHashMap::default(),
91        };
92
93        #[cfg(feature = "grammars")]
94        for grammar in panproto_grammars::grammars() {
95            let config = crate::languages::walker_configs::walker_config_for(grammar.name);
96            match crate::languages::common::LanguageParser::from_language_with_grammar_json(
97                grammar.name,
98                grammar.extensions.to_vec(),
99                grammar.language,
100                grammar.node_types,
101                grammar.tags_query,
102                config,
103                grammar.grammar_json,
104            ) {
105                Ok(p) => registry.register(Box::new(p)),
106                Err(err) => {
107                    let _ = err;
108                    #[cfg(debug_assertions)]
109                    eprintln!(
110                        "warning: grammar '{}' theory extraction failed: {err}",
111                        grammar.name
112                    );
113                }
114            }
115        }
116
117        registry
118    }
119
120    /// Register a parser implementation.
121    pub fn register(&mut self, parser: Box<dyn AstParser>) {
122        let name = parser.protocol_name().to_owned();
123        for ext in parser.supported_extensions() {
124            self.extension_map.insert((*ext).to_owned(), name.clone());
125        }
126        self.parsers.insert(name, parser);
127    }
128
129    /// Register a tree-sitter language as a full-AST parser.
130    ///
131    /// Used by `panproto-grammars-*` companion crates that ship grammars
132    /// outside the default `panproto-grammars` build. The byte-slice
133    /// arguments must outlive this registry; the canonical pattern is
134    /// for the companion to bake the data into `&'static` rodata at
135    /// compile time and pass references that are valid for the process
136    /// lifetime.
137    ///
138    /// `walker_config` is looked up by `name` from the bundled per-language
139    /// configuration table. Languages without a tailored configuration
140    /// fall back to the default walker config.
141    ///
142    /// # Errors
143    ///
144    /// Returns [`ParseError`] if theory extraction from `node_types_json`
145    /// fails or if the tags query rejects compilation.
146    pub fn register_external_grammar(
147        &mut self,
148        name: &'static str,
149        extensions: Vec<&'static str>,
150        language: tree_sitter::Language,
151        node_types_json: &'static [u8],
152        tags_query: Option<&'static str>,
153        grammar_json: Option<&'static [u8]>,
154    ) -> Result<(), crate::error::ParseError> {
155        let config = crate::languages::walker_configs::walker_config_for(name);
156        let parser = crate::languages::common::LanguageParser::from_language_with_grammar_json(
157            name,
158            extensions,
159            language,
160            node_types_json,
161            tags_query,
162            config,
163            grammar_json,
164        )?;
165        self.register(Box::new(parser));
166        Ok(())
167    }
168
169    /// Detect the language protocol for a file path by its extension.
170    ///
171    /// Returns `None` if the extension is not recognized (caller should
172    /// fall back to the `raw_file` protocol).
173    #[must_use]
174    pub fn detect_language(&self, path: &Path) -> Option<&str> {
175        path.extension()
176            .and_then(|ext| ext.to_str())
177            .and_then(|ext| self.extension_map.get(ext))
178            .map(String::as_str)
179    }
180
181    /// Parse a file by detecting its language from the file path.
182    ///
183    /// # Errors
184    ///
185    /// Returns [`ParseError::UnknownLanguage`] if the file extension is not recognized.
186    /// Returns other [`ParseError`] variants if parsing fails.
187    pub fn parse_file(&self, path: &Path, content: &[u8]) -> Result<Schema, ParseError> {
188        let protocol = self
189            .detect_language(path)
190            .ok_or_else(|| ParseError::UnknownLanguage {
191                extension: path
192                    .extension()
193                    .and_then(|e| e.to_str())
194                    .unwrap_or("")
195                    .to_owned(),
196            })?;
197
198        self.parse_with_protocol(protocol, content, &path.display().to_string())
199    }
200
201    /// Parse source code with a specific protocol name.
202    ///
203    /// # Errors
204    ///
205    /// Returns [`ParseError::UnknownLanguage`] if the protocol is not registered.
206    pub fn parse_with_protocol(
207        &self,
208        protocol: &str,
209        content: &[u8],
210        file_path: &str,
211    ) -> Result<Schema, ParseError> {
212        let parser = self
213            .parsers
214            .get(protocol)
215            .ok_or_else(|| ParseError::UnknownLanguage {
216                extension: protocol.to_owned(),
217            })?;
218
219        parser.parse(content, file_path)
220    }
221
222    /// Emit a schema back to source code bytes using the specified protocol.
223    ///
224    /// # Errors
225    ///
226    /// Returns [`ParseError::UnknownLanguage`] if the protocol is not registered.
227    pub fn emit_with_protocol(
228        &self,
229        protocol: &str,
230        schema: &Schema,
231    ) -> Result<Vec<u8>, ParseError> {
232        let parser = self
233            .parsers
234            .get(protocol)
235            .ok_or_else(|| ParseError::UnknownLanguage {
236                extension: protocol.to_owned(),
237            })?;
238
239        parser.emit(schema)
240    }
241
242    /// Render a by-construction schema using the named protocol.
243    ///
244    /// # Errors
245    ///
246    /// Returns [`ParseError::UnknownLanguage`] if the protocol is not
247    /// registered, or [`ParseError::EmitFailed`] from the underlying
248    /// parser's `emit_pretty`.
249    pub fn emit_pretty_with_protocol(
250        &self,
251        protocol: &str,
252        schema: &Schema,
253    ) -> Result<Vec<u8>, ParseError> {
254        let parser = self
255            .parsers
256            .get(protocol)
257            .ok_or_else(|| ParseError::UnknownLanguage {
258                extension: protocol.to_owned(),
259            })?;
260
261        parser.emit_pretty(schema)
262    }
263
264    /// Get the theory metadata for a specific protocol.
265    #[must_use]
266    pub fn theory_meta(&self, protocol: &str) -> Option<&ExtractedTheoryMeta> {
267        self.parsers.get(protocol).map(|p| p.theory_meta())
268    }
269
270    /// List all registered protocol names.
271    pub fn protocol_names(&self) -> impl Iterator<Item = &str> {
272        self.parsers.keys().map(String::as_str)
273    }
274
275    /// O(1) lookup: is a parser already registered for `protocol`?
276    ///
277    /// Useful for dedup at the registration boundary. The umbrella
278    /// `panproto-grammars-all` companion pack overlaps with both the
279    /// built-in core grammars and every per-group pack; callers can
280    /// short-circuit before re-registering rather than scanning
281    /// `protocol_names()` linearly.
282    #[must_use]
283    pub fn has_parser(&self, protocol: &str) -> bool {
284        self.parsers.contains_key(protocol)
285    }
286
287    /// Get the number of registered parsers.
288    #[must_use]
289    pub fn len(&self) -> usize {
290        self.parsers.len()
291    }
292
293    /// Check if the registry is empty.
294    #[must_use]
295    pub fn is_empty(&self) -> bool {
296        self.parsers.is_empty()
297    }
298}
299
300impl Default for ParserRegistry {
301    fn default() -> Self {
302        Self::new()
303    }
304}