epics-base-rs 0.18.2

Pure Rust EPICS IOC core — record system, database, iocsh, calc engine
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
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};

use crate::error::{CaError, CaResult};
use crate::server::record::Record;
use crate::types::EpicsValue;

mod include;
mod substitution;
#[cfg(test)]
pub(crate) use include::parse_include_directive;
pub use include::{DbLoadConfig, expand_includes, override_dtyp, parse_db_file};
pub use substitution::{TemplateLoad, load_substitution_file, parse_substitutions};

/// Factory function that creates a record instance.
pub type RecordFactory = Box<dyn Fn() -> Box<dyn Record> + Send + Sync>;

/// Global registry of external record type factories.
/// External crates (e.g., asyn-rs) can register their own record types
/// to override built-in stubs.
static RECORD_FACTORY_REGISTRY: OnceLock<Mutex<HashMap<String, RecordFactory>>> = OnceLock::new();

fn get_registry() -> &'static Mutex<HashMap<String, RecordFactory>> {
    RECORD_FACTORY_REGISTRY.get_or_init(|| Mutex::new(HashMap::new()))
}

/// Register an external record type factory.
/// This allows external crates to override built-in record stubs.
/// The factory is checked FIRST in `create_record()`, so it takes priority.
pub fn register_record_type(name: &str, factory: RecordFactory) {
    let mut reg = get_registry()
        .lock()
        .expect("record factory registry mutex poisoned");
    reg.insert(name.to_string(), factory);
}

/// A record definition parsed from a .db file.
#[derive(Debug, Clone)]
pub struct DbRecordDef {
    pub record_type: String,
    pub name: String,
    pub fields: Vec<(String, String)>,
    /// Aliases declared inside the record body (`alias("name")`).
    /// Mirrors epics-base PR #336 — alias names are validated with
    /// the same rules as record names.
    pub aliases: Vec<String>,
    /// `info(tag, value)` pairs declared inside the record body.
    /// Mirrors `info` directives in EPICS db files; common tags include
    /// `asyn:READBACK` (asyn upstream PRs #60 / #208), `Q:form`, etc.
    pub info_tags: Vec<(String, String)>,
}

/// Validate a record (or alias) name against epics-base PR #78 rules.
///
/// Returns `Err(CaError::DbParseError)` for the hard-error cases (empty
/// name, embedded space/tab/quote/dot/dollar). Logs `tracing::warn!`
/// for the soft-warning cases (leading `-`/`+`/`[`/`{`, embedded
/// non-printable characters); the parse continues so legacy databases
/// still load.
///
/// The check runs **after** macro substitution, mirroring base where
/// `dbRecordHead` is invoked from the lexer with the substituted name.
pub(crate) fn validate_record_name(name: &str, line: usize, col: usize) -> CaResult<()> {
    if name.is_empty() {
        return Err(CaError::DbParseError {
            line,
            column: col,
            message: "record/alias name can't be empty".into(),
        });
    }
    for (i, c) in name.chars().enumerate() {
        if i == 0 && matches!(c, '-' | '+' | '[' | '{') {
            tracing::warn!(name, "record/alias name should not begin with '{}'", c);
        }
        // Non-printable ASCII (< space) is a warning, not an error —
        // matches base PR #78's `errlogPrintf("Warning: ...")` branch.
        if (c as u32) < 0x20 {
            tracing::warn!(
                name,
                "record/alias name should not contain non-printable 0x{:02X}",
                c as u32
            );
            continue;
        }
        if matches!(c, ' ' | '\t' | '"' | '\'' | '.' | '$') {
            return Err(CaError::DbParseError {
                line,
                column: col,
                message: format!("bad character '{c}' in record/alias name \"{name}\""),
            });
        }
    }
    Ok(())
}

/// Parse an EPICS .db file with macro substitution.
pub fn parse_db(input: &str, macros: &HashMap<String, String>) -> CaResult<Vec<DbRecordDef>> {
    let expanded = substitute_macros(input, macros);
    let mut records = Vec::new();
    // Standalone `alias("record","newname")` directives (dbYacc.y:275).
    // Resolved against the record list after the full file is parsed
    // so the alias target may appear before or after the directive.
    let mut global_aliases: Vec<(String, String)> = Vec::new();
    let chars: Vec<char> = expanded.chars().collect();
    let mut pos = 0;
    let mut line = 1;
    let mut col = 1;

    while pos < chars.len() {
        skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
        if pos >= chars.len() {
            break;
        }

        // Top-level keyword. C dbStatic (`dbYacc.y:48-62`) accepts
        // `record`/`grecord` plus the directives below at file scope.
        let word = read_word(&chars, &mut pos, &mut col);
        if word.is_empty() {
            pos += 1;
            col += 1;
            continue;
        }

        // `path "dir"` / `addpath "dir"` — search-path directives
        // (dbYacc.y:71-81). Include resolution is handled by the
        // file-expansion layer (`expand_includes`); by the time raw
        // text reaches `parse_db` the path is already fixed, so these
        // are accepted and skipped rather than erroring out.
        if word == "path" || word == "addpath" {
            skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
            let _dir = read_quoted_string(&chars, &mut pos, &mut line, &mut col)?;
            continue;
        }

        // `include "file"` (dbYacc.y:65-69). Includes are normally
        // inlined by `expand_includes` before `parse_db` runs; a bare
        // `include` reaching here means the caller parsed un-expanded
        // text. Accept the directive so the grammar matches C, but the
        // file is NOT loaded at this layer — that is the expansion
        // layer's job.
        if word == "include" {
            skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
            let _file = read_quoted_string(&chars, &mut pos, &mut line, &mut col)?;
            continue;
        }

        // Standalone 2-arg `alias("record","newname")` (dbYacc.y:275).
        // Distinct from the in-record-body `alias("name")` form. The
        // new name is attached to the named record's alias list once
        // all records are parsed (the target may appear later in the
        // file).
        if word == "alias" {
            skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
            expect_char(&chars, &mut pos, &mut col, '(', line)?;
            skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
            let target = read_quoted_string(&chars, &mut pos, &mut line, &mut col)?;
            skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
            expect_char(&chars, &mut pos, &mut col, ',', line)?;
            skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
            let alias_name = read_quoted_string(&chars, &mut pos, &mut line, &mut col)?;
            validate_record_name(&alias_name, line, col)?;
            skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
            expect_char(&chars, &mut pos, &mut col, ')', line)?;
            global_aliases.push((target, alias_name));
            continue;
        }

        if word != "record" && word != "grecord" {
            return Err(CaError::DbParseError {
                line,
                column: col,
                message: format!("expected 'record', got '{word}'"),
            });
        }

        skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
        expect_char(&chars, &mut pos, &mut col, '(', line)?;

        skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
        let rec_type = read_word(&chars, &mut pos, &mut col);

        skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
        expect_char(&chars, &mut pos, &mut col, ',', line)?;

        skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
        let name = read_quoted_string(&chars, &mut pos, &mut line, &mut col)?;
        validate_record_name(&name, line, col)?;

        skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
        expect_char(&chars, &mut pos, &mut col, ')', line)?;

        skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
        expect_char(&chars, &mut pos, &mut col, '{', line)?;

        let mut fields = Vec::new();
        let mut aliases: Vec<String> = Vec::new();
        let mut info_tags: Vec<(String, String)> = Vec::new();
        loop {
            skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
            if pos >= chars.len() {
                return Err(CaError::DbParseError {
                    line,
                    column: col,
                    message: "unexpected end of file in record body".into(),
                });
            }
            if chars[pos] == '}' {
                pos += 1;
                col += 1;
                break;
            }

            let kw = read_word(&chars, &mut pos, &mut col);
            if kw != "field" && kw != "info" && kw != "alias" {
                return Err(CaError::DbParseError {
                    line,
                    column: col,
                    message: format!("expected 'field', got '{kw}'"),
                });
            }

            if kw == "alias" {
                // alias("name") — capture and validate per PR #336.
                skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
                expect_char(&chars, &mut pos, &mut col, '(', line)?;
                skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
                let alias_name = read_quoted_string(&chars, &mut pos, &mut line, &mut col)?;
                validate_record_name(&alias_name, line, col)?;
                skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
                expect_char(&chars, &mut pos, &mut col, ')', line)?;
                aliases.push(alias_name);
                continue;
            }
            if kw == "info" {
                // info(tag, value) — capture for downstream consumers
                // (asyn:READBACK, Q:form, etc.). PR #60 / #208 needs
                // the asyn:READBACK tag in particular.
                //
                // Both `tag` and `value` accept quoted *or* unquoted
                // tokens. Base's dbStaticLib parser tolerates either
                // form and ad-core templates rely on the unquoted
                // shape (`info(asyn:READBACK, "1")`).
                skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
                expect_char(&chars, &mut pos, &mut col, '(', line)?;
                skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
                let tag = read_field_value(&chars, &mut pos, &mut line, &mut col)?;
                skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
                expect_char(&chars, &mut pos, &mut col, ',', line)?;
                skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
                let value = read_field_value(&chars, &mut pos, &mut line, &mut col)?;
                skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
                expect_char(&chars, &mut pos, &mut col, ')', line)?;
                info_tags.push((tag, value));
                continue;
            }

            skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
            expect_char(&chars, &mut pos, &mut col, '(', line)?;

            skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
            let field_name = read_word(&chars, &mut pos, &mut col);

            skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
            expect_char(&chars, &mut pos, &mut col, ',', line)?;

            skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
            let field_value = read_field_value(&chars, &mut pos, &mut line, &mut col)?;

            skip_whitespace_and_comments(&chars, &mut pos, &mut line, &mut col);
            expect_char(&chars, &mut pos, &mut col, ')', line)?;

            fields.push((field_name, field_value));
        }

        records.push(DbRecordDef {
            record_type: rec_type,
            name,
            fields,
            aliases,
            info_tags,
        });
    }

    // Attach standalone `alias("record","newname")` directives to the
    // matching record (C `dbAlias`). An alias whose target record is
    // not present in this database is a hard error, matching base
    // where `dbAlias` fails on an unknown record name.
    for (target, alias_name) in global_aliases {
        match records.iter_mut().find(|r| r.name == target) {
            Some(rec) => rec.aliases.push(alias_name),
            None => {
                return Err(CaError::DbParseError {
                    line: 0,
                    column: 0,
                    message: format!(
                        "alias \"{alias_name}\" refers to unknown record \"{target}\""
                    ),
                });
            }
        }
    }

    Ok(records)
}

