keymap-config 0.1.0

Load keymap-rs bindings from TOML, with conflict detection
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
//! # keymap-config
//!
//! Builds a [`Keymap`] from a TOML `[keys]` table, resolving action names with a
//! caller-supplied function and reporting problems that should not silently
//! pass.
//!
//! ```
//! #[derive(Clone, Debug, PartialEq)]
//! enum Action { Quit, Save }
//!
//! let toml = r#"
//! [keys]
//! "ctrl+q" = "quit"
//! "ctrl+s" = "save"
//! "#;
//!
//! let out = keymap_config::from_str(toml, |name| match name {
//!     "quit" => Some(Action::Quit),
//!     "save" => Some(Action::Save),
//!     _ => None,
//! })
//! .unwrap();
//!
//! assert!(out.warnings.is_empty());
//! ```
//!
//! ## Named layers
//!
//! Bindings live in *layers*. The bare top-level `[keys]` table is the
//! [`GLOBAL_LAYER`] layer; additional `[layers.<name>]` tables each build a layer
//! of that name, holding chord→action entries directly:
//!
//! ```toml
//! [keys]               # the implicit "global" layer
//! "ctrl+q" = "quit"
//!
//! [layers.panel]       # a caller-named layer
//! "ctrl+s" = "split"
//! ```
//!
//! [`from_str`] returns these as [`BuildOutput::layers`], a name→[`Keymap`] map
//! always containing `"global"`. Which layers are active, and in what order, is
//! **not** this crate's concern: the caller picks them per event and resolves
//! with [`keymap_core::resolve_layered`] (first layer to bind a chord wins, misses
//! fall through). The same chord in two layers is therefore an *override*, not a
//! conflict — this crate only ever reports conflicts *within* a single layer.
//! Layer names are opaque labels; the library attaches meaning to none of them.
//!
//! ## What is an error versus a warning
//!
//! Structural problems — malformed TOML, or a key string that does not parse —
//! are [`BuildError`]: there is no usable map to return. Survivable problems —
//! two keys resolving to the same chord, or an action name the resolver does not
//! recognize — are collected into [`BuildOutput::warnings`] so the rest of the
//! bindings still work and the user can be told what to fix.
//!
//! ## Legacy-terminal survivability (opt-in, separate from warnings)
//!
//! "This binding won't survive a legacy terminal" (e.g. a `cmd+…` chord a legacy
//! terminal cannot deliver, or `ctrl+i` which is indistinguishable from `tab`) is
//! deliberately *not* a [`Warning`]: it depends on the deployment terminal, not
//! the config's correctness, and folding it into [`BuildOutput::warnings`] would
//! make a perfectly good config report warnings. It is exposed instead as the
//! opt-in [`keymap_core::legacy_lints`], which you call on a built keymap when
//! you want it: `keymap_core::legacy_lints(out.global())` (or on any one layer).
//! Callers gating on `warnings.is_empty()` are unaffected.
//!
//! ## Multi-key sequences
//!
//! Alongside the single-chord `[keys]` table, an `[[sequences]]` array of tables
//! binds *sequences* of chords (leader trees, `ctrl+x ctrl+s`) into a
//! [`SequenceKeymap`](keymap_seq::SequenceKeymap), returned as
//! [`BuildOutput::sequences`]:
//!
//! ```toml
//! [keys]
//! "ctrl+q" = "quit"
//!
//! [[sequences]]
//! keys = ["ctrl+x", "ctrl+s"]
//! action = "save"
//! ```
//!
//! Each element of `keys` reuses the single-chord grammar, so no new key syntax
//! is introduced. Two sequence bindings that share a prefix cannot coexist
//! without a timeout (see `keymap-seq`); such a pair is reported as
//! [`Warning::PrefixShadow`] and the later one is dropped. A single-key binding
//! that shadows a sequence (e.g. `"j"` in `[keys]` versus a sequence starting
//! with `j`) is reported as the advisory [`Warning::SequenceShadow`] — both
//! bindings are kept (they live in separate maps), so it only flags that the
//! caller composing the two maps must resolve the overlap with a timeout.
//!
//! ## Runnable examples
//!
//! Under [`examples/`](https://github.com/S-Nakamur-a/keymap-rs/tree/main/crates/keymap-config/examples):
//! `cargo run -p keymap-config --example load_config` walks the TOML-to-keymap
//! pipeline end to end, and `--example rebind` shows the runtime-rebind flow
//! on top of `keymap_term::decode`.

use std::collections::{BTreeMap, HashMap};

use keymap_core::{KeyInput, Keymap, ParseKeyInputError};
use keymap_seq::{SeqBindError, SequenceKeymap};
use serde::Deserialize;

/// The name of the layer built from the top-level `[keys]` table.
///
/// It is the one name this crate assigns: the bare `[keys]` table (and an
/// explicit `[layers.global]`, if present) build the layer under this key, which
/// is **always present** in [`BuildOutput::layers`] even when empty. Every other
/// layer name is opaque to the library — it is just the label the config author
/// chose; the library attaches no meaning to it and never decides when a layer is
/// active. That selection stays caller-side (see [`keymap_core::resolve_layered`]).
pub const GLOBAL_LAYER: &str = "global";

/// The result of a successful build: the named layers plus any non-fatal warnings.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct BuildOutput<A> {
    /// The assembled layers, keyed by name. The top-level `[keys]` table builds
    /// the [`GLOBAL_LAYER`] layer (always present, even when empty); each
    /// `[layers.<name>]` table builds the layer of that name. Within any one
    /// layer, conflicting chords resolve to the last binding. The same chord
    /// bound in two *different* layers is not a conflict — it is the override the
    /// caller composes with [`keymap_core::resolve_layered`], so this crate never
    /// reports across layer boundaries.
    ///
    /// Always contains the `"global"` key, so `layers.len()` counts the global
    /// layer even when the config bound nothing in it.
    pub layers: BTreeMap<String, Keymap<A>>,
    /// The assembled sequence map, built from the top-level `[[sequences]]`
    /// tables. Sequences are **not** layered (they belong to the global config);
    /// empty when the config has no sequences.
    pub sequences: SequenceKeymap<A>,
    /// Problems that did not prevent building (conflicts, unknown actions,
    /// prefix shadows), in the order they were first seen.
    pub warnings: Vec<Warning>,
}

impl<A> BuildOutput<A> {
    /// The [`GLOBAL_LAYER`] layer (built from the top-level `[keys]` table).
    ///
    /// This is the convenience accessor for the common case of a single,
    /// unlayered keymap: `out.global()` is exactly `&out.layers[GLOBAL_LAYER]`.
    /// A config with no `[keys]` table yields an empty global layer, not an
    /// absent one.
    ///
    /// # Panics
    ///
    /// Never in practice: [`from_str`] always inserts the global layer (empty if
    /// the config had no `[keys]` table), so the lookup cannot miss.
    #[must_use]
    pub fn global(&self) -> &Keymap<A> {
        self.layers
            .get(GLOBAL_LAYER)
            .expect("the global layer is always inserted")
    }
}

