litext 1.0.0

Just what you need for extracting string literal contents at compile time
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
use crate::literal::LitStr;

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

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

#[doc(hidden)]
mod __private {
    pub trait IntegerSeal {}
    pub trait FloatSeal {}

    impl IntegerSeal for i8 {}
    impl IntegerSeal for i16 {}
    impl IntegerSeal for i32 {}
    impl IntegerSeal for i64 {}
    impl IntegerSeal for i128 {}
    impl IntegerSeal for isize {}
    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 {}
}

/// The core trait for extracting a value from a [`Literal`] or [`Ident`] token.
///
/// Implement this trait to make `litext!(input as MyType)` work for your own
/// types. The macro will call [`FromLit::from_lit`] or [`FromLit::from_ident`]
/// with the extracted token and return the result.
///
/// # Trait Overview
///
/// The trait has two methods:
///
/// - [`from_lit`](Self::from_lit) - Converts a `Literal` token to the target type.
///   This is used for string, numeric, character, byte, and C string literals.
/// - [`from_ident`](Self::from_ident) - Converts an `Ident` token to the target type.
///   This is used for boolean literals (`true`, `false`).
///
/// Most types only need to implement `from_lit`. The `from_ident` method has a
/// default implementation that returns an error, but types like `bool` that are
/// represented as identifiers need to override it.
///
/// # Example
///
/// ```ignore
/// use litext::literal::FromLit;
/// use proc_macro2::{Literal, TokenStream};
///
/// pub struct MyType(String);
///
/// impl FromLit for MyType {
///     fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
///         // Parse the literal however you need
///         // Here we just grab the raw string representation
///         Ok(MyType(lit.to_string()))
///     }
/// }
/// ```
///
/// # Built-in Implementations
///
/// The crate provides implementations for the following types:
///
/// **String literals:**
/// - `String`, `LitStr` - String and raw string literals (`"..."`, `r#"..."#`)
///
/// **Integer literals (all radixes, with optional suffix and underscores):**
/// - `i8`, `i16`, `i32`, `i64`, `i128`, `isize`
/// - `u8`, `u16`, `u32`, `u64`, `u128`, `usize`
/// - `LitInt<T>` - Span-aware variant, defaults to `LitInt<i32>`
///
/// **Float literals (scientific notation, underscores, optional suffix):**
/// - `f32`, `f64`
/// - `LitFloat<T>` - Span-aware variant, defaults to `LitFloat<f64>`
///
/// **Character literals (with escape sequences):**
/// - `char`, `LitChar` - Character literals (`'a'`, `'\n'`, `'\u{1F600}'`)
///
/// **Boolean literals (as identifiers):**
/// - `bool`, `LitBool` - Boolean literals (`true`, `false`)
///
/// **Byte literals and strings:**
/// - `u8`, `LitByte` - Byte literals (`b'a'`, `b'\xff'`)
/// - `Vec<u8>`, `LitByteStr` - Byte string literals (`b"..."`, `br#"..."#`)
///
/// **C string literals:**
/// - `CString`, `LitCStr` - C string literals (`c"..."`, `cr#"..."#`)
///
/// # See Also
///
/// - [`extract`](../fn.extract.html) for the function that uses this trait
/// - [`litext!`](../macro.litext.html) macro for the macro that uses this trait
/// - [`ToTokens`](super::ToTokens) for converting back to tokens
pub trait FromLit: Sized {
    /// Attempts to extract a value from a [`Literal`] token.
    ///
    /// On success, returns `Ok` containing the extracted value.
    /// 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`).
    #[inline]
    fn from_ident(ident: Ident) -> Result<Self, TokenStream> {
        Err(comperr::error(
            ident.span(),
            format!("expected a literal, found identifier `{ident}`"),
        ))
    }
}

/// Strips integer type suffixes and parses numeric prefixes to extract the digits and radix.
///
/// Handles suffixes like `i32`, `u64`, `isize`, etc. and prefixes like `0x`, `0o`, `0b`.
/// Also removes underscore separators used for readability (e.g., `1_000`).
///
/// # Arguments
///
/// - `raw` - The raw string representation of an integer literal
///
/// # Returns
///
/// - `Some((digits, radix))` - The cleaned digit string and the numeric base (10, 16, 8, or 2)
/// - `None` - If the input is malformed
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 float type suffixes and removes 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(LitStr::new(value, span))
    }
}

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