/// Expand `$(...)` / `${...}` macro references, mirroring the C
/// `macLib` engine (`modules/libcom/src/macLib/macCore.c` `trans` /
/// `refer`). Implemented behaviors:
///
///   - `\<char>` blocks macro detection and copies both bytes verbatim
///     (`trans:740-749`; `macLib.plt:52`).
///   - macros are NOT expanded inside single quotes (`trans:722-733`).
///   - a reference name is itself macro-expanded before lookup
///     (`refer` runs `trans` on the name — `$($(WHICH))`).
///   - the name terminates at `=`, `,` or the closing bracket
///     (`macEnd = "=,)"`); `,name=val` introduces scoped macro
///     definitions visible only inside that reference's expansion.
///   - a resolved macro value is re-scanned for further `$(...)`
///     (chained expansion).
///   - an undefined macro with no default emits the placeholder
///     `$(name,undefined)` (`refer:errval = ",undefined)"`).
pub(crate) fn substitute_macros(input: &str, macros: &HashMap<String, String>) -> String {
    let chars: Vec<char> = input.chars().collect();
    let mut out = String::with_capacity(input.len());
    trans(
        &chars,
        0,
        macros,
        &mut Vec::new(),
        &mut Vec::new(),
        &mut out,
    );
    out
}

/// Translate `chars` into `out`, expanding macro references.
///
/// `scopes` is the stack of scoped-macro frames pushed by enclosing
/// `$(name,key=val)` references; lookup walks it innermost-first then
/// falls back to the base `macros` map. `visiting` is the stack of
/// macro names currently being expanded — it guards against a
/// self-referential macro (`A=$(A)`) recursing forever, mirroring C
/// `macCore.c`'s per-entry `visited` flag.
fn trans(
    chars: &[char],
    level: usize,
    macros: &HashMap<String, String>,
    scopes: &mut Vec<HashMap<String, String>>,
    visiting: &mut Vec<String>,
    out: &mut String,
) {
    let mut quote: Option<char> = None;
    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];

        // Track single/double quote state (C `trans` `quote` var).
        if let Some(q) = quote {
            if c == q {
                quote = None;
            }
        } else if c == '"' || c == '\'' {
            quote = Some(c);
        }

        // `\<char>`: emit both verbatim, skip macro detection.
        if c == '\\' && i + 1 < chars.len() {
            out.push('\\');
            out.push(chars[i + 1]);
            i += 2;
            continue;
        }

        // Macro reference: `$` followed by `(` or `{`, and NOT inside
        // single quotes (C `macRef && quote != '\''`).
        let mac_ref =
            c == '$' && i + 1 < chars.len() && (chars[i + 1] == '(' || chars[i + 1] == '{');
        if mac_ref && quote != Some('\'') {
            if let Some(next) = refer(chars, i, level, macros, scopes, visiting, out) {
                i = next;
                continue;
            }
        }

        out.push(c);
        i += 1;
    }
}

/// Expand one macro reference starting at `chars[start]` (`$`). On
/// success returns the index just past the closing bracket; returns
/// `None` if the reference is unterminated (caller copies `$` raw).
fn refer(
    chars: &[char],
    start: usize,
    level: usize,
    macros: &HashMap<String, String>,
    scopes: &mut Vec<HashMap<String, String>>,
    visiting: &mut Vec<String>,
    out: &mut String,
) -> Option<usize> {
    let close = if chars[start + 1] == '(' { ')' } else { '}' };
    // Find the matching close bracket, honoring nested `$(`/`${`.
    let body_start = start + 2;
    let mut depth = 1usize;
    let mut j = body_start;
    while j < chars.len() && depth > 0 {
        if j + 1 < chars.len() && chars[j] == '$' && (chars[j + 1] == '(' || chars[j + 1] == '{') {
            depth += 1;
            j += 2;
            continue;
        }
        if depth == 1 && chars[j] == close || depth > 1 && (chars[j] == ')' || chars[j] == '}') {
            depth -= 1;
            if depth == 0 {
                break;
            }
        }
        j += 1;
    }
    if depth != 0 {
        return None; // unterminated — caller emits '$' literally
    }
    let body = &chars[body_start..j];
    let after = j + 1;

    // Split the body at the first top-level `=` or `,` (the C
    // `macEnd` terminator set). Nested `$(...)` brackets are skipped
    // so a `=`/`,` inside an inner reference does not terminate.
    let split = top_level_terminator(body);
    let (name_chars, rest) = match split {
        Some(k) => (&body[..k], &body[k..]),
        None => (body, &body[body.len()..]),
    };

    // M-5: the name itself may contain macro references — expand it.
    let mut name = String::new();
    trans(name_chars, level + 1, macros, scopes, visiting, &mut name);

    // Default value (`=...`) and scoped definitions (`,k=v`).
    let mut default: Option<&[char]> = None;
    let mut scoped: Vec<(String, String)> = Vec::new();
    if let Some(first) = rest.first() {
        if *first == '=' {
            // Default runs until the first top-level `,` or end.
            let dflt = &rest[1..];
            let dsplit = top_level_comma(dflt);
            match dsplit {
                Some(k) => {
                    default = Some(&dflt[..k]);
                    parse_scoped(&dflt[k..], level, macros, scopes, visiting, &mut scoped);
                }
                None => default = Some(dflt),
            }
        } else if *first == ',' {
            parse_scoped(rest, level, macros, scopes, visiting, &mut scoped);
        }
    }

    // Push the scoped frame (visible only inside this expansion).
    let mut frame: HashMap<String, String> = HashMap::new();
    for (k, v) in scoped {
        frame.insert(k, v);
    }
    scopes.push(frame);

    // Look up: innermost scope first, then base macros.
    let resolved = scopes
        .iter()
        .rev()
        .find_map(|s| s.get(&name).cloned())
        .or_else(|| macros.get(&name).cloned());

    match resolved {
        Some(val) => {
            if visiting.contains(&name) {
                // Recursive reference (C `refentry->visited`): emit
                // the resolved value verbatim WITHOUT re-expansion to
                // break the cycle, rather than recursing forever.
                out.push_str(&val);
            } else {
                // M-1: re-scan the resolved value for further refs.
                visiting.push(name.clone());
                let val_chars: Vec<char> = val.chars().collect();
                trans(&val_chars, level + 1, macros, scopes, visiting, out);
                visiting.pop();
            }
        }
        None => match default {
            Some(def_chars) => {
                // Strip a single layer of surrounding quotes from the
                // default (`$(NAME="value")` → value).
                let def = strip_outer_quotes(def_chars);
                trans(def, level + 1, macros, scopes, visiting, out);
            }
            None => {
                // L-4: undefined macro placeholder. C emits
                // `$(name,undefined)` when warnings are enabled.
                out.push_str("$(");
                out.push_str(&name);
                out.push_str(",undefined)");
            }
        },
    }

    scopes.pop();
    Some(after)
}

/// Parse a `,key=val,key2=val2,...` scoped-definition tail. A bare
/// `,key` with no `=` defines nothing (C silently skips it).
fn parse_scoped(
    rest: &[char],
    level: usize,
    macros: &HashMap<String, String>,
    scopes: &mut Vec<HashMap<String, String>>,
    visiting: &mut Vec<String>,
    out: &mut Vec<(String, String)>,
) {
    let mut k = 0;
    while k < rest.len() {
        if rest[k] != ',' {
            break;
        }
        k += 1; // step over ','
        // Scoped name: up to next top-level `=` or `,`.
        let seg = &rest[k..];
        let term = top_level_terminator(seg);
        let (name_part, tail) = match term {
            Some(t) => (&seg[..t], &seg[t..]),
            None => (seg, &seg[seg.len()..]),
        };
        let mut sname = String::new();
        trans(name_part, level + 1, macros, scopes, visiting, &mut sname);
        k += name_part.len();
        if let Some('=') = tail.first() {
            let valseg = &tail[1..];
            let vterm = top_level_comma(valseg);
            let (val_part, _) = match vterm {
                Some(t) => (&valseg[..t], &valseg[t..]),
                None => (valseg, &valseg[valseg.len()..]),
            };
            let mut sval = String::new();
            trans(val_part, level + 1, macros, scopes, visiting, &mut sval);
            out.push((sname, sval));
            k += 1 + val_part.len();
        }
        // else: bare `,name` — no value, defines nothing.
    }
}

