fatou-parser 0.10.0

Lossless CST parser, typed AST wrappers, and incremental reparser for the Julia language
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! Typed documentation attachments and statically recoverable textual payloads.
//!
//! Julia's `@doc` accepts arbitrary metadata. This module therefore recognizes
//! attachment shape independently from content and decodes only standard
//! ordinary or `raw` string literals whose value is statically knowable.

use rowan::ast::AstNode as _;
use rowan::{TextRange, TextSize};

use super::{Doc, MacroCall, StringLiteral};
use crate::parser::StringDecodeError;
use crate::syntax::{SyntaxKind, SyntaxNode};

/// Whether documentation used Julia's adjacent-string sugar or an explicit
/// two-argument `@doc` macro call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DocAttachmentKind {
    Juxtaposed,
    Macro,
}

/// A documentable expression or statement.
///
/// Julia permits unrelated syntax kinds here, so this wrapper exposes the
/// lossless node without claiming that every target is an [`Expr`](super::Expr).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DocTarget(SyntaxNode);

impl DocTarget {
    pub(crate) fn new(syntax: SyntaxNode) -> Self {
        Self(syntax)
    }

    /// Return the lossless syntax node for the documented target.
    pub fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

/// A documentation payload and the syntax it documents.
///
/// This is deliberately not an [`AstNode`](rowan::ast::AstNode): it unifies a
/// `DOC` node with qualified or unqualified spellings of a two-argument `@doc`
/// `MACRO_CALL`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocAttachment {
    syntax: SyntaxNode,
    payload: SyntaxNode,
    target: SyntaxNode,
    kind: DocAttachmentKind,
}

impl DocAttachment {
    /// Recognize an adjacent docstring or exactly two arguments to a macro whose
    /// final identifier is `doc` (`@doc`, `Base.@doc`, or `@Base.doc`).
    pub fn cast(syntax: SyntaxNode) -> Option<Self> {
        if let Some(doc) = Doc::cast(syntax.clone()) {
            return Some(Self {
                payload: doc.literal()?.syntax().clone(),
                target: doc.target()?.syntax().clone(),
                syntax,
                kind: DocAttachmentKind::Juxtaposed,
            });
        }

        let call = MacroCall::cast(syntax.clone())?;
        let name = call.name()?;
        if name.macro_token()?.text() != "doc" {
            return None;
        }
        let args = macro_args(call.syntax());
        let [payload, target] = args.as_slice() else {
            return None;
        };
        Some(Self {
            syntax,
            payload: payload.clone(),
            target: target.clone(),
            kind: DocAttachmentKind::Macro,
        })
    }

    /// Return the complete attachment node.
    pub fn syntax(&self) -> &SyntaxNode {
        &self.syntax
    }

    /// Return the metadata expression passed as documentation.
    pub fn payload(&self) -> &SyntaxNode {
        &self.payload
    }

    /// Return the expression or statement that receives the documentation.
    pub fn target(&self) -> &SyntaxNode {
        &self.target
    }

    /// Return the Julia syntax form used for the attachment.
    pub fn kind(&self) -> DocAttachmentKind {
        self.kind
    }

    /// Recover textual documentation when Julia's value is statically known.
    pub fn text(&self) -> DocText {
        let Some(literal) = StringLiteral::cast(self.payload.clone()) else {
            return DocText::Opaque(OpaqueDocReason::NonString);
        };
        decode_literal(&literal)
    }
}

/// Why a documentation payload cannot be interpreted statically.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpaqueDocReason {
    /// The payload is not a string literal.
    NonString,
    /// The string literal contains interpolation.
    Interpolation,
    /// The string macro is not Julia's standard `raw` string.
    UnsupportedPrefix,
    /// The literal has a suffix, so a string macro controls its meaning.
    UnsupportedSuffix,
}

/// The statically knowable status of a documentation payload.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DocText {
    /// The exact documentation value is statically recoverable.
    Static(StaticDocText),
    /// Julia syntax permits the payload, but its value requires evaluation or
    /// string-macro semantics.
    Opaque(OpaqueDocReason),
    /// A standard string literal contains an invalid escape or byte sequence.
    Invalid(StringDecodeError),
}

