ghci 0.2.1

Manage and communicate with ghci (Haskell's GHC interpreter)
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
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
// For macros
#![allow(non_snake_case)]

//! Traits for converting between Rust values and Haskell expressions.
//!
//! [`ToHaskell`] converts a Rust value into a Haskell expression string,
//! and [`FromHaskell`] parses a Haskell expression string back into a Rust value.
//!
//! ```
//! use ghci::{ToHaskell, FromHaskell};
//!
//! assert_eq!(true.to_haskell(), "True");
//! assert_eq!((-3i32).to_haskell(), "(-3)");
//! assert_eq!(Some(42u32).to_haskell(), "(Just 42)");
//! assert_eq!(Vec::<i32>::new().to_haskell(), "[]");
//! assert_eq!(vec![1u32, 2, 3].to_haskell(), "[1, 2, 3]");
//!
//! assert_eq!(bool::from_haskell("True").unwrap(), true);
//! assert_eq!(i32::from_haskell("(-3)").unwrap(), -3);
//! assert_eq!(<Option<u32>>::from_haskell("(Just 42)").unwrap(), Some(42));
//! ```

use std::fmt;

/// Error type for parsing Haskell expressions.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum HaskellParseError {
    /// Failed to parse a Haskell expression.
    #[error("failed to parse Haskell expression: {message}")]
    ParseError {
        /// Description of what went wrong.
        message: String,
    },
    /// Input ended unexpectedly.
    #[error("unexpected end of input")]
    UnexpectedEnd,
    /// Parsing succeeded but there was leftover input.
    #[error("unexpected trailing input: {remaining:?}")]
    TrailingInput {
        /// The unconsumed input.
        remaining: String,
    },
}

/// Convert a Rust value to a Haskell expression string.
///
/// Implementors override [`write_haskell`](ToHaskell::write_haskell).
/// The expression must be safe for use as a function argument
/// (parenthesized where needed, e.g. negative numbers, constructor applications).
pub trait ToHaskell {
    /// Write this value as a Haskell expression into the buffer.
    ///
    /// # Errors
    ///
    /// Returns [`fmt::Error`] if writing to the buffer fails.
    fn write_haskell(&self, buf: &mut impl fmt::Write) -> fmt::Result;

    /// Convenience: return as owned `String`.
    fn to_haskell(&self) -> String {
        let mut buf = String::new();
        self.write_haskell(&mut buf)
            .expect("write to String cannot fail");
        buf
    }
}

/// Parse a Rust value from a Haskell expression string.
///
/// Implementors override [`parse_haskell`](FromHaskell::parse_haskell), which returns the
/// parsed value together with unconsumed input. The default [`from_haskell`](FromHaskell::from_haskell)
/// calls `parse_haskell` and checks that no input remains.
pub trait FromHaskell: Sized {
    /// Parse from full input (checks no trailing content).
    ///
    /// # Errors
    ///
    /// Returns [`HaskellParseError`] if parsing fails or there is trailing input.
    fn from_haskell(input: &str) -> Result<Self, HaskellParseError> {
        let (val, rest) = Self::parse_haskell(input)?;
        let rest = skip_ws(rest);
        if rest.is_empty() {
            Ok(val)
        } else {
            Err(HaskellParseError::TrailingInput {
                remaining: rest.to_string(),
            })
        }
    }

    /// Parse from start of input, return (value, remaining).
    ///
    /// # Errors
    ///
    /// Returns [`HaskellParseError`] if the input cannot be parsed.
    fn parse_haskell(input: &str) -> Result<(Self, &str), HaskellParseError>;
}

// ── ToHaskell impls ──────────────────────────────────────────────────

impl<T: ToHaskell + ?Sized> ToHaskell for &T {
    fn write_haskell(&self, buf: &mut impl fmt::Write) -> fmt::Result {
        (**self).write_haskell(buf)
    }
}

impl ToHaskell for bool {
    fn write_haskell(&self, buf: &mut impl fmt::Write) -> fmt::Result {
        buf.write_str(if *self { "True" } else { "False" })
    }
}

macro_rules! impl_to_haskell_unsigned {
    ($($t:ty),*) => {
        $(impl ToHaskell for $t {
            fn write_haskell(&self, buf: &mut impl fmt::Write) -> fmt::Result {
                write!(buf, "{self}")
            }
        })*
    };
}

impl_to_haskell_unsigned!(u8, u16, u32, u64, u128, usize);

macro_rules! impl_to_haskell_signed {
    ($($t:ty),*) => {
        $(impl ToHaskell for $t {
            fn write_haskell(&self, buf: &mut impl fmt::Write) -> fmt::Result {
                if *self < 0 {
                    write!(buf, "({self})")
                } else {
                    write!(buf, "{self}")
                }
            }
        })*
    };
}

impl_to_haskell_signed!(i8, i16, i32, i64, i128, isize);

/// Write a float value ensuring a decimal point is always present.
fn write_float(buf: &mut impl fmt::Write, value: impl fmt::Display) -> fmt::Result {
    use std::fmt::Write as _;
    let mut tmp = String::new();
    write!(tmp, "{value}")?;
    // Ensure a decimal point so Haskell interprets it as a fractional number
    if !tmp.contains('.') {
        tmp.push_str(".0");
    }
    buf.write_str(&tmp)
}

macro_rules! impl_to_haskell_float {
    ($($t:ty),*) => {
        $(impl ToHaskell for $t {
            fn write_haskell(&self, buf: &mut impl fmt::Write) -> fmt::Result {
                if self.is_nan() {
                    buf.write_str("(0/0)")
                } else if self.is_infinite() {
                    if self.is_sign_positive() {
                        buf.write_str("(1/0)")
                    } else {
                        buf.write_str("((-1)/0)")
                    }
                } else if *self < 0.0 {
                    buf.write_char('(')?;
                    write_float(buf, self)?;
                    buf.write_char(')')
                } else {
                    write_float(buf, self)
                }
            }
        })*
    };
}

impl_to_haskell_float!(f32, f64);

impl ToHaskell for str {
    fn write_haskell(&self, buf: &mut impl fmt::Write) -> fmt::Result {
        buf.write_char('"')?;
        let mut prev_was_numeric_escape = false;
        for c in self.chars() {
            // After a numeric escape like \0 or \31, a following digit would
            // be consumed as part of the escape. Insert \& to disambiguate.
            if prev_was_numeric_escape && c.is_ascii_digit() {
                buf.write_str("\\&")?;
            }
            // \0 and other control chars (except \n, \t, \r which use named
            // escapes) produce numeric escapes
            prev_was_numeric_escape =
                c == '\0' || (c.is_ascii_control() && !matches!(c, '\n' | '\t' | '\r'));
            write_haskell_char_escaped(buf, c, '"')?;
        }
        buf.write_char('"')
    }
}