/// Index of the first top-level `=` or `,` in `body`, skipping any
/// `$(...)` / `${...}` nested reference.
fn top_level_terminator(body: &[char]) -> Option<usize> {
    let mut depth = 0usize;
    let mut i = 0;
    while i < body.len() {
        let c = body[i];
        if c == '$' && i + 1 < body.len() && (body[i + 1] == '(' || body[i + 1] == '{') {
            depth += 1;
            i += 2;
            continue;
        }
        if (c == ')' || c == '}') && depth > 0 {
            depth -= 1;
        } else if depth == 0 && (c == '=' || c == ',') {
            return Some(i);
        }
        i += 1;
    }
    None
}

/// Index of the first top-level `,` in `body` (used to split a
/// default value from trailing scoped definitions).
fn top_level_comma(body: &[char]) -> Option<usize> {
    let mut depth = 0usize;
    let mut i = 0;
    while i < body.len() {
        let c = body[i];
        if c == '$' && i + 1 < body.len() && (body[i + 1] == '(' || body[i + 1] == '{') {
            depth += 1;
            i += 2;
            continue;
        }
        if (c == ')' || c == '}') && depth > 0 {
            depth -= 1;
        } else if depth == 0 && c == ',' {
            return Some(i);
        }
        i += 1;
    }
    None
}

/// Strip one layer of matching surrounding quotes from a char slice.
fn strip_outer_quotes(s: &[char]) -> &[char] {
    if s.len() >= 2 && s[0] == '"' && s[s.len() - 1] == '"' {
        &s[1..s.len() - 1]
    } else {
        s
    }
}

fn skip_whitespace_and_comments(
    chars: &[char],
    pos: &mut usize,
    line: &mut usize,
    col: &mut usize,
) {
    while *pos < chars.len() {
        match chars[*pos] {
            ' ' | '\t' | '\r' => {
                *pos += 1;
                *col += 1;
            }
            '\n' => {
                *pos += 1;
                *line += 1;
                *col = 1;
            }
            '#' => {
                // Line comment
                while *pos < chars.len() && chars[*pos] != '\n' {
                    *pos += 1;
                }
            }
            _ => break,
        }
    }
}

fn read_word(chars: &[char], pos: &mut usize, col: &mut usize) -> String {
    let mut word = String::new();
    while *pos < chars.len() && (chars[*pos].is_ascii_alphanumeric() || chars[*pos] == '_') {
        word.push(chars[*pos]);
        *pos += 1;
        *col += 1;
    }
    word
}

fn read_quoted_string(
    chars: &[char],
    pos: &mut usize,
    line: &mut usize,
    col: &mut usize,
) -> CaResult<String> {
    if *pos >= chars.len() || chars[*pos] != '"' {
        return Err(CaError::DbParseError {
            line: *line,
            column: *col,
            message: "expected '\"'".into(),
        });
    }
    *pos += 1;
    *col += 1;

    // C dbStatic lexer parity (dbLex.l:90-93): a quoted `tokenSTRING`
    // matches `{doublequote}({dqschar}|{escape})*{doublequote}` where
    // `escape = {backslash}.`. The lexer keeps the **raw bytes** of the
    // string body — `dbmfStrdup(yytext+1)` then NUL-terminates one byte
    // early, so only the surrounding quotes are stripped; escape
    // sequences are NOT translated. Escape translation
    // (`dbTranslateEscape`) runs in `dbGetFieldValue`/`dbRecordInfo`
    // ONLY when the value still carries quotes, which a plain
    // `tokenSTRING` never does (dbLexRoutines.c:1398). So for `.db`
    // field/name/info values a `\n` stays the literal 2 chars `\n`.
    //
    // The escape sequence still consumes its following char for
    // delimiter purposes — `\"` does not terminate the string — but
    // both bytes are emitted verbatim.
    let mut s = String::new();
    while *pos < chars.len() && chars[*pos] != '"' {
        if chars[*pos] == '\\' && *pos + 1 < chars.len() {
            // Emit both the backslash and the escaped char raw.
            s.push('\\');
            s.push(chars[*pos + 1]);
            *pos += 2;
            *col += 2;
        } else if chars[*pos] == '\n' {
            // dbLex.l:131-133: a newline inside an unterminated quoted
            // string is a hard parse error (`yyerrorAbort("Newline in
            // string, closing quote missing")`), not a literal char.
            return Err(CaError::DbParseError {
                line: *line,
                column: *col,
                message: "Newline in string, closing quote missing".into(),
            });
        } else {
            s.push(chars[*pos]);
            *pos += 1;
            *col += 1;
        }
    }

    if *pos >= chars.len() {
        return Err(CaError::DbParseError {
            line: *line,
            column: *col,
            message: "unterminated string".into(),
        });
    }
    *pos += 1; // skip closing "
    *col += 1;
    Ok(s)
}

fn read_field_value(
    chars: &[char],
    pos: &mut usize,
    line: &mut usize,
    col: &mut usize,
) -> CaResult<String> {
    if *pos < chars.len() && chars[*pos] == '"' {
        return read_quoted_string(chars, pos, line, col);
    }

    // Unquoted value: a C `bareword` (dbLex.l:21) —
    // `[a-zA-Z0-9_\-+:.\[\]<>;]+`. Leading/trailing whitespace is
    // skipped; an embedded space or any character outside the
    // bareword set is a lexer error in C (the text would tokenize as
    // two tokens). L-5: the Rust parser previously accepted arbitrary
    // bytes up to the next `,`/`)`, which is strictly more permissive
    // than C.
    let is_bareword = |c: char| {
        c.is_ascii_alphanumeric()
            || matches!(c, '_' | '-' | '+' | ':' | '.' | '[' | ']' | '<' | '>' | ';')
    };

    let mut s = String::new();
    while *pos < chars.len() && is_bareword(chars[*pos]) {
        s.push(chars[*pos]);
        *pos += 1;
        *col += 1;
    }
    // Skip trailing whitespace before the delimiter.
    while *pos < chars.len() && matches!(chars[*pos], ' ' | '\t' | '\r' | '\n') {
        if chars[*pos] == '\n' {
            *line += 1;
            *col = 0;
        }
        *pos += 1;
        *col += 1;
    }
    // The only thing allowed after an unquoted value is the field
    // delimiter (`,` or `)`); anything else means the value contained
    // an illegal bareword character.
    if *pos < chars.len() && chars[*pos] != ')' && chars[*pos] != ',' {
        return Err(CaError::DbParseError {
            line: *line,
            column: *col,
            message: format!(
                "illegal character '{}' in unquoted value (expected a quoted string or bareword)",
                chars[*pos]
            ),
        });
    }
    Ok(s)
}

fn expect_char(
    chars: &[char],
    pos: &mut usize,
    col: &mut usize,
    expected: char,
    line: usize,
) -> CaResult<()> {
    if *pos >= chars.len() || chars[*pos] != expected {
        let got = if *pos < chars.len() {
            chars[*pos].to_string()
        } else {
            "EOF".to_string()
        };
        return Err(CaError::DbParseError {
            line,
            column: *col,
            message: format!("expected '{expected}', got '{got}'"),
        });
    }
    *pos += 1;
    *col += 1;
    Ok(())
}

