ferro-hgvs 0.4.1

HGVS variant normalizer - part of the ferro bioinformatics toolkit
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
//! Accession parsing
//!
//! Parses reference sequence accessions like NC_000001.11, NM_000088.3,
//! ENST00000012345.1, etc.

use crate::hgvs::variant::Accession;
use memchr::memchr;
use nom::{
    branch::alt,
    bytes::complete::{tag, take_while, take_while1},
    character::complete::digit1,
    combinator::{map, opt},
    sequence::preceded,
    IResult, Parser,
};

/// Parse an accession (e.g., "NM_000088.3" or "ENST00000012345.1" or "GRCh37(chr23)" or "P54802")
/// Optimized with byte-based dispatch to avoid trying all 5 alternatives
#[inline]
pub fn parse_accession(input: &str) -> IResult<&str, Accession> {
    let bytes = input.as_bytes();
    if bytes.is_empty() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Eof,
        )));
    }

    // Dispatch based on first character(s)
    match bytes[0] {
        // Standard RefSeq accessions: NC_, NM_, NP_, NG_, NR_, NW_, NT_, XM_, XR_, XP_
        b'N' | b'X' => {
            // Check for underscore pattern (standard accession)
            if bytes.len() > 2 && bytes[2] == b'_' {
                if let Ok(result) = parse_standard_accession(input) {
                    return Ok(result);
                }
            }
            // Fall through to simple accession
            parse_simple_accession(input)
        }
        // Ensembl accessions: ENST, ENSG, ENSP, ENSE, ENSR
        b'E' => {
            if bytes.len() >= 4 && bytes[1] == b'N' && bytes[2] == b'S' {
                if let Ok(result) = parse_ensembl_accession(input) {
                    return Ok(result);
                }
            }
            parse_simple_accession(input)
        }
        // Assembly notation: GRCh37, GRCh38
        b'G' => {
            if bytes.len() >= 4 && bytes[1] == b'R' && bytes[2] == b'C' && bytes[3] == b'h' {
                if let Ok(result) = parse_assembly_accession(input) {
                    return Ok(result);
                }
            }
            parse_simple_accession(input)
        }
        // Assembly notation: hg18, hg19, hg38
        b'h' => {
            if bytes.len() >= 2 && bytes[1] == b'g' {
                if let Ok(result) = parse_assembly_accession(input) {
                    return Ok(result);
                }
            }
            parse_simple_accession(input)
        }
        // LRG accessions: LRG_XXX
        b'L' => {
            if bytes.len() >= 4 && bytes[1] == b'R' && bytes[2] == b'G' && bytes[3] == b'_' {
                if let Ok(result) = parse_standard_accession(input) {
                    return Ok(result);
                }
            }
            parse_simple_accession(input)
        }
        // Potential UniProt: uppercase letter followed by digits (P54802, Q8TAM1, A0A...)
        b'A'..=b'Z' => {
            // Try UniProt first if second char is digit or looks like UniProt pattern
            if bytes.len() >= 6 && bytes[1].is_ascii_digit() {
                if let Ok(result) = parse_uniprot_accession(input) {
                    return Ok(result);
                }
            }
            // Try standard accession for other letter prefixes (like AC_)
            if bytes.len() > 2 && bytes[2] == b'_' {
                if let Ok(result) = parse_standard_accession(input) {
                    return Ok(result);
                }
            }
            parse_simple_accession(input)
        }
        // Anything else goes to simple accession
        _ => parse_simple_accession(input),
    }
}

// Note: HGVS type prefixes (c., g., n., p., r., m., o.) are checked inline
// using byte matching for better performance - see parse_simple_accession()

/// Check if a character is valid in a SAM reference sequence name.
///
/// Per SAM spec v1, reference names may contain printable ASCII `[!-~]` except:
/// `\ , " ' ( ) [ ] { } < >`
/// Additionally, they cannot start with `*` or `=` (handled separately).
fn is_sam_refname_char(c: char) -> bool {
    // Printable ASCII range: ! (33) to ~ (126)
    let code = c as u32;
    if !(33..=126).contains(&code) {
        return false;
    }
    // Disallowed characters: \ , " ' ( ) [ ] { } < >
    !matches!(
        c,
        '\\' | ',' | '"' | '\'' | '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>'
    )
}

