Skip to main content

meta_language/
tree_sitter_adapter.rs

1use std::borrow::Cow;
2
3use tree_sitter::{
4    InputEdit, Language, Node, Parser, Point as TreeSitterPoint, Range as TreeSitterRange, Tree,
5};
6
7mod native;
8
9use crate::line_index::LineIndex;
10use crate::native_grammar_parser::{is_native_grammar, parse_native};
11use crate::{
12    ByteRange, LinkFlags, LinkId, LinkMetadata, LinkNetwork, LinkType, ParseConfiguration, Point,
13    SourceSpan,
14};
15use native::{convert_native_root, native_flags};
16
17pub fn parse(text: &str, language: &str, configuration: ParseConfiguration) -> Option<LinkNetwork> {
18    if let Some(id) = native_grammar_for_language(language) {
19        return Some(network_from_native(text, language, configuration, id));
20    }
21    let grammar = grammar_for_language(language)?;
22    let mut parser = Parser::new();
23    parser.set_language(&grammar).ok()?;
24    let parsed = parser.parse(text, None)?;
25
26    Some(network_from_tree(text, language, configuration, &parsed))
27}
28
29pub fn parse_incremental(
30    old_text: &str,
31    range: ByteRange,
32    replacement: &str,
33    language: &str,
34    configuration: ParseConfiguration,
35) -> Option<LinkNetwork> {
36    if let Some(id) = native_grammar_for_language(language) {
37        // The native executor parses the whole edited text.
38        let edited_text = apply_text_edit(old_text, range, replacement)?;
39        return Some(network_from_native(
40            &edited_text,
41            language,
42            configuration,
43            id,
44        ));
45    }
46    let grammar = grammar_for_language(language)?;
47    let edited_text = apply_text_edit(old_text, range, replacement)?;
48    let mut parser = Parser::new();
49    parser.set_language(&grammar).ok()?;
50    let mut old_tree = parser.parse(old_text, None)?;
51    old_tree.edit(&input_edit(old_text, range, replacement));
52    let mut parsed = parser.parse(&edited_text, Some(&old_tree))?;
53    // Error recovery that reuses subtrees of the old tree can settle on another
54    // tree than a fresh parse (for example an ERROR node that swallows an
55    // `else` clause), so a tree with errors is reparsed from scratch: the
56    // network of a text never depends on its edit history, and matches the
57    // JavaScript runtime, which always parses the whole text.
58    if parsed.root_node().has_error() {
59        parsed = parser.parse(&edited_text, None)?;
60    }
61
62    Some(network_from_tree(
63        &edited_text,
64        language,
65        configuration,
66        &parsed,
67    ))
68}
69
70/// Builds the network of `text` from the projected tree of the native
71/// grammar `id`, as `network_from_tree` builds it from a tree-sitter tree.
72fn network_from_native(
73    text: &str,
74    language: &str,
75    configuration: ParseConfiguration,
76    id: &str,
77) -> LinkNetwork {
78    let (mut network, document) = LinkNetwork::new_parse_document(text, language);
79    let root = parse_native(id, text);
80    let lines = LineIndex::new(text);
81    let context = ConvertContext::new(
82        text,
83        &lines,
84        language,
85        configuration,
86        SpanOffset::zero(),
87        text.len(),
88    );
89    let tree_parent = public_root(&mut network, document, context, native_flags(&root));
90    convert_native_root(&mut network, tree_parent, &root, context);
91    network.attach_embedded_regions(document, text, language, configuration);
92    network
93}
94
95/// Preserves the original public Lean root `file` above the grammar's
96/// `module` root, whichever grammar parsed the source, as `publicRoot` in
97/// `js/src/programming-language-parser.js` does. Consumers can query either
98/// layer; every other language's tree hangs from the document itself.
99fn public_root(
100    network: &mut LinkNetwork,
101    document: LinkId,
102    context: ConvertContext<'_>,
103    flags: LinkFlags,
104) -> LinkId {
105    let language = context.language;
106    if !language.eq_ignore_ascii_case("lean") && !language.eq_ignore_ascii_case("lean4") {
107        return document;
108    }
109    network.insert_link(
110        [document],
111        LinkMetadata::new()
112            .with_link_type(LinkType::Syntax)
113            .with_named(true)
114            .with_term("file")
115            .with_language(language)
116            .with_span(span_for_range(
117                context.lines,
118                0,
119                context.source_len,
120                SpanOffset::zero(),
121            ))
122            .with_flags(flags),
123    )
124}
125
126fn network_from_tree(
127    text: &str,
128    language: &str,
129    configuration: ParseConfiguration,
130    parsed: &Tree,
131) -> LinkNetwork {
132    let (mut network, document) = LinkNetwork::new_parse_document(text, language);
133    let root = parsed.root_node();
134    let lines = LineIndex::new(text);
135    let context = ConvertContext::new(
136        text,
137        &lines,
138        language,
139        configuration,
140        SpanOffset::zero(),
141        text.len(),
142    );
143    let tree_parent = public_root(&mut network, document, context, flags_for_node(root));
144    convert_root(&mut network, tree_parent, root, context);
145    network.attach_embedded_regions(document, text, language, configuration);
146    network
147}
148
149fn apply_text_edit(old_text: &str, range: ByteRange, replacement: &str) -> Option<String> {
150    if range.end() > old_text.len()
151        || !old_text.is_char_boundary(range.start())
152        || !old_text.is_char_boundary(range.end())
153    {
154        return None;
155    }
156
157    let mut edited =
158        String::with_capacity(old_text.len() - (range.end() - range.start()) + replacement.len());
159    edited.push_str(&old_text[..range.start()]);
160    edited.push_str(replacement);
161    edited.push_str(&old_text[range.end()..]);
162    Some(edited)
163}
164
165fn input_edit(old_text: &str, range: ByteRange, replacement: &str) -> InputEdit {
166    let lines = LineIndex::new(old_text);
167    let start_position = lines.byte_point(range.start());
168    let old_end_position = lines.byte_point(range.end());
169    let new_end_position = point_after_text(start_position, replacement);
170
171    InputEdit {
172        start_byte: range.start(),
173        old_end_byte: range.end(),
174        new_end_byte: range.start() + replacement.len(),
175        start_position: tree_sitter_point(start_position),
176        old_end_position: tree_sitter_point(old_end_position),
177        new_end_position: tree_sitter_point(new_end_position),
178    }
179}
180
181fn point_after_text(start: Point, text: &str) -> Point {
182    let mut row = start.row();
183    let mut column = start.column();
184    for byte in text.bytes() {
185        if byte == b'\n' {
186            row += 1;
187            column = 0;
188        } else {
189            column += 1;
190        }
191    }
192    Point::new(row, column)
193}
194
195const fn tree_sitter_point(point: Point) -> TreeSitterPoint {
196    TreeSitterPoint::new(point.row(), point.column())
197}
198
199pub fn parse_embedded_region_into(
200    network: &mut LinkNetwork,
201    region: LinkId,
202    text: &str,
203    language: &str,
204    span: SourceSpan,
205    configuration: ParseConfiguration,
206) -> Option<LinkId> {
207    let parse_text = embedded_parse_text(text, language);
208    if let Some(id) = native_grammar_for_language(language) {
209        let root = parse_native(id, parse_text.as_ref());
210        let lines = LineIndex::new(parse_text.as_ref());
211        let context = ConvertContext::new(
212            parse_text.as_ref(),
213            &lines,
214            language,
215            configuration,
216            SpanOffset::new(span.byte_range().start(), span.start_point()),
217            text.len(),
218        );
219        return Some(convert_native_root(network, region, &root, context));
220    }
221    let grammar = grammar_for_language(language)?;
222    let mut parser = Parser::new();
223    parser.set_language(&grammar).ok()?;
224    let parsed = parser.parse(parse_text.as_ref(), None)?;
225    let root = parsed.root_node();
226    let lines = LineIndex::new(parse_text.as_ref());
227    let context = ConvertContext::new(
228        parse_text.as_ref(),
229        &lines,
230        language,
231        configuration,
232        SpanOffset::new(span.byte_range().start(), span.start_point()),
233        text.len(),
234    );
235    Some(convert_root(network, region, root, context))
236}
237
238/// Converts a grammar root below `parent`. Tree-sitter starts the root after
239/// its leading padding, so the text outside the root is retained as gap
240/// tokens beside it, mirroring `parseGrammarCst` in
241/// `js/src/programming-language-parser.js`.
242fn convert_root(
243    network: &mut LinkNetwork,
244    parent: LinkId,
245    root: Node<'_>,
246    context: ConvertContext<'_>,
247) -> LinkId {
248    insert_gap_token(network, parent, 0, root.start_byte(), context);
249    let root_id = convert_node(network, parent, root, context);
250    insert_gap_token(
251        network,
252        parent,
253        root.end_byte(),
254        context.source_len,
255        context,
256    );
257    root_id
258}
259
260/// Returns the native grammar id the language catalog records as the primary
261/// default grammar of a language name or alias, when it is a native grammar.
262fn native_grammar_for_language(language: &str) -> Option<&'static str> {
263    let grammar = crate::language_catalog::language_entry(language)?
264        .grammars
265        .first()?;
266    is_native_grammar(&grammar.id).then_some(grammar.id.as_str())
267}
268
269/// Selects the primary default grammar the language catalog records for a
270/// language name or alias.
271fn grammar_for_language(language: &str) -> Option<Language> {
272    let grammar = crate::language_catalog::language_entry(language)?
273        .grammars
274        .first()?;
275    grammar_by_id(&grammar.id)
276}
277
278/// The node kind and field names a compiled default grammar declares.
279#[derive(Debug, Clone, PartialEq, Eq)]
280pub struct GrammarNames {
281    /// Node kind names by symbol id; bytes that are not UTF-8 read as U+FFFD.
282    pub node_kinds: Vec<String>,
283    /// Field names by field id, starting at field id 1.
284    pub fields: Vec<String>,
285}
286
287/// Returns the node kind and field names of a default grammar by its
288/// grammar-lock id, or `None` for an unknown id or an oracle grammar.
289///
290/// Both runtimes compile the same generated parser, so the names equal the
291/// WebAssembly grammar's. A C compiler that re-encodes the parser's non-ASCII
292/// names (MSVC without `/utf-8`) makes them differ instead of failing.
293#[must_use]
294#[allow(unsafe_code)]
295pub fn grammar_names(id: &str) -> Option<GrammarNames> {
296    use std::ffi::{CStr, c_char};
297    use tree_sitter::ffi;
298
299    let raw = grammar_by_id(id)?.into_raw();
300    let name = |pointer: *const c_char| {
301        if pointer.is_null() {
302            String::new()
303        } else {
304            // SAFETY: the grammar's names are NUL-terminated static strings.
305            unsafe { CStr::from_ptr(pointer) }
306                .to_string_lossy()
307                .into_owned()
308        }
309    };
310    // SAFETY: `raw` is the live language `into_raw` released, and the name
311    // functions return null for ids outside the grammar's tables.
312    let (node_kinds, fields) = unsafe {
313        let symbols = u16::try_from(ffi::ts_language_symbol_count(raw)).unwrap_or(u16::MAX);
314        let fields = u16::try_from(ffi::ts_language_field_count(raw)).unwrap_or(u16::MAX);
315        (
316            (0..symbols)
317                .map(|symbol| name(ffi::ts_language_symbol_name(raw, symbol)))
318                .collect(),
319            (1..=fields)
320                .map(|field| name(ffi::ts_language_field_name_for_id(raw, field)))
321                .collect(),
322        )
323    };
324    // SAFETY: returns the ownership `into_raw` released, so the language is freed.
325    drop(unsafe { Language::from_raw(raw) });
326    Some(GrammarNames { node_kinds, fields })
327}
328
329/// Returns the compiled grammar for a grammar-lock id. The oracle grammars of
330/// the languages a native grammar parses are development dependencies, so
331/// their ids return `None`.
332pub fn grammar_by_id(id: &str) -> Option<Language> {
333    Some(match id {
334        "bash" => tree_sitter_bash::LANGUAGE.into(),
335        "csharp" => tree_sitter_c_sharp::LANGUAGE.into(),
336        "elixir" => tree_sitter_elixir::LANGUAGE.into(),
337        "elm" => tree_sitter_elm::LANGUAGE.into(),
338        "haskell" => tree_sitter_haskell::LANGUAGE.into(),
339        "kotlin" => tree_sitter_kotlin_ng::LANGUAGE.into(),
340        "markdown" => tree_sitter_md_025::LANGUAGE.into(),
341        "markdown_inline" => tree_sitter_md_025::INLINE_LANGUAGE.into(),
342        "matlab" => tree_sitter_matlab::LANGUAGE.into(),
343        "ocaml" => tree_sitter_ocaml::LANGUAGE_OCAML.into(),
344        "ocaml_interface" => tree_sitter_ocaml::LANGUAGE_OCAML_INTERFACE.into(),
345        "perl" => ts_parser_perl::LANGUAGE.into(),
346        "php" => tree_sitter_php::LANGUAGE_PHP.into(),
347        "ruby" => tree_sitter_ruby::LANGUAGE.into(),
348        "scala" => tree_sitter_scala::LANGUAGE.into(),
349        "swift" => tree_sitter_swift::LANGUAGE.into(),
350        "yaml" => tree_sitter_yaml::LANGUAGE.into(),
351        _ => return None,
352    })
353}
354
355fn convert_node(
356    network: &mut LinkNetwork,
357    parent: LinkId,
358    node: Node<'_>,
359    context: ConvertContext<'_>,
360) -> LinkId {
361    convert_node_with(network, parent, node, &[], context)
362}
363
364/// Converts `node`, placing `injected` nodes from another tree (Markdown block
365/// continuations inside inline content) among its children. Mirrors
366/// `convertGrammarNode` in `js/src/programming-language-parser.js`.
367fn convert_node_with<'tree>(
368    network: &mut LinkNetwork,
369    parent: LinkId,
370    node: Node<'tree>,
371    injected: &[Node<'tree>],
372    context: ConvertContext<'_>,
373) -> LinkId {
374    let flags = flags_for_node(node);
375    let node_id = network.insert_link(
376        [parent],
377        LinkMetadata::new()
378            .with_link_type(LinkType::Syntax)
379            .with_named(node.is_named())
380            .with_term(node.kind())
381            .with_language(context.language)
382            .with_span(span_for_node(
383                node,
384                context.lines,
385                context.source_len,
386                context.offset,
387            ))
388            .with_flags(flags),
389    );
390
391    let inline_tree = is_markdown_inline_container(node, context.language)
392        .then(|| parse_markdown_inline(node, context.text));
393    let mut extra_children = injected.to_vec();
394    let own_children = inline_tree.as_ref().map_or_else(
395        || children_with_fields(node),
396        |tree| {
397            extra_children.extend(markdown_inline_excluded_children(node));
398            children_with_fields(tree.root_node())
399        },
400    );
401
402    if own_children.is_empty() && extra_children.is_empty() {
403        if is_rocq_identifier(node, context.language) {
404            let semantic_term =
405                rocq_identifier_term(&context.text[node.start_byte()..node.end_byte()]);
406            let semantic_id = network.insert_link(
407                [node_id],
408                LinkMetadata::new()
409                    .with_link_type(LinkType::Syntax)
410                    .with_named(node.is_named())
411                    .with_term(semantic_term)
412                    .with_language(context.language)
413                    .with_span(span_for_node(
414                        node,
415                        context.lines,
416                        context.source_len,
417                        context.offset,
418                    ))
419                    .with_flags(flags),
420            );
421            insert_leaf_token(network, semantic_id, node, context);
422        } else {
423            insert_leaf_token(network, node_id, node, context);
424        }
425        return node_id;
426    }
427
428    let mut covered_until = node.start_byte();
429    let mut child_has_error = false;
430    for child in distribute_injected_children(own_children, &extra_children) {
431        if context.has_synthetic_suffix() && child.node.start_byte() >= context.source_len {
432            break;
433        }
434        insert_gap_token(
435            network,
436            node_id,
437            covered_until,
438            child.node.start_byte(),
439            context,
440        );
441
442        let child_id = convert_node_with(network, node_id, child.node, &child.injected, context);
443        if let Some(label) = child.field {
444            network.insert_field(node_id, label, child_id);
445        }
446        child_has_error |= network
447            .link(child_id)
448            .is_some_and(|link| link.metadata().flags().has_error());
449        covered_until = covered_until.max(child.node.end_byte().min(context.source_len));
450    }
451
452    insert_gap_token(network, node_id, covered_until, node.end_byte(), context);
453    // A Markdown inline tree is parsed separately from its block container, so
454    // its errors reach the containing block nodes through their children.
455    if child_has_error && !flags.has_error() {
456        network.set_flags(node_id, flags.with_containing_error());
457    }
458    node_id
459}
460
461struct ChildNode<'tree> {
462    node: Node<'tree>,
463    field: Option<&'tree str>,
464    injected: Vec<Node<'tree>>,
465}
466
467fn children_with_fields(node: Node<'_>) -> Vec<ChildNode<'_>> {
468    (0..node.child_count())
469        .map(|index| ChildNode {
470            node: node
471                .child(index)
472                .expect("tree-sitter child index should be valid"),
473            field: node.field_name_for_child(index),
474            injected: Vec::new(),
475        })
476        .collect()
477}
478
479fn is_markdown_inline_container(node: Node<'_>, language: &str) -> bool {
480    (language.eq_ignore_ascii_case("markdown") || language.eq_ignore_ascii_case("md"))
481        && matches!(node.kind(), "inline" | "pipe_table_cell")
482}
483
484/// Named children of a Markdown inline container after the first, which the
485/// inline grammar skips, exactly as upstream's `MarkdownParser` does.
486fn markdown_inline_excluded_children(node: Node<'_>) -> Vec<Node<'_>> {
487    (1..node.child_count())
488        .filter_map(|index| node.child(index))
489        .filter(Node::is_named)
490        .collect()
491}
492
493/// tree-sitter-markdown parses block structure and inline content with two
494/// grammars. Like upstream's `MarkdownParser` (`bindings/rust/parser.rs` in
495/// tree-sitter-md), every `inline` and `pipe_table_cell` block node is parsed
496/// again with the inline grammar over the node's range minus its named
497/// children after the first (block continuations such as a quote's `> `).
498/// Mirrors `parseMarkdownInline` in `js/src/programming-language-parser.js`.
499fn parse_markdown_inline(node: Node<'_>, text: &str) -> Tree {
500    let mut range = node.range();
501    let mut ranges = Vec::new();
502    for child in markdown_inline_excluded_children(node) {
503        ranges.push(TreeSitterRange {
504            start_byte: range.start_byte,
505            start_point: range.start_point,
506            end_byte: child.start_byte(),
507            end_point: child.start_position(),
508        });
509        range.start_byte = child.end_byte();
510        range.start_point = child.end_position();
511    }
512    ranges.push(range);
513    let mut parser = Parser::new();
514    parser
515        .set_language(&tree_sitter_md_025::INLINE_LANGUAGE.into())
516        .expect("the Markdown inline grammar matches the tree-sitter ABI");
517    parser
518        .set_included_ranges(&ranges)
519        .expect("Markdown inline ranges follow the ordered block children");
520    parser
521        .parse(text, None)
522        .expect("tree-sitter parses without a timeout or cancellation")
523}
524
525/// Places nodes from another tree under the deepest child whose range contains
526/// them, and orders the rest among the children by start offset, block nodes
527/// first on ties.
528fn distribute_injected_children<'tree>(
529    mut children: Vec<ChildNode<'tree>>,
530    injected: &[Node<'tree>],
531) -> Vec<ChildNode<'tree>> {
532    let mut top = Vec::new();
533    for &node in injected {
534        if let Some(owner) = children
535            .iter_mut()
536            .find(|child| contains_node(child.node, node))
537        {
538            owner.injected.push(node);
539        } else {
540            top.push(ChildNode {
541                node,
542                field: None,
543                injected: Vec::new(),
544            });
545        }
546    }
547    if top.is_empty() {
548        return children;
549    }
550    top.extend(children);
551    top.sort_by_key(|child| child.node.start_byte());
552    top
553}
554
555fn contains_node(outer: Node<'_>, inner: Node<'_>) -> bool {
556    let (outer_start, outer_end) = (outer.start_byte(), outer.end_byte());
557    let (inner_start, inner_end) = (inner.start_byte(), inner.end_byte());
558    outer_start <= inner_start
559        && inner_end <= outer_end
560        && (inner_start < inner_end || (outer_start < inner_start && inner_start < outer_end))
561}
562
563const fn is_rocq_language(language: &str) -> bool {
564    language.eq_ignore_ascii_case("rocq") || language.eq_ignore_ascii_case("coq")
565}
566
567/// A Rocq `ident` with text, which also exposes it as a semantic leaf; a
568/// repaired, empty `ident` has none.
569fn is_rocq_identifier(node: Node<'_>, language: &str) -> bool {
570    is_rocq_language(language) && node.kind() == "ident" && node.start_byte() < node.end_byte()
571}
572
573fn rocq_identifier_term(text: &str) -> &'static str {
574    match text {
575        "bool" | "nat" | "Prop" | "Set" | "SProp" | "Type" | "Z" => "primitive_type",
576        _ => "identifier",
577    }
578}
579
580fn insert_leaf_token(
581    network: &mut LinkNetwork,
582    owner: LinkId,
583    node: Node<'_>,
584    context: ConvertContext<'_>,
585) {
586    let start = node.start_byte();
587    let end = node.end_byte().min(context.source_len);
588    if node.is_missing() || start >= end {
589        return;
590    }
591
592    let span = span_for_range(context.lines, start, end, context.offset);
593    let flags = flags_for_node(node);
594    let token = network.insert_link(
595        [owner],
596        LinkMetadata::new()
597            .with_link_type(LinkType::Token)
598            .with_named(node.is_named())
599            .with_term(&context.text[start..end])
600            .with_language(context.language)
601            .with_span(span)
602            .with_flags(flags),
603    );
604
605    if flags.is_extra() {
606        network.attach_trivia(
607            owner,
608            token,
609            span,
610            context.configuration.trivia_attachment_policy(),
611        );
612    }
613}
614
615/// Inserts the source text between visible tree-sitter children. That text is
616/// either lexer extras or text matched by hidden grammar rules (such as VB's
617/// `Module` keyword). Leading and trailing whitespace becomes extra trivia, and
618/// the text between them a non-extra token, mirroring `pushGapNodes` in
619/// `js/src/programming-language-parser.js`.
620fn insert_gap_token(
621    network: &mut LinkNetwork,
622    owner: LinkId,
623    start: usize,
624    end: usize,
625    context: ConvertContext<'_>,
626) {
627    let start = start.min(context.source_len);
628    let end = end.min(context.source_len);
629    if start >= end {
630        return;
631    }
632    let gap = &context.text[start..end];
633    let content_start = start + (gap.len() - gap.trim_start_matches(is_gap_whitespace).len());
634    let content_end = content_start + gap.trim_matches(is_gap_whitespace).len();
635    for (piece_start, piece_end, flags) in [
636        (start, content_start, LinkFlags::extra()),
637        (content_start, content_end, LinkFlags::clean()),
638        (content_end, end, LinkFlags::extra()),
639    ] {
640        if piece_start >= piece_end {
641            continue;
642        }
643        let span = span_for_range(context.lines, piece_start, piece_end, context.offset);
644        let token = network.insert_link(
645            [owner],
646            LinkMetadata::new()
647                .with_link_type(LinkType::Token)
648                .with_named(false)
649                .with_term(&context.text[piece_start..piece_end])
650                .with_language(context.language)
651                .with_span(span)
652                .with_flags(flags),
653        );
654        if flags.is_extra() {
655            network.attach_trivia(
656                owner,
657                token,
658                span,
659                context.configuration.trivia_attachment_policy(),
660            );
661        }
662    }
663}
664
665/// Whitespace around hidden-rule text: Unicode whitespace and the invisible
666/// format characters grammars lex as extras (tree-sitter-javascript's U+200B,
667/// U+2060 and U+FEFF).
668const fn is_gap_whitespace(character: char) -> bool {
669    character.is_whitespace() || matches!(character, '\u{200B}' | '\u{2060}' | '\u{FEFF}')
670}
671
672fn flags_for_node(node: Node<'_>) -> LinkFlags {
673    let mut flags = LinkFlags::clean();
674    if node.is_error() {
675        flags = flags.with_error();
676    }
677    // Mirrors tree-sitter's `ts_node_has_error`, which is true for error and
678    // missing nodes themselves as well as for their ancestors.
679    if node.has_error() || node.is_error() || node.is_missing() {
680        flags = flags.with_containing_error();
681    }
682    if node.is_missing() {
683        flags = flags.with_missing();
684    }
685    if node.is_extra() {
686        flags = flags.with_extra();
687    }
688    flags
689}
690
691fn span_for_node(
692    node: Node<'_>,
693    lines: &LineIndex,
694    source_len: usize,
695    offset: SpanOffset,
696) -> SourceSpan {
697    let start = node.start_byte().min(source_len);
698    let end = node.end_byte().min(source_len);
699    span_for_range(lines, start, end, offset)
700}
701
702fn span_for_range(lines: &LineIndex, start: usize, end: usize, offset: SpanOffset) -> SourceSpan {
703    SourceSpan::new(
704        ByteRange::new(offset.byte + start, offset.byte + end),
705        offset.point(lines.byte_point(start)),
706        offset.point(lines.byte_point(end)),
707    )
708}
709
710fn embedded_parse_text<'a>(text: &'a str, language: &str) -> Cow<'a, str> {
711    if language.eq_ignore_ascii_case("css") && css_declaration_list_needs_semicolon(text) {
712        Cow::Owned(format!("{text};"))
713    } else {
714        Cow::Borrowed(text)
715    }
716}
717
718fn css_declaration_list_needs_semicolon(text: &str) -> bool {
719    let trimmed = text.trim_end();
720    !trimmed.is_empty()
721        && !trimmed.ends_with(';')
722        && !trimmed.ends_with('}')
723        && !trimmed.contains('{')
724}
725
726/// Position of a parsed text inside its host document, used to translate
727/// region-relative spans into document spans.
728#[derive(Clone, Copy, Debug, PartialEq, Eq)]
729pub struct SpanOffset {
730    byte: usize,
731    point: Point,
732}
733
734impl SpanOffset {
735    pub const fn new(byte: usize, point: Point) -> Self {
736        Self { byte, point }
737    }
738
739    pub const fn zero() -> Self {
740        Self::new(0, Point::new(0, 0))
741    }
742
743    pub const fn byte(self, byte: usize) -> usize {
744        self.byte + byte
745    }
746
747    pub const fn point(self, point: Point) -> Point {
748        let row = self.point.row() + point.row();
749        let column = if point.row() == 0 {
750            self.point.column() + point.column()
751        } else {
752            point.column()
753        };
754        Point::new(row, column)
755    }
756}
757
758#[derive(Clone, Copy, Debug, PartialEq, Eq)]
759struct ConvertContext<'a> {
760    text: &'a str,
761    lines: &'a LineIndex,
762    language: &'a str,
763    configuration: ParseConfiguration,
764    offset: SpanOffset,
765    source_len: usize,
766}
767
768impl<'a> ConvertContext<'a> {
769    const fn new(
770        text: &'a str,
771        lines: &'a LineIndex,
772        language: &'a str,
773        configuration: ParseConfiguration,
774        offset: SpanOffset,
775        source_len: usize,
776    ) -> Self {
777        Self {
778            text,
779            lines,
780            language,
781            configuration,
782            offset,
783            source_len,
784        }
785    }
786
787    const fn has_synthetic_suffix(self) -> bool {
788        self.source_len < self.text.len()
789    }
790}
791
792/// The top-level nodes of `text` in `language`'s default grammar as
793/// `(kind, start, end)` byte ranges, or `None` when no grammar parses it.
794pub fn top_level_nodes(text: &str, language: &str) -> Option<Vec<(String, usize, usize)>> {
795    if let Some(id) = native_grammar_for_language(language) {
796        let root = parse_native(id, text);
797        if crate::translation::frontend_rules::accept_root_syntax_item(
798            &root.term,
799            !root.children.is_empty(),
800            root.end > root.start,
801        ) {
802            return Some(vec![(root.term, root.start, root.end)]);
803        }
804        return Some(
805            root.children
806                .iter()
807                .map(|(child, _)| (child.term.clone(), child.start, child.end))
808                .collect(),
809        );
810    }
811    let grammar = grammar_for_language(language)?;
812    let mut parser = Parser::new();
813    parser.set_language(&grammar).ok()?;
814    let parsed = parser.parse(text, None)?;
815    let root = parsed.root_node();
816    let mut cursor = root.walk();
817    Some(
818        root.children(&mut cursor)
819            .map(|child| {
820                (
821                    child.kind().to_owned(),
822                    child.start_byte(),
823                    child.end_byte(),
824                )
825            })
826            .collect(),
827    )
828}