panproto_parse/languages/common.rs
1//! Common language parser implementation shared by all tree-sitter-based parsers.
2//!
3//! Since the generic [`AstWalker`](crate::walker::AstWalker) handles all languages
4//! uniformly (the node kind IS the vertex kind, the field name IS the edge kind),
5//! per-language parsers are thin wrappers that provide:
6//!
7//! 1. The tree-sitter Language object
8//! 2. The embedded `NODE_TYPES` JSON
9//! 3. Language-specific [`WalkerConfig`](crate::walker::WalkerConfig) overrides
10//! 4. File extension mapping
11
12use std::sync::{Arc, Mutex, OnceLock};
13
14use panproto_schema::{Protocol, Schema};
15
16use crate::emit_pretty::{FormatPolicy, Grammar as EmitGrammar, emit_pretty as emit_pretty_inner};
17use crate::error::ParseError;
18use crate::registry::AstParser;
19use crate::scope_detector::ScopeDetector;
20use crate::theory_extract::{ExtractedTheoryMeta, extract_theory_from_node_types};
21use crate::walker::{AstWalker, WalkerConfig};
22
23/// A generic language parser built from a tree-sitter grammar.
24///
25/// This struct is the shared implementation behind all language parsers.
26/// Each language constructs one with its specific grammar, node types,
27/// tags query, and config.
28pub struct LanguageParser {
29 /// The protocol name (e.g. `"typescript"`, `"python"`).
30 protocol_name: String,
31 /// File extensions this language handles.
32 extensions: Vec<&'static str>,
33 /// The resolved tree-sitter language.
34 language: tree_sitter::Language,
35 /// The grammar's bundled `tags.scm`, if any (for named-scope detection).
36 tags_query: Option<&'static str>,
37 /// Project-level tags-query override (concatenated in front of
38 /// `tags_query` when constructing the [`ScopeDetector`]).
39 project_tags_override: Option<String>,
40 /// The auto-derived theory metadata.
41 theory_meta: ExtractedTheoryMeta,
42 /// The panproto protocol definition (used for `SchemaBuilder` validation).
43 protocol: Protocol,
44 /// Per-language walker configuration.
45 walker_config: WalkerConfig,
46 /// A reusable [`ScopeDetector`] for this language.
47 ///
48 /// Held behind a `Mutex` because `parse()` on [`AstParser`] takes `&self`
49 /// but the detector's `TagsContext` (and internal `QueryCursor`) need
50 /// `&mut` access during a tags query run. A single parser instance is
51 /// typically used serially; contention here is rare.
52 scope_detector: Mutex<ScopeDetector>,
53 /// Raw `grammar.json` bytes for the de-novo emit walker. `None`
54 /// when the upstream grammar does not ship `grammar.json` and
55 /// `tools/fetch-grammar-json.py` could not regenerate one.
56 grammar_json: Option<&'static [u8]>,
57 /// Raw `node-types.json` bytes for augmenting the Grammar's subtype
58 /// closure with parser-produced child kinds not in grammar.json.
59 node_types_json_for_emit: Option<Vec<u8>>,
60 /// Lazily-parsed grammar. Populated on first call to `emit_pretty`.
61 grammar_cache: OnceLock<Result<EmitGrammar, ParseError>>,
62 /// Per-grammar defaults for opaque external scanner tokens.
63 cassette: Arc<dyn super::cassettes::GrammarCassette>,
64}
65
66impl LanguageParser {
67 /// Create a new language parser from a pre-constructed [`Language`](tree_sitter::Language).
68 ///
69 /// `tags_query` is the grammar's `queries/tags.scm` content, usually
70 /// sourced from [`panproto_grammars::Grammar::tags_query`]; pass `None`
71 /// if the grammar does not ship one.
72 ///
73 /// # Errors
74 ///
75 /// Returns [`ParseError`] if theory extraction from `node_types_json`
76 /// fails, or if the grammar's tags query fails to compile.
77 pub fn from_language(
78 protocol_name: &str,
79 extensions: Vec<&'static str>,
80 language: tree_sitter::Language,
81 node_types_json: &[u8],
82 tags_query: Option<&'static str>,
83 walker_config: WalkerConfig,
84 ) -> Result<Self, ParseError> {
85 Self::from_language_with_grammar_json(
86 protocol_name,
87 extensions,
88 language,
89 node_types_json,
90 tags_query,
91 walker_config,
92 None,
93 )
94 }
95
96 /// Construct a `LanguageParser` with vendored `grammar.json` bytes
97 /// for de-novo emission via [`AstParser::emit_pretty`].
98 ///
99 /// `grammar_json` should come from
100 /// [`panproto_grammars::Grammar::grammar_json`]; pass `None` to
101 /// signal that the language has no production-rule table available.
102 /// Without it, `emit_pretty` returns
103 /// [`ParseError::EmitFailed`] with a `grammar.json missing` reason.
104 ///
105 /// # Errors
106 ///
107 /// Returns [`ParseError`] if theory extraction from
108 /// `node_types_json` fails or if the tags query rejects compilation.
109 pub fn from_language_with_grammar_json(
110 protocol_name: &str,
111 extensions: Vec<&'static str>,
112 language: tree_sitter::Language,
113 node_types_json: &[u8],
114 tags_query: Option<&'static str>,
115 walker_config: WalkerConfig,
116 grammar_json: Option<&'static [u8]>,
117 ) -> Result<Self, ParseError> {
118 let theory_name = format!("Th{}FullAST", capitalize_first(protocol_name));
119 let theory_meta = extract_theory_from_node_types(&theory_name, node_types_json)?;
120 let protocol = build_full_ast_protocol(protocol_name, &theory_name);
121 let scope_detector = ScopeDetector::new(&language, tags_query, None)?;
122
123 Ok(Self {
124 protocol_name: protocol_name.to_owned(),
125 extensions,
126 language,
127 tags_query,
128 project_tags_override: None,
129 theory_meta,
130 protocol,
131 walker_config,
132 scope_detector: Mutex::new(scope_detector),
133 grammar_json,
134 node_types_json_for_emit: Some(node_types_json.to_vec()),
135 grammar_cache: OnceLock::new(),
136 cassette: super::cassettes::cassette_for(protocol_name),
137 })
138 }
139
140 /// Install a project-level tags-query override.
141 ///
142 /// The override string is concatenated in front of the grammar's
143 /// bundled `tags.scm` when the detector is rebuilt. Tree-sitter unions
144 /// all patterns, so overrides augment the defaults without replacing
145 /// them. Pass `None` to clear an existing override.
146 ///
147 /// Typical source: `panproto.toml`'s `[parse.tags.<lang>] path = "..."`.
148 ///
149 /// # Errors
150 ///
151 /// Returns [`ParseError::ScopeQueryCompile`] if the combined query
152 /// fails to compile against this language.
153 pub fn set_tags_override(&mut self, override_query: Option<String>) -> Result<(), ParseError> {
154 let detector =
155 ScopeDetector::new(&self.language, self.tags_query, override_query.as_deref())?;
156 self.project_tags_override = override_query;
157 if let Ok(mut guard) = self.scope_detector.lock() {
158 *guard = detector;
159 }
160 Ok(())
161 }
162}
163
164impl AstParser for LanguageParser {
165 fn protocol_name(&self) -> &str {
166 &self.protocol_name
167 }
168
169 fn parse(&self, source: &[u8], file_path: &str) -> Result<Schema, ParseError> {
170 let mut parser = tree_sitter::Parser::new();
171 parser
172 .set_language(&self.language)
173 .map_err(|e| ParseError::TreeSitterParse {
174 path: format!("{file_path}: set_language failed: {e}"),
175 })?;
176
177 let tree = parser
178 .parse(source, None)
179 .ok_or_else(|| ParseError::TreeSitterParse {
180 path: format!("{file_path}: parse returned None (timeout or cancellation)"),
181 })?;
182
183 // Build the walker (which runs the tags query once via the
184 // detector) inside the guard scope, then drop the guard before
185 // walking the tree. The scope map is copied into the walker, so
186 // the detector lock is no longer needed past that point.
187 let walker = {
188 let mut detector_guard =
189 self.scope_detector
190 .lock()
191 .map_err(|_| ParseError::SchemaConstruction {
192 reason: "scope-detector mutex poisoned".to_owned(),
193 })?;
194 AstWalker::new(
195 source,
196 &self.theory_meta,
197 &self.protocol,
198 self.walker_config.clone(),
199 Some(&mut *detector_guard),
200 )
201 };
202
203 walker.walk(&tree, file_path)
204 }
205
206 fn emit(&self, schema: &Schema) -> Result<Vec<u8>, ParseError> {
207 // Reconstruct source text from the schema's structural information.
208 //
209 // The walker stores two types of text constraints:
210 // 1. `literal-value` on leaf nodes: the source text of identifiers, literals, etc.
211 // 2. `interstitial-N` on parent nodes: the text between named children, which
212 // contains keywords, punctuation, whitespace, and comments.
213 //
214 // The emitter walks the schema tree depth-first, interleaving interstitial text
215 // with child emissions to reconstruct the full source.
216 emit_from_schema(schema, &self.protocol_name)
217 }
218
219 fn supported_extensions(&self) -> &[&str] {
220 &self.extensions
221 }
222
223 fn theory_meta(&self) -> &ExtractedTheoryMeta {
224 &self.theory_meta
225 }
226
227 fn emit_pretty_with_policy(
228 &self,
229 schema: &Schema,
230 policy: &FormatPolicy,
231 ) -> Result<Vec<u8>, ParseError> {
232 let bytes = self.grammar_json.ok_or_else(|| ParseError::EmitFailed {
233 protocol: self.protocol_name.clone(),
234 reason: "grammar.json not vendored for this protocol; \
235 run tools/fetch-grammar-json.py to populate it"
236 .to_owned(),
237 })?;
238 let nt = self.node_types_json_for_emit.as_deref();
239 let cached = self.grammar_cache.get_or_init(|| {
240 EmitGrammar::from_bytes_with_node_types(&self.protocol_name, bytes, nt)
241 });
242 let grammar = match cached {
243 Ok(g) => g,
244 Err(e) => {
245 return Err(ParseError::EmitFailed {
246 protocol: self.protocol_name.clone(),
247 reason: format!("grammar.json parse failed: {e}"),
248 });
249 }
250 };
251 emit_pretty_inner(
252 &self.protocol_name,
253 schema,
254 grammar,
255 policy,
256 Some(&*self.cassette),
257 )
258 }
259}
260
261/// Reconstruct source text from a schema using interstitial text and leaf literals.
262///
263/// The walker stores two types of text data:
264/// - `literal-value` on leaf nodes: identifiers, literals, keywords that are named nodes
265/// - `interstitial-N` on parent nodes: text between named children (keywords, punctuation,
266/// whitespace, comments from anonymous/unnamed tokens)
267///
268/// The emitter reconstructs source by collecting ALL text fragments (both interstitials
269/// and leaf literals) and sorting them by their byte position in the original source.
270/// This produces exact round-trip fidelity: `emit(parse(source))` = `source`.
271fn emit_from_schema(schema: &Schema, protocol: &str) -> Result<Vec<u8>, ParseError> {
272 // Collect all text fragments with their byte positions.
273 // Each fragment is (start_byte, text).
274 let mut fragments: Vec<(usize, String)> = Vec::new();
275
276 for name in schema.vertices.keys() {
277 if let Some(constraints) = schema.constraints.get(name) {
278 // Get start-byte for this vertex.
279 let start_byte = constraints
280 .iter()
281 .find(|c| c.sort.as_ref() == "start-byte")
282 .and_then(|c| c.value.parse::<usize>().ok());
283
284 // Collect literal-value from leaf nodes.
285 let literal = constraints
286 .iter()
287 .find(|c| c.sort.as_ref() == "literal-value")
288 .map(|c| c.value.clone());
289
290 if let (Some(start), Some(text)) = (start_byte, literal) {
291 fragments.push((start, text));
292 }
293
294 // Collect interstitial text fragments.
295 // Each interstitial has a byte position derived from its parent and index.
296 for c in constraints {
297 let sort_str = c.sort.as_ref();
298 if sort_str.starts_with("interstitial-") {
299 // The interstitial's position is encoded in a companion constraint.
300 // We stored interstitial-N-start-byte alongside interstitial-N.
301 let pos_sort = format!("{sort_str}-start-byte");
302 let pos = constraints
303 .iter()
304 .find(|c2| c2.sort.as_ref() == pos_sort.as_str())
305 .and_then(|c2| c2.value.parse::<usize>().ok());
306
307 if let Some(p) = pos {
308 fragments.push((p, c.value.clone()));
309 }
310 }
311 }
312 }
313 }
314
315 if fragments.is_empty() {
316 return Err(ParseError::EmitFailed {
317 protocol: protocol.to_owned(),
318 reason: "schema has no text fragments".to_owned(),
319 });
320 }
321
322 // Sort by byte position and concatenate.
323 fragments.sort_by_key(|(pos, _)| *pos);
324
325 // Deduplicate overlapping fragments (parent interstitials may overlap with
326 // child literals). Keep the first fragment at each position.
327 let mut output = Vec::new();
328 let mut cursor = 0;
329
330 for (pos, text) in &fragments {
331 if *pos >= cursor {
332 output.extend_from_slice(text.as_bytes());
333 cursor = pos + text.len();
334 }
335 }
336
337 Ok(output)
338}
339
340/// Build the standard Protocol for a full-AST language parser.
341///
342/// Shared by `LanguageParser::new` and `LanguageParser::from_language`
343/// to avoid duplicating the constraint sorts and flag definitions.
344fn build_full_ast_protocol(protocol_name: &str, theory_name: &str) -> Protocol {
345 Protocol {
346 name: protocol_name.into(),
347 schema_theory: theory_name.into(),
348 instance_theory: format!("{theory_name}Instance"),
349 schema_composition: None,
350 instance_composition: None,
351 obj_kinds: vec![],
352 edge_rules: vec![],
353 constraint_sorts: vec![
354 "literal-value".into(),
355 "literal-type".into(),
356 "operator".into(),
357 "visibility".into(),
358 "mutability".into(),
359 "async".into(),
360 "static".into(),
361 "generator".into(),
362 "comment".into(),
363 "indent".into(),
364 "trailing-comma".into(),
365 "semicolon".into(),
366 "blank-lines-before".into(),
367 "start-byte".into(),
368 "end-byte".into(),
369 ],
370 has_order: true,
371 has_coproducts: false,
372 has_recursion: true,
373 has_causal: false,
374 nominal_identity: false,
375 has_defaults: false,
376 has_coercions: false,
377 has_mergers: false,
378 has_policies: false,
379 }
380}
381
382/// Capitalize the first letter of a string.
383fn capitalize_first(s: &str) -> String {
384 let mut chars = s.chars();
385 chars.next().map_or_else(String::new, |c| {
386 c.to_uppercase().collect::<String>() + chars.as_str()
387 })
388}