/// A non-fatal problem found while building a [`Keymap`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Warning {
    /// Two or more keys resolved to the same chord *within one layer*; the last
    /// one wins. A named layer's conflict uses this same variant and carries no
    /// layer name, so two layers each conflicting on the same chord produce
    /// warnings indistinguishable on their own (the chord identifies the clash,
    /// not the layer). The same chord across *different* layers is an override,
    /// not a conflict, and is never reported.
    Conflict {
        /// The shared chord, in canonical form (e.g. `"ctrl+a"`).
        chord: String,
        /// The competing action names, in file order.
        contenders: Vec<String>,
        /// The action name that won (the last binding for the chord).
        winner: String,
    },
    /// An action name in the config was not recognized by the resolver; the
    /// binding was skipped.
    UnknownAction {
        /// The key string as written in the config. For a sequence, the
        /// canonical chords joined by spaces.
        key: String,
        /// The unrecognized action name.
        action: String,
    },
    /// Two sequence bindings share a prefix: the shorter (`prefix`) is a proper
    /// prefix of the longer (`shadowed`), so they cannot coexist without a
    /// timeout to tell them apart. The later-in-file binding was dropped to keep
    /// the sequence table prefix-free.
    PrefixShadow {
        /// The shorter sequence, one canonical chord per element.
        prefix: Vec<String>,
        /// The action bound to the shorter sequence.
        prefix_action: String,
        /// The longer sequence that shares the prefix, one chord per element.
        shadowed: Vec<String>,
        /// The action bound to the longer sequence.
        shadowed_action: String,
    },
    /// A `[[sequences]]` entry had an empty `keys` array; it was skipped.
    EmptySequence {
        /// The action name the empty sequence would have been bound to.
        action: String,
    },
    /// A single-chord `[keys]` binding collides with the first key of a
    /// `[[sequences]]` entry (e.g. `"j"` in `[keys]` and a sequence `["j", "k"]`).
    /// Pressing that chord is then ambiguous — fire the single action now, or wait
    /// to see if the sequence continues? — and can only be disambiguated by a
    /// caller-side timeout (the vim `jj` case; see `keymap-seq`).
    ///
    /// Unlike [`PrefixShadow`](Warning::PrefixShadow), **nothing is dropped**: the
    /// chord stays in its layer (the global one — this is checked only against the
    /// global layer) and the sequence stays in [`BuildOutput::sequences`] (they are
    /// separate maps). This is purely an
    /// advisory that the caller composing the two maps must resolve the overlap.
    SequenceShadow {
        /// The single chord, in canonical form (e.g. `"j"`).
        chord: String,
        /// The action bound to the single chord.
        chord_action: String,
        /// One sequence the chord shadows — the lexicographically-first when it
        /// shadows several — one canonical chord per element (its first equals
        /// `chord`).
        sequence: Vec<String>,
        /// The action bound to that sequence.
        sequence_action: String,
    },
}

/// A fatal problem that prevents building a [`Keymap`].
#[derive(Debug)]
#[non_exhaustive]
pub enum BuildError {
    /// The input was not valid TOML.
    Toml(toml::de::Error),
    /// A key string in the `[keys]` table could not be parsed.
    KeyParse {
        /// The offending key string as written.
        key: String,
        /// The underlying parse error.
        source: ParseKeyInputError,
    },
}

impl core::fmt::Display for BuildError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            BuildError::Toml(_) => f.write_str("invalid TOML"),
            BuildError::KeyParse { key, .. } => write!(f, "invalid key string {key:?}"),
        }
    }
}

impl std::error::Error for BuildError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            BuildError::Toml(e) => Some(e),
            BuildError::KeyParse { source, .. } => Some(source),
        }
    }
}

impl From<toml::de::Error> for BuildError {
    fn from(e: toml::de::Error) -> Self {
        BuildError::Toml(e)
    }
}

// `deny_unknown_fields` makes a misspelled or unsupported key a `BuildError::Toml`
// rather than a silent no-op — chosen pre-1.0 because adding it *later* would
// reject configs that used to parse. It also keeps the door open for additive
// fields (e.g. a future per-`[[sequences]]` `layer = "..."` tag) without their
// typos failing silently.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawConfig {
    #[serde(default)]
    keys: BTreeMap<String, String>,
    #[serde(default)]
    layers: BTreeMap<String, BTreeMap<String, String>>,
    #[serde(default)]
    sequences: Vec<RawSequence>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RawSequence {
    keys: Vec<String>,
    action: String,
}

/// The built sequence map paired with its sequence→action-name dictionary (the
/// names let a cross-shadow be reported against the single-key table).
type SequenceBuild<A> = (SequenceKeymap<A>, HashMap<Vec<KeyInput>, String>);

/// Builds a [`Keymap`] from a TOML string.
///
/// The `[keys]` table maps key strings (see `keymap_core::KeyInput`'s `FromStr`)
/// to action names; `resolve` turns each action name into the caller's action
/// type `A`, returning `None` for names it does not recognize.
///
/// # Errors
///
/// Returns [`BuildError`] if the input is not valid TOML, or if any key string
/// fails to parse. Unknown action names and chord conflicts are not errors —
/// they are returned in [`BuildOutput::warnings`].
pub fn from_str<A, F>(toml_str: &str, mut resolve: F) -> Result<BuildOutput<A>, BuildError>
where
    F: FnMut(&str) -> Option<A>,
{
    let RawConfig {
        keys,
        mut layers,
        sequences: raw_sequences,
    } = toml::from_str(toml_str)?;

    let mut warnings = Vec::new();
    let mut built: BTreeMap<String, Keymap<A>> = BTreeMap::new();

    // The global layer is the top-level `[keys]` table plus an explicit
    // `[layers.global]` if the author also wrote one. The two are concatenated —
    // `[keys]` first, then `[layers.global]` — and fed through the same per-chord
    // pipeline, so a chord present in both is reported as an ordinary in-layer
    // `Conflict` (and, being last, the `[layers.global]` entry wins) rather than
    // silently dropped. The global layer is always inserted, even when empty.
    let explicit_global = layers.remove(GLOBAL_LAYER).unwrap_or_default();
    let global_entries = keys.into_iter().chain(explicit_global);
    let (global_keymap, global_names) = build_layer(global_entries, &mut resolve, &mut warnings)?;
    built.insert(GLOBAL_LAYER.to_string(), global_keymap);

    // Every other named layer, in `BTreeMap` name order so warnings are
    // deterministic. Each layer's conflicts are detected within itself; layer
    // boundaries are never crossed (the caller owns the active chain).
    for (name, raw_keys) in layers {
        // Only the global layer feeds the cross-shadow check below, so a
        // non-global layer's name dictionary is computed but not needed here.
        let (keymap, _names) = build_layer(raw_keys, &mut resolve, &mut warnings)?;
        built.insert(name, keymap);
    }

    // Sequences are global-only, so the cross-shadow check (single chord versus
    // the first key of a sequence) runs against the global layer alone.
    let (sequences, seq_names) = build_sequences(raw_sequences, &mut resolve, &mut warnings)?;
    detect_cross_shadows(&global_names, &seq_names, &mut warnings);

    Ok(BuildOutput {
        layers: built,
        sequences,
        warnings,
    })
}

/// Builds one layer's [`Keymap`] from its `(raw key string, action name)`
/// entries, appending survivable problems to `warnings`.
///
/// Entries are grouped by the chord they normalize to (so different spellings of
/// the same chord — `ctrl+a` and `control+a` — collide), visited in first-seen
/// order. Within a group the last resolvable binding wins and a [`Warning::Conflict`]
/// is reported; an unresolvable action name is a [`Warning::UnknownAction`] and
/// that single entry is skipped.
///
/// Returns the built map together with the winning action *name* per chord, kept
/// so a cross-shadow warning can name the single-key side (the keymap stores `A`,
/// not names). Callers that don't need the names (any layer but global) discard them.
fn build_layer<A, I, F>(
    entries: I,
    resolve: &mut F,
    warnings: &mut Vec<Warning>,
) -> Result<(Keymap<A>, HashMap<KeyInput, String>), BuildError>
where
    I: IntoIterator<Item = (String, String)>,
    F: FnMut(&str) -> Option<A>,
{
    // Parse every key first (parse failures are fatal), grouping entries by the
    // chord they normalize to, in first-seen order.
    let mut order: Vec<KeyInput> = Vec::new();
    let mut groups: HashMap<KeyInput, Vec<(String, String)>> = HashMap::new();
    for (raw_key, action_name) in entries {
        let chord = raw_key
            .parse::<KeyInput>()
            .map_err(|source| BuildError::KeyParse {
                key: raw_key.clone(),
                source,
            })?;
        let entry = groups.entry(chord).or_default();
        if entry.is_empty() {
            order.push(chord);
        }
        entry.push((raw_key, action_name));
    }

    let mut keymap = Keymap::new();
    let mut names: HashMap<KeyInput, String> = HashMap::new();
    for chord in order {
        let Some(entries) = groups.remove(&chord) else {
            continue;
        };

        let mut resolved: Vec<(String, A)> = Vec::new();
        for (raw_key, action_name) in entries {
            match resolve(&action_name) {
                Some(action) => resolved.push((action_name, action)),
                None => warnings.push(Warning::UnknownAction {
                    key: raw_key,
                    action: action_name,
                }),
            }
        }

        if resolved.len() > 1 {
            let contenders: Vec<String> = resolved.iter().map(|(name, _)| name.clone()).collect();
            if let Some(winner) = contenders.last().cloned() {
                warnings.push(Warning::Conflict {
                    chord: chord.to_string(),
                    contenders,
                    winner,
                });
            }
        }

        // Last binding wins.
        if let Some((name, action)) = resolved.pop() {
            keymap.bind(chord, action);
            names.insert(chord, name);
        }
    }

    Ok((keymap, names))
}

