arity 0.8.0

A language server, formatter, and linter for R
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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
//! The CommonMark inline pass for resolved `@md` emphasis and strong emphasis.
//!
//! Under `@md` the lexer carves `*`/`_` runs as **neutral** `RoxygenMdDelim`
//! leaves — it makes no open/close decision. This pass walks a block's events and,
//! over each maximal single-line run of inline-content tokens, resolves the
//! delimiter runs into `ROXYGEN_MD_EMPH` / `ROXYGEN_MD_STRONG` **nodes** via the
//! CommonMark delimiter-stack algorithm (full flanking — ASCII character classes
//! first —, the rule of three, and `process_emphasis`). Unmatched runs stay
//! literal `ROXYGEN_MD_DELIM` leaves (projected as plain text).
//!
//! Losslessness holds by construction: a matched run is split into `Event::Leaf`
//! delimiter pieces whose texts tile the original run, an unmatched run re-emits
//! its bytes, and every non-delimiter event passes through unchanged.
//!
//! **Scope (slice 1.5).** Emphasis/strong only, resolved at **paragraph
//! granularity**: a run spans every consecutive token of a paragraph (or tag-line)
//! body — including the inter-line trivia (newline, the next `#'` marker, leading
//! whitespace) that a continuation folds in — so a span may cross a *soft* line
//! break (`*foo`\n`bar*` → one `\emph` over `foo bar`). A run is bounded only by a
//! structural event (`Start`/`Finish`/`Leaf`): a paragraph/section/tag boundary, or
//! an inline node (`ROXYGEN_RD_MACRO`) which binds tighter than emphasis. The
//! inter-line trivia present as **whitespace** for flanking (a soft break is a
//! single space; the `#'` marker is treated as whitespace too) and pass through
//! verbatim — landing *inside* the resolved node when the span crosses a line.
//! Code spans, links, images, and raw HTML stay opaque local-span leaves, resolved
//! by the lexer *before* this pass — matching CommonMark precedence (they bind
//! tighter than emphasis), so the pass treats each as one opaque inline.

use crate::parser::events::Event;
use crate::parser::lexer::{TokKind, Token};
use crate::syntax::SyntaxKind;

/// Whether `kind` is a raw markdown-inline-markup token the pass resolves: an
/// emphasis delimiter run or an inline-link bracket. A run carrying neither is
/// re-emitted verbatim.
fn is_inline_markup(kind: &TokKind) -> bool {
    matches!(kind, TokKind::RoxygenMdDelim | TokKind::RoxygenMdBracket)
}

/// Resolve markdown emphasis/strong and inline links in `events` (in place). A
/// no-op unless the block carries at least one raw delimiter run or link bracket.
pub(super) fn resolve_emphasis(tokens: &[Token], events: &mut Vec<Event>) {
    let has_markup = events
        .iter()
        .any(|e| matches!(e, Event::Tok(i) if is_inline_markup(&tokens[*i].kind)));
    if !has_markup {
        return;
    }

    let mut out = Vec::with_capacity(events.len());
    let mut run: Vec<usize> = Vec::new();
    for ev in std::mem::take(events) {
        match ev {
            // Every paragraph-body token joins the run — content *and* the
            // inter-line trivia (newline / `#'` marker / whitespace) a continuation
            // folds in — so a span resolves across soft line breaks. A structural
            // event (a paragraph/section/tag boundary, or an inline `ROXYGEN_RD_MACRO`
            // which binds tighter than emphasis) bounds the run.
            Event::Tok(i) => run.push(i),
            other => {
                flush_run(tokens, &mut run, &mut out);
                out.push(other);
            }
        }
    }
    flush_run(tokens, &mut run, &mut out);
    *events = out;
}

/// Resolve one top-level inline run and append its events to `out`, then clear
/// `run`. A run with no markup re-emits its tokens verbatim (byte-identical), so
/// only markup-bearing runs are rebuilt. The run's edges are the start/end of the
/// inline content (whitespace, for flanking).
fn flush_run(tokens: &[Token], run: &mut Vec<usize>, out: &mut Vec<Event>) {
    if run.is_empty() {
        return;
    }
    if !run.iter().any(|&i| is_inline_markup(&tokens[i].kind)) {
        out.extend(run.drain(..).map(Event::Tok));
        return;
    }
    resolve_run(tokens, run, None, None, out);
    run.clear();
}

