panproto_parse/emit_pretty.rs
1#![allow(
2 clippy::module_name_repetitions,
3 clippy::too_many_lines,
4 clippy::too_many_arguments,
5 clippy::map_unwrap_or,
6 clippy::option_if_let_else,
7 clippy::elidable_lifetime_names,
8 clippy::items_after_statements,
9 clippy::needless_pass_by_value,
10 clippy::single_match_else,
11 clippy::manual_let_else,
12 clippy::match_same_arms,
13 clippy::missing_const_for_fn,
14 clippy::single_char_pattern,
15 clippy::naive_bytecount,
16 clippy::expect_used,
17 clippy::redundant_pub_crate,
18 clippy::used_underscore_binding,
19 clippy::redundant_field_names,
20 clippy::struct_field_names,
21 clippy::redundant_else,
22 clippy::similar_names
23)]
24
25//! De-novo source emission from a by-construction schema.
26//!
27//! [`AstParser::emit`] reconstructs source from byte-position fragments
28//! that the parser stored on the schema during `parse`. That works for
29//! edit pipelines (`parse → transform → emit`) but fails for schemas
30//! built by hand (`SchemaBuilder` with no parse history): they carry
31//! no `start-byte`, no `interstitial-N`, no `literal-value`, and the
32//! reconstructor returns `Err(EmitFailed { reason: "schema has no
33//! text fragments" })`.
34//!
35//! This module renders such schemas to source bytes by walking
36//! tree-sitter's `grammar.json` production rules. For each schema
37//! vertex of kind `K`, the walker looks up `K`'s production in the
38//! grammar and emits its body in order:
39//!
40//! - `STRING` nodes contribute literal token bytes directly.
41//! - `SYMBOL` and `FIELD` nodes recurse into the schema's children,
42//! matching by edge kind (which is the tree-sitter field name).
43//! - `SEQ` emits its members in order.
44//! - `CHOICE` picks the alternative whose head `SYMBOL` matches an
45//! actual child kind, or whose terminals appear in the rendered
46//! prefix; falls back to the first non-`BLANK` alternative when no
47//! alternative matches.
48//! - `REPEAT` and `REPEAT1` emit their content once per matching
49//! child edge in declared order.
50//! - `OPTIONAL` emits its content iff a corresponding child edge or
51//! constraint is populated.
52//! - `PATTERN` is a regex placeholder for variable-text terminals
53//! (identifiers, numbers, quoted strings). The walker emits a
54//! `literal-value` constraint when present and otherwise falls
55//! back to a placeholder derived from the regex shape.
56//! - `BLANK`, `TOKEN`, `IMMEDIATE_TOKEN`, `ALIAS`, `PREC*` are
57//! handled transparently (the inner content is emitted; the
58//! wrapper is dropped).
59//!
60//! Whitespace and indentation come from a `FormatPolicy` applied
61//! during emission. The default policy inserts a single space between
62//! adjacent tokens, a newline after `;` / `}` / `{`, and tracks an
63//! indent counter on `{` / `}` boundaries.
64//!
65//! Output is *syntactically valid* for any grammar that ships
66//! `grammar.json`. Idiomatic formatting (rustfmt-style spacing rules,
67//! per-language conventions) is a polish layer that lives outside
68//! this module.
69
70use std::collections::BTreeMap;
71
72use panproto_schema::{Edge, Schema};
73use serde::Deserialize;
74
75use crate::error::ParseError;
76
77// ═══════════════════════════════════════════════════════════════════
78// Grammar JSON model
79// ═══════════════════════════════════════════════════════════════════
80
81/// A single tree-sitter production rule.
82///
83/// Mirrors the shape emitted by `tree-sitter generate`: every node has
84/// a `type` discriminator that selects a structural variant. The
85/// untyped subset (`PATTERN`, `STRING`, `SYMBOL`, `BLANK`) handles
86/// terminals; the structural subset (`SEQ`, `CHOICE`, `REPEAT`,
87/// `REPEAT1`, `OPTIONAL`, `FIELD`, `ALIAS`, `TOKEN`,
88/// `IMMEDIATE_TOKEN`, `PREC*`) builds composite productions.
89#[derive(Debug, Clone, Deserialize)]
90#[serde(tag = "type")]
91#[non_exhaustive]
92pub enum Production {
93 /// Concatenation of productions.
94 #[serde(rename = "SEQ")]
95 Seq {
96 /// Ordered members; each is emitted in turn.
97 members: Vec<Self>,
98 },
99 /// Alternation between productions.
100 #[serde(rename = "CHOICE")]
101 Choice {
102 /// Alternatives; the walker picks one based on the schema's
103 /// children and constraints.
104 members: Vec<Self>,
105 },
106 /// Zero-or-more repetition.
107 #[serde(rename = "REPEAT")]
108 Repeat {
109 /// The repeated body.
110 content: Box<Self>,
111 },
112 /// One-or-more repetition.
113 #[serde(rename = "REPEAT1")]
114 Repeat1 {
115 /// The repeated body.
116 content: Box<Self>,
117 },
118 /// Optional inclusion (zero or one).
119 ///
120 /// Tree-sitter usually emits `OPTIONAL` as `CHOICE { content,
121 /// BLANK }`, but recent generator versions also emit explicit
122 /// `OPTIONAL` nodes; both shapes are accepted.
123 #[serde(rename = "OPTIONAL")]
124 Optional {
125 /// The optional body.
126 content: Box<Self>,
127 },
128 /// Reference to another rule by name.
129 #[serde(rename = "SYMBOL")]
130 Symbol {
131 /// Name of the referenced rule (matches a vertex kind on the
132 /// schema side).
133 name: String,
134 },
135 /// Literal token bytes.
136 #[serde(rename = "STRING")]
137 String {
138 /// The literal token. Emitted verbatim.
139 value: String,
140 },
141 /// Regex-matched terminal.
142 ///
143 /// At parse time this matches arbitrary bytes; at emit time the
144 /// walker substitutes a `literal-value` constraint when present
145 /// and falls back to a placeholder otherwise.
146 #[serde(rename = "PATTERN")]
147 Pattern {
148 /// The original regex.
149 value: String,
150 },
151 /// The empty production. Emits nothing.
152 #[serde(rename = "BLANK")]
153 Blank,
154 /// Named field over a content production.
155 ///
156 /// The field `name` matches an edge kind on the schema side; the
157 /// walker resolves the corresponding child vertex and recurses
158 /// into `content` with that child as context.
159 #[serde(rename = "FIELD")]
160 Field {
161 /// Field name (matches edge kind).
162 name: String,
163 /// The contents of the field.
164 content: Box<Self>,
165 },
166 /// An aliased production.
167 ///
168 /// `value` records the parser-visible kind; the walker emits
169 /// `content` and ignores the alias rename.
170 #[serde(rename = "ALIAS")]
171 Alias {
172 /// The aliased content.
173 content: Box<Self>,
174 /// Whether the alias is a named node.
175 #[serde(default)]
176 named: bool,
177 /// The alias's surface name.
178 #[serde(default)]
179 value: String,
180 },
181 /// A token wrapper.
182 ///
183 /// Tree-sitter uses `TOKEN` to mark a sub-rule as a single
184 /// lexical token; the walker emits the inner content unchanged.
185 #[serde(rename = "TOKEN")]
186 Token {
187 /// The wrapped content.
188 content: Box<Self>,
189 },
190 /// An immediate-token wrapper (no preceding whitespace).
191 ///
192 /// Treated like [`Production::Token`] for emit purposes.
193 #[serde(rename = "IMMEDIATE_TOKEN")]
194 ImmediateToken {
195 /// The wrapped content.
196 content: Box<Self>,
197 },
198 /// Precedence wrapper.
199 #[serde(rename = "PREC")]
200 Prec {
201 /// Precedence value (numeric or string). Ignored at emit time.
202 #[allow(dead_code)]
203 value: serde_json::Value,
204 /// The wrapped content.
205 content: Box<Self>,
206 },
207 /// Left-associative precedence wrapper.
208 #[serde(rename = "PREC_LEFT")]
209 PrecLeft {
210 /// Precedence value. Ignored at emit time.
211 #[allow(dead_code)]
212 value: serde_json::Value,
213 /// The wrapped content.
214 content: Box<Self>,
215 },
216 /// Right-associative precedence wrapper.
217 #[serde(rename = "PREC_RIGHT")]
218 PrecRight {
219 /// Precedence value. Ignored at emit time.
220 #[allow(dead_code)]
221 value: serde_json::Value,
222 /// The wrapped content.
223 content: Box<Self>,
224 },
225 /// Dynamic precedence wrapper.
226 #[serde(rename = "PREC_DYNAMIC")]
227 PrecDynamic {
228 /// Precedence value. Ignored at emit time.
229 #[allow(dead_code)]
230 value: serde_json::Value,
231 /// The wrapped content.
232 content: Box<Self>,
233 },
234 /// Reserved-word wrapper (tree-sitter ≥ 0.25).
235 ///
236 /// Tree-sitter's `RESERVED` rule marks an inner production as a
237 /// reserved-word context: the parser excludes the listed identifiers
238 /// from being treated as the inner symbol. The `context_name`
239 /// metadata names the reserved-word set; the emitter does not need
240 /// it (we are walking schema → bytes, not enforcing reserved-word
241 /// constraints), so we emit the inner content unchanged, the same
242 /// way [`Production::Token`] and [`Production::ImmediateToken`] do.
243 #[serde(rename = "RESERVED")]
244 Reserved {
245 /// The wrapped content.
246 content: Box<Self>,
247 /// Name of the reserved-word context. Ignored at emit time.
248 #[allow(dead_code)]
249 #[serde(default)]
250 context_name: String,
251 },
252}
253
254/// A grammar's production-rule table, deserialized from `grammar.json`.
255///
256/// Only the fields the emitter consumes are decoded; precedences,
257/// conflicts, externals, and other parser-only metadata are ignored.
258#[derive(Debug, Clone, Deserialize)]
259#[non_exhaustive]
260pub struct Grammar {
261 /// Grammar name (e.g. `"rust"`, `"typescript"`).
262 #[allow(dead_code)]
263 pub name: String,
264 /// Map from rule name (a vertex kind on the schema side) to
265 /// production. Entries are kept in lexical order so iteration
266 /// is deterministic.
267 pub rules: BTreeMap<String, Production>,
268 /// Supertypes declared in the grammar's `supertypes` field. A
269 /// supertype is a rule whose body is a `CHOICE` of `SYMBOL`
270 /// references; tree-sitter parsers report a node's kind as one
271 /// of the subtypes (e.g. `identifier`, `typed_parameter`) rather
272 /// than the supertype name (`parameter`), so the emitter needs to
273 /// know that a child kind in a subtype set should match the
274 /// supertype name when a SYMBOL references it.
275 #[serde(default, deserialize_with = "deserialize_supertypes")]
276 pub supertypes: std::collections::HashSet<String>,
277 /// Tree-sitter `extras` rules: the named symbols (typically comments)
278 /// that tree-sitter skips at parse time but records as children of the
279 /// surrounding vertex. They appear nowhere in the production grammar,
280 /// so the rule walker cannot reconcile them against the cursor — the
281 /// emit pass therefore drains them as a side channel: at vertex entry
282 /// and between REPEAT iterations any leading extras-kind edges are
283 /// consumed and emitted directly. The set is populated at
284 /// `Grammar::from_bytes` by collecting every `SYMBOL { name }` and
285 /// named `ALIAS { value, named: true }` under the top-level `extras`
286 /// array. Pattern-only extras (e.g. `\s` whitespace) are not vertex
287 /// kinds and are excluded.
288 #[serde(default, deserialize_with = "deserialize_extras")]
289 pub extras: std::collections::HashSet<String>,
290 /// Precomputed subtyping closure: `subtypes[symbol_name]` is the
291 /// set of vertex kinds that satisfy a SYMBOL `symbol_name`
292 /// reference on the schema side.
293 ///
294 /// Built once at [`Grammar::from_bytes`] time by walking each
295 /// hidden rule (`_`-prefixed), declared supertype, and named
296 /// `ALIAS { value: K, ... }` production to its leaf SYMBOLs and
297 /// recording the closure. This replaces the prior heuristic
298 /// `kind_satisfies_symbol` that walked the rule body on every
299 /// query: lookups are now O(1) and the relation is exactly the
300 /// transitive closure of "is reachable via hidden / supertype /
301 /// alias dispatch", with no over-expansion through non-hidden
302 /// non-supertype rule references.
303 #[serde(skip)]
304 pub subtypes: std::collections::HashMap<String, std::collections::HashSet<String>>,
305}
306
307fn deserialize_supertypes<'de, D>(
308 deserializer: D,
309) -> Result<std::collections::HashSet<String>, D::Error>
310where
311 D: serde::Deserializer<'de>,
312{
313 let entries: Vec<serde_json::Value> = Vec::deserialize(deserializer)?;
314 let mut out = std::collections::HashSet::new();
315 for entry in entries {
316 match entry {
317 serde_json::Value::String(s) => {
318 out.insert(s);
319 }
320 serde_json::Value::Object(map) => {
321 if let Some(serde_json::Value::String(name)) = map.get("name") {
322 out.insert(name.clone());
323 }
324 }
325 _ => {}
326 }
327 }
328 Ok(out)
329}
330
331fn deserialize_extras<'de, D>(
332 deserializer: D,
333) -> Result<std::collections::HashSet<String>, D::Error>
334where
335 D: serde::Deserializer<'de>,
336{
337 let entries: Vec<serde_json::Value> = Vec::deserialize(deserializer)?;
338 let mut out = std::collections::HashSet::new();
339 for entry in entries {
340 if let serde_json::Value::Object(map) = entry {
341 let ty = map.get("type").and_then(serde_json::Value::as_str);
342 match ty {
343 // SYMBOL { name: K } — the extras rule is a named symbol
344 // (typically `line_comment` / `block_comment`). The kind
345 // K appears as a real child vertex on the schema side.
346 Some("SYMBOL") => {
347 if let Some(serde_json::Value::String(name)) = map.get("name") {
348 out.insert(name.clone());
349 }
350 }
351 // ALIAS { content, value: V, named: true } — the extras
352 // rule renames its content; V is the kind on the schema.
353 Some("ALIAS") => {
354 let named = map
355 .get("named")
356 .and_then(serde_json::Value::as_bool)
357 .unwrap_or(false);
358 if named {
359 if let Some(serde_json::Value::String(value)) = map.get("value") {
360 out.insert(value.clone());
361 }
362 }
363 }
364 // PATTERN / STRING / TOKEN entries describe inter-token
365 // whitespace and have no vertex-side representation.
366 _ => {}
367 }
368 }
369 }
370 Ok(out)
371}
372
373impl Grammar {
374 /// Parse a grammar's `grammar.json` bytes.
375 ///
376 /// Builds the subtyping closure as part of construction so every
377 /// downstream lookup is O(1). The closure is the least relation
378 /// containing `(K, K)` for every rule key `K` and closed under:
379 ///
380 /// - hidden-rule expansion: if `S` is hidden and a SYMBOL `S` may
381 /// reach SYMBOL `K`, then `K ⊑ S`.
382 /// - supertype expansion: if `S` is in the grammar's supertypes
383 /// block and `K` is one of `S`'s alternatives, then `K ⊑ S`.
384 /// - alias renaming: if a rule body contains
385 /// `ALIAS { content: SYMBOL R, value: A, named: true }` where
386 /// `R` reaches kind `K` (or `K = R` when no further hop), then
387 /// `A ⊑ R` and `K ⊑ A`.
388 ///
389 /// # Errors
390 ///
391 /// Returns [`ParseError::EmitFailed`] when the bytes are not a
392 /// valid `grammar.json` document.
393 pub fn from_bytes(protocol: &str, bytes: &[u8]) -> Result<Self, ParseError> {
394 let mut grammar: Self =
395 serde_json::from_slice(bytes).map_err(|e| ParseError::EmitFailed {
396 protocol: protocol.to_owned(),
397 reason: format!("grammar.json deserialization failed: {e}"),
398 })?;
399 grammar.subtypes = compute_subtype_closure(&grammar);
400 Ok(grammar)
401 }
402}
403
404/// Compute the subtyping relation as a forward-indexed map from a
405/// SYMBOL name to the set of vertex kinds that satisfy that SYMBOL.
406fn compute_subtype_closure(
407 grammar: &Grammar,
408) -> std::collections::HashMap<String, std::collections::HashSet<String>> {
409 use std::collections::{HashMap, HashSet};
410 // Edges of the "kind X satisfies SYMBOL Y" relation. `K ⊑ Y` is
411 // recorded whenever Y is reached by walking the grammar's
412 // ALIAS / hidden-rule / supertype dispatch from a position where
413 // K is the actual vertex kind.
414 let mut subtypes: HashMap<String, HashSet<String>> = HashMap::new();
415 for name in grammar.rules.keys() {
416 subtypes
417 .entry(name.clone())
418 .or_default()
419 .insert(name.clone());
420 }
421
422 // First pass: collect the immediate "satisfies" edges from each
423 // expandable rule (hidden, supertype) to the kinds reachable by
424 // walking its body, plus alias edges.
425 fn walk<'g>(
426 grammar: &'g Grammar,
427 production: &'g Production,
428 visited: &mut HashSet<&'g str>,
429 out: &mut HashSet<String>,
430 ) {
431 match production {
432 Production::Symbol { name } => {
433 // Direct subtype.
434 out.insert(name.clone());
435 // Continue expansion through hidden / supertype rules
436 // so the closure traverses pass-through dispatch.
437 let expand = name.starts_with('_') || grammar.supertypes.contains(name.as_str());
438 if expand && visited.insert(name.as_str()) {
439 if let Some(rule) = grammar.rules.get(name) {
440 walk(grammar, rule, visited, out);
441 }
442 }
443 }
444 Production::Choice { members } | Production::Seq { members } => {
445 for m in members {
446 walk(grammar, m, visited, out);
447 }
448 }
449 Production::Alias {
450 content,
451 named,
452 value,
453 } => {
454 if *named && !value.is_empty() {
455 out.insert(value.clone());
456 }
457 walk(grammar, content, visited, out);
458 }
459 Production::Repeat { content }
460 | Production::Repeat1 { content }
461 | Production::Optional { content }
462 | Production::Field { content, .. }
463 | Production::Token { content }
464 | Production::ImmediateToken { content }
465 | Production::Prec { content, .. }
466 | Production::PrecLeft { content, .. }
467 | Production::PrecRight { content, .. }
468 | Production::PrecDynamic { content, .. }
469 | Production::Reserved { content, .. } => {
470 walk(grammar, content, visited, out);
471 }
472 _ => {}
473 }
474 }
475
476 for (name, rule) in &grammar.rules {
477 let expand = name.starts_with('_') || grammar.supertypes.contains(name.as_str());
478 if !expand {
479 continue;
480 }
481 let mut visited: HashSet<&str> = HashSet::new();
482 visited.insert(name.as_str());
483 let mut reachable: HashSet<String> = HashSet::new();
484 walk(grammar, rule, &mut visited, &mut reachable);
485 for kind in &reachable {
486 subtypes
487 .entry(kind.clone())
488 .or_default()
489 .insert(name.clone());
490 }
491 }
492
493 // Aliases: scan every rule body for ALIAS { content, value }
494 // declarations. The kinds reachable from `content` satisfy
495 // `value`, AND (by construction) `value` satisfies the
496 // surrounding rule. Walking the ENTIRE grammar once captures
497 // every alias site, irrespective of which rule introduces it.
498 fn collect_aliases<'g>(production: &'g Production, out: &mut Vec<(String, &'g Production)>) {
499 match production {
500 Production::Alias {
501 content,
502 named,
503 value,
504 } => {
505 if *named && !value.is_empty() {
506 out.push((value.clone(), content.as_ref()));
507 }
508 collect_aliases(content, out);
509 }
510 Production::Choice { members } | Production::Seq { members } => {
511 for m in members {
512 collect_aliases(m, out);
513 }
514 }
515 Production::Repeat { content }
516 | Production::Repeat1 { content }
517 | Production::Optional { content }
518 | Production::Field { content, .. }
519 | Production::Token { content }
520 | Production::ImmediateToken { content }
521 | Production::Prec { content, .. }
522 | Production::PrecLeft { content, .. }
523 | Production::PrecRight { content, .. }
524 | Production::PrecDynamic { content, .. }
525 | Production::Reserved { content, .. } => {
526 collect_aliases(content, out);
527 }
528 _ => {}
529 }
530 }
531 let mut aliases: Vec<(String, &Production)> = Vec::new();
532 for rule in grammar.rules.values() {
533 collect_aliases(rule, &mut aliases);
534 }
535 for (alias_value, content) in aliases {
536 let mut visited: HashSet<&str> = HashSet::new();
537 let mut reachable: HashSet<String> = HashSet::new();
538 walk(grammar, content, &mut visited, &mut reachable);
539 // Aliased value satisfies itself and is satisfied by every
540 // kind its content can reach.
541 subtypes
542 .entry(alias_value.clone())
543 .or_default()
544 .insert(alias_value.clone());
545 for kind in reachable {
546 subtypes
547 .entry(kind)
548 .or_default()
549 .insert(alias_value.clone());
550 }
551 }
552
553 // Transitive close: `K ⊑ A` and `A ⊑ B` implies `K ⊑ B`. Iterate
554 // a few rounds; the relation is small so a quick fixed-point
555 // suffices in practice.
556 for _ in 0..8 {
557 let snapshot = subtypes.clone();
558 let mut changed = false;
559 for (kind, supers) in &snapshot {
560 let extra: HashSet<String> = supers
561 .iter()
562 .flat_map(|s| snapshot.get(s).cloned().unwrap_or_default())
563 .collect();
564 let entry = subtypes.entry(kind.clone()).or_default();
565 for s in extra {
566 if entry.insert(s) {
567 changed = true;
568 }
569 }
570 }
571 if !changed {
572 break;
573 }
574 }
575
576 subtypes
577}
578
579// ═══════════════════════════════════════════════════════════════════
580// Format policy
581// ═══════════════════════════════════════════════════════════════════
582
583/// Whitespace and indentation policy applied during emission.
584///
585/// The default policy inserts a single space between adjacent tokens,
586/// a newline after `;` / `}` / `{`, and tracks indent on `{` / `}`
587/// boundaries. Per-language overrides (idiomatic indent width,
588/// trailing-comma rules, blank-line conventions) can ride alongside
589/// this struct in a follow-up branch; today's defaults aim only for
590/// syntactic validity.
591#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
592pub struct FormatPolicy {
593 /// Number of spaces per indent level.
594 pub indent_width: usize,
595 /// Separator inserted between adjacent terminals that the lexer
596 /// would otherwise glue together (word ↔ word, operator ↔ operator).
597 /// Default is a single space.
598 pub separator: String,
599 /// Newline byte sequence emitted after `line_break_after` tokens
600 /// and at end-of-output. Default is `"\n"`.
601 pub newline: String,
602 /// Tokens after which the walker breaks to a new line.
603 pub line_break_after: Vec<String>,
604 /// Tokens that increase indent on emission.
605 pub indent_open: Vec<String>,
606 /// Tokens that decrease indent on emission.
607 pub indent_close: Vec<String>,
608}
609
610impl Default for FormatPolicy {
611 fn default() -> Self {
612 Self {
613 indent_width: 2,
614 separator: " ".to_owned(),
615 newline: "\n".to_owned(),
616 line_break_after: vec![";".into(), "{".into(), "}".into()],
617 indent_open: vec!["{".into()],
618 indent_close: vec!["}".into()],
619 }
620 }
621}
622
623// ═══════════════════════════════════════════════════════════════════
624// Emitter
625// ═══════════════════════════════════════════════════════════════════
626
627/// Emit a by-construction schema to source bytes.
628///
629/// `protocol` is the grammar / language name (used in error messages
630/// and to label the entry point).
631///
632/// The walker treats `schema.entries` as the ordered list of root
633/// vertices, falling back to a deterministic by-id ordering when
634/// `entries` is empty. Each root is emitted using the production
635/// associated with its kind in `grammar.rules`.
636///
637/// # Errors
638///
639/// Returns [`ParseError::EmitFailed`] when:
640///
641/// - the schema has no vertices
642/// - a root vertex's kind is not a grammar rule
643/// - a `SYMBOL` reference points at a kind with no rule and no schema
644/// child to resolve it to
645/// - a required `FIELD` has no corresponding edge in the schema
646pub fn emit_pretty(
647 protocol: &str,
648 schema: &Schema,
649 grammar: &Grammar,
650 policy: &FormatPolicy,
651) -> Result<Vec<u8>, ParseError> {
652 let roots = collect_roots(schema);
653 if roots.is_empty() {
654 return Err(ParseError::EmitFailed {
655 protocol: protocol.to_owned(),
656 reason: "schema has no entry vertices".to_owned(),
657 });
658 }
659
660 let mut out = Output::new(policy);
661 for (i, root) in roots.iter().enumerate() {
662 if i > 0 {
663 out.newline();
664 }
665 emit_vertex(protocol, schema, grammar, root, &mut out)?;
666 }
667 Ok(out.finish())
668}
669
670fn collect_roots(schema: &Schema) -> Vec<&panproto_gat::Name> {
671 if !schema.entries.is_empty() {
672 return schema
673 .entries
674 .iter()
675 .filter(|name| schema.vertices.contains_key(*name))
676 .collect();
677 }
678
679 // Fallback: every vertex that is not the target of any structural edge
680 // (sorted by id for determinism).
681 let mut targets: std::collections::HashSet<&panproto_gat::Name> =
682 std::collections::HashSet::new();
683 for edge in schema.edges.keys() {
684 targets.insert(&edge.tgt);
685 }
686 let mut roots: Vec<&panproto_gat::Name> = schema
687 .vertices
688 .keys()
689 .filter(|name| !targets.contains(name))
690 .collect();
691 roots.sort();
692 roots
693}
694
695fn emit_vertex(
696 protocol: &str,
697 schema: &Schema,
698 grammar: &Grammar,
699 vertex_id: &panproto_gat::Name,
700 out: &mut Output<'_>,
701) -> Result<(), ParseError> {
702 let vertex = schema
703 .vertices
704 .get(vertex_id)
705 .ok_or_else(|| ParseError::EmitFailed {
706 protocol: protocol.to_owned(),
707 reason: format!("vertex '{vertex_id}' not found"),
708 })?;
709
710 // Leaf shortcut: a vertex carrying a `literal-value` constraint
711 // and no outgoing structural edges is a terminal token. Emit the
712 // captured value directly. This handles identifiers, numeric
713 // literals, and string literals that the parser stored as
714 // `literal-value` even on by-construction schemas.
715 if let Some(literal) = literal_value(schema, vertex_id) {
716 if children_for(schema, vertex_id).is_empty() {
717 out.token(literal);
718 return Ok(());
719 }
720 }
721
722 let kind = vertex.kind.as_ref();
723 let edges = children_for(schema, vertex_id);
724 if let Some(rule) = grammar.rules.get(kind) {
725 let mut cursor = ChildCursor::new(&edges);
726 emit_production(protocol, schema, grammar, vertex_id, rule, &mut cursor, out)?;
727 // Drain any extras left after the rule walk completed; tree-sitter
728 // may record trailing comments as children of the surrounding
729 // vertex (i.e. after the last structural child the rule matched).
730 drain_extras(protocol, schema, grammar, &mut cursor, out)?;
731 return Ok(());
732 }
733
734 // No rule for this kind. The parser produced it via an ALIAS
735 // (tree-sitter's `alias($.something, $.actual_kind)`) or via an
736 // external scanner (e.g. YAML's `document` root). Fall back to
737 // walking the children directly so the inner content survives;
738 // surrounding tokens — whose only source is the missing rule —
739 // are necessarily absent.
740 for edge in &edges {
741 emit_vertex(protocol, schema, grammar, &edge.tgt, out)?;
742 }
743 Ok(())
744}
745
746/// Linear cursor over a vertex's outgoing edges, used to thread
747/// children through a production rule without double-consuming them.
748struct ChildCursor<'a> {
749 edges: &'a [&'a Edge],
750 consumed: Vec<bool>,
751}
752
753impl<'a> ChildCursor<'a> {
754 fn new(edges: &'a [&'a Edge]) -> Self {
755 Self {
756 edges,
757 consumed: vec![false; edges.len()],
758 }
759 }
760
761 /// Take the next unconsumed edge whose kind equals `field_name`.
762 fn take_field(&mut self, field_name: &str) -> Option<&'a Edge> {
763 for (i, edge) in self.edges.iter().enumerate() {
764 if !self.consumed[i] && edge.kind.as_ref() == field_name {
765 self.consumed[i] = true;
766 return Some(edge);
767 }
768 }
769 None
770 }
771
772 /// Whether any unconsumed edge satisfies `predicate`. Used by the
773 /// unit tests; the live emit path went through `has_matching` on
774 /// each alternative until cursor-driven dispatch was rewritten to
775 /// pick the first-unconsumed-edge's kind directly.
776 #[cfg(test)]
777 fn has_matching(&self, predicate: impl Fn(&Edge) -> bool) -> bool {
778 self.edges
779 .iter()
780 .enumerate()
781 .any(|(i, edge)| !self.consumed[i] && predicate(edge))
782 }
783
784 /// Take the next unconsumed edge whose target vertex satisfies
785 /// `predicate`. Returns the edge and the underlying production
786 /// resolution path is the caller's job.
787 fn take_matching(&mut self, predicate: impl Fn(&Edge) -> bool) -> Option<&'a Edge> {
788 for (i, edge) in self.edges.iter().enumerate() {
789 if !self.consumed[i] && predicate(edge) {
790 self.consumed[i] = true;
791 return Some(edge);
792 }
793 }
794 None
795 }
796}
797
798thread_local! {
799 static EMIT_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
800 /// Set of `(vertex_id, rule_name)` pairs that are currently being
801 /// walked by the recursion. A SYMBOL that resolves to a rule
802 /// already on this stack closes a μ-binder cycle: in the
803 /// coinductive reading, the rule walk at any vertex is the least
804 /// fixed point of `body[μ X . body / X]`, which unfolds at most
805 /// once, with the second visit returning the empty sequence (the
806 /// unit of the free token monoid). Examples that trigger this:
807 /// YAML's `stream` ⊃ `_b_blk_*` mutually-recursive chain, Rust's
808 /// `_expression` ⊃ `binary_expression` ⊃ `_expression`.
809 static EMIT_MU_FRAMES: std::cell::RefCell<std::collections::HashSet<(String, String)>> =
810 std::cell::RefCell::new(std::collections::HashSet::new());
811 /// The name of the FIELD whose body the walker is currently inside,
812 /// or `None` at top level. Lets a SYMBOL nested arbitrarily deep
813 /// in the field's content (under SEQ, CHOICE, REPEAT, OPTIONAL)
814 /// consume from the *outer* cursor by edge-kind rather than from
815 /// the child's own cursor by symbol-match. Without this, shapes
816 /// like `field('args', commaSep1($.X))` — which expands to
817 /// `FIELD(SEQ(SYMBOL X, REPEAT(SEQ(',', SYMBOL X))))` — emit only
818 /// the first matched edge: the FIELD handler consumed one edge,
819 /// the inner REPEAT searched the consumed child's cursor (which
820 /// has no more sibling field edges), and the REPEAT broke after
821 /// one iteration. Setting the context here so the inner SYMBOL
822 /// pulls successive field-named edges from the outer cursor
823 /// recovers every matched edge across arbitrary nesting.
824 static EMIT_FIELD_CONTEXT: std::cell::RefCell<Option<String>> =
825 const { std::cell::RefCell::new(None) };
826}
827
828/// RAII guard that restores the prior `EMIT_FIELD_CONTEXT` value on drop.
829struct FieldContextGuard(Option<String>);
830
831impl Drop for FieldContextGuard {
832 fn drop(&mut self) {
833 EMIT_FIELD_CONTEXT.with(|f| *f.borrow_mut() = self.0.take());
834 }
835}
836
837fn push_field_context(name: &str) -> FieldContextGuard {
838 let prev = EMIT_FIELD_CONTEXT.with(|f| f.borrow_mut().replace(name.to_owned()));
839 FieldContextGuard(prev)
840}
841
842/// Clear the field context for the duration of a child-context walk.
843/// The child's own production has its own FIELDs that set their own
844/// context; the outer field hint must not leak into them.
845fn clear_field_context() -> FieldContextGuard {
846 let prev = EMIT_FIELD_CONTEXT.with(|f| f.borrow_mut().take());
847 FieldContextGuard(prev)
848}
849
850fn current_field_context() -> Option<String> {
851 EMIT_FIELD_CONTEXT.with(|f| f.borrow().clone())
852}
853
854/// Walk a rule at a vertex inside a μ-binder. The wrapping frame is
855/// pushed before recursion and popped after, so any SYMBOL inside
856/// `rule` that re-enters the same `(vertex_id, rule_name)` pair
857/// returns the empty sequence (μ X . body unfolds once).
858fn walk_in_mu_frame(
859 protocol: &str,
860 schema: &Schema,
861 grammar: &Grammar,
862 vertex_id: &panproto_gat::Name,
863 rule_name: &str,
864 rule: &Production,
865 cursor: &mut ChildCursor<'_>,
866 out: &mut Output<'_>,
867) -> Result<(), ParseError> {
868 let key = (vertex_id.to_string(), rule_name.to_owned());
869 let inserted = EMIT_MU_FRAMES.with(|frames| frames.borrow_mut().insert(key.clone()));
870 if !inserted {
871 // We are already walking this rule at this vertex deeper in
872 // the call stack. The coinductive μ-fixed-point reading
873 // returns the empty sequence here; the surrounding
874 // production resumes after the SYMBOL.
875 return Ok(());
876 }
877 let result = emit_production(protocol, schema, grammar, vertex_id, rule, cursor, out);
878 EMIT_MU_FRAMES.with(|frames| {
879 frames.borrow_mut().remove(&key);
880 });
881 result
882}
883
884fn emit_production(
885 protocol: &str,
886 schema: &Schema,
887 grammar: &Grammar,
888 vertex_id: &panproto_gat::Name,
889 production: &Production,
890 cursor: &mut ChildCursor<'_>,
891 out: &mut Output<'_>,
892) -> Result<(), ParseError> {
893 let depth = EMIT_DEPTH.with(|d| {
894 let v = d.get() + 1;
895 d.set(v);
896 v
897 });
898 if depth > 500 {
899 EMIT_DEPTH.with(|d| d.set(d.get() - 1));
900 return Err(ParseError::EmitFailed {
901 protocol: protocol.to_owned(),
902 reason: format!(
903 "emit_production recursion >500 (likely a cyclic grammar; \
904 vertex='{vertex_id}')"
905 ),
906 });
907 }
908 drain_extras(protocol, schema, grammar, cursor, out)?;
909 let result = emit_production_inner(
910 protocol, schema, grammar, vertex_id, production, cursor, out,
911 );
912 EMIT_DEPTH.with(|d| d.set(d.get() - 1));
913 result
914}
915
916/// Consume and emit every leading edge on `cursor` whose target kind
917/// is in `grammar.extras` (typically `line_comment` / `block_comment`).
918/// Extras live outside the production grammar — tree-sitter skips them
919/// at parse time and records them as children of the surrounding
920/// vertex — so the rule walker cannot reconcile them against the
921/// cursor. Draining them as a side channel preserves their content in
922/// the output without confusing the structural matchers.
923fn drain_extras(
924 protocol: &str,
925 schema: &Schema,
926 grammar: &Grammar,
927 cursor: &mut ChildCursor<'_>,
928 out: &mut Output<'_>,
929) -> Result<(), ParseError> {
930 if grammar.extras.is_empty() {
931 return Ok(());
932 }
933 loop {
934 let next_extra: Option<usize> = cursor
935 .edges
936 .iter()
937 .enumerate()
938 .find(|(i, _)| !cursor.consumed[*i])
939 .and_then(|(i, edge)| {
940 let kind = schema.vertices.get(&edge.tgt).map(|v| v.kind.as_ref())?;
941 if grammar.extras.contains(kind) {
942 Some(i)
943 } else {
944 None
945 }
946 });
947 let Some(idx) = next_extra else {
948 return Ok(());
949 };
950 cursor.consumed[idx] = true;
951 let target = &cursor.edges[idx].tgt;
952 emit_vertex(protocol, schema, grammar, target, out)?;
953 }
954}
955
956fn emit_production_inner(
957 protocol: &str,
958 schema: &Schema,
959 grammar: &Grammar,
960 vertex_id: &panproto_gat::Name,
961 production: &Production,
962 cursor: &mut ChildCursor<'_>,
963 out: &mut Output<'_>,
964) -> Result<(), ParseError> {
965 match production {
966 Production::String { value } => {
967 out.token(value);
968 Ok(())
969 }
970 Production::Pattern { value } => {
971 if let Some(literal) = literal_value(schema, vertex_id) {
972 out.token(literal);
973 } else if is_newline_like_pattern(value) {
974 // Patterns like `\r?\n`, `\n`, `\r\n` are the structural
975 // newline tokens grammars use to separate top-level
976 // statements (csound's `_new_line`, ABC's line-end, etc.).
977 // Emitting them through the placeholder fallback rendered
978 // the bare `_` sentinel between siblings; route them to
979 // the layout pass's line-break instead so the output
980 // re-parses.
981 out.newline();
982 } else if is_whitespace_only_pattern(value) {
983 // `\s+`, `[ \t]+` and friends are interstitial whitespace
984 // tokens. Emit nothing: the layout pass inserts the
985 // policy separator between adjacent Lits if needed.
986 } else {
987 out.token(&placeholder_for_pattern(value));
988 }
989 Ok(())
990 }
991 Production::Blank => Ok(()),
992 Production::Symbol { name } => {
993 // Inside a FIELD body, a SYMBOL consumes by field-name on
994 // the outer cursor rather than searching by symbol-match.
995 // This covers the simple `FIELD(SYMBOL X)` case as well as
996 // every nesting under FIELD that contains SYMBOLs (SEQ,
997 // CHOICE, REPEAT, OPTIONAL, ALIAS). Without the override,
998 // shapes like `field('args', commaSep1($.X))` consume one
999 // field edge in the FIELD handler and then the REPEAT
1000 // inside SEQ searches the consumed child's cursor — where
1001 // no sibling field edges sit — and breaks after one
1002 // iteration.
1003 if let Some(field) = current_field_context() {
1004 if let Some(edge) = cursor.take_field(&field) {
1005 return emit_in_child_context(
1006 protocol, schema, grammar, &edge.tgt, production, out,
1007 );
1008 }
1009 // No matching field-named edge left on the outer
1010 // cursor. Surface nothing; the surrounding REPEAT /
1011 // OPTIONAL / CHOICE backtracks the literal tokens it
1012 // emitted on this iteration when it sees no progress.
1013 return Ok(());
1014 }
1015 if name.starts_with('_') {
1016 // Hidden rule: not a vertex kind on the schema side.
1017 // Inline-expand the rule body so its children take
1018 // edges from the current cursor, instead of trying to
1019 // take a single child edge that "satisfies" the
1020 // hidden rule and discarding the rest of the body
1021 // (which would drop tokens like `=` and the trailing
1022 // value SYMBOL inside e.g. TOML's `_inline_pair`).
1023 //
1024 // Wrapped in a μ-frame so a hidden rule that
1025 // references its own kind cyclically (or another
1026 // hidden rule that closes the cycle) unfolds once
1027 // and then collapses to the empty sequence at the
1028 // second visit, rather than blowing the stack.
1029 if let Some(rule) = grammar.rules.get(name) {
1030 walk_in_mu_frame(
1031 protocol, schema, grammar, vertex_id, name, rule, cursor, out,
1032 )
1033 } else {
1034 // External hidden rule (declared in the
1035 // grammar's `externals` block, scanned by C code,
1036 // not listed in `rules`). Heuristic fallback by
1037 // name:
1038 //
1039 // - `_indent` / `*_indent`: open an indent block.
1040 // Indent-based grammars (Python, YAML, qvr)
1041 // declare an `_indent` external scanner before
1042 // the body of a block-bodied declaration; the
1043 // emitted output is unparseable without the
1044 // corresponding indentation jump.
1045 // - `_dedent` / `*_dedent`: close the matching
1046 // indent block.
1047 // - `_newline` / `*_line_ending` / `*_or_eof`:
1048 // universally newline-or-empty; emitting a
1049 // single newline is the right default for
1050 // grammars like TOML whose `pair` SEQ trails
1051 // into `_line_ending_or_eof`.
1052 //
1053 // Anything else falls through silently — better
1054 // to drop an unknown external token than to
1055 // invent one that confuses re-parsing.
1056 if name == "_indent" || name.ends_with("_indent") {
1057 out.indent_open();
1058 } else if name == "_dedent" || name.ends_with("_dedent") {
1059 out.indent_close();
1060 } else if name.contains("line_ending")
1061 || name.contains("newline")
1062 || name.ends_with("_or_eof")
1063 {
1064 out.newline();
1065 }
1066 Ok(())
1067 }
1068 } else if let Some(edge) = take_symbol_match(grammar, schema, cursor, name) {
1069 // For supertype / hidden-rule dispatch the child's
1070 // own kind names the actual production to walk
1071 // (`child.kind` IS the subtype). For ALIAS the
1072 // dependent-optic context is carried by the
1073 // surrounding `Production::Alias` branch, which calls
1074 // `emit_aliased_child` directly; we don't reach here
1075 // for that case. So walking `grammar.rules[child.kind]`
1076 // via `emit_vertex` is correct: the dependent-optic
1077 // path is preserved at every site where it actually
1078 // diverges from `child.kind`.
1079 emit_vertex(protocol, schema, grammar, &edge.tgt, out)
1080 } else if vertex_id_kind(schema, vertex_id) == Some(name.as_str()) {
1081 let rule = grammar
1082 .rules
1083 .get(name)
1084 .ok_or_else(|| ParseError::EmitFailed {
1085 protocol: protocol.to_owned(),
1086 reason: format!("no production for SYMBOL '{name}'"),
1087 })?;
1088 // Self-reference (`X = ... SYMBOL X ...`): wrap in a
1089 // μ-frame so re-entry collapses to the empty sequence.
1090 walk_in_mu_frame(
1091 protocol, schema, grammar, vertex_id, name, rule, cursor, out,
1092 )
1093 } else {
1094 // Named rule with no matching child: emit nothing and
1095 // let the surrounding CHOICE / OPTIONAL / REPEAT
1096 // resolve the absence.
1097 Ok(())
1098 }
1099 }
1100 Production::Seq { members } => {
1101 for member in members {
1102 emit_production(protocol, schema, grammar, vertex_id, member, cursor, out)?;
1103 }
1104 Ok(())
1105 }
1106 Production::Choice { members } => {
1107 if let Some(matched) =
1108 pick_choice_with_cursor(schema, grammar, vertex_id, cursor, members)
1109 {
1110 emit_production(protocol, schema, grammar, vertex_id, matched, cursor, out)
1111 } else {
1112 Ok(())
1113 }
1114 }
1115 Production::Repeat { content } | Production::Repeat1 { content } => {
1116 let mut emitted_any = false;
1117 loop {
1118 let cursor_snap = cursor.consumed.clone();
1119 let out_snap = out.snapshot();
1120 let consumed_before = cursor.consumed.iter().filter(|&&c| c).count();
1121 let result =
1122 emit_production(protocol, schema, grammar, vertex_id, content, cursor, out);
1123 let consumed_after = cursor.consumed.iter().filter(|&&c| c).count();
1124 if result.is_err() || consumed_after == consumed_before {
1125 cursor.consumed = cursor_snap;
1126 out.restore(out_snap);
1127 break;
1128 }
1129 emitted_any = true;
1130 }
1131 if matches!(production, Production::Repeat1 { .. }) && !emitted_any {
1132 emit_production(protocol, schema, grammar, vertex_id, content, cursor, out)?;
1133 }
1134 Ok(())
1135 }
1136 Production::Optional { content } => {
1137 let cursor_snap = cursor.consumed.clone();
1138 let out_snap = out.snapshot();
1139 let consumed_before = cursor.consumed.iter().filter(|&&c| c).count();
1140 let result =
1141 emit_production(protocol, schema, grammar, vertex_id, content, cursor, out);
1142 // OPTIONAL is a backtracking site: if the inner production
1143 // errored *or* made no progress without leaving a witness
1144 // constraint, restore both cursor and output to their
1145 // pre-attempt state. Mirrors `Repeat`'s loop body.
1146 if result.is_err() {
1147 cursor.consumed = cursor_snap;
1148 out.restore(out_snap);
1149 return result;
1150 }
1151 let consumed_after = cursor.consumed.iter().filter(|&&c| c).count();
1152 if consumed_after == consumed_before
1153 && !has_relevant_constraint(content, schema, vertex_id)
1154 {
1155 cursor.consumed = cursor_snap;
1156 out.restore(out_snap);
1157 }
1158 Ok(())
1159 }
1160 Production::Field { name, content } => {
1161 // Set the field context for the duration of `content`'s
1162 // walk and emit the content against the *outer* cursor.
1163 // The SYMBOL handler picks up the context and pulls
1164 // successive `take_field(name)` edges as it encounters
1165 // SYMBOLs anywhere under `content` (under SEQ, CHOICE,
1166 // REPEAT, OPTIONAL, ALIAS — arbitrarily nested). This
1167 // subsumes the prior carve-outs for FIELD(REPEAT(...)),
1168 // FIELD(REPEAT1(...)), and the bare FIELD(SYMBOL ...)
1169 // case, and adds coverage for
1170 // `field('xs', commaSep1($.X))` which expands to
1171 // FIELD(SEQ(SYMBOL X, REPEAT(SEQ(',', SYMBOL X)))) and
1172 // any other shape where REPEAT/REPEAT1 sits inside SEQ /
1173 // CHOICE / OPTIONAL under a FIELD. A FIELD that wraps a
1174 // non-SYMBOL production (e.g. `field('op', '+')` or
1175 // `field('op', CHOICE(STRING ...))`) still works: STRING
1176 // handlers ignore the context and emit literals
1177 // directly, so the operator token survives the round
1178 // trip.
1179 let _guard = push_field_context(name);
1180 emit_production(protocol, schema, grammar, vertex_id, content, cursor, out)
1181 }
1182 Production::Alias {
1183 content,
1184 named,
1185 value,
1186 } => {
1187 // A named ALIAS rewrites the parser-visible kind to
1188 // `value`. If the cursor has an unconsumed child whose
1189 // kind matches that alias name, take it and emit the
1190 // child using the alias's INNER content as the rule
1191 // (e.g. `ALIAS { SYMBOL real_rule, value: "kind_x" }`
1192 // means a `kind_x` vertex on the schema should be walked
1193 // through `real_rule`'s body, not through whatever rule
1194 // happens to be keyed under `kind_x`). This is the
1195 // dependent-optic shape: the rule the emitter walks at a
1196 // child position is determined by the parent's chosen
1197 // alias, not by the child kind alone — without it,
1198 // grammars like YAML that introduce the same kind through
1199 // many ALIAS sites lose the parent context the moment
1200 // emit_vertex is called.
1201 if *named && !value.is_empty() {
1202 if let Some(edge) = cursor.take_matching(|edge| {
1203 schema
1204 .vertices
1205 .get(&edge.tgt)
1206 .map(|v| v.kind.as_ref() == value.as_str())
1207 .unwrap_or(false)
1208 }) {
1209 return emit_aliased_child(protocol, schema, grammar, &edge.tgt, content, out);
1210 }
1211 }
1212 emit_production(protocol, schema, grammar, vertex_id, content, cursor, out)
1213 }
1214 Production::Token { content }
1215 | Production::ImmediateToken { content }
1216 | Production::Prec { content, .. }
1217 | Production::PrecLeft { content, .. }
1218 | Production::PrecRight { content, .. }
1219 | Production::PrecDynamic { content, .. }
1220 | Production::Reserved { content, .. } => {
1221 emit_production(protocol, schema, grammar, vertex_id, content, cursor, out)
1222 }
1223 }
1224}
1225
1226/// Take the next cursor edge whose target vertex's kind matches the
1227/// SYMBOL `name` directly or via inline expansion of a hidden rule.
1228fn take_symbol_match<'a>(
1229 grammar: &Grammar,
1230 schema: &Schema,
1231 cursor: &mut ChildCursor<'a>,
1232 name: &str,
1233) -> Option<&'a Edge> {
1234 cursor.take_matching(|edge| {
1235 let target_kind = schema.vertices.get(&edge.tgt).map(|v| v.kind.as_ref());
1236 kind_satisfies_symbol(grammar, target_kind, name)
1237 })
1238}
1239
1240/// Decide whether a schema vertex of kind `target_kind` satisfies a
1241/// SYMBOL `name` reference in the grammar.
1242///
1243/// Operates as an O(1) lookup against the precomputed subtype
1244/// closure built at [`Grammar::from_bytes`]. The semantic content is
1245/// "K satisfies SYMBOL S iff K is reachable from S by walking the
1246/// grammar's hidden, supertype, and named-alias dispatch": this is
1247/// exactly the relation tree-sitter induces on `(parser-visible kind,
1248/// rule-position)` pairs.
1249fn kind_satisfies_symbol(grammar: &Grammar, target_kind: Option<&str>, name: &str) -> bool {
1250 let Some(target) = target_kind else {
1251 return false;
1252 };
1253 if target == name {
1254 return true;
1255 }
1256 grammar
1257 .subtypes
1258 .get(target)
1259 .is_some_and(|set| set.contains(name))
1260}
1261
1262/// Emit a child reached through an ALIAS production using the
1263/// alias's inner content as the rule, not `grammar.rules[child.kind]`.
1264///
1265/// This carries the dependent-optic context across the ALIAS edge:
1266/// at the parent rule's site we know which underlying production the
1267/// alias wraps (typically `SYMBOL real_rule`), and that's the
1268/// production that should drive the emit walk on the child's
1269/// children. Looking up `grammar.rules.get(child.kind)` instead would
1270/// either fail (the renamed kind has no top-level rule, e.g. YAML's
1271/// `block_mapping_pair`) or pick an arbitrary same-kinded rule from
1272/// elsewhere in the grammar.
1273///
1274/// Walk-context invariant. The dependent-optic shape of `emit_pretty`
1275/// says: the production walked at any vertex is determined by the
1276/// path from the root through the grammar, not by the vertex kind in
1277/// isolation. Two dispatch sites realise that invariant:
1278///
1279/// * [`emit_vertex`] looks up `grammar.rules[child.kind]` and walks
1280/// it. Correct for supertype / hidden-rule dispatch: the child's
1281/// kind on the schema IS the subtype tree-sitter selected, so its
1282/// top-level rule is the right production to walk.
1283/// * `emit_aliased_child` threads the parent rule's `Production`
1284/// directly (the inner `content` of `Production::Alias`) and walks
1285/// it on the child's children. Correct for ALIAS dispatch: the
1286/// child's kind on the schema is the alias's `value` (a renamed
1287/// kind that may have no top-level rule), and the production to
1288/// walk is the alias's content body, supplied by the parent.
1289///
1290/// Together these cover every site where the rule-walked-at-child
1291/// diverges from `grammar.rules[child.kind]`; the recursion site for
1292/// plain SYMBOL therefore correctly delegates to `emit_vertex`, and
1293/// we do not need a richer `WalkContext` value passed by reference.
1294/// The grammar dependency is the thread.
1295fn emit_aliased_child(
1296 protocol: &str,
1297 schema: &Schema,
1298 grammar: &Grammar,
1299 child_id: &panproto_gat::Name,
1300 content: &Production,
1301 out: &mut Output<'_>,
1302) -> Result<(), ParseError> {
1303 // Leaf shortcut: if the child has a literal-value and no
1304 // structural children, emit the captured text. Identifiers and
1305 // similar terminals reach here when an ALIAS wraps a SYMBOL that
1306 // resolves to a PATTERN.
1307 if let Some(literal) = literal_value(schema, child_id) {
1308 if children_for(schema, child_id).is_empty() {
1309 out.token(literal);
1310 return Ok(());
1311 }
1312 }
1313
1314 // Resolve `content` to a rule when it's a SYMBOL (the dominant
1315 // shape: `ALIAS { content: SYMBOL real_rule, value: "kind_x" }`).
1316 if let Production::Symbol { name } = content {
1317 if let Some(rule) = grammar.rules.get(name) {
1318 let edges = children_for(schema, child_id);
1319 let mut cursor = ChildCursor::new(&edges);
1320 return emit_production(protocol, schema, grammar, child_id, rule, &mut cursor, out);
1321 }
1322 }
1323
1324 // Other ALIAS contents (CHOICE, SEQ, literals) walk in place.
1325 let edges = children_for(schema, child_id);
1326 let mut cursor = ChildCursor::new(&edges);
1327 emit_production(
1328 protocol,
1329 schema,
1330 grammar,
1331 child_id,
1332 content,
1333 &mut cursor,
1334 out,
1335 )
1336}
1337
1338fn emit_in_child_context(
1339 protocol: &str,
1340 schema: &Schema,
1341 grammar: &Grammar,
1342 child_id: &panproto_gat::Name,
1343 production: &Production,
1344 out: &mut Output<'_>,
1345) -> Result<(), ParseError> {
1346 // The child walks under its own production tree, with its own
1347 // FIELDs setting their own contexts. Clear the outer FIELD hint
1348 // so it does not leak through and cause sibling SYMBOLs inside
1349 // the child's body to mistakenly pull edges from the child's
1350 // cursor by the parent's field name.
1351 let _guard = clear_field_context();
1352 // If `production` is a structural wrapper (CHOICE / SEQ /
1353 // OPTIONAL / ...) whose referenced symbols cover the child's own
1354 // kind, the child IS the production's target node and the right
1355 // emit path is `emit_vertex(child)` (which honours the
1356 // literal-value leaf shortcut). Without this guard, FIELD(pattern,
1357 // CHOICE { _pattern, self }) on an identifier child walks the
1358 // CHOICE on the identifier's empty cursor, falls through to the
1359 // first non-BLANK alt, and loses the captured identifier text.
1360 if !matches!(production, Production::Symbol { .. }) {
1361 let child_kind = schema.vertices.get(child_id).map(|v| v.kind.as_ref());
1362 let symbols = referenced_symbols(production);
1363 if symbols
1364 .iter()
1365 .any(|s| kind_satisfies_symbol(grammar, child_kind, s) || child_kind == Some(s))
1366 {
1367 return emit_vertex(protocol, schema, grammar, child_id, out);
1368 }
1369 }
1370 match production {
1371 Production::Symbol { .. } => emit_vertex(protocol, schema, grammar, child_id, out),
1372 _ => {
1373 let edges = children_for(schema, child_id);
1374 let mut cursor = ChildCursor::new(&edges);
1375 emit_production(
1376 protocol,
1377 schema,
1378 grammar,
1379 child_id,
1380 production,
1381 &mut cursor,
1382 out,
1383 )
1384 }
1385 }
1386}
1387
1388fn pick_choice_with_cursor<'a>(
1389 schema: &Schema,
1390 grammar: &Grammar,
1391 vertex_id: &panproto_gat::Name,
1392 cursor: &ChildCursor<'_>,
1393 alternatives: &'a [Production],
1394) -> Option<&'a Production> {
1395 // Discriminator-driven dispatch (highest priority): when the
1396 // walker recorded a `chose-alt-fingerprint` constraint at parse
1397 // time, dispatch directly against that. This is the categorical
1398 // discriminator: it survives stripping of byte-position
1399 // constraints (so by-construction round-trips work) and is the
1400 // explicit witness of which CHOICE alternative the parser took.
1401 //
1402 // Falls back to the live `interstitial-*` substring blob when no
1403 // fingerprint is present (e.g. instances built by callers that
1404 // bypass the AstWalker). Both blobs are scored by the longest
1405 // STRING-literal token in an alternative that matches; the
1406 // length tiebreak prefers `&&` over `&`, `==` over `=`, etc.
1407 let constraint_blob = schema
1408 .constraints
1409 .get(vertex_id)
1410 .map(|cs| {
1411 let fingerprint: Option<&str> = cs
1412 .iter()
1413 .find(|c| c.sort.as_ref() == "chose-alt-fingerprint")
1414 .map(|c| c.value.as_str());
1415 if let Some(fp) = fingerprint {
1416 fp.to_owned()
1417 } else {
1418 cs.iter()
1419 .filter(|c| {
1420 let s = c.sort.as_ref();
1421 s.starts_with("interstitial-") && !s.ends_with("-start-byte")
1422 })
1423 .map(|c| c.value.as_str())
1424 .collect::<Vec<&str>>()
1425 .join(" ")
1426 }
1427 })
1428 .unwrap_or_default();
1429 let child_kinds: Vec<&str> = schema
1430 .constraints
1431 .get(vertex_id)
1432 .and_then(|cs| {
1433 cs.iter()
1434 .find(|c| c.sort.as_ref() == "chose-alt-child-kinds")
1435 .map(|c| c.value.split_whitespace().collect())
1436 })
1437 .unwrap_or_default();
1438 if !constraint_blob.is_empty() {
1439 // Primary score: literal-token match length. This dominates
1440 // alt selection so existing language tests that depend on
1441 // literal-only fingerprints keep working.
1442 // Secondary score (tiebreaker only): named-symbol kind match
1443 // count, read from the separate `chose-alt-child-kinds`
1444 // constraint (kept apart from the literal fingerprint so
1445 // identifiers like `:` in the kind list don't contaminate the
1446 // literal match). An alt that matches the recorded kinds is a
1447 // stronger witness than one whose only
1448 // overlap is literal punctuation.
1449 let mut best_literal: usize = 0;
1450 let mut best_symbols: usize = 0;
1451 let mut best_alt: Option<&Production> = None;
1452 let mut tied = false;
1453 for alt in alternatives {
1454 let strings = literal_strings(alt);
1455 if strings.is_empty() {
1456 continue;
1457 }
1458 let literal_score = strings
1459 .iter()
1460 .filter(|s| constraint_blob.contains(s.as_str()))
1461 .map(String::len)
1462 .sum::<usize>();
1463 if literal_score == 0 {
1464 continue;
1465 }
1466 // Symbol score is computed only as a tiebreaker among alts
1467 // whose literal-token coverage is the same; it never lifts
1468 // an alt above one with a strictly higher literal score.
1469 // Reads the `chose-alt-child-kinds` constraint (a separate
1470 // sequence the walker emits, kept apart from the literal
1471 // fingerprint to avoid cross-contamination).
1472 let symbol_score = if literal_score >= best_literal && !child_kinds.is_empty() {
1473 let symbols = referenced_symbols(alt);
1474 symbols
1475 .iter()
1476 .filter(|sym| {
1477 let sym_str: &str = sym;
1478 if child_kinds.contains(&sym_str) {
1479 return true;
1480 }
1481 grammar.subtypes.get(sym_str).is_some_and(|sub_set| {
1482 sub_set
1483 .iter()
1484 .any(|sub| child_kinds.contains(&sub.as_str()))
1485 })
1486 })
1487 .count()
1488 } else {
1489 0
1490 };
1491 let better = literal_score > best_literal
1492 || (literal_score == best_literal && symbol_score > best_symbols);
1493 let same = literal_score == best_literal && symbol_score == best_symbols;
1494 if better {
1495 best_literal = literal_score;
1496 best_symbols = symbol_score;
1497 best_alt = Some(alt);
1498 tied = false;
1499 } else if same && best_alt.is_some() {
1500 tied = true;
1501 }
1502 }
1503 // Only commit to an alt when the fingerprint discriminates it
1504 // uniquely. A tie means the alts share the same literal token
1505 // set (e.g. JSON's `string = CHOICE { SEQ { '"', '"' }, SEQ {
1506 // '"', _string_content, '"' } }` — both alts contain just the
1507 // two `"` tokens). In that case fall through to cursor-based
1508 // dispatch, which uses the actual edge structure.
1509 if let Some(alt) = best_alt {
1510 if !tied {
1511 return Some(alt);
1512 }
1513 }
1514 }
1515
1516 // Cursor-driven dispatch: pick the alternative whose body
1517 // references a SYMBOL covering the *first unconsumed* edge in
1518 // cursor order. `referenced_symbols` walks the alternative
1519 // recursively (across nested SEQs, REPEATs, OPTIONALs, FIELDs,
1520 // etc.) so a leading optional like `attribute_item` does not
1521 // block matching when only the trailing required symbol is
1522 // present on the schema.
1523 //
1524 // Ordering by the first unconsumed edge (rather than picking any
1525 // alternative whose SYMBOL set intersects the unconsumed
1526 // multiset) is what preserves schema edge order under
1527 // REPEAT(CHOICE(...)) productions. Without this rule, alt order
1528 // in the grammar's CHOICE determines the emission order, and a
1529 // schema with interleaved kinds like `[symbol, punct, int,
1530 // symbol, punct, int]` re-fuses to `[symbol, symbol, punct,
1531 // punct, int, int]` when emitted then re-parsed. The fix is the
1532 // categorical reading of REPEAT-over-list (list-shaped fold)
1533 // rather than REPEAT-over-multiset (unordered fold).
1534 let first_unconsumed_kind: Option<&str> = cursor
1535 .edges
1536 .iter()
1537 .enumerate()
1538 .find(|(i, _)| !cursor.consumed[*i])
1539 .and_then(|(_, edge)| schema.vertices.get(&edge.tgt).map(|v| v.kind.as_ref()));
1540 if let Some(target_kind) = first_unconsumed_kind {
1541 for alt in alternatives {
1542 let symbols = referenced_symbols(alt);
1543 if !symbols.is_empty()
1544 && symbols
1545 .iter()
1546 .any(|s| kind_satisfies_symbol(grammar, Some(target_kind), s))
1547 {
1548 return Some(alt);
1549 }
1550 }
1551 }
1552
1553 // FIELD dispatch: pick an alternative whose FIELD name matches an
1554 // unconsumed edge kind.
1555 let edge_kinds: Vec<&str> = cursor
1556 .edges
1557 .iter()
1558 .enumerate()
1559 .filter(|(i, _)| !cursor.consumed[*i])
1560 .map(|(_, e)| e.kind.as_ref())
1561 .collect();
1562 for alt in alternatives {
1563 if has_field_in(alt, &edge_kinds) {
1564 return Some(alt);
1565 }
1566 }
1567
1568 // No cursor-driven match. Fall back to:
1569 //
1570 // - BLANK (the explicit empty alternative) when present, so an
1571 // OPTIONAL-shaped CHOICE compiles to nothing.
1572 // - The first non-`BLANK` alternative as a last resort, used by
1573 // STRING-only alternatives (keyword tokens) and other choices
1574 // that don't reach the cursor.
1575 //
1576 // The previous "match own_kind" branch is intentionally absent:
1577 // when an alt's first SYMBOL equals the current vertex's kind, the
1578 // caller is already emitting that vertex's own rule. Recursing
1579 // into the alt would cause a self-loop in the rule walk.
1580 let _ = (schema, vertex_id);
1581 if alternatives.iter().any(|a| matches!(a, Production::Blank)) {
1582 return alternatives.iter().find(|a| matches!(a, Production::Blank));
1583 }
1584 alternatives
1585 .iter()
1586 .find(|alt| !matches!(alt, Production::Blank))
1587}
1588
1589/// Collect every literal STRING token directly inside `production`
1590/// (without descending into SYMBOLs / hidden rules). Used to score
1591/// CHOICE alternatives against the parent vertex's interstitials so
1592/// the right operator / keyword form is picked when the schema
1593/// preserves interstitial fragments from a prior parse.
1594fn literal_strings(production: &Production) -> Vec<String> {
1595 let mut out = Vec::new();
1596 fn walk(p: &Production, out: &mut Vec<String>) {
1597 match p {
1598 Production::String { value } if !value.is_empty() => {
1599 out.push(value.clone());
1600 }
1601 Production::Choice { members } | Production::Seq { members } => {
1602 for m in members {
1603 walk(m, out);
1604 }
1605 }
1606 Production::Repeat { content }
1607 | Production::Repeat1 { content }
1608 | Production::Optional { content }
1609 | Production::Field { content, .. }
1610 | Production::Alias { content, .. }
1611 | Production::Token { content }
1612 | Production::ImmediateToken { content }
1613 | Production::Prec { content, .. }
1614 | Production::PrecLeft { content, .. }
1615 | Production::PrecRight { content, .. }
1616 | Production::PrecDynamic { content, .. }
1617 | Production::Reserved { content, .. } => walk(content, out),
1618 _ => {}
1619 }
1620 }
1621 walk(production, &mut out);
1622 out
1623}
1624
1625/// Collect every SYMBOL name reachable from `production` without
1626/// crossing into nested rules. Used by `pick_choice_with_cursor` to
1627/// rank alternatives by "any SYMBOL inside this alt matches something
1628/// on the cursor", instead of just the first SYMBOL: a leading
1629/// optional like `attribute_item` then `parameter` is otherwise
1630/// rejected when only the parameter children are present.
1631fn referenced_symbols(production: &Production) -> Vec<&str> {
1632 let mut out = Vec::new();
1633 fn walk<'a>(p: &'a Production, out: &mut Vec<&'a str>) {
1634 match p {
1635 Production::Symbol { name } => out.push(name.as_str()),
1636 Production::Choice { members } | Production::Seq { members } => {
1637 for m in members {
1638 walk(m, out);
1639 }
1640 }
1641 Production::Alias {
1642 content,
1643 named,
1644 value,
1645 } => {
1646 // A named ALIAS produces a child vertex whose kind is
1647 // the alias `value` (e.g. `ALIAS { content: STRING "=",
1648 // value: "punctuation", named: true }` introduces a
1649 // `punctuation` child). For cursor-driven dispatch to
1650 // recognise alts that emit such children, yield the
1651 // alias value as a referenced symbol. Anonymous aliases
1652 // do not introduce a named node and only need their
1653 // inner content's symbols.
1654 if *named && !value.is_empty() {
1655 out.push(value.as_str());
1656 }
1657 walk(content, out);
1658 }
1659 Production::Repeat { content }
1660 | Production::Repeat1 { content }
1661 | Production::Optional { content }
1662 | Production::Field { content, .. }
1663 | Production::Token { content }
1664 | Production::ImmediateToken { content }
1665 | Production::Prec { content, .. }
1666 | Production::PrecLeft { content, .. }
1667 | Production::PrecRight { content, .. }
1668 | Production::PrecDynamic { content, .. }
1669 | Production::Reserved { content, .. } => walk(content, out),
1670 _ => {}
1671 }
1672 }
1673 walk(production, &mut out);
1674 out
1675}
1676
1677#[cfg(test)]
1678fn first_symbol(production: &Production) -> Option<&str> {
1679 match production {
1680 Production::Symbol { name } => Some(name),
1681 Production::Seq { members } => members.iter().find_map(first_symbol),
1682 Production::Choice { members } => members.iter().find_map(first_symbol),
1683 Production::Repeat { content }
1684 | Production::Repeat1 { content }
1685 | Production::Optional { content }
1686 | Production::Field { content, .. }
1687 | Production::Alias { content, .. }
1688 | Production::Token { content }
1689 | Production::ImmediateToken { content }
1690 | Production::Prec { content, .. }
1691 | Production::PrecLeft { content, .. }
1692 | Production::PrecRight { content, .. }
1693 | Production::PrecDynamic { content, .. }
1694 | Production::Reserved { content, .. } => first_symbol(content),
1695 _ => None,
1696 }
1697}
1698
1699fn has_field_in(production: &Production, edge_kinds: &[&str]) -> bool {
1700 match production {
1701 Production::Field { name, .. } => edge_kinds.contains(&name.as_str()),
1702 Production::Seq { members } | Production::Choice { members } => {
1703 members.iter().any(|m| has_field_in(m, edge_kinds))
1704 }
1705 Production::Repeat { content }
1706 | Production::Repeat1 { content }
1707 | Production::Optional { content }
1708 | Production::Alias { content, .. }
1709 | Production::Token { content }
1710 | Production::ImmediateToken { content }
1711 | Production::Prec { content, .. }
1712 | Production::PrecLeft { content, .. }
1713 | Production::PrecRight { content, .. }
1714 | Production::PrecDynamic { content, .. }
1715 | Production::Reserved { content, .. } => has_field_in(content, edge_kinds),
1716 _ => false,
1717 }
1718}
1719
1720fn has_relevant_constraint(
1721 production: &Production,
1722 schema: &Schema,
1723 vertex_id: &panproto_gat::Name,
1724) -> bool {
1725 let constraints = match schema.constraints.get(vertex_id) {
1726 Some(c) => c,
1727 None => return false,
1728 };
1729 fn walk(production: &Production, constraints: &[panproto_schema::Constraint]) -> bool {
1730 match production {
1731 Production::String { value } => constraints
1732 .iter()
1733 .any(|c| c.value == *value || c.sort.as_ref() == value),
1734 Production::Field { name, content } => {
1735 constraints.iter().any(|c| c.sort.as_ref() == name) || walk(content, constraints)
1736 }
1737 Production::Seq { members } | Production::Choice { members } => {
1738 members.iter().any(|m| walk(m, constraints))
1739 }
1740 Production::Repeat { content }
1741 | Production::Repeat1 { content }
1742 | Production::Optional { content }
1743 | Production::Alias { content, .. }
1744 | Production::Token { content }
1745 | Production::ImmediateToken { content }
1746 | Production::Prec { content, .. }
1747 | Production::PrecLeft { content, .. }
1748 | Production::PrecRight { content, .. }
1749 | Production::PrecDynamic { content, .. }
1750 | Production::Reserved { content, .. } => walk(content, constraints),
1751 _ => false,
1752 }
1753 }
1754 walk(production, constraints)
1755}
1756
1757fn children_for<'a>(schema: &'a Schema, vertex_id: &panproto_gat::Name) -> Vec<&'a Edge> {
1758 // Walk `outgoing` (insertion-ordered by SchemaBuilder via SmallVec
1759 // append) rather than the unordered `edges` HashMap so abstract
1760 // schemas under REPEAT(CHOICE(...)) preserve the order their edges
1761 // were inserted in. The previous implementation walked the HashMap
1762 // and sorted lexicographically by (kind, target id), which fused
1763 // interleaved children of the same kind into runs (e.g. a sequence
1764 // [symbol, punct, int, symbol, punct, int] became [symbol, symbol,
1765 // punct, punct, int, int] after the lex sort).
1766 let Some(edges) = schema.outgoing.get(vertex_id) else {
1767 return Vec::new();
1768 };
1769
1770 // Look up the canonical Edge reference (the key in `schema.edges`)
1771 // for each entry in `outgoing`. Falls back to the SmallVec entry if
1772 // the canonical key is missing, which would indicate index drift.
1773 let mut indexed: Vec<(usize, u32, &Edge)> = edges
1774 .iter()
1775 .enumerate()
1776 .map(|(i, e)| {
1777 let canonical = schema.edges.get_key_value(e).map_or(e, |(k, _)| k);
1778 let pos = schema.orderings.get(canonical).copied().unwrap_or(u32::MAX);
1779 (i, pos, canonical)
1780 })
1781 .collect();
1782
1783 // Stable sort by (explicit-ordering, insertion-index). Edges with
1784 // an explicit `orderings` entry come first in their declared order;
1785 // the remainder fall through in insertion order.
1786 indexed.sort_by_key(|(i, pos, _)| (*pos, *i));
1787 indexed.into_iter().map(|(_, _, e)| e).collect()
1788}
1789
1790fn vertex_id_kind<'a>(schema: &'a Schema, vertex_id: &panproto_gat::Name) -> Option<&'a str> {
1791 schema.vertices.get(vertex_id).map(|v| v.kind.as_ref())
1792}
1793
1794fn literal_value<'a>(schema: &'a Schema, vertex_id: &panproto_gat::Name) -> Option<&'a str> {
1795 schema
1796 .constraints
1797 .get(vertex_id)?
1798 .iter()
1799 .find(|c| c.sort.as_ref() == "literal-value")
1800 .map(|c| c.value.as_str())
1801}
1802
1803/// True iff `pattern` matches a (possibly optional / repeated) sequence
1804/// of carriage-return and newline characters only. Examples: `\r?\n`,
1805/// `\n`, `\r\n`, `\n+`, `\r?\n+`. Distinguishes structural newline
1806/// terminals from generic whitespace and from other patterns that
1807/// happen to contain a newline escape inside a larger class.
1808fn is_newline_like_pattern(pattern: &str) -> bool {
1809 if pattern.is_empty() {
1810 return false;
1811 }
1812 let mut chars = pattern.chars();
1813 let mut saw_newline_atom = false;
1814 while let Some(c) = chars.next() {
1815 match c {
1816 '\\' => match chars.next() {
1817 Some('n' | 'r') => saw_newline_atom = true,
1818 _ => return false,
1819 },
1820 '?' | '*' | '+' => {} // quantifiers on the previous atom
1821 _ => return false,
1822 }
1823 }
1824 saw_newline_atom
1825}
1826
1827/// True iff `pattern` matches a (possibly quantified) run of generic
1828/// whitespace characters: `\s+`, `[ \t]+`, ` +`, `\s*`. Such patterns
1829/// describe interstitial spacing rather than syntactic content, so the
1830/// pretty emitter can drop them and let the layout pass insert the
1831/// configured separator.
1832fn is_whitespace_only_pattern(pattern: &str) -> bool {
1833 if pattern.is_empty() {
1834 return false;
1835 }
1836 // Strip an outer quantifier suffix.
1837 let trimmed = pattern.trim_end_matches(['?', '*', '+']);
1838 if trimmed.is_empty() {
1839 return false;
1840 }
1841 // Bare `\s` / ` ` / `\t`.
1842 if matches!(trimmed, "\\s" | " " | "\\t") {
1843 return true;
1844 }
1845 // Character class containing only whitespace atoms.
1846 if let Some(inner) = trimmed.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
1847 let mut chars = inner.chars();
1848 let mut saw_atom = false;
1849 while let Some(c) = chars.next() {
1850 match c {
1851 '\\' => match chars.next() {
1852 Some('s' | 't' | 'r' | 'n') => saw_atom = true,
1853 _ => return false,
1854 },
1855 ' ' | '\t' => saw_atom = true,
1856 _ => return false,
1857 }
1858 }
1859 return saw_atom;
1860 }
1861 false
1862}
1863
1864fn placeholder_for_pattern(pattern: &str) -> String {
1865 // Heuristic placeholder for unconstrained PATTERN terminals.
1866 //
1867 // First handle the "the regex IS a literal escape" cases that
1868 // tree-sitter grammars use as separators (`\n`, `\r\n`, `;`,
1869 // etc.); emitting the matching character is always preferable
1870 // to a `_x` identifier-like placeholder when the surrounding
1871 // grammar expects a separator.
1872 let simple_lit = decode_simple_pattern_literal(pattern);
1873 if let Some(lit) = simple_lit {
1874 return lit;
1875 }
1876
1877 if pattern.contains("[0-9]") || pattern.contains("\\d") {
1878 "0".into()
1879 } else if pattern.contains("[a-zA-Z_]") || pattern.contains("\\w") {
1880 "_x".into()
1881 } else if pattern.contains('"') || pattern.contains('\'') {
1882 "\"\"".into()
1883 } else {
1884 "_".into()
1885 }
1886}
1887
1888/// Decode a tree-sitter PATTERN whose regex is a simple literal
1889/// (newline, semicolon, comma, etc.) to the byte sequence it matches.
1890/// Returns `None` for patterns with character classes, alternations,
1891/// or quantifiers; the caller falls back to the heuristic placeholder.
1892fn decode_simple_pattern_literal(pattern: &str) -> Option<String> {
1893 // Skip patterns containing regex metachars that would broaden the
1894 // match beyond a single literal byte sequence.
1895 if pattern
1896 .chars()
1897 .any(|c| matches!(c, '[' | ']' | '(' | ')' | '*' | '+' | '?' | '|' | '{' | '}'))
1898 {
1899 return None;
1900 }
1901 let mut out = String::new();
1902 let mut chars = pattern.chars();
1903 while let Some(c) = chars.next() {
1904 if c == '\\' {
1905 match chars.next() {
1906 Some('n') => out.push('\n'),
1907 Some('r') => out.push('\r'),
1908 Some('t') => out.push('\t'),
1909 Some('\\') => out.push('\\'),
1910 Some('/') => out.push('/'),
1911 Some(other) => out.push(other),
1912 None => return None,
1913 }
1914 } else {
1915 out.push(c);
1916 }
1917 }
1918 Some(out)
1919}
1920
1921// ═══════════════════════════════════════════════════════════════════
1922// Token list output with Spacing algebra
1923// ═══════════════════════════════════════════════════════════════════
1924//
1925// Emit produces a free monoid over `Token`. Layout (spaces, newlines,
1926// indentation) is a homomorphism `Vec<Token> -> Vec<u8>` parameterised
1927// by `FormatPolicy`. Separating the structural output from the layout
1928// decision means each phase has one job: emit walks the grammar and
1929// pushes tokens; layout is a single fold, locally driven by adjacent
1930// pairs and a depth counter. Snapshot/restore is just `tokens.len()`.
1931
1932#[derive(Clone)]
1933enum Token {
1934 /// A user-visible terminal contributed by the grammar.
1935 Lit(String),
1936 /// `indent_open` marker emitted when a `Lit` matched the policy's
1937 /// open list. Carried as a separate token so layout can decide to
1938 /// break + indent without re-scanning.
1939 IndentOpen,
1940 /// `indent_close` marker emitted before a closer-`Lit`.
1941 IndentClose,
1942 /// "Break a line here if not already at line start" — used after
1943 /// statements/declarations and after open braces.
1944 LineBreak,
1945}
1946
1947struct Output<'a> {
1948 tokens: Vec<Token>,
1949 policy: &'a FormatPolicy,
1950}
1951
1952#[derive(Clone)]
1953struct OutputSnapshot {
1954 tokens_len: usize,
1955}
1956
1957impl<'a> Output<'a> {
1958 fn new(policy: &'a FormatPolicy) -> Self {
1959 Self {
1960 tokens: Vec::new(),
1961 policy,
1962 }
1963 }
1964
1965 fn token(&mut self, value: &str) {
1966 if value.is_empty() {
1967 return;
1968 }
1969
1970 // A grammar STRING whose value is a newline (e.g. abc's `_NL = "\n"`
1971 // or any rule that uses `"\n"` as a structural line terminator)
1972 // must route through the layout's `LineBreak` channel. Emitting it
1973 // as a `Lit` leaves the newline character in the byte stream but
1974 // also makes `needs_space_between` insert the configured separator
1975 // between the newline and the following token, producing leading
1976 // spaces on every line after the first.
1977 if value == "\n" || value == "\r\n" || value == "\r" {
1978 self.tokens.push(Token::LineBreak);
1979 return;
1980 }
1981
1982 if self.policy.indent_close.iter().any(|t| t == value) {
1983 self.tokens.push(Token::IndentClose);
1984 }
1985
1986 self.tokens.push(Token::Lit(value.to_owned()));
1987
1988 if self.policy.indent_open.iter().any(|t| t == value) {
1989 self.tokens.push(Token::IndentOpen);
1990 self.tokens.push(Token::LineBreak);
1991 } else if self.policy.line_break_after.iter().any(|t| t == value) {
1992 self.tokens.push(Token::LineBreak);
1993 }
1994 }
1995
1996 fn newline(&mut self) {
1997 self.tokens.push(Token::LineBreak);
1998 }
1999
2000 /// Open an indent scope: subsequent `LineBreak`s render at the
2001 /// new depth until a matching `indent_close` pops it. Used by the
2002 /// external-token fallback to render indent-based grammars'
2003 /// `_indent` scanner outputs.
2004 fn indent_open(&mut self) {
2005 self.tokens.push(Token::IndentOpen);
2006 self.tokens.push(Token::LineBreak);
2007 }
2008
2009 /// Close one indent scope opened by `indent_open`.
2010 fn indent_close(&mut self) {
2011 self.tokens.push(Token::IndentClose);
2012 }
2013
2014 fn snapshot(&self) -> OutputSnapshot {
2015 OutputSnapshot {
2016 tokens_len: self.tokens.len(),
2017 }
2018 }
2019
2020 fn restore(&mut self, snap: OutputSnapshot) {
2021 self.tokens.truncate(snap.tokens_len);
2022 }
2023
2024 fn finish(self) -> Vec<u8> {
2025 layout(&self.tokens, self.policy)
2026 }
2027}
2028
2029/// Fold a token list into bytes. The algebra:
2030/// * adjacent `Lit`s get a single space iff `needs_space_between(a, b)`,
2031/// * `IndentOpen` / `IndentClose` adjust a depth counter,
2032/// * `LineBreak` writes `\n` if not already at line start, then the
2033/// next `Lit` writes `indent * indent_width` spaces of indent.
2034fn layout(tokens: &[Token], policy: &FormatPolicy) -> Vec<u8> {
2035 let mut bytes = Vec::new();
2036 let mut indent: usize = 0;
2037 let mut at_line_start = true;
2038 let mut last_lit: Option<&str> = None;
2039 // True iff, at the moment `last_lit` was emitted, the cursor was at a
2040 // position where the grammar expects an operand: start of stream / line,
2041 // just after an open paren / bracket / brace, just after a separator like
2042 // `,` or `;`, or just after a binary / assignment operator. Used by
2043 // `needs_space_between` to recognise `last_lit` as a tight unary prefix
2044 // (`f(-1.0)`) rather than a spaced binary operator (`a - b`).
2045 let mut last_was_in_operand_position = true;
2046 let mut expecting_operand = true;
2047 let newline = policy.newline.as_bytes();
2048 let separator = policy.separator.as_bytes();
2049
2050 for tok in tokens {
2051 match tok {
2052 Token::IndentOpen => indent += 1,
2053 Token::IndentClose => {
2054 indent = indent.saturating_sub(1);
2055 if !at_line_start {
2056 bytes.extend_from_slice(newline);
2057 at_line_start = true;
2058 expecting_operand = true;
2059 }
2060 }
2061 Token::LineBreak => {
2062 if !at_line_start {
2063 bytes.extend_from_slice(newline);
2064 at_line_start = true;
2065 expecting_operand = true;
2066 }
2067 }
2068 Token::Lit(value) => {
2069 if at_line_start {
2070 bytes.extend(std::iter::repeat_n(b' ', indent * policy.indent_width));
2071 } else if let Some(prev) = last_lit {
2072 if needs_space_between(prev, value, last_was_in_operand_position) {
2073 bytes.extend_from_slice(separator);
2074 }
2075 }
2076 bytes.extend_from_slice(value.as_bytes());
2077 at_line_start = false;
2078 last_was_in_operand_position = expecting_operand;
2079 expecting_operand = leaves_operand_position(value);
2080 last_lit = Some(value.as_str());
2081 }
2082 }
2083 }
2084
2085 if !at_line_start {
2086 bytes.extend_from_slice(newline);
2087 }
2088 bytes
2089}
2090
2091/// True iff emitting `tok` leaves the cursor in a position where the
2092/// grammar expects an operand next. Operand-introducing tokens are open
2093/// punctuation, separators, and operator-like strings; operand-terminating
2094/// tokens are identifiers, literals, and closing punctuation.
2095fn leaves_operand_position(tok: &str) -> bool {
2096 if tok.is_empty() {
2097 return true;
2098 }
2099 if is_punct_open(tok) {
2100 return true;
2101 }
2102 if matches!(tok, "," | ";") {
2103 return true;
2104 }
2105 if is_punct_close(tok) {
2106 return false;
2107 }
2108 if first_is_alnum_or_underscore(tok) || last_ends_with_alnum(tok) {
2109 return false;
2110 }
2111 // Pure punctuation/operator runs (`=`, `+`, `-`, `<=`, `>>`, …) leave
2112 // the cursor expecting another operand.
2113 true
2114}
2115
2116fn needs_space_between(last: &str, next: &str, expecting_operand: bool) -> bool {
2117 if last.is_empty() || next.is_empty() {
2118 return false;
2119 }
2120 if is_punct_open(last) || is_punct_open(next) {
2121 return false;
2122 }
2123 if is_punct_close(next) {
2124 return false;
2125 }
2126 if is_punct_close(last) && is_punct_punctuation(next) {
2127 return false;
2128 }
2129 if last == "." || next == "." {
2130 return false;
2131 }
2132 // Tight unary prefix: `last` is a sign/logical-not operator emitted
2133 // where the grammar expected an operand, so it glues to `next`.
2134 // `expecting_operand` here means: just before `last` was emitted,
2135 // the cursor expected an operand, which makes `last` a unary prefix.
2136 // Examples: `f(-1.0)`, `[ -2, 3 ]`, `return -x`, `a = !flag`.
2137 if expecting_operand && is_unary_prefix_operator(last) && first_is_operand_start(next) {
2138 return false;
2139 }
2140 if last_is_word_like(last) && first_is_word_like(next) {
2141 return true;
2142 }
2143 if last_ends_with_alnum(last) && first_is_alnum_or_underscore(next) {
2144 return true;
2145 }
2146 // Adjacent operator runs: keep them apart so the lexer doesn't glue
2147 // `>` and `=` into `>=` unintentionally.
2148 true
2149}
2150
2151fn is_unary_prefix_operator(s: &str) -> bool {
2152 matches!(s, "-" | "+" | "!" | "~")
2153}
2154
2155fn first_is_operand_start(s: &str) -> bool {
2156 s.chars()
2157 .next()
2158 .map(|c| c.is_alphanumeric() || c == '_' || c == '.' || c == '(')
2159 .unwrap_or(false)
2160}
2161
2162fn is_punct_open(s: &str) -> bool {
2163 matches!(s, "(" | "[" | "{" | "\"" | "'" | "`")
2164}
2165
2166fn is_punct_close(s: &str) -> bool {
2167 matches!(s, ")" | "]" | "}" | "," | ";" | ":" | "\"" | "'" | "`")
2168}
2169
2170fn is_punct_punctuation(s: &str) -> bool {
2171 matches!(s, "," | ";" | ":" | "." | ")" | "]" | "}")
2172}
2173
2174fn last_is_word_like(s: &str) -> bool {
2175 s.chars()
2176 .next_back()
2177 .map(|c| c.is_alphanumeric() || c == '_')
2178 .unwrap_or(false)
2179}
2180
2181fn first_is_word_like(s: &str) -> bool {
2182 s.chars()
2183 .next()
2184 .map(|c| c.is_alphanumeric() || c == '_')
2185 .unwrap_or(false)
2186}
2187
2188fn last_ends_with_alnum(s: &str) -> bool {
2189 s.chars()
2190 .next_back()
2191 .map(char::is_alphanumeric)
2192 .unwrap_or(false)
2193}
2194
2195fn first_is_alnum_or_underscore(s: &str) -> bool {
2196 s.chars()
2197 .next()
2198 .map(|c| c.is_alphanumeric() || c == '_')
2199 .unwrap_or(false)
2200}
2201
2202#[cfg(test)]
2203mod tests {
2204 use super::*;
2205
2206 #[test]
2207 fn parses_simple_grammar_json() {
2208 let bytes = br#"{
2209 "name": "tiny",
2210 "rules": {
2211 "program": {
2212 "type": "SEQ",
2213 "members": [
2214 {"type": "STRING", "value": "hello"},
2215 {"type": "STRING", "value": ";"}
2216 ]
2217 }
2218 }
2219 }"#;
2220 let g = Grammar::from_bytes("tiny", bytes).expect("valid tiny grammar");
2221 assert!(g.rules.contains_key("program"));
2222 }
2223
2224 #[test]
2225 fn output_emits_punctuation_without_leading_space() {
2226 let policy = FormatPolicy::default();
2227 let mut out = Output::new(&policy);
2228 out.token("foo");
2229 out.token("(");
2230 out.token(")");
2231 out.token(";");
2232 let bytes = out.finish();
2233 let s = std::str::from_utf8(&bytes).expect("ascii output");
2234 assert!(s.starts_with("foo();"), "got {s:?}");
2235 }
2236
2237 #[test]
2238 fn grammar_from_bytes_rejects_malformed_input() {
2239 let result = Grammar::from_bytes("malformed", b"not json");
2240 let err = result.expect_err("malformed bytes must yield Err");
2241 let msg = err.to_string();
2242 assert!(
2243 msg.contains("malformed"),
2244 "error message should name the protocol: {msg:?}"
2245 );
2246 }
2247
2248 #[test]
2249 fn output_indents_after_open_brace() {
2250 let policy = FormatPolicy::default();
2251 let mut out = Output::new(&policy);
2252 out.token("fn");
2253 out.token("foo");
2254 out.token("(");
2255 out.token(")");
2256 out.token("{");
2257 out.token("body");
2258 out.token("}");
2259 let bytes = out.finish();
2260 let s = std::str::from_utf8(&bytes).expect("ascii output");
2261 assert!(s.contains("{\n"), "newline after opening brace: {s:?}");
2262 assert!(s.contains("body"), "body inside block: {s:?}");
2263 assert!(s.ends_with("}\n"), "newline after closing brace: {s:?}");
2264 }
2265
2266 #[test]
2267 fn output_no_space_between_word_and_dot() {
2268 let policy = FormatPolicy::default();
2269 let mut out = Output::new(&policy);
2270 out.token("foo");
2271 out.token(".");
2272 out.token("bar");
2273 let bytes = out.finish();
2274 let s = std::str::from_utf8(&bytes).expect("ascii output");
2275 assert!(s.starts_with("foo.bar"), "no space around dot: {s:?}");
2276 }
2277
2278 #[test]
2279 fn output_snapshot_restore_truncates_bytes() {
2280 let policy = FormatPolicy::default();
2281 let mut out = Output::new(&policy);
2282 out.token("keep");
2283 let snap = out.snapshot();
2284 out.token("drop");
2285 out.token("more");
2286 out.restore(snap);
2287 out.token("after");
2288 let bytes = out.finish();
2289 let s = std::str::from_utf8(&bytes).expect("ascii output");
2290 assert!(s.contains("keep"), "kept token survives: {s:?}");
2291 assert!(s.contains("after"), "post-restore token visible: {s:?}");
2292 assert!(!s.contains("drop"), "rolled-back token removed: {s:?}");
2293 assert!(!s.contains("more"), "rolled-back token removed: {s:?}");
2294 }
2295
2296 #[test]
2297 fn child_cursor_take_field_consumes_once() {
2298 let edges_owned: Vec<Edge> = vec![Edge {
2299 src: panproto_gat::Name::from("p"),
2300 tgt: panproto_gat::Name::from("c"),
2301 kind: panproto_gat::Name::from("name"),
2302 name: None,
2303 }];
2304 let edges: Vec<&Edge> = edges_owned.iter().collect();
2305 let mut cursor = ChildCursor::new(&edges);
2306 let first = cursor.take_field("name");
2307 let second = cursor.take_field("name");
2308 assert!(first.is_some(), "first take returns the edge");
2309 assert!(
2310 second.is_none(),
2311 "second take returns None (already consumed)"
2312 );
2313 }
2314
2315 #[test]
2316 fn child_cursor_take_matching_predicate() {
2317 let edges_owned: Vec<Edge> = vec![
2318 Edge {
2319 src: "p".into(),
2320 tgt: "c1".into(),
2321 kind: "child_of".into(),
2322 name: None,
2323 },
2324 Edge {
2325 src: "p".into(),
2326 tgt: "c2".into(),
2327 kind: "key".into(),
2328 name: None,
2329 },
2330 ];
2331 let edges: Vec<&Edge> = edges_owned.iter().collect();
2332 let mut cursor = ChildCursor::new(&edges);
2333 assert!(cursor.has_matching(|e| e.kind.as_ref() == "key"));
2334 let taken = cursor.take_matching(|e| e.kind.as_ref() == "key");
2335 assert!(taken.is_some());
2336 assert!(
2337 !cursor.has_matching(|e| e.kind.as_ref() == "key"),
2338 "consumed edge no longer matches"
2339 );
2340 assert!(
2341 cursor.has_matching(|e| e.kind.as_ref() == "child_of"),
2342 "the other edge is still available"
2343 );
2344 }
2345
2346 #[test]
2347 fn kind_satisfies_symbol_direct_match() {
2348 let bytes = br#"{
2349 "name": "tiny",
2350 "rules": {
2351 "x": {"type": "STRING", "value": "x"}
2352 }
2353 }"#;
2354 let g = Grammar::from_bytes("tiny", bytes).expect("valid grammar");
2355 assert!(kind_satisfies_symbol(&g, Some("x"), "x"));
2356 assert!(!kind_satisfies_symbol(&g, Some("y"), "x"));
2357 assert!(!kind_satisfies_symbol(&g, None, "x"));
2358 }
2359
2360 #[test]
2361 fn kind_satisfies_symbol_through_hidden_rule() {
2362 let bytes = br#"{
2363 "name": "tiny",
2364 "rules": {
2365 "_value": {
2366 "type": "CHOICE",
2367 "members": [
2368 {"type": "SYMBOL", "name": "object"},
2369 {"type": "SYMBOL", "name": "number"}
2370 ]
2371 },
2372 "object": {"type": "STRING", "value": "{}"},
2373 "number": {"type": "PATTERN", "value": "[0-9]+"}
2374 }
2375 }"#;
2376 let g = Grammar::from_bytes("tiny", bytes).expect("valid grammar");
2377 assert!(
2378 kind_satisfies_symbol(&g, Some("number"), "_value"),
2379 "number is reachable from _value via CHOICE"
2380 );
2381 assert!(
2382 kind_satisfies_symbol(&g, Some("object"), "_value"),
2383 "object is reachable from _value via CHOICE"
2384 );
2385 assert!(
2386 !kind_satisfies_symbol(&g, Some("string"), "_value"),
2387 "string is NOT among the alternatives"
2388 );
2389 }
2390
2391 #[test]
2392 fn first_symbol_skips_string_terminals() {
2393 let prod: Production = serde_json::from_str(
2394 r#"{
2395 "type": "SEQ",
2396 "members": [
2397 {"type": "STRING", "value": "{"},
2398 {"type": "SYMBOL", "name": "body"},
2399 {"type": "STRING", "value": "}"}
2400 ]
2401 }"#,
2402 )
2403 .expect("valid SEQ");
2404 assert_eq!(first_symbol(&prod), Some("body"));
2405 }
2406
2407 #[test]
2408 fn placeholder_for_pattern_routes_by_regex_class() {
2409 assert_eq!(placeholder_for_pattern("[0-9]+"), "0");
2410 assert_eq!(placeholder_for_pattern("[a-zA-Z_]\\w*"), "_x");
2411 assert_eq!(placeholder_for_pattern("\"[^\"]*\""), "\"\"");
2412 assert_eq!(placeholder_for_pattern("\\d+\\.\\d+"), "0");
2413 }
2414
2415 #[test]
2416 fn format_policy_default_breaks_after_semicolon() {
2417 let policy = FormatPolicy::default();
2418 assert!(policy.line_break_after.iter().any(|t| t == ";"));
2419 assert!(policy.indent_open.iter().any(|t| t == "{"));
2420 assert!(policy.indent_close.iter().any(|t| t == "}"));
2421 assert_eq!(policy.indent_width, 2);
2422 }
2423
2424 #[test]
2425 fn placeholder_decodes_literal_pattern_separators() {
2426 // PATTERN regexes that match a single literal byte sequence
2427 // (newline, semicolon, comma) emit the bytes verbatim instead
2428 // of falling through to the `_` catch-all.
2429 assert_eq!(placeholder_for_pattern("\\n"), "\n");
2430 assert_eq!(placeholder_for_pattern("\\r\\n"), "\r\n");
2431 assert_eq!(placeholder_for_pattern(";"), ";");
2432 // Patterns with character classes / alternation still route
2433 // through the heuristic.
2434 assert_eq!(placeholder_for_pattern("[0-9]+"), "0");
2435 assert_eq!(placeholder_for_pattern("a|b"), "_");
2436 }
2437
2438 #[test]
2439 fn supertypes_decode_from_grammar_json_strings() {
2440 // Tree-sitter older grammars list supertypes as bare strings.
2441 let bytes = br#"{
2442 "name": "tiny",
2443 "supertypes": ["expression"],
2444 "rules": {
2445 "expression": {
2446 "type": "CHOICE",
2447 "members": [
2448 {"type": "SYMBOL", "name": "binary_expression"},
2449 {"type": "SYMBOL", "name": "identifier"}
2450 ]
2451 },
2452 "binary_expression": {"type": "STRING", "value": "x"},
2453 "identifier": {"type": "PATTERN", "value": "[a-z]+"}
2454 }
2455 }"#;
2456 let g = Grammar::from_bytes("tiny", bytes).expect("parse");
2457 assert!(g.supertypes.contains("expression"));
2458 // identifier matches the supertype `expression`.
2459 assert!(kind_satisfies_symbol(&g, Some("identifier"), "expression"));
2460 // unrelated kinds do not.
2461 assert!(!kind_satisfies_symbol(&g, Some("string"), "expression"));
2462 }
2463
2464 #[test]
2465 fn supertypes_decode_from_grammar_json_objects() {
2466 // Recent grammars list supertypes as `{type: SYMBOL, name: ...}`
2467 // entries instead of bare strings.
2468 let bytes = br#"{
2469 "name": "tiny",
2470 "supertypes": [{"type": "SYMBOL", "name": "stmt"}],
2471 "rules": {
2472 "stmt": {
2473 "type": "CHOICE",
2474 "members": [
2475 {"type": "SYMBOL", "name": "while_stmt"},
2476 {"type": "SYMBOL", "name": "if_stmt"}
2477 ]
2478 },
2479 "while_stmt": {"type": "STRING", "value": "while"},
2480 "if_stmt": {"type": "STRING", "value": "if"}
2481 }
2482 }"#;
2483 let g = Grammar::from_bytes("tiny", bytes).expect("parse");
2484 assert!(g.supertypes.contains("stmt"));
2485 assert!(kind_satisfies_symbol(&g, Some("while_stmt"), "stmt"));
2486 }
2487
2488 #[test]
2489 fn alias_value_matches_kind() {
2490 // A named ALIAS rewrites the parser-visible kind to `value`;
2491 // `kind_satisfies_symbol` should accept that rewritten kind
2492 // when looking up the original SYMBOL.
2493 let bytes = br#"{
2494 "name": "tiny",
2495 "rules": {
2496 "_package_identifier": {
2497 "type": "ALIAS",
2498 "named": true,
2499 "value": "package_identifier",
2500 "content": {"type": "SYMBOL", "name": "identifier"}
2501 },
2502 "identifier": {"type": "PATTERN", "value": "[a-z]+"}
2503 }
2504 }"#;
2505 let g = Grammar::from_bytes("tiny", bytes).expect("parse");
2506 assert!(kind_satisfies_symbol(
2507 &g,
2508 Some("package_identifier"),
2509 "_package_identifier"
2510 ));
2511 }
2512
2513 #[test]
2514 fn referenced_symbols_walks_nested_seq() {
2515 let prod: Production = serde_json::from_str(
2516 r#"{
2517 "type": "SEQ",
2518 "members": [
2519 {"type": "CHOICE", "members": [
2520 {"type": "SYMBOL", "name": "attribute_item"},
2521 {"type": "BLANK"}
2522 ]},
2523 {"type": "SYMBOL", "name": "parameter"},
2524 {"type": "REPEAT", "content": {
2525 "type": "SEQ",
2526 "members": [
2527 {"type": "STRING", "value": ","},
2528 {"type": "SYMBOL", "name": "parameter"}
2529 ]
2530 }}
2531 ]
2532 }"#,
2533 )
2534 .expect("seq");
2535 let symbols = referenced_symbols(&prod);
2536 assert!(symbols.contains(&"attribute_item"));
2537 assert!(symbols.contains(&"parameter"));
2538 }
2539
2540 #[test]
2541 fn literal_strings_collects_choice_members() {
2542 let prod: Production = serde_json::from_str(
2543 r#"{
2544 "type": "CHOICE",
2545 "members": [
2546 {"type": "STRING", "value": "+"},
2547 {"type": "STRING", "value": "-"},
2548 {"type": "STRING", "value": "*"}
2549 ]
2550 }"#,
2551 )
2552 .expect("choice");
2553 let strings = literal_strings(&prod);
2554 assert_eq!(strings, vec!["+", "-", "*"]);
2555 }
2556
2557 /// The ocaml and javascript grammars (tree-sitter ≥ 0.25) emit a
2558 /// `RESERVED` rule kind that an earlier deserialiser rejected
2559 /// with `unknown variant "RESERVED"`. Verify both that the bare
2560 /// variant deserialises and that a `RESERVED`-wrapped grammar is
2561 /// loadable end-to-end via [`Grammar::from_bytes`].
2562 #[test]
2563 fn reserved_variant_deserialises() {
2564 let prod: Production = serde_json::from_str(
2565 r#"{
2566 "type": "RESERVED",
2567 "content": {"type": "SYMBOL", "name": "_lowercase_identifier"},
2568 "context_name": "attribute_id"
2569 }"#,
2570 )
2571 .expect("RESERVED parses");
2572 match prod {
2573 Production::Reserved { content, .. } => match *content {
2574 Production::Symbol { name } => assert_eq!(name, "_lowercase_identifier"),
2575 other => panic!("expected inner SYMBOL, got {other:?}"),
2576 },
2577 other => panic!("expected RESERVED, got {other:?}"),
2578 }
2579 }
2580
2581 #[test]
2582 fn reserved_grammar_loads_end_to_end() {
2583 let bytes = br#"{
2584 "name": "tiny_reserved",
2585 "rules": {
2586 "program": {
2587 "type": "RESERVED",
2588 "content": {"type": "SYMBOL", "name": "ident"},
2589 "context_name": "keywords"
2590 },
2591 "ident": {"type": "PATTERN", "value": "[a-z]+"}
2592 }
2593 }"#;
2594 let g = Grammar::from_bytes("tiny_reserved", bytes).expect("RESERVED-using grammar loads");
2595 assert!(g.rules.contains_key("program"));
2596 }
2597
2598 #[test]
2599 fn reserved_walker_helpers_recurse_into_content() {
2600 // The walker's helpers (first_symbol, has_field_in,
2601 // referenced_symbols, ...) all need to descend through
2602 // RESERVED into its content. If they bail at RESERVED, the
2603 // `pick_choice_with_cursor` heuristic ranks the alt below
2604 // alts that DO recurse, which produces wrong emit output
2605 // even when the deserialiser doesn't crash.
2606 let prod: Production = serde_json::from_str(
2607 r#"{
2608 "type": "RESERVED",
2609 "content": {
2610 "type": "FIELD",
2611 "name": "lhs",
2612 "content": {"type": "SYMBOL", "name": "expr"}
2613 },
2614 "context_name": "ctx"
2615 }"#,
2616 )
2617 .expect("nested RESERVED parses");
2618 assert_eq!(first_symbol(&prod), Some("expr"));
2619 assert!(has_field_in(&prod, &["lhs"]));
2620 let symbols = referenced_symbols(&prod);
2621 assert!(symbols.contains(&"expr"));
2622 }
2623}