/// Parse a simple chromosome/contig accession using SAM-compatible character restrictions.
///
/// This handles bare reference sequence names like "chr1", "contig", "1", etc.
/// Uses look-ahead to correctly identify the HGVS separator (`:` followed by type prefix).
///
/// SAM spec: Reference names may contain printable ASCII `[!-~]` except `\ , " ' ( ) [ ] { } < >`
/// and cannot start with `*` or `=`. Because `(` is forbidden in SAM refnames, a `(` before
/// the type-prefix colon must be the start of an optional gene/transcript selector
/// (e.g. `MYSEQ(GENE1):c.…`); the accession ends there and `parse_gene_symbol` consumes
/// the selector next.
fn parse_simple_accession(input: &str) -> IResult<&str, Accession> {
    // Check first character: cannot be empty, and cannot start with * or =
    let first_char = input.chars().next().ok_or_else(|| {
        nom::Err::Error(nom::error::Error::new(input, nom::error::ErrorKind::Alpha))
    })?;

    if first_char == '*' || first_char == '=' || !is_sam_refname_char(first_char) {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Alpha,
        )));
    }

    // Find the HGVS separator: a colon followed by a valid type prefix
    // Use memchr for faster byte scanning
    let mut separator_pos = None;
    let mut search_start = 0;
    let input_bytes = input.as_bytes();

    while let Some(colon_offset) = memchr(b':', &input_bytes[search_start..]) {
        let colon_pos = search_start + colon_offset;
        let after_colon = &input_bytes[colon_pos + 1..];

        // Check if this colon is followed by a valid HGVS type prefix (X. format)
        // All prefixes are single letter + dot: c., g., n., p., r., m., o.
        let is_hgvs_prefix = after_colon.len() >= 2
            && after_colon[1] == b'.'
            && matches!(
                after_colon[0],
                b'c' | b'g' | b'n' | b'p' | b'r' | b'm' | b'o'
            );

        if is_hgvs_prefix {
            separator_pos = Some(colon_pos);
            break;
        }

        // Also accept colon followed by digit, '(', or '?' for type-less variants
        // e.g., AL513220.9:40902_43653del, NG_011403.2:(80027_96047)_(99154_121150)del
        // But only if there's no valid type prefix later in the string
        // (to avoid breaking HLA-style accessions like HLA-A*01:01:p.Arg100)
        let is_typeless_variant =
            !after_colon.is_empty() && matches!(after_colon[0], b'0'..=b'9' | b'(' | b'?');

        if is_typeless_variant {
            // Check if there's a type prefix later - if so, skip this colon
            let has_later_type_prefix = after_colon.windows(2).any(|w| {
                w[1] == b'.' && matches!(w[0], b'c' | b'g' | b'n' | b'p' | b'r' | b'm' | b'o')
            });
            if !has_later_type_prefix {
                separator_pos = Some(colon_pos);
                break;
            }
        }

        // This colon is part of the accession name, keep searching
        search_start = colon_pos + 1;
    }

    let separator_pos = separator_pos.ok_or_else(|| {
        nom::Err::Error(nom::error::Error::new(input, nom::error::ErrorKind::Tag))
    })?;

    // See doc comment: '(' before the colon ends the accession (selector boundary).
    let accession_end = memchr(b'(', &input_bytes[..separator_pos]).unwrap_or(separator_pos);

    // Validate all characters in the accession name are SAM-compatible
    let accession_str = &input[..accession_end];
    if accession_str.is_empty() || !accession_str.chars().all(is_sam_refname_char) {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Alpha,
        )));
    }

    // Check for optional version suffix: ".N" at the end where N is digits
    let (name, version) = if let Some(dot_pos) = accession_str.rfind('.') {
        let potential_version = &accession_str[dot_pos + 1..];
        if !potential_version.is_empty() && potential_version.chars().all(|c| c.is_ascii_digit()) {
            let version_num = potential_version.parse::<u32>().ok();
            (&accession_str[..dot_pos], version_num)
        } else {
            (accession_str, None)
        }
    } else {
        (accession_str, None)
    };

    Ok((
        &input[accession_end..],
        Accession::with_style(name.to_string(), String::new(), version, true),
    ))
}

/// Parse a UniProt-style accession (e.g., "P54802", "Q8TAM1", "A0A024R1R8")
///
/// Formats:
/// - 6-char: single letter + 5 alphanumeric (e.g., P54802)
/// - 10-char: letter + digit + letter + 2 alphanumeric + digit + letter + 2 alphanumeric + digit (e.g., A0A024R1R8)
///
/// UniProt accessions don't have versions or underscores
fn parse_uniprot_accession(input: &str) -> IResult<&str, Accession> {
    // Try 10-char format first (longer match)
    if let Ok(result) = parse_uniprot_10char(input) {
        return Ok(result);
    }
    // Fall back to 6-char format
    parse_uniprot_6char(input)
}