/// Decoded documentation text and its mapping back to Julia source bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StaticDocText {
    text: String,
    source_map: DocSourceMap,
}

impl StaticDocText {
    /// Return the decoded documentation value.
    pub fn as_str(&self) -> &str {
        &self.text
    }

    /// Return the mapping from decoded bytes to Julia source bytes.
    pub fn source_map(&self) -> &DocSourceMap {
        &self.source_map
    }
}

/// An exact byte-span map from decoded documentation to the string literal.
///
/// The map is stored as runs rather than one span per decoded byte: a
/// docstring is overwhelmingly literal text whose spans advance one source
/// byte at a time, so the common case is a single run. Size matters because a
/// whole file's maps live in the semantic model, which salsa caches and
/// compares for backdating.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocSourceMap {
    runs: Vec<SourceRun>,
    len: u32,
    empty_at: TextSize,
}

impl DocSourceMap {
    /// Map a decoded UTF-8 byte range to its enclosing absolute source range.
    /// Returns `None` for an out-of-bounds range.
    pub fn source_range(&self, range: TextRange) -> Option<TextRange> {
        let start = u32::from(range.start());
        let end = u32::from(range.end());
        if start > end || end > self.len {
            return None;
        }
        if start == end {
            let at = self
                .span(start)
                .map(|span| span.start)
                .or_else(|| self.runs.last().map(|run| run.span(run.len - 1).end))
                .unwrap_or(self.empty_at);
            return Some(TextRange::new(at, at));
        }
        Some(TextRange::new(
            self.span(start)?.start,
            self.span(end - 1)?.end,
        ))
    }

    /// Map an absolute Julia source offset into the decoded documentation.
    ///
    /// A cursor anywhere inside an escape maps to the first decoded byte that
    /// escape produced. Bytes removed by triple-string dedenting or a line
    /// continuation have no decoded position and return `None`.
    pub fn decoded_offset(&self, offset: TextSize) -> Option<TextSize> {
        let Some(last) = self.runs.last() else {
            return (offset == self.empty_at).then_some(TextSize::new(0));
        };
        if offset == last.span(last.len - 1).end {
            return Some(TextSize::new(self.len));
        }
        // Runs cover the source in increasing order, so the one that could
        // contain `offset` is the last starting at or before it. Dedented and
        // continued bytes fall in the gaps between runs.
        let index = self
            .runs
            .partition_point(|run| run.source_start <= offset)
            .checked_sub(1)?;
        let run = &self.runs[index];
        let step = run.step(offset)?;
        // Several decoded bytes can share one span (a multi-byte `\u` escape);
        // the cursor belongs to the first of them.
        let first = if run.stride == 0 { 0 } else { step };
        Some(TextSize::new(run.decoded_start + first))
    }

    /// The span of one decoded byte, or `None` past the end of the map.
    fn span(&self, decoded: u32) -> Option<SourceSpan> {
        let index = self
            .runs
            .partition_point(|run| run.decoded_start <= decoded)
            .checked_sub(1)?;
        let run = &self.runs[index];
        (decoded - run.decoded_start < run.len).then(|| run.span(decoded - run.decoded_start))
    }
}

/// A maximal span sequence advancing by a fixed source stride.
///
/// `stride` is zero when every decoded byte in the run shares one source span,
/// one for ordinary literal text, and larger for a run of same-width escapes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct SourceRun {
    decoded_start: u32,
    len: u32,
    source_start: TextSize,
    stride: u32,
    width: u32,
}

impl SourceRun {
    fn span(&self, step: u32) -> SourceSpan {
        let start = u32::from(self.source_start) + step * self.stride;
        SourceSpan {
            start: TextSize::new(start),
            end: TextSize::new(start + self.width),
        }
    }

    /// The step within this run whose span contains `offset`.
    fn step(&self, offset: TextSize) -> Option<u32> {
        let relative = u32::from(offset).checked_sub(u32::from(self.source_start))?;
        let step = relative
            .checked_div(self.stride)
            .map_or(0, |step| step.min(self.len - 1));
        let span = self.span(step);
        (span.start <= offset && offset < span.end).then_some(step)
    }

