crossmap 0.12.4

A bidirectional crosswalk codec: one crosswalk document derives both directions between a dataset's native JSON shape and a shared target shape.
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
//! The crosswalk document: its types, and parsing a JSON value into one with every issue reported.
//!
//! Parsing checks each rule on its own (the syntax of every path, the fields each operation takes, that an `enum`'s
//! two maps are one bijection, that a template has a unique inverse); the properties of the rule list as a whole are
//! [`crate::validate_crosswalk`]'s. A `keep` path is read as the identity `move` from that path to itself, appended
//! after `rules` in the order listed, and a single-path rule that leaves out `to` has its `from` filled in, so a parsed
//! crosswalk holds only rules and every rule carries a `to`.

use std::sync::OnceLock;

use json_shape::{PathSegment, Value};

use crate::error::{CrossmapError, SyntaxIssue};
use crate::executor::Prepared;
use crate::js;
use crate::ops::template;
use crate::path::{PROTO, is_path};
use crate::when::When;

/// The direction a crosswalk runs in.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Direction {
    /// From the native shape to the shared shape.
    Encode,
    /// From the shared shape back to the native shape.
    Decode,
}

impl Direction {
    /// The direction's name in the format: `encode` or `decode`.
    pub fn name(self) -> &'static str {
        match self {
            Direction::Encode => "encode",
            Direction::Decode => "decode",
        }
    }
}

/// The textual forms `format` converts, each a bijection between its canonical text and a machine value.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FormatKind {
    /// An ISO-8601 date or timestamp and epoch milliseconds.
    IsoDateTime,
    /// A calendar date (`YYYY-MM-DD`) and the epoch milliseconds of its UTC midnight.
    IsoDate,
    /// A decimal number in text and the number.
    NumberText,
    /// `"true"` or `"false"` and the boolean.
    BooleanText,
    /// JSON text and the value it denotes.
    JsonText,
}

impl FormatKind {
    /// Every kind, in the order the format lists them.
    pub(crate) const ALL: [FormatKind; 5] = [
        FormatKind::IsoDateTime,
        FormatKind::IsoDate,
        FormatKind::NumberText,
        FormatKind::BooleanText,
        FormatKind::JsonText,
    ];

    /// The kind's name in the format.
    pub fn name(self) -> &'static str {
        match self {
            FormatKind::IsoDateTime => "isoDateTime",
            FormatKind::IsoDate => "isoDate",
            FormatKind::NumberText => "numberText",
            FormatKind::BooleanText => "booleanText",
            FormatKind::JsonText => "jsonText",
        }
    }
}

/// What an `aggregate` computes over the elements it reads.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AggregateFunction {
    /// How many elements there are.
    Count,
    /// The sum of their numbers.
    Sum,
    /// The smallest of their numbers.
    Min,
    /// The largest of their numbers.
    Max,
}

impl AggregateFunction {
    /// Every function, in the order the format lists them.
    pub(crate) const ALL: [AggregateFunction; 4] = [
        AggregateFunction::Count,
        AggregateFunction::Sum,
        AggregateFunction::Min,
        AggregateFunction::Max,
    ];

    /// The function's name in the format.
    pub fn name(self) -> &'static str {
        match self {
            AggregateFunction::Count => "count",
            AggregateFunction::Sum => "sum",
            AggregateFunction::Min => "min",
            AggregateFunction::Max => "max",
        }
    }
}

/// A field a rule may carry. Which fields each operation takes is [`TWO_WAY_SHAPES`]' and [`ONE_WAY_SHAPES`]'s, which
/// the parser refuses any other field by and the JSON Schema lists the properties of each rule from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Field {
    Op,
    From,
    To,
    When,
    Factor,
    Map,
    MapBack,
    Kind,
    Separator,
    Template,
    Direction,
    Value,
    Fn,
}

impl Field {
    /// The field's key in a rule.
    pub(crate) fn name(self) -> &'static str {
        match self {
            Field::Op => "op",
            Field::From => "from",
            Field::To => "to",
            Field::When => "when",
            Field::Factor => "factor",
            Field::Map => "map",
            Field::MapBack => "mapBack",
            Field::Kind => "kind",
            Field::Separator => "separator",
            Field::Template => "template",
            Field::Direction => "direction",
            Field::Value => "value",
            Field::Fn => "fn",
        }
    }
}

/// The fields of one operation's rule and which of them a rule may leave out.
pub(crate) struct RuleShape {
    /// The operation's name, the value of `op`.
    pub(crate) op: &'static str,
    /// Every field the rule may carry, in the order the format lists them.
    pub(crate) fields: &'static [Field],
    /// The fields of `fields` a rule may leave out: the gate, and `to` where parsing fills it in from `from`.
    pub(crate) optional: &'static [Field],
    /// The directions a one-way rule may run in; empty for a two-way rule.
    pub(crate) directions: &'static [Direction],
}