/// Resolve an inline run (`run` token indices) into events appended to `out`,
/// given the flanking-relevant characters immediately `before`/`after` the run
/// (`None` = a whitespace boundary). Builds the arena (collapsing inline links
/// into opaque `ROXYGEN_MD_LINK` nodes, their text resolved by a recursive call),
/// resolves emphasis over the resulting top-level node list, and emits.
fn resolve_run(
    tokens: &[Token],
    run: &[usize],
    before: Option<char>,
    after: Option<char>,
    out: &mut Vec<Event>,
) {
    let mut arena = Arena::build(tokens, run, before, after);
    arena.process_emphasis();
    arena.emit(out);
}

/// A node in the inline arena: a doubly linked list at the top level, with
/// emphasis nodes owning a child sublist.
struct Node {
    data: NodeData,
    prev: Option<usize>,
    next: Option<usize>,
    first_child: Option<usize>,
    last_child: Option<usize>,
}

enum NodeData {
    /// An opaque passthrough inline (text / code span / link / …): its original
    /// token index, re-emitted verbatim.
    Token(usize),
    /// Residual literal delimiter characters not consumed into emphasis. Emitted
    /// as a `ROXYGEN_MD_DELIM` leaf; dropped when empty.
    Delim(String),
    /// A resolved emphasis (`strong = false`) or strong (`strong = true`) span.
    /// `open`/`close` are the consumed delimiter strings, emitted as the node's
    /// opener/closer `ROXYGEN_MD_DELIM` leaves around its children.
    Emph {
        strong: bool,
        open: String,
        close: String,
    },
    /// A resolved inline link `[text](url)`: `open` is the opener bracket (`[`),
    /// `close` the closer carrying the destination (`](url)`), and `body` the
    /// already-resolved events of the link text (emphasis/code spans inside it
    /// resolved by a recursive [`resolve_run`]). Emitted as a `ROXYGEN_MD_LINK`
    /// **node** with the brackets as `ROXYGEN_MD_DELIM` opener/closer leaves; the
    /// node is opaque to the enclosing emphasis stack (so an outer span wraps the
    /// whole link, exactly as a plain inline does).
    Link {
        open: String,
        close: String,
        body: Vec<Event>,
    },
}

/// A delimiter-stack entry (its own doubly linked list, threaded by `prev`/`next`
/// over the delimiter Vec). `node` is the arena index of the `Delim` text node it
/// shrinks as delimiters are consumed.
struct Delim {
    node: usize,
    ch: u8,
    length: usize,
    orig: usize,
    can_open: bool,
    can_close: bool,
    prev: Option<usize>,
    next: Option<usize>,
    /// Cleared when the entry is removed from the stack (skipped thereafter).
    active: bool,
}

struct Arena {
    nodes: Vec<Node>,
    delims: Vec<Delim>,
    head: Option<usize>,
    tail: Option<usize>,
    /// Top of the delimiter stack (the last delimiter), like cmark's `last_delim`.
    last_delim: Option<usize>,
}