    /// Extend the run with `span` when it continues the same stride and width.
    fn extend(&mut self, span: SourceSpan) -> bool {
        if u32::from(span.end) - u32::from(span.start) != self.width {
            return false;
        }
        if self.len == 1 {
            // A one-byte run has no stride yet, so any successor defines it.
            let Some(stride) = u32::from(span.start).checked_sub(u32::from(self.source_start))
            else {
                return false;
            };
            self.stride = stride;
            self.len += 1;
            return true;
        }
        if span.start != self.span(self.len).start {
            return false;
        }
        self.len += 1;
        true
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct SourceSpan {
    start: TextSize,
    end: TextSize,
}

/// Compress a per-decoded-byte span vector into runs.
fn compress(bytes: &[SourceSpan]) -> Vec<SourceRun> {
    let mut runs: Vec<SourceRun> = Vec::new();
    for (index, span) in bytes.iter().enumerate() {
        if let Some(run) = runs.last_mut()
            && run.extend(*span)
        {
            continue;
        }
        runs.push(SourceRun {
            decoded_start: index as u32,
            len: 1,
            source_start: span.start,
            stride: 1,
            width: u32::from(span.end) - u32::from(span.start),
        });
    }
    runs
}

#[derive(Clone)]
struct MappedText {
    text: String,
    bytes: Vec<SourceSpan>,
    empty_at: TextSize,
}

impl MappedText {
    fn from_literal(literal: &StringLiteral) -> Self {
        let empty_at = literal
            .syntax()
            .children_with_tokens()
            .filter_map(|element| element.into_token())
            .find(|token| token.kind() == SyntaxKind::STRING_DELIM_OPEN)
            .map(|token| token.text_range().end())
            .unwrap_or_else(|| literal.syntax().text_range().start());
        let mut out = Self {
            text: String::new(),
            bytes: Vec::new(),
            empty_at,
        };
        for token in literal.content_tokens() {
            let base: u32 = token.text_range().start().into();
            out.text.push_str(token.text());
            for i in 0..token.text().len() as u32 {
                out.bytes.push(SourceSpan {
                    start: TextSize::from(base + i),
                    end: TextSize::from(base + i + 1),
                });
            }
        }
        out
    }

    fn push_slice(&mut self, source: &Self, range: std::ops::Range<usize>) {
        self.text.push_str(&source.text[range.clone()]);
        self.bytes.extend_from_slice(&source.bytes[range]);
    }

    fn into_static(self) -> StaticDocText {
        StaticDocText {
            text: self.text,
            source_map: DocSourceMap {
                runs: compress(&self.bytes),
                len: self.bytes.len() as u32,
                empty_at: self.empty_at,
            },
        }
    }
}

fn macro_args(node: &SyntaxNode) -> Vec<SyntaxNode> {
    let mut out = Vec::new();
    for child in node.children() {
        match child.kind() {
            SyntaxKind::MACRO_NAME => {}
            SyntaxKind::ARG_LIST => {
                for arg in child.children() {
                    if arg.kind() == SyntaxKind::ARG {
                        out.extend(arg.children());
                    } else {
                        out.push(arg);
                    }
                }
            }
            _ => out.push(child),
        }
    }
    out
}

fn decode_literal(literal: &StringLiteral) -> DocText {
    if literal.interpolations().next().is_some() {
        return DocText::Opaque(OpaqueDocReason::Interpolation);
    }
    if literal.suffix().is_some() {
        return DocText::Opaque(OpaqueDocReason::UnsupportedSuffix);
    }
    let raw = match literal.prefix().as_ref().map(|token| token.text()) {
        None => false,
        Some("raw") => true,
        Some(_) => return DocText::Opaque(OpaqueDocReason::UnsupportedPrefix),
    };
    let triple = literal
        .syntax()
        .children_with_tokens()
        .filter_map(|element| element.into_token())
        .find(|token| token.kind() == SyntaxKind::STRING_DELIM_OPEN)
        .is_some_and(|token| token.text().len() >= 3);

    let mut mapped = MappedText::from_literal(literal);
    if raw {
        mapped = decode_raw(mapped);
    }
    if triple {
        mapped = dedent_triple(normalize_newlines(mapped));
    }
    if !raw {
        mapped = match decode_escapes(mapped) {
            Ok(mapped) => mapped,
            Err(err) => return DocText::Invalid(err),
        };
    }
    DocText::Static(mapped.into_static())
}

fn normalize_newlines(input: MappedText) -> MappedText {
    let bytes = input.text.as_bytes();
    let mut out = MappedText {
        text: String::new(),
        bytes: Vec::new(),
        empty_at: input.empty_at,
    };
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'\r' {
            let end = if bytes.get(i + 1) == Some(&b'\n') {
                i + 2
            } else {
                i + 1
            };
            out.text.push('\n');
            out.bytes.push(SourceSpan {
                start: input.bytes[i].start,
                end: input.bytes[end - 1].end,
            });
            i = end;
        } else {
            let len = input.text[i..].chars().next().unwrap().len_utf8();
            out.push_slice(&input, i..i + len);
            i += len;
        }
    }
    out
}

fn dedent_triple(input: MappedText) -> MappedText {
    let mut lines = Vec::new();
    let mut start = 0;
    for (i, byte) in input.text.bytes().enumerate() {
        if byte == b'\n' {
            lines.push((start, i, Some(i)));
            start = i + 1;
        }
    }
    lines.push((start, input.text.len(), None));

    let last = lines.len() - 1;
    let candidates: Vec<&str> = lines
        .iter()
        .enumerate()
        .filter(|(i, (start, end, _))| {
            *i != 0
                && (*i == last
                    || !input.text[*start..*end]
                        .bytes()
                        .all(|byte| matches!(byte, b' ' | b'\t')))
        })
        .map(|(_, (start, end, _))| {
            let line = &input.text[*start..*end];
            &line[..line
                .bytes()
                .take_while(|byte| matches!(byte, b' ' | b'\t'))
                .count()]
        })
        .collect();
    let dedent = common_whitespace_prefix_len(&candidates);

    let mut out = MappedText {
        text: String::new(),
        bytes: Vec::new(),
        empty_at: input.empty_at,
    };
    for (i, (start, end, newline)) in lines.into_iter().enumerate() {
        if i == 0 && start == end {
            continue;
        }
        let strip = if i == 0 { 0 } else { dedent.min(end - start) };
        out.push_slice(&input, start + strip..end);
        if let Some(newline) = newline {
            out.push_slice(&input, newline..newline + 1);
        }
    }
    out
}

/// Return the common byte prefix of leading space/tab strings.
///
/// This is shared with the JuliaSyntax projector so the public docstring value
/// and the differential oracle cannot drift on triple-string indentation.
pub(crate) fn common_whitespace_prefix_len(strings: &[&str]) -> usize {
    let Some(first) = strings.first() else {
        return 0;
    };
    strings.iter().skip(1).fold(first.len(), |len, string| {
        first
            .bytes()
            .zip(string.bytes())
            .take(len)
            .take_while(|(a, b)| a == b)
            .count()
    })
}

fn decode_raw(input: MappedText) -> MappedText {
    let bytes = input.text.as_bytes();
    let mut out = MappedText {
        text: String::new(),
        bytes: Vec::new(),
        empty_at: input.empty_at,
    };
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] != b'\\' {
            let len = input.text[i..].chars().next().unwrap().len_utf8();
            out.push_slice(&input, i..i + len);
            i += len;
            continue;
        }
        let mut run = 0;
        while i + run < bytes.len() && bytes[i + run] == b'\\' {
            run += 1;
        }
        let at_end = i + run == bytes.len();
        let before_quote = bytes.get(i + run) == Some(&b'"');
        if !at_end && !before_quote {
            out.push_slice(&input, i..i + run);
            i += run;
            continue;
        }
        for pair in 0..run / 2 {
            let start = i + pair * 2;
            out.text.push('\\');
            out.bytes.push(SourceSpan {
                start: input.bytes[start].start,
                end: input.bytes[start + 1].end,
            });
        }
        i += run;
        if run % 2 == 1 {
            out.text.push('"');
            let end = if before_quote { i + 1 } else { i };
            out.bytes.push(SourceSpan {
                start: input.bytes[i - 1].start,
                end: input.bytes[end.saturating_sub(1)].end,
            });
            i = end;
        }
    }
    out
}