impl ToHaskell for String {
    fn write_haskell(&self, buf: &mut impl fmt::Write) -> fmt::Result {
        self.as_str().write_haskell(buf)
    }
}

impl ToHaskell for char {
    fn write_haskell(&self, buf: &mut impl fmt::Write) -> fmt::Result {
        buf.write_char('\'')?;
        write_haskell_char_escaped(buf, *self, '\'')?;
        buf.write_char('\'')
    }
}

fn write_haskell_char_escaped(buf: &mut impl fmt::Write, c: char, quote: char) -> fmt::Result {
    match c {
        '\\' => buf.write_str("\\\\"),
        '\n' => buf.write_str("\\n"),
        '\t' => buf.write_str("\\t"),
        '\r' => buf.write_str("\\r"),
        '\0' => buf.write_str("\\0"),
        c if c == quote => {
            buf.write_char('\\')?;
            buf.write_char(quote)
        }
        c if c.is_ascii_control() => write!(buf, "\\{}", c as u32),
        c => buf.write_char(c),
    }
}

impl<T: ToHaskell> ToHaskell for Option<T> {
    fn write_haskell(&self, buf: &mut impl fmt::Write) -> fmt::Result {
        match self {
            None => buf.write_str("Nothing"),
            Some(v) => {
                buf.write_str("(Just ")?;
                v.write_haskell(buf)?;
                buf.write_char(')')
            }
        }
    }
}

impl<T: ToHaskell> ToHaskell for Vec<T> {
    fn write_haskell(&self, buf: &mut impl fmt::Write) -> fmt::Result {
        buf.write_char('[')?;
        for (i, v) in self.iter().enumerate() {
            if i > 0 {
                buf.write_str(", ")?;
            }
            v.write_haskell(buf)?;
        }
        buf.write_char(']')
    }
}

impl<T: ToHaskell> ToHaskell for [T] {
    fn write_haskell(&self, buf: &mut impl fmt::Write) -> fmt::Result {
        buf.write_char('[')?;
        for (i, v) in self.iter().enumerate() {
            if i > 0 {
                buf.write_str(", ")?;
            }
            v.write_haskell(buf)?;
        }
        buf.write_char(']')
    }
}

macro_rules! impl_to_haskell_tuple {
    ($($idx:tt $T:ident),+) => {
        impl<$($T: ToHaskell),+> ToHaskell for ($($T,)+) {
            fn write_haskell(&self, buf: &mut impl fmt::Write) -> fmt::Result {
                buf.write_char('(')?;
                let mut _first = true;
                $(
                    if !_first { buf.write_str(", ")?; }
                    _first = false;
                    self.$idx.write_haskell(buf)?;
                )+
                buf.write_char(')')
            }
        }
    };
}

// Tuple implementations for ToHaskell
impl_to_haskell_tuple!(0 A, 1 B);
impl_to_haskell_tuple!(0 A, 1 B, 2 C);
impl_to_haskell_tuple!(0 A, 1 B, 2 C, 3 D);
impl_to_haskell_tuple!(0 A, 1 B, 2 C, 3 D, 4 E);
impl_to_haskell_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F);
impl_to_haskell_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G);
impl_to_haskell_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H);

// ── FromHaskell impls ────────────────────────────────────────────────

impl FromHaskell for bool {
    fn parse_haskell(input: &str) -> Result<(Self, &str), HaskellParseError> {
        let input = skip_ws(input);
        if let Some(rest) = input.strip_prefix("True") {
            if rest.is_empty() || !rest.as_bytes()[0].is_ascii_alphanumeric() {
                return Ok((true, rest));
            }
        }
        if let Some(rest) = input.strip_prefix("False") {
            if rest.is_empty() || !rest.as_bytes()[0].is_ascii_alphanumeric() {
                return Ok((false, rest));
            }
        }
        Err(HaskellParseError::ParseError {
            message: format!("expected True or False, got {input:?}"),
        })
    }
}

/// Parse an integer (possibly parenthesized if negative).
fn parse_int<T: std::str::FromStr>(input: &str) -> Result<(T, &str), HaskellParseError>
where
    T::Err: fmt::Display,
{
    let input = skip_ws(input);
    // Try parenthesized negative: (-123)
    if let Some(inner) = input.strip_prefix('(') {
        let inner = skip_ws(inner);
        if inner.starts_with('-') {
            let end = inner
                .find(')')
                .ok_or_else(|| HaskellParseError::ParseError {
                    message: "unclosed parenthesis for negative number".to_string(),
                })?;
            let num_str = inner[..end].trim();
            let val = num_str
                .parse::<T>()
                .map_err(|e| HaskellParseError::ParseError {
                    message: format!("invalid number {num_str:?}: {e}"),
                })?;
            return Ok((val, &inner[end + 1..]));
        }
    }
    // Bare number
    let end = input
        .find(|c: char| !c.is_ascii_digit() && c != '-')
        .unwrap_or(input.len());
    if end == 0 {
        return Err(HaskellParseError::ParseError {
            message: format!("expected integer, got {input:?}"),
        });
    }
    let num_str = &input[..end];
    let val = num_str
        .parse::<T>()
        .map_err(|e| HaskellParseError::ParseError {
            message: format!("invalid number {num_str:?}: {e}"),
        })?;
    Ok((val, &input[end..]))
}

macro_rules! impl_from_haskell_int {
    ($($t:ty),*) => {
        $(impl FromHaskell for $t {
            fn parse_haskell(input: &str) -> Result<(Self, &str), HaskellParseError> {
                parse_int(input)
            }
        })*
    };
}

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

/// Parse a float (possibly parenthesized if negative, or special values like `(0/0)`).
fn parse_float<T>(input: &str) -> Result<(T, &str), HaskellParseError>
where
    T: std::str::FromStr + From<f32>,
    T::Err: fmt::Display,
{
    let input = skip_ws(input);
    // Handle parenthesized expressions: negative numbers or special values
    if let Some(inner) = input.strip_prefix('(') {
        let inner = skip_ws(inner);
        // (0/0) → NaN
        if let Some(rest) = inner.strip_prefix("0/0)") {
            return Ok((T::from(f32::NAN), rest));
        }
        // (1/0) → Inf
        if let Some(rest) = inner.strip_prefix("1/0)") {
            return Ok((T::from(f32::INFINITY), rest));
        }
        // ((-1)/0) → -Inf
        if let Some(rest) = inner.strip_prefix("(-1)/0)") {
            return Ok((T::from(f32::NEG_INFINITY), rest));
        }
        // Negative float: (-3.0)
        if inner.starts_with('-') {
            let end = inner
                .find(')')
                .ok_or_else(|| HaskellParseError::ParseError {
                    message: "unclosed parenthesis for negative float".to_string(),
                })?;
            let num_str = inner[..end].trim();
            let val = num_str
                .parse::<T>()
                .map_err(|e| HaskellParseError::ParseError {
                    message: format!("invalid float {num_str:?}: {e}"),
                })?;
            return Ok((val, &inner[end + 1..]));
        }
    }
    // Bare positive float
    let end = input
        .find(|c: char| {
            !c.is_ascii_digit() && c != '.' && c != '-' && c != 'e' && c != 'E' && c != '+'
        })
        .unwrap_or(input.len());
    if end == 0 {
        return Err(HaskellParseError::ParseError {
            message: format!("expected float, got {input:?}"),
        });
    }
    let num_str = &input[..end];
    let val = num_str
        .parse::<T>()
        .map_err(|e| HaskellParseError::ParseError {
            message: format!("invalid float {num_str:?}: {e}"),
        })?;
    Ok((val, &input[end..]))
}

