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 // Detect a "separator-leading SEQ" iteration body: SEQ whose
1117 // first member is a CHOICE containing BLANK (or an OPTIONAL),
1118 // i.e. the source-level separator between two iterations is
1119 // syntactically optional. When the chosen alternative for
1120 // that separator slot emits zero content tokens at runtime,
1121 // there was no source-level separator between this iteration
1122 // and the previous one; the layout pass must suppress its
1123 // policy separator to match the source's tight adjacency.
1124 //
1125 // Categorical reading: REPEAT body `B = SEQ(SEP, BODY)` is
1126 // the pullback of two halves. The bytes emitted in iteration
1127 // k+1 are a concatenation of `SEP_k+1` and `BODY_k+1`; if
1128 // `SEP_k+1` is the empty word, the concatenation of
1129 // `BODY_k` and `BODY_k+1` must remain a single contiguous
1130 // span. Hence the NoSpace marker.
1131 let separator_leading_seq: Option<&[Production]> = match content.as_ref() {
1132 Production::Seq { members } if members.len() >= 2 => {
1133 let first = &members[0];
1134 let is_separator_slot = match first {
1135 Production::Choice { members } => {
1136 members.iter().any(|m| matches!(m, Production::Blank))
1137 }
1138 Production::Optional { .. } => true,
1139 _ => false,
1140 };
1141 if is_separator_slot {
1142 Some(members.as_slice())
1143 } else {
1144 None
1145 }
1146 }
1147 _ => None,
1148 };
1149
1150 let mut emitted_any = false;
1151 loop {
1152 let cursor_snap = cursor.consumed.clone();
1153 let out_snap = out.snapshot();
1154 let consumed_before = cursor.consumed.iter().filter(|&&c| c).count();
1155 let result: Result<(), ParseError> =
1156 if let Some(seq_members) = separator_leading_seq {
1157 // Emit the separator slot first and observe
1158 // whether it contributed any Lit. If not, push
1159 // a NoSpace marker before walking the remaining
1160 // SEQ members. The OutputSnapshot here covers
1161 // only the separator's emission window.
1162 let pre_sep = out.snapshot();
1163 let sep_result = emit_production(
1164 protocol,
1165 schema,
1166 grammar,
1167 vertex_id,
1168 &seq_members[0],
1169 cursor,
1170 out,
1171 );
1172 match sep_result {
1173 Err(e) => Err(e),
1174 Ok(()) => {
1175 if !out.lit_emitted_since(pre_sep) {
1176 out.no_space();
1177 }
1178 let mut rest_result = Ok(());
1179 for member in &seq_members[1..] {
1180 rest_result = emit_production(
1181 protocol, schema, grammar, vertex_id, member, cursor, out,
1182 );
1183 if rest_result.is_err() {
1184 break;
1185 }
1186 }
1187 rest_result
1188 }
1189 }
1190 } else {
1191 emit_production(protocol, schema, grammar, vertex_id, content, cursor, out)
1192 };
1193 let consumed_after = cursor.consumed.iter().filter(|&&c| c).count();
1194 if result.is_err() || consumed_after == consumed_before {
1195 cursor.consumed = cursor_snap;
1196 out.restore(out_snap);
1197 break;
1198 }
1199 emitted_any = true;
1200 }
1201 if matches!(production, Production::Repeat1 { .. }) && !emitted_any {
1202 emit_production(protocol, schema, grammar, vertex_id, content, cursor, out)?;
1203 }
1204 Ok(())
1205 }
1206 Production::Optional { content } => {
1207 let cursor_snap = cursor.consumed.clone();
1208 let out_snap = out.snapshot();
1209 let consumed_before = cursor.consumed.iter().filter(|&&c| c).count();
1210 let result =
1211 emit_production(protocol, schema, grammar, vertex_id, content, cursor, out);
1212 // OPTIONAL is a backtracking site: if the inner production
1213 // errored *or* made no progress without leaving a witness
1214 // constraint, restore both cursor and output to their
1215 // pre-attempt state. Mirrors `Repeat`'s loop body.
1216 if result.is_err() {
1217 cursor.consumed = cursor_snap;
1218 out.restore(out_snap);
1219 return result;
1220 }
1221 let consumed_after = cursor.consumed.iter().filter(|&&c| c).count();
1222 if consumed_after == consumed_before
1223 && !has_relevant_constraint(content, schema, vertex_id)
1224 {
1225 cursor.consumed = cursor_snap;
1226 out.restore(out_snap);
1227 }
1228 Ok(())
1229 }
1230 Production::Field { name, content } => {
1231 // Set the field context for the duration of `content`'s
1232 // walk and emit the content against the *outer* cursor.
1233 // The SYMBOL handler picks up the context and pulls
1234 // successive `take_field(name)` edges as it encounters
1235 // SYMBOLs anywhere under `content` (under SEQ, CHOICE,
1236 // REPEAT, OPTIONAL, ALIAS — arbitrarily nested). This
1237 // subsumes the prior carve-outs for FIELD(REPEAT(...)),
1238 // FIELD(REPEAT1(...)), and the bare FIELD(SYMBOL ...)
1239 // case, and adds coverage for
1240 // `field('xs', commaSep1($.X))` which expands to
1241 // FIELD(SEQ(SYMBOL X, REPEAT(SEQ(',', SYMBOL X)))) and
1242 // any other shape where REPEAT/REPEAT1 sits inside SEQ /
1243 // CHOICE / OPTIONAL under a FIELD. A FIELD that wraps a
1244 // non-SYMBOL production (e.g. `field('op', '+')` or
1245 // `field('op', CHOICE(STRING ...))`) still works: STRING
1246 // handlers ignore the context and emit literals
1247 // directly, so the operator token survives the round
1248 // trip.
1249 let _guard = push_field_context(name);
1250 emit_production(protocol, schema, grammar, vertex_id, content, cursor, out)
1251 }
1252 Production::Alias {
1253 content,
1254 named,
1255 value,
1256 } => {
1257 // A named ALIAS rewrites the parser-visible kind to
1258 // `value`. If the cursor has an unconsumed child whose
1259 // kind matches that alias name, take it and emit the
1260 // child using the alias's INNER content as the rule
1261 // (e.g. `ALIAS { SYMBOL real_rule, value: "kind_x" }`
1262 // means a `kind_x` vertex on the schema should be walked
1263 // through `real_rule`'s body, not through whatever rule
1264 // happens to be keyed under `kind_x`). This is the
1265 // dependent-optic shape: the rule the emitter walks at a
1266 // child position is determined by the parent's chosen
1267 // alias, not by the child kind alone — without it,
1268 // grammars like YAML that introduce the same kind through
1269 // many ALIAS sites lose the parent context the moment
1270 // emit_vertex is called.
1271 if *named && !value.is_empty() {
1272 if let Some(edge) = cursor.take_matching(|edge| {
1273 schema
1274 .vertices
1275 .get(&edge.tgt)
1276 .map(|v| v.kind.as_ref() == value.as_str())
1277 .unwrap_or(false)
1278 }) {
1279 return emit_aliased_child(protocol, schema, grammar, &edge.tgt, content, out);
1280 }
1281 }
1282 emit_production(protocol, schema, grammar, vertex_id, content, cursor, out)
1283 }
1284 Production::Token { content }
1285 | Production::ImmediateToken { content }
1286 | Production::Prec { content, .. }
1287 | Production::PrecLeft { content, .. }
1288 | Production::PrecRight { content, .. }
1289 | Production::PrecDynamic { content, .. }
1290 | Production::Reserved { content, .. } => {
1291 emit_production(protocol, schema, grammar, vertex_id, content, cursor, out)
1292 }
1293 }
1294}
1295
1296/// Take the next cursor edge whose target vertex's kind matches the
1297/// SYMBOL `name` directly or via inline expansion of a hidden rule.
1298fn take_symbol_match<'a>(
1299 grammar: &Grammar,
1300 schema: &Schema,
1301 cursor: &mut ChildCursor<'a>,
1302 name: &str,
1303) -> Option<&'a Edge> {
1304 cursor.take_matching(|edge| {
1305 let target_kind = schema.vertices.get(&edge.tgt).map(|v| v.kind.as_ref());
1306 kind_satisfies_symbol(grammar, target_kind, name)
1307 })
1308}
1309
1310/// Decide whether a schema vertex of kind `target_kind` satisfies a
1311/// SYMBOL `name` reference in the grammar.
1312///
1313/// Operates as an O(1) lookup against the precomputed subtype
1314/// closure built at [`Grammar::from_bytes`]. The semantic content is
1315/// "K satisfies SYMBOL S iff K is reachable from S by walking the
1316/// grammar's hidden, supertype, and named-alias dispatch": this is
1317/// exactly the relation tree-sitter induces on `(parser-visible kind,
1318/// rule-position)` pairs.
1319fn kind_satisfies_symbol(grammar: &Grammar, target_kind: Option<&str>, name: &str) -> bool {
1320 let Some(target) = target_kind else {
1321 return false;
1322 };
1323 if target == name {
1324 return true;
1325 }
1326 grammar
1327 .subtypes
1328 .get(target)
1329 .is_some_and(|set| set.contains(name))
1330}
1331
1332/// Emit a child reached through an ALIAS production using the
1333/// alias's inner content as the rule, not `grammar.rules[child.kind]`.
1334///
1335/// This carries the dependent-optic context across the ALIAS edge:
1336/// at the parent rule's site we know which underlying production the
1337/// alias wraps (typically `SYMBOL real_rule`), and that's the
1338/// production that should drive the emit walk on the child's
1339/// children. Looking up `grammar.rules.get(child.kind)` instead would
1340/// either fail (the renamed kind has no top-level rule, e.g. YAML's
1341/// `block_mapping_pair`) or pick an arbitrary same-kinded rule from
1342/// elsewhere in the grammar.
1343///
1344/// Walk-context invariant. The dependent-optic shape of `emit_pretty`
1345/// says: the production walked at any vertex is determined by the
1346/// path from the root through the grammar, not by the vertex kind in
1347/// isolation. Two dispatch sites realise that invariant:
1348///
1349/// * [`emit_vertex`] looks up `grammar.rules[child.kind]` and walks
1350/// it. Correct for supertype / hidden-rule dispatch: the child's
1351/// kind on the schema IS the subtype tree-sitter selected, so its
1352/// top-level rule is the right production to walk.
1353/// * `emit_aliased_child` threads the parent rule's `Production`
1354/// directly (the inner `content` of `Production::Alias`) and walks
1355/// it on the child's children. Correct for ALIAS dispatch: the
1356/// child's kind on the schema is the alias's `value` (a renamed
1357/// kind that may have no top-level rule), and the production to
1358/// walk is the alias's content body, supplied by the parent.
1359///
1360/// Together these cover every site where the rule-walked-at-child
1361/// diverges from `grammar.rules[child.kind]`; the recursion site for
1362/// plain SYMBOL therefore correctly delegates to `emit_vertex`, and
1363/// we do not need a richer `WalkContext` value passed by reference.
1364/// The grammar dependency is the thread.
1365fn emit_aliased_child(
1366 protocol: &str,
1367 schema: &Schema,
1368 grammar: &Grammar,
1369 child_id: &panproto_gat::Name,
1370 content: &Production,
1371 out: &mut Output<'_>,
1372) -> Result<(), ParseError> {
1373 // Leaf shortcut: if the child has a literal-value and no
1374 // structural children, emit the captured text. Identifiers and
1375 // similar terminals reach here when an ALIAS wraps a SYMBOL that
1376 // resolves to a PATTERN.
1377 if let Some(literal) = literal_value(schema, child_id) {
1378 if children_for(schema, child_id).is_empty() {
1379 out.token(literal);
1380 return Ok(());
1381 }
1382 }
1383
1384 // Resolve `content` to a rule when it's a SYMBOL (the dominant
1385 // shape: `ALIAS { content: SYMBOL real_rule, value: "kind_x" }`).
1386 if let Production::Symbol { name } = content {
1387 if let Some(rule) = grammar.rules.get(name) {
1388 let edges = children_for(schema, child_id);
1389 let mut cursor = ChildCursor::new(&edges);
1390 return emit_production(protocol, schema, grammar, child_id, rule, &mut cursor, out);
1391 }
1392 }
1393
1394 // Other ALIAS contents (CHOICE, SEQ, literals) walk in place.
1395 let edges = children_for(schema, child_id);
1396 let mut cursor = ChildCursor::new(&edges);
1397 emit_production(
1398 protocol,
1399 schema,
1400 grammar,
1401 child_id,
1402 content,
1403 &mut cursor,
1404 out,
1405 )
1406}
1407
1408fn emit_in_child_context(
1409 protocol: &str,
1410 schema: &Schema,
1411 grammar: &Grammar,
1412 child_id: &panproto_gat::Name,
1413 production: &Production,
1414 out: &mut Output<'_>,
1415) -> Result<(), ParseError> {
1416 // The child walks under its own production tree, with its own
1417 // FIELDs setting their own contexts. Clear the outer FIELD hint
1418 // so it does not leak through and cause sibling SYMBOLs inside
1419 // the child's body to mistakenly pull edges from the child's
1420 // cursor by the parent's field name.
1421 let _guard = clear_field_context();
1422 // If `production` is a structural wrapper (CHOICE / SEQ /
1423 // OPTIONAL / ...) whose referenced symbols cover the child's own
1424 // kind, the child IS the production's target node and the right
1425 // emit path is `emit_vertex(child)` (which honours the
1426 // literal-value leaf shortcut). Without this guard, FIELD(pattern,
1427 // CHOICE { _pattern, self }) on an identifier child walks the
1428 // CHOICE on the identifier's empty cursor, falls through to the
1429 // first non-BLANK alt, and loses the captured identifier text.
1430 if !matches!(production, Production::Symbol { .. }) {
1431 let child_kind = schema.vertices.get(child_id).map(|v| v.kind.as_ref());
1432 let symbols = referenced_symbols(production);
1433 if symbols
1434 .iter()
1435 .any(|s| kind_satisfies_symbol(grammar, child_kind, s) || child_kind == Some(s))
1436 {
1437 return emit_vertex(protocol, schema, grammar, child_id, out);
1438 }
1439 }
1440 match production {
1441 Production::Symbol { .. } => emit_vertex(protocol, schema, grammar, child_id, out),
1442 _ => {
1443 let edges = children_for(schema, child_id);
1444 let mut cursor = ChildCursor::new(&edges);
1445 emit_production(
1446 protocol,
1447 schema,
1448 grammar,
1449 child_id,
1450 production,
1451 &mut cursor,
1452 out,
1453 )
1454 }
1455 }
1456}
1457
1458fn pick_choice_with_cursor<'a>(
1459 schema: &Schema,
1460 grammar: &Grammar,
1461 vertex_id: &panproto_gat::Name,
1462 cursor: &ChildCursor<'_>,
1463 alternatives: &'a [Production],
1464) -> Option<&'a Production> {
1465 // Discriminator-driven dispatch (highest priority): when the
1466 // walker recorded a `chose-alt-fingerprint` constraint at parse
1467 // time, dispatch directly against that. This is the categorical
1468 // discriminator: it survives stripping of byte-position
1469 // constraints (so by-construction round-trips work) and is the
1470 // explicit witness of which CHOICE alternative the parser took.
1471 //
1472 // Falls back to the live `interstitial-*` substring blob when no
1473 // fingerprint is present (e.g. instances built by callers that
1474 // bypass the AstWalker). Both blobs are scored by the longest
1475 // STRING-literal token in an alternative that matches; the
1476 // length tiebreak prefers `&&` over `&`, `==` over `=`, etc.
1477 let constraint_blob = schema
1478 .constraints
1479 .get(vertex_id)
1480 .map(|cs| {
1481 let fingerprint: Option<&str> = cs
1482 .iter()
1483 .find(|c| c.sort.as_ref() == "chose-alt-fingerprint")
1484 .map(|c| c.value.as_str());
1485 if let Some(fp) = fingerprint {
1486 fp.to_owned()
1487 } else {
1488 cs.iter()
1489 .filter(|c| {
1490 let s = c.sort.as_ref();
1491 s.starts_with("interstitial-") && !s.ends_with("-start-byte")
1492 })
1493 .map(|c| c.value.as_str())
1494 .collect::<Vec<&str>>()
1495 .join(" ")
1496 }
1497 })
1498 .unwrap_or_default();
1499 let child_kinds: Vec<&str> = schema
1500 .constraints
1501 .get(vertex_id)
1502 .and_then(|cs| {
1503 cs.iter()
1504 .find(|c| c.sort.as_ref() == "chose-alt-child-kinds")
1505 .map(|c| c.value.split_whitespace().collect())
1506 })
1507 .unwrap_or_default();
1508 // Cursor-exhaustion BLANK-preference: when all cursor edges have
1509 // been consumed AND `BLANK` is one of the alternatives, the only
1510 // alt that won't introduce a non-existent child is `BLANK`.
1511 //
1512 // This gate fires before the literal-blob discriminator because
1513 // the fingerprint is shared across every CHOICE position in the
1514 // vertex's rule body: a vertex like `sample_step` that ends in
1515 // `..., REPEAT(SEQ(",", arg)), CHOICE(",", BLANK)` records all of
1516 // its `","` interstitials in a single blob, so the literal-score
1517 // matcher would otherwise prefer `","` for the trailing CHOICE
1518 // even when the source had no trailing comma. By the time the
1519 // emitter reaches the trailing CHOICE, the REPEAT has consumed
1520 // every arg edge in cursor order; the residual unconsumed multiset
1521 // is empty; and the categorical reading of a CHOICE-with-BLANK at
1522 // a position with no remaining children is the no-op alternative.
1523 let any_unconsumed = cursor
1524 .edges
1525 .iter()
1526 .enumerate()
1527 .any(|(i, _)| !cursor.consumed[i]);
1528 let blank_present = alternatives.iter().any(|a| matches!(a, Production::Blank));
1529 if !any_unconsumed && blank_present {
1530 return alternatives.iter().find(|a| matches!(a, Production::Blank));
1531 }
1532
1533 if !constraint_blob.is_empty() {
1534 // Primary score: literal-token match length. This dominates
1535 // alt selection so existing language tests that depend on
1536 // literal-only fingerprints keep working.
1537 // Secondary score (tiebreaker only): named-symbol kind match
1538 // count, read from the separate `chose-alt-child-kinds`
1539 // constraint (kept apart from the literal fingerprint so
1540 // identifiers like `:` in the kind list don't contaminate the
1541 // literal match). An alt that matches the recorded kinds is a
1542 // stronger witness than one whose only
1543 // overlap is literal punctuation.
1544 let mut best_literal: usize = 0;
1545 let mut best_symbols: usize = 0;
1546 let mut best_alt: Option<&Production> = None;
1547 let mut tied = false;
1548 for alt in alternatives {
1549 let strings = literal_strings(alt);
1550 if strings.is_empty() {
1551 continue;
1552 }
1553 let literal_score = strings
1554 .iter()
1555 .filter(|s| constraint_blob.contains(s.as_str()))
1556 .map(String::len)
1557 .sum::<usize>();
1558 if literal_score == 0 {
1559 continue;
1560 }
1561 // Symbol score is computed only as a tiebreaker among alts
1562 // whose literal-token coverage is the same; it never lifts
1563 // an alt above one with a strictly higher literal score.
1564 // Reads the `chose-alt-child-kinds` constraint (a separate
1565 // sequence the walker emits, kept apart from the literal
1566 // fingerprint to avoid cross-contamination).
1567 let symbol_score = if literal_score >= best_literal && !child_kinds.is_empty() {
1568 let symbols = referenced_symbols(alt);
1569 symbols
1570 .iter()
1571 .filter(|sym| {
1572 let sym_str: &str = sym;
1573 if child_kinds.contains(&sym_str) {
1574 return true;
1575 }
1576 grammar.subtypes.get(sym_str).is_some_and(|sub_set| {
1577 sub_set
1578 .iter()
1579 .any(|sub| child_kinds.contains(&sub.as_str()))
1580 })
1581 })
1582 .count()
1583 } else {
1584 0
1585 };
1586 let better = literal_score > best_literal
1587 || (literal_score == best_literal && symbol_score > best_symbols);
1588 let same = literal_score == best_literal && symbol_score == best_symbols;
1589 if better {
1590 best_literal = literal_score;
1591 best_symbols = symbol_score;
1592 best_alt = Some(alt);
1593 tied = false;
1594 } else if same && best_alt.is_some() {
1595 tied = true;
1596 }
1597 }
1598 // Only commit to an alt when the fingerprint discriminates it
1599 // uniquely. A tie means the alts share the same literal token
1600 // set (e.g. JSON's `string = CHOICE { SEQ { '"', '"' }, SEQ {
1601 // '"', _string_content, '"' } }` — both alts contain just the
1602 // two `"` tokens). In that case fall through to cursor-based
1603 // dispatch, which uses the actual edge structure.
1604 if let Some(alt) = best_alt {
1605 if !tied {
1606 return Some(alt);
1607 }
1608 }
1609 }
1610
1611 // Cursor-driven dispatch: pick the alternative whose body
1612 // references a SYMBOL covering the *first unconsumed* edge in
1613 // cursor order. `referenced_symbols` walks the alternative
1614 // recursively (across nested SEQs, REPEATs, OPTIONALs, FIELDs,
1615 // etc.) so a leading optional like `attribute_item` does not
1616 // block matching when only the trailing required symbol is
1617 // present on the schema.
1618 //
1619 // Ordering by the first unconsumed edge (rather than picking any
1620 // alternative whose SYMBOL set intersects the unconsumed
1621 // multiset) is what preserves schema edge order under
1622 // REPEAT(CHOICE(...)) productions. Without this rule, alt order
1623 // in the grammar's CHOICE determines the emission order, and a
1624 // schema with interleaved kinds like `[symbol, punct, int,
1625 // symbol, punct, int]` re-fuses to `[symbol, symbol, punct,
1626 // punct, int, int]` when emitted then re-parsed. The fix is the
1627 // categorical reading of REPEAT-over-list (list-shaped fold)
1628 // rather than REPEAT-over-multiset (unordered fold).
1629 let first_unconsumed_kind: Option<&str> = cursor
1630 .edges
1631 .iter()
1632 .enumerate()
1633 .find(|(i, _)| !cursor.consumed[*i])
1634 .and_then(|(_, edge)| schema.vertices.get(&edge.tgt).map(|v| v.kind.as_ref()));
1635 if let Some(target_kind) = first_unconsumed_kind {
1636 for alt in alternatives {
1637 let symbols = referenced_symbols(alt);
1638 if !symbols.is_empty()
1639 && symbols
1640 .iter()
1641 .any(|s| kind_satisfies_symbol(grammar, Some(target_kind), s))
1642 {
1643 return Some(alt);
1644 }
1645 }
1646 }
1647
1648 // FIELD dispatch: pick an alternative whose FIELD name matches an
1649 // unconsumed edge kind.
1650 let edge_kinds: Vec<&str> = cursor
1651 .edges
1652 .iter()
1653 .enumerate()
1654 .filter(|(i, _)| !cursor.consumed[*i])
1655 .map(|(_, e)| e.kind.as_ref())
1656 .collect();
1657 for alt in alternatives {
1658 if has_field_in(alt, &edge_kinds) {
1659 return Some(alt);
1660 }
1661 }
1662
1663 // No cursor-driven match. Fall back to:
1664 //
1665 // - BLANK (the explicit empty alternative) when present, so an
1666 // OPTIONAL-shaped CHOICE compiles to nothing.
1667 // - The first non-`BLANK` alternative as a last resort, used by
1668 // STRING-only alternatives (keyword tokens) and other choices
1669 // that don't reach the cursor.
1670 //
1671 // The previous "match own_kind" branch is intentionally absent:
1672 // when an alt's first SYMBOL equals the current vertex's kind, the
1673 // caller is already emitting that vertex's own rule. Recursing
1674 // into the alt would cause a self-loop in the rule walk.
1675 let _ = (schema, vertex_id);
1676 if alternatives.iter().any(|a| matches!(a, Production::Blank)) {
1677 return alternatives.iter().find(|a| matches!(a, Production::Blank));
1678 }
1679 alternatives
1680 .iter()
1681 .find(|alt| !matches!(alt, Production::Blank))
1682}
1683
1684/// Collect every literal STRING token directly inside `production`
1685/// (without descending into SYMBOLs / hidden rules). Used to score
1686/// CHOICE alternatives against the parent vertex's interstitials so
1687/// the right operator / keyword form is picked when the schema
1688/// preserves interstitial fragments from a prior parse.
1689fn literal_strings(production: &Production) -> Vec<String> {
1690 let mut out = Vec::new();
1691 fn walk(p: &Production, out: &mut Vec<String>) {
1692 match p {
1693 Production::String { value } if !value.is_empty() => {
1694 out.push(value.clone());
1695 }
1696 Production::Choice { members } | Production::Seq { members } => {
1697 for m in members {
1698 walk(m, out);
1699 }
1700 }
1701 Production::Repeat { content }
1702 | Production::Repeat1 { content }
1703 | Production::Optional { content }
1704 | Production::Field { content, .. }
1705 | Production::Alias { content, .. }
1706 | Production::Token { content }
1707 | Production::ImmediateToken { content }
1708 | Production::Prec { content, .. }
1709 | Production::PrecLeft { content, .. }
1710 | Production::PrecRight { content, .. }
1711 | Production::PrecDynamic { content, .. }
1712 | Production::Reserved { content, .. } => walk(content, out),
1713 _ => {}
1714 }
1715 }
1716 walk(production, &mut out);
1717 out
1718}
1719
1720/// Collect every SYMBOL name reachable from `production` without
1721/// crossing into nested rules. Used by `pick_choice_with_cursor` to
1722/// rank alternatives by "any SYMBOL inside this alt matches something
1723/// on the cursor", instead of just the first SYMBOL: a leading
1724/// optional like `attribute_item` then `parameter` is otherwise
1725/// rejected when only the parameter children are present.
1726fn referenced_symbols(production: &Production) -> Vec<&str> {
1727 let mut out = Vec::new();
1728 fn walk<'a>(p: &'a Production, out: &mut Vec<&'a str>) {
1729 match p {
1730 Production::Symbol { name } => out.push(name.as_str()),
1731 Production::Choice { members } | Production::Seq { members } => {
1732 for m in members {
1733 walk(m, out);
1734 }
1735 }
1736 Production::Alias {
1737 content,
1738 named,
1739 value,
1740 } => {
1741 // A named ALIAS produces a child vertex whose kind is
1742 // the alias `value` (e.g. `ALIAS { content: STRING "=",
1743 // value: "punctuation", named: true }` introduces a
1744 // `punctuation` child). For cursor-driven dispatch to
1745 // recognise alts that emit such children, yield the
1746 // alias value as a referenced symbol. Anonymous aliases
1747 // do not introduce a named node and only need their
1748 // inner content's symbols.
1749 if *named && !value.is_empty() {
1750 out.push(value.as_str());
1751 }
1752 walk(content, out);
1753 }
1754 Production::Repeat { content }
1755 | Production::Repeat1 { content }
1756 | Production::Optional { content }
1757 | Production::Field { content, .. }
1758 | Production::Token { content }
1759 | Production::ImmediateToken { content }
1760 | Production::Prec { content, .. }
1761 | Production::PrecLeft { content, .. }
1762 | Production::PrecRight { content, .. }
1763 | Production::PrecDynamic { content, .. }
1764 | Production::Reserved { content, .. } => walk(content, out),
1765 _ => {}
1766 }
1767 }
1768 walk(production, &mut out);
1769 out
1770}
1771
1772#[cfg(test)]
1773fn first_symbol(production: &Production) -> Option<&str> {
1774 match production {
1775 Production::Symbol { name } => Some(name),
1776 Production::Seq { members } => members.iter().find_map(first_symbol),
1777 Production::Choice { members } => members.iter().find_map(first_symbol),
1778 Production::Repeat { content }
1779 | Production::Repeat1 { content }
1780 | Production::Optional { content }
1781 | Production::Field { content, .. }
1782 | Production::Alias { content, .. }
1783 | Production::Token { content }
1784 | Production::ImmediateToken { content }
1785 | Production::Prec { content, .. }
1786 | Production::PrecLeft { content, .. }
1787 | Production::PrecRight { content, .. }
1788 | Production::PrecDynamic { content, .. }
1789 | Production::Reserved { content, .. } => first_symbol(content),
1790 _ => None,
1791 }
1792}
1793
1794fn has_field_in(production: &Production, edge_kinds: &[&str]) -> bool {
1795 match production {
1796 Production::Field { name, .. } => edge_kinds.contains(&name.as_str()),
1797 Production::Seq { members } | Production::Choice { members } => {
1798 members.iter().any(|m| has_field_in(m, edge_kinds))
1799 }
1800 Production::Repeat { content }
1801 | Production::Repeat1 { content }
1802 | Production::Optional { content }
1803 | Production::Alias { content, .. }
1804 | Production::Token { content }
1805 | Production::ImmediateToken { content }
1806 | Production::Prec { content, .. }
1807 | Production::PrecLeft { content, .. }
1808 | Production::PrecRight { content, .. }
1809 | Production::PrecDynamic { content, .. }
1810 | Production::Reserved { content, .. } => has_field_in(content, edge_kinds),
1811 _ => false,
1812 }
1813}
1814
1815fn has_relevant_constraint(
1816 production: &Production,
1817 schema: &Schema,
1818 vertex_id: &panproto_gat::Name,
1819) -> bool {
1820 let constraints = match schema.constraints.get(vertex_id) {
1821 Some(c) => c,
1822 None => return false,
1823 };
1824 fn walk(production: &Production, constraints: &[panproto_schema::Constraint]) -> bool {
1825 match production {
1826 Production::String { value } => constraints
1827 .iter()
1828 .any(|c| c.value == *value || c.sort.as_ref() == value),
1829 Production::Field { name, content } => {
1830 constraints.iter().any(|c| c.sort.as_ref() == name) || walk(content, constraints)
1831 }
1832 Production::Seq { members } | Production::Choice { members } => {
1833 members.iter().any(|m| walk(m, constraints))
1834 }
1835 Production::Repeat { content }
1836 | Production::Repeat1 { content }
1837 | Production::Optional { content }
1838 | Production::Alias { content, .. }
1839 | Production::Token { content }
1840 | Production::ImmediateToken { content }
1841 | Production::Prec { content, .. }
1842 | Production::PrecLeft { content, .. }
1843 | Production::PrecRight { content, .. }
1844 | Production::PrecDynamic { content, .. }
1845 | Production::Reserved { content, .. } => walk(content, constraints),
1846 _ => false,
1847 }
1848 }
1849 walk(production, constraints)
1850}
1851
1852fn children_for<'a>(schema: &'a Schema, vertex_id: &panproto_gat::Name) -> Vec<&'a Edge> {
1853 // Walk `outgoing` (insertion-ordered by SchemaBuilder via SmallVec
1854 // append) rather than the unordered `edges` HashMap so abstract
1855 // schemas under REPEAT(CHOICE(...)) preserve the order their edges
1856 // were inserted in. The previous implementation walked the HashMap
1857 // and sorted lexicographically by (kind, target id), which fused
1858 // interleaved children of the same kind into runs (e.g. a sequence
1859 // [symbol, punct, int, symbol, punct, int] became [symbol, symbol,
1860 // punct, punct, int, int] after the lex sort).
1861 let Some(edges) = schema.outgoing.get(vertex_id) else {
1862 return Vec::new();
1863 };
1864
1865 // Look up the canonical Edge reference (the key in `schema.edges`)
1866 // for each entry in `outgoing`. Falls back to the SmallVec entry if
1867 // the canonical key is missing, which would indicate index drift.
1868 let mut indexed: Vec<(usize, u32, &Edge)> = edges
1869 .iter()
1870 .enumerate()
1871 .map(|(i, e)| {
1872 let canonical = schema.edges.get_key_value(e).map_or(e, |(k, _)| k);
1873 let pos = schema.orderings.get(canonical).copied().unwrap_or(u32::MAX);
1874 (i, pos, canonical)
1875 })
1876 .collect();
1877
1878 // Stable sort by (explicit-ordering, insertion-index). Edges with
1879 // an explicit `orderings` entry come first in their declared order;
1880 // the remainder fall through in insertion order.
1881 indexed.sort_by_key(|(i, pos, _)| (*pos, *i));
1882 indexed.into_iter().map(|(_, _, e)| e).collect()
1883}
1884
1885fn vertex_id_kind<'a>(schema: &'a Schema, vertex_id: &panproto_gat::Name) -> Option<&'a str> {
1886 schema.vertices.get(vertex_id).map(|v| v.kind.as_ref())
1887}
1888
1889fn literal_value<'a>(schema: &'a Schema, vertex_id: &panproto_gat::Name) -> Option<&'a str> {
1890 schema
1891 .constraints
1892 .get(vertex_id)?
1893 .iter()
1894 .find(|c| c.sort.as_ref() == "literal-value")
1895 .map(|c| c.value.as_str())
1896}
1897
1898/// True iff `pattern` matches a (possibly optional / repeated) sequence
1899/// of carriage-return and newline characters only. Examples: `\r?\n`,
1900/// `\n`, `\r\n`, `\n+`, `\r?\n+`. Distinguishes structural newline
1901/// terminals from generic whitespace and from other patterns that
1902/// happen to contain a newline escape inside a larger class.
1903fn is_newline_like_pattern(pattern: &str) -> bool {
1904 if pattern.is_empty() {
1905 return false;
1906 }
1907 let mut chars = pattern.chars();
1908 let mut saw_newline_atom = false;
1909 while let Some(c) = chars.next() {
1910 match c {
1911 '\\' => match chars.next() {
1912 Some('n' | 'r') => saw_newline_atom = true,
1913 _ => return false,
1914 },
1915 '?' | '*' | '+' => {} // quantifiers on the previous atom
1916 _ => return false,
1917 }
1918 }
1919 saw_newline_atom
1920}
1921
1922/// True iff `pattern` matches a (possibly quantified) run of generic
1923/// whitespace characters: `\s+`, `[ \t]+`, ` +`, `\s*`. Such patterns
1924/// describe interstitial spacing rather than syntactic content, so the
1925/// pretty emitter can drop them and let the layout pass insert the
1926/// configured separator.
1927fn is_whitespace_only_pattern(pattern: &str) -> bool {
1928 if pattern.is_empty() {
1929 return false;
1930 }
1931 // Strip an outer quantifier suffix.
1932 let trimmed = pattern.trim_end_matches(['?', '*', '+']);
1933 if trimmed.is_empty() {
1934 return false;
1935 }
1936 // Bare `\s` / ` ` / `\t`.
1937 if matches!(trimmed, "\\s" | " " | "\\t") {
1938 return true;
1939 }
1940 // Character class containing only whitespace atoms.
1941 if let Some(inner) = trimmed.strip_prefix('[').and_then(|s| s.strip_suffix(']')) {
1942 let mut chars = inner.chars();
1943 let mut saw_atom = false;
1944 while let Some(c) = chars.next() {
1945 match c {
1946 '\\' => match chars.next() {
1947 Some('s' | 't' | 'r' | 'n') => saw_atom = true,
1948 _ => return false,
1949 },
1950 ' ' | '\t' => saw_atom = true,
1951 _ => return false,
1952 }
1953 }
1954 return saw_atom;
1955 }
1956 false
1957}
1958
1959fn placeholder_for_pattern(pattern: &str) -> String {
1960 // Heuristic placeholder for unconstrained PATTERN terminals.
1961 //
1962 // First handle the "the regex IS a literal escape" cases that
1963 // tree-sitter grammars use as separators (`\n`, `\r\n`, `;`,
1964 // etc.); emitting the matching character is always preferable
1965 // to a `_x` identifier-like placeholder when the surrounding
1966 // grammar expects a separator.
1967 let simple_lit = decode_simple_pattern_literal(pattern);
1968 if let Some(lit) = simple_lit {
1969 return lit;
1970 }
1971
1972 if pattern.contains("[0-9]") || pattern.contains("\\d") {
1973 "0".into()
1974 } else if pattern.contains("[a-zA-Z_]") || pattern.contains("\\w") {
1975 "_x".into()
1976 } else if pattern.contains('"') || pattern.contains('\'') {
1977 "\"\"".into()
1978 } else {
1979 "_".into()
1980 }
1981}
1982
1983/// Decode a tree-sitter PATTERN whose regex is a simple literal
1984/// (newline, semicolon, comma, etc.) to the byte sequence it matches.
1985/// Returns `None` for patterns with character classes, alternations,
1986/// or quantifiers; the caller falls back to the heuristic placeholder.
1987fn decode_simple_pattern_literal(pattern: &str) -> Option<String> {
1988 // Skip patterns containing regex metachars that would broaden the
1989 // match beyond a single literal byte sequence.
1990 if pattern
1991 .chars()
1992 .any(|c| matches!(c, '[' | ']' | '(' | ')' | '*' | '+' | '?' | '|' | '{' | '}'))
1993 {
1994 return None;
1995 }
1996 let mut out = String::new();
1997 let mut chars = pattern.chars();
1998 while let Some(c) = chars.next() {
1999 if c == '\\' {
2000 match chars.next() {
2001 Some('n') => out.push('\n'),
2002 Some('r') => out.push('\r'),
2003 Some('t') => out.push('\t'),
2004 Some('\\') => out.push('\\'),
2005 Some('/') => out.push('/'),
2006 Some(other) => out.push(other),
2007 None => return None,
2008 }
2009 } else {
2010 out.push(c);
2011 }
2012 }
2013 Some(out)
2014}
2015
2016// ═══════════════════════════════════════════════════════════════════
2017// Token list output with Spacing algebra
2018// ═══════════════════════════════════════════════════════════════════
2019//
2020// Emit produces a free monoid over `Token`. Layout (spaces, newlines,
2021// indentation) is a homomorphism `Vec<Token> -> Vec<u8>` parameterised
2022// by `FormatPolicy`. Separating the structural output from the layout
2023// decision means each phase has one job: emit walks the grammar and
2024// pushes tokens; layout is a single fold, locally driven by adjacent
2025// pairs and a depth counter. Snapshot/restore is just `tokens.len()`.
2026
2027#[derive(Clone)]
2028enum Token {
2029 /// A user-visible terminal contributed by the grammar.
2030 Lit(String),
2031 /// `indent_open` marker emitted when a `Lit` matched the policy's
2032 /// open list. Carried as a separate token so layout can decide to
2033 /// break + indent without re-scanning.
2034 IndentOpen,
2035 /// `indent_close` marker emitted before a closer-`Lit`.
2036 IndentClose,
2037 /// "Break a line here if not already at line start" — used after
2038 /// statements/declarations and after open braces.
2039 LineBreak,
2040 /// Suppress the next inter-Lit separator. Pushed by the REPEAT
2041 /// walker when an iteration's "separator slot" (a CHOICE-with-BLANK
2042 /// or OPTIONAL at SEQ position 0) emitted zero content tokens, so
2043 /// the categorical reading is "no source-level separator existed
2044 /// between these two sibling iterations of the body".
2045 NoSpace,
2046}
2047
2048struct Output<'a> {
2049 tokens: Vec<Token>,
2050 policy: &'a FormatPolicy,
2051}
2052
2053#[derive(Clone)]
2054struct OutputSnapshot {
2055 tokens_len: usize,
2056}
2057
2058impl<'a> Output<'a> {
2059 fn new(policy: &'a FormatPolicy) -> Self {
2060 Self {
2061 tokens: Vec::new(),
2062 policy,
2063 }
2064 }
2065
2066 fn token(&mut self, value: &str) {
2067 if value.is_empty() {
2068 return;
2069 }
2070
2071 // A grammar STRING whose value is a newline (e.g. abc's `_NL = "\n"`
2072 // or any rule that uses `"\n"` as a structural line terminator)
2073 // must route through the layout's `LineBreak` channel. Emitting it
2074 // as a `Lit` leaves the newline character in the byte stream but
2075 // also makes `needs_space_between` insert the configured separator
2076 // between the newline and the following token, producing leading
2077 // spaces on every line after the first.
2078 if value == "\n" || value == "\r\n" || value == "\r" {
2079 self.tokens.push(Token::LineBreak);
2080 return;
2081 }
2082
2083 if self.policy.indent_close.iter().any(|t| t == value) {
2084 self.tokens.push(Token::IndentClose);
2085 }
2086
2087 self.tokens.push(Token::Lit(value.to_owned()));
2088
2089 if self.policy.indent_open.iter().any(|t| t == value) {
2090 self.tokens.push(Token::IndentOpen);
2091 self.tokens.push(Token::LineBreak);
2092 } else if self.policy.line_break_after.iter().any(|t| t == value) {
2093 self.tokens.push(Token::LineBreak);
2094 }
2095 }
2096
2097 fn newline(&mut self) {
2098 self.tokens.push(Token::LineBreak);
2099 }
2100
2101 /// Open an indent scope: subsequent `LineBreak`s render at the
2102 /// new depth until a matching `indent_close` pops it. Used by the
2103 /// external-token fallback to render indent-based grammars'
2104 /// `_indent` scanner outputs.
2105 fn indent_open(&mut self) {
2106 self.tokens.push(Token::IndentOpen);
2107 self.tokens.push(Token::LineBreak);
2108 }
2109
2110 /// Close one indent scope opened by `indent_open`.
2111 fn indent_close(&mut self) {
2112 self.tokens.push(Token::IndentClose);
2113 }
2114
2115 fn snapshot(&self) -> OutputSnapshot {
2116 OutputSnapshot {
2117 tokens_len: self.tokens.len(),
2118 }
2119 }
2120
2121 fn restore(&mut self, snap: OutputSnapshot) {
2122 self.tokens.truncate(snap.tokens_len);
2123 }
2124
2125 /// True iff at least one `Token::Lit` was pushed since `snap`.
2126 /// Control-only emissions (`LineBreak`, `IndentOpen` / `IndentClose`,
2127 /// `NoSpace`) do not count as content. Used by the REPEAT walker
2128 /// to detect that a "separator slot" CHOICE picked its BLANK
2129 /// alternative, so the next iteration's content can be marked
2130 /// tight against the previous iteration's content.
2131 fn lit_emitted_since(&self, snap: OutputSnapshot) -> bool {
2132 self.tokens[snap.tokens_len..]
2133 .iter()
2134 .any(|t| matches!(t, Token::Lit(_)))
2135 }
2136
2137 /// Push a marker that suppresses the next inter-Lit separator the
2138 /// layout pass would otherwise insert. Used to encode "no source-
2139 /// level separator was emitted between these two Lits" without
2140 /// having to make per-grammar adjacency decisions in the layout.
2141 fn no_space(&mut self) {
2142 self.tokens.push(Token::NoSpace);
2143 }
2144
2145 fn finish(self) -> Vec<u8> {
2146 layout(&self.tokens, self.policy)
2147 }
2148}
2149
2150/// Fold a token list into bytes. The algebra:
2151/// * adjacent `Lit`s get a single space iff `needs_space_between(a, b)`,
2152/// * `IndentOpen` / `IndentClose` adjust a depth counter,
2153/// * `LineBreak` writes `\n` if not already at line start, then the
2154/// next `Lit` writes `indent * indent_width` spaces of indent.
2155fn layout(tokens: &[Token], policy: &FormatPolicy) -> Vec<u8> {
2156 let mut bytes = Vec::new();
2157 let mut indent: usize = 0;
2158 let mut at_line_start = true;
2159 let mut last_lit: Option<&str> = None;
2160 // True iff, at the moment `last_lit` was emitted, the cursor was at a
2161 // position where the grammar expects an operand: start of stream / line,
2162 // just after an open paren / bracket / brace, just after a separator like
2163 // `,` or `;`, or just after a binary / assignment operator. Used by
2164 // `needs_space_between` to recognise `last_lit` as a tight unary prefix
2165 // (`f(-1.0)`) rather than a spaced binary operator (`a - b`).
2166 let mut last_was_in_operand_position = true;
2167 let mut expecting_operand = true;
2168 // Set when a `Token::NoSpace` marker is seen; cleared when the next
2169 // Lit consumes it. While set, suppress the policy separator that
2170 // would otherwise be inserted before the next Lit.
2171 let mut suppress_next_separator = false;
2172 let newline = policy.newline.as_bytes();
2173 let separator = policy.separator.as_bytes();
2174
2175 for tok in tokens {
2176 match tok {
2177 Token::IndentOpen => indent += 1,
2178 Token::IndentClose => {
2179 indent = indent.saturating_sub(1);
2180 if !at_line_start {
2181 bytes.extend_from_slice(newline);
2182 at_line_start = true;
2183 expecting_operand = true;
2184 }
2185 }
2186 Token::LineBreak => {
2187 if !at_line_start {
2188 bytes.extend_from_slice(newline);
2189 at_line_start = true;
2190 expecting_operand = true;
2191 }
2192 }
2193 Token::NoSpace => {
2194 suppress_next_separator = true;
2195 }
2196 Token::Lit(value) => {
2197 if at_line_start {
2198 bytes.extend(std::iter::repeat_n(b' ', indent * policy.indent_width));
2199 } else if let Some(prev) = last_lit {
2200 if !suppress_next_separator
2201 && needs_space_between(prev, value, last_was_in_operand_position)
2202 {
2203 bytes.extend_from_slice(separator);
2204 }
2205 }
2206 suppress_next_separator = false;
2207 bytes.extend_from_slice(value.as_bytes());
2208 at_line_start = false;
2209 last_was_in_operand_position = expecting_operand;
2210 expecting_operand = leaves_operand_position(value);
2211 last_lit = Some(value.as_str());
2212 }
2213 }
2214 }
2215
2216 if !at_line_start {
2217 bytes.extend_from_slice(newline);
2218 }
2219 bytes
2220}
2221
2222/// True iff emitting `tok` leaves the cursor in a position where the
2223/// grammar expects an operand next. Operand-introducing tokens are open
2224/// punctuation, separators, and operator-like strings; operand-terminating
2225/// tokens are identifiers, literals, and closing punctuation.
2226fn leaves_operand_position(tok: &str) -> bool {
2227 if tok.is_empty() {
2228 return true;
2229 }
2230 if is_punct_open(tok) {
2231 return true;
2232 }
2233 if matches!(tok, "," | ";") {
2234 return true;
2235 }
2236 if is_punct_close(tok) {
2237 return false;
2238 }
2239 if first_is_alnum_or_underscore(tok) || last_ends_with_alnum(tok) {
2240 return false;
2241 }
2242 // Pure punctuation/operator runs (`=`, `+`, `-`, `<=`, `>>`, …) leave
2243 // the cursor expecting another operand.
2244 true
2245}
2246
2247fn needs_space_between(last: &str, next: &str, expecting_operand: bool) -> bool {
2248 if last.is_empty() || next.is_empty() {
2249 return false;
2250 }
2251 if is_punct_open(last) || is_punct_open(next) {
2252 return false;
2253 }
2254 if is_punct_close(next) {
2255 return false;
2256 }
2257 if is_punct_close(last) && is_punct_punctuation(next) {
2258 return false;
2259 }
2260 if last == "." || next == "." {
2261 return false;
2262 }
2263 // Tight unary prefix: `last` is a sign/logical-not operator emitted
2264 // where the grammar expected an operand, so it glues to `next`.
2265 // `expecting_operand` here means: just before `last` was emitted,
2266 // the cursor expected an operand, which makes `last` a unary prefix.
2267 // Examples: `f(-1.0)`, `[ -2, 3 ]`, `return -x`, `a = !flag`.
2268 if expecting_operand && is_unary_prefix_operator(last) && first_is_operand_start(next) {
2269 return false;
2270 }
2271 if last_is_word_like(last) && first_is_word_like(next) {
2272 return true;
2273 }
2274 if last_ends_with_alnum(last) && first_is_alnum_or_underscore(next) {
2275 return true;
2276 }
2277 // Adjacent operator runs: keep them apart so the lexer doesn't glue
2278 // `>` and `=` into `>=` unintentionally.
2279 true
2280}
2281
2282fn is_unary_prefix_operator(s: &str) -> bool {
2283 matches!(s, "-" | "+" | "!" | "~")
2284}
2285
2286fn first_is_operand_start(s: &str) -> bool {
2287 s.chars()
2288 .next()
2289 .map(|c| c.is_alphanumeric() || c == '_' || c == '.' || c == '(')
2290 .unwrap_or(false)
2291}
2292
2293fn is_punct_open(s: &str) -> bool {
2294 matches!(s, "(" | "[" | "{" | "\"" | "'" | "`")
2295}
2296
2297fn is_punct_close(s: &str) -> bool {
2298 matches!(s, ")" | "]" | "}" | "," | ";" | ":" | "\"" | "'" | "`")
2299}
2300
2301fn is_punct_punctuation(s: &str) -> bool {
2302 matches!(s, "," | ";" | ":" | "." | ")" | "]" | "}")
2303}
2304
2305fn last_is_word_like(s: &str) -> bool {
2306 s.chars()
2307 .next_back()
2308 .map(|c| c.is_alphanumeric() || c == '_')
2309 .unwrap_or(false)
2310}
2311
2312fn first_is_word_like(s: &str) -> bool {
2313 s.chars()
2314 .next()
2315 .map(|c| c.is_alphanumeric() || c == '_')
2316 .unwrap_or(false)
2317}
2318
2319fn last_ends_with_alnum(s: &str) -> bool {
2320 s.chars()
2321 .next_back()
2322 .map(char::is_alphanumeric)
2323 .unwrap_or(false)
2324}
2325
2326fn first_is_alnum_or_underscore(s: &str) -> bool {
2327 s.chars()
2328 .next()
2329 .map(|c| c.is_alphanumeric() || c == '_')
2330 .unwrap_or(false)
2331}
2332
2333#[cfg(test)]
2334mod tests {
2335 use super::*;
2336
2337 #[test]
2338 fn parses_simple_grammar_json() {
2339 let bytes = br#"{
2340 "name": "tiny",
2341 "rules": {
2342 "program": {
2343 "type": "SEQ",
2344 "members": [
2345 {"type": "STRING", "value": "hello"},
2346 {"type": "STRING", "value": ";"}
2347 ]
2348 }
2349 }
2350 }"#;
2351 let g = Grammar::from_bytes("tiny", bytes).expect("valid tiny grammar");
2352 assert!(g.rules.contains_key("program"));
2353 }
2354
2355 #[test]
2356 fn output_emits_punctuation_without_leading_space() {
2357 let policy = FormatPolicy::default();
2358 let mut out = Output::new(&policy);
2359 out.token("foo");
2360 out.token("(");
2361 out.token(")");
2362 out.token(";");
2363 let bytes = out.finish();
2364 let s = std::str::from_utf8(&bytes).expect("ascii output");
2365 assert!(s.starts_with("foo();"), "got {s:?}");
2366 }
2367
2368 #[test]
2369 fn grammar_from_bytes_rejects_malformed_input() {
2370 let result = Grammar::from_bytes("malformed", b"not json");
2371 let err = result.expect_err("malformed bytes must yield Err");
2372 let msg = err.to_string();
2373 assert!(
2374 msg.contains("malformed"),
2375 "error message should name the protocol: {msg:?}"
2376 );
2377 }
2378
2379 #[test]
2380 fn output_indents_after_open_brace() {
2381 let policy = FormatPolicy::default();
2382 let mut out = Output::new(&policy);
2383 out.token("fn");
2384 out.token("foo");
2385 out.token("(");
2386 out.token(")");
2387 out.token("{");
2388 out.token("body");
2389 out.token("}");
2390 let bytes = out.finish();
2391 let s = std::str::from_utf8(&bytes).expect("ascii output");
2392 assert!(s.contains("{\n"), "newline after opening brace: {s:?}");
2393 assert!(s.contains("body"), "body inside block: {s:?}");
2394 assert!(s.ends_with("}\n"), "newline after closing brace: {s:?}");
2395 }
2396
2397 #[test]
2398 fn output_no_space_between_word_and_dot() {
2399 let policy = FormatPolicy::default();
2400 let mut out = Output::new(&policy);
2401 out.token("foo");
2402 out.token(".");
2403 out.token("bar");
2404 let bytes = out.finish();
2405 let s = std::str::from_utf8(&bytes).expect("ascii output");
2406 assert!(s.starts_with("foo.bar"), "no space around dot: {s:?}");
2407 }
2408
2409 #[test]
2410 fn output_snapshot_restore_truncates_bytes() {
2411 let policy = FormatPolicy::default();
2412 let mut out = Output::new(&policy);
2413 out.token("keep");
2414 let snap = out.snapshot();
2415 out.token("drop");
2416 out.token("more");
2417 out.restore(snap);
2418 out.token("after");
2419 let bytes = out.finish();
2420 let s = std::str::from_utf8(&bytes).expect("ascii output");
2421 assert!(s.contains("keep"), "kept token survives: {s:?}");
2422 assert!(s.contains("after"), "post-restore token visible: {s:?}");
2423 assert!(!s.contains("drop"), "rolled-back token removed: {s:?}");
2424 assert!(!s.contains("more"), "rolled-back token removed: {s:?}");
2425 }
2426
2427 #[test]
2428 fn child_cursor_take_field_consumes_once() {
2429 let edges_owned: Vec<Edge> = vec![Edge {
2430 src: panproto_gat::Name::from("p"),
2431 tgt: panproto_gat::Name::from("c"),
2432 kind: panproto_gat::Name::from("name"),
2433 name: None,
2434 }];
2435 let edges: Vec<&Edge> = edges_owned.iter().collect();
2436 let mut cursor = ChildCursor::new(&edges);
2437 let first = cursor.take_field("name");
2438 let second = cursor.take_field("name");
2439 assert!(first.is_some(), "first take returns the edge");
2440 assert!(
2441 second.is_none(),
2442 "second take returns None (already consumed)"
2443 );
2444 }
2445
2446 #[test]
2447 fn child_cursor_take_matching_predicate() {
2448 let edges_owned: Vec<Edge> = vec![
2449 Edge {
2450 src: "p".into(),
2451 tgt: "c1".into(),
2452 kind: "child_of".into(),
2453 name: None,
2454 },
2455 Edge {
2456 src: "p".into(),
2457 tgt: "c2".into(),
2458 kind: "key".into(),
2459 name: None,
2460 },
2461 ];
2462 let edges: Vec<&Edge> = edges_owned.iter().collect();
2463 let mut cursor = ChildCursor::new(&edges);
2464 assert!(cursor.has_matching(|e| e.kind.as_ref() == "key"));
2465 let taken = cursor.take_matching(|e| e.kind.as_ref() == "key");
2466 assert!(taken.is_some());
2467 assert!(
2468 !cursor.has_matching(|e| e.kind.as_ref() == "key"),
2469 "consumed edge no longer matches"
2470 );
2471 assert!(
2472 cursor.has_matching(|e| e.kind.as_ref() == "child_of"),
2473 "the other edge is still available"
2474 );
2475 }
2476
2477 #[test]
2478 fn kind_satisfies_symbol_direct_match() {
2479 let bytes = br#"{
2480 "name": "tiny",
2481 "rules": {
2482 "x": {"type": "STRING", "value": "x"}
2483 }
2484 }"#;
2485 let g = Grammar::from_bytes("tiny", bytes).expect("valid grammar");
2486 assert!(kind_satisfies_symbol(&g, Some("x"), "x"));
2487 assert!(!kind_satisfies_symbol(&g, Some("y"), "x"));
2488 assert!(!kind_satisfies_symbol(&g, None, "x"));
2489 }
2490
2491 #[test]
2492 fn kind_satisfies_symbol_through_hidden_rule() {
2493 let bytes = br#"{
2494 "name": "tiny",
2495 "rules": {
2496 "_value": {
2497 "type": "CHOICE",
2498 "members": [
2499 {"type": "SYMBOL", "name": "object"},
2500 {"type": "SYMBOL", "name": "number"}
2501 ]
2502 },
2503 "object": {"type": "STRING", "value": "{}"},
2504 "number": {"type": "PATTERN", "value": "[0-9]+"}
2505 }
2506 }"#;
2507 let g = Grammar::from_bytes("tiny", bytes).expect("valid grammar");
2508 assert!(
2509 kind_satisfies_symbol(&g, Some("number"), "_value"),
2510 "number is reachable from _value via CHOICE"
2511 );
2512 assert!(
2513 kind_satisfies_symbol(&g, Some("object"), "_value"),
2514 "object is reachable from _value via CHOICE"
2515 );
2516 assert!(
2517 !kind_satisfies_symbol(&g, Some("string"), "_value"),
2518 "string is NOT among the alternatives"
2519 );
2520 }
2521
2522 #[test]
2523 fn first_symbol_skips_string_terminals() {
2524 let prod: Production = serde_json::from_str(
2525 r#"{
2526 "type": "SEQ",
2527 "members": [
2528 {"type": "STRING", "value": "{"},
2529 {"type": "SYMBOL", "name": "body"},
2530 {"type": "STRING", "value": "}"}
2531 ]
2532 }"#,
2533 )
2534 .expect("valid SEQ");
2535 assert_eq!(first_symbol(&prod), Some("body"));
2536 }
2537
2538 #[test]
2539 fn placeholder_for_pattern_routes_by_regex_class() {
2540 assert_eq!(placeholder_for_pattern("[0-9]+"), "0");
2541 assert_eq!(placeholder_for_pattern("[a-zA-Z_]\\w*"), "_x");
2542 assert_eq!(placeholder_for_pattern("\"[^\"]*\""), "\"\"");
2543 assert_eq!(placeholder_for_pattern("\\d+\\.\\d+"), "0");
2544 }
2545
2546 #[test]
2547 fn format_policy_default_breaks_after_semicolon() {
2548 let policy = FormatPolicy::default();
2549 assert!(policy.line_break_after.iter().any(|t| t == ";"));
2550 assert!(policy.indent_open.iter().any(|t| t == "{"));
2551 assert!(policy.indent_close.iter().any(|t| t == "}"));
2552 assert_eq!(policy.indent_width, 2);
2553 }
2554
2555 #[test]
2556 fn placeholder_decodes_literal_pattern_separators() {
2557 // PATTERN regexes that match a single literal byte sequence
2558 // (newline, semicolon, comma) emit the bytes verbatim instead
2559 // of falling through to the `_` catch-all.
2560 assert_eq!(placeholder_for_pattern("\\n"), "\n");
2561 assert_eq!(placeholder_for_pattern("\\r\\n"), "\r\n");
2562 assert_eq!(placeholder_for_pattern(";"), ";");
2563 // Patterns with character classes / alternation still route
2564 // through the heuristic.
2565 assert_eq!(placeholder_for_pattern("[0-9]+"), "0");
2566 assert_eq!(placeholder_for_pattern("a|b"), "_");
2567 }
2568
2569 #[test]
2570 fn supertypes_decode_from_grammar_json_strings() {
2571 // Tree-sitter older grammars list supertypes as bare strings.
2572 let bytes = br#"{
2573 "name": "tiny",
2574 "supertypes": ["expression"],
2575 "rules": {
2576 "expression": {
2577 "type": "CHOICE",
2578 "members": [
2579 {"type": "SYMBOL", "name": "binary_expression"},
2580 {"type": "SYMBOL", "name": "identifier"}
2581 ]
2582 },
2583 "binary_expression": {"type": "STRING", "value": "x"},
2584 "identifier": {"type": "PATTERN", "value": "[a-z]+"}
2585 }
2586 }"#;
2587 let g = Grammar::from_bytes("tiny", bytes).expect("parse");
2588 assert!(g.supertypes.contains("expression"));
2589 // identifier matches the supertype `expression`.
2590 assert!(kind_satisfies_symbol(&g, Some("identifier"), "expression"));
2591 // unrelated kinds do not.
2592 assert!(!kind_satisfies_symbol(&g, Some("string"), "expression"));
2593 }
2594
2595 #[test]
2596 fn supertypes_decode_from_grammar_json_objects() {
2597 // Recent grammars list supertypes as `{type: SYMBOL, name: ...}`
2598 // entries instead of bare strings.
2599 let bytes = br#"{
2600 "name": "tiny",
2601 "supertypes": [{"type": "SYMBOL", "name": "stmt"}],
2602 "rules": {
2603 "stmt": {
2604 "type": "CHOICE",
2605 "members": [
2606 {"type": "SYMBOL", "name": "while_stmt"},
2607 {"type": "SYMBOL", "name": "if_stmt"}
2608 ]
2609 },
2610 "while_stmt": {"type": "STRING", "value": "while"},
2611 "if_stmt": {"type": "STRING", "value": "if"}
2612 }
2613 }"#;
2614 let g = Grammar::from_bytes("tiny", bytes).expect("parse");
2615 assert!(g.supertypes.contains("stmt"));
2616 assert!(kind_satisfies_symbol(&g, Some("while_stmt"), "stmt"));
2617 }
2618
2619 #[test]
2620 fn alias_value_matches_kind() {
2621 // A named ALIAS rewrites the parser-visible kind to `value`;
2622 // `kind_satisfies_symbol` should accept that rewritten kind
2623 // when looking up the original SYMBOL.
2624 let bytes = br#"{
2625 "name": "tiny",
2626 "rules": {
2627 "_package_identifier": {
2628 "type": "ALIAS",
2629 "named": true,
2630 "value": "package_identifier",
2631 "content": {"type": "SYMBOL", "name": "identifier"}
2632 },
2633 "identifier": {"type": "PATTERN", "value": "[a-z]+"}
2634 }
2635 }"#;
2636 let g = Grammar::from_bytes("tiny", bytes).expect("parse");
2637 assert!(kind_satisfies_symbol(
2638 &g,
2639 Some("package_identifier"),
2640 "_package_identifier"
2641 ));
2642 }
2643
2644 #[test]
2645 fn referenced_symbols_walks_nested_seq() {
2646 let prod: Production = serde_json::from_str(
2647 r#"{
2648 "type": "SEQ",
2649 "members": [
2650 {"type": "CHOICE", "members": [
2651 {"type": "SYMBOL", "name": "attribute_item"},
2652 {"type": "BLANK"}
2653 ]},
2654 {"type": "SYMBOL", "name": "parameter"},
2655 {"type": "REPEAT", "content": {
2656 "type": "SEQ",
2657 "members": [
2658 {"type": "STRING", "value": ","},
2659 {"type": "SYMBOL", "name": "parameter"}
2660 ]
2661 }}
2662 ]
2663 }"#,
2664 )
2665 .expect("seq");
2666 let symbols = referenced_symbols(&prod);
2667 assert!(symbols.contains(&"attribute_item"));
2668 assert!(symbols.contains(&"parameter"));
2669 }
2670
2671 #[test]
2672 fn literal_strings_collects_choice_members() {
2673 let prod: Production = serde_json::from_str(
2674 r#"{
2675 "type": "CHOICE",
2676 "members": [
2677 {"type": "STRING", "value": "+"},
2678 {"type": "STRING", "value": "-"},
2679 {"type": "STRING", "value": "*"}
2680 ]
2681 }"#,
2682 )
2683 .expect("choice");
2684 let strings = literal_strings(&prod);
2685 assert_eq!(strings, vec!["+", "-", "*"]);
2686 }
2687
2688 /// The ocaml and javascript grammars (tree-sitter ≥ 0.25) emit a
2689 /// `RESERVED` rule kind that an earlier deserialiser rejected
2690 /// with `unknown variant "RESERVED"`. Verify both that the bare
2691 /// variant deserialises and that a `RESERVED`-wrapped grammar is
2692 /// loadable end-to-end via [`Grammar::from_bytes`].
2693 #[test]
2694 fn reserved_variant_deserialises() {
2695 let prod: Production = serde_json::from_str(
2696 r#"{
2697 "type": "RESERVED",
2698 "content": {"type": "SYMBOL", "name": "_lowercase_identifier"},
2699 "context_name": "attribute_id"
2700 }"#,
2701 )
2702 .expect("RESERVED parses");
2703 match prod {
2704 Production::Reserved { content, .. } => match *content {
2705 Production::Symbol { name } => assert_eq!(name, "_lowercase_identifier"),
2706 other => panic!("expected inner SYMBOL, got {other:?}"),
2707 },
2708 other => panic!("expected RESERVED, got {other:?}"),
2709 }
2710 }
2711
2712 #[test]
2713 fn reserved_grammar_loads_end_to_end() {
2714 let bytes = br#"{
2715 "name": "tiny_reserved",
2716 "rules": {
2717 "program": {
2718 "type": "RESERVED",
2719 "content": {"type": "SYMBOL", "name": "ident"},
2720 "context_name": "keywords"
2721 },
2722 "ident": {"type": "PATTERN", "value": "[a-z]+"}
2723 }
2724 }"#;
2725 let g = Grammar::from_bytes("tiny_reserved", bytes).expect("RESERVED-using grammar loads");
2726 assert!(g.rules.contains_key("program"));
2727 }
2728
2729 #[test]
2730 fn reserved_walker_helpers_recurse_into_content() {
2731 // The walker's helpers (first_symbol, has_field_in,
2732 // referenced_symbols, ...) all need to descend through
2733 // RESERVED into its content. If they bail at RESERVED, the
2734 // `pick_choice_with_cursor` heuristic ranks the alt below
2735 // alts that DO recurse, which produces wrong emit output
2736 // even when the deserialiser doesn't crash.
2737 let prod: Production = serde_json::from_str(
2738 r#"{
2739 "type": "RESERVED",
2740 "content": {
2741 "type": "FIELD",
2742 "name": "lhs",
2743 "content": {"type": "SYMBOL", "name": "expr"}
2744 },
2745 "context_name": "ctx"
2746 }"#,
2747 )
2748 .expect("nested RESERVED parses");
2749 assert_eq!(first_symbol(&prod), Some("expr"));
2750 assert!(has_field_in(&prod, &["lhs"]));
2751 let symbols = referenced_symbols(&prod);
2752 assert!(symbols.contains(&"expr"));
2753 }
2754}