impl Arena {
    /// Build the top-level node list and the delimiter stack from an inline run.
    /// `before`/`after` are the flanking-relevant boundary characters at the run's
    /// edges (`None` = whitespace). An inline-link bracket pair (`[` … `](url)`) is
    /// **collapsed** into one opaque [`NodeData::Link`] whose body is the recursively
    /// resolved link text — so the brackets never reach the emphasis stack and an
    /// enclosing span wraps the whole link.
    fn build(tokens: &[Token], run: &[usize], before: Option<char>, after: Option<char>) -> Arena {
        let mut arena = Arena {
            nodes: Vec::new(),
            delims: Vec::new(),
            head: None,
            tail: None,
            last_delim: None,
        };
        // The flanking neighbor char at run position `p` on the given side: an
        // interior position reads its neighbor token's edge char; a run edge uses
        // the passed boundary (the link-text `[`/`]` for a recursive call, else ws).
        let neighbor = |p: usize, leading: bool| -> Option<char> {
            if leading {
                run.get(p + 1)
                    .map_or(after, |&j| edge_char(&tokens[j], true))
            } else {
                match p.checked_sub(1) {
                    Some(q) => edge_char(&tokens[run[q]], false),
                    None => before,
                }
            }
        };
        // Match the link brackets first (CommonMark `look_for_link_or_image`:
        // backward matching with opener deactivation, so nested links resolve
        // inner-first and the enclosing brackets stay literal), then walk the run.
        let roles = match_brackets(tokens, run);
        let mut p = 0;
        while p < run.len() {
            match &roles[p] {
                // A matched link opener collapses with its closer into one Link
                // node; the inner tokens resolve recursively, bounded by the bracket
                // chars (`[` before, `]` after) for flanking. A matched link's
                // interior provably contains no further matched link (an inner link
                // would have deactivated this opener), so the recursion only resolves
                // emphasis and literal brackets. The closer text distinguishes the
                // forms: an inline `](url)` leaf, or — for a *reference* link
                // `[text][ref]` — a lone `]` plus the consumed `[ref]` label folded
                // in as `][ref]`, or a bare `]` *shortcut*.
                BracketRole::MatchedOpener {
                    closer,
                    after,
                    close_text,
                } => {
                    let open = tokens[run[p]].text.clone();
                    let close = close_text.clone();
                    let (closer, after_p) = (*closer, *after);
                    let mut body = Vec::new();
                    resolve_run(
                        tokens,
                        &run[p + 1..closer],
                        open.chars().next_back(),
                        Some(']'),
                        &mut body,
                    );
                    arena.push_node(NodeData::Link { open, close, body });
                    p = after_p;
                    continue;
                }
                // An unmatched/inactive bracket re-emits as literal text (a `Delim`
                // node, projected as plain text) — a deactivated outer opener, a `]`
                // whose opener never appeared, or a closer that formed no link.
                BracketRole::LiteralBracket => {
                    arena.push_node(NodeData::Delim(tokens[run[p]].text.clone()));
                    p += 1;
                    continue;
                }
                // A closer or reference label already folded into its opener's link.
                BracketRole::Consumed => {
                    p += 1;
                    continue;
                }
                BracketRole::Other => {}
            }
            let tok = &tokens[run[p]];
            if tok.kind == TokKind::RoxygenMdDelim {
                let ch = tok.text.as_bytes()[0];
                let len = tok.text.len(); // a same-char ASCII run: bytes == chars
                let (can_open, can_close) = flanking(ch, neighbor(p, false), neighbor(p, true));
                let node = arena.push_node(NodeData::Delim(tok.text.clone()));
                arena.push_delim(node, ch, len, can_open, can_close);
            } else {
                arena.push_node(NodeData::Token(run[p]));
            }
            p += 1;
        }
        arena
    }

    fn push_node(&mut self, data: NodeData) -> usize {
        let id = self.nodes.len();
        self.nodes.push(Node {
            data,
            prev: self.tail,
            next: None,
            first_child: None,
            last_child: None,
        });
        if let Some(t) = self.tail {
            self.nodes[t].next = Some(id);
        } else {
            self.head = Some(id);
        }
        self.tail = Some(id);
        id
    }

    fn push_delim(&mut self, node: usize, ch: u8, length: usize, can_open: bool, can_close: bool) {
        let id = self.delims.len();
        self.delims.push(Delim {
            node,
            ch,
            length,
            orig: length,
            can_open,
            can_close,
            prev: self.last_delim,
            next: None,
            active: true,
        });
        if let Some(t) = self.last_delim {
            self.delims[t].next = Some(id);
        }
        self.last_delim = Some(id);
    }

