sphinx-ultra 0.5.0

High-performance Rust-based Sphinx documentation builder for large codebases
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
use anyhow::{anyhow, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::config::BuildConfig;

/// Python configuration parser for conf.py files.
///
/// This is a *parser*, not an executor: it handles the declarative subset of
/// Python used by typical conf.py files (assignments of literals, including
/// multi-line lists/dicts/tuples, string concatenation, and triple-quoted
/// strings). Every construct it cannot handle produces a [`ConfigWarning`] —
/// silent dropping is banned. Full execution arrives with the Python sidecar
/// (ROADMAP M5).
pub struct PythonConfigParser {
    conf_namespace: HashMap<String, serde_json::Value>,
    warnings: Vec<ConfigWarning>,
}

/// A conf.py construct that could not be parsed and was dropped.
#[derive(Debug, Clone)]
pub struct ConfigWarning {
    /// 1-based line in conf.py where the construct starts.
    pub line: usize,
    pub message: String,
}

/// Represents a parsed conf.py configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfPyConfig {
    // Project information
    pub project: Option<String>,
    pub version: Option<String>,
    pub release: Option<String>,
    pub copyright: Option<String>,
    pub author: Option<String>,

    // General configuration
    pub extensions: Vec<String>,
    pub templates_path: Vec<String>,
    pub exclude_patterns: Vec<String>,
    pub include_patterns: Vec<String>,
    pub source_suffix: HashMap<String, String>,
    pub root_doc: Option<String>,
    pub language: Option<String>,
    pub locale_dirs: Vec<String>,
    pub gettext_compact: Option<bool>,

    // HTML output options
    pub html_theme: Option<String>,
    pub html_theme_options: HashMap<String, serde_json::Value>,
    pub html_title: Option<String>,
    pub html_short_title: Option<String>,
    pub html_logo: Option<String>,
    pub html_favicon: Option<String>,
    pub html_css_files: Vec<String>,
    pub html_js_files: Vec<String>,
    pub html_static_path: Vec<String>,
    pub html_extra_path: Vec<String>,
    pub html_use_index: Option<bool>,
    pub html_split_index: Option<bool>,
    pub html_copy_source: Option<bool>,
    pub html_show_sourcelink: Option<bool>,
    pub html_sourcelink_suffix: Option<String>,
    pub html_use_opensearch: Option<String>,
    pub html_file_suffix: Option<String>,
    pub html_link_suffix: Option<String>,
    pub html_show_copyright: Option<bool>,
    pub html_show_sphinx: Option<bool>,
    pub html_context: HashMap<String, serde_json::Value>,
    pub html_output_encoding: Option<String>,
    pub html_compact_lists: Option<bool>,
    pub html_secnumber_suffix: Option<String>,
    pub html_search_language: Option<String>,
    pub html_search_options: HashMap<String, serde_json::Value>,
    pub html_search_scorer: Option<String>,
    pub html_scaled_image_link: Option<bool>,
    pub html_baseurl: Option<String>,
    pub html_codeblock_linenos_style: Option<String>,
    pub html_math_renderer: Option<String>,
    pub html_math_renderer_options: HashMap<String, serde_json::Value>,

    // LaTeX output options
    pub latex_engine: Option<String>,
    pub latex_documents: Vec<(String, String, String, String, String)>,
    pub latex_logo: Option<String>,
    pub latex_appendices: Vec<String>,
    pub latex_domain_indices: Option<bool>,
    pub latex_show_pagerefs: Option<bool>,
    pub latex_show_urls: Option<String>,
    pub latex_use_latex_multicolumn: Option<bool>,
    pub latex_use_xindy: Option<bool>,
    pub latex_toplevel_sectioning: Option<String>,
    pub latex_docclass: HashMap<String, String>,
    pub latex_additional_files: Vec<String>,
    pub latex_elements: HashMap<String, String>,

    // ePub output options
    pub epub_title: Option<String>,
    pub epub_author: Option<String>,
    pub epub_language: Option<String>,
    pub epub_publisher: Option<String>,
    pub epub_copyright: Option<String>,
    pub epub_identifier: Option<String>,
    pub epub_scheme: Option<String>,
    pub epub_uid: Option<String>,
    pub epub_cover: Option<(String, String)>,
    pub epub_css_files: Vec<String>,
    pub epub_pre_files: Vec<(String, String)>,
    pub epub_post_files: Vec<(String, String)>,
    pub epub_exclude_files: Vec<String>,
    pub epub_tocdepth: Option<i32>,
    pub epub_tocdup: Option<bool>,
    pub epub_tocscope: Option<String>,
    pub epub_fix_images: Option<bool>,
    pub epub_max_image_width: Option<i32>,
    pub epub_show_urls: Option<String>,
    pub epub_use_index: Option<bool>,
    pub epub_description: Option<String>,
    pub epub_contributor: Option<String>,
    pub epub_writing_mode: Option<String>,

    // Extension-specific configurations
    pub extension_configs: HashMap<String, HashMap<String, serde_json::Value>>,

    // Build options
    pub needs_sphinx: Option<String>,
    pub needs_extensions: HashMap<String, String>,
    pub manpages_url: Option<String>,
    pub nitpicky: Option<bool>,
    pub nitpick_ignore: Vec<(String, String)>,
    pub nitpick_ignore_regex: Vec<(String, String)>,
    pub numfig: Option<bool>,
    pub numfig_format: HashMap<String, String>,
    pub numfig_secnum_depth: Option<i32>,
    pub math_number_all: Option<bool>,
    pub math_eqref_format: Option<String>,
    pub math_numfig: Option<bool>,
    pub tls_verify: Option<bool>,
    pub tls_cacerts: Option<crate::intersphinx::TlsCacerts>,
    pub user_agent: Option<String>,

    // Object-signature / py-domain family. `None` means "conf.py did not
    // mention it", which is what keeps sphinx's own default in place —
    // notably distinct from `Some(0)` for the two line-length keys, where
    // the difference decides `PySigConfig::max_len`.
    pub maximum_signature_line_length: Option<i64>,
    pub python_maximum_signature_line_length: Option<i64>,
    pub python_trailing_comma_in_multi_line_signatures: Option<bool>,
    pub python_display_short_literal_types: Option<bool>,
    pub python_use_unqualified_type_names: Option<bool>,
    pub toc_object_entries: Option<bool>,
    pub toc_object_entries_show_parents: Option<String>,
    /// `source_encoding` as written, `None` when conf.py said nothing.
    pub source_encoding: Option<String>,
    /// `(key, python type name)` for the `int | None` keys whose conf.py
    /// value is neither an int nor `None` — what sphinx's
    /// `check_confval_types` warns about (see
    /// [`crate::config::BuildConfig::confval_type_mismatches`]).
    pub confval_type_mismatches: Vec<(String, String)>,
    pub add_function_parentheses: Option<bool>,
    pub add_module_names: Option<bool>,
    pub strip_signature_backslash: Option<bool>,
    pub modindex_common_prefix: Vec<String>,

    // intersphinx
    /// The raw `intersphinx_mapping` value, exactly as `conf.py` wrote it.
    /// Normalisation and validation happen in [`ConfPyConfig::to_build_config`],
    /// where a failure can abort configuration the way Sphinx's `ConfigError`
    /// aborts the build.
    pub intersphinx_mapping: serde_json::Value,
    pub intersphinx_disabled_reftypes: Option<Vec<String>>,
    pub intersphinx_resolve_self: Option<String>,
    pub intersphinx_cache_limit: Option<i64>,
    pub intersphinx_timeout: Option<f64>,

    // Internationalization
    pub gettext_uuid: Option<bool>,
    pub gettext_location: Option<bool>,
    pub gettext_auto_build: Option<bool>,
    pub gettext_additional_targets: Vec<String>,

    // Custom configurations (catch-all for extension-specific or custom settings)
    pub custom_configs: HashMap<String, serde_json::Value>,
}