/// Parse 6-character UniProt accession (e.g., "P54802", "Q8TAM1")
fn parse_uniprot_6char(input: &str) -> IResult<&str, Accession> {
    let bytes = input.as_bytes();

    // Need at least 6 chars for accession + 3 for ":p." or ":p("
    if bytes.len() < 9 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Eof,
        )));
    }

    // First char must be uppercase letter
    if !bytes[0].is_ascii_uppercase() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Alpha,
        )));
    }

    // Next 5 chars must be alphanumeric
    for &b in &bytes[1..6] {
        if !b.is_ascii_alphanumeric() {
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::AlphaNumeric,
            )));
        }
    }

    // Check what follows (must be ':p.' or ':p(')
    if bytes[6] != b':' || bytes[7] != b'p' || (bytes[8] != b'.' && bytes[8] != b'(') {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    // Safe: all bytes verified as ASCII
    let first = &input[0..1];
    let number_part = &input[1..6];
    Ok((
        &input[6..],
        Accession::with_style(first.to_string(), number_part.to_string(), None, true),
    ))
}

/// Parse 10-character UniProt accession (e.g., "A0A024R1R8")
/// Format: [A-NR-Z][0-9][A-Z][A-Z0-9]{2}[0-9][A-Z][A-Z0-9]{2}[0-9]
fn parse_uniprot_10char(input: &str) -> IResult<&str, Accession> {
    let bytes = input.as_bytes();

    // Need at least 10 chars for accession + 3 for ":p." or ":p("
    if bytes.len() < 13 {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Eof,
        )));
    }

    // First char must be uppercase letter
    if !bytes[0].is_ascii_uppercase() {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Alpha,
        )));
    }

    // Next 9 chars must be alphanumeric
    for &b in &bytes[1..10] {
        if !b.is_ascii_alphanumeric() {
            return Err(nom::Err::Error(nom::error::Error::new(
                input,
                nom::error::ErrorKind::AlphaNumeric,
            )));
        }
    }

    // Check what follows (must be ':p.' or ':p(')
    if bytes[10] != b':' || bytes[11] != b'p' || (bytes[12] != b'.' && bytes[12] != b'(') {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    // Safe: all bytes verified as ASCII
    let first = &input[0..1];
    let number_part = &input[1..10];
    Ok((
        &input[10..],
        Accession::with_style(first.to_string(), number_part.to_string(), None, true),
    ))
}

/// Parse assembly/chromosome notation (e.g., "GRCh37(chr23)")
fn parse_assembly_accession(input: &str) -> IResult<&str, Accession> {
    // Parse assembly name (alphanumeric, e.g., GRCh37, GRCh38, hg19, hg38)
    let (input, assembly) = take_while1(|c: char| c.is_ascii_alphanumeric()).parse(input)?;

    // Must be a recognized assembly name
    if !matches!(
        assembly,
        "GRCh37" | "GRCh38" | "hg19" | "hg38" | "hg18" | "GRCh36"
    ) {
        return Err(nom::Err::Error(nom::error::Error::new(
            input,
            nom::error::ErrorKind::Tag,
        )));
    }

    let (input, _) = tag("(").parse(input)?;
    let (input, chromosome) = take_while1(|c: char| c.is_ascii_alphanumeric()).parse(input)?;
    let (input, _) = tag(")").parse(input)?;

    Ok((
        input,
        Accession::from_assembly(assembly.to_string(), chromosome.to_string()),
    ))
}

/// Parse a standard RefSeq-style accession with underscore (e.g., "NM_000088.3")
/// Also handles compound reference syntax: NC_000013.11(NM_004119.3)
fn parse_standard_accession(input: &str) -> IResult<&str, Accession> {
    let (input, prefix) = parse_prefix(input)?;
    let (input, _) = tag("_").parse(input)?;
    let (input, number) = parse_number(input)?;
    let (input, version) = opt(preceded(tag("."), parse_version)).parse(input)?;

    let outer = Accession::with_style(prefix.to_string(), number.to_string(), version, false);

    // Check for compound reference syntax: outer(inner)
    // Only attempt if the next char is '(' and the content looks like an accession
    // (starts with a letter pattern that could be a RefSeq/Ensembl/LRG accession)
    if let Some(rest) = input.strip_prefix('(') {
        if looks_like_accession_start(rest) {
            if let Ok((after_inner, inner)) = parse_compound_inner(rest) {
                // Reject nested compound refs: inner must not already have a genomic_context
                if inner.genomic_context.is_none() {
                    if let Some(after_close) = after_inner.strip_prefix(')') {
                        return Ok((after_close, inner.with_genomic_context(outer)));
                    }
                }
            }
        }
    }

    Ok((input, outer))
}

