Skip to main content

fatou_parser/parser/
core.rs

1use crate::parser::events::Event;
2use crate::parser::expr::parse_stmt;
3use crate::parser::lexer::{TokKind, Token, lex};
4use crate::parser::tree_builder::{build_tree, syntax_kind_for};
5use crate::syntax::{SyntaxKind, SyntaxNode};
6
7pub use crate::parser::diagnostics::ParseDiagnostic;
8use crate::parser::diagnostics::{DiagnosticKind, push_diagnostic};
9
10/// The result of a parse: the lossless CST plus any diagnostics.
11#[derive(Debug, Clone)]
12pub struct ParseOutput {
13    pub cst: SyntaxNode,
14    pub diagnostics: Vec<ParseDiagnostic>,
15}
16
17/// Parse `text` into a lossless `rowan` CST. The drive loop works one logical
18/// line at a time: leading trivia (including newlines) is emitted directly at
19/// the root, then the line's statements are parsed with the Pratt parser. A line
20/// that carries a top-level `;` groups its statements into a `TOPLEVEL_SEMICOLON`
21/// node (mirroring JuliaSyntax's `toplevel-;`); a plain line stays bare. An
22/// unparseable token is consumed as one error token so the loop always makes
23/// progress.
24pub fn parse(text: &str) -> ParseOutput {
25    let tokens = lex(text);
26    let mut diagnostics = Vec::new();
27    let mut events = Vec::new();
28
29    let mut i = 0usize;
30    while i < tokens.len() {
31        // Leading trivia and blank/newline runs belong directly at the root.
32        if tokens[i].kind.is_trivia() {
33            events.push(Event::Tok(i));
34            i += 1;
35            continue;
36        }
37
38        // Collect a single logical line (up to the next newline or EOF),
39        // tracking whether it carries a `;` separator. `leftover_mark` records
40        // the event offset right after the line's first complete statement so a
41        // trailing junk run on a separator-less line can be wrapped in an
42        // `ERROR` node and flagged with a `TrailingJunk` diagnostic (projected
43        // `(error-t …)`: `x y` ⇒ `x (error-t y)`).
44        let mut line = Vec::new();
45        let mut has_semicolon = false;
46        let mut leftover_mark: Option<usize> = None;
47        let mut first_is_doc_string = false;
48        // A doc-eligible string is only a docstring when a *real* statement
49        // follows it. If the leftover after the string can't start a statement
50        // (a stray closer/keyword: `"doc" ]`), the string is a plain statement
51        // and the remainder is junk — un-gate the raw trailing-junk collection.
52        let mut doc_no_target = false;
53        // A separator-less line: after the first complete statement, JuliaSyntax
54        // bumps the remainder as flat error tokens rather than re-parsing it. A
55        // line that carries a `;` keeps the per-segment behavior (deferred), so
56        // flat-junk collection is gated off when one is present.
57        let line_has_semicolon = rest_of_line_has_semicolon(&tokens, i);
58        while i < tokens.len() {
59            match tokens[i].kind {
60                TokKind::Newline => break,
61                TokKind::Semicolon => {
62                    has_semicolon = true;
63                    line.push(Event::Tok(i));
64                    i += 1;
65                }
66                k if k.is_trivia() => {
67                    line.push(Event::Tok(i));
68                    i += 1;
69                }
70                _ => {
71                    if !line_has_semicolon
72                        && leftover_mark.is_some()
73                        && (!first_is_doc_string || doc_no_target)
74                    {
75                        // Trailing junk after the first statement: collect raw
76                        // (no structural re-parse) so the wrapping below puts the
77                        // whole run in one ERROR node and the projector renders
78                        // delimiters, commas, and `@` as `✘` (`x y, z` ⇒
79                        // `x (error-t y ✘ z)`, `x@y` ⇒ `x (error-t ✘ y)`).
80                        line.push(Event::Tok(i));
81                        i += 1;
82                    } else if let Some(expr) = parse_stmt(&tokens, i, &mut diagnostics) {
83                        if leftover_mark.is_none() {
84                            first_is_doc_string = stmt_is_doc_string(&expr.events, &tokens);
85                        }
86                        line.extend(expr.events);
87                        i = expr.end;
88                        leftover_mark.get_or_insert(line.len());
89                    } else if leftover_mark.is_none()
90                        && is_close_delimiter_tok(tokens[i].kind)
91                        && !rest_of_line_has_semicolon(&tokens, i)
92                    {
93                        // A stray *closing* delimiter at statement start (no
94                        // preceding statement) is JuliaSyntax's leading empty
95                        // `(error)` plus an `(error-t ✘ …)` that swallows the
96                        // rest of the line: `)` ⇒ `(error) (error-t ✘)`,
97                        // `) x` ⇒ `(error) (error-t ✘ x)`, `)))` ⇒ `… ✘ ✘ ✘`.
98                        // The `;`-segment forms emit a subtler double marker, so
99                        // they are left to the loose-token fallback below.
100                        line.push(Event::Start(SyntaxKind::ERROR));
101                        line.push(Event::Finish);
102                        let run_start = tokens[i].start;
103                        line.push(Event::Start(SyntaxKind::ERROR));
104                        while i < tokens.len() && tokens[i].kind != TokKind::Newline {
105                            line.push(Event::Tok(i));
106                            i += 1;
107                        }
108                        line.push(Event::Finish);
109                        push_diagnostic(
110                            &mut diagnostics,
111                            DiagnosticKind::StrayCloser,
112                            "stray closing delimiter",
113                            run_start,
114                            tokens[i - 1].end,
115                        );
116                    } else if leftover_mark.is_none() && is_stray_block_keyword_tok(tokens[i].kind)
117                    {
118                        // A middle/closing block keyword (`end`, `else`,
119                        // `elseif`, `catch`, `finally`) where a statement is
120                        // expected is not a block opener; JuliaSyntax wraps it
121                        // alone in `(error <kw>)` and bumps the rest of the line
122                        // as a separate trailing-junk run (`end y z` ⇒
123                        // `(error end) (error-t y z)`). Emit the wrapped keyword
124                        // as the line's first "statement" and set `leftover_mark`
125                        // so the existing trailing-junk machinery handles the
126                        // remainder.
127                        line.push(Event::Start(SyntaxKind::ERROR));
128                        line.push(Event::Tok(i));
129                        line.push(Event::Finish);
130                        push_diagnostic(
131                            &mut diagnostics,
132                            DiagnosticKind::StrayKeyword,
133                            "unexpected block keyword",
134                            tokens[i].start,
135                            tokens[i].end,
136                        );
137                        i += 1;
138                        leftover_mark = Some(line.len());
139                    } else {
140                        // A leftover token that can't start a statement. After a
141                        // doc-eligible string this means the string has no
142                        // documentable target, so the rest of the line is junk.
143                        if first_is_doc_string && leftover_mark.is_some() {
144                            doc_no_target = true;
145                        }
146                        line.push(Event::Tok(i));
147                        i += 1;
148                    }
149                }
150            }
151        }
152
153        if has_semicolon {
154            events.push(Event::Start(SyntaxKind::TOPLEVEL_SEMICOLON));
155            events.extend(line);
156            events.push(Event::Finish);
157        } else if let Some(mark) = leftover_mark.filter(|&m| {
158            // Junk after the first statement on a separator-less line — but a
159            // bare docstring (`"a"\nfoo`) owns its trailing statement, so leave
160            // that to `fold_docstrings`. A docstring defers only when its
161            // leftover actually begins with a documentable statement subtree
162            // (`"doc" foo`); a leftover that opens with junk (`"doc" ]`) is
163            // recovered here so the stray closer becomes `(error-t ✘)`.
164            let tail = &line[m..];
165            let defer_to_doc = first_is_doc_string && leftover_starts_with_subtree(tail, &tokens);
166            !defer_to_doc && tail.iter().any(|e| is_significant_event(e, &tokens))
167        }) {
168            events.extend(line[..mark].iter().cloned());
169            let tail = &line[mark..];
170            // Leading trivia stays outside the error node; everything from the
171            // first significant leftover token onward is the recovered run.
172            let lead = tail
173                .iter()
174                .take_while(|e| !is_significant_event(e, &tokens))
175                .count();
176            events.extend(tail[..lead].iter().cloned());
177            let first_junk = tail[lead..].iter().find_map(|e| match e {
178                Event::Tok(idx) => Some(*idx),
179                _ => None,
180            });
181            events.push(Event::Start(SyntaxKind::ERROR));
182            events.extend(tail[lead..].iter().cloned());
183            events.push(Event::Finish);
184            if let Some(idx) = first_junk {
185                push_diagnostic(
186                    &mut diagnostics,
187                    DiagnosticKind::TrailingJunk,
188                    "trailing tokens after statement",
189                    tokens[idx].start,
190                    tokens[idx].end,
191                );
192            }
193        } else {
194            events.extend(line);
195        }
196    }
197
198    let events = fold_docstrings(&events, &tokens);
199
200    let cst = build_tree(&tokens, &events);
201    // The post-build flag passes. Each walks the finished CST for a shape
202    // JuliaSyntax error-wraps and records a *zero-width point* diagnostic at the
203    // offending node's start; the projector reconstructs the error wrapper from
204    // that anchor, so the CST itself stays faithful to the source.
205    flag_invalid_const_decls(&cst, &mut diagnostics);
206    flag_invalid_function_signatures(&cst, &mut diagnostics);
207    flag_invalid_catch_vars(&cst, &mut diagnostics);
208    flag_invalid_export_items(&cst, &mut diagnostics);
209    ParseOutput { cst, diagnostics }
210}
211
212/// Flag each parenthesized `export` item that is not a single symbol. An export
213/// item may be parenthesized, but only around a single identifier, operator,
214/// `var"…"`, or `$`-interpolation (`export (x)`/`export (+)`/`export ($a)`),
215/// which JuliaSyntax unwraps to the bare symbol. Any other parenthesized form
216/// (`export (x::T)`, `export (x, y)`, `export ()`, `export ((x))`) is invalid and
217/// JuliaSyntax error-wraps the parsed expression (`(export (error (::-i x T)))`).
218fn flag_invalid_export_items(cst: &SyntaxNode, diagnostics: &mut Vec<ParseDiagnostic>) {
219    for stmt in cst
220        .descendants()
221        .filter(|n| n.kind() == SyntaxKind::EXPORT_STMT)
222    {
223        for item in stmt
224            .children()
225            .filter(|c| matches!(c.kind(), SyntaxKind::PAREN_EXPR | SyntaxKind::TUPLE_EXPR))
226        {
227            if !export_paren_is_symbol(&item) {
228                let pos = usize::from(item.text_range().start());
229                push_diagnostic(
230                    diagnostics,
231                    DiagnosticKind::InvalidExportItem,
232                    "invalid `export` item: expected a single symbol",
233                    pos,
234                    pos,
235                );
236            }
237        }
238    }
239}
240
241/// Whether a parenthesized `export` item wraps a single symbol that JuliaSyntax
242/// unwraps: a lone identifier (`(x)`), `var"…"` (`(var"x")`), `$`-interpolation
243/// (`($a)`), or operator (`(+)`). A `(x, y)` tuple, an empty `()`, a nested paren
244/// (`((x))`), a literal (`(1)`), or any compound expression (`(x::T)`, `(a+b)`)
245/// is not. A `TUPLE_EXPR` (a comma/empty paren) is always invalid.
246fn export_paren_is_symbol(item: &SyntaxNode) -> bool {
247    if item.kind() != SyntaxKind::PAREN_EXPR {
248        return false;
249    }
250    let mut significant = item.children_with_tokens().filter(|el| {
251        !matches!(
252            el.kind(),
253            SyntaxKind::WHITESPACE
254                | SyntaxKind::NEWLINE
255                | SyntaxKind::COMMENT
256                | SyntaxKind::BLOCK_COMMENT
257                | SyntaxKind::LPAREN
258                | SyntaxKind::RPAREN
259        )
260    });
261    let Some(first) = significant.next() else {
262        return false;
263    };
264    if significant.next().is_some() {
265        return false;
266    }
267    match first {
268        // A symbol-shaped node: a bare name, `var"…"`, or `$`-interpolation. A
269        // `LITERAL`, `TYPE_ANNOTATION`, nested `PAREN_EXPR`, etc. is not.
270        rowan::NodeOrToken::Node(n) => match n.kind() {
271            SyntaxKind::NAME | SyntaxKind::NONSTANDARD_IDENTIFIER | SyntaxKind::INTERPOLATION => {
272                true
273            }
274            // A parenthesized operator value (`(..)`, `(√)`, `(⊕)`) — which
275            // `parse_paren` wraps in an `OPERATOR_ATOM` — is a valid export
276            // symbol, but a dotted broadcast operator (`(.+)`, `(.≤)`) is not:
277            // JuliaSyntax error-wraps it (`export (.+)` ⇒ `(export (error (. +)))`).
278            SyntaxKind::OPERATOR_ATOM => !export_operator_atom_is_dotted(&n),
279            _ => false,
280        },
281        // The only bare token a `PAREN_EXPR` carries is the lone operator-value
282        // form (`(+)`, `(:)`), which `parse_paren` builds for `is_paren_value_op`.
283        rowan::NodeOrToken::Token(_) => true,
284    }
285}
286
287/// Whether a parenthesized `export`/`import` operator atom is a *dotted*
288/// (broadcast) operator (`.+`, `.≤`, `.&&`), which JuliaSyntax rejects as an
289/// export symbol. The range/splat operators `..`/`...` lead with a *doubled*
290/// dot and are not broadcasts, so they are valid; a lone `√`/`⊕` has no dot.
291fn export_operator_atom_is_dotted(atom: &SyntaxNode) -> bool {
292    atom.children_with_tokens()
293        .filter_map(|el| el.into_token())
294        .find(|t| {
295            !matches!(
296                t.kind(),
297                SyntaxKind::WHITESPACE
298                    | SyntaxKind::NEWLINE
299                    | SyntaxKind::COMMENT
300                    | SyntaxKind::BLOCK_COMMENT
301            )
302        })
303        .is_some_and(|t| {
304            let bytes = t.text().as_bytes();
305            bytes.first() == Some(&b'.') && bytes.len() > 1 && bytes[1] != b'.'
306        })
307}
308
309/// Flag each `const` whose declaration is not the plain `=` assignment
310/// JuliaSyntax requires. A bare declaration (`const x`), a non-`=` assignment
311/// (`const x += 1`, `const x .= 1`), or a `global`/`local` declaration without an
312/// `=` (`const global x`) is invalid, so JuliaSyntax wraps the whole `const` in
313/// `(error …)` (`const x` ⇒ `(error (const x))`). A valid `const x = 1` — or a
314/// `global`/`local`-wrapped `=` (`const global x = 1`) — is left alone. The
315/// diagnostic anchors at the `const` keyword start.
316fn flag_invalid_const_decls(cst: &SyntaxNode, diagnostics: &mut Vec<ParseDiagnostic>) {
317    for node in cst
318        .descendants()
319        .filter(|n| n.kind() == SyntaxKind::CONST_STMT)
320    {
321        if !const_decl_is_assignment(&node) && !is_struct_const_field(&node) {
322            let pos = usize::from(node.text_range().start());
323            push_diagnostic(
324                diagnostics,
325                DiagnosticKind::ConstNotAssignment,
326                "expected assignment after `const`",
327                pos,
328                pos,
329            );
330        }
331    }
332}
333
334/// Flag each invalid `function`/`macro` signature. A bare name is a valid forward
335/// declaration only with a truly empty body; a direct parenthesized macro call or
336/// interpolation is an invalid anonymous-function parameter tuple. JuliaSyntax
337/// error-wraps either signature, and the diagnostic anchors at `SIGNATURE`.
338fn flag_invalid_function_signatures(cst: &SyntaxNode, diagnostics: &mut Vec<ParseDiagnostic>) {
339    for node in cst
340        .descendants()
341        .filter(|n| matches!(n.kind(), SyntaxKind::FUNCTION_DEF | SyntaxKind::MACRO_DEF))
342    {
343        let Some(sig) = node.children().find(|c| c.kind() == SyntaxKind::SIGNATURE) else {
344            continue;
345        };
346        let sig_is_bare_name = sig
347            .first_child()
348            .is_some_and(|inner| is_bare_signature_name(&inner));
349        let invalid_bare_name = sig_is_bare_name
350            && (!function_body_is_empty(&node) || invalid_forward_operator_name(&sig));
351        let invalid_parenthesized_macro = invalid_parenthesized_macro_signature(&sig);
352        if invalid_bare_name || invalid_parenthesized_macro {
353            let pos = usize::from(sig.text_range().start());
354            push_diagnostic(
355                diagnostics,
356                DiagnosticKind::InvalidFunctionSignature,
357                if invalid_bare_name {
358                    "invalid function signature: expected a call, not a bare name"
359                } else {
360                    "invalid function signature: macro call or interpolation cannot bind a parameter"
361                },
362                pos,
363                pos,
364            );
365        }
366    }
367}
368
369/// Whether a singleton anonymous-function parameter list is a macro call or an
370/// interpolation. These expression forms cannot bind a parameter, so JuliaSyntax
371/// wraps the whole tuple in an error. A comma, semicolon, or splat makes the
372/// corresponding tuple shape valid and therefore stays outside this recovery.
373fn invalid_parenthesized_macro_signature(signature: &SyntaxNode) -> bool {
374    let Some(tuple) = signature
375        .first_child()
376        .filter(|node| node.kind() == SyntaxKind::TUPLE_EXPR)
377    else {
378        return false;
379    };
380    if tuple.children().count() != 1
381        || tuple
382            .children_with_tokens()
383            .any(|element| element.kind() == SyntaxKind::COMMA)
384    {
385        return false;
386    }
387
388    let mut child = tuple.first_child();
389    while child
390        .as_ref()
391        .is_some_and(|node| node.kind() == SyntaxKind::PAREN_EXPR)
392    {
393        child = child.and_then(|node| node.first_child());
394    }
395    child.is_some_and(|node| {
396        matches!(
397            node.kind(),
398            SyntaxKind::MACRO_CALL | SyntaxKind::INTERPOLATION
399        )
400    })
401}
402
403/// JuliaSyntax 1.0 rejects syntactic, broadcast, and bare `&` operators as
404/// forward-declaration names even though ordinary operators remain valid.
405fn invalid_forward_operator_name(signature: &SyntaxNode) -> bool {
406    let Some(inner) = signature.first_child() else {
407        return false;
408    };
409    if inner.kind() == SyntaxKind::ERROR {
410        return true;
411    }
412    if inner.kind() != SyntaxKind::OPERATOR_ATOM {
413        return false;
414    }
415    inner.first_token().is_some_and(|token| {
416        let text = token.text();
417        text == "&" || (text.starts_with('.') && !text.starts_with(".."))
418    })
419}
420
421/// Whether a `function`/`macro` signature's first node is a *bare name* — the
422/// thing being declared rather than a call or other expression. Besides a plain
423/// or `var"…"` identifier and a `$`-interpolation, an operator name counts
424/// (`function + end`, `function .+ end`), including one Julia rejects as a name,
425/// which the parser leaves as an `ERROR`-wrapped operator atom (`function = end`
426/// ⇒ `(function (error =))`).
427pub(super) fn is_bare_signature_name(node: &SyntaxNode) -> bool {
428    match node.kind() {
429        SyntaxKind::NAME
430        | SyntaxKind::NONSTANDARD_IDENTIFIER
431        | SyntaxKind::INTERPOLATION
432        | SyntaxKind::OPERATOR_ATOM => true,
433        SyntaxKind::ERROR => node
434            .first_child()
435            .is_some_and(|inner| inner.kind() == SyntaxKind::OPERATOR_ATOM),
436        _ => false,
437    }
438}
439
440/// Flag each `catch` clause whose variable is not a plain identifier. The catch
441/// variable must be a bare identifier (`catch e`), a `$`-interpolation
442/// (`catch $e`), or a `var"…"` non-standard identifier (`catch var"e"`); any
443/// other expression (`catch e+3`, `catch e.f`, `catch f(e)`, `catch 3`) is
444/// invalid and JuliaSyntax wraps it in `(error …)` (`catch e+3` ⇒ `(catch
445/// (error (call-i e + 3)) …)`). The diagnostic anchors at the catch-variable
446/// node's start.
447fn flag_invalid_catch_vars(cst: &SyntaxNode, diagnostics: &mut Vec<ParseDiagnostic>) {
448    for node in cst
449        .descendants()
450        .filter(|n| n.kind() == SyntaxKind::CATCH_CLAUSE)
451    {
452        let Some(var) = node.children().find(|c| c.kind() != SyntaxKind::BLOCK) else {
453            continue;
454        };
455        if !matches!(
456            var.kind(),
457            SyntaxKind::NAME | SyntaxKind::INTERPOLATION | SyntaxKind::NONSTANDARD_IDENTIFIER
458        ) {
459            let pos = usize::from(var.text_range().start());
460            push_diagnostic(
461                diagnostics,
462                DiagnosticKind::CatchVarNotIdentifier,
463                "catch variable must be an identifier",
464                pos,
465                pos,
466            );
467        }
468    }
469}
470
471/// Whether a `function`/`macro`'s body is syntactically empty — no statement
472/// nodes and no `;` separator opening the block. A bare-name header keeps the
473/// forward-declaration form only while this holds; a `;` (`function f; end`) or
474/// any body statement marks the block as genuinely opened.
475fn function_body_is_empty(node: &SyntaxNode) -> bool {
476    match node.children().find(|c| c.kind() == SyntaxKind::BLOCK) {
477        Some(block) => {
478            block.first_child().is_none()
479                && !block
480                    .children_with_tokens()
481                    .any(|el| el.kind() == SyntaxKind::SEMICOLON)
482        }
483        None => true,
484    }
485}
486
487/// Whether `node` is a `const` field declaration directly inside a struct body
488/// (`struct A const a end` ⇒ `(const a)`, not wrapped). Such a bare `const` is
489/// valid; the exemption is narrow — a `const` nested inside an `if`/`begin`
490/// within the struct (its block's parent is not the `STRUCT_DEF`) is still an
491/// error.
492fn is_struct_const_field(node: &SyntaxNode) -> bool {
493    node.parent()
494        .filter(|b| b.kind() == SyntaxKind::BLOCK)
495        .and_then(|b| b.parent())
496        .is_some_and(|p| p.kind() == SyntaxKind::STRUCT_DEF)
497}
498
499/// Whether a `const`'s declaration is a plain `=` assignment. The body is the
500/// `const`'s first child node, unwrapping any `global`/`local` declaration; it is
501/// valid only when it is an `ASSIGNMENT_EXPR` headed by a plain `=` (not
502/// `.=`/`+=`/…).
503fn const_decl_is_assignment(node: &SyntaxNode) -> bool {
504    let mut body = node.first_child();
505    while let Some(n) = body {
506        match n.kind() {
507            SyntaxKind::GLOBAL_STMT | SyntaxKind::LOCAL_STMT => body = n.first_child(),
508            SyntaxKind::ASSIGNMENT_EXPR => {
509                return n
510                    .children_with_tokens()
511                    .filter_map(|el| el.into_token())
512                    .any(|t| t.kind() == SyntaxKind::EQ);
513            }
514            _ => return false,
515        }
516    }
517    false
518}
519
520/// Whether `kind` is a closing delimiter (`)`, `]`, `}`), which when stray at
521/// statement start drives JuliaSyntax's leading-`(error)` recovery.
522fn is_close_delimiter_tok(kind: TokKind) -> bool {
523    matches!(kind, TokKind::RParen | TokKind::RBracket | TokKind::RBrace)
524}
525
526/// Whether `kind` is a middle/closing block keyword (`end`, `else`, `elseif`,
527/// `catch`, `finally`) — a token that only closes or continues an enclosing
528/// block. Where a statement is expected one of these is stray, so JuliaSyntax
529/// wraps it alone in `(error <kw>)` (`@doc x\nend` ⇒ `(macrocall @doc x) (error
530/// end)`, `end y z` ⇒ `(error end) (error-t y z)`).
531fn is_stray_block_keyword_tok(kind: TokKind) -> bool {
532    matches!(
533        kind,
534        TokKind::EndKw
535            | TokKind::ElseKw
536            | TokKind::ElseifKw
537            | TokKind::CatchKw
538            | TokKind::FinallyKw
539    )
540}
541
542/// Whether the logical line starting at `start` (up to the next newline or EOF)
543/// carries a top-level `;`. The stray-closer recovery only applies to the clean
544/// separator-less form; `;`-segment lines keep the loose-token fallback.
545fn rest_of_line_has_semicolon(tokens: &[Token], start: usize) -> bool {
546    tokens[start..]
547        .iter()
548        .take_while(|t| t.kind != TokKind::Newline)
549        .any(|t| t.kind == TokKind::Semicolon)
550}
551
552/// Whether an event carries significant (non-trivia) content: any node opener,
553/// or a non-trivia leaf token.
554fn is_significant_event(event: &Event, tokens: &[Token]) -> bool {
555    match event {
556        Event::Start(_) => true,
557        Event::Tok(idx) => !tokens[*idx].kind.is_trivia(),
558        Event::Finish => false,
559    }
560}
561
562/// Whether the first significant event in `tail` opens a node (a real statement
563/// subtree). A docstring's trailing leftover defers to `fold_docstrings` only
564/// when it begins with such a subtree (its documentable target); a leftover that
565/// opens with a bare junk token is recovered as trailing junk instead.
566fn leftover_starts_with_subtree(tail: &[Event], tokens: &[Token]) -> bool {
567    matches!(
568        tail.iter().find(|e| is_significant_event(e, tokens)),
569        Some(Event::Start(_))
570    )
571}
572
573/// Whether a statement's events open a bare (doc-eligible) `STRING_LITERAL` —
574/// the first inner token is not a `STRING_PREFIX`. Such a statement starts a
575/// potential docstring, so a trailing statement on the same logical line is left
576/// to `fold_docstrings` rather than wrapped as junk.
577pub(super) fn stmt_is_doc_string(events: &[Event], tokens: &[Token]) -> bool {
578    matches!(
579        events.first(),
580        Some(Event::Start(SyntaxKind::STRING_LITERAL))
581    ) && string_is_doc_eligible(&events[1..], tokens)
582}
583
584/// Whether a node of `kind` is a statement container in which the docstring fold
585/// applies (a string literal statement directly followed by another statement).
586fn is_doc_container(kind: SyntaxKind) -> bool {
587    matches!(kind, SyntaxKind::BLOCK | SyntaxKind::TOPLEVEL_SEMICOLON)
588}
589
590/// Whether a `STRING_LITERAL` subtree is a plain string (doc-eligible) rather
591/// than a prefixed string macro (`r"…"`, `b"…"`), which is a macro call in
592/// JuliaSyntax and never a docstring. Eligible iff its first token is not a
593/// `STRING_PREFIX`.
594fn string_is_doc_eligible(inner: &[Event], tokens: &[Token]) -> bool {
595    match inner.first() {
596        Some(Event::Tok(idx)) => syntax_kind_for(tokens[*idx].kind) != SyntaxKind::STRING_PREFIX,
597        _ => true,
598    }
599}
600
601/// Fold docstrings across the whole event stream. A bare unprefixed
602/// `STRING_LITERAL` statement immediately followed by another statement — at
603/// most one newline of intervening trivia, no `;` — folds into a `DOC` node
604/// `(doc str target)`, mirroring JuliaSyntax's `parse_docstring`. The pass
605/// descends into every subtree so nested blocks (function/module/begin bodies)
606/// fold too.
607///
608/// The fold only ever *inserts* a `Start(DOC)` before the string's `Start` and a
609/// matching `Finish` after the target's `Finish` — every other event keeps its
610/// order and its meaning. So rather than rebuilding the stream level by level,
611/// this marks the two insertion points per fold and splices them in with one
612/// final pass, which keeps the whole thing linear in the event count.
613fn fold_docstrings(events: &[Event], tokens: &[Token]) -> Vec<Event> {
614    let extents = subtree_extents(events);
615    let mut marks = DocMarks {
616        open: vec![false; events.len()],
617        close: vec![false; events.len()],
618        folds: 0,
619    };
620    mark_doc_folds(events, tokens, &extents, 0, events.len(), true, &mut marks);
621
622    if marks.folds == 0 {
623        return events.to_vec();
624    }
625
626    let mut out = Vec::with_capacity(events.len() + 2 * marks.folds);
627    for (i, event) in events.iter().enumerate() {
628        // A fold opens before a `Start` and closes after a `Finish`, so the two
629        // marks can never land on the same event and their order is unambiguous.
630        if marks.open[i] {
631            out.push(Event::Start(SyntaxKind::DOC));
632        }
633        out.push(event.clone());
634        if marks.close[i] {
635            out.push(Event::Finish);
636        }
637    }
638    out
639}
640
641/// Where each fold inserts its `DOC` wrapper: `open[i]` puts a `Start(DOC)`
642/// before event `i`, `close[i]` puts a `Finish` after it.
643struct DocMarks {
644    open: Vec<bool>,
645    close: Vec<bool>,
646    folds: usize,
647}
648
649/// For every `Start` in `events`, the index of its matching `Finish`; `usize::MAX`
650/// for any unmatched opener. One stack pass, so a later walk can skip a whole
651/// subtree in constant time instead of rescanning it for the matching close.
652fn subtree_extents(events: &[Event]) -> Vec<usize> {
653    let mut extents = vec![usize::MAX; events.len()];
654    let mut open: Vec<usize> = Vec::new();
655    for (i, event) in events.iter().enumerate() {
656        match event {
657            Event::Start(_) => open.push(i),
658            Event::Finish => {
659                if let Some(start) = open.pop() {
660                    extents[start] = i;
661                }
662            }
663            Event::Tok(_) => {}
664        }
665    }
666    extents
667}
668
669/// Walk the direct children of the level spanning `start..end`, recording a fold
670/// for each docstring pair and descending into every subtree. `is_container` says
671/// whether a fold may happen at *this* level.
672fn mark_doc_folds(
673    events: &[Event],
674    tokens: &[Token],
675    extents: &[usize],
676    start: usize,
677    end: usize,
678    is_container: bool,
679    marks: &mut DocMarks,
680) {
681    let mut i = start;
682    while i < end {
683        let Event::Start(kind) = events[i] else {
684            i += 1;
685            continue;
686        };
687        // An unmatched opener runs to the end of this level.
688        let stop = extents[i].min(end);
689        mark_doc_folds(
690            events,
691            tokens,
692            extents,
693            i + 1,
694            stop,
695            is_doc_container(kind),
696            marks,
697        );
698
699        if is_container
700            && kind == SyntaxKind::STRING_LITERAL
701            && string_is_doc_eligible(&events[i + 1..stop], tokens)
702            && let Some(target) = doc_target(events, tokens, stop + 1, end)
703        {
704            let target_end = extents[target].min(end);
705            // The target is consumed by this fold: it is documented *by* the
706            // string, so it never goes on to document what follows it. Descend
707            // into it here, then resume past it.
708            mark_doc_folds(
709                events,
710                tokens,
711                extents,
712                target + 1,
713                target_end,
714                is_doc_container(as_start_kind(&events[target])),
715                marks,
716            );
717            marks.open[i] = true;
718            marks.close[target_end] = true;
719            marks.folds += 1;
720            i = target_end + 1;
721            continue;
722        }
723        i = stop + 1;
724    }
725}
726
727/// The kind of a `Start` event. Only ever called on an event already matched as
728/// one, so the fallback kind is unreachable.
729fn as_start_kind(event: &Event) -> SyntaxKind {
730    match event {
731        Event::Start(kind) => *kind,
732        _ => SyntaxKind::ERROR,
733    }
734}
735
736/// Scanning forward from `from` within a level ending at `end`, the index of the
737/// `Start` of the statement a preceding docstring documents: the next subtree
738/// child, reachable across at most one newline of trivia and no `;`. `None` if no
739/// eligible target follows.
740fn doc_target(events: &[Event], tokens: &[Token], from: usize, end: usize) -> Option<usize> {
741    let mut newlines = 0;
742    let mut j = from;
743    while j < end {
744        match events[j] {
745            // An error-recovery node is never a documentable target (`"doc"\n]`
746            // ⇒ `(string) (error) (error-t ✘)`, not a `(doc …)`); the string is
747            // a plain statement.
748            Event::Start(SyntaxKind::ERROR) => return None,
749            Event::Start(_) => return Some(j),
750            Event::Tok(t) => {
751                let kind = tokens[t].kind;
752                if kind == TokKind::Newline {
753                    newlines += 1;
754                    if newlines > 1 {
755                        return None;
756                    }
757                } else if !kind.is_trivia() {
758                    return None;
759                }
760                j += 1;
761            }
762            // Only reachable on an unbalanced stream, where it ends the level.
763            Event::Finish => return None,
764        }
765    }
766    None
767}
768
769/// Round-trip the input through the parser: concatenating every token in the CST
770/// must reproduce the original text exactly (the losslessness invariant).
771pub fn reconstruct(text: &str) -> String {
772    parse(text)
773        .cst
774        .descendants_with_tokens()
775        .filter_map(|el| el.into_token())
776        .map(|tok| tok.text().to_string())
777        .collect()
778}
779
780#[cfg(test)]
781mod tests {
782    use super::*;
783
784    fn assert_lossless(input: &str) {
785        assert_eq!(reconstruct(input), input, "not lossless: {input:?}");
786    }
787
788    #[test]
789    fn lossless_corpus() {
790        for input in [
791            "",
792            "x = 1\n",
793            "y = a + b * c\n",
794            "f(a, b, c)\n",
795            "v[1]\n",
796            "a[end]\n",
797            "a[end - 1]\n",
798            "a[2:end]\n",
799            "m[end, end]\n",
800            "z = (a + b) / 2\n",
801            "function g(x)\n    x ^ 2\nend\n",
802            "if a >= b\n    a\nelseif c\n    c\nelse\n    b\nend\n",
803            "begin\n    a\n    b\nend\n",
804            "map(xs) do x\n    x + 1\nend\n",
805            "open(\"f\") do\n    read()\nend\n",
806            "# a comment\nx = 1  # trailing\n",
807            "#= block =#\nq = 2\n",
808            "obj.field\n",
809            "x::Int\n",
810            "Vector{T}\n",
811            "foo(x::T) where {T<:Number} = x\n",
812            "f(a, b; c=1, d=2)\n",
813            "g(args...; kwargs...)\n",
814            "y = a .+ b .* c\n",
815            "z = .-x\n",
816            "a .= f.(b, c)\n",
817            "t = (a, b)\n",
818            "u = (a,)\n",
819            "e = ()\n",
820            "nt = (x = 1, y = 2)\n",
821            "y = a ? b : c\n",
822            "z = a == b ? x + 1 : x - 1\n",
823            "w = a ? b : c ? d : e\n",
824            "v = [1, 2, 3]\n",
825            "e = []\n",
826            "m = [1 2; 3 4]\n",
827            "s = [1 +2]\n",
828            "c = [1; 2; 3]\n",
829            "q = [x for x in xs]\n",
830            "r = [x^2 for x in 1:10 if x > 2]\n",
831            "g = (x for x in xs)\n",
832            "a; b\n",
833            "a;;;b;;\n",
834            ";a\n",
835            "@assert nl > 1  # trailing comment\nnx = 2\n",
836            "@foo x  # c\n",
837            "x = @bind 🐶 html\"<input>\"\n",
838            "begin @m 10 end\n",
839        ] {
840            assert_lossless(input);
841        }
842    }
843
844    #[test]
845    fn groups_top_level_semicolon_line() {
846        let out = parse("a; b\nc\n");
847        let kinds: Vec<_> = out.cst.children().map(|n| n.kind()).collect();
848        use crate::syntax::SyntaxKind::{NAME, TOPLEVEL_SEMICOLON};
849        assert_eq!(kinds, vec![TOPLEVEL_SEMICOLON, NAME]);
850    }
851
852    #[test]
853    fn builds_expected_top_level_shape() {
854        let out = parse("x = 1 + 2\n");
855        let kinds: Vec<_> = out.cst.children().map(|n| n.kind()).collect();
856        assert_eq!(kinds, vec![crate::syntax::SyntaxKind::ASSIGNMENT_EXPR]);
857        assert!(out.diagnostics.is_empty());
858    }
859}