impl PythonConfigParser {
    /// Create a new Python configuration parser
    pub fn new() -> Result<Self> {
        Ok(Self {
            conf_namespace: HashMap::new(),
            warnings: Vec::new(),
        })
    }

    /// Constructs dropped during the last parse (never silently discarded).
    pub fn warnings(&self) -> &[ConfigWarning] {
        &self.warnings
    }

    /// Parse a conf.py file and extract configuration
    pub fn parse_conf_py<P: AsRef<Path>>(&mut self, conf_py_path: P) -> Result<ConfPyConfig> {
        let conf_py_path = conf_py_path.as_ref();
        let _conf_dir = conf_py_path
            .parent()
            .ok_or_else(|| anyhow!("Invalid conf.py path"))?;

        // Read the conf.py file
        let conf_py_content = std::fs::read_to_string(conf_py_path)?;

        self.parse_statements(&conf_py_content)?;

        // Extract configuration values
        self.extract_configuration()
    }

    /// Parse the declarative subset of a conf.py: literal assignments, with a
    /// warning recorded for every construct that had to be dropped.
    fn parse_statements(&mut self, content: &str) -> Result<()> {
        for (line, stmt) in logical_statements(content) {
            let stmt = stmt.trim();
            if stmt.is_empty() {
                continue;
            }

            // Imports set no configuration values; ignoring them loses nothing.
            if stmt.starts_with("import ") || stmt.starts_with("from ") {
                continue;
            }

            match split_assignment(stmt) {
                Some((name, value_src)) => match parse_python_literal(value_src) {
                    Ok(value) => {
                        self.conf_namespace.insert(name.to_string(), value);
                    }
                    Err(reason) => self.warnings.push(ConfigWarning {
                        line,
                        message: format!(
                            "unsupported value for '{}' dropped ({}): {}",
                            name,
                            reason,
                            snippet(value_src)
                        ),
                    }),
                },
                None => self.warnings.push(ConfigWarning {
                    line,
                    message: format!("unsupported statement dropped: {}", snippet(stmt)),
                }),
            }
        }

        Ok(())
    }

