badness-parser 0.8.0

Lossless CST parser, semantic model, and command-signature database for LaTeX and BibTeX
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
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
778
779
780
781
782
783
784
785
786
787
788
789
//! Build the per-file label/reference model from the CST.
//!
//! A single whole-tree walk (mirror of `project::collect_include_edges`)
//! collects `\label{…}` definitions, literal `label` options from curated
//! environments, and the reference-command family, then a flat `resolve` pass
//! matches refs to defs by name. Labels live in one document-global namespace,
//! so there is no scope walk—resolution is a flat name match, not a scope-chain
//! resolution.

use std::collections::HashSet;

use smol_str::SmolStr;

use rowan::{NodeOrToken, TextRange, TextSize};

use crate::ast::{
    AstNode, Group, Optional, child, command_name, first_group_range, nth_group_inner,
};
use crate::declarations::ResolvedDeclarations;
use crate::semantic::label::{
    CitationRef, ColorDef, ColorDefKind, GlossaryDef, GlossaryDefKind, LabelDef, LabelRef,
    RefCommand,
};
use crate::semantic::pkgmeta;
use crate::semantic::{SemanticModel, Signatures};
use crate::syntax::{SyntaxKind, SyntaxNode};

pub fn build(root: &SyntaxNode) -> SemanticModel {
    build_with_declarations(root, &ResolvedDeclarations::default())
}

/// Build the semantic model while honoring project-declared ref/cite aliases.
pub fn build_with_declarations(
    root: &SyntaxNode,
    declared: &ResolvedDeclarations,
) -> SemanticModel {
    let mut model = SemanticModel::default();
    let signatures = Signatures::new(declared.as_db());

    for node in root.descendants() {
        if node.kind() == SyntaxKind::BEGIN {
            if let Some(sig) = signatures.environment_at(&node)
                && sig.label_key
                && let Some(optional) = child::<Optional>(&node)
                && let Some(label) = option_label(&optional)
            {
                model.labels.push(label);
            }
            continue;
        }
        if node.kind() != SyntaxKind::COMMAND {
            continue;
        }
        let command = node;
        let Some(name) = command_name(&command) else {
            continue;
        };
        let semantic_name = declared.command_like(&name).unwrap_or(&name);
        // Recorded before the key-collecting arms below, and independently of
        // them: an alias whose first group holds no extractable key still takes a
        // key argument, and the name-based gates must see it.
        if let Some(target) = declared.command_like(&name)
            && key_argument_command(target)
        {
            model
                .declared_key_commands
                .insert(SmolStr::new(name.as_str()));
        }

        if collect_key_command(&mut model, &command, &name, semantic_name) {
            continue;
        } else if pkgmeta::provides_kind(&name).is_some() {
            // Package/class self-identification — first `\Provides…` wins (a file
            // identifies itself once).
            if model.provides.is_none()
                && let Some(decl) = pkgmeta::provides_from_command(&command)
            {
                model.provides = Some(decl);
            }
        } else if name == "NeedsTeXFormat" {
            if model.needs_format.is_none()
                && let Some(decl) = pkgmeta::needs_format_from_command(&command)
            {
                model.needs_format = Some(decl);
            }
        } else if name == "DeclareOption"
            && let Some(decl) = pkgmeta::option_from_command(&command)
        {
            model.options.push(decl);
        }
    }

    resolve(&mut model);
    model
}

#[derive(Clone, Copy)]
enum KeyCommand {
    Label,
    Reference(RefCommand),
    Glossary(GlossaryDefKind),
    Color(ColorDefKind),
    Citation(CiteCommand),
}

fn key_command(name: &str, semantic_name: &str) -> Option<KeyCommand> {
    if name == "label" {
        Some(KeyCommand::Label)
    } else if let Some(kind) = ref_command(semantic_name) {
        Some(KeyCommand::Reference(kind))
    } else if let Some(kind) = glossary_definer(name) {
        Some(KeyCommand::Glossary(kind))
    } else if let Some(kind) = color_definer(name) {
        Some(KeyCommand::Color(kind))
    } else {
        cite_command(semantic_name).map(KeyCommand::Citation)
    }
}