impl FromHaskell for f32 {
    fn parse_haskell(input: &str) -> Result<(Self, &str), HaskellParseError> {
        parse_float(input)
    }
}

impl FromHaskell for f64 {
    fn parse_haskell(input: &str) -> Result<(Self, &str), HaskellParseError> {
        parse_float(input)
    }
}

impl FromHaskell for String {
    fn parse_haskell(input: &str) -> Result<(Self, &str), HaskellParseError> {
        let input = skip_ws(input);
        let mut chars = input.chars();
        if chars.next() != Some('"') {
            return Err(HaskellParseError::ParseError {
                message: format!("expected string literal, got {input:?}"),
            });
        }
        let mut result = Self::new();
        let mut rest = &input[1..];
        loop {
            let c = rest
                .chars()
                .next()
                .ok_or(HaskellParseError::UnexpectedEnd)?;
            match c {
                '"' => return Ok((result, &rest[1..])),
                '\\' => {
                    if rest[1..].starts_with('&') {
                        // \& is Haskell's empty escape, used to disambiguate
                        // named escapes (e.g. "\SO\&H" is SO followed by 'H')
                        rest = &rest[2..];
                    } else {
                        let (escaped, after) = parse_escape(&rest[1..])?;
                        result.push(escaped);
                        rest = after;
                    }
                }
                _ => {
                    result.push(c);
                    rest = &rest[c.len_utf8()..];
                }
            }
        }
    }
}

impl FromHaskell for char {
    fn parse_haskell(input: &str) -> Result<(Self, &str), HaskellParseError> {
        let input = skip_ws(input);
        let rest = input
            .strip_prefix('\'')
            .ok_or_else(|| HaskellParseError::ParseError {
                message: format!("expected char literal, got {input:?}"),
            })?;
        let (c, rest) = if let Some(escaped_rest) = rest.strip_prefix('\\') {
            parse_escape(escaped_rest)?
        } else {
            let c = rest
                .chars()
                .next()
                .ok_or(HaskellParseError::UnexpectedEnd)?;
            (c, &rest[c.len_utf8()..])
        };
        if !rest.starts_with('\'') {
            return Err(HaskellParseError::ParseError {
                message: "unterminated char literal".to_string(),
            });
        }
        Ok((c, &rest[1..]))
    }
}

/// Named ASCII escape sequences produced by Haskell's `show`.
const NAMED_ESCAPES: &[(&str, char)] = &[
    ("NUL", '\x00'),
    ("SOH", '\x01'),
    ("STX", '\x02'),
    ("ETX", '\x03'),
    ("EOT", '\x04'),
    ("ENQ", '\x05'),
    ("ACK", '\x06'),
    ("BEL", '\x07'),
    ("BS", '\x08'),
    ("HT", '\x09'),
    ("LF", '\x0A'),
    ("VT", '\x0B'),
    ("FF", '\x0C'),
    ("CR", '\x0D'),
    ("SO", '\x0E'),
    ("SI", '\x0F'),
    ("DLE", '\x10'),
    ("DC1", '\x11'),
    ("DC2", '\x12'),
    ("DC3", '\x13'),
    ("DC4", '\x14'),
    ("NAK", '\x15'),
    ("SYN", '\x16'),
    ("ETB", '\x17'),
    ("CAN", '\x18'),
    ("EM", '\x19'),
    ("SUB", '\x1A'),
    ("ESC", '\x1B'),
    ("FS", '\x1C'),
    ("GS", '\x1D'),
    ("RS", '\x1E'),
    ("US", '\x1F'),
    ("SP", '\x20'),
    ("DEL", '\x7F'),
];

fn parse_escape(input: &str) -> Result<(char, &str), HaskellParseError> {
    let c = input
        .chars()
        .next()
        .ok_or(HaskellParseError::UnexpectedEnd)?;
    match c {
        '\\' => Ok(('\\', &input[1..])),
        '"' => Ok(('"', &input[1..])),
        '\'' => Ok(('\'', &input[1..])),
        'n' => Ok(('\n', &input[1..])),
        't' => Ok(('\t', &input[1..])),
        'r' => Ok(('\r', &input[1..])),
        'a' => Ok(('\x07', &input[1..])),
        'b' => Ok(('\x08', &input[1..])),
        'f' => Ok(('\x0C', &input[1..])),
        'v' => Ok(('\x0B', &input[1..])),
        '0' => Ok(('\0', &input[1..])),
        c if c.is_ascii_digit() => {
            // Numeric escape: \NNN
            let end = input
                .find(|c: char| !c.is_ascii_digit())
                .unwrap_or(input.len());
            let num: u32 = input[..end]
                .parse()
                .map_err(|_| HaskellParseError::ParseError {
                    message: format!("invalid numeric escape: {}", &input[..end]),
                })?;
            let c = char::from_u32(num).ok_or_else(|| HaskellParseError::ParseError {
                message: format!("invalid unicode code point: {num}"),
            })?;
            Ok((c, &input[end..]))
        }
        c if c.is_ascii_uppercase() => {
            // Named ASCII escapes: \NUL, \SOH, \DEL, etc.
            for &(name, ch) in NAMED_ESCAPES {
                if let Some(rest) = input.strip_prefix(name) {
                    return Ok((ch, rest));
                }
            }
            Err(HaskellParseError::ParseError {
                message: format!("unknown escape sequence: \\{c}"),
            })
        }
        _ => Err(HaskellParseError::ParseError {
            message: format!("unknown escape sequence: \\{c}"),
        }),
    }
}