/// Check if the input starts with something that looks like an accession
/// (not a gene symbol). Accessions have patterns like NC_, NM_, ENST, LRG_, etc.
fn looks_like_accession_start(input: &str) -> bool {
    let bytes = input.as_bytes();
    if bytes.len() < 3 {
        return false;
    }
    // Standard RefSeq/GenBank: XX_digits (NC_, NM_, NP_, NR_, NG_, NW_, NT_, XM_, XR_, XP_, AC_)
    if bytes.len() > 2
        && bytes[2] == b'_'
        && bytes[0].is_ascii_uppercase()
        && bytes[1].is_ascii_uppercase()
    {
        return true;
    }
    // Ensembl: ENS followed by T/G/P/E/R
    if bytes.len() >= 4 && bytes[0] == b'E' && bytes[1] == b'N' && bytes[2] == b'S' {
        return true;
    }
    // LRG: LRG_
    if bytes.len() >= 4
        && bytes[0] == b'L'
        && bytes[1] == b'R'
        && bytes[2] == b'G'
        && bytes[3] == b'_'
    {
        return true;
    }
    false
}

/// Parse the inner accession of a compound reference (after the opening paren)
fn parse_compound_inner(input: &str) -> IResult<&str, Accession> {
    let bytes = input.as_bytes();
    // Try standard accession (NC_, NM_, etc.)
    if bytes.len() > 2 && bytes[2] == b'_' {
        if let Ok(result) = parse_standard_accession(input) {
            return Ok(result);
        }
    }
    // Try Ensembl
    if bytes.len() >= 4 && bytes[0] == b'E' && bytes[1] == b'N' && bytes[2] == b'S' {
        if let Ok(result) = parse_ensembl_accession(input) {
            return Ok(result);
        }
    }
    Err(nom::Err::Error(nom::error::Error::new(
        input,
        nom::error::ErrorKind::Tag,
    )))
}

/// Parse an Ensembl-style accession without underscore (e.g., "ENST00000012345.1")
fn parse_ensembl_accession(input: &str) -> IResult<&str, Accession> {
    let (input, prefix) = parse_ensembl_prefix(input)?;
    let (input, number) = digit1.parse(input)?;
    let (input, version) = opt(preceded(tag("."), parse_version)).parse(input)?;

    Ok((
        input,
        Accession::with_style(prefix.to_string(), number.to_string(), version, true),
    ))
}

/// Parse Ensembl prefix (ENST, ENSG, ENSP, ENSE, ENSR)
#[inline]
fn parse_ensembl_prefix(input: &str) -> IResult<&str, &str> {
    alt((
        tag("ENST"),
        tag("ENSG"),
        tag("ENSP"),
        tag("ENSE"),
        tag("ENSR"),
    ))
    .parse(input)
}

/// Parse accession prefix (letters like NC, NM, NP, LRG)
#[inline]
fn parse_prefix(input: &str) -> IResult<&str, &str> {
    take_while1(|c: char| c.is_ascii_alphabetic()).parse(input)
}

/// Parse accession number (digits, possibly with embedded letters)
#[inline]
fn parse_number(input: &str) -> IResult<&str, &str> {
    take_while1(|c: char| c.is_ascii_alphanumeric()).parse(input)
}

/// Parse version number
#[inline]
fn parse_version(input: &str) -> IResult<&str, u32> {
    let (remaining, s) = digit1.parse(input)?;
    // Use checked parsing to return error on overflow instead of silent 0
    let version: u32 = s.parse().map_err(|_| {
        nom::Err::Error(nom::error::Error::new(input, nom::error::ErrorKind::Digit))
    })?;
    Ok((remaining, version))
}