impl RuleShape {
    /// The names of the fields the rule may carry.
    pub(crate) fn field_names(&self) -> Vec<&'static str> {
        self.fields.iter().map(|field| field.name()).collect()
    }
}

/// The two-way operations, in the order the format lists them.
pub(crate) const TWO_WAY_SHAPES: [RuleShape; 7] = [
    RuleShape {
        op: "move",
        fields: &[Field::Op, Field::From, Field::To, Field::When],
        optional: &[Field::To, Field::When],
        directions: &[],
    },
    RuleShape {
        op: "scale",
        fields: &[
            Field::Op,
            Field::From,
            Field::To,
            Field::Factor,
            Field::When,
        ],
        optional: &[Field::To, Field::When],
        directions: &[],
    },
    RuleShape {
        op: "enum",
        fields: &[
            Field::Op,
            Field::From,
            Field::To,
            Field::Map,
            Field::MapBack,
            Field::When,
        ],
        optional: &[Field::To, Field::When],
        directions: &[],
    },
    RuleShape {
        op: "format",
        fields: &[Field::Op, Field::From, Field::To, Field::Kind, Field::When],
        optional: &[Field::To, Field::When],
        directions: &[],
    },
    RuleShape {
        op: "split",
        fields: &[
            Field::Op,
            Field::From,
            Field::To,
            Field::Separator,
            Field::When,
        ],
        optional: &[Field::To, Field::When],
        directions: &[],
    },
    RuleShape {
        op: "template",
        fields: &[
            Field::Op,
            Field::From,
            Field::To,
            Field::Template,
            Field::When,
        ],
        optional: &[Field::When],
        directions: &[],
    },
    RuleShape {
        op: "copy",
        fields: &[Field::Op, Field::From, Field::To, Field::When],
        optional: &[Field::When],
        directions: &[],
    },
];

/// The one-way operations, in the order the format lists them.
pub(crate) const ONE_WAY_SHAPES: [RuleShape; 3] = [
    RuleShape {
        op: "drop",
        fields: &[Field::Op, Field::From, Field::Direction, Field::When],
        optional: &[Field::When],
        directions: &[Direction::Encode],
    },
    RuleShape {
        op: "default",
        fields: &[
            Field::Op,
            Field::To,
            Field::Value,
            Field::Direction,
            Field::When,
        ],
        optional: &[Field::When],
        directions: &[Direction::Encode, Direction::Decode],
    },
    RuleShape {
        op: "aggregate",
        fields: &[
            Field::Op,
            Field::Fn,
            Field::From,
            Field::To,
            Field::Direction,
            Field::When,
        ],
        optional: &[Field::When],
        directions: &[Direction::Encode, Direction::Decode],
    },
];

/// The fields of a crosswalk document, in the order the format lists them.
pub(crate) const CROSSWALK_FIELDS: [&str; 6] =
    ["$schema", "source", "target", "rules", "keep", "oneWay"];

/// The shape of the operation named `op` among `shapes`.
fn shape_of<'s>(shapes: &'s [RuleShape], op: Option<&str>) -> Option<&'s RuleShape> {
    shapes.iter().find(|shape| Some(shape.op) == op)
}

/// The paths and gate of a rule with one path on each side.
#[derive(Clone, Debug, PartialEq)]
pub struct SinglePath {
    /// The native-side path.
    pub from: String,
    /// The shared-side path.
    pub to: String,
    /// The rule's gate.
    pub when: Option<When>,
}

/// A two-way rule: both directions derive from it.
#[derive(Clone, Debug, PartialEq)]
pub enum TwoWayRule {
    /// Carries any JSON value across unchanged.
    Move(SinglePath),
    /// Multiplies by `factor` while encoding and divides by it while decoding.
    Scale {
        /// The paths and gate.
        path: SinglePath,
        /// A finite, non-zero factor.
        factor: f64,
    },
    /// Maps text through `map` while encoding and through its inverse `map_back` while decoding.
    Enum {
        /// The paths and gate.
        path: SinglePath,
        /// The encode mapping, injective.
        map: Vec<(String, String)>,
        /// Exactly the inverse of `map`.
        map_back: Vec<(String, String)>,
    },
    /// Parses a textual form while encoding and renders its canonical text while decoding.
    Format {
        /// The paths and gate.
        path: SinglePath,
        /// The textual form.
        kind: FormatKind,
    },
    /// Cuts text at every separator while encoding and joins the parts while decoding.
    Split {
        /// The paths and gate.
        path: SinglePath,
        /// A non-empty separator.
        separator: String,
    },
    /// Renders several fields into one text while encoding and splits them back out while decoding.
    Template {
        /// Each placeholder name with the path of its field, in the order a JavaScript object lists the names.
        from: Vec<(String, String)>,
        /// The path of the rendered text.
        to: String,
        /// The template text.
        template: String,
        /// The rule's gate.
        when: Option<When>,
    },
    /// Writes one value to several places while encoding, and requires the copies to agree while decoding.
    Copy {
        /// The path of the value.
        from: String,
        /// Two or more paths of the copies.
        to: Vec<String>,
        /// The rule's gate.
        when: Option<When>,
    },
}