impl<T: FromHaskell> FromHaskell for Option<T> {
    fn parse_haskell(input: &str) -> Result<(Self, &str), HaskellParseError> {
        let input = skip_ws(input);
        if let Some(rest) = input.strip_prefix("Nothing") {
            if rest.is_empty() || !rest.as_bytes()[0].is_ascii_alphanumeric() {
                return Ok((None, rest));
            }
        }
        // (Just expr) — with parens
        if let Some(inner) = input.strip_prefix('(') {
            let inner = skip_ws(inner);
            if let Some(inner) = inner.strip_prefix("Just") {
                if !inner.is_empty() && inner.as_bytes()[0].is_ascii_alphanumeric() {
                    return Err(HaskellParseError::ParseError {
                        message: format!("expected Nothing or Just, got {input:?}"),
                    });
                }
                let (val, rest) = T::parse_haskell(inner)?;
                let rest = skip_ws(rest);
                let rest = rest
                    .strip_prefix(')')
                    .ok_or_else(|| HaskellParseError::ParseError {
                        message: "expected closing ')' for Just".to_string(),
                    })?;
                return Ok((Some(val), rest));
            }
        }
        // Just expr — without parens
        if let Some(inner) = input.strip_prefix("Just") {
            if !inner.is_empty() && inner.as_bytes()[0].is_ascii_alphanumeric() {
                return Err(HaskellParseError::ParseError {
                    message: format!("expected Nothing or Just, got {input:?}"),
                });
            }
            let (val, rest) = T::parse_haskell(inner)?;
            return Ok((Some(val), rest));
        }
        Err(HaskellParseError::ParseError {
            message: format!("expected Nothing or Just, got {input:?}"),
        })
    }
}

impl<T: FromHaskell> FromHaskell for Vec<T> {
    fn parse_haskell(input: &str) -> Result<(Self, &str), HaskellParseError> {
        let input = skip_ws(input);
        let rest = input
            .strip_prefix('[')
            .ok_or_else(|| HaskellParseError::ParseError {
                message: format!("expected '[', got {input:?}"),
            })?;
        let rest = skip_ws(rest);
        if let Some(rest) = rest.strip_prefix(']') {
            return Ok((Self::new(), rest));
        }
        let mut result = Self::new();
        let mut rest = rest;
        loop {
            let (val, r) = T::parse_haskell(rest)?;
            result.push(val);
            let r = skip_ws(r);
            if let Some(r) = r.strip_prefix(']') {
                return Ok((result, r));
            }
            rest = r
                .strip_prefix(',')
                .ok_or_else(|| HaskellParseError::ParseError {
                    message: format!("expected ',' or ']' in list, got {r:?}"),
                })?;
            rest = skip_ws(rest);
        }
    }
}

macro_rules! impl_from_haskell_tuple {
    ($($idx:tt $T:ident),+) => {
        impl<$($T: FromHaskell),+> FromHaskell for ($($T,)+) {
            fn parse_haskell(input: &str) -> Result<(Self, &str), HaskellParseError> {
                let input = skip_ws(input);
                let rest = input.strip_prefix('(').ok_or_else(|| {
                    HaskellParseError::ParseError {
                        message: format!("expected '(' for tuple, got {input:?}"),
                    }
                })?;
                let mut rest = skip_ws(rest);
                let mut _first = true;
                $(
                    if !_first {
                        rest = skip_ws(rest);
                        rest = rest.strip_prefix(',').ok_or_else(|| {
                            HaskellParseError::ParseError {
                                message: format!("expected ',' in tuple, got {rest:?}"),
                            }
                        })?;
                        rest = skip_ws(rest);
                    }
                    _first = false;
                    let ($T, r) = $T::parse_haskell(rest)?;
                    rest = r;
                )+
                let rest = skip_ws(rest);
                let rest = rest.strip_prefix(')').ok_or_else(|| {
                    HaskellParseError::ParseError {
                        message: format!("expected ')' for tuple, got {rest:?}"),
                    }
                })?;
                Ok((($($T,)+), rest))
            }
        }
    };
}

impl_from_haskell_tuple!(0 A, 1 B);
impl_from_haskell_tuple!(0 A, 1 B, 2 C);
impl_from_haskell_tuple!(0 A, 1 B, 2 C, 3 D);
impl_from_haskell_tuple!(0 A, 1 B, 2 C, 3 D, 4 E);
impl_from_haskell_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F);
impl_from_haskell_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G);
impl_from_haskell_tuple!(0 A, 1 B, 2 C, 3 D, 4 E, 5 F, 6 G, 7 H);

// ── Helper functions ─────────────────────────────────────────────────

/// Skip leading whitespace.
#[must_use]
fn skip_ws(input: &str) -> &str {
    input.trim_start()
}

fn parse_constructor(input: &str) -> Result<(&str, &str), HaskellParseError> {
    let input = skip_ws(input);
    let first = input
        .chars()
        .next()
        .ok_or(HaskellParseError::UnexpectedEnd)?;
    if !first.is_ascii_uppercase() {
        return Err(HaskellParseError::ParseError {
            message: format!("expected constructor (uppercase), got {input:?}"),
        });
    }
    let end = input
        .find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '\'')
        .unwrap_or(input.len());
    Ok((&input[..end], &input[end..]))
}

fn parse_identifier(input: &str) -> Result<(&str, &str), HaskellParseError> {
    let input = skip_ws(input);
    let first = input
        .chars()
        .next()
        .ok_or(HaskellParseError::UnexpectedEnd)?;
    if !first.is_ascii_alphabetic() && first != '_' {
        return Err(HaskellParseError::ParseError {
            message: format!("expected identifier, got {input:?}"),
        });
    }
    let end = input
        .find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '\'')
        .unwrap_or(input.len());
    Ok((&input[..end], &input[end..]))
}

#[allow(clippy::type_complexity)]
fn parse_record_fields(input: &str) -> Result<(Vec<(&str, &str)>, &str), HaskellParseError> {
    let input = skip_ws(input);
    let rest = input
        .strip_prefix('{')
        .ok_or_else(|| HaskellParseError::ParseError {
            message: format!("expected '{{' for record, got {input:?}"),
        })?;
    let rest = skip_ws(rest);
    if let Some(rest) = rest.strip_prefix('}') {
        return Ok((Vec::new(), rest));
    }

    let mut fields = Vec::new();
    let mut rest = rest;

    loop {
        rest = skip_ws(rest);
        // Parse field name
        let name_end = rest
            .find(|c: char| !c.is_ascii_alphanumeric() && c != '_' && c != '\'')
            .unwrap_or(rest.len());
        if name_end == 0 {
            return Err(HaskellParseError::ParseError {
                message: format!("expected field name, got {rest:?}"),
            });
        }
        let name = &rest[..name_end];
        rest = skip_ws(&rest[name_end..]);

        // Expect '='
        rest = rest
            .strip_prefix('=')
            .ok_or_else(|| HaskellParseError::ParseError {
                message: format!("expected '=' after field name {name:?}, got {rest:?}"),
            })?;
        rest = skip_ws(rest);

        // Parse value: nesting-aware scan until ',' or '}'
        let val_end = find_field_end(rest)?;
        let val = rest[..val_end].trim_end();
        fields.push((name, val));
        rest = &rest[val_end..];
        rest = skip_ws(rest);

        if let Some(r) = rest.strip_prefix('}') {
            return Ok((fields, r));
        }
        rest = rest
            .strip_prefix(',')
            .ok_or_else(|| HaskellParseError::ParseError {
                message: format!("expected ',' or '}}' in record, got {rest:?}"),
            })?;
    }
}

