litext 1.3.0

Seamless proc-macro literal extraction.
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
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
use crate::literal::LitStr;

use std::{fmt::Display, str::FromStr};

use proc_macro2::{Ident, Literal, Span, TokenStream};

#[doc(hidden)]
mod __private {
    pub trait IntegerSeal {
        fn is_signed() -> bool {
            false
        }
    }
    pub trait FloatSeal {}

    impl IntegerSeal for i8 {
        fn is_signed() -> bool {
            true
        }
    }
    impl IntegerSeal for i16 {
        fn is_signed() -> bool {
            true
        }
    }
    impl IntegerSeal for i32 {
        fn is_signed() -> bool {
            true
        }
    }
    impl IntegerSeal for i64 {
        fn is_signed() -> bool {
            true
        }
    }
    impl IntegerSeal for i128 {
        fn is_signed() -> bool {
            true
        }
    }
    impl IntegerSeal for isize {
        fn is_signed() -> bool {
            true
        }
    }
    impl IntegerSeal for u8 {}
    impl IntegerSeal for u16 {}
    impl IntegerSeal for u32 {}
    impl IntegerSeal for u64 {}
    impl IntegerSeal for u128 {}
    impl IntegerSeal for usize {}

    impl FloatSeal for f32 {}
    impl FloatSeal for f64 {}
}

/// Converts literal tokens into typed values.
///
/// This trait is the core extension point for `litext`. Implementing it enables
/// `litext!(input as MyType)` to work for custom types.
///
/// # Implementations
///
/// The trait is automatically implemented for all built-in literal types:
/// - Strings: [`String`], [`LitStr`]
/// - Integers: `i8`–`i128`, `isize`, `u8`–`u128`, `usize`, [`LitInt<T>`]
/// - Floats: `f32`, `f64`, [`LitFloat<T>`]
/// - Characters: [`char`], [`LitChar`]
/// - Booleans: [`bool`], [`LitBool`]
/// - Bytes: `u8`, [`LitByte`], `Vec<u8>`, [`LitByteStr`]
/// - C Strings: [`CString`], [`LitCStr`]
///
/// # Method Overview
///
/// - [`from_lit`](Self::from_lit) handles literal tokens (`"hello"`, `42`, `3.14`)
/// - [`from_ident`](Self::from_ident) handles identifier tokens (`true`, `false`)
/// - [`from_negative_lit`](Self::from_negative_lit) handles negative literals (`-42`)
///
/// Override `from_ident` for types represented as identifiers (like `bool`).
/// Override `from_negative_lit` for signed numeric types. The default
/// implementations return errors, which is correct for non-numeric types.
///
/// # Example
///
/// ```ignore
/// use litext::literal::FromLit;
/// use proc_macro2::{Literal, TokenStream};
///
/// pub struct UpperString(String);
///
/// impl FromLit for UpperString {
///     fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
///         let s = String::from_lit(lit)?;
///         Ok(UpperString(s.to_uppercase()))
///     }
/// }
///
/// // Then in your macro:
/// // let val: UpperString = litext!(input as UpperString);
/// ```
///
/// # See Also
///
/// - [`crate::extract`] for the function that drives extraction
/// - [`ToTokens`](super::ToTokens) for the reverse direction
pub trait FromLit: Sized {
    /// Attempts to extract a value from a [`Literal`] token.
    ///
    /// On success, returns `Ok` containing the extracted value.
    ///
    /// # Errors
    ///
    /// On failure, returns `Err` containing a `TokenStream` that triggers a
    /// compile error when returned from a proc-macro.
    fn from_lit(lit: Literal) -> Result<Self, TokenStream>;

    /// Attempts to extract a value from an [`Ident`] token.
    ///
    /// Most types will never receive an ident, the default implementation
    /// returns an error. Override this for types like `bool` where the
    /// literal representation is an identifier (`true`, `false`).
    ///
    /// # Errors
    ///
    /// Errors to this function is in the form of a `compile_error!()` token stream, the cause
    /// completely up to the implementer.
    #[inline]
    fn from_ident(ident: Ident) -> Result<Self, TokenStream> {
        Err(comperr::error(
            ident.span(),
            format!("expected a literal, found identifier `{ident}`"),
        ))
    }

