sphinx-ultra 0.5.0

High-performance Rust-based Sphinx documentation builder for large codebases
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
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
//! docutils-exact id/name normalization and the document id registry.
//!
//! Algorithms ported from docutils 0.22.4 `nodes.py` (`make_id`,
//! `fully_normalize_name`, `whitespace_normalize_name`, `document.set_id`,
//! `set_name_id_map`/`set_duplicate_name_id`), with the Sphinx settings
//! `id_prefix=''`, `auto_id_prefix='id'` baked in (sphinx/environment
//! overrides docutils' `'%'` default — auto ids are `id1`, `id2`, …).

use std::collections::{HashMap, HashSet};

use unicode_normalization::UnicodeNormalization;

use super::messages;
use super::Node;
use crate::utils::py_isspace;

/// docutils `_non_id_translate_digraphs` (applied after lowercasing).
fn translate_digraph(c: char) -> Option<&'static str> {
    Some(match c as u32 {
        223 => "sz", // ß
        230 => "ae", // æ
        339 => "oe", // œ
        568 => "db", // ȸ
        569 => "qp", // ȹ
        _ => return None,
    })
}

/// docutils `_non_id_translate` (single-char replacements).
fn translate_single(c: char) -> Option<char> {
    Some(match c as u32 {
        248 => 'o', // ø
        273 => 'd', // đ
        295 => 'h', // ħ
        305 => 'i', // ı
        322 => 'l', // ł
        359 => 't', // ŧ
        384 => 'b', // ƀ
        387 => 'b', // ƃ
        392 => 'c', // ƈ
        396 => 'd', // ƌ
        402 => 'f', // ƒ
        409 => 'k', // ƙ
        410 => 'l', // ƚ
        414 => 'n', // ƞ
        421 => 'p', // ƥ
        427 => 't', // ƫ
        429 => 't', // ƭ
        436 => 'y', // ƴ
        438 => 'z', // ƶ
        485 => 'g', // ǥ
        549 => 'z', // ȥ
        564 => 'l', // ȴ
        565 => 'n', // ȵ
        566 => 't', // ȶ
        567 => 'j', // ȷ
        572 => 'c', // ȼ
        575 => 's', // ȿ
        576 => 'z', // ɀ
        583 => 'e', // ɇ
        585 => 'j', // ɉ
        587 => 'q', // ɋ
        589 => 'r', // ɍ
        591 => 'y', // ɏ
        _ => return None,
    })
}

/// docutils `nodes.make_id`. Result grammar: `[a-z](-?[a-z0-9]+)*` or empty.
pub fn make_id(s: &str) -> String {
    // 1. lowercase FIRST (order is load-bearing: Ü -> ü -> NFKD u).
    let lowered = s.to_lowercase();
    // 2. digraph + single-char translate tables (disjoint key sets).
    let mut translated = String::with_capacity(lowered.len());
    for c in lowered.chars() {
        if let Some(d) = translate_digraph(c) {
            translated.push_str(d);
        } else if let Some(r) = translate_single(c) {
            translated.push(r);
        } else {
            translated.push(c);
        }
    }
    // 3. NFKD-normalize, drop remaining non-ASCII.
    let ascii: String = translated.nfkd().filter(char::is_ascii).collect();
    // 4. collapse whitespace runs (' '.join(s.split()) — Python's
    //    `str.split()`, i.e. [`py_isspace`] runs).
    let collapsed = py_split_join(&ascii);
    // 5. every [^a-z0-9]+ run -> single '-'.
    let mut out = String::with_capacity(collapsed.len());
    let mut in_run = false;
    for c in collapsed.chars() {
        if c.is_ascii_lowercase() || c.is_ascii_digit() {
            out.push(c);
            in_run = false;
        } else if !in_run {
            out.push('-');
            in_run = true;
        }
    }
    // 6. strip leading [-0-9]+ and trailing -+ (ASCII-only by now).
    let bytes = out.as_bytes();
    let mut start = 0;
    while start < bytes.len() && (bytes[start] == b'-' || bytes[start].is_ascii_digit()) {
        start += 1;
    }
    let mut end = bytes.len();
    while end > start && bytes[end - 1] == b'-' {
        end -= 1;
    }
    out[start..end].to_string()
}