impl TwoWayRule {
    /// The operation's name in the format.
    pub fn op(&self) -> &'static str {
        match self {
            TwoWayRule::Move(_) => "move",
            TwoWayRule::Scale { .. } => "scale",
            TwoWayRule::Enum { .. } => "enum",
            TwoWayRule::Format { .. } => "format",
            TwoWayRule::Split { .. } => "split",
            TwoWayRule::Template { .. } => "template",
            TwoWayRule::Copy { .. } => "copy",
        }
    }

    /// The rule's gate.
    pub fn when(&self) -> Option<&When> {
        match self {
            TwoWayRule::Move(path)
            | TwoWayRule::Scale { path, .. }
            | TwoWayRule::Enum { path, .. }
            | TwoWayRule::Format { path, .. }
            | TwoWayRule::Split { path, .. } => path.when.as_ref(),
            TwoWayRule::Template { when, .. } | TwoWayRule::Copy { when, .. } => when.as_ref(),
        }
    }
}

/// The paths a two-way rule reads and writes, in the order its operation takes and produces values: encode reads
/// `from` and writes `to`, decode the reverse. Each list is non-empty.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RuleSides {
    /// The native-side paths.
    pub from: Vec<String>,
    /// The shared-side paths.
    pub to: Vec<String>,
}

/// The sides of a two-way rule: a template reads its fields in its `from` record's order, a copy writes several
/// targets, and every other rule has one path on each side.
pub fn rule_sides(rule: &TwoWayRule) -> RuleSides {
    match rule {
        TwoWayRule::Template { from, to, .. } => RuleSides {
            from: from.iter().map(|(_, path)| path.clone()).collect(),
            to: vec![to.clone()],
        },
        TwoWayRule::Copy { from, to, .. } => RuleSides {
            from: vec![from.clone()],
            to: to.clone(),
        },
        TwoWayRule::Move(path)
        | TwoWayRule::Scale { path, .. }
        | TwoWayRule::Enum { path, .. }
        | TwoWayRule::Format { path, .. }
        | TwoWayRule::Split { path, .. } => RuleSides {
            from: vec![path.from.clone()],
            to: vec![path.to.clone()],
        },
    }
}

/// A one-way rule: explicitly lossy, applying in one direction.
#[derive(Clone, Debug, PartialEq)]
pub enum OneWayRule {
    /// Declares that `from` is deliberately not carried across while encoding.
    Drop {
        /// The native-side path left behind.
        from: String,
        /// The rule's gate.
        when: Option<When>,
    },
    /// Inserts `value` at `to` while running in `direction`, when `to` is still absent from the output.
    Default {
        /// The wildcard-free path of the value.
        to: String,
        /// The value.
        value: Value,
        /// The direction it applies in.
        direction: Direction,
        /// The rule's gate.
        when: Option<When>,
    },
    /// Writes the count, sum, minimum or maximum of the elements `from` reaches, grouped at the wildcards `to` keeps.
    Aggregate {
        /// The function.
        function: AggregateFunction,
        /// The path of the elements.
        from: String,
        /// The path of the results, with fewer wildcards than `from`.
        to: String,
        /// The direction it applies in.
        direction: Direction,
        /// The rule's gate.
        when: Option<When>,
    },
}

impl OneWayRule {
    /// The rule's gate.
    pub fn when(&self) -> Option<&When> {
        match self {
            OneWayRule::Drop { when, .. }
            | OneWayRule::Default { when, .. }
            | OneWayRule::Aggregate { when, .. } => when.as_ref(),
        }
    }
}

/// A parsed crosswalk. It is built only by [`parse_crosswalk`] and cannot be changed afterwards, so the prepared form
/// the executor builds the first time it is used stays the crosswalk's own.
#[derive(Clone, Debug)]
pub struct Crosswalk {
    schema: Option<String>,
    source: String,
    target: String,
    rules: Vec<TwoWayRule>,
    one_way: Vec<OneWayRule>,
    pub(crate) prepared: OnceLock<Result<Prepared, CrossmapError>>,
}

impl PartialEq for Crosswalk {
    fn eq(&self, other: &Self) -> bool {
        self.schema == other.schema
            && self.source == other.source
            && self.target == other.target
            && self.rules == other.rules
            && self.one_way == other.one_way
    }
}