    /// The CommonMark `process_emphasis` (ported from cmark). Walks the delimiter
    /// stack, matching each closer to the nearest eligible opener (rule of three),
    /// consuming 2 delimiters for strong else 1, wrapping the enclosed nodes.
    fn process_emphasis(&mut self) {
        // `openers_bottom[char][len % 3]` — the lower search bound per delimiter
        // char and closer length class. `*` = index 0, `_` = index 1.
        let mut openers_bottom = [[None; 3]; 2];

        // Find the first closer (move to the bottom of the active stack).
        let mut closer = self.last_delim;
        while let Some(c) = closer {
            match self.delims[c].prev {
                Some(p) => closer = Some(p),
                None => break,
            }
        }

        while let Some(c) = closer {
            if !self.delims[c].active {
                closer = self.delims[c].next;
                continue;
            }
            if !self.delims[c].can_close {
                closer = self.delims[c].next;
                continue;
            }

            let cc = self.delims[c].ch;
            let ci = if cc == b'*' { 0 } else { 1 };
            let bound = openers_bottom[ci][self.delims[c].length % 3];

            // Look back for the first matching opener.
            let mut opener = self.delims[c].prev;
            let mut opener_found = false;
            while let Some(o) = opener {
                if Some(o) == bound {
                    break;
                }
                if self.delims[o].active && self.delims[o].can_open && self.delims[o].ch == cc {
                    let odd_match = (self.delims[c].can_open || self.delims[o].can_close)
                        && !self.delims[c].orig.is_multiple_of(3)
                        && (self.delims[o].orig + self.delims[c].orig).is_multiple_of(3);
                    if !odd_match {
                        opener_found = true;
                        break;
                    }
                }
                opener = self.delims[o].prev;
            }

            if opener_found {
                let o = opener.unwrap();
                let use_delims = if self.delims[c].length >= 2 && self.delims[o].length >= 2 {
                    2
                } else {
                    1
                };
                self.delims[o].length -= use_delims;
                self.delims[c].length -= use_delims;

                let opener_inl = self.delims[o].node;
                let closer_inl = self.delims[c].node;
                let open_str = self.shorten_from_end(opener_inl, use_delims);
                let close_str = self.shorten_from_start(closer_inl, use_delims);

                let emph = self.push_emph(use_delims == 2, open_str, close_str);
                self.wrap_between(opener_inl, closer_inl, emph);

                self.remove_delims_between(o, c);

                if self.delims[o].length == 0 {
                    self.unlink(opener_inl);
                    self.remove_delim(o);
                }
                if self.delims[c].length == 0 {
                    let next = self.delims[c].next;
                    self.unlink(closer_inl);
                    self.remove_delim(c);
                    closer = next;
                }
            } else {
                openers_bottom[ci][self.delims[c].length % 3] = self.delims[c].prev;
                let next = self.delims[c].next;
                if !self.delims[c].can_open {
                    self.remove_delim(c);
                }
                closer = next;
            }
        }
    }

    /// Allocate an `Emph` node (not yet linked into any list).
    fn push_emph(&mut self, strong: bool, open: String, close: String) -> usize {
        let id = self.nodes.len();
        self.nodes.push(Node {
            data: NodeData::Emph {
                strong,
                open,
                close,
            },
            prev: None,
            next: None,
            first_child: None,
            last_child: None,
        });
        id
    }

    /// Remove `use_delims` characters from the *end* of a `Delim` node's literal,
    /// returning the removed string (the opener delimiters).
    fn shorten_from_end(&mut self, node: usize, use_delims: usize) -> String {
        let NodeData::Delim(s) = &mut self.nodes[node].data else {
            unreachable!("delimiter stack node is not a Delim")
        };
        let cut = s.len() - use_delims;
        s.split_off(cut)
    }

    /// Remove `use_delims` characters from the *start* of a `Delim` node's literal,
    /// returning the removed string (the closer delimiters).
    fn shorten_from_start(&mut self, node: usize, use_delims: usize) -> String {
        let NodeData::Delim(s) = &mut self.nodes[node].data else {
            unreachable!("delimiter stack node is not a Delim")
        };
        let removed = s[..use_delims].to_string();
        s.drain(..use_delims);
        removed
    }

    /// Move every top-level node strictly between `opener_inl` and `closer_inl`
    /// into `emph`'s child list, then insert `emph` right after `opener_inl`.
    fn wrap_between(&mut self, opener_inl: usize, closer_inl: usize, emph: usize) {
        let mut tmp = self.nodes[opener_inl].next;
        while let Some(t) = tmp {
            if t == closer_inl {
                break;
            }
            let next = self.nodes[t].next;
            self.unlink(t);
            self.append_child(emph, t);
            tmp = next;
        }
        self.insert_after(opener_inl, emph);
    }

    /// Detach `node` from whatever list it is in (top level only here).
    fn unlink(&mut self, node: usize) {
        let prev = self.nodes[node].prev;
        let next = self.nodes[node].next;
        match prev {
            Some(p) => self.nodes[p].next = next,
            None => self.head = next,
        }
        match next {
            Some(n) => self.nodes[n].prev = prev,
            None => self.tail = prev,
        }
        self.nodes[node].prev = None;
        self.nodes[node].next = None;
    }