    /// Attempts to extract a value from a negative [`Literal`] token.
    ///
    /// A 'negative Literal' token in this case is the negative number,
    /// a dash punctuation followed by a number. Most types won't accept or receive
    /// a negative literal. Override this for signed integer / float types where it accepts negatives
    /// as a value.
    ///
    /// # Errors
    ///
    /// Errors to this function is in the form of a `compile_error!()` token stream, the cause
    /// completely up to the implementer.
    #[inline]
    fn from_negative_lit(lit: Literal) -> Result<Self, TokenStream> {
        Err(comperr::error(lit.span(), "unexpected negative literal"))
    }
}

/// Strips integer type suffixes and prefix notation from a raw integer literal string.
///
/// Returns `Some((digits, radix, suffix))` where digits are the base-N digits with
/// underscores removed, radix is 2/8/10/16, and suffix is the optional type suffix
/// like `"u8"` or `"i32"`. Returns `None` for malformed input.
fn parse_int_raw(raw: &str) -> Option<(String, u32, Option<String>)> {
    let suffixes = [
        "i8", "i16", "i32", "i64", "i128", "isize", "u8", "u16", "u32", "u64", "u128", "usize",
    ];
    let mut s = raw;
    let mut found_suffix: Option<String> = None;
    for suffix in suffixes {
        if let Some(stripped) = s.strip_suffix(suffix) {
            s = stripped;
            found_suffix = Some(suffix.to_string());
            break;
        }
    }

    let (digits, radix) = if let Some(rest) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X"))
    {
        (rest, 16)
    } else if let Some(rest) = s.strip_prefix("0o").or_else(|| s.strip_prefix("0O")) {
        (rest, 8)
    } else if let Some(rest) = s.strip_prefix("0b").or_else(|| s.strip_prefix("0B")) {
        (rest, 2)
    } else {
        (s, 10)
    };

    let cleaned: String = if digits.contains('_') {
        let s: String = digits.chars().filter(|c| *c != '_').collect();
        if s.is_empty() {
            return None;
        }
        s
    } else {
        if digits.is_empty() {
            return None;
        }
        digits.to_string()
    };
    Some((cleaned, radix, found_suffix))
}

/// Strips the optional float type suffix (`f32`/`f64`) and underscore separators.
fn parse_float_raw(raw: &str) -> (String, Option<String>) {
    let suffixes = ["f32", "f64"];
    let mut s = raw;
    let mut found_suffix: Option<String> = None;
    for suffix in suffixes {
        if let Some(stripped) = s.strip_suffix(suffix) {
            s = stripped;
            found_suffix = Some(suffix.to_string());
            break;
        }
    }
    let cleaned = if s.contains('_') {
        s.chars().filter(|c| *c != '_').collect()
    } else {
        s.to_string()
    };
    (cleaned, found_suffix)
}

// ---------------------------------------------------------------------------
// Strings
// ---------------------------------------------------------------------------

impl FromLit for String {
    #[inline]
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        crate::parse_lit(&lit)
    }
}

impl FromLit for LitStr {
    #[inline]
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        let span = lit.span();
        let value = crate::parse_lit(&lit)?;
        Ok(Self::new(value, span))
    }
}

// ---------------------------------------------------------------------------
// LitInt
// ---------------------------------------------------------------------------

/// A parsed integer literal bundled with its source location.
///
/// Use `LitInt<T>` when you need the span for diagnostics. The type parameter
/// `T` must be one of the sealed integer types:
/// - Signed: `i8`, `i16`, `i32`, `i64`, `i128`, `isize`
/// - Unsigned: `u8`, `u16`, `u32`, `u64`, `u128`, `usize`
///
/// Defaults to `i32` when using `LitInt` without a type parameter.
///
/// # Supported Formats
///
/// | Format | Example |
/// |--------|---------|
/// | Decimal | `42` |
/// | Hexadecimal | `0xFF`, `0XFF` |
/// | Octal | `0o77`, `0O77` |
/// | Binary | `0b1010`, `0B1010` |
/// | Underscores | `1_000_000` |
/// | Type suffix | `42u8`, `255i32` |
///
/// Overflow triggers a compile error.
///
/// # Example
///
/// ```ignore
/// use litext::{litext, TokenStream};
/// use litext::literal::LitInt;
///
/// pub fn my_macro(input: TokenStream) -> TokenStream {
///     let lit: LitInt<u8> = litext!(input as LitInt<u8>);
///     if *lit.value() == 0 {
///         return comperr::error(lit.span(), "value cannot be zero");
///     }
///     quote::quote! { /* use lit.value() */ }
/// }
/// ```
pub struct LitInt<T: __private::IntegerSeal = i32> {
    /// The parsed integer value.
    pub value: T,
    /// The source location of the literal.
    pub span: Span,
    /// The type suffix if explicitly written, e.g. `Some("u8")` for `42u8`,
    /// or `None` for `42`.
    pub suffix: Option<String>,
}