impl Crosswalk {
    /// The address of the JSON Schema the document declares itself written against. It has no part in encoding,
    /// decoding or validation.
    pub fn schema(&self) -> Option<&str> {
        self.schema.as_deref()
    }

    /// The label of the native shape.
    pub fn source(&self) -> &str {
        &self.source
    }

    /// The label of the shared shape.
    pub fn target(&self) -> &str {
        &self.target
    }

    /// The two-way rules, kept paths included as the moves they stand for.
    pub fn rules(&self) -> &[TwoWayRule] {
        &self.rules
    }

    /// The one-way rules.
    pub fn one_way(&self) -> &[OneWayRule] {
        &self.one_way
    }

    /// The parsed crosswalk as a JSON document: defaults filled in, kept paths as moves, every `to` present.
    pub fn to_value(&self) -> Value {
        let mut pairs = Vec::new();
        if let Some(schema) = &self.schema {
            pairs.push(("$schema".to_owned(), text(schema)));
        }
        pairs.push(("source".to_owned(), text(&self.source)));
        pairs.push(("target".to_owned(), text(&self.target)));
        pairs.push((
            "rules".to_owned(),
            Value::Array(self.rules.iter().map(two_way_value).collect()),
        ));
        pairs.push((
            "oneWay".to_owned(),
            Value::Array(self.one_way.iter().map(one_way_value).collect()),
        ));
        Value::Object(pairs)
    }
}

impl serde::Serialize for Crosswalk {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.to_value().serialize(serializer)
    }
}

impl<'de> serde::Deserialize<'de> for Crosswalk {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = Value::deserialize(deserializer)?;
        parse_crosswalk(&value).map_err(serde::de::Error::custom)
    }
}

fn text(value: &str) -> Value {
    Value::String(value.to_owned())
}

fn record(pairs: &[(String, String)]) -> Value {
    Value::Object(
        pairs
            .iter()
            .map(|(key, value)| (key.clone(), text(value)))
            .collect(),
    )
}

fn with_when(mut pairs: Vec<(String, Value)>, when: Option<&When>) -> Value {
    if let Some(when) = when {
        pairs.push(("when".to_owned(), when.json().clone()));
    }
    Value::Object(pairs)
}

fn single(op: &str, path: &SinglePath, extra: Vec<(String, Value)>) -> Value {
    let mut pairs = vec![
        ("op".to_owned(), text(op)),
        ("from".to_owned(), text(&path.from)),
        ("to".to_owned(), text(&path.to)),
    ];
    pairs.extend(extra);
    with_when(pairs, path.when.as_ref())
}

fn two_way_value(rule: &TwoWayRule) -> Value {
    match rule {
        TwoWayRule::Move(path) => single("move", path, Vec::new()),
        TwoWayRule::Scale { path, factor } => single(
            "scale",
            path,
            vec![("factor".to_owned(), Value::Number(*factor))],
        ),
        TwoWayRule::Enum {
            path,
            map,
            map_back,
        } => single(
            "enum",
            path,
            vec![
                ("map".to_owned(), record(map)),
                ("mapBack".to_owned(), record(map_back)),
            ],
        ),
        TwoWayRule::Format { path, kind } => {
            single("format", path, vec![("kind".to_owned(), text(kind.name()))])
        }
        TwoWayRule::Split { path, separator } => single(
            "split",
            path,
            vec![("separator".to_owned(), text(separator))],
        ),
        TwoWayRule::Template {
            from,
            to,
            template,
            when,
        } => with_when(
            vec![
                ("op".to_owned(), text("template")),
                ("from".to_owned(), record(from)),
                ("to".to_owned(), text(to)),
                ("template".to_owned(), text(template)),
            ],
            when.as_ref(),
        ),
        TwoWayRule::Copy { from, to, when } => with_when(
            vec![
                ("op".to_owned(), text("copy")),
                ("from".to_owned(), text(from)),
                (
                    "to".to_owned(),
                    Value::Array(to.iter().map(|path| text(path)).collect()),
                ),
            ],
            when.as_ref(),
        ),
    }
}

fn one_way_value(rule: &OneWayRule) -> Value {
    match rule {
        OneWayRule::Drop { from, when } => with_when(
            vec![
                ("op".to_owned(), text("drop")),
                ("from".to_owned(), text(from)),
                ("direction".to_owned(), text("encode")),
            ],
            when.as_ref(),
        ),
        OneWayRule::Default {
            to,
            value,
            direction,
            when,
        } => with_when(
            vec![
                ("op".to_owned(), text("default")),
                ("to".to_owned(), text(to)),
                ("value".to_owned(), value.clone()),
                ("direction".to_owned(), text(direction.name())),
            ],
            when.as_ref(),
        ),
        OneWayRule::Aggregate {
            function,
            from,
            to,
            direction,
            when,
        } => with_when(
            vec![
                ("op".to_owned(), text("aggregate")),
                ("fn".to_owned(), text(function.name())),
                ("from".to_owned(), text(from)),
                ("to".to_owned(), text(to)),
                ("direction".to_owned(), text(direction.name())),
            ],
            when.as_ref(),
        ),
    }
}