    fn append_child(&mut self, parent: usize, child: usize) {
        self.nodes[child].prev = self.nodes[parent].last_child;
        self.nodes[child].next = None;
        match self.nodes[parent].last_child {
            Some(l) => self.nodes[l].next = Some(child),
            None => self.nodes[parent].first_child = Some(child),
        }
        self.nodes[parent].last_child = Some(child);
    }

    fn insert_after(&mut self, anchor: usize, node: usize) {
        let next = self.nodes[anchor].next;
        self.nodes[node].prev = Some(anchor);
        self.nodes[node].next = next;
        self.nodes[anchor].next = Some(node);
        match next {
            Some(n) => self.nodes[n].prev = Some(node),
            None => self.tail = Some(node),
        }
    }

    /// Deactivate a delimiter and splice it out of the delimiter stack.
    fn remove_delim(&mut self, d: usize) {
        if !self.delims[d].active {
            return;
        }
        self.delims[d].active = false;
        let prev = self.delims[d].prev;
        let next = self.delims[d].next;
        if let Some(p) = prev {
            self.delims[p].next = next;
        }
        match next {
            Some(n) => self.delims[n].prev = prev,
            None => self.last_delim = prev,
        }
    }

    /// Remove every delimiter strictly between `opener` and `closer`.
    fn remove_delims_between(&mut self, opener: usize, closer: usize) {
        let mut d = self.delims[opener].next;
        while let Some(cur) = d {
            if cur == closer {
                break;
            }
            let next = self.delims[cur].next;
            self.remove_delim(cur);
            d = next;
        }
    }

    /// Emit the resolved top-level node list as events.
    fn emit(&self, out: &mut Vec<Event>) {
        let mut cur = self.head;
        while let Some(n) = cur {
            self.emit_node(n, out);
            cur = self.nodes[n].next;
        }
    }

    fn emit_node(&self, n: usize, out: &mut Vec<Event>) {
        match &self.nodes[n].data {
            NodeData::Token(idx) => out.push(Event::Tok(*idx)),
            NodeData::Delim(s) => {
                if !s.is_empty() {
                    out.push(Event::Leaf(SyntaxKind::ROXYGEN_MD_DELIM, s.clone()));
                }
            }
            NodeData::Emph {
                strong,
                open,
                close,
            } => {
                let kind = if *strong {
                    SyntaxKind::ROXYGEN_MD_STRONG
                } else {
                    SyntaxKind::ROXYGEN_MD_EMPH
                };
                out.push(Event::Start(kind));
                out.push(Event::Leaf(SyntaxKind::ROXYGEN_MD_DELIM, open.clone()));
                let mut child = self.nodes[n].first_child;
                while let Some(c) = child {
                    self.emit_node(c, out);
                    child = self.nodes[c].next;
                }
                out.push(Event::Leaf(SyntaxKind::ROXYGEN_MD_DELIM, close.clone()));
                out.push(Event::Finish);
            }
            NodeData::Link { open, close, body } => {
                // A `ROXYGEN_MD_LINK` node: the brackets are opener/closer
                // `ROXYGEN_MD_DELIM` leaves around the already-resolved link-text
                // events (so the projector skips first/last child, as for emphasis).
                out.push(Event::Start(SyntaxKind::ROXYGEN_MD_LINK));
                out.push(Event::Leaf(SyntaxKind::ROXYGEN_MD_DELIM, open.clone()));
                out.extend(body.iter().cloned());
                out.push(Event::Leaf(SyntaxKind::ROXYGEN_MD_DELIM, close.clone()));
                out.push(Event::Finish);
            }
        }
    }
}

/// Whether a `RoxygenMdBracket` token text is an inline-link opener (`[` or `![`).
fn is_bracket_open(text: &str) -> bool {
    text.starts_with('[') || text.starts_with('!')
}

/// The role of a run position after bracket matching: a matched link opener
/// (collapsed into a Link node), a literal bracket (an unmatched/deactivated
/// opener, or a closer that formed no link), a consumed closer or reference label
/// (emitted as part of its opener's link), or a non-bracket position (`Other`).
enum BracketRole {
    MatchedOpener {
        closer: usize,
        after: usize,
        close_text: String,
    },
    LiteralBracket,
    Consumed,
    Other,
}