/// Parse optional gene symbol in parentheses, e.g., "(COL1A1)"
///
/// Returns None for missing gene symbols or empty parentheses "()"
pub fn parse_gene_symbol(input: &str) -> IResult<&str, Option<String>> {
    opt(map(
        (tag("("), take_while(|c: char| c != ')'), tag(")")),
        |(_, symbol, _): (&str, &str, &str)| {
            // Treat empty strings as None (no gene symbol)
            if symbol.is_empty() {
                None
            } else {
                Some(symbol.to_string())
            }
        },
    ))
    .parse(input)
    .map(|(remaining, opt_opt)| (remaining, opt_opt.flatten()))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_nm_accession() {
        let (remaining, acc) = parse_accession("NM_000088.3:c").unwrap();
        assert_eq!(remaining, ":c");
        assert_eq!(&*acc.prefix, "NM");
        assert_eq!(&*acc.number, "000088");
        assert_eq!(acc.version, Some(3));
        assert!(!acc.ensembl_style);
    }

    #[test]
    fn test_parse_nc_accession() {
        let (remaining, acc) = parse_accession("NC_000001.11:g").unwrap();
        assert_eq!(remaining, ":g");
        assert_eq!(&*acc.prefix, "NC");
        assert_eq!(&*acc.number, "000001");
        assert_eq!(acc.version, Some(11));
        assert!(!acc.ensembl_style);
    }

    #[test]
    fn test_parse_accession_no_version() {
        let (remaining, acc) = parse_accession("NM_000088:c").unwrap();
        assert_eq!(remaining, ":c");
        assert_eq!(acc.version, None);
    }

    #[test]
    fn test_parse_ensembl_transcript() {
        // Standard Ensembl format without underscore
        let (remaining, acc) = parse_accession("ENST00000012345.1:c").unwrap();
        assert_eq!(remaining, ":c");
        assert_eq!(&*acc.prefix, "ENST");
        assert_eq!(&*acc.number, "00000012345");
        assert_eq!(acc.version, Some(1));
        assert!(acc.ensembl_style);
        assert!(acc.is_ensembl());
        // Check display format - should be without underscore
        assert_eq!(acc.full(), "ENST00000012345.1");
    }

    #[test]
    fn test_parse_ensembl_gene() {
        let (remaining, acc) = parse_accession("ENSG00000141510.5:g").unwrap();
        assert_eq!(remaining, ":g");
        assert_eq!(&*acc.prefix, "ENSG");
        assert!(acc.ensembl_style);
        assert_eq!(acc.full(), "ENSG00000141510.5");
    }

    #[test]
    fn test_parse_ensembl_protein() {
        let (remaining, acc) = parse_accession("ENSP00000012345.2:p").unwrap();
        assert_eq!(remaining, ":p");
        assert_eq!(&*acc.prefix, "ENSP");
        assert!(acc.ensembl_style);
    }

    #[test]
    fn test_parse_ensembl_no_version() {
        let (remaining, acc) = parse_accession("ENST00000012345:c").unwrap();
        assert_eq!(remaining, ":c");
        assert_eq!(acc.version, None);
        assert!(acc.ensembl_style);
        assert_eq!(acc.full(), "ENST00000012345");
    }

    #[test]
    fn test_ensembl_validation() {
        // Valid: 11 digits
        let acc =
            Accession::with_style("ENST".to_string(), "00000012345".to_string(), Some(1), true);
        assert!(acc.validate_ensembl());

        // Valid: 15 digits
        let acc = Accession::with_style(
            "ENST".to_string(),
            "000000123456789".to_string(),
            Some(1),
            true,
        );
        assert!(acc.validate_ensembl());

        // Invalid: too few digits (10)
        let acc =
            Accession::with_style("ENST".to_string(), "0000001234".to_string(), Some(1), true);
        assert!(!acc.validate_ensembl());

        // Invalid: too many digits (16)
        let acc = Accession::with_style(
            "ENST".to_string(),
            "0000001234567890".to_string(),
            Some(1),
            true,
        );
        assert!(!acc.validate_ensembl());
    }

    #[test]
    fn test_inferred_variant_type() {
        let acc = Accession::new("NC".to_string(), "000001".to_string(), Some(11));
        assert_eq!(acc.inferred_variant_type(), Some("g"));

        let acc = Accession::new("NM".to_string(), "000088".to_string(), Some(3));
        assert_eq!(acc.inferred_variant_type(), Some("c"));

        let acc = Accession::new("NR".to_string(), "000001".to_string(), Some(1));
        assert_eq!(acc.inferred_variant_type(), Some("n"));

        let acc = Accession::new("NP".to_string(), "000079".to_string(), Some(2));
        assert_eq!(acc.inferred_variant_type(), Some("p"));

        let acc =
            Accession::with_style("ENST".to_string(), "00000012345".to_string(), Some(1), true);
        assert_eq!(acc.inferred_variant_type(), Some("c"));

        let acc =
            Accession::with_style("ENSG".to_string(), "00000141510".to_string(), Some(5), true);
        assert_eq!(acc.inferred_variant_type(), Some("g"));

        let acc =
            Accession::with_style("ENSP".to_string(), "00000012345".to_string(), Some(2), true);
        assert_eq!(acc.inferred_variant_type(), Some("p"));
    }

    #[test]
    fn test_parse_gene_symbol() {
        let (remaining, symbol) = parse_gene_symbol("(COL1A1)c.100").unwrap();
        assert_eq!(remaining, "c.100");
        assert_eq!(symbol, Some("COL1A1".to_string()));
    }

    #[test]
    fn test_parse_no_gene_symbol() {
        let (remaining, symbol) = parse_gene_symbol("c.100").unwrap();
        assert_eq!(remaining, "c.100");
        assert_eq!(symbol, None);
    }

    #[test]
    fn test_parse_simple_accession_chr() {
        // Basic chromosome accession
        let (remaining, acc) = parse_accession("chr1:g.123").unwrap();
        assert_eq!(remaining, ":g.123");
        assert_eq!(&*acc.prefix, "chr1");
        assert_eq!(&*acc.number, "");
        assert_eq!(acc.version, None);
        assert!(acc.ensembl_style); // Uses ensembl_style for no-underscore formatting
        assert_eq!(acc.full(), "chr1");
    }

    #[test]
    fn test_parse_simple_accession_contig() {
        // Bare contig name
        let (remaining, acc) = parse_accession("contig:g.123").unwrap();
        assert_eq!(remaining, ":g.123");
        assert_eq!(&*acc.prefix, "contig");
        assert_eq!(acc.full(), "contig");
    }

    #[test]
    fn test_parse_simple_accession_numeric() {
        // Purely numeric chromosome
        let (remaining, acc) = parse_accession("1:g.123").unwrap();
        assert_eq!(remaining, ":g.123");
        assert_eq!(&*acc.prefix, "1");
        assert_eq!(acc.full(), "1");
    }

    #[test]
    fn test_parse_simple_accession_versioned() {
        // Simple accession with version
        let (remaining, acc) = parse_accession("chr1.2:g.123").unwrap();
        assert_eq!(remaining, ":g.123");
        assert_eq!(&*acc.prefix, "chr1");
        assert_eq!(acc.version, Some(2));
        assert_eq!(acc.full(), "chr1.2");
    }

    #[test]
    fn test_parse_simple_accession_hla_style() {
        // HLA-style accession with internal colons
        let (remaining, acc) = parse_accession("HLA-A*01:01:p.Arg100").unwrap();
        assert_eq!(remaining, ":p.Arg100");
        assert_eq!(&*acc.prefix, "HLA-A*01:01");
        assert_eq!(acc.full(), "HLA-A*01:01");
    }

    #[test]
    fn test_parse_simple_accession_all_types() {
        // Test all HGVS type prefixes
        for type_prefix in ["c.", "g.", "n.", "p.", "r.", "m.", "o."] {
            let input = format!("chr1:{type_prefix}123");
            let (remaining, acc) = parse_accession(&input).unwrap();
            assert_eq!(remaining, format!(":{type_prefix}123"));
            assert_eq!(&*acc.prefix, "chr1");
        }
    }

    #[test]
    fn test_parse_simple_accession_special_chars() {
        // SAM-compatible special characters (no underscore to avoid matching RefSeq pattern)
        let (remaining, acc) = parse_accession("scaffold#1:g.123").unwrap();
        assert_eq!(remaining, ":g.123");
        assert_eq!(&*acc.prefix, "scaffold#1");

        // Pipe character (common in NCBI FASTA headers)
        let (remaining, acc) = parse_accession("gi|12345|ref:g.123").unwrap();
        assert_eq!(remaining, ":g.123");
        assert_eq!(&*acc.prefix, "gi|12345|ref");
    }

    #[test]
    fn test_parse_simple_accession_invalid_start() {
        // Cannot start with * or =
        assert!(parse_accession("*chr1:g.123").is_err());
        assert!(parse_accession("=chr1:g.123").is_err());
    }

    #[test]
    fn test_parse_simple_accession_refseq_still_works() {
        // Ensure RefSeq-style accessions are still parsed by parse_standard_accession
        let (remaining, acc) = parse_accession("NC_000001.11:g.123").unwrap();
        assert_eq!(remaining, ":g.123");
        assert_eq!(&*acc.prefix, "NC");
        assert_eq!(&*acc.number, "000001");
        assert_eq!(acc.version, Some(11));
        assert!(!acc.ensembl_style); // RefSeq uses underscore style
    }

    // =========================================================================
    // Compound reference syntax: NC_000013.11(NM_004119.3):c.…
    // =========================================================================

    #[test]
    fn test_parse_compound_ref_nc_nm() {
        // Genomic context NC with transcript NM
        let (remaining, acc) =
            parse_accession("NC_000013.11(NM_004119.3):c.1837+2_1837+3insA").unwrap();
        assert_eq!(remaining, ":c.1837+2_1837+3insA");
        // The primary accession is the transcript (inner)
        assert_eq!(&*acc.prefix, "NM");
        assert_eq!(&*acc.number, "004119");
        assert_eq!(acc.version, Some(3));
        // Genomic context stores the outer accession
        let ctx = acc
            .genomic_context
            .as_ref()
            .expect("should have genomic context");
        assert_eq!(&*ctx.prefix, "NC");
        assert_eq!(&*ctx.number, "000013");
        assert_eq!(ctx.version, Some(11));
    }

    #[test]
    fn test_parse_compound_ref_nc_nr() {
        // Genomic context with non-coding RNA transcript
        let (remaining, acc) = parse_accession("NC_000001.11(NR_046018.2):n.100A>G").unwrap();
        assert_eq!(remaining, ":n.100A>G");
        assert_eq!(&*acc.prefix, "NR");
        assert_eq!(&*acc.number, "046018");
        assert_eq!(acc.version, Some(2));
        assert!(acc.genomic_context.is_some());
    }

    #[test]
    fn test_parse_compound_ref_nc_np() {
        // Genomic context with protein accession
        let (remaining, acc) = parse_accession("NC_000013.11(NP_004110.2):p.Val600Glu").unwrap();
        assert_eq!(remaining, ":p.Val600Glu");
        assert_eq!(&*acc.prefix, "NP");
        assert!(acc.genomic_context.is_some());
    }

    #[test]
    fn test_parse_compound_ref_ng_nm() {
        // NG (gene region) context with transcript
        let (remaining, acc) = parse_accession("NG_007400.1(NM_000088.3):c.459A>G").unwrap();
        assert_eq!(remaining, ":c.459A>G");
        assert_eq!(&*acc.prefix, "NM");
        let ctx = acc.genomic_context.as_ref().unwrap();
        assert_eq!(&*ctx.prefix, "NG");
    }

    #[test]
    fn test_parse_compound_ref_no_version_outer() {
        // Outer accession without version
        let (remaining, acc) = parse_accession("NC_000013(NM_004119.3):c.100A>G").unwrap();
        assert_eq!(remaining, ":c.100A>G");
        assert_eq!(&*acc.prefix, "NM");
        let ctx = acc.genomic_context.as_ref().unwrap();
        assert_eq!(ctx.version, None);
    }

    #[test]
    fn test_parse_compound_ref_no_version_inner() {
        // Inner accession without version
        let (remaining, acc) = parse_accession("NC_000013.11(NM_004119):c.100A>G").unwrap();
        assert_eq!(remaining, ":c.100A>G");
        assert_eq!(acc.version, None);
        assert!(acc.genomic_context.is_some());
    }

    #[test]
    fn test_parse_compound_ref_display_roundtrip() {
        // Accession Display should produce the compound format
        let (_, acc) = parse_accession("NC_000013.11(NM_004119.3):c.100A>G").unwrap();
        assert_eq!(acc.full(), "NC_000013.11(NM_004119.3)");
        assert_eq!(acc.base(), "NC_000013.11(NM_004119)");
    }

    #[test]
    fn test_parse_compound_ref_does_not_break_gene_symbol() {
        // A bare NC accession followed by a gene symbol should still work
        // NC_000013.11(FLT3):g.… — (FLT3) is a gene symbol, not a compound ref
        // This is handled at the variant parsing level, not at accession level
        let (remaining, acc) = parse_accession("NC_000013.11:g.100A>G").unwrap();
        assert_eq!(remaining, ":g.100A>G");
        assert_eq!(&*acc.prefix, "NC");
        assert!(acc.genomic_context.is_none());
    }

    #[test]
    fn test_parse_compound_ref_ensembl_inner() {
        // Genomic context with Ensembl transcript
        let (remaining, acc) = parse_accession("NC_000013.11(ENST00000241453.7):c.100A>G").unwrap();
        assert_eq!(remaining, ":c.100A>G");
        assert_eq!(&*acc.prefix, "ENST");
        assert!(acc.is_ensembl());
        assert!(acc.genomic_context.is_some());
    }

    #[test]
    fn test_parse_compound_ref_lrg_outer() {
        // LRG as outer context
        let (remaining, acc) = parse_accession("LRG_1(NM_000088.3):c.459A>G").unwrap();
        assert_eq!(remaining, ":c.459A>G");
        assert_eq!(&*acc.prefix, "NM");
        let ctx = acc.genomic_context.as_ref().unwrap();
        assert_eq!(&*ctx.prefix, "LRG");
    }

    #[test]
    fn test_parse_nested_compound_ref_rejected() {
        // Nested compound refs like NC_...(NG_...(NM_...)) should not be accepted
        // The inner accession should not already carry a genomic_context
        let (remaining, acc) =
            parse_accession("NC_000013.11(NG_000001.1(NM_004119.3)):c.100A>G").unwrap();
        // Should parse NC_000013.11 as a bare accession, not as a compound
        // because the inner itself is compound (NG wrapping NM) which is rejected
        assert!(
            acc.genomic_context.is_none(),
            "nested compound refs should be rejected, got: {}",
            acc.full()
        );
        assert_eq!(&*acc.prefix, "NC");
        assert!(remaining.starts_with('('));
    }

    // =========================================================================
    // Gene selectors on non-RefSeq accessions (issue #69)
    // =========================================================================

    #[test]
    fn test_parse_simple_accession_with_gene_selector() {
        // Bare accession not matching the RefSeq XX_digits pattern should still
        // accept an optional gene/transcript selector in parentheses.
        let (remaining, acc) = parse_accession("MYSEQ(1):c.100A>G").unwrap();
        assert_eq!(remaining, "(1):c.100A>G");
        assert_eq!(&*acc.prefix, "MYSEQ");
        assert_eq!(acc.version, None);
    }

    #[test]
    fn test_parse_simple_accession_with_gene_selector_dashed() {
        let (remaining, acc) = parse_accession("MY-SEQ(GENE1):c.100A>G").unwrap();
        assert_eq!(remaining, "(GENE1):c.100A>G");
        assert_eq!(&*acc.prefix, "MY-SEQ");
    }

    #[test]
    fn test_parse_simple_accession_with_underscore_and_selector() {
        // An accession with an underscore that does not match the strict RefSeq
        // 2-letter prefix shape (e.g. MYREF_SEQ vs NM_…). Falls through to the
        // simple-accession path and must still accept a selector.
        let (remaining, acc) = parse_accession("MYREF_SEQ(1):c.100A>G").unwrap();
        assert_eq!(remaining, "(1):c.100A>G");
        assert_eq!(&*acc.prefix, "MYREF_SEQ");
    }

    #[test]
    fn test_parse_hgvs_simple_accession_with_selector_end_to_end() {
        // End-to-end via the public parser: a non-RefSeq accession with a gene
        // selector should parse, retain the bare accession, and capture the
        // selector as gene_symbol. (Display does not currently re-emit the
        // selector for any accession kind, matching existing RefSeq behavior.)
        use crate::hgvs::parser::parse_hgvs;
        use crate::hgvs::variant::HgvsVariant;
        let variant = parse_hgvs("MYREF_SEQ(1):c.100A>G").unwrap();
        let cds = match variant {
            HgvsVariant::Cds(v) => v,
            other => panic!("expected CdsVariant, got {other:?}"),
        };
        assert_eq!(&*cds.accession.prefix, "MYREF_SEQ");
        assert_eq!(cds.gene_symbol.as_deref(), Some("1"));
    }

    #[test]
    fn test_parse_hgvs_simple_accession_with_selector_protein() {
        // Outer parens are the selector; the inner :p.(...) is the predicted form.
        use crate::hgvs::parser::parse_hgvs;
        use crate::hgvs::variant::HgvsVariant;
        let variant = parse_hgvs("MYREF_SEQ(1):p.(Arg8Gln)").unwrap();
        let prot = match variant {
            HgvsVariant::Protein(v) => v,
            other => panic!("expected ProteinVariant, got {other:?}"),
        };
        assert_eq!(&*prot.accession.prefix, "MYREF_SEQ");
        assert_eq!(prot.gene_symbol.as_deref(), Some("1"));
    }
}