/// A span-aware integer literal.
///
/// `LitInt<T>` bundles a parsed integer value with its original source location.
/// Use this type when you need to emit diagnostics that point to the exact location
/// of an integer literal in the macro input.
///
/// # Type Parameter
///
/// - `T` - The integer type to parse into. Must be one of `i8`, `i16`, `i32`, `i64`,
///   `i128`, `isize`, `u8`, `u16`, `u32`, `u64`, `u128`, or `usize`. Defaults to `i32`.
///
/// # Supported Formats
///
/// The following integer literal formats are supported:
///
/// | Format | Example | Notes |
/// |--------|---------|-------|
/// | Decimal | `42` | Default base |
/// | Hexadecimal | `0xFF`, `0XFF` | Base 16 |
/// | Octal | `0o77`, `0O77` | Base 8 |
/// | Binary | `0b1010`, `0B1010` | Base 2 |
/// | Underscores | `1_000_000` | Digit separators |
/// | Type suffix | `42_i32`, `100_u8` | Explicit type annotation |
///
/// # Overflow Handling
///
/// If the literal value is too large for type `T`, an error is returned. The error
/// message includes the span of the literal for precise error reporting.
///
/// # Why Not Just Use `i32`?
///
/// Use `LitInt<T>` when you need the span for error reporting. If you only need the
/// integer value, using the plain integer types directly is simpler.
///
/// # Examples
///
/// ```ignore
/// use litext::{litext, TokenStream};
/// use litext::literal::LitInt;
///
/// pub fn my_macro(input: TokenStream) -> TokenStream {
///     // Extract as LitInt<u8> for small unsigned integers
///     let lit: LitInt<u8> = litext!(input as LitInt<u8>);
///     let value: u8 = lit.value();
///
///     // Access the span for error reporting
///     if value == 0 {
///         return comperr::error(lit.span(), "division by zero not allowed");
///     }
///
///     quote::quote! { /* use value */ }
/// }
/// ```
///
/// # See Also
///
/// - [`FromLit`](super::FromLit) for the extraction trait
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 fn new(value: T, span: Span, suffix: Option<String>) -> Self {
        Self {
            value,
            span,
            suffix,
        }
    }

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

    /// Returns the source span of the literal.
    pub 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(LitInt::new(value, span, suffix))
    }
}

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

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

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

impl FromLit for u8 {
    fn from_lit(lit: Literal) -> Result<Self, TokenStream> {
        let raw = lit.to_string();
        if raw.starts_with("b'") {
            // It's a byte literal
            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 unescaped = crate::unescape(inner, span)?;
            let bytes = unescaped.as_bytes();
            if bytes.len() != 1 {
                return Err(comperr::error(span, "invalid byte literal"));
            }
            return Ok(bytes[0]);
        }
        // Otherwise, treat as integer
        Ok(*LitInt::<u8>::from_lit(lit)?.value())
    }
}

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

/// A span-aware float literal.
///
/// `LitFloat<T>` bundles a parsed floating-point value with its original source
/// location. Use this type when you need to emit diagnostics that point to the
/// exact location of a float literal in the macro input.
///
/// # Type Parameter
///
/// - `T` - The float type to parse into. Must be either `f32` or `f64`. Defaults
///   to `f64`.
///
/// # Supported Formats
///
/// The following float literal formats are supported:
///
/// | Format | Example | Notes |
/// |--------|---------|-------|
/// | Decimal | `3.14` | Standard notation |
/// | Scientific | `1e10`, `2.5e-3` | Scientific notation |
/// | Underscores | `1_000.5` | Digit separators |
/// | Type suffix | `3.14_f32`, `1e10_f64` | Explicit type annotation |
///
/// # Parsing Behavior
///
/// The parsing delegates to `T::from_str`, so it follows the same rules as Rust's
/// standard float literal parsing. Invalid float literals will produce an error
/// with the span of the problematic input.
///
/// # Why Not Just Use `f64`?
///
/// Use `LitFloat<T>` when you need the span for error reporting. If you only need the
/// float value, using the plain float types directly is simpler.
///
/// # Examples
///
/// ```ignore
/// use litext::{litext, TokenStream};
/// use litext::literal::LitFloat;
///
/// pub fn my_macro(input: TokenStream) -> TokenStream {
///     // Extract as LitFloat<f32> for single-precision floats
///     let lit: LitFloat<f32> = litext!(input as LitFloat<f32>);
///     let value: f32 = lit.value();
///
///     // Access the span for error reporting
///     if value < 0.0 {
///         return comperr::error(lit.span(), "expected non-negative float");
///     }
///
///     quote::quote! { /* use value */ }
/// }
/// ```
///
/// # See Also
///
/// - [`FromLit`](super::FromLit) for the extraction trait
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 fn new(value: T, span: Span, suffix: Option<String>) -> Self {
        Self {
            value,
            span,
            suffix,
        }
    }

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

    /// Returns the source span of the literal.
    pub 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,
    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(LitFloat::new(value, span, suffix))
    }
}

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

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

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

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