impl<T> LitInt<T>
where
    T: __private::IntegerSeal,
{
    /// Creates a new [`LitInt`] from a value and a span.
    pub const fn new(value: T, span: Span, suffix: Option<String>) -> Self {
        Self {
            value,
            span,
            suffix,
        }
    }

    /// Returns the parsed integer value.
    pub const fn value(&self) -> &T {
        &self.value
    }

    /// Returns the source span of the literal.
    pub const fn span(&self) -> Span {
        self.span
    }

    /// Returns the explicit type suffix if present.
    ///
    /// For `42u8` this returns `Some("u8")`.
    /// For `42` this returns `None`.
    pub fn suffix(&self) -> Option<&str> {
        self.suffix.as_deref()
    }
}

impl<T> FromLit for LitInt<T>
where
    T: TryFrom<u128> + TryFrom<i128> + __private::IntegerSeal,
    <T as TryFrom<u128>>::Error: Display,
    <T as TryFrom<i128>>::Error: Display,
{
    #[inline]
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        let span = lit.span();
        let raw = lit.to_string();
        let (digits, radix, suffix) =
            parse_int_raw(&raw).ok_or_else(|| comperr::error(span, "malformed integer literal"))?;

        let value: T = if let Ok(n) = u128::from_str_radix(&digits, radix) {
            T::try_from(n)
                .map_err(|e| comperr::error(span, format!("integer out of range: {e}")))?
        } else if let Ok(n) = i128::from_str_radix(&digits, radix) {
            T::try_from(n)
                .map_err(|e| comperr::error(span, format!("integer out of range: {e}")))?
        } else {
            return Err(comperr::error(span, "malformed integer literal"));
        };

        Ok(Self::new(value, span, suffix))
    }

    #[inline]
    // use of allow: the function checked for all possible failures that clippy::pedantic is being pedantic about
    #[allow(clippy::cast_sign_loss, clippy::cast_possible_wrap)]
    fn from_negative_lit(lit: Literal) -> Result<Self, TokenStream> {
        if !T::is_signed() {
            return Err(comperr::error(
                lit.span(),
                "cannot negate an unsigned integer",
            ));
        }
        let span = lit.span();
        let raw = lit.to_string();
        let (digits, radix, suffix) =
            parse_int_raw(&raw).ok_or_else(|| comperr::error(span, "malformed integer literal"))?;
        let n = u128::from_str_radix(&digits, radix)
            .map_err(|_| comperr::error(span, "malformed integer literal"))?;
        let negated = if n == (i128::MIN as u128) {
            i128::MIN
        } else if n > (i128::MAX as u128) {
            return Err(comperr::error(span, "integer out of range"));
        } else {
            -(n as i128)
        };
        let value = T::try_from(negated)
            .map_err(|e| comperr::error(span, format!("integer out of range: {e}")))?;
        Ok(Self::new(value, span, suffix))
    }
}

// ---------------------------------------------------------------------------
// Plain integer impls
// ---------------------------------------------------------------------------

macro_rules! impl_from_lit_int_signed {
    ($($t:ty),*) => {
        $(impl FromLit for $t {
            #[inline]
            fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
                Ok(LitInt::<$t>::from_lit(lit)?.value)
            }
            #[inline]
            fn from_negative_lit(lit: Literal) -> Result<Self, TokenStream> {
                Ok(LitInt::<$t>::from_negative_lit(lit)?.value)
            }
        })*
    };
}

macro_rules! impl_from_lit_int_unsigned {
    ($($t:ty),*) => {
        $(impl FromLit for $t {
            #[inline]
            fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
                Ok(LitInt::<$t>::from_lit(lit)?.value)
            }
            #[inline]
            fn from_negative_lit(lit: Literal) -> Result<Self, TokenStream> {
                Err(comperr::error(lit.span(), "cannot negate an unsigned integer"))
            }
        })*
    };
}

impl_from_lit_int_signed!(i8, i16, i32, i64, i128, isize);
impl_from_lit_int_unsigned!(u16, u32, u64, u128, usize);