/// The message of a path field that is not a well-formed path.
const PATH_MESSAGE: &str = "not a well-formed path (a key, then any of '.key', '[\"quoted key\"]', '[n]' or '[]'; bare keys are [A-Za-z0-9_-]+, and no key may be __proto__)";

/// Collects the issues of one parse, each prefixed with the dotted path of its field.
struct Reader {
    issues: Vec<SyntaxIssue>,
}

/// A location in the document being parsed.
#[derive(Clone)]
struct At(Vec<String>);

impl At {
    fn key(&self, key: &str) -> At {
        let mut path = self.0.clone();
        path.push(key.to_owned());
        At(path)
    }

    fn index(&self, index: usize) -> At {
        self.key(&index.to_string())
    }

    fn text(&self) -> String {
        if self.0.is_empty() {
            "(root)".to_owned()
        } else {
            self.0.join(".")
        }
    }
}

fn kind_name(value: Option<&Value>) -> &'static str {
    match value {
        None => "undefined",
        Some(Value::Null) => "null",
        Some(Value::Bool(_)) => "boolean",
        Some(Value::Number(_)) => "number",
        Some(Value::String(_)) => "string",
        Some(Value::Array(_)) => "array",
        Some(Value::Object(_)) => "object",
    }
}

impl Reader {
    fn issue(&mut self, at: &At, message: impl AsRef<str>) {
        self.issues.push(SyntaxIssue {
            message: format!("{}: {}", at.text(), message.as_ref()),
        });
    }

    fn expected(&mut self, at: &At, expected: &str, found: Option<&Value>) {
        self.issue(
            at,
            format!(
                "Invalid input: expected {expected}, received {}",
                kind_name(found)
            ),
        );
    }