/// A span-aware boolean literal.
///
/// `LitBool` bundles a parsed boolean value with its original source location.
/// Use this type when you need to emit diagnostics that point to the exact location
/// of a boolean literal in the macro input.
///
/// # Type Details
///
/// Unlike other literal types, `bool` values in Rust are represented as identifiers
/// (`true`, `false`) rather than literals. This means `LitBool` implements special
/// handling for `from_ident` in addition to `from_lit`.
///
/// # Why Not Just Use `bool`?
///
/// Use `LitBool` when you need the span for error reporting. If you only need the
/// boolean value, using `bool` directly is simpler.
///
/// # Examples
///
/// ```ignore
/// use litext::{litext, TokenStream};
/// use litext::literal::LitBool;
///
/// pub fn my_macro(input: TokenStream) -> TokenStream {
///     let lit: LitBool = litext!(input as LitBool);
///     let value: bool = lit.value();
///
///     // Access the span for error reporting
///     if !value {
///         return comperr::error(lit.span(), "feature must be enabled");
///     }
///
///     quote::quote! { /* use value */ }
/// }
/// ```
///
/// # See Also
///
/// - [`FromLit`](super::FromLit) for the extraction trait
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 fn new(value: bool, span: Span) -> Self {
        Self { value, span }
    }

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

    /// Returns the source span of the literal.
    #[must_use] 
    pub 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(LitBool::new(true, span)),
            "false" => Ok(LitBool::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 span-aware character literal.
///
/// `LitChar` bundles a parsed character value with its original source location.
/// Use this type when you need to emit diagnostics that point to the exact location
/// of a character literal in the macro input.
///
/// # Type Details
///
/// The extracted `value` is a valid Unicode `char`. Escape sequences in the input
/// literal are resolved before parsing:
///
/// | Input | Extracted Char |
/// |-------|----------------|
/// | `'a'` | `a` |
/// | `'\n'` | newline |
/// | `'\t'` | tab |
/// | `'\''` | single quote |
/// | `'\\'` | backslash |
/// | `'\0'` | null character |
/// | `'\x41'` | `A` |
/// | `'\u{1F600}'` | emoji character |
///
/// # Validation
///
/// If the character literal contains more than one character (after unescaping),
/// an error is returned. This includes empty literals and multi-character sequences.
///
/// # Why Not Just Use `char`?
///
/// Use `LitChar` when you need the span for error reporting. If you only need the
/// character value, using `char` directly is simpler.
///
/// # Examples
///
/// ```ignore
/// use litext::{litext, TokenStream};
/// use litext::literal::LitChar;
///
/// pub fn my_macro(input: TokenStream) -> TokenStream {
///     let lit: LitChar = litext!(input as LitChar);
///     let value: char = lit.value();
///
///     // Access the span for error reporting
///     if value.is_control() {
///         return comperr::error(lit.span(), "control characters not allowed");
///     }
///
///     quote::quote! { /* use value */ }
/// }
/// ```
///
/// # See Also
///
/// - [`FromLit`](super::FromLit) for the extraction trait
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 fn new(value: char, span: Span) -> Self {
        Self { value, span }
    }

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

    /// Returns the source span of the literal.
    #[must_use] 
    pub 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(LitChar::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::CString;

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

/// Parses a byte string literal like `b"hello"` or `br#"hello"#` into a
/// `Vec<u8>`.
///
/// Returns `None` if the input does not look like a byte string literal.
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('"')) {
        let unescaped = crate::unescape(inner, span)?;
        return Ok(unescaped.into_bytes());
    }

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

/// Parses a C string literal like `c"hello"` or `cr#"hello"#` into a `Vec<u8>`,
/// without the null terminator. The null terminator is added by `CString::new`.
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 span-aware byte string literal.
///
/// Represents a `b"..."` or `br#"..."#` literal, with the extracted bytes
/// and the source location bundled together.
///
/// # 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 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 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(LitByteStr::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 span-aware byte literal.
///
/// Represents a `b'...'` literal -- a single byte value paired with its
/// source location.
///
/// # What Gets Extracted
///
/// | Input | Extracted Value |
/// |-------|-----------------|
/// | `b'a'` | `97u8` |
/// | `b'\n'` | `10u8` |
/// | `b'\xff'` | `255u8` |
/// | `b'\x41'` | `65u8` |
///
/// # Example
///
/// ```ignore
/// use litext::{litext, TokenStream};
/// use litext::literal::LitByte;
///
/// pub fn my_macro(input: TokenStream) -> TokenStream {
///     let lit: LitByte = litext!(input as LitByte);
///     let byte: u8 = lit.value();
///
///     if byte == 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 fn new(value: u8, span: Span) -> Self {
        Self { value, span }
    }

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

    /// Returns the source span of the literal.
    #[must_use] 
    pub 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 unescaped = crate::unescape(inner, span)?;
        let bytes = unescaped.as_bytes();

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

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

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

/// A span-aware C string literal.
///
/// Represents a `c"..."` or `cr#"..."#` literal, with the extracted
/// [`CString`] and the source location bundled together.
///
/// Note that C string literals cannot contain interior null bytes. If the
/// literal contains a null byte, a compile error is emitted.
///
/// # 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 fn new(value: CString, span: Span) -> Self {
        Self { value, span }
    }

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

    /// Returns the source span of the literal.
    #[must_use] 
    pub 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(LitCStr::new(cstring, span))
    }
}

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