fn decode_escapes(input: MappedText) -> Result<MappedText, StringDecodeError> {
    let source = input.text.as_bytes();
    let mut decoded = Vec::new();
    let mut spans = Vec::new();
    let mut i = 0;
    while i < source.len() {
        if source[i] != b'\\' {
            let len = input.text[i..].chars().next().unwrap().len_utf8();
            decoded.extend_from_slice(&source[i..i + len]);
            spans.extend_from_slice(&input.bytes[i..i + len]);
            i += len;
            continue;
        }
        let start = i;
        i += 1;
        let Some(&escaped) = source.get(i) else {
            return Err(StringDecodeError::BadEscape);
        };
        if matches!(escaped, b'\n' | b'\r') {
            if escaped == b'\r' && source.get(i + 1) == Some(&b'\n') {
                i += 1;
            }
            i += 1;
            while matches!(source.get(i), Some(b' ' | b'\t')) {
                i += 1;
            }
            continue;
        }
        let value = match escaped {
            b'n' => vec![b'\n'],
            b't' => vec![b'\t'],
            b'r' => vec![b'\r'],
            b'a' => vec![0x07],
            b'b' => vec![0x08],
            b'f' => vec![0x0c],
            b'v' => vec![0x0b],
            b'e' => vec![0x1b],
            b'\\' => vec![b'\\'],
            b'\'' => vec![b'\''],
            b'"' => vec![b'"'],
            b'$' => vec![b'$'],
            b'x' => decode_numeric_escape(source, &mut i, 2, false)?,
            b'u' => decode_numeric_escape(source, &mut i, 4, true)?,
            b'U' => decode_numeric_escape(source, &mut i, 8, true)?,
            b'0'..=b'7' => decode_octal_escape(source, &mut i)?,
            _ => return Err(StringDecodeError::BadEscape),
        };
        i += 1;
        let span = SourceSpan {
            start: input.bytes[start].start,
            end: input.bytes[i - 1].end,
        };
        decoded.extend_from_slice(&value);
        spans.extend(std::iter::repeat_n(span, value.len()));
    }
    let text = String::from_utf8(decoded).map_err(|_| StringDecodeError::BadUtf8)?;
    Ok(MappedText {
        text,
        bytes: spans,
        empty_at: input.empty_at,
    })
}