    /// The members of a record, or `None` with an issue when the value is not one.
    fn object<'v>(&mut self, at: &At, value: &'v Value) -> Option<&'v [(String, Value)]> {
        match value {
            Value::Object(pairs) => Some(pairs),
            other => {
                self.expected(at, "object", Some(other));
                None
            }
        }
    }

    /// Reports every key of a record that is not among `known`.
    fn strict(&mut self, at: &At, pairs: &[(String, Value)], known: &[&str]) {
        let unknown: Vec<String> = js::ordered_pairs(pairs)
            .into_iter()
            .filter(|(key, _)| !known.contains(&key.as_str()))
            .map(|(key, _)| js::quote(key))
            .collect();
        match unknown.len() {
            0 => {}
            1 => self.issue(at, format!("Unrecognized key: {}", unknown.join(", "))),
            _ => self.issue(at, format!("Unrecognized keys: {}", unknown.join(", "))),
        }
    }

    fn string(&mut self, at: &At, value: Option<&Value>) -> Option<String> {
        match value {
            Some(Value::String(text)) => Some(text.clone()),
            other => {
                self.expected(at, "string", other);
                None
            }
        }
    }

    fn path(&mut self, at: &At, value: Option<&Value>) -> Option<String> {
        let path = self.string(at, value)?;
        if is_path(&path) {
            Some(path)
        } else {
            self.issue(at, PATH_MESSAGE);
            None
        }
    }

    /// An optional path field: `Some(None)` when absent, `None` when present and invalid.
    fn optional_path(&mut self, at: &At, value: Option<&Value>) -> Option<Option<String>> {
        match value {
            None => Some(None),
            present => self.path(at, present).map(Some),
        }
    }

    fn when(&mut self, at: &At, value: Option<&Value>) -> Option<Option<When>> {
        let Some(value) = value else {
            return Some(None);
        };
        match When::read(value) {
            Ok(when) => Some(Some(when)),
            Err(issues) => {
                for issue in issues {
                    let mut place = at.clone();
                    for segment in &issue.path {
                        place = match segment {
                            PathSegment::Key(key) => place.key(key),
                            PathSegment::Index(index) => place.index(*index),
                        };
                    }
                    self.issue(&place, &issue.message);
                }
                None
            }
        }
    }

    fn string_record(&mut self, at: &At, value: Option<&Value>) -> Option<Vec<(String, String)>> {
        let pairs = match value {
            Some(Value::Object(pairs)) => pairs,
            other => {
                self.expected(at, "record", other);
                return None;
            }
        };
        let mut read = Vec::new();
        let mut sound = true;
        for (key, member) in js::ordered_pairs(pairs) {
            match self.string(&at.key(key), Some(member)) {
                Some(text) => read.push((key.clone(), text)),
                None => sound = false,
            }
        }
        sound.then_some(read)
    }

    fn direction(
        &mut self,
        at: &At,
        value: Option<&Value>,
        allowed: &[Direction],
    ) -> Option<Direction> {
        let found = allowed
            .iter()
            .copied()
            .find(|direction| value == Some(&Value::String(direction.name().to_owned())));
        if found.is_none() {
            let names: Vec<String> = allowed
                .iter()
                .map(|direction| js::quote(direction.name()))
                .collect();
            if names.len() == 1 {
                self.issue(at, format!("Invalid input: expected {}", names.join("")));
            } else {
                self.issue(
                    at,
                    format!("Invalid option: expected one of {}", names.join("|")),
                );
            }
        }
        found
    }

    fn two_way(&mut self, at: &At, value: &Value) -> Option<TwoWayRule> {
        let pairs = self.object(at, value)?;
        let get = |key: &str| member(pairs, key);
        let op = get("op").and_then(Value::as_str);
        let Some(shape) = shape_of(&TWO_WAY_SHAPES, op) else {
            self.issue(
                &at.key("op"),
                "Invalid input: expected one of \"move\"|\"scale\"|\"enum\"|\"format\"|\"split\"|\"template\"|\"copy\"",
            );
            return None;
        };
        let before = self.issues.len();
        let rule = match op {
            Some("template") => self.template(at, pairs),
            Some("copy") => self.copy(at, pairs),
            Some(single_op) => self.single(at, single_op, pairs),
            None => None,
        };
        self.strict(at, pairs, &shape.field_names());
        rule.filter(|_| self.issues.len() == before)
    }

    fn single(&mut self, at: &At, op: &str, pairs: &[(String, Value)]) -> Option<TwoWayRule> {
        let get = |key: &str| member(pairs, key);
        let from = self.path(&at.key("from"), get("from"));
        let to = self.optional_path(&at.key("to"), get("to"));
        let when = self.when(&at.key("when"), get("when"));
        let rule = match op {
            "move" => Some(Rest::Move),
            "scale" => self
                .factor(&at.key("factor"), get("factor"))
                .map(Rest::Scale),
            "enum" => {
                let map = self.string_record(&at.key("map"), get("map"));
                let map_back = self.string_record(&at.key("mapBack"), get("mapBack"));
                match (map, map_back) {
                    (Some(map), Some(map_back)) => Some(Rest::Enum(map, map_back)),
                    _ => None,
                }
            }
            "format" => self
                .format_kind(&at.key("kind"), get("kind"))
                .map(Rest::Format),
            "split" => self
                .separator(&at.key("separator"), get("separator"))
                .map(Rest::Split),
            _ => None,
        };
        let (from, to, when, rest) = (from?, to?, when?, rule?);
        let path = SinglePath {
            to: to.unwrap_or_else(|| from.clone()),
            from,
            when,
        };
        Some(match rest {
            Rest::Move => TwoWayRule::Move(path),
            Rest::Scale(factor) => TwoWayRule::Scale { path, factor },
            Rest::Enum(map, map_back) => {
                if !self.bijection(at, &map, &map_back) {
                    return None;
                }
                TwoWayRule::Enum {
                    path,
                    map,
                    map_back,
                }
            }
            Rest::Format(kind) => TwoWayRule::Format { path, kind },
            Rest::Split(separator) => TwoWayRule::Split { path, separator },
        })
    }

    fn factor(&mut self, at: &At, value: Option<&Value>) -> Option<f64> {
        match value {
            Some(Value::Number(factor)) if factor.is_finite() && *factor != 0.0 => Some(*factor),
            Some(Value::Number(_)) => {
                self.issue(
                    at,
                    "factor must be a finite non-zero number: decode divides by it",
                );
                None
            }
            other => {
                self.expected(at, "number", other);
                None
            }
        }
    }

    fn format_kind(&mut self, at: &At, value: Option<&Value>) -> Option<FormatKind> {
        let found = FormatKind::ALL
            .into_iter()
            .find(|kind| value.and_then(Value::as_str) == Some(kind.name()));
        if found.is_none() {
            let names: Vec<String> = FormatKind::ALL
                .iter()
                .map(|kind| js::quote(kind.name()))
                .collect();
            self.issue(
                at,
                format!("Invalid option: expected one of {}", names.join("|")),
            );
        }
        found
    }

    fn separator(&mut self, at: &At, value: Option<&Value>) -> Option<String> {
        let separator = self.string(at, value)?;
        if separator.is_empty() {
            self.issue(
                at,
                "separator must be non-empty: an empty separator makes decode's join ambiguous",
            );
            return None;
        }
        Some(separator)
    }

    /// Checks that `map_back` is exactly the inverse of an injective `map`.
    fn bijection(
        &mut self,
        at: &At,
        map: &[(String, String)],
        map_back: &[(String, String)],
    ) -> bool {
        let before = self.issues.len();
        let mut image: Vec<&str> = map.iter().map(|(_, to)| to.as_str()).collect();
        image.sort_unstable();
        image.dedup();
        if image.len() != map.len() {
            self.issue(
                &at.key("map"),
                "map must be injective: two keys mapping to one value have no inverse",
            );
        }
        if map_back.len() != image.len() {
            self.issue(
                &at.key("mapBack"),
                "mapBack must hold exactly the image of map: an entry map never produces, or a produced value it lacks, has no inverse",
            );
        }
        for (from, to) in map {
            let back = map_back
                .iter()
                .find(|(key, _)| key == to)
                .map(|(_, value)| value);
            if back != Some(from) {
                self.issue(
                    &at.key("mapBack"),
                    format!("mapBack must invert map: map sends {from} to {to} but mapBack does not send {to} back to {from}"),
                );
            }
        }
        self.issues.len() == before
    }

    fn template(&mut self, at: &At, pairs: &[(String, Value)]) -> Option<TwoWayRule> {
        let get = |key: &str| member(pairs, key);
        let from_at = at.key("from");
        let from = match get("from") {
            Some(Value::Object(pairs)) => {
                let mut read = Vec::new();
                let mut sound = true;
                for (name, path) in js::ordered_pairs(pairs) {
                    if !template::is_placeholder_name(name) {
                        self.issue(
                            &from_at.key(name),
                            "a template field name is [A-Za-z0-9_]+ other than __proto__",
                        );
                        sound = false;
                    }
                    match self.path(&from_at.key(name), Some(path)) {
                        Some(path) => read.push((name.clone(), path)),
                        None => sound = false,
                    }
                }
                sound.then_some(read)
            }
            other => {
                self.expected(&from_at, "record", other);
                None
            }
        };
        let to = self.path(&at.key("to"), get("to"));
        let text = self.string(&at.key("template"), get("template"));
        let when = self.when(&at.key("when"), get("when"));
        let (from, to, text, when) = (from?, to?, text?, when?);
        let names: Vec<&str> = from.iter().map(|(name, _)| name.as_str()).collect();
        let problems = match template::parse(&text) {
            Ok(pieces) => template::problems(&pieces, &names),
            Err(message) => vec![message],
        };
        if !problems.is_empty() {
            for problem in problems {
                self.issue(&at.key("template"), problem);
            }
            return None;
        }
        Some(TwoWayRule::Template {
            from,
            to,
            template: text,
            when,
        })
    }

    fn copy(&mut self, at: &At, pairs: &[(String, Value)]) -> Option<TwoWayRule> {
        let get = |key: &str| member(pairs, key);
        let from = self.path(&at.key("from"), get("from"));
        let to_at = at.key("to");
        let to = match get("to") {
            Some(Value::Array(items)) => {
                let mut read = Vec::new();
                let mut sound = true;
                for (index, item) in items.iter().enumerate() {
                    match self.path(&to_at.index(index), Some(item)) {
                        Some(path) => read.push(path),
                        None => sound = false,
                    }
                }
                if items.len() < 2 {
                    self.issue(&to_at, "a copy writes at least two paths: one is a move");
                    sound = false;
                }
                sound.then_some(read)
            }
            other => {
                self.expected(&to_at, "array", other);
                None
            }
        };
        let when = self.when(&at.key("when"), get("when"));
        Some(TwoWayRule::Copy {
            from: from?,
            to: to?,
            when: when?,
        })
    }

    fn one_way(&mut self, at: &At, value: &Value) -> Option<OneWayRule> {
        let pairs = self.object(at, value)?;
        let get = |key: &str| member(pairs, key);
        let before = self.issues.len();
        let Some(shape) = shape_of(&ONE_WAY_SHAPES, get("op").and_then(Value::as_str)) else {
            self.issue(
                &at.key("op"),
                "Invalid input: expected one of \"drop\"|\"default\"|\"aggregate\"",
            );
            return None;
        };
        let rule = match shape.op {
            "drop" => {
                let from = self.path(&at.key("from"), get("from"));
                let direction =
                    self.direction(&at.key("direction"), get("direction"), shape.directions);
                let when = self.when(&at.key("when"), get("when"));
                match (from, direction, when) {
                    (Some(from), Some(_), Some(when)) => Some(OneWayRule::Drop { from, when }),
                    _ => None,
                }
            }
            "default" => {
                let to = self.path(&at.key("to"), get("to"));
                let value = match get("value") {
                    Some(value) => Some(without_prototype_keys(value)),
                    None => {
                        self.issue(
                            &at.key("value"),
                            "Invalid input: expected JSON value, received undefined",
                        );
                        None
                    }
                };
                let direction =
                    self.direction(&at.key("direction"), get("direction"), shape.directions);
                let when = self.when(&at.key("when"), get("when"));
                match (to, value, direction, when) {
                    (Some(to), Some(value), Some(direction), Some(when)) => {
                        Some(OneWayRule::Default {
                            to,
                            value,
                            direction,
                            when,
                        })
                    }
                    _ => None,
                }
            }
            "aggregate" => {
                let function = AggregateFunction::ALL
                    .into_iter()
                    .find(|function| get("fn").and_then(Value::as_str) == Some(function.name()));
                if function.is_none() {
                    self.issue(
                        &at.key("fn"),
                        "Invalid option: expected one of \"count\"|\"sum\"|\"min\"|\"max\"",
                    );
                }
                let from = self.path(&at.key("from"), get("from"));
                let to = self.path(&at.key("to"), get("to"));
                let direction =
                    self.direction(&at.key("direction"), get("direction"), shape.directions);
                let when = self.when(&at.key("when"), get("when"));
                match (function, from, to, direction, when) {
                    (Some(function), Some(from), Some(to), Some(direction), Some(when)) => {
                        Some(OneWayRule::Aggregate {
                            function,
                            from,
                            to,
                            direction,
                            when,
                        })
                    }
                    _ => None,
                }
            }
            _ => None,
        };
        self.strict(at, pairs, &shape.field_names());
        rule.filter(|_| self.issues.len() == before)
    }
}