/// sphinx `util.nodes._make_id` (`:537-561`) — a fork of docutils' 0.16
/// `make_id` with two documented changes: capital letters survive, and `.`
/// and `_` count as identifier characters (so `envvar-HOME_A` stays
/// `envvar-HOME_A`, where docutils' would yield `envvar-home-a`). The
/// translate tables are the same ones [`make_id`] uses; the lowercasing
/// step is what sphinx drops, so this runs them on the raw string.
///
/// Result grammar: `[^-0-9._][a-zA-Z0-9._-]*` with no trailing `-`, or empty.
pub fn sphinx_make_id(s: &str) -> String {
    // 1. digraph + single-char translate tables (NO lowercasing first).
    let mut translated = String::with_capacity(s.len());
    for c in s.chars() {
        if let Some(d) = translate_digraph(c) {
            translated.push_str(d);
        } else if let Some(r) = translate_single(c) {
            translated.push(r);
        } else {
            translated.push(c);
        }
    }
    // 2. NFKD-normalize, drop remaining non-ASCII.
    let ascii: String = translated.nfkd().filter(char::is_ascii).collect();
    // 3. collapse whitespace runs (' '.join(s.split())).
    let collapsed = py_split_join(&ascii);
    // 4. every [^a-zA-Z0-9._]+ run -> single '-'.
    let mut out = String::with_capacity(collapsed.len());
    let mut in_run = false;
    for c in collapsed.chars() {
        if c.is_ascii_alphanumeric() || c == '.' || c == '_' {
            out.push(c);
            in_run = false;
        } else if !in_run {
            out.push('-');
            in_run = true;
        }
    }
    // 5. `^[-0-9._]+|-+$` -> '' (both ends, one re.sub pass).
    let bytes = out.as_bytes();
    let mut start = 0;
    while start < bytes.len() && matches!(bytes[start], b'-' | b'.' | b'_' | b'0'..=b'9') {
        start += 1;
    }
    let mut end = bytes.len();
    while end > start && bytes[end - 1] == b'-' {
        end -= 1;
    }
    out[start..end].to_string()
}

/// Python `' '.join(s.split())`: strip the ends and collapse every run of
/// `str.isspace` characters to one space. `str.split()` splits on
/// [`py_isspace`], which admits `\x1c`-`\x1f` where Rust's
/// `split_whitespace` (Unicode White_Space) does not — so `a\x1fb` is the
/// name `a b` under docutils (`nodes.py:3044-3050`; probed: `.. _a\x1fb:`
/// yields `names="a\ b"`, a `Sec\x1fC` title `names="sec\ c"`).
fn py_split_join(s: &str) -> String {
    s.split(py_isspace)
        .filter(|w| !w.is_empty())
        .collect::<Vec<_>>()
        .join(" ")
}

/// docutils `fully_normalize_name`: lowercase + collapse whitespace.
pub fn fully_normalize_name(s: &str) -> String {
    py_split_join(&s.to_lowercase())
}

/// docutils `whitespace_normalize_name`: collapse whitespace, keep case.
pub fn whitespace_normalize_name(s: &str) -> String {
    py_split_join(s)
}

/// A deferred "first node loses its name too" fixup: on a duplicate name,
/// docutils dupnames BOTH nodes, but the first one is already deep in the
/// tree — the parser applies these after parsing via
/// [`apply_dupname_fixups`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DupnameFixup {
    pub name: String,
    pub node_id: String,
}

/// Document-level id/name registry (docutils `document.ids`/`nameids`/
/// `id_counter` with Sphinx auto-id settings).
#[derive(Debug, Clone)]
struct NameEntry {
    /// Some(id) while the name maps uniquely; None once duplicated away.
    id: Option<String>,
    explicit: bool,
    refuri: Option<String>,
}

