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
43/// Registry of all full-AST parsers, keyed by protocol name.
44///
45/// Provides language detection by file extension and dispatches parse/emit
46/// operations to the appropriate language parser.
47pub struct ParserRegistry {
48 /// Parsers keyed by protocol name.
49 parsers: FxHashMap<String, Box<dyn AstParser>>,
50 /// Extension → protocol name mapping.
51 extension_map: FxHashMap<String, String>,
52}
53
54impl ParserRegistry {
55 /// Create a new registry populated with all enabled language parsers.
56 ///
57 /// The set of languages depends on which `panproto-grammars` feature flags
58 /// are enabled. The default is `group-core` (GitHub's top 10 languages).
59 /// Use `group-all` for all 248 supported languages.
60 #[must_use]
61 pub fn new() -> Self {
62 let mut registry = Self {
63 parsers: FxHashMap::default(),
64 extension_map: FxHashMap::default(),
65 };
66
67 for grammar in panproto_grammars::grammars() {
68 let config = crate::languages::walker_configs::walker_config_for(grammar.name);
69 match crate::languages::common::LanguageParser::from_language(
70 grammar.name,
71 grammar.extensions.to_vec(),
72 grammar.language,
73 grammar.node_types,
74 config,
75 ) {
76 Ok(p) => registry.register(Box::new(p)),
77 Err(err) => {
78 #[cfg(debug_assertions)]
79 eprintln!(
80 "warning: grammar '{}' theory extraction failed: {err}",
81 grammar.name
82 );
83 }
84 }
85 }
86
87 registry
88 }
89
90 /// Register a parser implementation.
91 pub fn register(&mut self, parser: Box<dyn AstParser>) {
92 let name = parser.protocol_name().to_owned();
93 for ext in parser.supported_extensions() {
94 self.extension_map.insert((*ext).to_owned(), name.clone());
95 }
96 self.parsers.insert(name, parser);
97 }
98
99 /// Detect the language protocol for a file path by its extension.
100 ///
101 /// Returns `None` if the extension is not recognized (caller should
102 /// fall back to the `raw_file` protocol).
103 #[must_use]
104 pub fn detect_language(&self, path: &Path) -> Option<&str> {
105 path.extension()
106 .and_then(|ext| ext.to_str())
107 .and_then(|ext| self.extension_map.get(ext))
108 .map(String::as_str)
109 }
110
111 /// Parse a file by detecting its language from the file path.
112 ///
113 /// # Errors
114 ///
115 /// Returns [`ParseError::UnknownLanguage`] if the file extension is not recognized.
116 /// Returns other [`ParseError`] variants if parsing fails.
117 pub fn parse_file(&self, path: &Path, content: &[u8]) -> Result<Schema, ParseError> {
118 let protocol = self
119 .detect_language(path)
120 .ok_or_else(|| ParseError::UnknownLanguage {
121 extension: path
122 .extension()
123 .and_then(|e| e.to_str())
124 .unwrap_or("")
125 .to_owned(),
126 })?;
127
128 self.parse_with_protocol(protocol, content, &path.display().to_string())
129 }
130
131 /// Parse source code with a specific protocol name.
132 ///
133 /// # Errors
134 ///
135 /// Returns [`ParseError::UnknownLanguage`] if the protocol is not registered.
136 pub fn parse_with_protocol(
137 &self,
138 protocol: &str,
139 content: &[u8],
140 file_path: &str,
141 ) -> Result<Schema, ParseError> {
142 let parser = self
143 .parsers
144 .get(protocol)
145 .ok_or_else(|| ParseError::UnknownLanguage {
146 extension: protocol.to_owned(),
147 })?;
148
149 parser.parse(content, file_path)
150 }
151
152 /// Emit a schema back to source code bytes using the specified protocol.
153 ///
154 /// # Errors
155 ///
156 /// Returns [`ParseError::UnknownLanguage`] if the protocol is not registered.
157 pub fn emit_with_protocol(
158 &self,
159 protocol: &str,
160 schema: &Schema,
161 ) -> Result<Vec<u8>, ParseError> {
162 let parser = self
163 .parsers
164 .get(protocol)
165 .ok_or_else(|| ParseError::UnknownLanguage {
166 extension: protocol.to_owned(),
167 })?;
168
169 parser.emit(schema)
170 }
171
172 /// Get the theory metadata for a specific protocol.
173 #[must_use]
174 pub fn theory_meta(&self, protocol: &str) -> Option<&ExtractedTheoryMeta> {
175 self.parsers.get(protocol).map(|p| p.theory_meta())
176 }
177
178 /// List all registered protocol names.
179 pub fn protocol_names(&self) -> impl Iterator<Item = &str> {
180 self.parsers.keys().map(String::as_str)
181 }
182
183 /// Get the number of registered parsers.
184 #[must_use]
185 pub fn len(&self) -> usize {
186 self.parsers.len()
187 }
188
189 /// Check if the registry is empty.
190 #[must_use]
191 pub fn is_empty(&self) -> bool {
192 self.parsers.is_empty()
193 }
194}
195
196impl Default for ParserRegistry {
197 fn default() -> Self {
198 Self::new()
199 }
200}