/// The member of a record under `key`.
fn member<'v>(pairs: &'v [(String, Value)], key: &str) -> Option<&'v Value> {
    pairs
        .iter()
        .find(|(name, _)| name == key)
        .map(|(_, member)| member)
}

/// The two-way rule's fields beyond its paths and gate, read before the rule is assembled.
enum Rest {
    Move,
    Scale(f64),
    Enum(Vec<(String, String)>, Vec<(String, String)>),
    Format(FormatKind),
    Split(String),
}

/// A JSON value with every `__proto__` key removed, as trilean's JSON value schema reads a value.
fn without_prototype_keys(value: &Value) -> Value {
    match value {
        Value::Array(items) => Value::Array(items.iter().map(without_prototype_keys).collect()),
        Value::Object(pairs) => Value::Object(
            pairs
                .iter()
                .filter(|(key, _)| key != PROTO)
                .map(|(key, member)| (key.clone(), without_prototype_keys(member)))
                .collect(),
        ),
        other => other.clone(),
    }
}

/// Parses a JSON value as a crosswalk document.
///
/// # Errors
///
/// [`CrossmapError::Syntax`] carrying every issue found, not just the first.
pub fn parse_crosswalk(document: &Value) -> Result<Crosswalk, CrossmapError> {
    let mut reader = Reader { issues: Vec::new() };
    let root = At(Vec::new());
    let Some(pairs) = reader.object(&root, document) else {
        return Err(CrossmapError::Syntax {
            issues: reader.issues,
        });
    };
    let get = |key: &str| member(pairs, key);
    let schema = match get("$schema") {
        None => None,
        present => reader.string(&root.key("$schema"), present),
    };
    let source = reader.string(&root.key("source"), get("source"));
    let target = reader.string(&root.key("target"), get("target"));
    let mut rules = Vec::new();
    match get("rules") {
        None => {}
        Some(Value::Array(items)) => {
            for (index, item) in items.iter().enumerate() {
                if let Some(rule) = reader.two_way(&root.key("rules").index(index), item) {
                    rules.push(rule);
                }
            }
        }
        Some(other) => reader.expected(&root.key("rules"), "array", Some(other)),
    }
    match get("keep") {
        None => {}
        Some(Value::Array(items)) => {
            for (index, item) in items.iter().enumerate() {
                if let Some(path) = reader.path(&root.key("keep").index(index), Some(item)) {
                    rules.push(TwoWayRule::Move(SinglePath {
                        from: path.clone(),
                        to: path,
                        when: None,
                    }));
                }
            }
        }
        Some(other) => reader.expected(&root.key("keep"), "array", Some(other)),
    }
    let mut one_way = Vec::new();
    match get("oneWay") {
        None => {}
        Some(Value::Array(items)) => {
            for (index, item) in items.iter().enumerate() {
                if let Some(rule) = reader.one_way(&root.key("oneWay").index(index), item) {
                    one_way.push(rule);
                }
            }
        }
        Some(other) => reader.expected(&root.key("oneWay"), "array", Some(other)),
    }
    reader.strict(&root, pairs, &CROSSWALK_FIELDS);
    match (source, target) {
        (Some(source), Some(target)) if reader.issues.is_empty() => Ok(Crosswalk {
            schema,
            source,
            target,
            rules,
            one_way,
            prepared: OnceLock::new(),
        }),
        _ => Err(CrossmapError::Syntax {
            issues: reader.issues,
        }),
    }
}