    /// Extract configuration values from the parsed Python namespace
    fn extract_configuration(&self) -> Result<ConfPyConfig> {
        let mut config = ConfPyConfig::default();

        // Helper function to extract optional string values
        let extract_string = |key: &str| -> Option<String> {
            self.conf_namespace
                .get(key)
                .and_then(|val| val.as_str().map(|s| s.to_string()))
        };

        // Helper function to extract optional bool values
        let extract_bool = |key: &str| -> Option<bool> {
            self.conf_namespace.get(key).and_then(|val| val.as_bool())
        };

        // Helper function to extract optional int values
        let extract_int = |key: &str| -> Option<i32> {
            self.conf_namespace
                .get(key)
                .and_then(|val| val.as_i64().map(|i| i as i32))
        };

        // Helper function to extract list of strings
        let extract_string_list = |key: &str| -> Vec<String> {
            self.conf_namespace
                .get(key)
                .and_then(|val| val.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| v.as_str().map(|s| s.to_string()))
                        .collect()
                })
                .unwrap_or_default()
        };

        // Helper function to extract a list of 2-string tuples
        // (`nitpick_ignore`'s `[('py:func', 'foo'), ...]` shape).
        let extract_pair_list = |key: &str| -> Vec<(String, String)> {
            self.conf_namespace
                .get(key)
                .and_then(|val| val.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|pair| {
                            let pair = pair.as_array()?;
                            let first = pair.first()?.as_str()?;
                            let second = pair.get(1)?.as_str()?;
                            Some((first.to_string(), second.to_string()))
                        })
                        .collect()
                })
                .unwrap_or_default()
        };

        // Helper function to extract dictionary
        let extract_dict = |key: &str| -> HashMap<String, serde_json::Value> {
            self.conf_namespace
                .get(key)
                .and_then(|val| val.as_object())
                .map(|obj| obj.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
                .unwrap_or_default()
        };

        // Extract project information
        config.project = extract_string("project");
        config.version = extract_string("version");
        config.release = extract_string("release");
        config.copyright = extract_string("copyright");
        config.author = extract_string("author");

        // Extract general configuration
        config.extensions = extract_string_list("extensions");
        config.templates_path = extract_string_list("templates_path");
        config.exclude_patterns = extract_string_list("exclude_patterns");
        config.include_patterns = extract_string_list("include_patterns");
        config.root_doc = extract_string("root_doc").or_else(|| extract_string("master_doc"));
        config.language = extract_string("language");
        config.locale_dirs = extract_string_list("locale_dirs");
        config.gettext_compact = extract_bool("gettext_compact");

        // Extract HTML output options
        config.html_theme = extract_string("html_theme");
        config.html_theme_options = extract_dict("html_theme_options");
        config.html_title = extract_string("html_title");
        config.html_short_title = extract_string("html_short_title");
        config.html_logo = extract_string("html_logo");
        config.html_favicon = extract_string("html_favicon");
        config.html_css_files = extract_string_list("html_css_files");
        config.html_js_files = extract_string_list("html_js_files");
        config.html_static_path = extract_string_list("html_static_path");
        config.html_extra_path = extract_string_list("html_extra_path");
        config.html_use_index = extract_bool("html_use_index");
        config.html_split_index = extract_bool("html_split_index");
        config.html_copy_source = extract_bool("html_copy_source");
        config.html_show_sourcelink = extract_bool("html_show_sourcelink");
        config.html_sourcelink_suffix = extract_string("html_sourcelink_suffix");
        config.html_use_opensearch = extract_string("html_use_opensearch");
        config.html_file_suffix = extract_string("html_file_suffix");
        config.html_link_suffix = extract_string("html_link_suffix");
        config.html_show_copyright = extract_bool("html_show_copyright");
        config.html_show_sphinx = extract_bool("html_show_sphinx");
        config.html_context = extract_dict("html_context");
        config.html_output_encoding = extract_string("html_output_encoding");
        config.html_compact_lists = extract_bool("html_compact_lists");
        config.html_secnumber_suffix = extract_string("html_secnumber_suffix");
        config.html_search_language = extract_string("html_search_language");
        config.html_search_options = extract_dict("html_search_options");
        config.html_search_scorer = extract_string("html_search_scorer");
        config.html_scaled_image_link = extract_bool("html_scaled_image_link");
        config.html_baseurl = extract_string("html_baseurl");
        config.html_codeblock_linenos_style = extract_string("html_codeblock_linenos_style");
        config.html_math_renderer = extract_string("html_math_renderer");
        config.html_math_renderer_options = extract_dict("html_math_renderer_options");

        // Extract build options
        config.needs_sphinx = extract_string("needs_sphinx");
        config.nitpicky = extract_bool("nitpicky");
        config.nitpick_ignore = extract_pair_list("nitpick_ignore");
        config.nitpick_ignore_regex = extract_pair_list("nitpick_ignore_regex");
        config.numfig = extract_bool("numfig");
        // `numfig_format` is a str -> str dict; a non-string value is not a
        // format string sphinx could interpolate, so it is dropped here
        // rather than carried as JSON.
        config.numfig_format = extract_dict("numfig_format")
            .into_iter()
            .filter_map(|(k, v)| v.as_str().map(|s| (k, s.to_string())))
            .collect();
        config.numfig_secnum_depth = extract_int("numfig_secnum_depth");
        config.math_number_all = extract_bool("math_number_all");
        config.math_eqref_format = extract_string("math_eqref_format");
        config.math_numfig = extract_bool("math_numfig");
        config.tls_verify = extract_bool("tls_verify");
        // `tls_cacerts` is `str | dict[str, str] | None` (`config.py:287`):
        // one CA bundle for everything, or one per host.
        config.tls_cacerts = self
            .conf_namespace
            .get("tls_cacerts")
            .and_then(|value| match value {
                serde_json::Value::String(path) => {
                    Some(crate::intersphinx::TlsCacerts::Bundle(path.clone()))
                }
                serde_json::Value::Object(map) => Some(crate::intersphinx::TlsCacerts::PerHost(
                    map.iter()
                        .filter_map(|(k, v)| v.as_str().map(|v| (k.clone(), v.to_string())))
                        .collect(),
                )),
                _ => None,
            });
        config.user_agent = extract_string("user_agent");

        // Object-signature / py-domain family. The two line-length keys are
        // `int | None`, so they read through `as_i64` rather than
        // `extract_int`: `x = None` in conf.py is a JSON null, which lands
        // as `None` exactly like an absent key, and `x = 0` stays `Some(0)`.
        // Any other type is what sphinx's `check_confval_types` warns about
        // (`The config value ... has type `str'; expected `NoneType' or
        // `int'.`) — recorded with the python type name and left unset.
        let mut mismatches: Vec<(String, String)> = Vec::new();
        let mut extract_none_default_int = |key: &str| -> Option<i64> {
            match self.conf_namespace.get(key) {
                None | Some(serde_json::Value::Null) => None,
                Some(value) => match value.as_i64() {
                    Some(int) => Some(int),
                    None => {
                        mismatches.push((key.to_string(), python_type_name(value).to_string()));
                        None
                    }
                },
            }
        };
        config.maximum_signature_line_length =
            extract_none_default_int("maximum_signature_line_length");
        config.python_maximum_signature_line_length =
            extract_none_default_int("python_maximum_signature_line_length");
        config.confval_type_mismatches = mismatches;
        config.source_encoding = extract_string("source_encoding");
        config.python_trailing_comma_in_multi_line_signatures =
            extract_bool("python_trailing_comma_in_multi_line_signatures");
        config.python_display_short_literal_types =
            extract_bool("python_display_short_literal_types");
        config.python_use_unqualified_type_names =
            extract_bool("python_use_unqualified_type_names");
        config.toc_object_entries = extract_bool("toc_object_entries");
        config.toc_object_entries_show_parents = extract_string("toc_object_entries_show_parents");
        config.add_function_parentheses = extract_bool("add_function_parentheses");
        config.add_module_names = extract_bool("add_module_names");
        config.strip_signature_backslash = extract_bool("strip_signature_backslash");
        config.modindex_common_prefix = extract_string_list("modindex_common_prefix");

        // Extract intersphinx configuration. The mapping is carried raw:
        // validating it is `to_build_config`'s job, because that is where a
        // failure can be reported as a configuration error.
        config.intersphinx_mapping = self
            .conf_namespace
            .get("intersphinx_mapping")
            .cloned()
            .unwrap_or(serde_json::Value::Null);
        config.intersphinx_disabled_reftypes = self
            .conf_namespace
            .get("intersphinx_disabled_reftypes")
            .map(|_| extract_string_list("intersphinx_disabled_reftypes"));
        config.intersphinx_resolve_self = extract_string("intersphinx_resolve_self");
        config.intersphinx_cache_limit = self
            .conf_namespace
            .get("intersphinx_cache_limit")
            .and_then(serde_json::Value::as_i64);
        config.intersphinx_timeout = self
            .conf_namespace
            .get("intersphinx_timeout")
            .and_then(serde_json::Value::as_f64);

        // Extract internationalization
        config.gettext_uuid = extract_bool("gettext_uuid");
        config.gettext_location = extract_bool("gettext_location");
        config.gettext_auto_build = extract_bool("gettext_auto_build");
        config.gettext_additional_targets = extract_string_list("gettext_additional_targets");

        // Extract custom configurations
        for (key, value) in &self.conf_namespace {
            if !Self::is_standard_config_key(key) {
                config.custom_configs.insert(key.clone(), value.clone());
            }
        }

        Ok(config)
    }

    /// Check if a configuration key is a standard Sphinx configuration
    fn is_standard_config_key(key: &str) -> bool {
        matches!(
            key,
            "project"
                | "version"
                | "release"
                | "copyright"
                | "author"
                | "extensions"
                | "templates_path"
                | "exclude_patterns"
                | "include_patterns"
                | "source_suffix"
                | "source_encoding"
                | "root_doc"
                | "master_doc"
                | "language"
                | "locale_dirs"
                | "gettext_compact"
                | "html_theme"
                | "html_theme_options"
                | "html_title"
                | "html_short_title"
                | "html_logo"
                | "html_favicon"
                | "html_css_files"
                | "html_js_files"
                | "html_static_path"
                | "html_extra_path"
                | "html_use_index"
                | "html_split_index"
                | "html_copy_source"
                | "html_show_sourcelink"
                | "html_sourcelink_suffix"
                | "html_use_opensearch"
                | "html_file_suffix"
                | "html_link_suffix"
                | "html_show_copyright"
                | "html_show_sphinx"
                | "html_context"
                | "html_output_encoding"
                | "html_compact_lists"
                | "html_secnumber_suffix"
                | "html_search_language"
                | "html_search_options"
                | "html_search_scorer"
                | "html_scaled_image_link"
                | "html_baseurl"
                | "html_codeblock_linenos_style"
                | "html_math_renderer"
                | "html_math_renderer_options"
                | "needs_sphinx"
                | "nitpicky"
                | "nitpick_ignore"
                | "nitpick_ignore_regex"
                | "maximum_signature_line_length"
                | "python_maximum_signature_line_length"
                | "python_trailing_comma_in_multi_line_signatures"
                | "python_display_short_literal_types"
                | "python_use_unqualified_type_names"
                | "toc_object_entries"
                | "toc_object_entries_show_parents"
                | "add_function_parentheses"
                | "add_module_names"
                | "strip_signature_backslash"
                | "modindex_common_prefix"
                | "numfig"
                | "numfig_format"
                | "numfig_secnum_depth"
                | "math_number_all"
                | "math_eqref_format"
                | "math_numfig"
                | "tls_verify"
                | "tls_cacerts"
                | "user_agent"
                | "intersphinx_mapping"
                | "intersphinx_disabled_reftypes"
                | "intersphinx_resolve_self"
                | "intersphinx_cache_limit"
                | "intersphinx_timeout"
                | "gettext_uuid"
                | "gettext_location"
                | "gettext_auto_build"
                | "gettext_additional_targets"
        )
    }
}

/// The `type(value).__name__` sphinx's `check_confval_types` prints for a
/// conf.py literal, by way of its JSON shape. A python tuple arrives as a
/// list here, so it would be named `list` — a spelling-only difference in
/// a warning about an already-rejected value.
fn python_type_name(value: &serde_json::Value) -> &'static str {
    match value {
        serde_json::Value::Null => "NoneType",
        serde_json::Value::Bool(_) => "bool",
        serde_json::Value::Number(number) if number.is_i64() || number.is_u64() => "int",
        serde_json::Value::Number(_) => "float",
        serde_json::Value::String(_) => "str",
        serde_json::Value::Array(_) => "list",
        serde_json::Value::Object(_) => "dict",
    }
}

/// First ~60 chars of a construct, for warning messages.
fn snippet(s: &str) -> String {
    let s = s.trim();
    match s.char_indices().nth(60) {
        Some((idx, _)) => format!("{}…", &s[..idx]),
        None => s.to_string(),
    }
}