/// Serializes a [`Keymap`] and [`SequenceKeymap`] back into a TOML config string
/// — the inverse of [`from_str`].
///
/// `name_of` is the mirror of [`from_str`]'s `resolve`: it turns each bound
/// action `A` back into the name written in the config, returning `None` for an
/// action that has no config name. A binding whose action returns `None` is
/// **omitted** from the output (the write-side dual of how [`from_str`] reports
/// an unresolvable name as [`Warning::UnknownAction`]); pass a total `name_of`
/// for a faithful export.
///
/// The result is **deterministic**: the `[keys]` table is emitted in canonical
/// chord order and the `[[sequences]]` array in joined-chord order, so the same
/// maps always produce byte-identical output (suitable for writing to disk and
/// diffing). I/O is the caller's — like [`from_str`], this crate only deals in
/// `&str`/`String`.
///
/// The guarantee is a **semantic round-trip**, not byte identity:
/// `from_str(&to_toml(km, seq, name_of), resolve)` rebuilds keymaps equivalent to
/// `km`/`seq` when `name_of` and `resolve` are inverses. The reverse direction is
/// lossy by design — normalization (`shift+a` → `a`) is non-invertible, and
/// comments, ordering, and original spelling are not preserved.
///
/// Action names and chords are emitted by constructing a [`toml::Value`] (never
/// by string concatenation), so the `toml` serializer handles all escaping; a
/// name containing quotes or TOML metacharacters cannot break out of its string
/// to inject extra bindings on the round-trip.
///
/// # Trust boundary
///
/// `to_toml` applies **no** policy: it emits whatever is bound, reserved/escape
/// keys included. A caller that writes this output somewhere another process
/// (notably a PTY-internal process) can also write **must** enforce reserved-key
/// rejection at its own load/bind boundary — otherwise an attacker who can write
/// that file can rebind the escape key. See `docs/STATUS.md`.
///
/// # Panics
///
/// Never in practice: it serializes a TOML value built only from string keys and
/// values, which the `toml` serializer cannot fail on.
pub fn to_toml<A, F>(keymap: &Keymap<A>, sequences: &SequenceKeymap<A>, mut name_of: F) -> String
where
    F: FnMut(&A) -> Option<&str>,
{
    let mut root = toml::Table::new();

    let keys = keymap_to_table(keymap, &mut name_of);
    if !keys.is_empty() {
        root.insert("keys".to_string(), toml::Value::Table(keys));
    }
    insert_sequences(&mut root, sequences, &mut name_of);

    // Serializing a table of string-only values is infallible.
    toml::to_string(&root).expect("string-only TOML value always serializes")
}

/// Serializes a named-layer set and the global [`SequenceKeymap`] back into a
/// TOML config string — the inverse of [`from_str`] for a multi-layer config.
///
/// The [`GLOBAL_LAYER`] layer is emitted as the top-level `[keys]` table and every
/// other layer as `[layers.<name>]`, with `[[sequences]]` carrying the (global)
/// sequence map. Like [`to_toml`] the output is **deterministic** (`BTreeMap`/sorted
/// layer, chord, and sequence order) and applies **no** policy — the same trust-boundary
/// caveat applies (see [`to_toml`]). Pass [`BuildOutput::layers`] straight in to
/// round-trip a parsed config; an empty layer emits nothing, and a global-only set
/// produces byte-identical output to [`to_toml`] on that one layer.
///
/// # Panics
///
/// Never in practice, for the same reason as [`to_toml`].
pub fn to_toml_layered<A, F>(
    layers: &BTreeMap<String, Keymap<A>>,
    sequences: &SequenceKeymap<A>,
    mut name_of: F,
) -> String
where
    F: FnMut(&A) -> Option<&str>,
{
    let mut root = toml::Table::new();
    let mut named = toml::Table::new();

    for (name, keymap) in layers {
        let table = keymap_to_table(keymap, &mut name_of);
        if table.is_empty() {
            continue;
        }
        if name == GLOBAL_LAYER {
            root.insert("keys".to_string(), toml::Value::Table(table));
        } else {
            named.insert(name.clone(), toml::Value::Table(table));
        }
    }

    insert_sequences(&mut root, sequences, &mut name_of);
    if !named.is_empty() {
        root.insert("layers".to_string(), toml::Value::Table(named));
    }

    // Serializing a table of string-only values is infallible.
    toml::to_string(&root).expect("string-only TOML value always serializes")
}

/// Renders one keymap as a `chord -> action name` [`toml::Table`]. A `toml` table
/// is a sorted map, so chord order is canonical with no extra sorting; bindings
/// whose action has no config name (`name_of` returns `None`) are omitted.
fn keymap_to_table<A, F>(keymap: &Keymap<A>, name_of: &mut F) -> toml::Table
where
    F: FnMut(&A) -> Option<&str>,
{
    let mut table = toml::Table::new();
    for (chord, action) in keymap.iter() {
        if let Some(name) = name_of(action) {
            table.insert(chord.to_string(), toml::Value::String(name.to_string()));
        }
    }
    table
}

/// Inserts a `[[sequences]]` array into `root` when the map has any named
/// sequences, sorted by the joined canonical chords (the same ordering key
/// cross-shadow detection uses) for deterministic output.
fn insert_sequences<A, F>(root: &mut toml::Table, sequences: &SequenceKeymap<A>, name_of: &mut F)
where
    F: FnMut(&A) -> Option<&str>,
{
    let mut seqs: Vec<(Vec<String>, String)> = sequences
        .bindings()
        .filter_map(|(path, action)| {
            name_of(action).map(|name| (render_sequence(&path), name.to_string()))
        })
        .collect();
    seqs.sort_by_key(|(chords, _)| chords.join(" "));

    if seqs.is_empty() {
        return;
    }
    let array = seqs
        .into_iter()
        .map(|(chords, name)| {
            let mut entry = toml::Table::new();
            entry.insert(
                "keys".to_string(),
                toml::Value::Array(chords.into_iter().map(toml::Value::String).collect()),
            );
            entry.insert("action".to_string(), toml::Value::String(name));
            toml::Value::Table(entry)
        })
        .collect();
    root.insert("sequences".to_string(), toml::Value::Array(array));
}

/// Flags single-chord bindings that collide with the first key of a sequence.
///
/// The two maps are built independently and composed by the caller, so a chord
/// `j` and a sequence starting with `j` are not a build-time conflict in either
/// table alone — but together they make the press of `j` ambiguous. One advisory
/// [`Warning::SequenceShadow`] is emitted per offending chord (naming the
/// lexicographically-first sequence it shadows), chords visited in canonical-string
/// order for a deterministic warning sequence.
fn detect_cross_shadows(
    single_names: &HashMap<KeyInput, String>,
    seq_names: &HashMap<Vec<KeyInput>, String>,
    warnings: &mut Vec<Warning>,
) {
    let mut singles: Vec<(&KeyInput, &String)> = single_names.iter().collect();
    singles.sort_by_key(|(chord, _)| chord.to_string());

    for (chord, chord_action) in singles {
        let mut shadowed: Vec<(&Vec<KeyInput>, &String)> = seq_names
            .iter()
            .filter(|(seq, _)| seq.first() == Some(chord))
            .collect();
        shadowed.sort_by_key(|(seq, _)| render_sequence(seq).join(" "));

        if let Some((sequence, sequence_action)) = shadowed.first() {
            warnings.push(Warning::SequenceShadow {
                chord: chord.to_string(),
                chord_action: chord_action.clone(),
                sequence: render_sequence(sequence),
                sequence_action: (*sequence_action).clone(),
            });
        }
    }
}