/// Collect one of the key-bearing command families through a shared extraction
/// path. A recognized family returns `true` even when its key is not a flat
/// literal, preventing unrelated command classifiers from seeing it.
fn collect_key_command(
    model: &mut SemanticModel,
    command: &SyntaxNode,
    name: &str,
    semantic_name: &str,
) -> bool {
    let Some(kind) = key_command(name, semantic_name) else {
        return false;
    };
    let Some((inner_range, inner)) = nth_group_inner(command, 0) else {
        return true;
    };
    if matches!(kind, KeyCommand::Citation(CiteCommand::Nocite)) && inner.trim() == "*" {
        model.nocite_all = true;
        return true;
    }

    let split = match kind {
        KeyCommand::Reference(kind) => kind.is_key_list(),
        KeyCommand::Citation(_) => true,
        _ => false,
    };
    for (key, key_range) in key_spans(&inner, inner_range, split) {
        let key = SmolStr::new(key);
        match kind {
            KeyCommand::Label => model.labels.push(LabelDef {
                name: key,
                range: first_group_range(command),
                key_range,
                referenced: false,
            }),
            KeyCommand::Reference(command_kind) => model.refs.push(LabelRef {
                name: key,
                command: command_kind,
                range: command.text_range(),
                key_range,
                resolved: false,
            }),
            KeyCommand::Glossary(kind) => model.glossary_defs.push(GlossaryDef {
                key,
                kind,
                range: first_group_range(command),
                key_range,
            }),
            KeyCommand::Color(kind) => model.color_defs.push(ColorDef {
                name: key,
                kind,
                range: first_group_range(command),
                key_range,
            }),
            KeyCommand::Citation(_) => model.citations.push(CitationRef {
                name: key,
                command: SmolStr::new(name),
                range: command.text_range(),
                key_range,
            }),
        }
    }
    true
}

/// The final top-level `label` entry in an environment options bracket, when its
/// value is a flat literal. Key-value processors apply repeated keys in order, so
/// a later dynamic or empty `label` must also clear an earlier literal rather than
/// leave a definition the source no longer proves.
fn option_label(optional: &Optional) -> Option<LabelDef> {
    let syntax = optional.syntax();
    let base = usize::from(syntax.text_range().start());
    let source = syntax.text().to_string();
    let mut entry_start = base;
    let mut close = None;
    let mut boundaries = Vec::new();

    for element in syntax.children_with_tokens() {
        match element {
            NodeOrToken::Token(token) if token.kind() == SyntaxKind::L_BRACKET => {
                entry_start = usize::from(token.text_range().end());
            }
            NodeOrToken::Token(token) if token.kind() == SyntaxKind::R_BRACKET => {
                close = Some(usize::from(token.text_range().start()));
                break;
            }
            // Nested groups are child nodes, so commas in their text never reach
            // this direct-token stream. A control sequence is a child node too.
            NodeOrToken::Token(token) if token.kind() == SyntaxKind::WORD => {
                let token_start = usize::from(token.text_range().start());
                boundaries.extend(
                    token
                        .text()
                        .match_indices(',')
                        .map(|(i, _)| token_start + i),
                );
            }
            _ => {}
        }
    }

    let close = close?;
    let mut label = None;
    for entry_end in boundaries.into_iter().chain(std::iter::once(close)) {
        match option_label_entry(syntax, &source, base, entry_start, entry_end) {
            LabelEntry::Other => {}
            LabelEntry::Unknown => label = None,
            LabelEntry::Literal(found) => label = Some(found),
        }
        entry_start = entry_end + 1;
    }
    label
}

enum LabelEntry {
    Other,
    /// A `label` key whose value is empty, malformed, or not statically literal.
    Unknown,
    Literal(LabelDef),
}