#[derive(Debug, Default)]
pub struct IdRegistry {
    ids: HashSet<String>,
    nameids: HashMap<String, NameEntry>,
    /// per-prefix auto-id counters (only "id" in wave 1).
    id_counter: HashMap<&'static str, u64>,
    fixups: Vec<DupnameFixup>,
    /// sphinx env.new_serialno('index') — shared by the index directive
    /// and the index-entry-emitting roles (pep/rfc/cve/cwe/:index:).
    index_serial: u32,
    /// The other `env.new_serialno(category)` counters, keyed by the
    /// `sphinx.util.nodes.make_id` prefix that asked for one
    /// (`cmdoption-myprog`, `confval`, …). Kept apart from
    /// [`Self::index_serial`] only because that one has a public accessor
    /// (`index_serial`) that rides the parse export; the semantics are the
    /// same per-document, per-category counter starting at 0.
    serialnos: HashMap<String, u32>,
}

impl IdRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    /// sphinx env.new_serialno('index'): returns the current value and
    /// increments (serials start at 0 per document).
    pub fn new_index_serialno(&mut self) -> u32 {
        let n = self.index_serial;
        self.index_serial += 1;
        n
    }

    /// sphinx `util.nodes.make_id(env, document, prefix, term)` (`:610-637`),
    /// both prefix regimes:
    ///
    /// - non-empty prefix: candidate `_make_id(f'{prefix}-{term}')`, rejected
    ///   when it collapses to just the prefix, then serial fallback
    ///   `f'{prefix}-{env.new_serialno(prefix)}'` until the id is free;
    /// - EMPTY prefix (the py domain's object ids, `domains/python/
    ///   _object.py:420`): `idformat` becomes `(id_prefix or 'id') + '%s'`
    ///   with the Sphinx-pinned `id_prefix=''`, so the candidate is the bare
    ///   `_make_id(term)` — dots, underscores and capitals survive, making
    ///   `mymod.C.meth` its own node id — rejected when empty, and the
    ///   serial fallback is `id{n}` (`id0`, `id1`, …) with the counter still
    ///   keyed by the empty prefix.
    ///
    /// Sphinx does NOT register the result in `document.ids` here —
    /// `note_explicit_target` → `document.set_id` does, which is
    /// [`Self::note_explicit_id`].
    pub fn sphinx_make_id(&mut self, prefix: &str, term: &str) -> String {
        let mut node_id = if term.is_empty() {
            None
        } else if prefix.is_empty() {
            let candidate = sphinx_make_id(term);
            // `if not node_id: node_id = None` — empty term hash.
            (!candidate.is_empty()).then_some(candidate)
        } else {
            let candidate = sphinx_make_id(&format!("{prefix}-{term}"));
            // "*term* is not good to generate a node_id."
            (candidate != prefix).then_some(candidate)
        };
        loop {
            match &node_id {
                Some(id) if !self.ids.contains(id) => return id.clone(),
                _ => {}
            }
            let counter = self.serialnos.entry(prefix.to_string()).or_insert(0);
            let serial = *counter;
            *counter += 1;
            node_id = Some(if prefix.is_empty() {
                format!("id{serial}")
            } else {
                format!("{prefix}-{serial}")
            });
        }
    }

    /// docutils `document.set_id` for a node that already carries ids
    /// (`nodes.py:1832-1843`): registration only — the duplicate-id ERROR
    /// path cannot fire for the ids [`Self::sphinx_make_id`] hands out,
    /// which are chosen to be free.
    pub fn note_explicit_id(&mut self, id: &str) {
        self.ids.insert(id.to_string());
    }

    /// docutils `document.set_id` (id_prefix='', auto_id_prefix='id'):
    /// first unregistered nonempty `make_id(name)` wins; otherwise `idN`.
    fn allocate_id(&mut self, names: &[String]) -> String {
        for name in names {
            let base = make_id(name);
            if !base.is_empty() && !self.ids.contains(&base) {
                self.ids.insert(base.clone());
                return base;
            }
        }
        loop {
            let counter = self.id_counter.entry("id").or_insert(0);
            *counter += 1;
            let id = format!("id{counter}");
            if !self.ids.contains(&id) {
                self.ids.insert(id.clone());
                return id;
            }
        }
    }

    fn dupname_new(node: &mut Node, name: &str) {
        if let Some(pos) = node.attrs.names.iter().position(|n| n == name) {
            node.attrs.names.remove(pos);
            node.attrs.dupnames.push(name.to_string());
        }
    }

    /// docutils `set_name_id_map`/`set_duplicate_name_id` with the
    /// explicit-vs-implicit precedence table (fixture-verified):
    /// - implicit vs implicit: BOTH dupname'd, INFO "Duplicate implicit …"
    /// - explicit vs explicit: BOTH dupname'd, WARNING "Duplicate explicit …"
    ///   (unless both share an identical refuri: new dupname'd silently)
    /// - new implicit vs old explicit: only the NEW node dupname'd, INFO
    /// - new explicit vs old implicit: OLD dupname'd, new KEEPS the name,
    ///   INFO "Target name overrides implicit target name …"
    fn register(
        &mut self,
        node: &mut Node,
        line: u32,
        source: &str,
        explicit: bool,
        backrefs_on_msg: bool,
        refuri: Option<&str>,
    ) -> Option<Node> {
        let id = self.allocate_id(&node.attrs.names);
        node.attrs.ids.push(id.clone());

        let mut message = None;
        let names = node.attrs.names.clone();
        for name in names {
            let Some(entry) = self.nameids.get(&name).cloned() else {
                self.nameids.insert(
                    name,
                    NameEntry {
                        id: Some(id.clone()),
                        explicit,
                        refuri: refuri.map(str::to_string),
                    },
                );
                continue;
            };
            let dup_info = |level: u8, text: String, with_backrefs: bool| {
                let mut msg = messages::system_message(level, &text, line, source);
                if with_backrefs {
                    msg.attrs.backrefs.push(id.clone());
                }
                msg
            };
            match (entry.explicit, explicit) {
                (true, true) => {
                    if refuri.is_some() && entry.refuri.as_deref() == refuri {
                        // Identical external duplicate: silent, new dupname'd.
                        Self::dupname_new(node, &name);
                        continue;
                    }
                    if let Some(old_id) = entry.id.clone() {
                        self.fixups.push(DupnameFixup {
                            name: name.clone(),
                            node_id: old_id,
                        });
                    }
                    self.nameids.insert(
                        name.clone(),
                        NameEntry {
                            id: None,
                            explicit: true,
                            refuri: None,
                        },
                    );
                    Self::dupname_new(node, &name);
                    message = Some(dup_info(
                        messages::WARNING,
                        format!("Duplicate explicit target name: \"{name}\"."),
                        backrefs_on_msg,
                    ));
                }
                (true, false) => {
                    // Old explicit wins: only the new node is dupname'd.
                    Self::dupname_new(node, &name);
                    message = Some(dup_info(
                        messages::INFO,
                        format!("Duplicate implicit target name: \"{name}\"."),
                        backrefs_on_msg,
                    ));
                }
                (false, true) => {
                    // New explicit overrides: old dupname'd, new keeps name.
                    if let Some(old_id) = entry.id.clone() {
                        self.fixups.push(DupnameFixup {
                            name: name.clone(),
                            node_id: old_id,
                        });
                    }
                    self.nameids.insert(
                        name.clone(),
                        NameEntry {
                            id: Some(id.clone()),
                            explicit: true,
                            refuri: refuri.map(str::to_string),
                        },
                    );
                    message = Some(dup_info(
                        messages::INFO,
                        format!("Target name overrides implicit target name \"{name}\"."),
                        false,
                    ));
                }
                (false, false) => {
                    if let Some(old_id) = entry.id.clone() {
                        self.fixups.push(DupnameFixup {
                            name: name.clone(),
                            node_id: old_id,
                        });
                    }
                    self.nameids.insert(
                        name.clone(),
                        NameEntry {
                            id: None,
                            explicit: false,
                            refuri: None,
                        },
                    );
                    Self::dupname_new(node, &name);
                    message = Some(dup_info(
                        messages::INFO,
                        format!("Duplicate implicit target name: \"{name}\"."),
                        backrefs_on_msg,
                    ));
                }
            }
        }
        message
    }

    /// Register an implicit target (section). On duplicate: INFO/1 message
    /// (placed by the caller inside the new section after its title), new
    /// node dupname'd immediately, old node queued for
    /// [`apply_dupname_fixups`].
    pub fn set_id_implicit(&mut self, node: &mut Node, line: u32, source: &str) -> Option<Node> {
        self.register(node, line, source, false, true, None)
    }

    /// Register an explicit target (`.. _name:` forms). On duplicate:
    /// WARNING/2; `backrefs` appear on the message only for internal targets
    /// (probe-verified: external/refuri duplicates carry no backrefs).
    pub fn set_id_explicit(
        &mut self,
        node: &mut Node,
        line: u32,
        source: &str,
        internal: bool,
        refuri: Option<&str>,
    ) -> Option<Node> {
        self.register(node, line, source, true, internal, refuri)
    }

    /// Register an anonymous target: always an auto id, never a name.
    pub fn set_id_anonymous(&mut self, node: &mut Node) {
        let id = self.allocate_id(&[]);
        node.attrs.ids.push(id);
    }

    /// Allocate a bare auto id (`idN`) — used by the inline parser for
    /// problematic/system_message pairs.
    pub fn allocate_auto_id(&mut self) -> String {
        self.allocate_id(&[])
    }

    pub fn take_fixups(&mut self) -> Vec<DupnameFixup> {
        std::mem::take(&mut self.fixups)
    }

    /// Snapshot of the name->id table for downstream consumers (wave 4's
    /// std-domain label harvest) that need name -> (id, explicit) after
    /// this registry itself is dropped: `(name, id, explicit)`. `id` is
    /// `None` once a name has been duplicated away (see [`Self::register`]).
    pub fn nameids_snapshot(&self) -> Vec<(String, Option<String>, bool)> {
        self.nameids
            .iter()
            .map(|(name, entry)| (name.clone(), entry.id.clone(), entry.explicit))
            .collect()
    }

    /// Current value of the `env.new_serialno('index')` counter (see
    /// [`Self::new_index_serialno`]).
    pub fn index_serial(&self) -> u32 {
        self.index_serial
    }
}