/// Builds the [`SequenceKeymap`] from the `[[sequences]]` tables, appending any
/// survivable problems to `warnings`.
///
/// Detection of prefix conflicts lives entirely in `keymap-seq`: this function
/// just calls [`SequenceKeymap::bind`] in file order and translates its result
/// into warnings, keeping only a sequence→action-name dictionary (names are this
/// crate's vocabulary, not `keymap-seq`'s) so it can name both sides of a clash.
///
/// Two write policies show through here, intentionally asymmetric:
/// - An exact re-binding of the same sequence is **last-wins** (overwrites) and
///   reported as a [`Warning::Conflict`], matching the single-chord `[keys]`
///   table.
/// - A *prefix* clash keeps the **earlier** binding and drops the later one
///   (reported as [`Warning::PrefixShadow`]); the established prefix path wins.
///
/// Returns the built map together with the sequence→action-name dictionary it
/// accrues, so the caller can detect cross-shadows against the single-key table
/// without re-deriving names.
fn build_sequences<A, F>(
    raw_sequences: Vec<RawSequence>,
    resolve: &mut F,
    warnings: &mut Vec<Warning>,
) -> Result<SequenceBuild<A>, BuildError>
where
    F: FnMut(&str) -> Option<A>,
{
    let mut sequences = SequenceKeymap::new();
    // Action *names* keyed by the sequence they bind, so a clash can name both
    // sides. This is naming data, not conflict detection — the trie owns that.
    let mut names: HashMap<Vec<KeyInput>, String> = HashMap::new();

    for raw_seq in raw_sequences {
        let mut keys = Vec::with_capacity(raw_seq.keys.len());
        for raw_key in &raw_seq.keys {
            let chord = raw_key
                .parse::<KeyInput>()
                .map_err(|source| BuildError::KeyParse {
                    key: raw_key.clone(),
                    source,
                })?;
            keys.push(chord);
        }

        let Some(action) = resolve(&raw_seq.action) else {
            warnings.push(Warning::UnknownAction {
                key: render_sequence(&keys).join(" "),
                action: raw_seq.action,
            });
            continue;
        };

        match sequences.bind(keys.iter().copied(), action) {
            Ok(None) => {
                names.insert(keys, raw_seq.action);
            }
            Ok(Some(_)) => {
                // Exact re-binding: last wins, reported like a repeated chord.
                let previous = names.insert(keys.clone(), raw_seq.action.clone());
                warnings.push(Warning::Conflict {
                    chord: render_sequence(&keys).join(" "),
                    contenders: vec![previous.unwrap_or_default(), raw_seq.action.clone()],
                    winner: raw_seq.action,
                });
            }
            Err(SeqBindError::Empty) => {
                warnings.push(Warning::EmptySequence {
                    action: raw_seq.action,
                });
            }
            Err(SeqBindError::PrefixShadow { sequence, conflict }) => {
                let conflict_action = names.get(&conflict).cloned().unwrap_or_default();
                // The shorter sequence is the prefix that wins; the longer is shadowed.
                let (prefix, prefix_action, shadowed, shadowed_action) =
                    if sequence.len() <= conflict.len() {
                        (sequence, raw_seq.action, conflict, conflict_action)
                    } else {
                        (conflict, conflict_action, sequence, raw_seq.action)
                    };
                warnings.push(Warning::PrefixShadow {
                    prefix: render_sequence(&prefix),
                    prefix_action,
                    shadowed: render_sequence(&shadowed),
                    shadowed_action,
                });
            }
            // `SeqBindError` is non-exhaustive: a future rejection reason we do
            // not yet model drops the binding rather than aborting the build.
            Err(_) => {}
        }
    }

    Ok((sequences, names))
}