/// Split Python source into logical statements: physical lines joined while
/// brackets are open, a string (incl. triple-quoted) is unterminated, or a
/// trailing backslash continues the line. Comments outside strings are
/// stripped. Yields `(1-based start line, statement text)`.
fn logical_statements(content: &str) -> Vec<(usize, String)> {
    let chars: Vec<char> = content.chars().collect();
    let mut statements = Vec::new();

    let mut buf = String::new();
    let mut start_line = 1usize;
    let mut line = 1usize;
    let mut depth = 0i32;
    // (quote char, is_triple)
    let mut string_state: Option<(char, bool)> = None;
    let mut escaped = false;

    let mut i = 0;
    while i < chars.len() {
        let c = chars[i];

        if let Some((quote, triple)) = string_state {
            buf.push(c);
            if c == '\n' {
                line += 1;
            }
            if escaped {
                escaped = false;
            } else if c == '\\' {
                escaped = true;
            } else if c == quote {
                if triple {
                    if i + 2 < chars.len() && chars[i + 1] == quote && chars[i + 2] == quote {
                        buf.push(quote);
                        buf.push(quote);
                        i += 2;
                        string_state = None;
                    }
                } else {
                    string_state = None;
                }
            }
            i += 1;
            continue;
        }

        match c {
            '\'' | '"' => {
                let triple = i + 2 < chars.len() && chars[i + 1] == c && chars[i + 2] == c;
                buf.push(c);
                if triple {
                    buf.push(c);
                    buf.push(c);
                    i += 2;
                }
                string_state = Some((c, triple));
            }
            '#' => {
                // Comment: skip to (but not past) end of line.
                while i + 1 < chars.len() && chars[i + 1] != '\n' {
                    i += 1;
                }
            }
            '(' | '[' | '{' => {
                depth += 1;
                buf.push(c);
            }
            ')' | ']' | '}' => {
                depth -= 1;
                buf.push(c);
            }
            '\\' if i + 1 < chars.len() && chars[i + 1] == '\n' => {
                // Explicit line continuation: join without the backslash.
                buf.push(' ');
                line += 1;
                i += 1;
            }
            '\n' => {
                line += 1;
                if depth > 0 {
                    buf.push('\n');
                } else {
                    if !buf.trim().is_empty() {
                        statements.push((start_line, std::mem::take(&mut buf)));
                    } else {
                        buf.clear();
                    }
                    start_line = line;
                }
            }
            _ => {
                if buf.trim().is_empty() && !c.is_whitespace() && buf.is_empty() {
                    start_line = line;
                }
                buf.push(c);
            }
        }
        i += 1;
    }

    if !buf.trim().is_empty() {
        statements.push((start_line, buf));
    }

    statements
}

/// Split `identifier = <value>` at the first top-level `=` that is a plain
/// assignment (not `==`, `!=`, `<=`, `>=`, or an augmented assignment).
/// Returns `None` for anything that is not a simple assignment to a bare name.
fn split_assignment(stmt: &str) -> Option<(&str, &str)> {
    let bytes = stmt.as_bytes();
    let mut depth = 0i32;
    let mut string_quote: Option<u8> = None;

    for i in 0..bytes.len() {
        let b = bytes[i];
        if let Some(q) = string_quote {
            if b == q && (i == 0 || bytes[i - 1] != b'\\') {
                string_quote = None;
            }
            continue;
        }
        match b {
            b'\'' | b'"' => string_quote = Some(b),
            b'(' | b'[' | b'{' => depth += 1,
            b')' | b']' | b'}' => depth -= 1,
            b'=' if depth == 0 => {
                let next_eq = bytes.get(i + 1) == Some(&b'=');
                let prev = if i > 0 { bytes[i - 1] } else { 0 };
                if next_eq || matches!(prev, b'=' | b'!' | b'<' | b'>') {
                    return None; // comparison
                }
                if matches!(
                    prev,
                    b'+' | b'-' | b'*' | b'/' | b'%' | b'&' | b'|' | b'^' | b'@'
                ) {
                    return None; // augmented assignment
                }
                let name = stmt[..i].trim();
                let is_identifier = !name.is_empty()
                    && name
                        .chars()
                        .next()
                        .map(|c| c.is_ascii_alphabetic() || c == '_')
                        .unwrap_or(false)
                    && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
                if !is_identifier {
                    return None;
                }
                return Some((name, stmt[i + 1..].trim()));
            }
            _ => {}
        }
    }
    None
}

/// Recursive-descent parser for Python literals → JSON values.
/// Supports: strings (escapes, implicit adjacent concatenation, triple
/// quotes), ints/floats, True/False/None, lists, tuples (as arrays), dicts
/// with string keys, arbitrary nesting, trailing commas.
pub(crate) fn parse_python_literal(src: &str) -> std::result::Result<serde_json::Value, String> {
    let chars: Vec<char> = src.chars().collect();
    let mut p = PyLiteralParser {
        chars,
        pos: 0,
        saw_comma: false,
    };
    let value = p.parse_value()?;
    p.skip_ws();
    if p.pos < p.chars.len() {
        return Err("trailing expression".to_string());
    }
    Ok(value)
}

struct PyLiteralParser {
    chars: Vec<char>,
    pos: usize,
    /// Whether the most recently closed sequence contained a comma — used to
    /// tell a parenthesized grouping `(x)` from a one-element tuple `(x,)`.
    saw_comma: bool,
}

impl PyLiteralParser {
    fn peek(&self) -> Option<char> {
        self.chars.get(self.pos).copied()
    }

    fn skip_ws(&mut self) {
        while matches!(self.peek(), Some(c) if c.is_whitespace()) {
            self.pos += 1;
        }
    }

    fn parse_value(&mut self) -> std::result::Result<serde_json::Value, String> {
        self.skip_ws();
        if let Some(raw) = self.string_prefix() {
            let mut s = self.parse_string(raw)?;
            // Implicit adjacent string concatenation: 'a' 'b' == 'ab'
            while let Some(raw) = {
                self.skip_ws();
                self.string_prefix()
            } {
                s.push_str(&self.parse_string(raw)?);
            }
            return Ok(serde_json::Value::String(s));
        }
        match self.peek() {
            Some('[') => self.parse_sequence('[', ']'),
            Some('(') => {
                // Python: `(x)` is grouping, `(x,)` / `(x, y)` is a tuple.
                // Either way an array (or the inner value) serves config needs.
                let value = self.parse_sequence('(', ')')?;
                match value {
                    serde_json::Value::Array(items) if items.len() == 1 && !self.saw_comma => {
                        Ok(items.into_iter().next().unwrap())
                    }
                    other => Ok(other),
                }
            }
            Some('{') => self.parse_dict(),
            Some(c) if c.is_ascii_digit() || c == '-' || c == '+' || c == '.' => {
                self.parse_number()
            }
            Some(_) => {
                if self.eat_keyword("True") {
                    Ok(serde_json::Value::Bool(true))
                } else if self.eat_keyword("False") {
                    Ok(serde_json::Value::Bool(false))
                } else if self.eat_keyword("None") {
                    Ok(serde_json::Value::Null)
                } else {
                    Err("unsupported expression".to_string())
                }
            }
            None => Err("empty value".to_string()),
        }
    }

    fn eat_keyword(&mut self, kw: &str) -> bool {
        let end = self.pos + kw.len();
        if end <= self.chars.len() && self.chars[self.pos..end].iter().collect::<String>() == kw {
            let boundary = self
                .chars
                .get(end)
                .map(|c| !c.is_ascii_alphanumeric() && *c != '_')
                .unwrap_or(true);
            if boundary {
                self.pos = end;
                return true;
            }
        }
        false
    }

    /// A string literal starts here — with an optional Python prefix, which
    /// is consumed. `Some(true)` means the literal is *raw*: `nitpick_ignore_regex`
    /// entries are conventionally written `r'...'`, and a raw literal's
    /// backslashes must survive into the pattern. `f` prefixes are
    /// deliberately not accepted: an f-string's braces are an expression
    /// this parser cannot evaluate, so it stays an unsupported expression
    /// (skipped) rather than being taken literally.
    fn string_prefix(&mut self) -> Option<bool> {
        if matches!(self.peek(), Some('\'') | Some('"')) {
            return Some(false);
        }
        for len in [2usize, 1] {
            let quote_at = self.pos + len;
            if !matches!(self.chars.get(quote_at), Some('\'') | Some('"')) {
                continue;
            }
            let prefix: String = self.chars[self.pos..quote_at]
                .iter()
                .collect::<String>()
                .to_lowercase();
            if matches!(prefix.as_str(), "r" | "u" | "b" | "rb" | "br") {
                self.pos = quote_at;
                return Some(prefix.contains('r'));
            }
        }
        None
    }