/// Post-parse pass: move `name` from `names` to `dupnames` on the node
/// carrying `node_id` (the FIRST occurrence keeps its id, loses its name).
pub fn apply_dupname_fixups(root: &mut Node, fixups: &[DupnameFixup]) {
    if fixups.is_empty() {
        return;
    }
    for fixup in fixups {
        apply_one_fixup(root, fixup);
    }
}

fn apply_one_fixup(node: &mut Node, fixup: &DupnameFixup) -> bool {
    if node.attrs.ids.contains(&fixup.node_id) {
        if let Some(pos) = node.attrs.names.iter().position(|n| *n == fixup.name) {
            node.attrs.names.remove(pos);
            node.attrs.dupnames.push(fixup.name.clone());
        }
        return true;
    }
    node.children
        .iter_mut()
        .any(|child| apply_one_fixup(child, fixup))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::doctree::{kinds, AttrValue, Node, Span};

    /// Python's `str.split()` (what every docutils name normalizer and
    /// `make_id` collapse with) splits on `str.isspace`, which admits the
    /// C0 separators `\x1c`-`\x1f`; Rust's `split_whitespace` does not.
    /// Probed on docutils 0.22.4 (panel fix round D): `.. _a\x1fb:` is the
    /// label `a b` with id `a-b`, and a `Sec\x1fC` title has
    /// `names="sec\ c"`.
    #[test]
    fn name_normalizers_split_on_python_whitespace() {
        assert_eq!(fully_normalize_name("a\x1fb"), "a b");
        assert_eq!(fully_normalize_name("Sec\x1fC"), "sec c");
        assert_eq!(fully_normalize_name("\x1f a \x1c\x1d\x1e b \x1f"), "a b");
        assert_eq!(whitespace_normalize_name("A\x1fB"), "A B");
        assert_eq!(whitespace_normalize_name("\x1fA  B\x1f"), "A B");
        assert_eq!(make_id("a\x1fb"), "a-b");
        assert_eq!(make_id("\x1fa\x1f"), "a");
        assert_eq!(sphinx_make_id("envvar-FOO\x1fBAR"), "envvar-FOO-BAR");
        assert_eq!(sphinx_make_id("\x1fA.b\x1f"), "A.b");
    }

    #[test]
    fn make_id_basics() {
        assert_eq!(make_id("My  Section    Title!"), "my-section-title");
        assert_eq!(make_id("Hello World!"), "hello-world");
        assert_eq!(make_id("1. Intro"), "intro");
        assert_eq!(make_id("2026 report"), "report");
        assert_eq!(make_id("Überblick"), "uberblick");
        assert_eq!(make_id("straße"), "strasze");
        assert_eq!(make_id("!!!"), "");
        assert_eq!(make_id("123"), "");
        assert_eq!(make_id("..."), "");
    }

    /// sphinx's fork keeps case and treats `.`/`_` as identifier
    /// characters, which is why `envvar-HOME_A` survives where docutils'
    /// `make_id` would flatten it to `envvar-home-a`.
    #[test]
    fn sphinx_make_id_keeps_case_dots_and_underscores() {
        assert_eq!(sphinx_make_id("envvar-HOME_A"), "envvar-HOME_A");
        assert_eq!(sphinx_make_id("confval-my_setting"), "confval-my_setting");
        assert_eq!(sphinx_make_id("a.b.C"), "a.b.C");
        // `[^a-zA-Z0-9._]+` collapses to a single '-'.
        assert_eq!(
            sphinx_make_id("cmdoption-myprog---verbose"),
            "cmdoption-myprog-verbose"
        );
        assert_eq!(
            sphinx_make_id("term-source directory"),
            "term-source-directory"
        );
        // `^[-0-9._]+` and `-+$` are stripped; docutils strips only `[-0-9]+`.
        assert_eq!(sphinx_make_id("._-1abc--"), "abc");
        assert_eq!(sphinx_make_id("Überblick"), "Uberblick");
        assert_eq!(sphinx_make_id("!!!"), "");
    }

    #[test]
    fn sphinx_registry_make_id_falls_back_to_a_per_prefix_serial() {
        let mut reg = IdRegistry::new();
        assert_eq!(reg.sphinx_make_id("envvar", "HOME"), "envvar-HOME");
        // Not registered until note_explicit_id, so the same call repeats.
        assert_eq!(reg.sphinx_make_id("envvar", "HOME"), "envvar-HOME");
        reg.note_explicit_id("envvar-HOME");
        assert_eq!(reg.sphinx_make_id("envvar", "HOME"), "envvar-0");
        reg.note_explicit_id("envvar-0");
        assert_eq!(reg.sphinx_make_id("envvar", "HOME"), "envvar-1");
        // A term that collapses to the prefix itself is "not good to
        // generate a node_id" and goes straight to the serial; the counter
        // is per prefix.
        assert_eq!(reg.sphinx_make_id("cmdoption", "!!!"), "cmdoption-0");
    }

    /// The empty-prefix regime the py domain's `make_id(env, doc, '',
    /// fullname)` calls hit (research spec [PY §1.5]): the candidate is the
    /// bare `_make_id(term)` — dots and capitals survive, so the id IS the
    /// fullname — and the serial fallback switches to `id{n}` starting at
    /// `id0` (probe `duplicate_functions`: second `dup` gets `id0`).
    #[test]
    fn sphinx_registry_make_id_empty_prefix_keeps_fullname_and_serials_as_id_n() {
        let mut reg = IdRegistry::new();
        assert_eq!(reg.sphinx_make_id("", "mymod.C.meth"), "mymod.C.meth");
        reg.note_explicit_id("mymod.C.meth");
        assert_eq!(reg.sphinx_make_id("", "mymod.C.meth"), "id0");
        reg.note_explicit_id("id0");
        assert_eq!(reg.sphinx_make_id("", "mymod.C.meth"), "id1");
        // A term whose hash is empty goes straight to the serial; the
        // counter is shared per prefix ('' here), not per term.
        reg.note_explicit_id("id1");
        assert_eq!(reg.sphinx_make_id("", "!!!"), "id2");
        // Empty term likewise.
        reg.note_explicit_id("id2");
        assert_eq!(reg.sphinx_make_id("", ""), "id3");
    }

    #[test]
    fn name_normalization() {
        assert_eq!(
            fully_normalize_name("My  Phrase   Target"),
            "my phrase target"
        );
        assert_eq!(fully_normalize_name("Hello World!"), "hello world!");
        assert_eq!(fully_normalize_name("Überblick"), "überblick");
        assert_eq!(whitespace_normalize_name("A  B"), "A B");
    }

    #[test]
    fn registry_assigns_ids_and_handles_implicit_duplicates() {
        let mut reg = IdRegistry::new();
        let mut s1 = Node::elem(kinds::SECTION, Span::ZERO);
        s1.attrs.names.push("duplicate".into());
        assert!(reg.set_id_implicit(&mut s1, 3, "<snippet>").is_none());
        assert_eq!(s1.attrs.ids, vec!["duplicate"]);

        let mut s2 = Node::elem(kinds::SECTION, Span::ZERO);
        s2.attrs.names.push("duplicate".into());
        let msg = reg
            .set_id_implicit(&mut s2, 7, "<snippet>")
            .expect("dup INFO");
        assert_eq!(s2.attrs.ids, vec!["id1"]);
        assert!(s2.attrs.names.is_empty());
        assert_eq!(s2.attrs.dupnames, vec!["duplicate"]);
        assert_eq!(msg.get("type"), Some(&AttrValue::Str("INFO".into())));
        assert_eq!(msg.get("line"), Some(&AttrValue::Int(7)));
        assert_eq!(msg.attrs.backrefs, vec!["id1"]);

        // The FIRST node's fixup is deferred (it lives in the tree):
        let fixups = reg.take_fixups();
        assert_eq!(
            fixups,
            vec![DupnameFixup {
                name: "duplicate".into(),
                node_id: "duplicate".into()
            }]
        );
        let mut root = Node::elem(kinds::DOCUMENT, Span::ZERO);
        root.children.push(s1);
        apply_dupname_fixups(&mut root, &fixups);
        let s1 = &root.children[0];
        assert!(s1.attrs.names.is_empty());
        assert_eq!(s1.attrs.dupnames, vec!["duplicate"]);
        assert_eq!(s1.attrs.ids, vec!["duplicate"]); // keeps its id
    }

    #[test]
    fn registry_auto_ids_for_unmakeable_names() {
        let mut reg = IdRegistry::new();
        for (i, title) in ["!!!", "123", "..."].iter().enumerate() {
            let mut s = Node::elem(kinds::SECTION, Span::ZERO);
            s.attrs.names.push(fully_normalize_name(title));
            reg.set_id_implicit(&mut s, 1, "<snippet>");
            assert_eq!(s.attrs.ids, vec![format!("id{}", i + 1)]);
            assert_eq!(s.attrs.names.len(), 1); // names kept, no collision
        }
    }

    #[test]
    fn explicit_duplicate_warning_backrefs_only_when_internal() {
        let mut reg = IdRegistry::new();
        let mut t1 = Node::elem(kinds::TARGET, Span::ZERO);
        t1.attrs.names.push("dup".into());
        assert!(reg
            .set_id_explicit(&mut t1, 1, "<snippet>", false, Some("https://1/"))
            .is_none());

        let mut t2 = Node::elem(kinds::TARGET, Span::ZERO);
        t2.attrs.names.push("dup".into());
        let msg = reg
            .set_id_explicit(&mut t2, 3, "<snippet>", false, Some("https://2/"))
            .expect("dup WARNING");
        assert_eq!(msg.get("type"), Some(&AttrValue::Str("WARNING".into())));
        assert!(msg.attrs.backrefs.is_empty()); // external: no backrefs
        assert_eq!(t2.attrs.ids, vec!["id1"]);
        assert_eq!(t2.attrs.dupnames, vec!["dup"]);

        let mut reg = IdRegistry::new();
        let mut i1 = Node::elem(kinds::TARGET, Span::ZERO);
        i1.attrs.names.push("t".into());
        reg.set_id_explicit(&mut i1, 1, "<snippet>", true, None);
        let mut i2 = Node::elem(kinds::TARGET, Span::ZERO);
        i2.attrs.names.push("t".into());
        let msg = reg
            .set_id_explicit(&mut i2, 5, "<snippet>", true, None)
            .expect("dup WARNING");
        assert_eq!(msg.attrs.backrefs, vec!["id1"]); // internal: backrefs
    }
}