/// Classify one top-level comma-delimited option entry. The source slices are
/// exact because every boundary comes from the `OPTIONAL` node's own direct token
/// stream; nested brace groups remain whole child nodes.
fn option_label_entry(
    optional: &SyntaxNode,
    source: &str,
    base: usize,
    start: usize,
    end: usize,
) -> LabelEntry {
    let Some((entry, entry_start, entry_end)) = trimmed_source(source, base, start, end) else {
        return LabelEntry::Other;
    };
    let equals = optional
        .children_with_tokens()
        .filter_map(NodeOrToken::into_token)
        .filter(|token| token.kind() == SyntaxKind::WORD)
        .find_map(|token| {
            let token_start = usize::from(token.text_range().start());
            token
                .text()
                .match_indices('=')
                .map(|(i, _)| token_start + i)
                .find(|offset| entry_start <= *offset && *offset < entry_end)
        });
    let Some(equals) = equals else {
        return if entry.trim() == "label" {
            LabelEntry::Unknown
        } else {
            LabelEntry::Other
        };
    };
    if source_slice(source, base, entry_start, equals).trim() != "label" {
        return LabelEntry::Other;
    }
    let Some((_, value_start, value_end)) = trimmed_source(source, base, equals + 1, entry_end)
    else {
        return LabelEntry::Unknown;
    };
    let value_range = TextRange::new(
        TextSize::from(value_start as u32),
        TextSize::from(value_end as u32),
    );

    let mut nodes = optional
        .children()
        .filter(|node| ranges_overlap(node.text_range(), value_range));
    let first_node = nodes.next();
    if nodes.next().is_some() {
        return LabelEntry::Unknown;
    }
    let (name, key_range) = match first_node {
        Some(node) if node.text_range() == value_range => {
            let Some(group) = Group::cast(node) else {
                return LabelEntry::Unknown;
            };
            let Some((inner_range, inner)) = group.inner() else {
                return LabelEntry::Unknown;
            };
            let Some((key, key_range)) = key_spans(&inner, inner_range, false).into_iter().next()
            else {
                return LabelEntry::Unknown;
            };
            (SmolStr::from(key), key_range)
        }
        Some(_) => return LabelEntry::Unknown,
        None => {
            let dynamic = optional
                .children_with_tokens()
                .filter_map(NodeOrToken::into_token)
                .filter(|token| ranges_overlap(token.text_range(), value_range))
                .any(|token| matches!(token.kind(), SyntaxKind::COMMENT | SyntaxKind::HASH));
            if dynamic {
                return LabelEntry::Unknown;
            }
            (
                SmolStr::from(source_slice(source, base, value_start, value_end)),
                value_range,
            )
        }
    };

    LabelEntry::Literal(LabelDef {
        name,
        range: TextRange::new(
            TextSize::from(entry_start as u32),
            TextSize::from(entry_end as u32),
        ),
        key_range,
        referenced: false,
    })
}

fn source_slice(source: &str, base: usize, start: usize, end: usize) -> &str {
    &source[start - base..end - base]
}

/// Trim a source subrange and return its text plus absolute byte bounds.
fn trimmed_source(
    source: &str,
    base: usize,
    start: usize,
    end: usize,
) -> Option<(&str, usize, usize)> {
    let segment = source_slice(source, base, start, end);
    let (trimmed, lo, hi) = trimmed_span(segment)?;
    Some((trimmed, start + lo, start + hi))
}

fn ranges_overlap(left: TextRange, right: TextRange) -> bool {
    left.start() < right.end() && right.start() < left.end()
}

/// The behavior of a curated citation command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CiteCommand {
    /// A command whose first braced argument is a comma-separated citation-key list.
    Cite,
    /// `\nocite`, whose key list additionally accepts the `*` wildcard.
    Nocite,
}