/// Find the end of a record field value, respecting nesting of `()`, `[]`, `{}`,
/// and string literals.
fn find_field_end(input: &str) -> Result<usize, HaskellParseError> {
    let mut depth_paren = 0i32;
    let mut depth_bracket = 0i32;
    let mut depth_brace = 0i32;
    let mut chars = input.char_indices();

    while let Some((i, c)) = chars.next() {
        match c {
            '(' => depth_paren += 1,
            ')' => {
                if depth_paren == 0 {
                    return Ok(i);
                }
                depth_paren -= 1;
            }
            '[' => depth_bracket += 1,
            ']' => {
                if depth_bracket == 0 {
                    return Ok(i);
                }
                depth_bracket -= 1;
            }
            '{' => depth_brace += 1,
            '}' => {
                if depth_brace == 0 {
                    return Ok(i);
                }
                depth_brace -= 1;
            }
            '"' => {
                // Skip string literal
                loop {
                    match chars.next() {
                        Some((_, '"')) => break,
                        Some((_, '\\')) => {
                            chars.next(); // skip escaped char
                        }
                        Some(_) => {}
                        None => {
                            return Err(HaskellParseError::UnexpectedEnd);
                        }
                    }
                }
            }
            '\'' => {
                // Skip char literal
                match chars.next() {
                    Some((_, '\\')) => {
                        chars.next(); // skip escaped char
                    }
                    Some(_) => {}
                    None => return Err(HaskellParseError::UnexpectedEnd),
                }
                // closing quote
                chars.next();
            }
            ',' if depth_paren == 0 && depth_bracket == 0 && depth_brace == 0 => {
                return Ok(i);
            }
            _ => {}
        }
    }

    Ok(input.len())
}

// ── ToHaskell builders ────────────────────────────────────────────────

/// Builder for writing Haskell record expressions: `Name {f1 = v1, f2 = v2}`.
///
/// Created by [`record`]. Each [`field`](HaskellRecord::field) call can use a
/// different `ToHaskell` type.
pub struct HaskellRecord<'a, W: fmt::Write> {
    buf: &'a mut W,
    result: fmt::Result,
    has_fields: bool,
}

/// Start writing a Haskell record expression.
///
/// ```
/// use ghci::haskell;
/// use ghci::ToHaskell;
///
/// let mut buf = String::new();
/// haskell::record(&mut buf, "Point")
///     .field("x", &1u32)
///     .field("y", &2u32)
///     .finish()
///     .unwrap();
/// assert_eq!(buf, "Point {x = 1, y = 2}");
/// ```
pub fn record<'a, W: fmt::Write>(buf: &'a mut W, name: &str) -> HaskellRecord<'a, W> {
    let result = buf.write_str(name).and_then(|()| buf.write_str(" {"));
    HaskellRecord {
        buf,
        result,
        has_fields: false,
    }
}

impl<W: fmt::Write> HaskellRecord<'_, W> {
    /// Write a field `name = value`. Each call may use a different `ToHaskell` type.
    pub fn field<T: ToHaskell>(&mut self, name: &str, value: &T) -> &mut Self {
        self.result = self.result.and_then(|()| {
            if self.has_fields {
                self.buf.write_str(", ")?;
            }
            self.buf.write_str(name)?;
            self.buf.write_str(" = ")?;
            value.write_haskell(self.buf)
        });
        self.has_fields = true;
        self
    }

    /// Finish the record expression by writing `}`.
    ///
    /// # Errors
    ///
    /// Returns [`fmt::Error`] if any prior write (including [`field`](Self::field)) failed.
    pub fn finish(&mut self) -> fmt::Result {
        self.result.and_then(|()| self.buf.write_char('}'))
    }
}

/// Builder for writing Haskell constructor applications: `(Constructor arg1 arg2)`.
///
/// Created by [`app`]. Bare constructor (no parens) when there are no args.
pub struct HaskellApp<'a, W: fmt::Write> {
    buf: &'a mut W,
    constructor: &'a str,
    result: fmt::Result,
    has_args: bool,
}

/// Start writing a Haskell constructor application.
///
/// ```
/// use ghci::haskell;
/// use ghci::ToHaskell;
///
/// let mut buf = String::new();
/// haskell::app(&mut buf, "Pair")
///     .arg(&1u32)
///     .arg(&true)
///     .finish()
///     .unwrap();
/// assert_eq!(buf, "(Pair 1 True)");
/// ```
pub const fn app<'a, W: fmt::Write>(buf: &'a mut W, constructor: &'a str) -> HaskellApp<'a, W> {
    HaskellApp {
        buf,
        constructor,
        result: Ok(()),
        has_args: false,
    }
}

impl<W: fmt::Write> HaskellApp<'_, W> {
    /// Write an argument. Each call may use a different `ToHaskell` type.
    pub fn arg<T: ToHaskell>(&mut self, value: &T) -> &mut Self {
        self.result = self.result.and_then(|()| {
            if !self.has_args {
                self.buf.write_char('(')?;
                self.buf.write_str(self.constructor)?;
            }
            self.buf.write_char(' ')?;
            value.write_haskell(self.buf)
        });
        self.has_args = true;
        self
    }

    /// Finish the application. Writes bare constructor if no args, closing `)` otherwise.
    ///
    /// # Errors
    ///
    /// Returns [`fmt::Error`] if any prior write failed.
    pub fn finish(&mut self) -> fmt::Result {
        self.result.and_then(|()| {
            if self.has_args {
                self.buf.write_char(')')
            } else {
                self.buf.write_str(self.constructor)
            }
        })
    }
}

// ── FromHaskell helpers ──────────────────────────────────────────────

/// Parsed record fields, returned by [`parse_record`].
///
/// Use [`field`](RecordFields::field) to extract typed values by name.
pub struct RecordFields<'a> {
    fields: Vec<(&'a str, &'a str)>,
}

/// Parse a Haskell record expression, checking the constructor name.
///
/// Returns the parsed fields and remaining input.
///
/// ```
/// use ghci::haskell;
/// use ghci::FromHaskell;
///
/// let (rec, rest) = haskell::parse_record("Point", "Point {x = 1, y = 2}").unwrap();
/// let x: u32 = rec.field("x").unwrap();
/// let y: u32 = rec.field("y").unwrap();
/// assert_eq!((x, y), (1, 2));
/// assert_eq!(rest, "");
/// ```
///
/// # Errors
///
/// Returns [`HaskellParseError`] if the constructor doesn't match or the record syntax is malformed.
pub fn parse_record<'a>(
    constructor: &str,
    input: &'a str,
) -> Result<(RecordFields<'a>, &'a str), HaskellParseError> {
    let input = skip_ws(input);
    let (name, rest) = parse_constructor(input)?;
    if name != constructor {
        return Err(HaskellParseError::ParseError {
            message: format!("expected constructor {constructor:?}, got {name:?}"),
        });
    }
    let (fields, rest) = parse_record_fields(rest)?;
    Ok((RecordFields { fields }, rest))
}