    fn parse_string(&mut self, raw: bool) -> std::result::Result<String, String> {
        let quote = self.peek().ok_or("expected string")?;
        self.pos += 1;
        let triple = self.chars.get(self.pos) == Some(&quote)
            && self.chars.get(self.pos + 1) == Some(&quote);
        if triple {
            self.pos += 2;
        }

        let mut out = String::new();
        loop {
            let c = *self
                .chars
                .get(self.pos)
                .ok_or("unterminated string literal")?;
            if c == '\\' {
                let next = *self
                    .chars
                    .get(self.pos + 1)
                    .ok_or("unterminated escape sequence")?;
                if raw {
                    // A raw literal keeps both characters — but the escaped
                    // quote still does not end the string.
                    out.push('\\');
                    out.push(next);
                    self.pos += 2;
                    continue;
                }
                let translated = match next {
                    'n' => '\n',
                    't' => '\t',
                    'r' => '\r',
                    '\\' => '\\',
                    '\'' => '\'',
                    '"' => '"',
                    other => {
                        // Unknown escape: Python keeps the backslash.
                        out.push('\\');
                        other
                    }
                };
                out.push(translated);
                self.pos += 2;
                continue;
            }
            if c == quote {
                if triple {
                    if self.chars.get(self.pos + 1) == Some(&quote)
                        && self.chars.get(self.pos + 2) == Some(&quote)
                    {
                        self.pos += 3;
                        return Ok(out);
                    }
                } else {
                    self.pos += 1;
                    return Ok(out);
                }
            }
            out.push(c);
            self.pos += 1;
        }
    }

    fn parse_number(&mut self) -> std::result::Result<serde_json::Value, String> {
        let start = self.pos;
        if matches!(self.peek(), Some('-') | Some('+')) {
            self.pos += 1;
        }
        while matches!(self.peek(), Some(c) if c.is_ascii_digit() || c == '.' || c == '_' || c == 'e' || c == 'E')
        {
            self.pos += 1;
        }
        let text: String = self.chars[start..self.pos]
            .iter()
            .filter(|c| **c != '_')
            .collect();
        if let Ok(i) = text.parse::<i64>() {
            return Ok(serde_json::Value::Number(i.into()));
        }
        if let Ok(f) = text.parse::<f64>() {
            if let Some(n) = serde_json::Number::from_f64(f) {
                return Ok(serde_json::Value::Number(n));
            }
        }
        Err(format!("invalid number '{text}'"))
    }

    fn parse_sequence(
        &mut self,
        open: char,
        close: char,
    ) -> std::result::Result<serde_json::Value, String> {
        debug_assert_eq!(self.peek(), Some(open));
        self.pos += 1;
        self.saw_comma = false;
        let mut items = Vec::new();
        let mut saw_comma = false;
        loop {
            self.skip_ws();
            if self.peek() == Some(close) {
                self.pos += 1;
                self.saw_comma = saw_comma;
                return Ok(serde_json::Value::Array(items));
            }
            items.push(self.parse_value()?);
            self.skip_ws();
            match self.peek() {
                Some(',') => {
                    saw_comma = true;
                    self.pos += 1;
                }
                Some(c) if c == close => {}
                _ => return Err(format!("expected ',' or '{close}'")),
            }
        }
    }

    fn parse_dict(&mut self) -> std::result::Result<serde_json::Value, String> {
        debug_assert_eq!(self.peek(), Some('{'));
        self.pos += 1;
        let mut map = serde_json::Map::new();
        loop {
            self.skip_ws();
            if self.peek() == Some('}') {
                self.pos += 1;
                return Ok(serde_json::Value::Object(map));
            }
            let key = match self.parse_value()? {
                serde_json::Value::String(s) => s,
                other => return Err(format!("non-string dict key {other}")),
            };
            self.skip_ws();
            if self.peek() != Some(':') {
                return Err("expected ':' in dict".to_string());
            }
            self.pos += 1;
            let value = self.parse_value()?;
            map.insert(key, value);
            self.skip_ws();
            match self.peek() {
                Some(',') => {
                    self.pos += 1;
                }
                Some('}') => {}
                _ => return Err("expected ',' or '}'".to_string()),
            }
        }
    }
}

impl Default for ConfPyConfig {
    fn default() -> Self {
        Self {
            project: None,
            version: None,
            release: None,
            copyright: None,
            author: None,
            extensions: Vec::new(),
            templates_path: vec!["_templates".to_string()],
            exclude_patterns: Vec::new(),
            include_patterns: vec!["**".to_string()], // Sphinx default
            source_suffix: HashMap::new(),
            root_doc: Some("index".to_string()),
            language: None,
            locale_dirs: vec!["locales".to_string()],
            gettext_compact: Some(true),
            html_theme: Some("alabaster".to_string()),
            html_theme_options: HashMap::new(),
            html_title: None,
            html_short_title: None,
            html_logo: None,
            html_favicon: None,
            html_css_files: Vec::new(),
            html_js_files: Vec::new(),
            html_static_path: vec!["_static".to_string()],
            html_extra_path: Vec::new(),
            html_use_index: Some(true),
            html_split_index: Some(false),
            html_copy_source: Some(true),
            html_show_sourcelink: Some(true),
            html_sourcelink_suffix: Some(".txt".to_string()),
            html_use_opensearch: None,
            html_file_suffix: Some(".html".to_string()),
            html_link_suffix: Some(".html".to_string()),
            html_show_copyright: Some(true),
            html_show_sphinx: Some(true),
            html_context: HashMap::new(),
            html_output_encoding: Some("utf-8".to_string()),
            html_compact_lists: Some(true),
            html_secnumber_suffix: Some(". ".to_string()),
            html_search_language: None,
            html_search_options: HashMap::new(),
            html_search_scorer: None,
            html_scaled_image_link: Some(true),
            html_baseurl: None,
            html_codeblock_linenos_style: Some("table".to_string()),
            html_math_renderer: Some("mathjax".to_string()),
            html_math_renderer_options: HashMap::new(),
            latex_engine: Some("pdflatex".to_string()),
            latex_documents: Vec::new(),
            latex_logo: None,
            latex_appendices: Vec::new(),
            latex_domain_indices: Some(true),
            latex_show_pagerefs: Some(false),
            latex_show_urls: Some("no".to_string()),
            latex_use_latex_multicolumn: Some(false),
            latex_use_xindy: Some(false),
            latex_toplevel_sectioning: None,
            latex_docclass: HashMap::new(),
            latex_additional_files: Vec::new(),
            latex_elements: HashMap::new(),
            epub_title: None,
            epub_author: None,
            epub_language: None,
            epub_publisher: None,
            epub_copyright: None,
            epub_identifier: None,
            epub_scheme: None,
            epub_uid: None,
            epub_cover: None,
            epub_css_files: Vec::new(),
            epub_pre_files: Vec::new(),
            epub_post_files: Vec::new(),
            epub_exclude_files: Vec::new(),
            epub_tocdepth: Some(3),
            epub_tocdup: Some(true),
            epub_tocscope: Some("default".to_string()),
            epub_fix_images: Some(false),
            epub_max_image_width: Some(0),
            epub_show_urls: Some("inline".to_string()),
            epub_use_index: Some(true),
            epub_description: None,
            epub_contributor: None,
            epub_writing_mode: Some("horizontal".to_string()),
            extension_configs: HashMap::new(),
            needs_sphinx: None,
            needs_extensions: HashMap::new(),
            manpages_url: None,
            nitpicky: Some(false),
            nitpick_ignore: Vec::new(),
            nitpick_ignore_regex: Vec::new(),
            numfig: Some(false),
            numfig_format: HashMap::new(),
            numfig_secnum_depth: Some(1),
            math_number_all: Some(false),
            math_eqref_format: None,
            math_numfig: Some(true),
            tls_verify: Some(true),
            tls_cacerts: None,
            user_agent: None,
            // `None` = "conf.py said nothing", which leaves
            // `BuildConfig::default()`'s sphinx defaults untouched.
            maximum_signature_line_length: None,
            python_maximum_signature_line_length: None,
            python_trailing_comma_in_multi_line_signatures: None,
            python_display_short_literal_types: None,
            python_use_unqualified_type_names: None,
            toc_object_entries: None,
            toc_object_entries_show_parents: None,
            source_encoding: None,
            confval_type_mismatches: Vec::new(),
            add_function_parentheses: None,
            add_module_names: None,
            strip_signature_backslash: None,
            modindex_common_prefix: Vec::new(),
            intersphinx_mapping: serde_json::Value::Null,
            intersphinx_disabled_reftypes: None,
            intersphinx_resolve_self: None,
            intersphinx_cache_limit: None,
            intersphinx_timeout: None,
            gettext_uuid: Some(false),
            gettext_location: Some(true),
            gettext_auto_build: Some(true),
            gettext_additional_targets: Vec::new(),
            custom_configs: HashMap::new(),
        }
    }
}