/// The recognized citation command for a control-word name, or `None`.
///
/// This is a closed table because a `cite` prefix does not establish argument
/// semantics: `\citestyle` and `\citetext`, for example, do not take citation
/// keys. Multicite and volume-cite commands are also excluded because their
/// repeated or shifted key groups need a different extractor.
pub fn cite_command(name: &str) -> Option<CiteCommand> {
    Some(match name {
        "nocite" => CiteCommand::Nocite,
        "cite" | "Cite" | "citep" | "Citep" | "citet" | "Citet" | "citealt" | "Citealt"
        | "citealp" | "Citealp" | "citenum" | "citeauthor" | "Citeauthor" | "citefullauthor"
        | "Citefullauthor" | "citeyear" | "citeyearpar" | "citetalias" | "citepalias"
        | "parencite" | "Parencite" | "footcite" | "Footcite" | "footcitetext" | "Footcitetext"
        | "textcite" | "Textcite" | "smartcite" | "Smartcite" | "autocite" | "Autocite"
        | "supercite" | "fullcite" | "footfullcite" | "citetitle" | "Citetitle" | "citedate"
        | "citeurl" | "notecite" | "Notecite" | "pnotecite" | "Pnotecite" | "fnotecite"
        | "Fnotecite" | "citename" | "citelist" | "citefield" => CiteCommand::Cite,
        _ => return None,
    })
}

/// The recognized reference command for a control-word name, or `None`. A small
/// explicit table — the analog of `project::include::include_kind`. Shared with
/// the completion classifier (`crate::completion`) so the ref-family name set has
/// a single source of truth.
pub fn ref_command(name: &str) -> Option<RefCommand> {
    Some(match name {
        "ref" => RefCommand::Ref,
        "pageref" => RefCommand::PageRef,
        "eqref" => RefCommand::EqRef,
        "autoref" => RefCommand::AutoRef,
        "nameref" => RefCommand::NameRef,
        "cref" => RefCommand::Cref,
        "Cref" => RefCommand::CrefUpper,
        "vref" => RefCommand::Vref,
        "Vref" => RefCommand::VrefUpper,
        "cpageref" => RefCommand::CpageRef,
        _ => return None,
    })
}

/// The recognized glossary/acronym *definer* command for a control-word name, or
/// `None`. The definition-side analog of [`ref_command`]; the key is always the
/// first `{…}` group.
pub(crate) fn glossary_definer(name: &str) -> Option<GlossaryDefKind> {
    Some(match name {
        "newglossaryentry"
        | "longnewglossaryentry"
        | "provideglossaryentry"
        | "longprovideglossaryentry" => GlossaryDefKind::Entry,
        "newacronym" => GlossaryDefKind::Acronym,
        "newabbreviation" => GlossaryDefKind::Abbreviation,
        _ => return None,
    })
}

/// The recognized color *definer* command for a control-word name, or `None`.
/// The definition-side analog of [`glossary_definer`]: the newly defined color
/// name is always the first `{…}` group (`\definecolor{name}{model}{spec}`,
/// `\colorlet{name}{base}`).
pub(crate) fn color_definer(name: &str) -> Option<ColorDefKind> {
    Some(match name {
        "definecolor" => ColorDefKind::DefineColor,
        "providecolor" => ColorDefKind::ProvideColor,
        "colorlet" => ColorDefKind::Colorlet,
        _ => return None,
    })
}