impl FromLit for u8 {
    #[inline]
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        let raw = lit.to_string();
        if raw.starts_with("b'") {
            let span = lit.span();
            let inner = raw
                .strip_prefix("b'")
                .and_then(|s| s.strip_suffix('\''))
                .ok_or_else(|| comperr::error(span, "expected a byte literal"))?;
            let bytes = crate::unescape_bytes(inner, span)?;
            if bytes.len() != 1 {
                return Err(comperr::error(span, "invalid byte literal"));
            }
            return Ok(bytes[0]);
        }
        Ok(*LitInt::<Self>::from_lit(lit)?.value())
    }

    #[inline]
    fn from_negative_lit(lit: Literal) -> Result<Self, TokenStream> {
        Err(comperr::error(
            lit.span(),
            "cannot negate an unsigned integer",
        ))
    }
}

// ---------------------------------------------------------------------------
// LitFloat
// ---------------------------------------------------------------------------

/// A parsed float literal bundled with its source location.
///
/// Use `LitFloat<T>` when you need the span for diagnostics. `T` must be
/// `f32` or `f64`. Defaults to `f64`.
///
/// # Supported Formats
///
/// | Format | Example |
/// |--------|---------|
/// | Standard | `3.14`, `3.0` |
/// | Scientific | `1e10`, `2.5e-3`, `1E10` |
/// | Underscores | `1_000.5` |
/// | Type suffix | `3.14f32`, `1e10f64` |
///
/// Parsing delegates to `T::from_str`.
///
/// # Example
///
/// ```ignore
/// use litext::{litext, TokenStream};
/// use litext::literal::LitFloat;
///
/// pub fn my_macro(input: TokenStream) -> TokenStream {
///     let lit: LitFloat<f32> = litext!(input as LitFloat<f32>);
///     if *lit.value() < 0.0 {
///         return comperr::error(lit.span(), "expected non-negative float");
///     }
///     quote::quote! { /* use lit.value() */ }
/// }
/// ```
pub struct LitFloat<T: __private::FloatSeal = f64> {
    /// The parsed float value.
    pub value: T,
    /// The source location of the literal.
    pub span: Span,
    /// The type suffix if explicitly written, e.g. `Some("f32")` for `3.14f32`,
    /// or `None` for `3.14`.
    pub suffix: Option<String>,
}
impl<T> LitFloat<T>
where
    T: __private::FloatSeal,
{
    /// Creates a new [`LitFloat`] from a value and a span.
    pub const fn new(value: T, span: Span, suffix: Option<String>) -> Self {
        Self {
            value,
            span,
            suffix,
        }
    }

    /// Returns the parsed float value.
    pub const fn value(&self) -> &T {
        &self.value
    }

    /// Returns the source span of the literal.
    pub const fn span(&self) -> Span {
        self.span
    }

    /// Returns the explicit type suffix if present.
    ///
    /// For `42f32` this returns `Some("f32")`.
    /// For `42.0` this returns `None`.
    pub fn suffix(&self) -> Option<&str> {
        self.suffix.as_deref()
    }
}

impl<T> FromLit for LitFloat<T>
where
    T: __private::FloatSeal + std::ops::Neg<Output = T>,
    T: FromStr,
    T::Err: Display,
{
    #[inline]
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        let span = lit.span();
        let raw = lit.to_string();
        let (cleaned, suffix) = parse_float_raw(&raw);
        let value = cleaned
            .parse::<T>()
            .map_err(|e| comperr::error(span, format!("malformed float literal: {e}")))?;
        Ok(Self::new(value, span, suffix))
    }

    #[inline]
    fn from_negative_lit(lit: Literal) -> Result<Self, TokenStream> {
        let span = lit.span();
        let raw = lit.to_string();
        let (cleaned, suffix) = parse_float_raw(&raw);
        let value = cleaned
            .parse::<T>()
            .map_err(|e| comperr::error(span, format!("litext: malformed float literal: {e}")))?;
        Ok(Self::new(-value, span, suffix))
    }
}

// ---------------------------------------------------------------------------
// float impls
// ---------------------------------------------------------------------------

macro_rules! impl_from_lit_float {
    ($($t:ty),*) => {
        $(impl FromLit for $t {
            #[inline]
            fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
                Ok(LitFloat::<$t>::from_lit(lit)?.value)
            }
            #[inline]
            fn from_negative_lit(lit: Literal) -> Result<Self, TokenStream> {
                Ok(LitFloat::<$t>::from_negative_lit(lit)?.value)
            }
        })*
    };
}

