panache-parser 0.10.0

Lossless CST parser and syntax wrappers for Pandoc markdown, Quarto, and RMarkdown
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
//! Link and image AST node wrappers.

use super::ast::support;
use super::{AstNode, PanacheLanguage, SyntaxKind, SyntaxNode};

pub struct Link(SyntaxNode);

impl AstNode for Link {
    type Language = PanacheLanguage;

    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::LINK
    }

    fn cast(syntax: SyntaxNode) -> Option<Self> {
        if Self::can_cast(syntax.kind()) {
            Some(Self(syntax))
        } else {
            None
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl Link {
    /// Returns the link text node.
    pub fn text(&self) -> Option<LinkText> {
        support::child(&self.0)
    }

    /// Returns the link destination node.
    pub fn dest(&self) -> Option<LinkDest> {
        support::child(&self.0)
    }

    /// Returns the reference label for reference-style links.
    pub fn reference(&self) -> Option<LinkRef> {
        support::child(&self.0)
    }
}

pub struct AutoLink(SyntaxNode);

impl AstNode for AutoLink {
    type Language = PanacheLanguage;

    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::AUTO_LINK
    }

    fn cast(syntax: SyntaxNode) -> Option<Self> {
        if Self::can_cast(syntax.kind()) {
            Some(Self(syntax))
        } else {
            None
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl AutoLink {
    /// Returns the autolink target text without angle brackets.
    pub fn target(&self) -> String {
        self.0
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .filter(|token| token.kind() == SyntaxKind::TEXT)
            .map(|token| token.text().to_string())
            .collect()
    }
}

pub struct LinkText(SyntaxNode);

impl AstNode for LinkText {
    type Language = PanacheLanguage;

    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::LINK_TEXT
    }

    fn cast(syntax: SyntaxNode) -> Option<Self> {
        if Self::can_cast(syntax.kind()) {
            Some(Self(syntax))
        } else {
            None
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl LinkText {
    /// Returns the text content.
    pub fn text_content(&self) -> String {
        self.0
            .descendants_with_tokens()
            .filter_map(|it| it.into_token())
            .filter(|token| token.kind() == SyntaxKind::TEXT)
            .map(|token| token.text().to_string())
            .collect()
    }
}

pub struct LinkDest(SyntaxNode);

impl AstNode for LinkDest {
    type Language = PanacheLanguage;

    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::LINK_DEST
    }

    fn cast(syntax: SyntaxNode) -> Option<Self> {
        if Self::can_cast(syntax.kind()) {
            Some(Self(syntax))
        } else {
            None
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl LinkDest {
    /// Returns the URL/destination as a string (with surrounding parentheses).
    pub fn url(&self) -> String {
        self.0.text().to_string()
    }

    /// Returns the URL without parentheses.
    pub fn url_content(&self) -> String {
        let text = self.0.text().to_string();
        text.trim_start_matches('(')
            .trim_end_matches(')')
            .to_string()
    }

    /// Returns the range for a hash-anchor id within destination text (without '#').
    pub fn hash_anchor_id_range(&self) -> Option<rowan::TextRange> {
        let text = self.0.text().to_string();
        let hash_idx = text.find('#')?;
        let after_hash = &text[hash_idx + 1..];
        let id_len = after_hash
            .chars()
            .take_while(|ch| !ch.is_whitespace() && *ch != ')')
            .map(char::len_utf8)
            .sum::<usize>();
        if id_len == 0 {
            return None;
        }
        let node_start: usize = self.0.text_range().start().into();
        let start = rowan::TextSize::from((node_start + hash_idx + 1) as u32);
        let end = rowan::TextSize::from((node_start + hash_idx + 1 + id_len) as u32);
        Some(rowan::TextRange::new(start, end))
    }

    /// Returns the hash-anchor id within destination text (without '#').
    pub fn hash_anchor_id(&self) -> Option<String> {
        let text = self.0.text().to_string();
        let hash_idx = text.find('#')?;
        let after_hash = &text[hash_idx + 1..];
        let id_len = after_hash
            .chars()
            .take_while(|ch| !ch.is_whitespace() && *ch != ')')
            .map(char::len_utf8)
            .sum::<usize>();
        if id_len == 0 {
            return None;
        }
        Some(after_hash[..id_len].to_string())
    }
}

pub struct LinkRef(SyntaxNode);

impl AstNode for LinkRef {
    type Language = PanacheLanguage;

    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::LINK_REF
    }

    fn cast(syntax: SyntaxNode) -> Option<Self> {
        if Self::can_cast(syntax.kind()) {
            Some(Self(syntax))
        } else {
            None
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl LinkRef {
    /// Returns the reference label text.
    pub fn label(&self) -> String {
        self.0
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .filter(|token| token.kind() == SyntaxKind::TEXT)
            .map(|token| token.text().to_string())
            .collect()
    }

    /// Returns the text range for the reference label (without brackets).
    pub fn label_range(&self) -> Option<rowan::TextRange> {
        self.0
            .children_with_tokens()
            .filter_map(|it| it.into_token())
            .find(|token| token.kind() == SyntaxKind::TEXT)
            .map(|token| token.text_range())
    }

    /// Returns the text range for the label value (without brackets).
    pub fn label_value_range(&self) -> Option<rowan::TextRange> {
        self.label_range()
    }
}

pub struct ImageLink(SyntaxNode);

impl AstNode for ImageLink {
    type Language = PanacheLanguage;

    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::IMAGE_LINK
    }

    fn cast(syntax: SyntaxNode) -> Option<Self> {
        if Self::can_cast(syntax.kind()) {
            Some(Self(syntax))
        } else {
            None
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl ImageLink {
    /// Returns the alt text node.
    pub fn alt(&self) -> Option<ImageAlt> {
        support::child(&self.0)
    }

    /// Returns the image destination.
    pub fn dest(&self) -> Option<LinkDest> {
        support::child(&self.0)
    }

    /// Returns the reference label for reference-style images.
    pub fn reference(&self) -> Option<LinkRef> {
        support::child(&self.0)
    }

    /// Returns the reference label text for reference-style images.
    pub fn reference_label(&self) -> Option<String> {
        self.reference().map(|link_ref| link_ref.label())
    }

    /// Returns the text range for the reference label in reference-style images.
    pub fn reference_label_range(&self) -> Option<rowan::TextRange> {
        self.reference().and_then(|link_ref| link_ref.label_range())
    }
}

pub struct ImageAlt(SyntaxNode);

impl AstNode for ImageAlt {
    type Language = PanacheLanguage;

    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::IMAGE_ALT
    }

    fn cast(syntax: SyntaxNode) -> Option<Self> {
        if Self::can_cast(syntax.kind()) {
            Some(Self(syntax))
        } else {
            None
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl ImageAlt {
    /// Returns the alt text content.
    pub fn text(&self) -> String {
        self.0
            .descendants_with_tokens()
            .filter_map(|it| it.into_token())
            .filter(|token| token.kind() == SyntaxKind::TEXT)
            .map(|token| token.text().to_string())
            .collect()
    }
}

pub struct Figure(SyntaxNode);

impl AstNode for Figure {
    type Language = PanacheLanguage;

    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::FIGURE
    }

    fn cast(syntax: SyntaxNode) -> Option<Self> {
        if Self::can_cast(syntax.kind()) {
            Some(Self(syntax))
        } else {
            None
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl Figure {
    /// Returns the image link within the figure.
    pub fn image(&self) -> Option<ImageLink> {
        support::child(&self.0)
    }
}

/// A bracket-shape pattern (`[foo]`, `[text][label]`, `[text][]`,
/// `![alt]`, ...) that did not resolve as a link or image — i.e. no
/// matching reference definition was found.
///
/// Distinct from `Link` / `ImageLink` so downstream tools (linter, LSP,
/// formatter, salsa, pandoc-ast projector) can attach behavior to
/// unresolved bracket-shape patterns without the parser having to lie
/// about resolution. Use `is_image()` to discriminate `[foo]` from
/// `![foo]` shapes.
pub struct UnresolvedReference(SyntaxNode);

impl AstNode for UnresolvedReference {
    type Language = PanacheLanguage;

    fn can_cast(kind: SyntaxKind) -> bool {
        kind == SyntaxKind::UNRESOLVED_REFERENCE
    }

    fn cast(syntax: SyntaxNode) -> Option<Self> {
        if Self::can_cast(syntax.kind()) {
            Some(Self(syntax))
        } else {
            None
        }
    }

    fn syntax(&self) -> &SyntaxNode {
        &self.0
    }
}

impl UnresolvedReference {
    /// `true` if this is an image-shape reference (`![alt]...`),
    /// `false` for a link-shape reference (`[text]...`). Determined
    /// from the leading byte of the node's source text.
    pub fn is_image(&self) -> bool {
        self.0.text().to_string().as_bytes().first() == Some(&b'!')
    }

    /// The bracket-text content (the bytes between the outer `[` and
    /// `]`). For `[foo]` this is `"foo"`; for `[text][label]` this is
    /// `"text"`.
    pub fn text(&self) -> String {
        // Mirror Link::text behavior: collect TEXT tokens from the
        // primary text wrapper if present, falling back to all TEXT
        // tokens under the node.
        if let Some(link_text) = support::child::<LinkText>(&self.0) {
            return link_text.text_content();
        }
        if let Some(image_alt) = support::child::<ImageAlt>(&self.0) {
            return image_alt.text();
        }
        self.0
            .descendants_with_tokens()
            .filter_map(|it| it.into_token())
            .filter(|token| token.kind() == SyntaxKind::TEXT)
            .map(|token| token.text().to_string())
            .collect()
    }

    /// The reference label for full / collapsed forms
    /// (`[text][label]` → `Some("label")`; `[text][]` → `Some("text")`;
    /// `[text]` shortcut → `None`).
    pub fn label(&self) -> Option<String> {
        support::child::<LinkRef>(&self.0).map(|r| r.label())
    }

    /// Source range of the node.
    pub fn text_range(&self) -> rowan::TextRange {
        self.0.text_range()
    }
}

#[cfg(test)]
mod tests {
    use super::{AstNode, ImageLink, UnresolvedReference};

    #[test]
    fn image_reference_label_and_range_are_extracted() {
        // Refdef present: parses as ImageLink so the wrapper accessors apply.
        let input = "![Alt text][img]\n\n[img]: /url\n";
        let tree = crate::parse(input, None);
        let image = tree
            .descendants()
            .find_map(ImageLink::cast)
            .expect("image link");

        assert_eq!(image.reference_label().as_deref(), Some("img"));

        let range = image.reference_label_range().expect("label range");
        let start: usize = range.start().into();
        let end: usize = range.end().into();
        assert_eq!(&input[start..end], "img");
    }

    #[test]
    fn unresolved_image_reference_label_is_extracted() {
        // No matching refdef: parses as UnresolvedReference under Pandoc.
        // Confirms `is_image()` and `label()` accessors.
        let input = "![Alt text][img]";
        let tree = crate::parse(input, None);
        let unresolved = tree
            .descendants()
            .find_map(UnresolvedReference::cast)
            .expect("unresolved reference");

        assert!(unresolved.is_image(), "expected image-shape unresolved ref");
        assert_eq!(unresolved.label().as_deref(), Some("img"));
    }

    #[test]
    fn unresolved_link_reference_label_is_extracted() {
        let input = "[link text][missing]";
        let tree = crate::parse(input, None);
        let unresolved = tree
            .descendants()
            .find_map(UnresolvedReference::cast)
            .expect("unresolved reference");

        assert!(!unresolved.is_image(), "expected link-shape unresolved ref");
        assert_eq!(unresolved.label().as_deref(), Some("missing"));
    }

    #[test]
    fn unresolved_shortcut_reference_has_no_label() {
        let input = "[no refdef]";
        let tree = crate::parse(input, None);
        let unresolved = tree
            .descendants()
            .find_map(UnresolvedReference::cast)
            .expect("unresolved reference");

        assert!(!unresolved.is_image());
        assert!(unresolved.label().is_none());
    }
}