/// Create a record from a type name.
/// Checks the external factory registry first, then falls back to built-in types.
pub fn create_record(record_type: &str) -> CaResult<Box<dyn Record>> {
    // Check external registry first (allows overrides from e.g. asyn-rs)
    if let Ok(reg) = get_registry().lock() {
        if let Some(factory) = reg.get(record_type) {
            return Ok(factory());
        }
    }

    use crate::server::records::*;

    match record_type {
        "ai" => Ok(Box::new(ai::AiRecord::default())),
        "ao" => Ok(Box::new(ao::AoRecord::default())),
        "bi" => Ok(Box::new(bi::BiRecord::default())),
        "bo" => Ok(Box::new(bo::BoRecord::default())),
        "busy" => Ok(Box::new(busy::BusyRecord::default())),
        "stringin" => Ok(Box::new(stringin::StringinRecord::default())),
        "asyn" => Ok(Box::new(asyn_record::AsynRecord::default())),
        "stringout" => Ok(Box::new(stringout::StringoutRecord::default())),
        "longin" => Ok(Box::new(longin::LonginRecord::default())),
        "longout" => Ok(Box::new(longout::LongoutRecord::default())),
        "int64in" => Ok(Box::new(int64in::Int64inRecord::default())),
        "int64out" => Ok(Box::new(int64out::Int64outRecord::default())),
        "lsi" => Ok(Box::new(lsi::LsiRecord::default())),
        "lso" => Ok(Box::new(lso::LsoRecord::default())),
        "mbbi" => Ok(Box::new(mbbi::MbbiRecord::default())),
        "mbbo" => Ok(Box::new(mbbo::MbboRecord::default())),
        "mbbiDirect" => Ok(Box::new(mbbi_direct::MbbiDirectRecord::default())),
        "mbboDirect" => Ok(Box::new(mbbo_direct::MbboDirectRecord::default())),
        "event" => Ok(Box::new(event::EventRecord::default())),
        "printf" => Ok(Box::new(printf::PrintfRecord::default())),
        "swait" => Ok(Box::new(swait::SwaitRecord::default())),
        "waveform" => Ok(Box::new(waveform::WaveformRecord::with_kind(
            waveform::ArrayKind::Waveform,
        ))),
        "aai" => Ok(Box::new(waveform::WaveformRecord::with_kind(
            waveform::ArrayKind::Aai,
        ))),
        "aao" => Ok(Box::new(waveform::WaveformRecord::with_kind(
            waveform::ArrayKind::Aao,
        ))),
        "subArray" => Ok(Box::new(waveform::WaveformRecord::with_kind(
            waveform::ArrayKind::SubArray,
        ))),
        "calc" => Ok(Box::new(calc::CalcRecord::default())),
        "fanout" => Ok(Box::new(fanout::FanoutRecord::default())),
        "seq" => Ok(Box::new(seq::SeqRecord::default())),
        "sseq" => Ok(Box::new(sseq::SseqRecord::default())),
        "scalcout" => Ok(Box::new(scalcout::ScalcoutRecord::default())),
        "transform" => Ok(Box::new(transform::TransformRecord::default())),
        "calcout" => Ok(Box::new(calcout::CalcoutRecord::default())),
        "dfanout" => Ok(Box::new(dfanout::DfanoutRecord::default())),
        "compress" => Ok(Box::new(compress::CompressRecord::default())),
        "histogram" => Ok(Box::new(histogram::HistogramRecord::default())),
        "sel" => Ok(Box::new(sel::SelRecord::default())),
        "sub" => Ok(Box::new(sub_record::SubRecord::default())),
        "aSub" => Ok(Box::new(asub_record::ASubRecord::default())),
        _ => Err(CaError::DbParseError {
            line: 0,
            column: 0,
            message: format!("unknown record type: '{record_type}'"),
        }),
    }
}

/// Create a record, checking extra factories first, then built-in types.
/// Preferred over `create_record()` — avoids the global registry.
pub fn create_record_with_factories(
    record_type: &str,
    extra_factories: &std::collections::HashMap<String, super::RecordFactory>,
) -> CaResult<Box<dyn Record>> {
    if let Some(factory) = extra_factories.get(record_type) {
        return Ok(factory());
    }
    create_record(record_type)
}