impl_from_lit_float!(f32, f64);

// ---------------------------------------------------------------------------
// LitBool
// ---------------------------------------------------------------------------

/// A parsed boolean literal bundled with its source location.
///
/// `true` and `false` are identifier tokens in Rust's token stream, not literal
/// tokens. The [`FromLit`] implementation overrides [`FromLit::from_ident`] to handle
/// them. [`FromLit::from_lit`] always returns an error.
///
/// Use `LitBool` when you need the span. Use `bool` when you only need the value.
///
/// # Example
///
/// ```ignore
/// use litext::{litext, TokenStream};
/// use litext::literal::LitBool;
///
/// pub fn my_macro(input: TokenStream) -> TokenStream {
///     let lit: LitBool = litext!(input as LitBool);
///     if !lit.value() {
///         return comperr::error(lit.span(), "feature must be enabled");
///     }
///     quote::quote! { /* use lit.value() */ }
/// }
/// ```
pub struct LitBool {
    /// The parsed boolean value.
    pub value: bool,
    /// The source location of the literal.
    pub span: Span,
}

impl LitBool {
    /// Creates a new [`LitBool`] from a value and a span.
    #[must_use]
    pub const fn new(value: bool, span: Span) -> Self {
        Self { value, span }
    }

    /// Returns the parsed boolean value.
    #[must_use]
    pub const fn value(&self) -> bool {
        self.value
    }

    /// Returns the source span of the literal.
    #[must_use]
    pub const fn span(&self) -> Span {
        self.span
    }
}

impl FromLit for LitBool {
    #[inline]
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        Err(comperr::error(
            lit.span(),
            "expected `true` or `false`, found a literal",
        ))
    }

    #[inline]
    fn from_ident(ident: Ident) -> Result<Self, TokenStream> {
        let span = ident.span();
        match ident.to_string().as_str() {
            "true" => Ok(Self::new(true, span)),
            "false" => Ok(Self::new(false, span)),
            other => Err(comperr::error(
                span,
                format!("expected `true` or `false`, found `{other}`"),
            )),
        }
    }
}

impl FromLit for bool {
    #[inline]
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        Err(comperr::error(
            lit.span(),
            "expected `true` or `false`, found a literal",
        ))
    }

    #[inline]
    fn from_ident(ident: Ident) -> Result<Self, TokenStream> {
        let span = ident.span();
        match ident.to_string().as_str() {
            "true" => Ok(true),
            "false" => Ok(false),
            other => Err(comperr::error(
                span,
                format!("expected `true` or `false`, found `{other}`"),
            )),
        }
    }
}

// ---------------------------------------------------------------------------
// LitChar
// ---------------------------------------------------------------------------

/// A parsed character literal bundled with its source location.
///
/// Escape sequences are resolved during extraction. The extracted [`value`](Self::value)
/// is always a single valid Unicode `char`.
///
/// # Supported Formats
///
/// | Format | Example |
/// |--------|---------|
/// | Regular character | `'a'`, `'z'` |
/// | Escape sequences | `'\n'`, `'\r'`, `'\t'`, `'\\'`, `'\''`, `'\"'`, `'\0'` |
/// | Hex escape | `'\x41'` (ASCII) |
/// | Unicode escape | `'\u{1F600}'` (emoji) |
///
/// The Rust tokenizer validates escape sequences before litext processes them.
///
/// # Example
///
/// ```ignore
/// use litext::{litext, TokenStream};
/// use litext::literal::LitChar;
///
/// pub fn my_macro(input: TokenStream) -> TokenStream {
///     let lit: LitChar = litext!(input as LitChar);
///     if lit.value().is_control() {
///         return comperr::error(lit.span(), "control characters not allowed");
///     }
///     quote::quote! { /* use lit.value() */ }
/// }
/// ```
pub struct LitChar {
    /// The parsed character value.
    pub value: char,
    /// The source location of the literal.
    pub span: Span,
}

impl LitChar {
    /// Creates a new [`LitChar`] from a value and a span.
    #[must_use]
    pub const fn new(value: char, span: Span) -> Self {
        Self { value, span }
    }

    /// Returns the parsed character value.
    #[must_use]
    pub const fn value(&self) -> char {
        self.value
    }