impl ConfPyConfig {
    /// Convert conf.py configuration to BuildConfig.
    ///
    /// Fails only where Sphinx itself raises `ConfigError` at
    /// `config-inited` — today that is `intersphinx_mapping` validation
    /// (`ext/intersphinx/_load.py:131-136`), which aborts the build before
    /// it reads a single document.
    pub fn to_build_config(&self) -> Result<BuildConfig> {
        let mut config = BuildConfig::default();

        // Map basic project information
        if let Some(project) = &self.project {
            config.project = project.clone();
        }
        if let Some(version) = &self.version {
            config.version = Some(version.clone());
        }
        if let Some(release) = &self.release {
            config.release = Some(release.clone());
        }
        if let Some(copyright) = &self.copyright {
            config.copyright = Some(copyright.clone());
        }
        if let Some(language) = &self.language {
            config.language = Some(language.clone());
        }
        if let Some(root_doc) = &self.root_doc {
            config.root_doc = Some(root_doc.clone());
        }

        // Map extensions
        config.extensions = self.extensions.clone();

        // Map template paths
        config.template_dirs = self.templates_path.iter().map(PathBuf::from).collect();

        // Map static paths
        config.static_dirs = self.html_static_path.iter().map(PathBuf::from).collect();
        config.html_static_path = self.html_static_path.iter().map(PathBuf::from).collect();

        // Map HTML configuration
        if let Some(html_theme) = &self.html_theme {
            config.output.html_theme = html_theme.clone();
            config.theme.name = html_theme.clone();
        }
        if let Some(html_title) = &self.html_title {
            config.html_title = Some(html_title.clone());
        }
        if let Some(html_short_title) = &self.html_short_title {
            config.html_short_title = Some(html_short_title.clone());
        }
        if let Some(html_logo) = &self.html_logo {
            config.html_logo = Some(html_logo.clone());
        }
        if let Some(html_favicon) = &self.html_favicon {
            config.html_favicon = Some(html_favicon.clone());
        }
        config.html_css_files = self.html_css_files.clone();
        config.html_js_files = self.html_js_files.clone();
        if let Some(html_show_copyright) = self.html_show_copyright {
            config.html_show_copyright = Some(html_show_copyright);
        }
        if let Some(html_show_sphinx) = self.html_show_sphinx {
            config.html_show_sphinx = Some(html_show_sphinx);
        }
        if let Some(html_copy_source) = self.html_copy_source {
            config.html_copy_source = Some(html_copy_source);
        }
        if let Some(html_show_sourcelink) = self.html_show_sourcelink {
            config.html_show_sourcelink = Some(html_show_sourcelink);
        }
        if let Some(html_sourcelink_suffix) = &self.html_sourcelink_suffix {
            config.html_sourcelink_suffix = Some(html_sourcelink_suffix.clone());
        }
        if let Some(html_use_index) = self.html_use_index {
            config.html_use_index = Some(html_use_index);
        }
        if let Some(html_use_opensearch) = &self.html_use_opensearch {
            config.html_use_opensearch = Some(!html_use_opensearch.is_empty());
        }
        if let Some(html_last_updated_fmt) = &self.html_context.get("last_updated") {
            if let Some(fmt_str) = html_last_updated_fmt.as_str() {
                config.html_last_updated_fmt = Some(fmt_str.to_string());
            }
        }

        // Map templates path
        config.templates_path = self.templates_path.iter().map(PathBuf::from).collect();

        // Map file patterns (Sphinx compatibility)
        config.include_patterns = if self.include_patterns.is_empty() {
            vec!["**".to_string()] // Sphinx default
        } else {
            self.include_patterns.clone()
        };
        config.exclude_patterns = self.exclude_patterns.clone();

        config.nitpicky = self.nitpicky.unwrap_or(false);
        config.nitpick_ignore = self.nitpick_ignore.clone();
        config.nitpick_ignore_regex = self.nitpick_ignore_regex.clone();
        config.html_context = self
            .html_context
            .iter()
            .map(|(key, value)| (key.clone(), value.clone()))
            .collect();

        // Numbering (`numfig` family). `numfig_format` MERGES over the
        // defaults `BuildConfig::default()` seeded — sphinx applies the
        // user dict on top of its own at `config-inited` prio 800
        // (`config.py:682-693`), so a conf.py naming only `figure` keeps
        // `section`/`table`/`code-block`.
        config.numfig = self.numfig.unwrap_or(false);
        for (figtype, format) in &self.numfig_format {
            config.numfig_format.insert(figtype.clone(), format.clone());
        }
        if let Some(depth) = self.numfig_secnum_depth {
            config.numfig_secnum_depth = depth.max(0) as u32;
        }

        // Object-signature / py-domain family: every key that `conf.py`
        // actually named overrides the sphinx default, and nothing else does.
        // The two `Option<i64>` keys assign straight through, because for
        // them "unset" and "set to None" are the same thing in sphinx too.
        config.maximum_signature_line_length = self.maximum_signature_line_length;
        config.python_maximum_signature_line_length = self.python_maximum_signature_line_length;
        config.confval_type_mismatches = self.confval_type_mismatches.clone();
        if let Some(source_encoding) = &self.source_encoding {
            config.source_encoding = source_encoding.clone();
        }
        if let Some(trailing_comma) = self.python_trailing_comma_in_multi_line_signatures {
            config.python_trailing_comma_in_multi_line_signatures = trailing_comma;
        }
        if let Some(short_literals) = self.python_display_short_literal_types {
            config.python_display_short_literal_types = short_literals;
        }
        if let Some(unqualified) = self.python_use_unqualified_type_names {
            config.python_use_unqualified_type_names = unqualified;
        }
        if let Some(toc_object_entries) = self.toc_object_entries {
            config.toc_object_entries = toc_object_entries;
        }
        if let Some(show_parents) = &self.toc_object_entries_show_parents {
            // Carried through even when it is outside the ENUM: sphinx only
            // warns (`BuildConfig::validate`).
            config.toc_object_entries_show_parents = show_parents.clone();
        }
        if let Some(add_parens) = self.add_function_parentheses {
            config.add_function_parentheses = add_parens;
        }
        if let Some(add_module_names) = self.add_module_names {
            config.add_module_names = add_module_names;
        }
        if let Some(strip_backslash) = self.strip_signature_backslash {
            config.strip_signature_backslash = strip_backslash;
        }
        config.modindex_common_prefix = self.modindex_common_prefix.clone();

        // intersphinx + the shared HTTP configuration group.
        let (mapping, errors) = crate::intersphinx::validate_mapping(&self.intersphinx_mapping);
        for error in &errors {
            // Sphinx logs each one with `LOGGER.error` before raising.
            log::error!("{error}");
        }
        if !errors.is_empty() {
            return Err(anyhow!(crate::intersphinx::mapping_config_error(
                errors.len()
            )));
        }
        config.intersphinx_mapping = mapping;
        if let Some(disabled) = &self.intersphinx_disabled_reftypes {
            config.intersphinx_disabled_reftypes = disabled.clone();
        }
        if let Some(resolve_self) = &self.intersphinx_resolve_self {
            config.intersphinx_resolve_self = resolve_self.clone();
        }
        if let Some(limit) = self.intersphinx_cache_limit {
            config.intersphinx_cache_limit = limit;
        }
        config.intersphinx_timeout = self.intersphinx_timeout;
        if let Some(tls_verify) = self.tls_verify {
            config.tls_verify = tls_verify;
        }
        config.tls_cacerts = self.tls_cacerts.clone();
        config.user_agent = self.user_agent.clone();

        Ok(config)
    }
}

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

    fn parse(content: &str) -> PythonConfigParser {
        let mut parser = PythonConfigParser::new().unwrap();
        parser.parse_statements(content).unwrap();
        parser
    }

    #[test]
    fn multiline_list_parses() {
        let p = parse("extensions = [\n    'sphinx.ext.autodoc',\n    'sphinx.ext.viewcode',\n]\n");
        let v = p.conf_namespace.get("extensions").expect("extensions set");
        let items: Vec<&str> = v
            .as_array()
            .unwrap()
            .iter()
            .map(|i| i.as_str().unwrap())
            .collect();
        assert_eq!(items, vec!["sphinx.ext.autodoc", "sphinx.ext.viewcode"]);
        assert!(p.warnings().is_empty(), "warnings: {:?}", p.warnings());
    }

    #[test]
    fn multiline_dict_parses() {
        let p = parse(
            "html_theme_options = {\n    'collapse_navigation': False,\n    'navigation_depth': 4,\n}\n",
        );
        let v = p
            .conf_namespace
            .get("html_theme_options")
            .expect("dict set");
        let obj = v.as_object().unwrap();
        assert_eq!(
            obj.get("collapse_navigation"),
            Some(&serde_json::Value::Bool(false))
        );
        assert_eq!(
            obj.get("navigation_depth").and_then(|n| n.as_i64()),
            Some(4)
        );
    }

    #[test]
    fn adjacent_string_concat_parses() {
        let p = parse("copyright = ('2024, ' 'Team')\n");
        assert_eq!(
            p.conf_namespace.get("copyright").and_then(|v| v.as_str()),
            Some("2024, Team")
        );
    }

    #[test]
    fn triple_quoted_string_parses() {
        let p = parse("project = \"\"\"Multi\nLine\"\"\"\n");
        assert_eq!(
            p.conf_namespace.get("project").and_then(|v| v.as_str()),
            Some("Multi\nLine")
        );
    }

    #[test]
    fn trailing_comment_stripped() {
        let p = parse("version = '1.0'  # the version\n");
        assert_eq!(
            p.conf_namespace.get("version").and_then(|v| v.as_str()),
            Some("1.0")
        );
    }

    #[test]
    fn unsupported_value_warns_and_drops() {
        let p = parse("project = os.environ['P']\n");
        assert!(!p.conf_namespace.contains_key("project"));
        assert_eq!(p.warnings().len(), 1);
        assert_eq!(p.warnings()[0].line, 1);
        assert!(
            p.warnings()[0].message.contains("project"),
            "warning names the variable: {}",
            p.warnings()[0].message
        );
    }

    #[test]
    fn unsupported_statement_warns_but_imports_do_not() {
        let p = parse("import os\nfrom pathlib import Path\nsys.path.insert(0, 'x')\n");
        assert_eq!(p.warnings().len(), 1, "warnings: {:?}", p.warnings());
        assert_eq!(p.warnings()[0].line, 3);
    }

    #[test]
    fn nested_structures_parse() {
        let p = parse(
            "intersphinx_mapping = {\n    'python': ('https://docs.python.org/3', None),\n}\n",
        );
        let v = p.conf_namespace.get("intersphinx_mapping").unwrap();
        let python = v
            .as_object()
            .unwrap()
            .get("python")
            .unwrap()
            .as_array()
            .unwrap();
        assert_eq!(python[0].as_str(), Some("https://docs.python.org/3"));
        assert!(python[1].is_null());
    }

    #[test]
    fn numfig_family_reaches_the_build_config() {
        let p = parse(
            "numfig = True\nnumfig_secnum_depth = 2\n\
             numfig_format = {'figure': 'Figure %s', 'table': 'Table {number}'}\n",
        );
        let config = p
            .extract_configuration()
            .unwrap()
            .to_build_config()
            .unwrap();

        assert!(config.numfig);
        assert_eq!(config.numfig_secnum_depth, 2);
        // The user's two entries merge OVER the four defaults rather than
        // replacing them (`config.py:682-693`).
        assert_eq!(config.numfig_format["figure"], "Figure %s");
        assert_eq!(config.numfig_format["table"], "Table {number}");
        assert_eq!(config.numfig_format["section"], "Section %s");
        assert_eq!(config.numfig_format["code-block"], "Listing %s");
    }

    #[test]
    fn nitpick_ignore_lists_reach_the_build_config() {
        let p = parse(
            "nitpicky = True\n\
             nitpick_ignore = [('py:func', 'nope'), ('doc', 'missing')]\n\
             nitpick_ignore_regex = [(r'std:.*', r'legacy-.*')]\n",
        );
        let config = p
            .extract_configuration()
            .unwrap()
            .to_build_config()
            .unwrap();

        assert!(config.nitpicky);
        assert_eq!(
            config.nitpick_ignore,
            vec![
                ("py:func".to_string(), "nope".to_string()),
                ("doc".to_string(), "missing".to_string()),
            ]
        );
        assert_eq!(
            config.nitpick_ignore_regex,
            vec![("std:.*".to_string(), "legacy-.*".to_string())]
        );
    }

    /// The eleven object-signature / py-domain keys must reach `BuildConfig`
    /// from `conf.py`, with the defaults surviving for anything the file
    /// does not mention.
    #[test]
    fn the_object_signature_family_reaches_the_build_config() {
        let p = parse(
            "maximum_signature_line_length = 88\n\
             python_maximum_signature_line_length = 0\n\
             python_trailing_comma_in_multi_line_signatures = False\n\
             python_display_short_literal_types = True\n\
             python_use_unqualified_type_names = True\n\
             toc_object_entries = False\n\
             toc_object_entries_show_parents = 'all'\n\
             add_function_parentheses = False\n\
             add_module_names = False\n\
             strip_signature_backslash = True\n\
             modindex_common_prefix = ['mypkg.', 'other.']\n",
        );
        let config = p
            .extract_configuration()
            .unwrap()
            .to_build_config()
            .unwrap();

        assert_eq!(config.maximum_signature_line_length, Some(88));
        assert_eq!(
            config.python_maximum_signature_line_length,
            Some(0),
            "an explicit 0 is NOT the same as unset — max_len()'s truthiness \
             fall-through depends on carrying it through unchanged"
        );
        assert!(!config.python_trailing_comma_in_multi_line_signatures);
        assert!(config.python_display_short_literal_types);
        assert!(config.python_use_unqualified_type_names);
        assert!(!config.toc_object_entries);
        assert_eq!(config.toc_object_entries_show_parents, "all");
        assert!(!config.add_function_parentheses);
        assert!(!config.add_module_names);
        assert!(config.strip_signature_backslash);
        assert_eq!(
            config.modindex_common_prefix,
            vec!["mypkg.".to_string(), "other.".to_string()]
        );

        // A conf.py that mentions none of them keeps sphinx's defaults.
        let untouched = parse("project = 'x'\n")
            .extract_configuration()
            .unwrap()
            .to_build_config()
            .unwrap();
        assert_eq!(untouched.maximum_signature_line_length, None);
        assert!(untouched.add_function_parentheses);
        assert!(untouched.toc_object_entries);
        assert_eq!(untouched.toc_object_entries_show_parents, "domain");
    }

    /// A key this crate maps is a *standard* key: it must not also be
    /// dumped into `custom_configs`, which is the catch-all for settings
    /// only an extension understands.
    #[test]
    fn the_object_signature_family_is_not_treated_as_custom_config() {
        let p = parse(
            "maximum_signature_line_length = 88\n\
             python_maximum_signature_line_length = 40\n\
             python_trailing_comma_in_multi_line_signatures = False\n\
             python_display_short_literal_types = True\n\
             python_use_unqualified_type_names = True\n\
             toc_object_entries = False\n\
             toc_object_entries_show_parents = 'all'\n\
             add_function_parentheses = False\n\
             add_module_names = False\n\
             strip_signature_backslash = True\n\
             modindex_common_prefix = ['mypkg.']\n\
             nitpick_ignore = [('py:func', 'nope')]\n\
             nitpick_ignore_regex = [('py:.*', 'nope.*')]\n\
             my_extension_knob = 3\n",
        );
        let config = p.extract_configuration().unwrap();

        assert_eq!(
            config.custom_configs.keys().collect::<Vec<_>>(),
            vec!["my_extension_knob"],
            "only the genuinely unknown key is custom: {:?}",
            config.custom_configs
        );
    }

    #[test]
    fn raw_and_prefixed_string_literals_parse() {
        // A raw Rust literal: what follows is byte-for-byte what conf.py holds.
        let p = parse(
            r"a = r'back\slash'
b = R'\d+'
c = u'plain'
d = rb'bytes'
e = 'esc\n'
",
        );
        let ns = |key: &str| p.conf_namespace[key].as_str().unwrap().to_string();
        assert_eq!(
            ns("a"),
            r"back\slash",
            "a raw literal keeps its backslashes"
        );
        assert_eq!(ns("b"), r"\d+");
        assert_eq!(ns("c"), "plain");
        assert_eq!(ns("d"), "bytes");
        assert_eq!(ns("e"), "esc\n", "a plain literal still translates escapes");
    }

    #[test]
    fn the_intersphinx_family_reaches_the_build_config() {
        let p = parse(
            "intersphinx_mapping = {\n\
             'python': ('https://docs.python.org/3', None),\n\
             'other': ('https://example.org/', 'local.inv'),\n\
             }\n\
             intersphinx_disabled_reftypes = ['std:doc', 'std:label']\n\
             intersphinx_resolve_self = 'mine'\n\
             intersphinx_cache_limit = 0\n\
             intersphinx_timeout = 2.5\n\
             tls_verify = False\n\
             tls_cacerts = '/etc/ca.pem'\n\
             user_agent = 'mine/1'\n",
        );
        let config = p
            .extract_configuration()
            .unwrap()
            .to_build_config()
            .expect("a valid mapping must not fail configuration");

        assert_eq!(
            config.intersphinx_mapping["python"],
            ("https://docs.python.org/3".to_string(), vec![None])
        );
        assert_eq!(
            config.intersphinx_mapping["other"],
            (
                "https://example.org/".to_string(),
                vec![Some("local.inv".to_string())]
            )
        );
        assert_eq!(
            config.intersphinx_disabled_reftypes,
            vec!["std:doc".to_string(), "std:label".to_string()]
        );
        assert_eq!(config.intersphinx_resolve_self, "mine");
        assert_eq!(config.intersphinx_cache_limit, 0);
        assert_eq!(config.intersphinx_timeout, Some(2.5));
        assert!(!config.tls_verify);
        assert_eq!(
            config.tls_cacerts,
            Some(crate::intersphinx::TlsCacerts::Bundle(
                "/etc/ca.pem".to_string()
            ))
        );
        assert_eq!(config.user_agent, Some("mine/1".to_string()));
    }

    #[test]
    fn tls_cacerts_accepts_the_per_host_mapping_form() {
        let p = parse("tls_cacerts = {'docs.example.org': '/etc/example.pem'}\n");
        let config = p
            .extract_configuration()
            .unwrap()
            .to_build_config()
            .unwrap();
        assert_eq!(
            config.tls_cacerts,
            Some(crate::intersphinx::TlsCacerts::PerHost(
                std::collections::BTreeMap::from([(
                    "docs.example.org".to_string(),
                    "/etc/example.pem".to_string()
                )])
            ))
        );
    }

    #[test]
    fn an_invalid_intersphinx_mapping_stops_the_configuration() {
        let p = parse("intersphinx_mapping = {'p': 'https://x/'}\n");
        let err = p
            .extract_configuration()
            .unwrap()
            .to_build_config()
            .expect_err("a malformed entry must abort");
        assert_eq!(
            err.to_string(),
            "Invalid `intersphinx_mapping` configuration (1 error)."
        );
    }

    #[test]
    fn a_conf_py_without_numfig_keeps_the_defaults() {
        let p = parse("project = 'Docs'\n");
        let config = p
            .extract_configuration()
            .unwrap()
            .to_build_config()
            .unwrap();

        assert!(!config.numfig);
        assert_eq!(config.numfig_secnum_depth, 1);
        assert_eq!(config.numfig_format["figure"], "Fig. %s");
    }

    /// conf.py side of `check_confval_types` for the two `int | None` keys
    /// (panel fix round B, [18]): an int or `None` is taken as is; any
    /// other literal is recorded with its python type name for
    /// `BuildConfig::validate` to report, and the key stays unset.
    #[test]
    fn a_mistyped_none_default_int_key_in_conf_py_is_recorded_not_coerced() {
        let p = parse(
            "maximum_signature_line_length = '88'\n\
             python_maximum_signature_line_length = 42\n",
        );
        let config = p.extract_configuration().unwrap();
        assert_eq!(config.maximum_signature_line_length, None);
        assert_eq!(config.python_maximum_signature_line_length, Some(42));
        assert_eq!(
            config.confval_type_mismatches,
            vec![(
                "maximum_signature_line_length".to_string(),
                "str".to_string()
            )]
        );
        let build = config.to_build_config().unwrap();
        assert_eq!(build.maximum_signature_line_length, None);
        assert_eq!(
            build.validate(),
            vec![
                "The config value `maximum_signature_line_length' has type `str'; expected \
                 `NoneType' or `int'."
                    .to_string()
            ]
        );

        for (literal, type_name) in [
            ("88.0", "float"),
            ("True", "bool"),
            ("[88]", "list"),
            ("{'a': 1}", "dict"),
        ] {
            let p = parse(&format!(
                "python_maximum_signature_line_length = {literal}\n"
            ));
            let config = p.extract_configuration().unwrap();
            assert_eq!(
                config.python_maximum_signature_line_length, None,
                "{literal}"
            );
            assert_eq!(
                config.confval_type_mismatches,
                vec![(
                    "python_maximum_signature_line_length".to_string(),
                    type_name.to_string()
                )],
                "{literal}"
            );
        }

        // `None` and an absent key are the same thing, and neither is a
        // mismatch.
        let p = parse("maximum_signature_line_length = None\n");
        let config = p.extract_configuration().unwrap();
        assert_eq!(config.maximum_signature_line_length, None);
        assert!(config.confval_type_mismatches.is_empty());
    }

    /// `source_encoding` is a standard key: read from conf.py, handed to
    /// the build configuration, and never dropped into `custom_configs`.
    #[test]
    fn source_encoding_is_read_from_conf_py() {
        let p = parse("source_encoding = 'latin-1'\n");
        let config = p.extract_configuration().unwrap();
        assert_eq!(config.source_encoding.as_deref(), Some("latin-1"));
        assert!(!config.custom_configs.contains_key("source_encoding"));
        assert_eq!(config.to_build_config().unwrap().source_encoding, "latin-1");

        let p = parse("project = 'x'\n");
        let config = p.extract_configuration().unwrap();
        assert_eq!(config.source_encoding, None);
        assert_eq!(
            config.to_build_config().unwrap().source_encoding,
            "utf-8-sig"
        );
    }
}