Skip to main content

meta_language/grammar/feature_runtime/
tree.rs

1//! The public concrete syntax tree of the native grammar executor and its
2//! compact, stable text rendering (docs/grammar/feature-union.md#syntax-tree),
3//! as `js/src/grammar-runtime/syntax-tree.js`. Every node keeps its byte span,
4//! every token its exact text, and trivia, ERROR, MISSING and
5//! embedded-language nodes stay in the tree, so the tree reproduces the input
6//! byte for byte.
7
8use std::fmt::Write as _;
9
10use indexmap::IndexMap;
11
12use super::operations::OperationValue;
13use super::program::Compiled;
14use super::results::{Tree, TreeType};
15use super::text::{hex_of, quote_text, text_of};
16
17/// The attributes semantic actions set on a node or token, by name.
18pub type SyntaxAttributes = IndexMap<String, OperationValue>;
19
20/// The text of a leaf: the exact UTF-8 text, or the hexadecimal spelling of
21/// bytes that are not well-formed UTF-8.
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub enum LeafText {
24    /// Well-formed UTF-8 text.
25    Text(String),
26    /// The lower-case hexadecimal spelling of the bytes.
27    Hex(String),
28}
29
30impl LeafText {
31    fn of(bytes: &[u8], start: usize, end: usize) -> Self {
32        text_of(bytes, start, end).map_or_else(|| Self::Hex(hex_of(bytes, start, end)), Self::Text)
33    }
34
35    fn render(&self) -> String {
36        match self {
37            Self::Text(text) => quote_text(text),
38            Self::Hex(hex) => format!("<{hex}>"),
39        }
40    }
41}
42
43/// One node of a concrete syntax tree; offsets are byte offsets into the input.
44#[derive(Clone, Debug, PartialEq, Eq)]
45pub enum SyntaxTree {
46    /// A node a rule (or an alias) built.
47    Node {
48        /// The node kind.
49        kind: String,
50        /// The field the node is captured under.
51        field: Option<String>,
52        /// Whether the node is trivia (an extra of a rule that builds a node).
53        trivia: bool,
54        /// The first byte.
55        start: usize,
56        /// The byte after the last.
57        end: usize,
58        /// The children, trivia included.
59        children: Vec<Self>,
60        /// The attributes semantic actions set.
61        attributes: Option<SyntaxAttributes>,
62    },
63    /// A leaf: a literal, a token rule, an external token or trivia.
64    Token {
65        /// The token kind; `None` for an anonymous literal.
66        kind: Option<String>,
67        /// The field the token is captured under.
68        field: Option<String>,
69        /// Whether the token is trivia (an extra or a channel token).
70        trivia: bool,
71        /// The first byte.
72        start: usize,
73        /// The byte after the last.
74        end: usize,
75        /// The attributes semantic actions set.
76        attributes: Option<SyntaxAttributes>,
77        /// The token text.
78        text: LeafText,
79        /// Lossless source-local lexer metadata; absent on ordinary tokens.
80        lexical: Option<serde_json::Value>,
81    },
82    /// Input error recovery skipped, or the whole input of a refused parse.
83    Error {
84        /// The first byte.
85        start: usize,
86        /// The byte after the last.
87        end: usize,
88        /// The skipped text.
89        text: LeafText,
90        /// Why the input is an error node, when it is not skipped input.
91        reason: Option<String>,
92    },
93    /// A zero-width node error recovery inserted for an absent item.
94    Missing {
95        /// The missing rule kind or literal.
96        kind: Option<String>,
97        /// The offset.
98        start: usize,
99        /// The offset again: missing nodes are empty.
100        end: usize,
101        /// Whether `kind` is a literal.
102        literal: bool,
103    },
104    /// A region another language parsed.
105    Embed {
106        /// The embedded language.
107        language: String,
108        /// The first byte.
109        start: usize,
110        /// The byte after the last.
111        end: usize,
112        /// The tree of the embedded language.
113        root: Box<Self>,
114        /// Optional inspectable selection policy, origin metadata and witnesses.
115        selection: Option<Box<super::grammar_selection::GrammarSelection>>,
116        /// Full original host CST children for an explicitly mapped source.
117        source_children: Option<Vec<Self>>,
118    },
119}
120
121impl SyntaxTree {
122    /// The first byte of the node.
123    #[must_use]
124    pub const fn start(&self) -> usize {
125        match self {
126            Self::Node { start, .. }
127            | Self::Token { start, .. }
128            | Self::Error { start, .. }
129            | Self::Missing { start, .. }
130            | Self::Embed { start, .. } => *start,
131        }
132    }
133
134    /// The byte after the last byte of the node.
135    #[must_use]
136    pub const fn end(&self) -> usize {
137        match self {
138            Self::Node { end, .. }
139            | Self::Token { end, .. }
140            | Self::Error { end, .. }
141            | Self::Missing { end, .. }
142            | Self::Embed { end, .. } => *end,
143        }
144    }
145
146    /// The first ERROR or MISSING node, in preorder.
147    #[must_use]
148    pub fn first_recovery(&self) -> Option<&Self> {
149        match self {
150            Self::Error { .. } | Self::Missing { .. } => Some(self),
151            Self::Node { children, .. } => children.iter().find_map(Self::first_recovery),
152            Self::Embed {
153                root,
154                source_children,
155                ..
156            } => source_children
157                .as_ref()
158                .and_then(|children| children.iter().find_map(Self::first_recovery))
159                .or_else(|| root.first_recovery()),
160            Self::Token { .. } => None,
161        }
162    }
163
164    pub(super) fn recovery_diagnostic(
165        &self,
166    ) -> Result<Option<serde_json::Value>, super::GrammarRuntimeError> {
167        use serde_json::json;
168        let data = match self {
169            Self::Error {
170                start,
171                end,
172                text,
173                reason,
174            } => {
175                let mut value = json!({"type":"error","start":start,"end":end});
176                match text {
177                    LeafText::Text(text) => value["text"] = json!(text),
178                    LeafText::Hex(hex) => {
179                        value["text"] = serde_json::Value::Null;
180                        value["hex"] = json!(hex);
181                    }
182                }
183                if let Some(reason) = reason {
184                    value["reason"] = json!(reason);
185                }
186                return Ok(Some(value));
187            }
188            Self::Missing {
189                start,
190                end,
191                kind,
192                literal,
193            } => {
194                let mut value = json!({"type":"missing","kind":kind,"start":start,"end":end});
195                if *literal {
196                    value["literal"] = json!(true);
197                }
198                return Ok(Some(value));
199            }
200            Self::Node { children, .. } => {
201                for child in children {
202                    if let Some(recovery) = child.recovery_diagnostic()? {
203                        return Ok(Some(recovery));
204                    }
205                }
206                return Ok(None);
207            }
208            Self::Token { .. } => return Ok(None),
209            Self::Embed {
210                root,
211                source_children,
212                selection,
213                ..
214            } => {
215                if let Some(children) = source_children {
216                    for child in children {
217                        if let Some(recovery) = child.recovery_diagnostic()? {
218                            return Ok(Some(recovery));
219                        }
220                    }
221                }
222                let Some(recovery) = root.recovery_diagnostic()? else {
223                    return Ok(None);
224                };
225                if source_children.is_none() {
226                    return Ok(Some(recovery));
227                }
228                let mapping = selection
229                    .as_ref()
230                    .and_then(|selection| selection.source_mapping.as_ref())
231                    .ok_or_else(|| super::GrammarRuntimeError {
232                        reason: "selection",
233                        message: "a mapped grammar has no source correspondence".to_owned(),
234                    })?;
235                (recovery, mapping)
236            }
237        };
238        let (mut recovery, mapping) = data;
239        let start = recovery["start"]
240            .as_u64()
241            .and_then(|value| usize::try_from(value).ok());
242        let end = recovery["end"]
243            .as_u64()
244            .and_then(|value| usize::try_from(value).ok());
245        let cover = start
246            .zip(end)
247            .and_then(|(start, end)| {
248                super::selection_source_mapping::mapped_cover(mapping, start, end)
249            })
250            .ok_or_else(|| super::GrammarRuntimeError {
251                reason: "selection",
252                message: "a grammar mapping has no source cover for this decoded range".to_owned(),
253            })?;
254        if recovery.get("source").is_none() {
255            recovery["source"] = mapping["output"].clone();
256        }
257        if recovery.get("sourceStart").is_none() {
258            recovery["sourceStart"] = recovery["start"].clone();
259        }
260        if recovery.get("sourceEnd").is_none() {
261            recovery["sourceEnd"] = recovery["end"].clone();
262        }
263        let mut route = recovery["sourceRoute"]
264            .as_array()
265            .cloned()
266            .unwrap_or_default();
267        route.push(json!({"output":mapping["output"],"outputStart":start,"outputEnd":end,
268            "input":mapping["input"],"inputStart":cover[1],"inputEnd":cover[2],"displayAnchor":cover[0]}));
269        recovery["start"] = json!(cover[1]);
270        recovery["end"] = json!(cover[2]);
271        recovery["sourceRoute"] = json!(route);
272        recovery["offsetSemantics"] = json!("covering-source-spelling");
273        Ok(Some(recovery))
274    }
275
276    /// The compact text rendering: `(kind {attributes} child ...)` for a
277    /// node, `field:` before a captured child, the quoted text of an
278    /// anonymous token, `(kind "text")` for a named one, `~` before trivia,
279    /// and `(ERROR@S..E "text")`, `(MISSING@P kind)` and
280    /// `(EMBED language@S..E root)`.
281    #[must_use]
282    pub fn render(&self) -> String {
283        let mut rendered = String::new();
284        self.render_into(&mut rendered);
285        rendered
286    }
287
288    fn render_into(&self, out: &mut String) {
289        match self {
290            Self::Node {
291                kind,
292                field,
293                trivia,
294                children,
295                attributes,
296                ..
297            } => {
298                render_field(field.as_deref(), out);
299                if *trivia {
300                    out.push('~');
301                }
302                out.push('(');
303                out.push_str(&render_name(kind));
304                if let Some(attributes) = attributes {
305                    out.push(' ');
306                    render_attributes(attributes, out);
307                }
308                for child in children {
309                    out.push(' ');
310                    child.render_into(out);
311                }
312                out.push(')');
313            }
314            Self::Token {
315                kind,
316                field,
317                trivia,
318                attributes,
319                text,
320                ..
321            } => {
322                render_field(field.as_deref(), out);
323                if *trivia {
324                    out.push('~');
325                }
326                if kind.is_none() && attributes.is_none() {
327                    out.push_str(&text.render());
328                    return;
329                }
330                out.push('(');
331                out.push_str(&kind.as_deref().map_or_else(|| "_".to_owned(), render_name));
332                if let Some(attributes) = attributes {
333                    out.push(' ');
334                    render_attributes(attributes, out);
335                }
336                out.push(' ');
337                out.push_str(&text.render());
338                out.push(')');
339            }
340            Self::Error {
341                start, end, text, ..
342            } => {
343                let _ = write!(out, "(ERROR@{start}..{end} {})", text.render());
344            }
345            Self::Missing {
346                kind,
347                start,
348                literal,
349                ..
350            } => match kind {
351                None => {
352                    let _ = write!(out, "(MISSING@{start})");
353                }
354                Some(kind) => {
355                    let name = if *literal {
356                        quote_text(kind)
357                    } else {
358                        render_name(kind)
359                    };
360                    let _ = write!(out, "(MISSING@{start} {name})");
361                }
362            },
363            Self::Embed {
364                language,
365                start,
366                end,
367                root,
368                selection,
369                source_children,
370            } => {
371                let _ = write!(out, "(EMBED {}@{start}..{end} ", render_name(language));
372                if let Some(children) = source_children {
373                    out.push_str("(SOURCE ");
374                    for (index, child) in children.iter().enumerate() {
375                        if index > 0 {
376                            out.push(' ');
377                        }
378                        child.render_into(out);
379                    }
380                    let output = selection
381                        .as_ref()
382                        .and_then(|selection| selection.source_mapping.as_ref())
383                        .and_then(|mapping| mapping["output"].as_u64());
384                    if let Some(output) = output {
385                        let _ = write!(out, ") (DECODED {output} ");
386                        root.render_into(out);
387                        out.push(')');
388                    } else {
389                        out.push_str(") (INVALID-SOURCE-MAPPING)");
390                    }
391                } else {
392                    root.render_into(out);
393                }
394                out.push(')');
395            }
396        }
397    }
398}
399
400fn render_field(field: Option<&str>, out: &mut String) {
401    if let Some(field) = field {
402        out.push_str(&render_name(field));
403        out.push(':');
404    }
405}
406
407fn render_name(name: &str) -> String {
408    let mut chars = name.chars();
409    let plain = chars
410        .next()
411        .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
412        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
413    if plain {
414        name.to_owned()
415    } else {
416        quote_text(name)
417    }
418}
419
420fn render_attributes(attributes: &SyntaxAttributes, out: &mut String) {
421    out.push('{');
422    let mut entries: Vec<_> = attributes.iter().collect();
423    entries.sort_by(|(left, _), (right, _)| left.encode_utf16().cmp(right.encode_utf16()));
424    for (index, (name, value)) in entries.into_iter().enumerate() {
425        if index > 0 {
426            out.push(',');
427        }
428        out.push_str(&render_name(name));
429        out.push('=');
430        match value {
431            OperationValue::Text(text) => out.push_str(&quote_text(text)),
432            OperationValue::Integer(integer) => {
433                let _ = write!(out, "{integer}");
434            }
435        }
436    }
437    out.push('}');
438}
439
440/// Copies an executor tree into the public shape.
441pub(super) fn public_tree(node: &Tree, bytes: &[u8]) -> SyntaxTree {
442    let name = |value: &Option<super::program::Name>| value.as_deref().map(str::to_owned);
443    match node.ty {
444        TreeType::Node => SyntaxTree::Node {
445            kind: name(&node.projection_name)
446                .or_else(|| name(&node.kind))
447                .unwrap_or_default(),
448            field: name(&node.field),
449            trivia: node.trivia,
450            start: node.start,
451            end: node.end,
452            children: node
453                .children
454                .iter()
455                .map(|child| public_tree(child, bytes))
456                .collect(),
457            attributes: super::attributes::public_attributes(node),
458        },
459        TreeType::Token => SyntaxTree::Token {
460            kind: if node.projection_anonymous {
461                None
462            } else {
463                name(&node.projection_name).or_else(|| name(&node.kind))
464            },
465            field: name(&node.field),
466            trivia: node.trivia,
467            start: node.start,
468            end: node.end,
469            attributes: super::attributes::public_attributes(node),
470            text: LeafText::of(bytes, node.start, node.end),
471            lexical: node.lexical.clone(),
472        },
473        TreeType::Error => error_tree(bytes, node.start, node.end, None),
474        TreeType::Missing => SyntaxTree::Missing {
475            kind: name(&node.kind),
476            start: node.start,
477            end: node.end,
478            literal: node.literal,
479        },
480        TreeType::Embed => SyntaxTree::Embed {
481            language: name(&node.language).unwrap_or_default(),
482            start: node.start,
483            end: node.end,
484            root: Box::new(node.root.as_ref().map_or_else(
485                || error_tree(bytes, node.start, node.end, None),
486                |root| {
487                    public_tree(
488                        root,
489                        node.selection
490                            .as_ref()
491                            .and_then(|selection| selection.source_bytes.as_deref())
492                            .unwrap_or(bytes),
493                    )
494                },
495            )),
496            source_children: node.source_children.as_ref().map(|children| {
497                children
498                    .iter()
499                    .map(|child| public_tree(child, bytes))
500                    .collect()
501            }),
502            selection: node.selection.as_deref().map(|selection| {
503                Box::new(super::grammar_selection::public_selection(selection, bytes))
504            }),
505        },
506    }
507}
508
509pub(super) fn error_tree(
510    bytes: &[u8],
511    start: usize,
512    end: usize,
513    reason: Option<&str>,
514) -> SyntaxTree {
515    SyntaxTree::Error {
516        start,
517        end,
518        text: LeafText::of(bytes, start, end),
519        reason: reason.map(str::to_owned),
520    }
521}
522
523/// An ambiguous node outside the declared conflicts.
524#[derive(Clone, Debug, PartialEq, Eq)]
525pub struct Ambiguity {
526    /// The rule (or alias) that built the node.
527    pub rule: String,
528    /// The first byte.
529    pub start: usize,
530    /// The byte after the last.
531    pub end: usize,
532    /// Explicit accepted grammar alternatives for a language selection.
533    pub languages: Option<Vec<String>>,
534    /// Original decoded source coordinates and covering physical route.
535    pub source: Option<usize>,
536    pub source_start: Option<usize>,
537    pub source_end: Option<usize>,
538    pub source_route: Option<Vec<serde_json::Value>>,
539    pub offset_semantics: Option<String>,
540}
541
542/// The ambiguous nodes of an executor tree, in preorder, outside the declared conflicts.
543pub(super) fn collect_ambiguities(
544    node: &Tree,
545    compiled: &Compiled,
546    program: usize,
547    found: &mut Vec<Ambiguity>,
548) {
549    match node.ty {
550        TreeType::Node => {
551            let conflicts = &compiled.programs[program].conflicts;
552            if node.ambiguous
553                && !node
554                    .rule
555                    .as_deref()
556                    .is_some_and(|rule| conflicts.contains(rule))
557            {
558                found.push(Ambiguity {
559                    rule: node
560                        .rule
561                        .as_deref()
562                        .or(node.kind.as_deref())
563                        .unwrap_or_default()
564                        .to_owned(),
565                    start: node.start,
566                    end: node.end,
567                    languages: None,
568                    source: None,
569                    source_start: None,
570                    source_end: None,
571                    source_route: None,
572                    offset_semantics: None,
573                });
574            }
575            for child in node.children.iter() {
576                collect_ambiguities(child, compiled, program, found);
577            }
578        }
579        TreeType::Embed => {
580            if let Some(selection) = &node.selection
581                && selection.ambiguous
582            {
583                found.push(Ambiguity {
584                    rule: "any-grammar".to_owned(),
585                    start: node.start,
586                    end: node.end,
587                    languages: Some(
588                        selection
589                            .candidates
590                            .iter()
591                            .filter(|candidate| candidate["relation"] == "accepted")
592                            .filter_map(|candidate| {
593                                candidate["language"].as_str().map(str::to_owned)
594                            })
595                            .collect(),
596                    ),
597                    source: None,
598                    source_start: None,
599                    source_end: None,
600                    source_route: None,
601                    offset_semantics: None,
602                });
603            }
604            if let Some(children) = &node.source_children {
605                for child in children.iter() {
606                    collect_ambiguities(child, compiled, program, found);
607                }
608            }
609            let mut decoded = Vec::new();
610            let interpreted = if node.source_children.is_some() {
611                &mut decoded
612            } else {
613                &mut *found
614            };
615            if let Some(root) = &node.root {
616                collect_ambiguities(root, compiled, node.program, interpreted);
617            }
618            if let Some(selection) = &node.selection {
619                for alternative in &selection.alternatives {
620                    collect_ambiguities(
621                        &alternative.root,
622                        compiled,
623                        alternative.program,
624                        interpreted,
625                    );
626                }
627                if let Some(mapping) = &selection.source_mapping {
628                    for mut ambiguity in decoded {
629                        if let Some(cover) = super::selection_source_mapping::mapped_cover(
630                            mapping,
631                            ambiguity.start,
632                            ambiguity.end,
633                        ) {
634                            ambiguity.source.get_or_insert_with(|| {
635                                mapping["output"]
636                                    .as_u64()
637                                    .and_then(|source| usize::try_from(source).ok())
638                                    .unwrap_or_default()
639                            });
640                            ambiguity.source_start.get_or_insert(ambiguity.start);
641                            ambiguity.source_end.get_or_insert(ambiguity.end);
642                            ambiguity.source_route.get_or_insert_with(Vec::new).push(serde_json::json!({"output":mapping["output"],"outputStart":ambiguity.start,"outputEnd":ambiguity.end,
643                                "input":mapping["input"],"inputStart":cover[1],"inputEnd":cover[2],"displayAnchor":cover[0]}));
644                            ambiguity.start = cover[1];
645                            ambiguity.end = cover[2];
646                            ambiguity.offset_semantics =
647                                Some("covering-source-spelling".to_owned());
648                        }
649                        found.push(ambiguity);
650                    }
651                }
652            }
653        }
654        _ => {}
655    }
656}