    /// Returns the source span of the literal.
    #[must_use]
    pub const fn span(&self) -> Span {
        self.span
    }
}

impl FromLit for LitChar {
    #[inline]
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        let span = lit.span();
        let raw = lit.to_string();
        let Some(inner) = raw.strip_prefix('\'').and_then(|s| s.strip_suffix('\'')) else {
            return Err(comperr::error(span, "expected a char literal"));
        };
        let unescaped = crate::unescape(inner, span)?;
        if unescaped.chars().count() != 1 {
            return Err(comperr::error(span, "invalid char literal"));
        }
        // SAFETY: count() == 1 guarantees exactly one char exists
        Ok(Self::new(unescaped.chars().next().unwrap(), span))
    }
}

impl FromLit for char {
    #[inline]
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        Ok(LitChar::from_lit(lit)?.value)
    }
}

// ---------------------------------------------------------------------------
// C and Byte strings
// ---------------------------------------------------------------------------

use std::ffi::{CStr, CString};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Parses a byte string literal (`b"..."` or `br#"..."#`) into raw bytes.
///
/// Unlike string literal parsing, `\xNN` allows the full 0x00..=0xFF range.
fn parse_byte_str_raw(raw: &str, span: Span) -> Result<Vec<u8>, TokenStream> {
    if raw.starts_with("br") {
        let rest = &raw[1..];
        let inner = crate::parse_raw(rest)
            .ok_or_else(|| comperr::error(span, "litext: malformed raw byte string literal"))?;
        return Ok(inner.into_bytes());
    }

    if let Some(inner) = raw.strip_prefix("b\"").and_then(|s| s.strip_suffix('"')) {
        return crate::unescape_bytes(inner, span);
    }

    Err(comperr::error(
        span,
        "litext: expected a byte string literal",
    ))
}

/// Parses a C string literal (`c"..."` or `cr#"..."#`) into raw bytes, without
/// the null terminator (which `CString::new` appends). Interior null bytes cause
/// `CString::new` to fail, producing a compile error.
fn parse_c_str_raw(raw: &str, span: Span) -> Result<Vec<u8>, TokenStream> {
    if raw.starts_with("cr") {
        let rest = &raw[1..];
        let inner = crate::parse_raw(rest)
            .ok_or_else(|| comperr::error(span, "litext: malformed raw C string literal"))?;
        return Ok(inner.into_bytes());
    }

    if let Some(inner) = raw.strip_prefix("c\"").and_then(|s| s.strip_suffix('"')) {
        let unescaped = crate::unescape(inner, span)?;
        return Ok(unescaped.into_bytes());
    }

    Err(comperr::error(span, "litext: expected a C string literal"))
}

// ---------------------------------------------------------------------------
// LitByteStr
// ---------------------------------------------------------------------------

/// A parsed byte string literal (`b"..."` or `br#"..."#`) bundled with its source location.
///
/// Unlike string literals which restrict `\x` to ASCII (0x00..=0x7F), byte strings
/// allow the full 0x00..=0xFF range for `\x` escapes.
///
/// # Supported Formats
///
/// | Format | Example |
/// |--------|---------|
/// | Regular byte string | `b"hello"` |
/// | Byte string escapes | `b"\xff\x80"`, `b"\n\t\r\\"` |
/// | Raw byte string | `br#"raw bytes"#` |
///
/// # Example
///
/// ```ignore
/// use litext::{litext, TokenStream};
/// use litext::literal::LitByteStr;
///
/// pub fn my_macro(input: TokenStream) -> TokenStream {
///     let lit: LitByteStr = litext!(input as LitByteStr);
///     let bytes: &[u8] = lit.value();
/// }
/// ```
pub struct LitByteStr {
    /// The extracted bytes from the byte string literal.
    pub value: Vec<u8>,
    /// The source location of the literal.
    pub span: Span,
}

impl LitByteStr {
    /// Creates a new [`LitByteStr`] from a value and a span.
    #[must_use]
    pub const fn new(value: Vec<u8>, span: Span) -> Self {
        Self { value, span }
    }

    /// Returns the extracted bytes.
    #[must_use]
    pub fn value(&self) -> &[u8] {
        &self.value
    }

    /// Returns the source span of the literal.
    #[must_use]
    pub const fn span(&self) -> Span {
        self.span
    }
}