/// Apply fields from a DbRecordDef to a record.
/// Returns the record along with any common field values.
pub fn apply_fields(
    record: &mut Box<dyn Record>,
    fields: &[(String, String)],
    common_fields: &mut Vec<(String, EpicsValue)>,
) -> CaResult<()> {
    for (name, value_str) in fields {
        let upper_name = name.to_uppercase();

        // Try record-specific field first
        let field_desc = record
            .field_list()
            .iter()
            .find(|f| f.name == upper_name.as_str());

        if let Some(desc) = field_desc {
            let value = EpicsValue::parse(desc.dbf_type, value_str).map_err(|e| {
                CaError::InvalidValue(format!(
                    "field {upper_name} (type {:?}): cannot parse '{}': {e}",
                    desc.dbf_type, value_str
                ))
            })?;
            record.put_field(&upper_name, value)?;
        } else {
            // Store as common field for RecordInstance to handle
            common_fields.push((upper_name, EpicsValue::String(value_str.clone())));
        }
    }
    Ok(())
}

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

    #[test]
    fn test_parse_simple_db() {
        let input = r#"
    record(ai, "TEMP") {
    field(DESC, "Temperature")
    field(SCAN, "1 second")
    field(HOPR, "100")
    field(LOPR, "0")
    }
    "#;
        let records = parse_db(input, &HashMap::new()).unwrap();
        assert_eq!(records.len(), 1);
        assert_eq!(records[0].record_type, "ai");
        assert_eq!(records[0].name, "TEMP");
        assert_eq!(records[0].fields.len(), 4);
        assert_eq!(records[0].fields[0], ("DESC".into(), "Temperature".into()));
    }

    #[test]
    fn test_macro_substitution() {
        let input = r#"
    record(ai, "$(P)TEMP") {
    field(DESC, "$(D=Default Desc)")
    }
    "#;
        let mut macros = HashMap::new();
        macros.insert("P".to_string(), "IOC:".to_string());

        let records = parse_db(input, &macros).unwrap();
        assert_eq!(records[0].name, "IOC:TEMP");
        assert_eq!(records[0].fields[0].1, "Default Desc");
    }

    #[test]
    fn test_multiple_records() {
        let input = r#"
    record(ai, "TEMP1") {
    field(VAL, "25.0")
    }
    record(bo, "SWITCH") {
    field(VAL, "1")
    field(ZNAM, "Off")
    field(ONAM, "On")
    }
    "#;
        let records = parse_db(input, &HashMap::new()).unwrap();
        assert_eq!(records.len(), 2);
        assert_eq!(records[0].record_type, "ai");
        assert_eq!(records[1].record_type, "bo");
    }

    #[test]
    fn test_comments() {
        let input = r#"
    # This is a comment
    record(ai, "TEMP") {
    # Another comment
    field(VAL, "25.0")
    }
    "#;
        let records = parse_db(input, &HashMap::new()).unwrap();
        assert_eq!(records.len(), 1);
    }

    #[test]
    fn test_unknown_record_type() {
        let result = create_record("nonexistent");
        assert!(result.is_err());
    }

    #[test]
    fn test_quoted_string_escape() {
        // C dbStatic parity (H-2): a quoted `tokenSTRING` keeps escape
        // bytes RAW — only the surrounding quotes are stripped. A `.db`
        // field value `"hello \"world\""` therefore stores the literal
        // 15 chars `hello \"world\"`, NOT `hello "world"`. The `\"`
        // still does not terminate the string.
        let input = r#"
    record(stringin, "TEST") {
    field(VAL, "hello \"world\"")
    }
    "#;
        let records = parse_db(input, &HashMap::new()).unwrap();
        assert_eq!(records[0].fields[0].1, r#"hello \"world\""#);
    }

    #[test]
    fn test_quoted_string_keeps_escapes_raw() {
        // H-2: `\n`, `\t`, `\\` are all kept verbatim for `.db` field
        // values — a C IOC stores the literal backslash sequences.
        let input = r#"
    record(stringin, "TEST") {
    field(DESC, "line1\nline2")
    field(OUT, "a\\b\tc")
    }
    "#;
        let records = parse_db(input, &HashMap::new()).unwrap();
        assert_eq!(records[0].fields[0].1, r"line1\nline2");
        assert_eq!(records[0].fields[1].1, r"a\\b\tc");
    }

    #[test]
    fn test_quoted_string_newline_aborts() {
        // H-3: a literal newline inside a quoted string (missing
        // closing quote) is a hard parse error in C (dbLex.l:131-133).
        let input = "record(stringin, \"TEST\") {\n    field(DESC, \"line1\nline2\")\n}\n";
        let res = parse_db(input, &HashMap::new());
        assert!(
            matches!(res, Err(CaError::DbParseError { ref message, .. })
                if message.contains("Newline in string")),
            "expected newline-in-string abort, got {res:?}"
        );
    }

    #[test]
    fn test_macro_with_quoted_default_in_string() {
        // C EPICS macLib treats quotes inside $(...) as literal characters.
        // e.g. $(XPOS="") means "default to empty-string pair".
        let input = r#"
    record(longout, "$(P)$(R)PositionXLink") {
    field(DOL, "$(XPOS="") CP MS")
    }
    "#;
        let mut macros = HashMap::new();
        macros.insert("P".to_string(), "SIM1:".to_string());
        macros.insert("R".to_string(), "Over1:1:".to_string());
        macros.insert("XPOS".to_string(), "SIM1:ROI1:MinX_RBV".to_string());
        let records = parse_db(input, &macros).unwrap();
        assert_eq!(records[0].fields[0].1, "SIM1:ROI1:MinX_RBV CP MS");
    }

    #[test]
    fn test_macro_with_quoted_default_unset() {
        // When XPOS is not set, $(XPOS="") should expand to "" (literal quotes)
        let input = r#"
    record(longout, "TEST:Link") {
    field(DOL, "$(XPOS="") CP MS")
    }
    "#;
        let macros = HashMap::new();
        let records = parse_db(input, &macros).unwrap();
        // With undefined macro and default="", the field gets the raw default
        assert!(records[0].fields[0].1.contains("CP MS"));
    }

    #[test]
    fn test_recursive_macro_default() {
        // $(TS_PORT=$(PORT)_TS) with PORT=ATTR1 → ATTR1_TS
        let input = r#"
    record(stringin, "TEST") {
    field(VAL, "$(TS_PORT=$(PORT)_TS)")
    }
    "#;
        let mut macros = HashMap::new();
        macros.insert("PORT".to_string(), "ATTR1".to_string());
        let records = parse_db(input, &macros).unwrap();
        assert_eq!(records[0].fields[0].1, "ATTR1_TS");
    }

    #[test]
    fn test_substitute_directive_in_expand() {
        use std::io::Write;
        let dir = tempfile::tempdir().unwrap();

        // Create a simple child template
        let child = dir.path().join("child.db");
        let mut f = std::fs::File::create(&child).unwrap();
        writeln!(f, r#"record(ai, "$(P)$(R)Val") {{"#).unwrap();
        writeln!(f, r#"    field(VAL, "$(ADDR)")"#).unwrap();
        writeln!(f, r#"}}"#).unwrap();

        // Create parent with substitute + include
        let parent = dir.path().join("parent.db");
        let mut f = std::fs::File::create(&parent).unwrap();
        writeln!(f, r#"substitute "R=A:,ADDR=0""#).unwrap();
        writeln!(f, r#"include "child.db""#).unwrap();
        writeln!(f, r#"substitute "R=B:,ADDR=1""#).unwrap();
        writeln!(f, r#"include "child.db""#).unwrap();

        let mut macros = HashMap::new();
        macros.insert("P".to_string(), "IOC:".to_string());
        let config = DbLoadConfig {
            include_paths: vec![],
            max_include_depth: 10,
        };
        let records = parse_db_file(&parent, &macros, &config).unwrap();
        assert_eq!(records.len(), 2);
        assert_eq!(records[0].name, "IOC:A:Val");
        assert_eq!(records[0].fields[0].1, "0");
        assert_eq!(records[1].name, "IOC:B:Val");
        assert_eq!(records[1].fields[0].1, "1");
    }

    #[test]
    fn test_empty_string_numeric_parse() {
        // C EPICS treats empty VAL as 0 for numeric record types
        let input = r#"
    record(longin, "TEST:Int") {
    field(VAL, "")
    }
    "#;
        let records = parse_db(input, &HashMap::new()).unwrap();
        // Should parse without error — empty string → 0
        assert_eq!(records.len(), 1);
    }

    #[test]
    fn test_calcout_process() {
        use crate::server::record::Record;
        use crate::server::records::calcout::CalcoutRecord;

        let mut rec = CalcoutRecord::default();
        rec.put_field("CALC", EpicsValue::String("A+B".into()))
            .unwrap();
        rec.put_field("A", EpicsValue::Double(3.0)).unwrap();
        rec.put_field("B", EpicsValue::Double(4.0)).unwrap();
        rec.process().unwrap();
        match rec.get_field("VAL") {
            Some(EpicsValue::Double(v)) => assert!((v - 7.0).abs() < 1e-10),
            other => panic!("expected Double(7.0), got {:?}", other),
        }
    }

    #[test]
    fn test_calcout_oopt() {
        use crate::server::record::Record;
        use crate::server::records::calcout::CalcoutRecord;

        let mut rec = CalcoutRecord::default();
        rec.put_field("CALC", EpicsValue::String("A".into()))
            .unwrap();
        rec.put_field("OOPT", EpicsValue::Short(1)).unwrap(); // On Change
        rec.put_field("A", EpicsValue::Double(5.0)).unwrap();

        // First process — value changes from 0 to 5
        rec.process().unwrap();
        assert!((rec.oval - 5.0).abs() < 1e-10);

        // Second process — same value, OVAL should not update (but val still computes)
        rec.process().unwrap();
        // OVAL is still 5.0 since val didn't change
    }

    #[test]
    fn test_calcout_dopt() {
        use crate::server::record::Record;
        use crate::server::records::calcout::CalcoutRecord;

        let mut rec = CalcoutRecord::default();
        rec.put_field("CALC", EpicsValue::String("A+B".into()))
            .unwrap();
        rec.put_field("OCAL", EpicsValue::String("A*B".into()))
            .unwrap();
        rec.put_field("DOPT", EpicsValue::Short(1)).unwrap(); // Use OCAL
        rec.put_field("A", EpicsValue::Double(3.0)).unwrap();
        rec.put_field("B", EpicsValue::Double(4.0)).unwrap();
        rec.process().unwrap();

        // VAL = A+B = 7, OVAL = A*B = 12
        match rec.get_field("VAL") {
            Some(EpicsValue::Double(v)) => assert!((v - 7.0).abs() < 1e-10),
            other => panic!("expected Double(7.0), got {:?}", other),
        }
        match rec.get_field("OVAL") {
            Some(EpicsValue::Double(v)) => assert!((v - 12.0).abs() < 1e-10),
            other => panic!("expected Double(12.0), got {:?}", other),
        }
    }

    #[test]
    fn test_dfanout_basic() {
        use crate::server::record::Record;
        use crate::server::records::dfanout::DfanoutRecord;

        let mut rec = DfanoutRecord::default();
        rec.put_field("VAL", EpicsValue::Double(42.0)).unwrap();
        assert_eq!(rec.record_type(), "dfanout");
        match rec.get_field("VAL") {
            Some(EpicsValue::Double(v)) => assert!((v - 42.0).abs() < 1e-10),
            other => panic!("expected Double(42.0), got {:?}", other),
        }
    }

    #[test]
    fn test_dfanout_output_links() {
        use crate::server::record::Record;
        use crate::server::records::dfanout::DfanoutRecord;

        let mut rec = DfanoutRecord::default();
        rec.put_field("OUTA", EpicsValue::String("REC_A".into()))
            .unwrap();
        rec.put_field("OUTB", EpicsValue::String("REC_B".into()))
            .unwrap();
        let links = rec.output_links();
        assert_eq!(links.len(), 2);
    }

    #[test]
    fn test_compress_circular_buffer() {
        use crate::server::record::Record;
        use crate::server::records::compress::CompressRecord;

        let mut rec = CompressRecord::new(5, 4); // nsam=5, alg=Circular Buffer
        for i in 0..7 {
            rec.push_value(i as f64);
        }
        // C `get_array_info` linearises FIFO oldest→newest. After
        // 7 pushes to nsam=5: nuse saturates at 5, the last 5 values
        // are [2, 3, 4, 5, 6].
        match rec.get_field("VAL") {
            Some(EpicsValue::DoubleArray(arr)) => {
                assert_eq!(arr, vec![2.0, 3.0, 4.0, 5.0, 6.0]);
            }
            other => panic!("expected DoubleArray, got {:?}", other),
        }
    }

    #[test]
    fn test_compress_n_to_1_mean() {
        use crate::server::record::Record;
        use crate::server::records::compress::CompressRecord;

        let mut rec = CompressRecord::new(10, 2); // alg=Mean
        rec.put_field("N", EpicsValue::Long(3)).unwrap();
        rec.push_value(3.0);
        rec.push_value(6.0);
        rec.push_value(9.0); // mean = 6.0
        match rec.get_field("VAL") {
            Some(EpicsValue::DoubleArray(arr)) => {
                assert!((arr[0] - 6.0).abs() < 1e-10);
            }
            other => panic!("expected DoubleArray, got {:?}", other),
        }
    }

    #[test]
    fn test_histogram_bucket_count() {
        use crate::server::records::histogram::HistogramRecord;

        let mut rec = HistogramRecord::new(10, 0.0, 10.0);
        rec.add_sample(2.5); // bucket 2
        rec.add_sample(2.7); // bucket 2
        // C `histogramRecord.c:340-345` selects the bucket with a
        // closed upper edge (`temp <= i*wdth`): a value exactly on a
        // boundary lands in the LOWER bucket. sgnl=7.0, wdth=1.0 ->
        // i=7 is the first `7.0 <= i*1.0`, dest = i-1 = bucket 6.
        rec.add_sample(7.0); // boundary value -> bucket 6 (C parity)
        assert_eq!(rec.val[2], 2);
        assert_eq!(rec.val[6], 1);
    }

    #[test]
    fn test_histogram_out_of_range() {
        use crate::server::records::histogram::HistogramRecord;

        let mut rec = HistogramRecord::new(10, 0.0, 10.0);
        rec.add_sample(-1.0); // below range
        rec.add_sample(10.0); // at upper limit (excluded)
        rec.add_sample(15.0); // above range
        let total: i32 = rec.val.iter().sum();
        assert_eq!(total, 0);
    }

    #[test]
    fn test_sel_specified() {
        use crate::server::record::Record;
        use crate::server::records::sel::SelRecord;

        let mut rec = SelRecord::default();
        rec.put_field("SELM", EpicsValue::Short(0)).unwrap(); // Specified
        rec.put_field("SELN", EpicsValue::Short(2)).unwrap(); // Select C
        rec.put_field("C", EpicsValue::Double(99.0)).unwrap();
        rec.process().unwrap();
        match rec.get_field("VAL") {
            Some(EpicsValue::Double(v)) => assert!((v - 99.0).abs() < 1e-10),
            other => panic!("expected Double(99.0), got {:?}", other),
        }
    }

    #[test]
    fn test_sel_high_low_median() {
        use crate::server::record::Record;
        use crate::server::records::sel::SelRecord;

        let mut rec = SelRecord::default();
        rec.put_field("A", EpicsValue::Double(10.0)).unwrap();
        rec.put_field("B", EpicsValue::Double(30.0)).unwrap();
        rec.put_field("C", EpicsValue::Double(20.0)).unwrap();

        // High
        rec.put_field("SELM", EpicsValue::Short(1)).unwrap();
        rec.process().unwrap();
        match rec.get_field("VAL") {
            Some(EpicsValue::Double(v)) => assert!((v - 30.0).abs() < 1e-10),
            other => panic!("expected Double(30.0), got {:?}", other),
        }

        // Low
        rec.put_field("SELM", EpicsValue::Short(2)).unwrap();
        rec.process().unwrap();
        match rec.get_field("VAL") {
            Some(EpicsValue::Double(v)) => assert!((v - 10.0).abs() < 1e-10), // min of finite values (A=10,B=30,C=20)
            other => panic!("expected near 0.0, got {:?}", other),
        }
    }

    #[test]
    fn test_sub_record_register_and_call() {
        use crate::server::record::{Record, RecordInstance, SubroutineFn};
        use crate::server::records::sub_record::SubRecord;
        use std::sync::Arc;

        let mut rec = SubRecord::default();
        rec.put_field("SNAM", EpicsValue::String("double_val".into()))
            .unwrap();
        rec.put_field("VAL", EpicsValue::Double(5.0)).unwrap();

        let mut instance = RecordInstance::new("TEST_SUB".into(), rec);
        let sub_fn: SubroutineFn = Box::new(|record: &mut dyn Record| {
            if let Some(EpicsValue::Double(v)) = record.get_field("VAL") {
                record.put_field("VAL", EpicsValue::Double(v * 2.0))?;
            }
            Ok(())
        });
        instance.subroutine = Some(Arc::new(sub_fn));

        instance.process_local().unwrap();

        match instance.record.get_field("VAL") {
            Some(EpicsValue::Double(v)) => assert!((v - 10.0).abs() < 1e-10),
            other => panic!("expected Double(10.0), got {:?}", other),
        }
    }

    #[test]
    fn test_new_record_types_in_db() {
        let input = r#"
    record(calcout, "TEST_CO") {
    field(CALC, "A+1")
    }
    record(dfanout, "TEST_DF") {
    field(VAL, "5.0")
    }
    record(compress, "TEST_CMP") {
    field(DESC, "test compress")
    }
    record(histogram, "TEST_HIST") {
    field(DESC, "test hist")
    }
    record(sel, "TEST_SEL") {
    field(SELM, "0")
    }
    record(sub, "TEST_SUB") {
    field(SNAM, "my_sub")
    }
    "#;
        let records = parse_db(input, &HashMap::new()).unwrap();
        assert_eq!(records.len(), 6);
        // Verify they can all be created
        for def in &records {
            create_record(&def.record_type).unwrap();
        }
    }

    // ===== include / parse_db_file tests =====

    #[test]
    fn test_parse_include_directive() {
        // Normal include
        assert_eq!(
            parse_include_directive(r#"include "foo.template""#),
            Some("foo.template".to_string())
        );
        // With leading whitespace
        assert_eq!(
            parse_include_directive(r#"  include "bar.db""#),
            Some("bar.db".to_string())
        );
        // With trailing comment
        assert_eq!(
            parse_include_directive(r#"include "baz.template" # a comment"#),
            Some("baz.template".to_string())
        );
        // No quote — not an include
        assert_eq!(parse_include_directive("include something"), None);
        // Comment line
        assert_eq!(parse_include_directive(r#"# include "ignored.db""#), None);
        // Not an include keyword
        assert_eq!(parse_include_directive("record(ai, \"X\") {"), None);
        // "includes" is not "include"
        assert_eq!(parse_include_directive(r#"includes "nope.db""#), None);
    }

    #[test]
    fn test_commented_include_ignored() {
        assert_eq!(parse_include_directive(r#"# include "file.db""#), None);
        assert_eq!(parse_include_directive(r#"  # include "file.db""#), None);
    }

    #[test]
    fn test_expand_includes() {
        use std::io::Write;
        let dir = tempfile::tempdir().unwrap();

        // Create child.db
        let child_path = dir.path().join("child.db");
        let mut f = std::fs::File::create(&child_path).unwrap();
        writeln!(f, r#"record(ai, "CHILD") {{"#).unwrap();
        writeln!(f, r#"    field(VAL, "1.0")"#).unwrap();
        writeln!(f, r#"}}"#).unwrap();

        // Create parent.db that includes child.db
        let parent_path = dir.path().join("parent.db");
        let mut f = std::fs::File::create(&parent_path).unwrap();
        writeln!(f, r#"record(ao, "PARENT") {{"#).unwrap();
        writeln!(f, r#"    field(VAL, "2.0")"#).unwrap();
        writeln!(f, r#"}}"#).unwrap();
        writeln!(f, r#"include "child.db""#).unwrap();

        let config = DbLoadConfig::default();
        let result = expand_includes(&parent_path, &HashMap::new(), &config).unwrap();
        assert!(result.contains(r#"record(ao, "PARENT")"#));
        assert!(result.contains(r#"record(ai, "CHILD")"#));

        // Verify it parses correctly
        let records = parse_db(&result, &HashMap::new()).unwrap();
        assert_eq!(records.len(), 2);
    }

    #[test]
    fn test_circular_include_error() {
        use std::io::Write;
        let dir = tempfile::tempdir().unwrap();

        let a_path = dir.path().join("a.template");
        let b_path = dir.path().join("b.template");

        let mut fa = std::fs::File::create(&a_path).unwrap();
        writeln!(fa, r#"include "b.template""#).unwrap();

        let mut fb = std::fs::File::create(&b_path).unwrap();
        writeln!(fb, r#"include "a.template""#).unwrap();

        let config = DbLoadConfig::default();
        let result = expand_includes(&a_path, &HashMap::new(), &config);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("circular include"), "error was: {err}");
    }

    #[test]
    fn test_duplicate_include_allowed() {
        use std::io::Write;
        let dir = tempfile::tempdir().unwrap();

        let shared_path = dir.path().join("shared.db");
        let mut f = std::fs::File::create(&shared_path).unwrap();
        writeln!(f, r#"record(ai, "SHARED") {{"#).unwrap();
        writeln!(f, r#"    field(VAL, "0")"#).unwrap();
        writeln!(f, r#"}}"#).unwrap();

        // main.db includes shared.db twice (not circular, just duplicate)
        let main_path = dir.path().join("main.db");
        let mut f = std::fs::File::create(&main_path).unwrap();
        writeln!(f, r#"include "shared.db""#).unwrap();
        writeln!(f, r#"include "shared.db""#).unwrap();

        let config = DbLoadConfig::default();
        let result = expand_includes(&main_path, &HashMap::new(), &config).unwrap();
        // shared.db content appears twice
        assert_eq!(result.matches(r#"record(ai, "SHARED")"#).count(), 2);
    }

    #[test]
    fn test_include_depth_limit() {
        use std::io::Write;
        let dir = tempfile::tempdir().unwrap();

        // Create a chain: file0 -> file1 -> file2 -> ... -> file33
        for i in 0..34 {
            let path = dir.path().join(format!("file{i}.db"));
            let mut f = std::fs::File::create(&path).unwrap();
            if i < 33 {
                writeln!(f, r#"include "file{}.db""#, i + 1).unwrap();
            } else {
                writeln!(f, r#"record(ai, "DEEP") {{"#).unwrap();
                writeln!(f, r#"    field(VAL, "0")"#).unwrap();
                writeln!(f, r#"}}"#).unwrap();
            }
        }

        let config = DbLoadConfig {
            include_paths: vec![],
            max_include_depth: 32,
        };
        let result = expand_includes(&dir.path().join("file0.db"), &HashMap::new(), &config);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("depth limit"), "error was: {err}");
    }

    #[test]
    fn test_include_not_found_error() {
        use std::io::Write;
        let dir = tempfile::tempdir().unwrap();

        let path = dir.path().join("main.db");
        let mut f = std::fs::File::create(&path).unwrap();
        writeln!(f, r#"include "nonexistent.db""#).unwrap();

        let config = DbLoadConfig::default();
        let result = expand_includes(&path, &HashMap::new(), &config);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("not found"), "error was: {err}");
    }

    #[test]
    fn test_include_with_macro_filename() {
        use std::io::Write;
        let dir = tempfile::tempdir().unwrap();
        let subdir = dir.path().join("sub");
        std::fs::create_dir(&subdir).unwrap();

        let child_path = subdir.join("child.db");
        let mut f = std::fs::File::create(&child_path).unwrap();
        writeln!(f, r#"record(ai, "CHILD") {{"#).unwrap();
        writeln!(f, r#"    field(VAL, "0")"#).unwrap();
        writeln!(f, r#"}}"#).unwrap();

        let main_path = dir.path().join("main.db");
        let mut f = std::fs::File::create(&main_path).unwrap();
        writeln!(f, r#"include "$(DIR)/child.db""#).unwrap();

        let mut macros = HashMap::new();
        macros.insert("DIR".to_string(), subdir.to_string_lossy().to_string());

        let config = DbLoadConfig::default();
        let result = expand_includes(&main_path, &macros, &config).unwrap();
        assert!(result.contains(r#"record(ai, "CHILD")"#));
    }

    #[test]
    fn test_include_search_order() {
        use std::io::Write;
        let dir = tempfile::tempdir().unwrap();
        let inc_dir = dir.path().join("inc");
        std::fs::create_dir(&inc_dir).unwrap();

        // Put file in include path only (not in current dir)
        let child_path = inc_dir.join("child.db");
        let mut f = std::fs::File::create(&child_path).unwrap();
        writeln!(f, r#"record(ai, "FROM_INC") {{"#).unwrap();
        writeln!(f, r#"    field(VAL, "0")"#).unwrap();
        writeln!(f, r#"}}"#).unwrap();

        let main_path = dir.path().join("main.db");
        let mut f = std::fs::File::create(&main_path).unwrap();
        writeln!(f, r#"include "child.db""#).unwrap();

        let config = DbLoadConfig {
            include_paths: vec![inc_dir.clone()],
            max_include_depth: 32,
        };
        let result = expand_includes(&main_path, &HashMap::new(), &config).unwrap();
        assert!(result.contains(r#"record(ai, "FROM_INC")"#));

        // Now also put a file in current dir — it should take priority
        let local_child = dir.path().join("child.db");
        let mut f = std::fs::File::create(&local_child).unwrap();
        writeln!(f, r#"record(ai, "FROM_LOCAL") {{"#).unwrap();
        writeln!(f, r#"    field(VAL, "0")"#).unwrap();
        writeln!(f, r#"}}"#).unwrap();

        let result = expand_includes(&main_path, &HashMap::new(), &config).unwrap();
        assert!(result.contains(r#"record(ai, "FROM_LOCAL")"#));
    }

    #[test]
    fn test_addpath_directive_resolves_include() {
        // L-3: an `addpath` directive inside a .db file mutates the
        // include search path for subsequent `include` directives.
        use std::io::Write;
        let dir = tempfile::tempdir().unwrap();
        let inc_dir = dir.path().join("extra");
        std::fs::create_dir(&inc_dir).unwrap();

        // child.db lives ONLY in the extra/ dir.
        let child = inc_dir.join("child.db");
        let mut f = std::fs::File::create(&child).unwrap();
        writeln!(f, r#"record(ai, "FROM_ADDPATH") {{ field(VAL, "0") }}"#).unwrap();

        let main = dir.path().join("main.db");
        let mut f = std::fs::File::create(&main).unwrap();
        writeln!(f, r#"addpath "{}""#, inc_dir.display()).unwrap();
        writeln!(f, r#"include "child.db""#).unwrap();

        // No include path in config — only the addpath directive can
        // make this resolve.
        let config = DbLoadConfig::default();
        let result = expand_includes(&main, &HashMap::new(), &config).unwrap();
        assert!(result.contains(r#"record(ai, "FROM_ADDPATH")"#));
    }

    #[test]
    fn test_path_directive_replaces_search_path() {
        // L-3: `path` replaces the search path entirely.
        use std::io::Write;
        let dir = tempfile::tempdir().unwrap();
        let inc_dir = dir.path().join("p");
        std::fs::create_dir(&inc_dir).unwrap();

        let child = inc_dir.join("c.db");
        let mut f = std::fs::File::create(&child).unwrap();
        writeln!(f, r#"record(ai, "VIA_PATH") {{ field(VAL, "0") }}"#).unwrap();

        let main = dir.path().join("main.db");
        let mut f = std::fs::File::create(&main).unwrap();
        writeln!(f, r#"path "{}""#, inc_dir.display()).unwrap();
        writeln!(f, r#"include "c.db""#).unwrap();

        let config = DbLoadConfig::default();
        let result = expand_includes(&main, &HashMap::new(), &config).unwrap();
        assert!(result.contains(r#"record(ai, "VIA_PATH")"#));
    }

    #[test]
    fn test_dtyp_override_existing_only() {
        let mut records = vec![
            DbRecordDef {
                record_type: "ai".to_string(),
                name: "REC_WITH_DTYP".to_string(),
                fields: vec![
                    ("DTYP".to_string(), "oldDtyp".to_string()),
                    ("VAL".to_string(), "0".to_string()),
                ],
                aliases: Vec::new(),
                info_tags: Vec::new(),
            },
            DbRecordDef {
                record_type: "ao".to_string(),
                name: "REC_WITHOUT_DTYP".to_string(),
                fields: vec![("VAL".to_string(), "1".to_string())],
                aliases: Vec::new(),
                info_tags: Vec::new(),
            },
        ];

        override_dtyp(&mut records, "newDtyp");

        // Record with DTYP: value replaced
        assert_eq!(
            records[0].fields[0],
            ("DTYP".to_string(), "newDtyp".to_string())
        );
        // Record without DTYP: unchanged (no DTYP added)
        assert_eq!(records[1].fields.len(), 1);
        assert!(!records[1].fields.iter().any(|(n, _)| n == "DTYP"));
    }

    #[test]
    fn test_parse_db_file_no_includes() {
        use std::io::Write;
        let dir = tempfile::tempdir().unwrap();

        let path = dir.path().join("simple.db");
        let mut f = std::fs::File::create(&path).unwrap();
        writeln!(f, r#"record(ai, "$(P)TEMP") {{"#).unwrap();
        writeln!(f, r#"    field(VAL, "25.0")"#).unwrap();
        writeln!(f, r#"}}"#).unwrap();

        let mut macros = HashMap::new();
        macros.insert("P".to_string(), "IOC:".to_string());

        let config = DbLoadConfig::default();
        let records = parse_db_file(&path, &macros, &config).unwrap();
        assert_eq!(records.len(), 1);
        assert_eq!(records[0].name, "IOC:TEMP");
    }

    // epics-base PR #78 — record-name validation regressions.

    #[test]
    fn name_validation_accepts_typical_names() {
        for n in [
            "IOC:TEMP",
            "MOTOR-1",
            "X[1]",
            "scan_5",
            "BL3:STD:01",
            "abc.xyz_record",
        ]
        .iter()
        .copied()
        // ".xyz" inside the bracket-allowed shape would actually fail
        // — the slash above is just to demonstrate the OK/FAIL split.
        {
            // Skip the deliberately-bad sample.
            if n.contains('.') {
                assert!(validate_record_name(n, 1, 1).is_err());
                continue;
            }
            validate_record_name(n, 1, 1).unwrap_or_else(|e| panic!("'{n}' should pass: {e:?}"));
        }
    }

    #[test]
    fn name_validation_rejects_empty() {
        assert!(validate_record_name("", 1, 1).is_err());
    }

    #[test]
    fn name_validation_rejects_bad_chars() {
        // Mirrors base: TAB (0x09) is non-printable so it falls into the
        // warn-and-continue branch, NOT the hard-error set. Only the
        // printable bad chars below produce a hard error.
        for bad in ["spa ce", "do.t", "qu\"ot", "ap'os", "do$llar"] {
            assert!(
                validate_record_name(bad, 1, 1).is_err(),
                "'{bad}' must be rejected"
            );
        }
    }

    #[test]
    fn name_validation_warns_but_passes_on_nonprintable() {
        // 0x09 (TAB) and 0x01 are < 0x20 so they only emit a warning.
        validate_record_name("ta\tb", 1, 1).expect("TAB is warn-only per base spec");
        validate_record_name("hello\x01world", 1, 1).expect("0x01 is warn-only");
    }

    #[test]
    fn name_validation_warns_on_leading_special_but_passes() {
        for warn in ["-x", "+y", "[arr", "{obj"] {
            validate_record_name(warn, 1, 1).expect("leading special is warn-only");
        }
    }

    #[test]
    fn parse_db_propagates_name_validation_error() {
        let bad = r#"record(ai, "BAD NAME") { }"#;
        let res = parse_db(bad, &HashMap::new());
        assert!(matches!(res, Err(CaError::DbParseError { .. })));
    }

    // epics-base PR #336 — alias parsing + name validation.

    #[test]
    fn parse_db_captures_aliases() {
        let src = r#"record(ai, "TARGET") {
            alias("ALIAS1")
            alias("ALIAS2")
            field(VAL, 42)
        }"#;
        let recs = parse_db(src, &HashMap::new()).unwrap();
        assert_eq!(recs.len(), 1);
        assert_eq!(recs[0].name, "TARGET");
        assert_eq!(recs[0].aliases, vec!["ALIAS1", "ALIAS2"]);
        assert_eq!(recs[0].fields.len(), 1);
    }

    #[test]
    fn parse_db_rejects_alias_with_bad_name() {
        let src = r#"record(ai, "TARGET") {
            alias("BAD ALIAS")
        }"#;
        let res = parse_db(src, &HashMap::new());
        assert!(matches!(res, Err(CaError::DbParseError { .. })));
    }

    // L-2 — top-level directive grammar coverage.

    #[test]
    fn parse_db_accepts_path_and_addpath() {
        // `path`/`addpath` at file scope are accepted and skipped —
        // include resolution is the expansion layer's job.
        let src = r#"
            path "/opt/epics/db"
            addpath "/extra/db"
            record(ai, "REC") { field(VAL, "1") }
        "#;
        let recs = parse_db(src, &HashMap::new()).unwrap();
        assert_eq!(recs.len(), 1);
        assert_eq!(recs[0].name, "REC");
    }

    #[test]
    fn parse_db_accepts_top_level_include() {
        // A bare `include` at file scope is accepted (grammar parity);
        // the file is not loaded at this layer.
        let src = r#"
            include "common.db"
            record(ai, "REC") { field(VAL, "1") }
        "#;
        let recs = parse_db(src, &HashMap::new()).unwrap();
        assert_eq!(recs.len(), 1);
    }

    #[test]
    fn parse_db_global_alias_two_arg() {
        // Standalone `alias("record","newname")` attaches the new name
        // to the target record's alias list.
        let src = r#"
            record(ai, "TARGET") { field(VAL, "1") }
            alias("TARGET", "TARGET_ALIAS")
        "#;
        let recs = parse_db(src, &HashMap::new()).unwrap();
        assert_eq!(recs.len(), 1);
        assert_eq!(recs[0].aliases, vec!["TARGET_ALIAS"]);
    }

    #[test]
    fn parse_db_global_alias_forward_reference() {
        // The alias directive may precede its target record.
        let src = r#"
            alias("TARGET", "EARLY_ALIAS")
            record(ai, "TARGET") { field(VAL, "1") }
        "#;
        let recs = parse_db(src, &HashMap::new()).unwrap();
        assert_eq!(recs[0].aliases, vec!["EARLY_ALIAS"]);
    }

    #[test]
    fn parse_db_global_alias_unknown_record_errors() {
        let src = r#"alias("NOSUCH", "X")"#;
        let res = parse_db(src, &HashMap::new());
        assert!(matches!(res, Err(CaError::DbParseError { .. })));
    }

    // L-5 — unquoted field values are restricted to the C bareword set.

    #[test]
    fn parse_db_unquoted_bareword_value_ok() {
        let src = r#"record(ai, "REC") { field(VAL, 42) field(EGU, deg-C) }"#;
        let recs = parse_db(src, &HashMap::new()).unwrap();
        assert_eq!(recs[0].fields[0].1, "42");
        assert_eq!(recs[0].fields[1].1, "deg-C");
    }

    #[test]
    fn parse_db_unquoted_value_with_space_rejected() {
        // An unquoted multi-word value is two tokens in C — a parse
        // error. The author must quote it.
        let src = r#"record(ai, "REC") { field(DESC, hello world) }"#;
        let res = parse_db(src, &HashMap::new());
        assert!(
            matches!(res, Err(CaError::DbParseError { .. })),
            "unquoted value with space must be rejected, got {res:?}"
        );
    }

    #[test]
    fn parse_db_unquoted_value_with_illegal_char_rejected() {
        // `*` is outside the C bareword set.
        let src = r#"record(ai, "REC") { field(DESC, a*b) }"#;
        let res = parse_db(src, &HashMap::new());
        assert!(matches!(res, Err(CaError::DbParseError { .. })));
    }

    #[test]
    fn parse_db_record_without_alias_has_empty_aliases() {
        let src = r#"record(ai, "PLAIN") { field(VAL, 1) }"#;
        let recs = parse_db(src, &HashMap::new()).unwrap();
        assert!(recs[0].aliases.is_empty());
    }

    /// Round-9 regression: `info(asyn:READBACK, "1")` (unquoted tag,
    /// quoted value) is the form ad-core templates use. Base accepts
    /// it; round-5's parser fix tightened the grammar to require a
    /// quoted tag, which broke all NDOverlayN / NDFile / NDArrayBase
    /// templates and the mini-beamline/xrt-beamline IOCs that load
    /// commonPlugins.cmd.
    #[test]
    fn parse_db_info_accepts_unquoted_tag() {
        let src = r#"
record(ai, "REC") {
    field(VAL, "0")
    info(asyn:READBACK, "1")
    info("Q:group", "demo")
    info(autosaveFields, "VAL DESC")
}
"#;
        let recs = parse_db(src, &HashMap::new()).unwrap();
        assert_eq!(recs.len(), 1);
        let tags = &recs[0].info_tags;
        // Unquoted tag, quoted value.
        assert!(
            tags.iter().any(|(k, v)| k == "asyn:READBACK" && v == "1"),
            "unquoted tag must parse: {tags:?}"
        );
        // Quoted tag, quoted value (existing form).
        assert!(tags.iter().any(|(k, v)| k == "Q:group" && v == "demo"));
        // Unquoted tag, unquoted multi-word value.
        assert!(
            tags.iter()
                .any(|(k, v)| k == "autosaveFields" && v == "VAL DESC"),
            "unquoted multi-word value must parse: {tags:?}"
        );
    }

    /// C parity (modules/libcom/test/macLib.plt:52):
    ///   $(a)\$(b)  with a=foo  ->  foo\$(b)
    /// The `\` MUST block the macro-reference detection of the following
    /// `$` so `$(b)` survives as literal text. The `\` itself is
    /// preserved verbatim (macLib level 0 semantic — downstream
    /// caller-side escape passes may discard it).
    #[test]
    fn substitute_macros_backslash_escapes_dollar() {
        let mut macros = HashMap::new();
        macros.insert("a".to_string(), "foo".to_string());
        macros.insert("b".to_string(), "baz".to_string());

        // Anchor test: backslash before $ blocks expansion.
        assert_eq!(substitute_macros(r"$(a)\$(b)", &macros), r"foo\$(b)");

        // Backslash before brace form too.
        assert_eq!(substitute_macros(r"\${a}", &macros), r"\${a}");

        // Without backslash, both expand.
        assert_eq!(substitute_macros("$(a)$(b)", &macros), "foobaz");

        // Backslash escape consumes the IMMEDIATELY next char (one
        // step at a time, matching C macCore.c:741-744). So `\\$(a)`
        // emits the first `\` + second `\` literal (escape pair), then
        // resumes parsing at `$(a)` which expands. Result: `\\foo`.
        assert_eq!(substitute_macros(r"\\$(a)", &macros), r"\\foo");

        // Backslash NOT before $ / { passes through too (escape any next char).
        assert_eq!(
            substitute_macros(r"path\file $(a)", &macros),
            r"path\file foo"
        );
    }

    // M-1 — resolved macro values are re-expanded (chained).
    #[test]
    fn substitute_macros_chained_expansion() {
        // P=$(Q), Q=IOC:  →  $(P) expands to IOC:
        let mut macros = HashMap::new();
        macros.insert("P".to_string(), "$(Q)".to_string());
        macros.insert("Q".to_string(), "IOC:".to_string());
        assert_eq!(substitute_macros("$(P)TEMP", &macros), "IOC:TEMP");
    }

    // M-2 — `$(name,key=val,...)` scoped macro definitions.
    #[test]
    fn substitute_macros_scoped_definitions() {
        // INNER references A and B which are only defined for the
        // duration of this reference.
        let mut macros = HashMap::new();
        macros.insert("INNER".to_string(), "$(A)-$(B)".to_string());
        assert_eq!(substitute_macros("$(INNER,A=1,B=2)", &macros), "1-2");
    }

    #[test]
    fn substitute_macros_scoped_not_leaking() {
        // A scoped macro must not leak past its reference.
        let mut macros = HashMap::new();
        macros.insert("INNER".to_string(), "$(A)".to_string());
        // After the scoped $(INNER,A=9), a bare $(A) is undefined.
        let out = substitute_macros("$(INNER,A=9)|$(A)", &macros);
        assert_eq!(out, "9|$(A,undefined)");
    }

    // M-3 — macros are NOT expanded inside single quotes.
    #[test]
    fn substitute_macros_suppressed_in_single_quotes() {
        let mut macros = HashMap::new();
        macros.insert("X".to_string(), "VAL".to_string());
        // Single quotes suppress.
        assert_eq!(substitute_macros("'$(X)'", &macros), "'$(X)'");
        // Double quotes do NOT suppress.
        assert_eq!(substitute_macros("\"$(X)\"", &macros), "\"VAL\"");
    }

    // M-5 — the reference name is macro-expanded before lookup.
    #[test]
    fn substitute_macros_indirect_name() {
        // $($(WHICH)) — WHICH selects which macro to read.
        let mut macros = HashMap::new();
        macros.insert("WHICH".to_string(), "SEL".to_string());
        macros.insert("SEL".to_string(), "chosen".to_string());
        assert_eq!(substitute_macros("$($(WHICH))", &macros), "chosen");
    }

    // L-4 — undefined macro with no default emits `$(name,undefined)`.
    #[test]
    fn substitute_macros_undefined_placeholder() {
        let macros = HashMap::new();
        assert_eq!(
            substitute_macros("$(MISSING)", &macros),
            "$(MISSING,undefined)"
        );
    }

    #[test]
    fn substitute_macros_default_with_comma_is_c_parity() {
        // C parity (M-2): `$(LIST=a,b,c)` — the name is LIST, the
        // default is `a` (terminates at the first top-level comma),
        // and `b`/`c` are bare scoped names that define nothing.
        let macros = HashMap::new();
        assert_eq!(substitute_macros("$(LIST=a,b,c)", &macros), "a");
    }

    #[test]
    fn substitute_macros_self_reference_terminates() {
        // M-1 re-expansion must not recurse forever on `A=$(A)`.
        // The recursion guard emits the value once without re-scan.
        let mut macros = HashMap::new();
        macros.insert("A".to_string(), "$(A)".to_string());
        // Must terminate; the exact text is the cycle-broken value.
        let out = substitute_macros("$(A)", &macros);
        assert!(out.contains("A"), "self-ref expansion produced: {out}");
    }

    #[test]
    fn substitute_macros_mutual_reference_terminates() {
        // A=$(B), B=$(A) — mutual cycle must also terminate.
        let mut macros = HashMap::new();
        macros.insert("A".to_string(), "$(B)".to_string());
        macros.insert("B".to_string(), "$(A)".to_string());
        let _ = substitute_macros("$(A)", &macros); // must not hang
    }
}