/// Match the link brackets in `run` left-to-right with CommonMark opener
/// deactivation (`look_for_link_or_image`): each `]` closes the nearest *active*
/// `[` opener, and forming a link deactivates every opener still below it on the
/// stack — so nested links resolve inner-first and the enclosing brackets stay
/// literal (`[a [b] c](url)` → literal `[a `, `\link{b}`, literal ` c](url)`).
/// Images are opaque leaves and autolinks are not brackets, so neither reaches
/// here; every opener is a link opener. Returns a role per run position.
fn match_brackets(tokens: &[Token], run: &[usize]) -> Vec<BracketRole> {
    let mut roles = Vec::with_capacity(run.len());
    roles.resize_with(run.len(), || BracketRole::Other);
    // Stack of (run position of an open `[`, still active).
    let mut stack: Vec<(usize, bool)> = Vec::new();
    let mut q = 0;
    while q < run.len() {
        let tok = &tokens[run[q]];
        if tok.kind != TokKind::RoxygenMdBracket {
            q += 1;
            continue;
        }
        if is_bracket_open(&tok.text) {
            stack.push((q, true));
            roles[q] = BracketRole::LiteralBracket; // until matched below
            q += 1;
            continue;
        }
        // A closer (`]`-shaped): pop the nearest opener.
        let Some((o_pos, active)) = stack.pop() else {
            roles[q] = BracketRole::LiteralBracket;
            q += 1;
            continue;
        };
        if !active {
            roles[q] = BracketRole::LiteralBracket;
            q += 1;
            continue;
        }
        match classify_closer(tokens, run, o_pos, q) {
            Some((close_text, after)) => {
                roles[o_pos] = BracketRole::MatchedOpener {
                    closer: q,
                    after,
                    close_text,
                };
                // Consume the closer and any folded-in `[ref]` label tokens
                // (`q + 1 .. after`); for an inline/shortcut closer the range is just
                // the closer itself (`after == q + 1`).
                for role in &mut roles[q..after] {
                    *role = BracketRole::Consumed;
                }
                // A link (never an image here) deactivates the openers below it.
                for e in stack.iter_mut() {
                    e.1 = false;
                }
                q = after;
            }
            None => {
                roles[q] = BracketRole::LiteralBracket;
                q += 1;
            }
        }
    }
    roles
}

/// Classify the closer at `run[closer_q]` for an active opener at `run[o_pos]`,
/// returning `(close_text, after)` for a valid link or `None` for none, where
/// `after` is the run index just past the closer and any folded-in `[ref]` label.
/// An inline `](url)` composite closer is always a valid link. A lone `]` is a
/// *reference* link when immediately followed by a `[ref]` label — neutral `[`/`]`
/// bracket tokens on the lookahead, folded in as `][ref]` (or, for a `\`-bearing
/// label, the legacy opaque `scan_md_link` leaf). Otherwise it is a *shortcut* link
/// iff the opener's raw interior is bracket-free (roxygen synthesizes a reference
/// only for a bracket-free shortcut label) — a bracket-bearing shortcut is not a link.
fn classify_closer(
    tokens: &[Token],
    run: &[usize],
    o_pos: usize,
    closer_q: usize,
) -> Option<(String, usize)> {
    let close_tok = &tokens[run[closer_q]];
    if close_tok.text != "]" {
        return Some((close_tok.text.clone(), closer_q + 1));
    }
    // A reference label `[ref]` on the lookahead, as neutral bracket tokens.
    if let Some((label, after)) = neutral_ref_label(tokens, run, closer_q + 1) {
        return Some((format!("][{label}]"), after));
    }
    // Legacy: a `\`-bearing label still carved as one opaque `scan_md_link` leaf.
    if let Some(&j) = run.get(closer_q + 1)
        && tokens[j].kind == TokKind::RoxygenMdLink
    {
        return Some((format!("]{}", tokens[j].text), closer_q + 2));
    }
    interior_bracket_free(tokens, run, o_pos, closer_q).then(|| ("]".to_string(), closer_q + 1))
}