fn decode_numeric_escape(
    source: &[u8],
    i: &mut usize,
    max: usize,
    unicode: bool,
) -> Result<Vec<u8>, StringDecodeError> {
    let mut value = 0u32;
    let mut count = 0;
    while count < max {
        let Some(digit) = source
            .get(*i + 1)
            .and_then(|byte| char::from(*byte).to_digit(16))
        else {
            break;
        };
        *i += 1;
        value = value * 16 + digit;
        count += 1;
    }
    if count == 0 {
        return Err(StringDecodeError::BadEscape);
    }
    if !unicode {
        return Ok(vec![value as u8]);
    }
    let character = char::from_u32(value).ok_or(StringDecodeError::BadEscape)?;
    let mut buffer = [0; 4];
    Ok(character.encode_utf8(&mut buffer).as_bytes().to_vec())
}

fn decode_octal_escape(source: &[u8], i: &mut usize) -> Result<Vec<u8>, StringDecodeError> {
    let mut value = u32::from(source[*i] - b'0');
    for _ in 0..2 {
        let Some(digit) = source
            .get(*i + 1)
            .and_then(|byte| char::from(*byte).to_digit(8))
        else {
            break;
        };
        *i += 1;
        value = value * 8 + digit;
    }
    let byte = u8::try_from(value).map_err(|_| StringDecodeError::BadEscape)?;
    Ok(vec![byte])
}