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 `function`/`macro` whose signature is a bare identifier name but
335/// which carries a non-empty body. A header like `function f end` (a bare name
336/// with a truly empty body) is the valid forward-declaration form `(function f)`,
337/// but once a body is present (`function f body end`) or the body block is
338/// explicitly opened with a `;` (`function f; end`), the bare name is no longer a
339/// valid signature: JuliaSyntax error-wraps it (`(function (error f) (block
340/// body))`). The diagnostic anchors at the `SIGNATURE` node's start.
341fn flag_invalid_function_signatures(cst: &SyntaxNode, diagnostics: &mut Vec<ParseDiagnostic>) {
342 for node in cst
343 .descendants()
344 .filter(|n| matches!(n.kind(), SyntaxKind::FUNCTION_DEF | SyntaxKind::MACRO_DEF))
345 {
346 let Some(sig) = node.children().find(|c| c.kind() == SyntaxKind::SIGNATURE) else {
347 continue;
348 };
349 let sig_is_bare_name = sig
350 .first_child()
351 .is_some_and(|inner| is_bare_signature_name(&inner));
352 if sig_is_bare_name && !function_body_is_empty(&node) {
353 let pos = usize::from(sig.text_range().start());
354 push_diagnostic(
355 diagnostics,
356 DiagnosticKind::InvalidFunctionSignature,
357 "invalid function signature: expected a call, not a bare name",
358 pos,
359 pos,
360 );
361 }
362 }
363}
364
365/// Whether a `function`/`macro` signature's first node is a *bare name* — the
366/// thing being declared rather than a call or other expression. Besides a plain
367/// identifier and a `$`-interpolation, an operator name counts (`function + end`,
368/// `function .+ end`), including one Julia rejects as a name, which the parser
369/// leaves as an `ERROR`-wrapped operator atom (`function = end` ⇒
370/// `(function (error =))`).
371pub(super) fn is_bare_signature_name(node: &SyntaxNode) -> bool {
372 match node.kind() {
373 SyntaxKind::NAME | SyntaxKind::INTERPOLATION | SyntaxKind::OPERATOR_ATOM => true,
374 SyntaxKind::ERROR => node
375 .first_child()
376 .is_some_and(|inner| inner.kind() == SyntaxKind::OPERATOR_ATOM),
377 _ => false,
378 }
379}
380
381/// Flag each `catch` clause whose variable is not a plain identifier. The catch
382/// variable must be a bare identifier (`catch e`), a `$`-interpolation
383/// (`catch $e`), or a `var"…"` non-standard identifier (`catch var"e"`); any
384/// other expression (`catch e+3`, `catch e.f`, `catch f(e)`, `catch 3`) is
385/// invalid and JuliaSyntax wraps it in `(error …)` (`catch e+3` ⇒ `(catch
386/// (error (call-i e + 3)) …)`). The diagnostic anchors at the catch-variable
387/// node's start.
388fn flag_invalid_catch_vars(cst: &SyntaxNode, diagnostics: &mut Vec<ParseDiagnostic>) {
389 for node in cst
390 .descendants()
391 .filter(|n| n.kind() == SyntaxKind::CATCH_CLAUSE)
392 {
393 let Some(var) = node.children().find(|c| c.kind() != SyntaxKind::BLOCK) else {
394 continue;
395 };
396 if !matches!(
397 var.kind(),
398 SyntaxKind::NAME | SyntaxKind::INTERPOLATION | SyntaxKind::NONSTANDARD_IDENTIFIER
399 ) {
400 let pos = usize::from(var.text_range().start());
401 push_diagnostic(
402 diagnostics,
403 DiagnosticKind::CatchVarNotIdentifier,
404 "catch variable must be an identifier",
405 pos,
406 pos,
407 );
408 }
409 }
410}
411
412/// Whether a `function`/`macro`'s body is syntactically empty — no statement
413/// nodes and no `;` separator opening the block. A bare-name header keeps the
414/// forward-declaration form only while this holds; a `;` (`function f; end`) or
415/// any body statement marks the block as genuinely opened.
416fn function_body_is_empty(node: &SyntaxNode) -> bool {
417 match node.children().find(|c| c.kind() == SyntaxKind::BLOCK) {
418 Some(block) => {
419 block.first_child().is_none()
420 && !block
421 .children_with_tokens()
422 .any(|el| el.kind() == SyntaxKind::SEMICOLON)
423 }
424 None => true,
425 }
426}
427
428/// Whether `node` is a `const` field declaration directly inside a struct body
429/// (`struct A const a end` ⇒ `(const a)`, not wrapped). Such a bare `const` is
430/// valid; the exemption is narrow — a `const` nested inside an `if`/`begin`
431/// within the struct (its block's parent is not the `STRUCT_DEF`) is still an
432/// error.
433fn is_struct_const_field(node: &SyntaxNode) -> bool {
434 node.parent()
435 .filter(|b| b.kind() == SyntaxKind::BLOCK)
436 .and_then(|b| b.parent())
437 .is_some_and(|p| p.kind() == SyntaxKind::STRUCT_DEF)
438}
439
440/// Whether a `const`'s declaration is a plain `=` assignment. The body is the
441/// `const`'s first child node, unwrapping any `global`/`local` declaration; it is
442/// valid only when it is an `ASSIGNMENT_EXPR` headed by a plain `=` (not
443/// `.=`/`+=`/…).
444fn const_decl_is_assignment(node: &SyntaxNode) -> bool {
445 let mut body = node.first_child();
446 while let Some(n) = body {
447 match n.kind() {
448 SyntaxKind::GLOBAL_STMT | SyntaxKind::LOCAL_STMT => body = n.first_child(),
449 SyntaxKind::ASSIGNMENT_EXPR => {
450 return n
451 .children_with_tokens()
452 .filter_map(|el| el.into_token())
453 .any(|t| t.kind() == SyntaxKind::EQ);
454 }
455 _ => return false,
456 }
457 }
458 false
459}
460
461/// Whether `kind` is a closing delimiter (`)`, `]`, `}`), which when stray at
462/// statement start drives JuliaSyntax's leading-`(error)` recovery.
463fn is_close_delimiter_tok(kind: TokKind) -> bool {
464 matches!(kind, TokKind::RParen | TokKind::RBracket | TokKind::RBrace)
465}
466
467/// Whether `kind` is a middle/closing block keyword (`end`, `else`, `elseif`,
468/// `catch`, `finally`) — a token that only closes or continues an enclosing
469/// block. Where a statement is expected one of these is stray, so JuliaSyntax
470/// wraps it alone in `(error <kw>)` (`@doc x\nend` ⇒ `(macrocall @doc x) (error
471/// end)`, `end y z` ⇒ `(error end) (error-t y z)`).
472fn is_stray_block_keyword_tok(kind: TokKind) -> bool {
473 matches!(
474 kind,
475 TokKind::EndKw
476 | TokKind::ElseKw
477 | TokKind::ElseifKw
478 | TokKind::CatchKw
479 | TokKind::FinallyKw
480 )
481}
482
483/// Whether the logical line starting at `start` (up to the next newline or EOF)
484/// carries a top-level `;`. The stray-closer recovery only applies to the clean
485/// separator-less form; `;`-segment lines keep the loose-token fallback.
486fn rest_of_line_has_semicolon(tokens: &[Token], start: usize) -> bool {
487 tokens[start..]
488 .iter()
489 .take_while(|t| t.kind != TokKind::Newline)
490 .any(|t| t.kind == TokKind::Semicolon)
491}
492
493/// Whether an event carries significant (non-trivia) content: any node opener,
494/// or a non-trivia leaf token.
495fn is_significant_event(event: &Event, tokens: &[Token]) -> bool {
496 match event {
497 Event::Start(_) => true,
498 Event::Tok(idx) => !tokens[*idx].kind.is_trivia(),
499 Event::Finish => false,
500 }
501}
502
503/// Whether the first significant event in `tail` opens a node (a real statement
504/// subtree). A docstring's trailing leftover defers to `fold_docstrings` only
505/// when it begins with such a subtree (its documentable target); a leftover that
506/// opens with a bare junk token is recovered as trailing junk instead.
507fn leftover_starts_with_subtree(tail: &[Event], tokens: &[Token]) -> bool {
508 matches!(
509 tail.iter().find(|e| is_significant_event(e, tokens)),
510 Some(Event::Start(_))
511 )
512}
513
514/// Whether a statement's events open a bare (doc-eligible) `STRING_LITERAL` —
515/// the first inner token is not a `STRING_PREFIX`. Such a statement starts a
516/// potential docstring, so a trailing statement on the same logical line is left
517/// to `fold_docstrings` rather than wrapped as junk.
518pub(super) fn stmt_is_doc_string(events: &[Event], tokens: &[Token]) -> bool {
519 matches!(
520 events.first(),
521 Some(Event::Start(SyntaxKind::STRING_LITERAL))
522 ) && string_is_doc_eligible(&events[1..], tokens)
523}
524
525/// Whether a node of `kind` is a statement container in which the docstring fold
526/// applies (a string literal statement directly followed by another statement).
527fn is_doc_container(kind: SyntaxKind) -> bool {
528 matches!(kind, SyntaxKind::BLOCK | SyntaxKind::TOPLEVEL_SEMICOLON)
529}
530
531/// Whether a `STRING_LITERAL` subtree is a plain string (doc-eligible) rather
532/// than a prefixed string macro (`r"…"`, `b"…"`), which is a macro call in
533/// JuliaSyntax and never a docstring. Eligible iff its first token is not a
534/// `STRING_PREFIX`.
535fn string_is_doc_eligible(inner: &[Event], tokens: &[Token]) -> bool {
536 match inner.first() {
537 Some(Event::Tok(idx)) => syntax_kind_for(tokens[*idx].kind) != SyntaxKind::STRING_PREFIX,
538 _ => true,
539 }
540}
541
542/// Fold docstrings across the whole event stream. A bare unprefixed
543/// `STRING_LITERAL` statement immediately followed by another statement — at
544/// most one newline of intervening trivia, no `;` — folds into a `DOC` node
545/// `(doc str target)`, mirroring JuliaSyntax's `parse_docstring`. The pass
546/// descends into every subtree so nested blocks (function/module/begin bodies)
547/// fold too.
548///
549/// The fold only ever *inserts* a `Start(DOC)` before the string's `Start` and a
550/// matching `Finish` after the target's `Finish` — every other event keeps its
551/// order and its meaning. So rather than rebuilding the stream level by level,
552/// this marks the two insertion points per fold and splices them in with one
553/// final pass, which keeps the whole thing linear in the event count.
554fn fold_docstrings(events: &[Event], tokens: &[Token]) -> Vec<Event> {
555 let extents = subtree_extents(events);
556 let mut marks = DocMarks {
557 open: vec![false; events.len()],
558 close: vec![false; events.len()],
559 folds: 0,
560 };
561 mark_doc_folds(events, tokens, &extents, 0, events.len(), true, &mut marks);
562
563 if marks.folds == 0 {
564 return events.to_vec();
565 }
566
567 let mut out = Vec::with_capacity(events.len() + 2 * marks.folds);
568 for (i, event) in events.iter().enumerate() {
569 // A fold opens before a `Start` and closes after a `Finish`, so the two
570 // marks can never land on the same event and their order is unambiguous.
571 if marks.open[i] {
572 out.push(Event::Start(SyntaxKind::DOC));
573 }
574 out.push(event.clone());
575 if marks.close[i] {
576 out.push(Event::Finish);
577 }
578 }
579 out
580}
581
582/// Where each fold inserts its `DOC` wrapper: `open[i]` puts a `Start(DOC)`
583/// before event `i`, `close[i]` puts a `Finish` after it.
584struct DocMarks {
585 open: Vec<bool>,
586 close: Vec<bool>,
587 folds: usize,
588}
589
590/// For every `Start` in `events`, the index of its matching `Finish`; `usize::MAX`
591/// for any unmatched opener. One stack pass, so a later walk can skip a whole
592/// subtree in constant time instead of rescanning it for the matching close.
593fn subtree_extents(events: &[Event]) -> Vec<usize> {
594 let mut extents = vec![usize::MAX; events.len()];
595 let mut open: Vec<usize> = Vec::new();
596 for (i, event) in events.iter().enumerate() {
597 match event {
598 Event::Start(_) => open.push(i),
599 Event::Finish => {
600 if let Some(start) = open.pop() {
601 extents[start] = i;
602 }
603 }
604 Event::Tok(_) => {}
605 }
606 }
607 extents
608}
609
610/// Walk the direct children of the level spanning `start..end`, recording a fold
611/// for each docstring pair and descending into every subtree. `is_container` says
612/// whether a fold may happen at *this* level.
613fn mark_doc_folds(
614 events: &[Event],
615 tokens: &[Token],
616 extents: &[usize],
617 start: usize,
618 end: usize,
619 is_container: bool,
620 marks: &mut DocMarks,
621) {
622 let mut i = start;
623 while i < end {
624 let Event::Start(kind) = events[i] else {
625 i += 1;
626 continue;
627 };
628 // An unmatched opener runs to the end of this level.
629 let stop = extents[i].min(end);
630 mark_doc_folds(
631 events,
632 tokens,
633 extents,
634 i + 1,
635 stop,
636 is_doc_container(kind),
637 marks,
638 );
639
640 if is_container
641 && kind == SyntaxKind::STRING_LITERAL
642 && string_is_doc_eligible(&events[i + 1..stop], tokens)
643 && let Some(target) = doc_target(events, tokens, stop + 1, end)
644 {
645 let target_end = extents[target].min(end);
646 // The target is consumed by this fold: it is documented *by* the
647 // string, so it never goes on to document what follows it. Descend
648 // into it here, then resume past it.
649 mark_doc_folds(
650 events,
651 tokens,
652 extents,
653 target + 1,
654 target_end,
655 is_doc_container(as_start_kind(&events[target])),
656 marks,
657 );
658 marks.open[i] = true;
659 marks.close[target_end] = true;
660 marks.folds += 1;
661 i = target_end + 1;
662 continue;
663 }
664 i = stop + 1;
665 }
666}
667
668/// The kind of a `Start` event. Only ever called on an event already matched as
669/// one, so the fallback kind is unreachable.
670fn as_start_kind(event: &Event) -> SyntaxKind {
671 match event {
672 Event::Start(kind) => *kind,
673 _ => SyntaxKind::ERROR,
674 }
675}
676
677/// Scanning forward from `from` within a level ending at `end`, the index of the
678/// `Start` of the statement a preceding docstring documents: the next subtree
679/// child, reachable across at most one newline of trivia and no `;`. `None` if no
680/// eligible target follows.
681fn doc_target(events: &[Event], tokens: &[Token], from: usize, end: usize) -> Option<usize> {
682 let mut newlines = 0;
683 let mut j = from;
684 while j < end {
685 match events[j] {
686 // An error-recovery node is never a documentable target (`"doc"\n]`
687 // ⇒ `(string) (error) (error-t ✘)`, not a `(doc …)`); the string is
688 // a plain statement.
689 Event::Start(SyntaxKind::ERROR) => return None,
690 Event::Start(_) => return Some(j),
691 Event::Tok(t) => {
692 let kind = tokens[t].kind;
693 if kind == TokKind::Newline {
694 newlines += 1;
695 if newlines > 1 {
696 return None;
697 }
698 } else if !kind.is_trivia() {
699 return None;
700 }
701 j += 1;
702 }
703 // Only reachable on an unbalanced stream, where it ends the level.
704 Event::Finish => return None,
705 }
706 }
707 None
708}
709
710/// Round-trip the input through the parser: concatenating every token in the CST
711/// must reproduce the original text exactly (the losslessness invariant).
712pub fn reconstruct(text: &str) -> String {
713 parse(text)
714 .cst
715 .descendants_with_tokens()
716 .filter_map(|el| el.into_token())
717 .map(|tok| tok.text().to_string())
718 .collect()
719}
720
721#[cfg(test)]
722mod tests {
723 use super::*;
724
725 fn assert_lossless(input: &str) {
726 assert_eq!(reconstruct(input), input, "not lossless: {input:?}");
727 }
728
729 #[test]
730 fn lossless_corpus() {
731 for input in [
732 "",
733 "x = 1\n",
734 "y = a + b * c\n",
735 "f(a, b, c)\n",
736 "v[1]\n",
737 "a[end]\n",
738 "a[end - 1]\n",
739 "a[2:end]\n",
740 "m[end, end]\n",
741 "z = (a + b) / 2\n",
742 "function g(x)\n x ^ 2\nend\n",
743 "if a >= b\n a\nelseif c\n c\nelse\n b\nend\n",
744 "begin\n a\n b\nend\n",
745 "map(xs) do x\n x + 1\nend\n",
746 "open(\"f\") do\n read()\nend\n",
747 "# a comment\nx = 1 # trailing\n",
748 "#= block =#\nq = 2\n",
749 "obj.field\n",
750 "x::Int\n",
751 "Vector{T}\n",
752 "foo(x::T) where {T<:Number} = x\n",
753 "f(a, b; c=1, d=2)\n",
754 "g(args...; kwargs...)\n",
755 "y = a .+ b .* c\n",
756 "z = .-x\n",
757 "a .= f.(b, c)\n",
758 "t = (a, b)\n",
759 "u = (a,)\n",
760 "e = ()\n",
761 "nt = (x = 1, y = 2)\n",
762 "y = a ? b : c\n",
763 "z = a == b ? x + 1 : x - 1\n",
764 "w = a ? b : c ? d : e\n",
765 "v = [1, 2, 3]\n",
766 "e = []\n",
767 "m = [1 2; 3 4]\n",
768 "s = [1 +2]\n",
769 "c = [1; 2; 3]\n",
770 "q = [x for x in xs]\n",
771 "r = [x^2 for x in 1:10 if x > 2]\n",
772 "g = (x for x in xs)\n",
773 "a; b\n",
774 "a;;;b;;\n",
775 ";a\n",
776 "@assert nl > 1 # trailing comment\nnx = 2\n",
777 "@foo x # c\n",
778 "x = @bind 🐶 html\"<input>\"\n",
779 "begin @m 10 end\n",
780 ] {
781 assert_lossless(input);
782 }
783 }
784
785 #[test]
786 fn groups_top_level_semicolon_line() {
787 let out = parse("a; b\nc\n");
788 let kinds: Vec<_> = out.cst.children().map(|n| n.kind()).collect();
789 use crate::syntax::SyntaxKind::{NAME, TOPLEVEL_SEMICOLON};
790 assert_eq!(kinds, vec![TOPLEVEL_SEMICOLON, NAME]);
791 }
792
793 #[test]
794 fn builds_expected_top_level_shape() {
795 let out = parse("x = 1 + 2\n");
796 let kinds: Vec<_> = out.cst.children().map(|n| n.kind()).collect();
797 assert_eq!(kinds, vec![crate::syntax::SyntaxKind::ASSIGNMENT_EXPR]);
798 assert!(out.diagnostics.is_empty());
799 }
800}