/// Whether `name` is a glossary/acronym *reference* command whose first `{…}`
/// group is an entry key (`\gls`, `\acrshort`, `\glsxtrfull`, …). Shared with the
/// completion classifier (`crate::completion`), like [`ref_command`] and
/// [`cite_command`], so the name set has a single source of truth. Unlike
/// citations, every command here takes exactly **one** key per group (no comma
/// list).
pub fn is_glossary_ref_command(name: &str) -> bool {
    // The `\gls` core set: base name + first-letter-uppercase + all-caps
    // sentence-start variants, each with an optional plural `pl`.
    const GLS: &[&str] = &[
        "gls",
        "Gls",
        "GLS",
        "glspl",
        "Glspl",
        "GLSpl",
        // Text-form accessors (`\glstext{key}` prints the entry text without
        // triggering first-use).
        "glstext",
        "Glstext",
        "glsfirst",
        "Glsfirst",
        "glsplural",
        "Glsplural",
        "glsfirstplural",
        "Glsfirstplural",
        "glsdesc",
        "Glsdesc",
        "glsname",
        "Glsname",
        "glssymbol",
        "Glssymbol",
        // Key-first commands with further groups (`\glslink{key}{text}`).
        "glslink",
        "glsdisp",
        "glsadd",
        // glossaries-extra short/long/full accessors.
        "glsxtrshort",
        "Glsxtrshort",
        "glsxtrlong",
        "Glsxtrlong",
        "glsxtrfull",
        "Glsxtrfull",
    ];
    if GLS.contains(&name) {
        return true;
    }
    // The acronym set: `\acrshort`/`\acrlong`/`\acrfull`, plural `pl`, in
    // `acr`/`Acr`/`ACR` casing.
    for stem in ["acr", "Acr", "ACR"] {
        if let Some(rest) = name.strip_prefix(stem) {
            return matches!(
                rest,
                "short" | "shortpl" | "long" | "longpl" | "full" | "fullpl"
            );
        }
    }
    false
}

/// Whether `name` is a command whose arguments hold opaque keys, identifiers, or
/// text rather than typeset math — the `\label`/`\ref`/`\cite`/`\gls`/color
/// families plus `\tag` (amsmath, text content) and `\hyperref` (key plus link
/// text). The union of the family predicates above, kept here so the name sets
/// stay single-sourced; shared with the linter's key-argument gate
/// (`crate::linter::rules::in_key_argument`), which uses it to keep identifier
/// keys like `\label{eq:thing_max}` out of the math-shape rules' scope.
pub fn key_argument_command(name: &str) -> bool {
    matches!(name, "label" | "tag" | "hyperref")
        || ref_command(name).is_some()
        || cite_command(name).is_some()
        || is_glossary_ref_command(name)
        || glossary_definer(name).is_some()
        || color_definer(name).is_some()
}

/// Split a group's inner text into keys paired with their precise byte ranges in
/// the source. When `split` (key-list commands, citations), keys are comma-
/// separated; otherwise the whole inner is one key (`\label`, single-key refs).
/// Surrounding whitespace is trimmed (TeX ignores it around these keys) and empty
/// keys are dropped. `inner_range` is the byte span of `inner`, so each key's range
/// is sliced off it by offset — exact because trimming removes only single-byte
/// ASCII whitespace.
fn key_spans(inner: &str, inner_range: TextRange, split: bool) -> Vec<(&str, TextRange)> {
    let base = inner_range.start();
    let mut out = Vec::new();
    if split {
        // Track each comma-segment's byte offset within `inner` (the segment text
        // plus one byte for the comma that followed it).
        let mut seg_off = 0usize;
        for segment in inner.split(',') {
            if let Some((key, lo, hi)) = trimmed_span(segment) {
                out.push((key, key_range(base, seg_off + lo, seg_off + hi)));
            }
            seg_off += segment.len() + 1;
        }
    } else if let Some((key, lo, hi)) = trimmed_span(inner) {
        out.push((key, key_range(base, lo, hi)));
    }
    out
}

/// The trimmed key of `segment` with its start/end byte offsets *within* `segment`,
/// or `None` when the segment is empty after trimming.
fn trimmed_span(segment: &str) -> Option<(&str, usize, usize)> {
    let key = segment.trim();
    if key.is_empty() {
        return None;
    }
    let lo = segment.len() - segment.trim_start().len();
    Some((key, lo, lo + key.len()))
}

/// Build a [`TextRange`] from `base` plus byte offsets `lo`/`hi`.
fn key_range(base: TextSize, lo: usize, hi: usize) -> TextRange {
    TextRange::new(
        base + TextSize::from(lo as u32),
        base + TextSize::from(hi as u32),
    )
}