impl FromLit for LitByteStr {
    #[inline]
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        let span = lit.span();
        let raw = lit.to_string();
        let bytes = parse_byte_str_raw(&raw, span)?;
        Ok(Self::new(bytes, span))
    }
}

impl FromLit for Vec<u8> {
    #[inline]
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        Ok(LitByteStr::from_lit(lit)?.value)
    }
}

// ---------------------------------------------------------------------------
// LitByte
// ---------------------------------------------------------------------------

/// A parsed byte literal (`b'...'`) bundled with its source location.
///
/// The full 0x00..=0xFF byte range is valid. `\xNN` escapes with `NN > 7F`
/// are accepted, unlike in string literals where they are rejected.
///
/// | Input | Extracted value |
/// |-------|-----------------|
/// | `b'a'` | `97` |
/// | `b'\n'` | `10` |
/// | `b'\xff'` | `255` |
/// | `b'\x41'` | `65` |
///
/// # Example
///
/// ```ignore
/// use litext::{litext, TokenStream};
/// use litext::literal::LitByte;
///
/// pub fn my_macro(input: TokenStream) -> TokenStream {
///     let lit: LitByte = litext!(input as LitByte);
///     if lit.value() == 0 {
///         return comperr::error(lit.span(), "null bytes not allowed");
///     }
/// }
/// ```
pub struct LitByte {
    /// The extracted byte value.
    pub value: u8,
    /// The source location of the literal.
    pub span: Span,
}

impl LitByte {
    /// Creates a new [`LitByte`] from a value and a span.
    #[must_use]
    pub const fn new(value: u8, span: Span) -> Self {
        Self { value, span }
    }

    /// Returns the extracted byte value.
    #[must_use]
    pub const fn value(&self) -> u8 {
        self.value
    }

    /// Returns the source span of the literal.
    #[must_use]
    pub const fn span(&self) -> Span {
        self.span
    }
}

impl FromLit for LitByte {
    #[inline]
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        let span = lit.span();
        let raw = lit.to_string();

        let Some(inner) = raw.strip_prefix("b'").and_then(|s| s.strip_suffix('\'')) else {
            return Err(comperr::error(span, "expected a byte literal"));
        };

        let bytes = crate::unescape_bytes(inner, span)?;

        if bytes.len() != 1 {
            return Err(comperr::error(span, "invalid byte literal"));
        }

        Ok(Self::new(bytes[0], span))
    }
}

// ---------------------------------------------------------------------------
// LitCStr
// ---------------------------------------------------------------------------

/// A parsed C string literal (`c"..."` or `cr#"..."#`) bundled with its source location.
///
/// The extracted value is a [`CString`] with the null terminator already appended.
/// Interior null bytes produce a compile error at extraction time.
///
/// # Supported Formats
///
/// | Format | Example |
/// |--------|---------|
/// | Regular C string | `c"hello"` |
/// | C string with escapes | `c"hello\nworld"` |
/// | Raw C string | `cr#"raw c string"#` |
///
/// # Example
///
/// ```ignore
/// use litext::{litext, TokenStream};
/// use litext::literal::LitCStr;
///
/// pub fn my_macro(input: TokenStream) -> TokenStream {
///     let lit: LitCStr = litext!(input as LitCStr);
///     let value: &std::ffi::CStr = lit.value();
/// }
/// ```
pub struct LitCStr {
    /// The extracted C string value.
    pub value: CString,
    /// The source location of the literal.
    pub span: Span,
}

impl LitCStr {
    /// Creates a new [`LitCStr`] from a value and a span.
    #[must_use]
    pub const fn new(value: CString, span: Span) -> Self {
        Self { value, span }
    }

    /// Returns the extracted C string value.
    #[must_use]
    pub fn value(&self) -> &CStr {
        &self.value
    }

    /// Returns the source span of the literal.
    #[must_use]
    pub const fn span(&self) -> Span {
        self.span
    }
}

impl FromLit for LitCStr {
    #[inline]
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        let span = lit.span();
        let raw = lit.to_string();
        let bytes = parse_c_str_raw(&raw, span)?;
        let cstring = CString::new(bytes).map_err(|_| {
            comperr::error(
                span,
                "litext: C string literal contains an interior null byte",
            )
        })?;
        Ok(Self::new(cstring, span))
    }
}

impl FromLit for CString {
    #[inline]
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        Ok(LitCStr::from_lit(lit)?.value)
    }
}