impl RecordFields<'_> {
    /// Look up a field by name and parse its value.
    ///
    /// # Errors
    ///
    /// Returns [`HaskellParseError`] if the field is not found or its value cannot be parsed.
    pub fn field<T: FromHaskell>(&self, name: &str) -> Result<T, HaskellParseError> {
        let raw = self
            .fields
            .iter()
            .find(|(n, _)| *n == name)
            .map(|(_, v)| *v)
            .ok_or_else(|| HaskellParseError::ParseError {
                message: format!("field {name:?} not found"),
            })?;
        T::from_haskell(raw)
    }
}

/// Streaming parser for Haskell constructor applications, returned by [`parse_app`].
///
/// Use [`arg`](AppParser::arg) to parse each positional argument in order,
/// then [`finish`](AppParser::finish) to consume the closing `)`.
pub struct AppParser<'a> {
    rest: &'a str,
    in_parens: bool,
}

/// Parse a Haskell constructor application, checking the constructor name.
///
/// Handles both `(Constructor arg1 arg2)` (parenthesized) and bare `Constructor`.
///
/// ```
/// use ghci::haskell;
/// use ghci::FromHaskell;
///
/// let mut p = haskell::parse_app("Pair", "(Pair 1 True)").unwrap();
/// let x: u32 = p.arg().unwrap();
/// let b: bool = p.arg().unwrap();
/// let rest = p.finish().unwrap();
/// assert_eq!((x, b), (1, true));
/// assert_eq!(rest, "");
/// ```
///
/// # Errors
///
/// Returns [`HaskellParseError`] if the constructor doesn't match.
pub fn parse_app<'a>(
    constructor: &str,
    input: &'a str,
) -> Result<AppParser<'a>, HaskellParseError> {
    let input = skip_ws(input);
    // Try parenthesized: (Constructor ...)
    if let Some(inner) = input.strip_prefix('(') {
        let inner = skip_ws(inner);
        let (name, rest) = parse_identifier(inner)?;
        if name != constructor {
            return Err(HaskellParseError::ParseError {
                message: format!("expected constructor {constructor:?}, got {name:?}"),
            });
        }
        return Ok(AppParser {
            rest,
            in_parens: true,
        });
    }
    // Bare constructor
    let (name, rest) = parse_identifier(input)?;
    if name != constructor {
        return Err(HaskellParseError::ParseError {
            message: format!("expected constructor {constructor:?}, got {name:?}"),
        });
    }
    Ok(AppParser {
        rest,
        in_parens: false,
    })
}

impl<'a> AppParser<'a> {
    /// Parse the next positional argument.
    ///
    /// # Errors
    ///
    /// Returns [`HaskellParseError`] if the argument cannot be parsed.
    pub fn arg<T: FromHaskell>(&mut self) -> Result<T, HaskellParseError> {
        let (val, rest) = T::parse_haskell(self.rest)?;
        self.rest = rest;
        Ok(val)
    }

    /// Finish parsing, consuming the closing `)` if the application was parenthesized.
    ///
    /// # Errors
    ///
    /// Returns [`HaskellParseError`] if a closing `)` is expected but not found.
    pub fn finish(self) -> Result<&'a str, HaskellParseError> {
        let rest = skip_ws(self.rest);
        if self.in_parens {
            rest.strip_prefix(')')
                .ok_or_else(|| HaskellParseError::ParseError {
                    message: format!(
                        "expected closing ')' for constructor application, got {rest:?}"
                    ),
                })
        } else {
            Ok(rest)
        }
    }
}