/// Flat name-match resolution, indexed by name so duplicate definitions and
/// references remain linear in their combined count.
fn resolve(model: &mut SemanticModel) {
    let label_names: HashSet<_> = model
        .labels
        .iter()
        .map(|label| label.name.clone())
        .collect();
    let mut referenced_names = HashSet::new();
    for reference in &mut model.refs {
        reference.resolved = label_names.contains(&reference.name);
        if reference.resolved {
            referenced_names.insert(reference.name.clone());
        }
    }
    for label in &mut model.labels {
        label.referenced = referenced_names.contains(&label.name);
    }
}

#[cfg(test)]
mod tests {
    use crate::parser::parse;
    use crate::syntax::SyntaxNode;

    use super::{CiteCommand, build, cite_command};

    fn model(src: &str) -> crate::semantic::SemanticModel {
        build(&SyntaxNode::new_root(parse(src).green))
    }

    #[test]
    fn label_key_range_excludes_command_and_braces() {
        let src = "\\label{ sec:intro }\n";
        let model = model(src);
        let def = &model.labels()[0];
        assert_eq!(def.name, "sec:intro");
        assert_eq!(&src[def.key_range], "sec:intro");
    }

    #[test]
    fn curated_environment_options_create_labels() {
        let src = "\\begin{lstlisting}[caption={A, B}, label = { lst:one }]\n\
                   x\n\
                   \\end{lstlisting}\n\
                   \\begin{frame}[fragile,label=frame:one]\n\
                   x\n\
                   \\end{frame}\n\
                   \\ref{lst:one}\\ref{frame:one}\n";
        let model = model(src);
        let labels: Vec<_> = model
            .labels()
            .iter()
            .map(|label| label.name.as_str())
            .collect();
        assert_eq!(labels, vec!["lst:one", "frame:one"]);
        assert!(model.labels().iter().all(|label| label.referenced));
        assert_eq!(&src[model.labels()[0].range], "label = { lst:one }");
        assert_eq!(&src[model.labels()[0].key_range], "lst:one");
        assert_eq!(&src[model.labels()[1].range], "label=frame:one");
        assert_eq!(&src[model.labels()[1].key_range], "frame:one");
    }

    #[test]
    fn only_top_level_literal_label_values_are_collected() {
        let model = model(
            "\\begin{tikzpicture}[label={not:a:latex:label}]\\end{tikzpicture}\n\
             \\begin{lstlisting}[other={label={nested}},label=\\dynamic]\n\
             x\n\
             \\end{lstlisting}\n\
             \\begin{lstlisting}[label={#1}]\n\
             x\n\
             \\end{lstlisting}\n",
        );
        assert!(model.labels().is_empty());
    }

    #[test]
    fn final_valid_label_entry_wins() {
        let src = "\\begin{lstlisting}[label=first,label={second}]\n\
                   x\n\
                   \\end{lstlisting}\n";
        let model = model(src);
        assert_eq!(model.labels().len(), 1);
        assert_eq!(model.labels()[0].name, "second");
        assert_eq!(&src[model.labels()[0].range], "label={second}");
    }

    #[test]
    fn later_dynamic_label_clears_an_earlier_literal() {
        let model = model(
            "\\begin{lstlisting}[label=first,label=\\dynamic]\n\
             x\n\
             \\end{lstlisting}\n",
        );
        assert!(model.labels().is_empty());
    }

    #[test]
    fn parameter_template_keys_are_skipped() {
        let model = model("\\def\\foo#1{\\label{#1}\\eqref{##1}\\cite{#1}}\n");
        assert!(model.labels().is_empty());
        assert!(model.refs().is_empty());
        assert!(model.citations().is_empty());
    }

    #[test]
    fn cref_list_keys_get_isolated_ranges() {
        let src = "\\cref{a,b,c}\n";
        let model = model(src);
        let keys: Vec<_> = model
            .refs()
            .iter()
            .map(|r| (r.name.as_str(), &src[r.key_range]))
            .collect();
        assert_eq!(
            keys,
            vec![("a", "a"), ("b", "b"), ("c", "c")],
            "each key in a list command isolates its own span"
        );
    }