/// If `run[label_open]` is a neutral `[` bracket opening a bracket-free reference
/// label, return `(label_text, after)` where `after` is the run index just past the
/// label's closing `]`. The label runs to the next neutral `]` bracket (the opener
/// carve guarantees a bracket-free interior, so the first `]` closes it). `None`
/// when `run[label_open]` is not a neutral `[` opener or no closing `]` follows.
fn neutral_ref_label(
    tokens: &[Token],
    run: &[usize],
    label_open: usize,
) -> Option<(String, usize)> {
    let open = run.get(label_open).map(|&j| &tokens[j])?;
    if open.kind != TokKind::RoxygenMdBracket || !open.text.starts_with('[') {
        return None;
    }
    let mut label = String::new();
    let mut k = label_open + 1;
    while let Some(&j) = run.get(k) {
        let tok = &tokens[j];
        if tok.kind == TokKind::RoxygenMdBracket {
            return (tok.text == "]").then_some((label, k + 1));
        }
        label.push_str(&tok.text);
        k += 1;
    }
    None
}

/// Whether the raw interior between an opener at `run[o_pos]` and a closer at
/// `run[closer_q]` carries no `[`/`]` in any token — the roxygen shortcut/reference
/// validity test (a bracket-bearing label is not a synthesized reference).
fn interior_bracket_free(tokens: &[Token], run: &[usize], o_pos: usize, closer_q: usize) -> bool {
    run[o_pos + 1..closer_q]
        .iter()
        .all(|&j| !tokens[j].text.bytes().any(|b| matches!(b, b'[' | b']')))
}

/// CommonMark flanking for a delimiter run of char `ch`, given the characters
/// immediately before and after the run (`None` = start/end of the inline run,
/// treated as whitespace). ASCII punctuation classification (the Unicode-class
/// refinement is a noted backlog item — it only differs when a non-ASCII
/// punctuation char abuts a delimiter).
fn flanking(ch: u8, before: Option<char>, after: Option<char>) -> (bool, bool) {
    let before_ws = is_ws(before);
    let after_ws = is_ws(after);
    let before_punct = is_punct(before);
    let after_punct = is_punct(after);

    let left_flanking = !after_ws && (!after_punct || before_ws || before_punct);
    let right_flanking = !before_ws && (!before_punct || after_ws || after_punct);

    match ch {
        b'_' => (
            left_flanking && (!right_flanking || before_punct),
            right_flanking && (!left_flanking || after_punct),
        ),
        // `*` (and any other delimiter char routed here).
        _ => (left_flanking, right_flanking),
    }
}

/// The flanking-relevant edge char of a run neighbor: the first char (`leading`)
/// or the last char of its text. A `#'` marker token is mapped to a space — an
/// inter-line continuation is a soft break, which CommonMark treats as whitespace
/// (newline/whitespace tokens already yield a whitespace char). `None` (an empty
/// token) falls back to the start/end boundary, also whitespace.
///
/// An inline Rd macro (`\code{…}`, `\link{…}`, `\emph{…}`, …) is **opaque** to the
/// markdown pass exactly as it is to roxygen2's cmark: roxygen2 replaces a fragile
/// tag with an alphanumeric placeholder (`make_random_string`) suffixed `-<i>-`
/// (`str_sub_same`) *before* parsing, and a non-fragile tag is plain text whose
/// markdown the arg-recursion handles. So for flanking a macro must present that
/// placeholder's shape, **not** its own `\`/`}` punctuation bytes: an alphanumeric
/// at the **leading** edge (so a `*` opener abutting the macro can open —
/// `a*\code{x} y*` → `\emph{\code{x} y}`) and the trailing `-` at the **trailing**
/// edge (so a `*` closer abutting the macro stays blocked, as the placeholder's `-`
/// blocks it — `a*\code{x}*b` keeps both `*` literal). Without this the macro's raw
/// `\` (leading) / `}` (trailing) punctuation would wrongly suppress a span.
fn edge_char(tok: &Token, leading: bool) -> Option<char> {
    if tok.kind == TokKind::RoxygenMarker {
        return Some(' ');
    }
    if tok.kind == TokKind::RoxygenRdMacro {
        return Some(if leading { 'x' } else { '-' });
    }
    if leading {
        tok.text.chars().next()
    } else {
        tok.text.chars().next_back()
    }
}

/// A start/end boundary (`None`) counts as whitespace, per CommonMark.
fn is_ws(c: Option<char>) -> bool {
    c.is_none_or(char::is_whitespace)
}

/// ASCII-punctuation classification (CommonMark's punctuation set, ASCII subset).
fn is_punct(c: Option<char>) -> bool {
    c.is_some_and(|c| c.is_ascii_punctuation())
}