// ── Tests ────────────────────────────────────────────────────────────

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

    // ── ToHaskell tests ──────────────────────────────────────────────

    #[test]
    fn bool_to_haskell() {
        assert_eq!(true.to_haskell(), "True");
        assert_eq!(false.to_haskell(), "False");
    }

    #[test]
    fn unsigned_to_haskell() {
        assert_eq!(42u32.to_haskell(), "42");
        assert_eq!(0u8.to_haskell(), "0");
        assert_eq!(255u8.to_haskell(), "255");
    }

    #[test]
    fn signed_to_haskell() {
        assert_eq!(42i32.to_haskell(), "42");
        assert_eq!((-3i32).to_haskell(), "(-3)");
        assert_eq!(0i32.to_haskell(), "0");
    }

    #[test]
    fn float_to_haskell() {
        assert_eq!(3.0f64.to_haskell(), "3.0");
        assert_eq!((-3.0f64).to_haskell(), "(-3.0)");
        assert_eq!(f64::NAN.to_haskell(), "(0/0)");
        assert_eq!(f64::INFINITY.to_haskell(), "(1/0)");
        assert_eq!(f64::NEG_INFINITY.to_haskell(), "((-1)/0)");
        // Precision is preserved
        assert_eq!(1.234_567_890_123_456_f64.to_haskell(), "1.234567890123456");
        assert_eq!((-0.001f64).to_haskell(), "(-0.001)");
        assert_eq!(1.0f32.to_haskell(), "1.0");
    }

    #[test]
    fn string_to_haskell() {
        assert_eq!("hello".to_haskell(), r#""hello""#);
        assert_eq!("he\"llo".to_haskell(), r#""he\"llo""#);
        assert_eq!("new\nline".to_haskell(), r#""new\nline""#);
        assert_eq!("tab\there".to_haskell(), r#""tab\there""#);
        assert_eq!("back\\slash".to_haskell(), r#""back\\slash""#);
    }

    #[test]
    fn char_to_haskell() {
        assert_eq!('x'.to_haskell(), "'x'");
        assert_eq!('\''.to_haskell(), "'\\''");
        assert_eq!('\n'.to_haskell(), "'\\n'");
    }

    #[test]
    fn option_to_haskell() {
        assert_eq!(None::<i32>.to_haskell(), "Nothing");
        assert_eq!(Some(42u32).to_haskell(), "(Just 42)");
        assert_eq!(Some(-3i32).to_haskell(), "(Just (-3))");
    }

    #[test]
    fn vec_to_haskell() {
        assert_eq!(Vec::<i32>::new().to_haskell(), "[]");
        assert_eq!(vec![1u32, 2, 3].to_haskell(), "[1, 2, 3]");
    }

    #[test]
    fn tuple_to_haskell() {
        assert_eq!((1u32, true).to_haskell(), "(1, True)");
        assert_eq!((1u32, 2u32, 3u32).to_haskell(), "(1, 2, 3)");
    }

    #[test]
    fn nested_to_haskell() {
        assert_eq!(Some(vec![1i32, -2, 3]).to_haskell(), "(Just [1, (-2), 3])");
    }

    #[test]
    fn ref_to_haskell() {
        let x = 42u32;
        assert_eq!(x.to_haskell(), "42");
    }

    // ── FromHaskell tests ────────────────────────────────────────────

    #[test]
    fn bool_from_haskell() {
        assert!(bool::from_haskell("True").unwrap());
        assert!(!bool::from_haskell("False").unwrap());
    }

    #[test]
    fn unsigned_from_haskell() {
        assert_eq!(u32::from_haskell("42").unwrap(), 42);
        assert_eq!(u8::from_haskell("0").unwrap(), 0);
    }

    #[test]
    fn signed_from_haskell() {
        assert_eq!(i32::from_haskell("42").unwrap(), 42);
        assert_eq!(i32::from_haskell("(-3)").unwrap(), -3);
        assert_eq!(i32::from_haskell("0").unwrap(), 0);
    }

    #[test]
    fn float_from_haskell() {
        assert!((f64::from_haskell("3.0").unwrap() - 3.0).abs() < f64::EPSILON);
        assert!((f64::from_haskell("(-3.0)").unwrap() + 3.0).abs() < f64::EPSILON);
        assert!(f64::from_haskell("(0/0)").unwrap().is_nan());
        assert!(
            f64::from_haskell("(1/0)").unwrap().is_infinite()
                && f64::from_haskell("(1/0)").unwrap().is_sign_positive()
        );
        assert!(
            f64::from_haskell("((-1)/0)").unwrap().is_infinite()
                && f64::from_haskell("((-1)/0)").unwrap().is_sign_negative()
        );
    }

    #[test]
    fn string_from_haskell() {
        assert_eq!(String::from_haskell(r#""hello""#).unwrap(), "hello");
        assert_eq!(String::from_haskell(r#""he\"llo""#).unwrap(), "he\"llo");
        assert_eq!(String::from_haskell(r#""new\nline""#).unwrap(), "new\nline");
        assert_eq!(
            String::from_haskell(r#""back\\slash""#).unwrap(),
            "back\\slash"
        );
    }

    #[test]
    fn char_from_haskell() {
        assert_eq!(char::from_haskell("'x'").unwrap(), 'x');
        assert_eq!(char::from_haskell("'\\''").unwrap(), '\'');
        assert_eq!(char::from_haskell("'\\n'").unwrap(), '\n');
    }

    #[test]
    fn single_char_escapes_from_haskell() {
        assert_eq!(char::from_haskell("'\\a'").unwrap(), '\x07');
        assert_eq!(char::from_haskell("'\\b'").unwrap(), '\x08');
        assert_eq!(char::from_haskell("'\\f'").unwrap(), '\x0C');
        assert_eq!(char::from_haskell("'\\v'").unwrap(), '\x0B');
    }

    #[test]
    fn named_escapes_from_haskell() {
        assert_eq!(String::from_haskell(r#""\NUL""#).unwrap(), "\x00");
        assert_eq!(String::from_haskell(r#""\SOH""#).unwrap(), "\x01");
        assert_eq!(String::from_haskell(r#""\STX""#).unwrap(), "\x02");
        assert_eq!(String::from_haskell(r#""\ETX""#).unwrap(), "\x03");
        assert_eq!(String::from_haskell(r#""\EOT""#).unwrap(), "\x04");
        assert_eq!(String::from_haskell(r#""\ENQ""#).unwrap(), "\x05");
        assert_eq!(String::from_haskell(r#""\ACK""#).unwrap(), "\x06");
        assert_eq!(String::from_haskell(r#""\BEL""#).unwrap(), "\x07");
        assert_eq!(String::from_haskell(r#""\BS""#).unwrap(), "\x08");
        assert_eq!(String::from_haskell(r#""\HT""#).unwrap(), "\x09");
        assert_eq!(String::from_haskell(r#""\LF""#).unwrap(), "\x0A");
        assert_eq!(String::from_haskell(r#""\VT""#).unwrap(), "\x0B");
        assert_eq!(String::from_haskell(r#""\FF""#).unwrap(), "\x0C");
        assert_eq!(String::from_haskell(r#""\CR""#).unwrap(), "\x0D");
        assert_eq!(String::from_haskell(r#""\SO""#).unwrap(), "\x0E");
        assert_eq!(String::from_haskell(r#""\SI""#).unwrap(), "\x0F");
        assert_eq!(String::from_haskell(r#""\DLE""#).unwrap(), "\x10");
        assert_eq!(String::from_haskell(r#""\DC1""#).unwrap(), "\x11");
        assert_eq!(String::from_haskell(r#""\DC2""#).unwrap(), "\x12");
        assert_eq!(String::from_haskell(r#""\DC3""#).unwrap(), "\x13");
        assert_eq!(String::from_haskell(r#""\DC4""#).unwrap(), "\x14");
        assert_eq!(String::from_haskell(r#""\NAK""#).unwrap(), "\x15");
        assert_eq!(String::from_haskell(r#""\SYN""#).unwrap(), "\x16");
        assert_eq!(String::from_haskell(r#""\ETB""#).unwrap(), "\x17");
        assert_eq!(String::from_haskell(r#""\CAN""#).unwrap(), "\x18");
        assert_eq!(String::from_haskell(r#""\EM""#).unwrap(), "\x19");
        assert_eq!(String::from_haskell(r#""\SUB""#).unwrap(), "\x1A");
        assert_eq!(String::from_haskell(r#""\ESC""#).unwrap(), "\x1B");
        assert_eq!(String::from_haskell(r#""\FS""#).unwrap(), "\x1C");
        assert_eq!(String::from_haskell(r#""\GS""#).unwrap(), "\x1D");
        assert_eq!(String::from_haskell(r#""\RS""#).unwrap(), "\x1E");
        assert_eq!(String::from_haskell(r#""\US""#).unwrap(), "\x1F");
        assert_eq!(String::from_haskell(r#""\SP""#).unwrap(), "\x20");
        assert_eq!(String::from_haskell(r#""\DEL""#).unwrap(), "\x7F");
    }

    #[test]
    fn so_soh_prefix_conflict() {
        // SOH must match before SO to avoid prefix conflict
        assert_eq!(String::from_haskell(r#""\SOH""#).unwrap(), "\x01");
        assert_eq!(String::from_haskell(r#""\SO""#).unwrap(), "\x0E");
    }

    #[test]
    fn empty_escape_disambiguation() {
        // \& is Haskell's empty escape for disambiguating named escapes
        // "\SO\&H" is SO (0x0E) followed by 'H', not SOH (0x01)
        assert_eq!(String::from_haskell(r#""\SO\&H""#).unwrap(), "\x0EH");
        assert_eq!(String::from_haskell(r#""\NUL\&0""#).unwrap(), "\x000");
    }

    #[test]
    fn option_from_haskell() {
        assert_eq!(<Option<i32>>::from_haskell("Nothing").unwrap(), None);
        assert_eq!(<Option<u32>>::from_haskell("(Just 42)").unwrap(), Some(42));
        assert_eq!(
            <Option<i32>>::from_haskell("(Just (-3))").unwrap(),
            Some(-3)
        );
        assert_eq!(<Option<u32>>::from_haskell("Just 42").unwrap(), Some(42));
    }

    #[test]
    fn vec_from_haskell() {
        assert_eq!(<Vec<i32>>::from_haskell("[]").unwrap(), Vec::<i32>::new());
        assert_eq!(
            <Vec<u32>>::from_haskell("[1, 2, 3]").unwrap(),
            vec![1, 2, 3]
        );
        assert_eq!(
            <Vec<i32>>::from_haskell("[1, (-2), 3]").unwrap(),
            vec![1, -2, 3]
        );
    }

    #[test]
    fn tuple_from_haskell() {
        assert_eq!(<(u32, bool)>::from_haskell("(1, True)").unwrap(), (1, true));
        assert_eq!(
            <(u32, u32, u32)>::from_haskell("(1, 2, 3)").unwrap(),
            (1, 2, 3)
        );
    }

    #[test]
    fn nested_option_vec_roundtrip() {
        let val: Option<Vec<i32>> = Some(vec![1, -2, 3]);
        let s = val.to_haskell();
        assert_eq!(s, "(Just [1, (-2), 3])");
        let parsed = <Option<Vec<i32>>>::from_haskell(&s).unwrap();
        assert_eq!(parsed, val);
    }

    #[test]
    fn none_roundtrip() {
        let val: Option<i32> = None;
        let s = val.to_haskell();
        let parsed = <Option<i32>>::from_haskell(&s).unwrap();
        assert_eq!(parsed, val);
    }

    #[test]
    fn empty_vec_roundtrip() {
        let val: Vec<i32> = vec![];
        let s = val.to_haskell();
        let parsed = <Vec<i32>>::from_haskell(&s).unwrap();
        assert_eq!(parsed, val);
    }

    #[test]
    fn string_escaping_roundtrip() {
        let val = "hello\n\"world\"\t\\end".to_string();
        let s = val.to_haskell();
        let parsed = String::from_haskell(&s).unwrap();
        assert_eq!(parsed, val);
    }

    #[test]
    fn trailing_input_error() {
        let res = i32::from_haskell("42 extra");
        assert!(matches!(res, Err(HaskellParseError::TrailingInput { .. })));
    }

    // ── Builder tests ──────────────────────────────────────────────────

    #[test]
    fn record_builder_single_field() {
        let mut buf = String::new();
        record(&mut buf, "Foo")
            .field("bar", &42u32)
            .finish()
            .unwrap();
        assert_eq!(buf, "Foo {bar = 42}");
    }

    #[test]
    fn record_builder_mixed_types() {
        let mut buf = String::new();
        record(&mut buf, "Point")
            .field("x", &1u32)
            .field("y", &2.5f64)
            .field("label", &"origin")
            .finish()
            .unwrap();
        assert_eq!(buf, r#"Point {x = 1, y = 2.5, label = "origin"}"#);
    }

    #[test]
    fn record_builder_no_fields() {
        let mut buf = String::new();
        record(&mut buf, "Empty").finish().unwrap();
        assert_eq!(buf, "Empty {}");
    }

    #[test]
    fn app_builder_no_args() {
        let mut buf = String::new();
        app(&mut buf, "Nothing").finish().unwrap();
        assert_eq!(buf, "Nothing");
    }

    #[test]
    fn app_builder_single_arg() {
        let mut buf = String::new();
        app(&mut buf, "Just").arg(&42u32).finish().unwrap();
        assert_eq!(buf, "(Just 42)");
    }

    #[test]
    fn app_builder_mixed_types() {
        let mut buf = String::new();
        app(&mut buf, "Pair")
            .arg(&1u32)
            .arg(&true)
            .finish()
            .unwrap();
        assert_eq!(buf, "(Pair 1 True)");
    }

    #[test]
    fn parse_record_basic() {
        let (rec, rest) = parse_record("Foo", "Foo {bar = 42, baz = True}").unwrap();
        assert_eq!(rec.field::<u32>("bar").unwrap(), 42);
        assert!(rec.field::<bool>("baz").unwrap());
        assert_eq!(rest, "");
    }

    #[test]
    fn parse_record_nested() {
        let (rec, rest) = parse_record("X", r#"X {a = (Just [1, 2]), b = "hello"}"#).unwrap();
        assert_eq!(
            rec.field::<Option<Vec<u32>>>("a").unwrap(),
            Some(vec![1, 2])
        );
        assert_eq!(rec.field::<String>("b").unwrap(), "hello");
        assert_eq!(rest, "");
    }

    #[test]
    fn parse_record_missing_field() {
        let (rec, _) = parse_record("Foo", "Foo {bar = 42}").unwrap();
        assert!(rec.field::<u32>("missing").is_err());
    }

    #[test]
    fn parse_record_wrong_constructor() {
        assert!(parse_record("Bar", "Foo {x = 1}").is_err());
    }

    #[test]
    fn parse_app_no_args() {
        let p = parse_app("Nothing", "Nothing").unwrap();
        let rest = p.finish().unwrap();
        assert_eq!(rest, "");
    }

    #[test]
    fn parse_app_single_arg() {
        let mut p = parse_app("Just", "(Just 42)").unwrap();
        let val: u32 = p.arg().unwrap();
        assert_eq!(val, 42);
        let rest = p.finish().unwrap();
        assert_eq!(rest, "");
    }

    #[test]
    fn parse_app_mixed_types() {
        let mut p = parse_app("Pair", "(Pair 1 True)").unwrap();
        let x: u32 = p.arg().unwrap();
        let b: bool = p.arg().unwrap();
        assert_eq!((x, b), (1, true));
        let rest = p.finish().unwrap();
        assert_eq!(rest, "");
    }

    #[test]
    fn parse_app_wrong_constructor() {
        assert!(parse_app("Bar", "(Foo 1)").is_err());
    }

    #[test]
    fn record_roundtrip() {
        let mut buf = String::new();
        record(&mut buf, "Point")
            .field("x", &10i32)
            .field("y", &(-3i32))
            .field("name", &"test")
            .finish()
            .unwrap();

        let (rec, rest) = parse_record("Point", &buf).unwrap();
        assert_eq!(rec.field::<i32>("x").unwrap(), 10);
        assert_eq!(rec.field::<i32>("y").unwrap(), -3);
        assert_eq!(rec.field::<String>("name").unwrap(), "test");
        assert_eq!(rest, "");
    }

    #[test]
    fn app_roundtrip() {
        let mut buf = String::new();
        app(&mut buf, "Pair")
            .arg(&42u32)
            .arg(&"hello".to_string())
            .finish()
            .unwrap();

        let mut p = parse_app("Pair", &buf).unwrap();
        assert_eq!(p.arg::<u32>().unwrap(), 42);
        assert_eq!(p.arg::<String>().unwrap(), "hello");
        assert_eq!(p.finish().unwrap(), "");
    }
}