    #[test]
    fn newglossaryentry_key_scanned_with_range() {
        let src = "\\newglossaryentry{ex}{name={example},description={an example}}\n";
        let model = model(src);
        let def = &model.glossary_defs()[0];
        assert_eq!(def.key, "ex");
        assert_eq!(def.kind, crate::semantic::label::GlossaryDefKind::Entry);
        assert_eq!(&src[def.key_range], "ex");
    }

    #[test]
    fn newacronym_optional_arg_does_not_shift_key() {
        let src = "\\newacronym[longplural={frames}]{fps}{FPS}{frame rate}\n";
        let model = model(src);
        let def = &model.glossary_defs()[0];
        assert_eq!(def.key, "fps");
        assert_eq!(def.kind, crate::semantic::label::GlossaryDefKind::Acronym);
        assert_eq!(&src[def.key_range], "fps");
    }

    #[test]
    fn glossary_definer_family_scanned() {
        let src = "\\longnewglossaryentry{a}{name={a}}{desc}\n\\newabbreviation{b}{B}{bee}\n\\provideglossaryentry{c}{name={c}}\n";
        let model = model(src);
        let keys: Vec<_> = model
            .glossary_defs()
            .iter()
            .map(|d| d.key.as_str())
            .collect();
        assert_eq!(keys, vec!["a", "b", "c"]);
    }

    #[test]
    fn glossary_nested_macro_key_skipped() {
        let model = model("\\newacronym{\\foo}{F}{foo}\n");
        assert!(model.glossary_defs().is_empty());
    }

    #[test]
    fn gls_use_is_not_a_definition() {
        let model = model("\\gls{ex}\\acrshort{fps}\n");
        assert!(model.glossary_defs().is_empty());
    }

    #[test]
    fn color_definers_scanned_with_ranges() {
        let src = "\\definecolor{brandblue}{HTML}{0055AA}\n\\colorlet{accent}{brandblue}\n\\providecolor{muted}{gray}{0.5}\n";
        let model = model(src);
        let defs: Vec<_> = model
            .color_defs()
            .iter()
            .map(|d| (d.name.as_str(), d.kind, &src[d.key_range]))
            .collect();
        use crate::semantic::label::ColorDefKind::*;
        assert_eq!(
            defs,
            vec![
                ("brandblue", DefineColor, "brandblue"),
                ("accent", Colorlet, "accent"),
                ("muted", ProvideColor, "muted"),
            ]
        );
    }

    #[test]
    fn textcolor_use_is_not_a_color_definition() {
        let model = model("\\textcolor{red}{x}\\color{blue}\n");
        assert!(model.color_defs().is_empty());
    }

    #[test]
    fn cite_list_keys_get_isolated_ranges() {
        let src = "\\cite{ foo , bar }\n";
        let model = model(src);
        let keys: Vec<_> = model
            .citations()
            .iter()
            .map(|c| (c.name.as_str(), &src[c.key_range]))
            .collect();
        assert_eq!(keys, vec![("foo", "foo"), ("bar", "bar")]);
    }

    #[test]
    fn cite_prefixed_non_citation_commands_are_ignored() {
        let model = model(
            "\\citestyle{authoryear}\\citetext{see \\cite{real}}\\citebox{content}\\citecolor{blue}\n",
        );
        let names: Vec<_> = model
            .citations()
            .iter()
            .map(|citation| citation.name.as_str())
            .collect();
        assert_eq!(names, vec!["real"]);
    }

    #[test]
    fn citation_command_table_is_closed_and_shape_specific() {
        assert_eq!(cite_command("nocite"), Some(CiteCommand::Nocite));
        for name in [
            "cite",
            "Citep",
            "citenum",
            "citetalias",
            "Footcite",
            "Autocite",
            "Citetitle",
            "Pnotecite",
            "citefield",
        ] {
            assert_eq!(cite_command(name), Some(CiteCommand::Cite), "{name}");
        }
        for name in ["citestyle", "citetext", "cites", "volcite", "citebox"] {
            assert_eq!(cite_command(name), None, "{name}");
        }
    }
}