/// Renders a sequence as one canonical chord string per key.
fn render_sequence(keys: &[KeyInput]) -> Vec<String> {
    keys.iter().map(ToString::to_string).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use keymap_core::{Key, Modifiers};

    #[derive(Debug, Clone, PartialEq)]
    enum Action {
        Quit,
        Save,
        Split,
        Top,
    }

    fn resolver(name: &str) -> Option<Action> {
        match name {
            "quit" => Some(Action::Quit),
            "save" => Some(Action::Save),
            "split" => Some(Action::Split),
            "top" => Some(Action::Top),
            _ => None,
        }
    }

    use keymap_seq::Match;

    fn seq(keys: &[(char, Modifiers)]) -> Vec<KeyInput> {
        keys.iter()
            .map(|&(c, m)| KeyInput::new(Key::Char(c), m))
            .collect()
    }

    #[test]
    fn builds_bindings_and_resolves_actions() {
        let toml = "[keys]\n\"ctrl+q\" = \"quit\"\n\"ctrl+s\" = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert!(out.warnings.is_empty());
        let q = KeyInput::new(Key::Char('q'), Modifiers::CTRL);
        assert_eq!(out.global().get(&q), Some(&Action::Quit));
    }

    #[test]
    fn bare_keys_build_the_global_layer_which_is_always_present() {
        // Even an empty config has a (empty) global layer, so `global()` never
        // panics and callers can rely on `layers["global"]` existing.
        let empty: BuildOutput<Action> = from_str("", resolver).unwrap();
        assert_eq!(empty.layers.keys().collect::<Vec<_>>(), vec![GLOBAL_LAYER]);
        assert!(empty.global().is_empty());

        let out = from_str("[keys]\n\"ctrl+q\" = \"quit\"\n", resolver).unwrap();
        assert_eq!(out.layers.keys().collect::<Vec<_>>(), vec![GLOBAL_LAYER]);
    }

    #[test]
    fn named_layers_are_parsed_under_their_names() {
        let toml = "\
[keys]\n\"ctrl+q\" = \"quit\"\n\
[layers.panel]\n\"ctrl+s\" = \"split\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert!(out.warnings.is_empty());
        // global and panel both present, named exactly.
        assert_eq!(
            out.layers.keys().map(String::as_str).collect::<Vec<_>>(),
            vec!["global", "panel"]
        );
        let q = KeyInput::new(Key::Char('q'), Modifiers::CTRL);
        let s = KeyInput::new(Key::Char('s'), Modifiers::CTRL);
        assert_eq!(out.global().get(&q), Some(&Action::Quit));
        assert_eq!(out.layers["panel"].get(&s), Some(&Action::Split));
        // A chord lives only in the layer that bound it.
        assert_eq!(out.global().get(&s), None);
        assert_eq!(out.layers["panel"].get(&q), None);
    }

    #[test]
    fn a_layer_with_no_keys_section_still_gets_an_empty_global() {
        let toml = "[layers.panel]\n\"ctrl+s\" = \"split\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert!(out.global().is_empty());
        assert!(!out.layers["panel"].is_empty());
    }

    #[test]
    fn same_chord_in_two_layers_is_an_override_not_a_conflict() {
        // The crux of the layered design: `ctrl+s` bound in both global and panel
        // is exactly the override `resolve_layered` exists for. The library never
        // knows which layer is active, so it must not report across the boundary.
        let toml = "\
[keys]\n\"ctrl+s\" = \"save\"\n\
[layers.panel]\n\"ctrl+s\" = \"split\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert!(
            out.warnings.is_empty(),
            "cross-layer override must not warn: {:?}",
            out.warnings
        );
        let s = KeyInput::new(Key::Char('s'), Modifiers::CTRL);
        assert_eq!(out.global().get(&s), Some(&Action::Save));
        assert_eq!(out.layers["panel"].get(&s), Some(&Action::Split));
    }

    #[test]
    fn explicit_global_layer_merges_into_the_top_level_keys() {
        let toml = "\
[keys]\n\"ctrl+q\" = \"quit\"\n\
[layers.global]\n\"ctrl+s\" = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert!(out.warnings.is_empty());
        // No separate "global" layer is created beyond the merged one.
        assert_eq!(out.layers.keys().collect::<Vec<_>>(), vec![GLOBAL_LAYER]);
        let q = KeyInput::new(Key::Char('q'), Modifiers::CTRL);
        let s = KeyInput::new(Key::Char('s'), Modifiers::CTRL);
        assert_eq!(out.global().get(&q), Some(&Action::Quit));
        assert_eq!(out.global().get(&s), Some(&Action::Save));
    }

    #[test]
    fn keys_and_explicit_global_colliding_on_a_chord_conflict_last_wins() {
        // The same chord in `[keys]` and `[layers.global]` is a within-layer
        // conflict (they are the same layer): reported, and the `[layers.global]`
        // entry — fed after `[keys]` — wins.
        let toml = "\
[keys]\n\"ctrl+q\" = \"quit\"\n\
[layers.global]\n\"ctrl+q\" = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert_eq!(
            out.warnings,
            vec![Warning::Conflict {
                chord: "ctrl+q".to_string(),
                contenders: vec!["quit".to_string(), "save".to_string()],
                winner: "save".to_string(),
            }]
        );
        let q = KeyInput::new(Key::Char('q'), Modifiers::CTRL);
        assert_eq!(out.global().get(&q), Some(&Action::Save));
    }

    #[test]
    fn conflict_within_a_named_layer_is_reported() {
        // `ctrl+a` and `control+a` are the same chord spelled two ways; within one
        // layer that is a conflict, exactly as it is in the global layer.
        let toml = "\
[layers.panel]\n\"ctrl+a\" = \"quit\"\n\"control+a\" = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert_eq!(
            out.warnings,
            vec![Warning::Conflict {
                chord: "ctrl+a".to_string(),
                contenders: vec!["save".to_string(), "quit".to_string()],
                winner: "quit".to_string(),
            }]
        );
    }

    #[test]
    fn cross_shadow_is_checked_against_global_only() {
        // A chord `j` lives in `panel`, while the (global) sequence `j k` lives in
        // the global config. Because sequences are global and cross-shadow is a
        // global-layer-only check, the panel chord is *not* flagged.
        let toml = "\
[layers.panel]\n\"j\" = \"top\"\n\
[[sequences]]\nkeys = [\"j\", \"k\"]\naction = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert!(
            out.warnings.is_empty(),
            "a non-global chord must not cross-shadow a global sequence: {:?}",
            out.warnings
        );
    }

    #[test]
    fn unknown_action_in_a_named_layer_is_a_warning_carrying_no_layer_name() {
        // A named layer goes through the same pipeline as global, so an unknown
        // action there is a `UnknownAction` warning (binding skipped, not fatal).
        // By design the warning names the chord, not the layer.
        let toml = "[layers.panel]\n\"ctrl+z\" = \"undo\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert_eq!(
            out.warnings,
            vec![Warning::UnknownAction {
                key: "ctrl+z".to_string(),
                action: "undo".to_string(),
            }]
        );
        assert!(out.layers["panel"].is_empty());
    }

    #[test]
    fn malformed_key_in_a_named_layer_is_a_fatal_error() {
        // Parse failures are fatal in any layer, not just `[keys]`.
        let toml = "[layers.panel]\n\"ctrl+nope\" = \"quit\"\n";
        let err = from_str(toml, resolver).unwrap_err();
        assert!(matches!(err, BuildError::KeyParse { .. }));
    }

    #[test]
    fn sequences_do_not_create_extra_layers() {
        // A global-only config with sequences must still yield exactly the global
        // layer — sequences live beside the layers, not as one.
        let toml = "\
[keys]\n\"ctrl+q\" = \"quit\"\n\
[[sequences]]\nkeys = [\"ctrl+x\", \"ctrl+s\"]\naction = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert!(out.warnings.is_empty());
        assert_eq!(out.layers.keys().collect::<Vec<_>>(), vec![GLOBAL_LAYER]);
        assert!(!out.sequences.is_empty());
    }

    #[test]
    fn unknown_actions_across_layers_warn_global_first_then_name_order() {
        // Warning order is deterministic: global first, then named layers in
        // `BTreeMap` (lexicographic) name order.
        let toml = "\
[keys]\n\"a\" = \"nope_global\"\n\
[layers.zeta]\n\"b\" = \"nope_zeta\"\n\
[layers.alpha]\n\"c\" = \"nope_alpha\"\n";
        let out = from_str(toml, resolver).unwrap();
        let unknown_actions: Vec<&str> = out
            .warnings
            .iter()
            .filter_map(|w| match w {
                Warning::UnknownAction { action, .. } => Some(action.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(
            unknown_actions,
            vec!["nope_global", "nope_alpha", "nope_zeta"]
        );
    }

    #[test]
    fn unknown_top_level_field_is_a_fatal_error() {
        // `deny_unknown_fields`: a misspelled table is rejected, not ignored.
        let err = from_str("[kesy]\n\"ctrl+q\" = \"quit\"\n", resolver).unwrap_err();
        assert!(matches!(err, BuildError::Toml(_)));
    }

    #[test]
    fn unknown_sequence_field_is_a_fatal_error() {
        // Guards the future `layer = "..."` extension: an unsupported sequence
        // field fails loudly today rather than being silently dropped.
        let toml = "[[sequences]]\nkeys = [\"g\"]\naction = \"top\"\nlayer = \"panel\"\n";
        let err = from_str(toml, resolver).unwrap_err();
        assert!(matches!(err, BuildError::Toml(_)));
    }

    #[test]
    fn unknown_action_is_a_warning_not_a_failure() {
        let toml = "[keys]\n\"ctrl+q\" = \"quit\"\n\"ctrl+z\" = \"undo\"\n";
        let out = from_str(toml, resolver).unwrap();
        // The good binding still works.
        let q = KeyInput::new(Key::Char('q'), Modifiers::CTRL);
        assert_eq!(out.global().get(&q), Some(&Action::Quit));
        assert_eq!(
            out.warnings,
            vec![Warning::UnknownAction {
                key: "ctrl+z".to_string(),
                action: "undo".to_string(),
            }]
        );
    }

    #[test]
    fn distinct_spellings_of_same_chord_conflict() {
        // Different spellings of the same chord: "ctrl+a" and the alias
        // "control+a". (Note "ctrl+A" would be a *different* chord, since the
        // glyph case is significant by design.)
        let toml = "[keys]\n\"ctrl+a\" = \"quit\"\n\"control+a\" = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        let a = KeyInput::new(Key::Char('a'), Modifiers::CTRL);
        // One winner is bound for the shared chord.
        assert!(out.global().get(&a).is_some());
        let conflicts: Vec<_> = out
            .warnings
            .iter()
            .filter(|w| matches!(w, Warning::Conflict { .. }))
            .collect();
        assert_eq!(conflicts.len(), 1);
    }

    #[test]
    fn legacy_lints_are_opt_in_and_separate_from_warnings() {
        // `cmd+s` is a perfectly valid binding — the config is clean — but it
        // won't reach a legacy terminal. That is NOT a build warning; it surfaces
        // only when the caller opts in by calling `legacy_lints`.
        let toml = "[keys]\n\"cmd+s\" = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert!(out.warnings.is_empty());
        assert_eq!(
            keymap_core::legacy_lints(out.global()),
            vec![keymap_core::LegacyLint::Unrepresentable {
                chord: "super+s".to_string(),
            }]
        );
    }

    #[test]
    fn malformed_key_is_a_fatal_error() {
        let toml = "[keys]\n\"ctrl+nope\" = \"quit\"\n";
        let err = from_str(toml, resolver).unwrap_err();
        assert!(matches!(err, BuildError::KeyParse { .. }));
    }

    #[test]
    fn malformed_toml_is_a_fatal_error() {
        let err = from_str("this is not toml", resolver).unwrap_err();
        assert!(matches!(err, BuildError::Toml(_)));
    }

    #[test]
    fn empty_config_builds_empty_map() {
        let out: BuildOutput<Action> = from_str("", resolver).unwrap();
        assert!(out.global().is_empty());
        assert!(out.sequences.is_empty());
        assert!(out.warnings.is_empty());
    }

    #[test]
    fn builds_sequence_bindings() {
        let toml = "\
[keys]\n\"ctrl+q\" = \"quit\"\n\
[[sequences]]\nkeys = [\"ctrl+x\", \"ctrl+s\"]\naction = \"save\"\n\
[[sequences]]\nkeys = [\"ctrl+x\", \"ctrl+c\"]\naction = \"quit\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert!(out.warnings.is_empty());
        // Single chord still lands in the single-key map.
        let q = KeyInput::new(Key::Char('q'), Modifiers::CTRL);
        assert_eq!(out.global().get(&q), Some(&Action::Quit));
        // The sequence resolves; a partial buffer is a prefix.
        let save = seq(&[('x', Modifiers::CTRL), ('s', Modifiers::CTRL)]);
        assert_eq!(out.sequences.lookup(&save), Match::Exact(&Action::Save));
        assert_eq!(out.sequences.lookup(&save[..1]), Match::Prefix);
    }

    #[test]
    fn sequence_unknown_action_is_a_warning() {
        let toml = "[[sequences]]\nkeys = [\"ctrl+x\", \"ctrl+z\"]\naction = \"undo\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert!(out.sequences.is_empty());
        assert_eq!(
            out.warnings,
            vec![Warning::UnknownAction {
                key: "ctrl+x ctrl+z".to_string(),
                action: "undo".to_string(),
            }]
        );
    }

    #[test]
    fn sequence_prefix_shadow_is_a_warning_and_drops_the_later() {
        // `g` (top) then `g g` (split): the shorter shadows the longer.
        let toml = "\
[[sequences]]\nkeys = [\"g\"]\naction = \"top\"\n\
[[sequences]]\nkeys = [\"g\", \"g\"]\naction = \"split\"\n";
        let out = from_str(toml, resolver).unwrap();
        // The earlier (shorter) binding survives; the later is dropped.
        assert_eq!(
            out.sequences.lookup(&seq(&[('g', Modifiers::NONE)])),
            Match::Exact(&Action::Top)
        );
        assert_eq!(
            out.warnings,
            vec![Warning::PrefixShadow {
                prefix: vec!["g".to_string()],
                prefix_action: "top".to_string(),
                shadowed: vec!["g".to_string(), "g".to_string()],
                shadowed_action: "split".to_string(),
            }]
        );
    }

    #[test]
    fn sequence_prefix_shadow_reverse_order_drops_the_later_short_one() {
        // Longer bound first, then the shorter prefix arrives: the shorter is the
        // later binding and is dropped, but it is still labelled the `prefix`.
        let toml = "\
[[sequences]]\nkeys = [\"g\", \"g\"]\naction = \"split\"\n\
[[sequences]]\nkeys = [\"g\"]\naction = \"top\"\n";
        let out = from_str(toml, resolver).unwrap();
        // The earlier (longer) binding survives.
        assert_eq!(
            out.sequences
                .lookup(&seq(&[('g', Modifiers::NONE), ('g', Modifiers::NONE)])),
            Match::Exact(&Action::Split)
        );
        assert_eq!(
            out.warnings,
            vec![Warning::PrefixShadow {
                prefix: vec!["g".to_string()],
                prefix_action: "top".to_string(),
                shadowed: vec!["g".to_string(), "g".to_string()],
                shadowed_action: "split".to_string(),
            }]
        );
    }

    #[test]
    fn same_sequence_three_times_reports_pairwise_conflicts() {
        let toml = "\
[[sequences]]\nkeys = [\"ctrl+x\"]\naction = \"save\"\n\
[[sequences]]\nkeys = [\"ctrl+x\"]\naction = \"split\"\n\
[[sequences]]\nkeys = [\"ctrl+x\"]\naction = \"quit\"\n";
        let out = from_str(toml, resolver).unwrap();
        // Last one wins.
        assert_eq!(
            out.sequences.lookup(&seq(&[('x', Modifiers::CTRL)])),
            Match::Exact(&Action::Quit)
        );
        // Two pairwise conflicts, each naming the running winner vs the newcomer.
        assert_eq!(
            out.warnings,
            vec![
                Warning::Conflict {
                    chord: "ctrl+x".to_string(),
                    contenders: vec!["save".to_string(), "split".to_string()],
                    winner: "split".to_string(),
                },
                Warning::Conflict {
                    chord: "ctrl+x".to_string(),
                    contenders: vec!["split".to_string(), "quit".to_string()],
                    winner: "quit".to_string(),
                },
            ]
        );
    }

    #[test]
    fn empty_sequence_is_a_warning() {
        let toml = "[[sequences]]\nkeys = []\naction = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert!(out.sequences.is_empty());
        assert_eq!(
            out.warnings,
            vec![Warning::EmptySequence {
                action: "save".to_string(),
            }]
        );
    }

    #[test]
    fn duplicate_sequence_conflicts_and_last_wins() {
        let toml = "\
[[sequences]]\nkeys = [\"ctrl+x\", \"ctrl+s\"]\naction = \"save\"\n\
[[sequences]]\nkeys = [\"ctrl+x\", \"ctrl+s\"]\naction = \"split\"\n";
        let out = from_str(toml, resolver).unwrap();
        let s = seq(&[('x', Modifiers::CTRL), ('s', Modifiers::CTRL)]);
        assert_eq!(out.sequences.lookup(&s), Match::Exact(&Action::Split));
        assert_eq!(
            out.warnings,
            vec![Warning::Conflict {
                chord: "ctrl+x ctrl+s".to_string(),
                contenders: vec!["save".to_string(), "split".to_string()],
                winner: "split".to_string(),
            }]
        );
    }

    #[test]
    fn malformed_sequence_key_is_a_fatal_error() {
        let toml = "[[sequences]]\nkeys = [\"ctrl+x\", \"ctrl+nope\"]\naction = \"save\"\n";
        let err = from_str(toml, resolver).unwrap_err();
        assert!(matches!(err, BuildError::KeyParse { .. }));
    }

    #[test]
    fn single_chord_shadowing_a_sequence_is_an_advisory_warning() {
        // `j` (down) and a sequence `j j` (the vim `jj` case): pressing `j` is
        // ambiguous without a timeout. Both bindings are kept — only flagged.
        let toml = "\
[keys]\n\"j\" = \"top\"\n\
[[sequences]]\nkeys = [\"j\", \"k\"]\naction = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        // Nothing dropped: the chord resolves and the sequence resolves.
        assert_eq!(
            out.global()
                .get(&KeyInput::new(Key::Char('j'), Modifiers::NONE)),
            Some(&Action::Top)
        );
        assert_eq!(
            out.sequences
                .lookup(&seq(&[('j', Modifiers::NONE), ('k', Modifiers::NONE)])),
            Match::Exact(&Action::Save)
        );
        assert_eq!(
            out.warnings,
            vec![Warning::SequenceShadow {
                chord: "j".to_string(),
                chord_action: "top".to_string(),
                sequence: vec!["j".to_string(), "k".to_string()],
                sequence_action: "save".to_string(),
            }]
        );
    }

    #[test]
    fn length_one_sequence_equal_to_a_single_chord_shadows() {
        // A degenerate overlap: the single chord and a length-1 sequence are the
        // exact same key, bound in both maps.
        let toml = "\
[keys]\n\"q\" = \"quit\"\n\
[[sequences]]\nkeys = [\"q\"]\naction = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert_eq!(
            out.warnings,
            vec![Warning::SequenceShadow {
                chord: "q".to_string(),
                chord_action: "quit".to_string(),
                sequence: vec!["q".to_string()],
                sequence_action: "save".to_string(),
            }]
        );
    }

    #[test]
    fn disjoint_first_keys_do_not_shadow() {
        // `j` single, `g g` sequence: different first keys, no overlap.
        let toml = "\
[keys]\n\"j\" = \"top\"\n\
[[sequences]]\nkeys = [\"g\", \"g\"]\naction = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert!(out.warnings.is_empty());
    }

    #[test]
    fn one_chord_shadowing_several_sequences_reports_the_lex_first() {
        // `j` starts both `j k` and `j a`; one advisory names the lex-first (`j a`).
        let toml = "\
[keys]\n\"j\" = \"top\"\n\
[[sequences]]\nkeys = [\"j\", \"k\"]\naction = \"save\"\n\
[[sequences]]\nkeys = [\"j\", \"a\"]\naction = \"quit\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert_eq!(
            out.warnings,
            vec![Warning::SequenceShadow {
                chord: "j".to_string(),
                chord_action: "top".to_string(),
                sequence: vec!["j".to_string(), "a".to_string()],
                sequence_action: "quit".to_string(),
            }]
        );
    }

    #[test]
    fn multiple_shadowing_chords_emit_in_canonical_chord_order() {
        // `z` is declared before `j`, but warnings come out chord-sorted (`j`
        // before `z`) — pins the sort, which the HashMap source order would not
        // otherwise guarantee.
        let toml = "\
[keys]\n\"z\" = \"top\"\n\"j\" = \"quit\"\n\
[[sequences]]\nkeys = [\"z\", \"x\"]\naction = \"save\"\n\
[[sequences]]\nkeys = [\"j\", \"k\"]\naction = \"split\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert_eq!(
            out.warnings,
            vec![
                Warning::SequenceShadow {
                    chord: "j".to_string(),
                    chord_action: "quit".to_string(),
                    sequence: vec!["j".to_string(), "k".to_string()],
                    sequence_action: "split".to_string(),
                },
                Warning::SequenceShadow {
                    chord: "z".to_string(),
                    chord_action: "top".to_string(),
                    sequence: vec!["z".to_string(), "x".to_string()],
                    sequence_action: "save".to_string(),
                },
            ]
        );
    }

    #[test]
    fn unknown_single_chord_does_not_shadow() {
        // `j` resolves to nothing, so it never enters the keymap — it cannot
        // shadow. Only the UnknownAction warning fires, no SequenceShadow.
        let toml = "\
[keys]\n\"j\" = \"nonexistent\"\n\
[[sequences]]\nkeys = [\"j\", \"k\"]\naction = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert_eq!(
            out.warnings,
            vec![Warning::UnknownAction {
                key: "j".to_string(),
                action: "nonexistent".to_string(),
            }]
        );
    }

    #[test]
    fn cross_shadow_coexists_with_conflict_and_comes_last() {
        // A single-key Conflict and a SequenceShadow in one config: detection
        // appends after the key/sequence passes, so the shadow is emitted last.
        let toml = "\
[keys]\n\"ctrl+a\" = \"quit\"\n\"control+a\" = \"save\"\n\"j\" = \"top\"\n\
[[sequences]]\nkeys = [\"j\", \"k\"]\naction = \"split\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert_eq!(
            out.warnings,
            vec![
                // The `[keys]` table is a BTreeMap, so "control+a" (save) sorts
                // before "ctrl+a" (quit); save is the earlier contender, quit wins.
                Warning::Conflict {
                    chord: "ctrl+a".to_string(),
                    contenders: vec!["save".to_string(), "quit".to_string()],
                    winner: "quit".to_string(),
                },
                Warning::SequenceShadow {
                    chord: "j".to_string(),
                    chord_action: "top".to_string(),
                    sequence: vec!["j".to_string(), "k".to_string()],
                    sequence_action: "split".to_string(),
                },
            ]
        );
    }

    #[test]
    fn chord_matching_a_non_first_sequence_key_does_not_shadow() {
        // `j` is only the *second* key of `g j`; the predicate is `first() ==`,
        // not "contains", so this must not warn.
        let toml = "\
[keys]\n\"j\" = \"top\"\n\
[[sequences]]\nkeys = [\"g\", \"j\"]\naction = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert!(out.warnings.is_empty());
    }

    // --- to_toml round-trip ---
    //
    // These use `String` as the action type, so `name_of`/`resolve` are exact
    // inverses (`|a| Some(a)` / `|n| Some(n.to_owned())`) and any round-trip
    // failure is the serializer's, not the resolver's.

    fn km_pairs(km: &Keymap<String>) -> Vec<(KeyInput, String)> {
        let mut v: Vec<_> = km.iter().map(|(k, a)| (*k, a.clone())).collect();
        v.sort_by_key(|(k, _)| k.to_string());
        v
    }

    fn seq_pairs(s: &SequenceKeymap<String>) -> Vec<(Vec<KeyInput>, String)> {
        let mut v: Vec<_> = s.bindings().map(|(p, a)| (p, a.clone())).collect();
        v.sort_by_key(|(p, _)| render_sequence(p).join(" "));
        v
    }

    /// `to_toml` then `from_str` reproduces the same bindings.
    fn assert_round_trips(km: &Keymap<String>, seq: &SequenceKeymap<String>) {
        let toml = to_toml(km, seq, |a: &String| Some(a.as_str()));
        let out = from_str(&toml, |name: &str| Some(name.to_owned())).unwrap();
        assert!(
            out.warnings.is_empty(),
            "round-trip warned: {:?}",
            out.warnings
        );
        assert_eq!(km_pairs(km), km_pairs(out.global()));
        assert_eq!(seq_pairs(seq), seq_pairs(&out.sequences));
    }

    fn norm(key: Key, mods: Modifiers) -> KeyInput {
        KeyInput::normalized(key, mods)
    }

    #[test]
    fn to_toml_round_trips_keys_and_sequences() {
        let mut km = Keymap::new();
        km.bind(norm(Key::Char('q'), Modifiers::CTRL), "quit".to_owned());
        km.bind(norm(Key::Char('s'), Modifiers::CTRL), "save".to_owned());
        // Normalization fixed point: bare shift+letter folds to the letter, so it
        // emits as "a" and round-trips to the same normalized chord.
        km.bind(norm(Key::Char('a'), Modifiers::SHIFT), "all".to_owned());
        // Multi-modifier keeps shift: "ctrl+shift+a" survives as itself.
        km.bind(
            norm(Key::Char('a'), Modifiers::CTRL | Modifiers::SHIFT),
            "alt_all".to_owned(),
        );

        let mut seq = SequenceKeymap::new();
        seq.bind(
            [
                norm(Key::Char('x'), Modifiers::CTRL),
                norm(Key::Char('s'), Modifiers::CTRL),
            ],
            "seq_save".to_owned(),
        )
        .unwrap();
        seq.bind(
            [
                norm(Key::Char('g'), Modifiers::NONE),
                norm(Key::Char('g'), Modifiers::NONE),
            ],
            "top".to_owned(),
        )
        .unwrap();

        assert_round_trips(&km, &seq);
    }

    #[test]
    fn to_toml_is_deterministic_and_canonically_ordered() {
        let mut km = Keymap::new();
        km.bind(norm(Key::Char('z'), Modifiers::CTRL), "z".to_owned());
        km.bind(norm(Key::Char('a'), Modifiers::CTRL), "a".to_owned());
        let seq = SequenceKeymap::new();

        let first = to_toml(&km, &seq, |a: &String| Some(a.as_str()));
        let second = to_toml(&km, &seq, |a: &String| Some(a.as_str()));
        assert_eq!(first, second, "output must be deterministic");
        // Canonical chord order: "ctrl+a" before "ctrl+z" regardless of bind order.
        let a_at = first.find("ctrl+a").unwrap();
        let z_at = first.find("ctrl+z").unwrap();
        assert!(
            a_at < z_at,
            "keys must be emitted in canonical order:\n{first}"
        );
    }

    #[test]
    fn to_toml_omits_unnameable_bindings() {
        let mut km = Keymap::new();
        km.bind(norm(Key::Char('q'), Modifiers::CTRL), "quit".to_owned());
        km.bind(norm(Key::Char('x'), Modifiers::CTRL), "secret".to_owned());
        let seq = SequenceKeymap::new();

        // `name_of` declines to name "secret", so that binding is dropped.
        let toml = to_toml(&km, &seq, |a: &String| {
            (a != "secret").then_some(a.as_str())
        });
        let out = from_str(&toml, |name: &str| Some(name.to_owned())).unwrap();
        assert_eq!(
            out.global().get(&norm(Key::Char('q'), Modifiers::CTRL)),
            Some(&"quit".to_owned())
        );
        assert_eq!(
            out.global().get(&norm(Key::Char('x'), Modifiers::CTRL)),
            None
        );
    }

    #[test]
    fn to_toml_empty_maps_emit_empty_string() {
        let km: Keymap<String> = Keymap::new();
        let seq: SequenceKeymap<String> = SequenceKeymap::new();
        assert_eq!(to_toml(&km, &seq, |a: &String| Some(a.as_str())), "");
    }

    #[test]
    fn to_toml_round_trips_adversarial_names_and_chords() {
        // Action names with TOML metacharacters must not break out of their
        // string and inject bindings; emitting via `toml::Value` escapes them.
        let mut km = Keymap::new();
        km.bind(
            norm(Key::Char('a'), Modifiers::NONE),
            "quit\"; [injected]\nx = \"oops".to_owned(),
        );
        // Chords whose glyph collides with grammar/TOML punctuation.
        km.bind(norm(Key::Char('+'), Modifiers::NONE), "plus".to_owned());
        km.bind(norm(Key::Char(' '), Modifiers::NONE), "space".to_owned());
        km.bind(norm(Key::Char('"'), Modifiers::NONE), "quote".to_owned());
        km.bind(norm(Key::Char(''), Modifiers::NONE), "hira".to_owned());
        km.bind(norm(Key::Char('F'), Modifiers::NONE), "cap_f".to_owned());

        // Sequence starts with an unbound key (`z`) so it does not cross-shadow
        // the single-key ` `/`+` bindings; ` ` and `+` still appear as non-first
        // elements to exercise array-element round-tripping of odd glyphs.
        let mut seq = SequenceKeymap::new();
        seq.bind(
            [
                norm(Key::Char('z'), Modifiers::NONE),
                norm(Key::Char(' '), Modifiers::NONE),
                norm(Key::Char('+'), Modifiers::NONE),
            ],
            "z_space_plus".to_owned(),
        )
        .unwrap();

        assert_round_trips(&km, &seq);
    }

    #[test]
    fn shadow_matching_is_on_the_parsed_chord_not_the_label() {
        // Positive: `ctrl+x` single shadows `[ctrl+x, ctrl+s]`.
        let toml = "\
[keys]\n\"ctrl+x\" = \"top\"\n\
[[sequences]]\nkeys = [\"ctrl+x\", \"ctrl+s\"]\naction = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert_eq!(
            out.warnings,
            vec![Warning::SequenceShadow {
                chord: "ctrl+x".to_string(),
                chord_action: "top".to_string(),
                sequence: vec!["ctrl+x".to_string(), "ctrl+s".to_string()],
                sequence_action: "save".to_string(),
            }]
        );

        // Negative: a different modifier set is a different KeyInput, no shadow.
        let toml = "\
[keys]\n\"ctrl+x\" = \"top\"\n\
[[sequences]]\nkeys = [\"ctrl+shift+x\", \"ctrl+s\"]\naction = \"save\"\n";
        let out = from_str(toml, resolver).unwrap();
        assert!(out.warnings.is_empty());
    }

    #[test]
    fn to_toml_layered_round_trips_named_layers() {
        let mut global = Keymap::new();
        global.bind(norm(Key::Char('q'), Modifiers::CTRL), "quit".to_owned());
        let mut panel = Keymap::new();
        panel.bind(norm(Key::Char('s'), Modifiers::CTRL), "split".to_owned());
        // The same chord in two layers is preserved independently on round-trip.
        panel.bind(
            norm(Key::Char('q'), Modifiers::CTRL),
            "panel_quit".to_owned(),
        );

        let mut layers = BTreeMap::new();
        layers.insert(GLOBAL_LAYER.to_string(), global);
        layers.insert("panel".to_string(), panel);

        let mut seq = SequenceKeymap::new();
        seq.bind(
            [
                norm(Key::Char('x'), Modifiers::CTRL),
                norm(Key::Char('s'), Modifiers::CTRL),
            ],
            "seq_save".to_owned(),
        )
        .unwrap();

        let toml = to_toml_layered(&layers, &seq, |a: &String| Some(a.as_str()));
        let out = from_str(&toml, |name: &str| Some(name.to_owned())).unwrap();
        assert!(
            out.warnings.is_empty(),
            "round-trip warned: {:?}",
            out.warnings
        );
        assert_eq!(km_pairs(&layers["global"]), km_pairs(out.global()));
        assert_eq!(km_pairs(&layers["panel"]), km_pairs(&out.layers["panel"]));
        assert_eq!(seq_pairs(&seq), seq_pairs(&out.sequences));
    }

    #[test]
    fn to_toml_layered_matches_to_toml_for_a_global_only_set() {
        // A set with only the global layer must emit byte-identical output to
        // `to_toml` on that one keymap, so the two emitters cannot drift.
        let mut global = Keymap::new();
        global.bind(norm(Key::Char('q'), Modifiers::CTRL), "quit".to_owned());
        global.bind(norm(Key::Char('s'), Modifiers::CTRL), "save".to_owned());
        let mut seq = SequenceKeymap::new();
        seq.bind(
            [
                norm(Key::Char('g'), Modifiers::NONE),
                norm(Key::Char('g'), Modifiers::NONE),
            ],
            "top".to_owned(),
        )
        .unwrap();

        let mut layers = BTreeMap::new();
        layers.insert(GLOBAL_LAYER.to_string(), global.clone());

        let plain = to_toml(&global, &seq, |a: &String| Some(a.as_str()));
        let layered = to_toml_layered(&layers, &seq, |a: &String| Some(a.as_str()));
        assert_eq!(plain, layered);
        // And an empty global-only set emits the empty string, like `to_toml`.
        let empty: BTreeMap<String, Keymap<String>> = BTreeMap::new();
        assert_eq!(
            to_toml_layered(&empty, &SequenceKeymap::new(), |a: &String| Some(
                a.as_str()
            )),
            ""
        );
    }

    #[test]
    fn to_toml_layered_drops_empty_layers() {
        // An empty layer emits no table, so it does not survive a round-trip.
        // This is the deliberate asymmetry: `from_str` keeps a declared-but-empty
        // layer in the map, but `to_toml_layered` writes only layers with bindings.
        let mut global = Keymap::new();
        global.bind(norm(Key::Char('q'), Modifiers::CTRL), "quit".to_owned());
        let mut layers = BTreeMap::new();
        layers.insert(GLOBAL_LAYER.to_string(), global);
        layers.insert("panel".to_string(), Keymap::<String>::new());

        let toml = to_toml_layered(&layers, &SequenceKeymap::new(), |a: &String| {
            Some(a.as_str())
        });
        assert!(
            !toml.contains("panel"),
            "empty layer must not be emitted:\n{toml}"
        );
        let out = from_str(&toml, |name: &str| Some(name.to_owned())).unwrap();
        assert_eq!(out.layers.keys().collect::<Vec<_>>(), vec![GLOBAL_LAYER]);
    }
}