blue-lang-cli 0.0.262

The blue command line: run, fmt, ast, erase, check.
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
//! Tier T3 (docs/PERFORMANCE.md, 1.7.1): a definition compiled ahead of time by
//! chuuzou, one nix derivation per `def_hash`, and the run-time side that
//! answers a call from it.
//!
//! [`defs`] is what `blue ast --resolved --defs FILE` prints: each definition
//! of the entry file with its `def_hash` and its slice, the resolved forms of
//! every entry definition it reaches, each function and value renamed to
//! `%root/d_<hex>` after its own hash. The slice is then a function of the
//! hash: a rename changes no byte of it, and an edit outside what it reaches
//! changes none either. `native/build/defs.b` reads it, and
//! `nix/native-defs.nix` builds one derivation per slice.
//!
//! [`Tier`] is the call observer that answers a call of a definition whose
//! hash has an artifact under `BLUE_CACHE_SHARED`
//! (`blue_lang_mondou::store::native_artifact`), with every argument an Int,
//! by running the artifact; any other call, and any artifact that does not
//! answer, runs in the interpreter as before. It is on by default (rule R7 of
//! the default cascade): a run whose program has an artifact answers natively
//! each definition whose outermost calls averaged [`hot_from`] or more in
//! earlier runs (0.2 ms with a library, 20 ms without), and records this run's times in the profile tier
//! (`blue_lang_mondou::store::profile`), so a definition goes native once it is
//! known to be hot. `BLUE_NATIVE=on` answers every call it can; `off` none.

use std::collections::{BTreeSet, HashMap};
use std::path::PathBuf;
use std::sync::Arc;

use blue_lang_mondou::def_hash::{DefHash, DefHashes, DefKind};
use blue_lang_runtime::observe::{Call, CallObserver, Exit};
use blue_lang_runtime::uses::ResolvedProgram;
use blue_lang_syntax::{Atom, Span, Spanned, SpannedForm};
use tatara_lisp_eval::Value;

pub(crate) const ENV: &str = "BLUE_NATIVE";

/// The name a definition takes in every slice: its own hash.
fn canonical(hash: &DefHash) -> String {
    format!("%root/d_{}", hash.hex())
}

fn renamable(form: &Spanned) -> bool {
    matches!(
        form.as_list()
            .and_then(|items| items.first())
            .and_then(Spanned::as_symbol),
        Some("define" | "define-typed")
    )
}

fn rename(form: &Spanned, names: &HashMap<&str, String>) -> Spanned {
    let renamed = match &form.form {
        SpannedForm::Atom(Atom::Symbol(s)) => match names.get(s.as_str()) {
            Some(to) => SpannedForm::Atom(Atom::Symbol(to.clone())),
            None => form.form.clone(),
        },
        SpannedForm::List(items) => {
            SpannedForm::List(items.iter().map(|i| rename(i, names)).collect())
        }
        SpannedForm::Quote(x) => SpannedForm::Quote(Box::new(rename(x, names))),
        SpannedForm::Quasiquote(x) => SpannedForm::Quasiquote(Box::new(rename(x, names))),
        SpannedForm::Unquote(x) => SpannedForm::Unquote(Box::new(rename(x, names))),
        SpannedForm::UnquoteSplice(x) => SpannedForm::UnquoteSplice(Box::new(rename(x, names))),
        other => other.clone(),
    };
    Spanned::new(form.span, renamed)
}

fn reached(hashes: &DefHashes, from: usize, entry: &dyn Fn(usize) -> bool) -> BTreeSet<usize> {
    let mut seen = BTreeSet::new();
    let mut frontier = vec![from];
    while let Some(d) = frontier.pop() {
        if !entry(hashes.defs()[d].top_level) || !seen.insert(d) {
            continue;
        }
        frontier.extend(hashes.defs()[d].calls.iter().copied());
    }
    seen
}

/// Every unambiguous definition of the entry file of `program`: its key, its
/// `def_hash` as `def_hash(f)` answers it, its kind, the name it has in its
/// slice, and the slice. `lowered` is what the hash reads, `tree` the
/// resolved tree chuuzou reads, one form per top-level form of `program`.
///
/// # Errors
///
/// When `lowered` and `tree` do not hold one form per top-level form.
pub(crate) fn defs(
    program: &ResolvedProgram,
    lowered: &[Spanned],
    tree: &[Spanned],
) -> Result<serde_json::Value, String> {
    if lowered.len() != tree.len() {
        return Err(format!(
            "the lowered tree has {} forms and the resolved tree {}",
            lowered.len(),
            tree.len()
        ));
    }
    let hashes = blue_lang_mondou::hash_checked(program, lowered);
    let entry = |top: usize| program.owner_of(top) == Some(ResolvedProgram::ENTRY);
    let names: HashMap<&str, String> = hashes
        .defs()
        .iter()
        .filter(|d| entry(d.top_level) && !hashes.is_ambiguous(&d.key))
        .filter(|d| renamable(&tree[d.top_level]))
        .map(|d| (d.key.as_str(), canonical(&d.hash)))
        .collect();
    let mut out = Vec::new();
    for (i, d) in hashes.defs().iter().enumerate() {
        if !entry(d.top_level) || hashes.is_ambiguous(&d.key) {
            continue;
        }
        let mut seen = BTreeSet::new();
        let slice: Vec<String> = reached(&hashes, i, &entry)
            .into_iter()
            .map(|r| hashes.defs()[r].top_level)
            .collect::<BTreeSet<usize>>()
            .into_iter()
            .map(|top| rename(&tree[top], &names).to_sexp().to_string())
            .filter(|text| seen.insert(text.clone()))
            .collect();
        out.push(serde_json::json!({
            "key": d.key,
            "hash": d.hash.to_string(),
            "kind": match d.kind {
                DefKind::Function => "function",
                DefKind::Value => "value",
                DefKind::Macro => "macro",
            },
            "entry": names.get(d.key.as_str()).cloned().unwrap_or_else(|| d.key.clone()),
            "slice": slice.join("\n"),
        }));
    }
    Ok(serde_json::Value::Array(out))
}

/// A word the seam carries, as a definition's signature names it.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Word {
    Int,
    Bool,
    Float,
    Str,
    List,
    Record(Arc<Fields>),
    Map,
    Items(Arc<Fields>),
}

/// A record whose every field holds an Int, a Bool or a Float (an untyped
/// field an Int): its
/// key, its fields in declared order (the order its token lists them), and
/// the kind each field holds.
#[derive(Debug, PartialEq, Eq)]
struct Fields {
    key: String,
    names: Vec<String>,
    kinds: Vec<Kind>,
}

impl Fields {
    /// Whether a field holds a Str or a list, so the token carries each field
    /// as its own token (`R`, `;` between them) rather than as a word (`r`).
    fn counted(&self) -> bool {
        self.kinds
            .iter()
            .any(|k| matches!(k, Kind::Str | Kind::List))
    }

    /// The record `v` as its token: `r` and its fields as words, or `R` and
    /// each field's own token when one is counted; `None` when `v` is not
    /// this record.
    fn token(&self, v: &Value) -> Option<String> {
        let Value::Map(m) = v else { return None };
        (blue_lang_runtime::record::name_of(v)?
            == blue_lang_runtime::record::name_of_key(&self.key))
        .then_some(())?;
        let counted = self.counted();
        self.names
            .iter()
            .zip(&self.kinds)
            .map(|(n, k)| {
                let v = m.get(&tatara_lisp_eval::MapKey::Keyword(Arc::from(n.as_str())))?;
                if counted {
                    k.token(v)
                } else {
                    k.word(v).map(|w| w.to_string())
                }
            })
            .collect::<Option<Vec<String>>>()
            .map(|xs| {
                if counted {
                    format!("R{}", xs.join(";"))
                } else {
                    format!("r{}", xs.join(","))
                }
            })
    }

    /// The record a token names, built as its constructor builds it, or
    /// `None` when the token is not this record's.
    fn of_token(&self, token: &str) -> Option<Value> {
        let (tag, rest) = (token.as_bytes().first()?, token.get(1..)?);
        let values = match (tag, self.counted()) {
            (b'R', true) | (b'r', false) if rest.is_empty() => Vec::new(),
            (b'R', true) => rest
                .split(';')
                .zip(&self.kinds)
                .map(|(t, k)| k.of_token(t))
                .collect::<Option<Vec<Value>>>()?,
            (b'r', false) => rest
                .split(',')
                .zip(&self.kinds)
                .map(|(n, k)| n.parse().ok().and_then(|w| k.value(w)))
                .collect::<Option<Vec<Value>>>()?,
            _ => return None,
        };
        (values.len() == self.kinds.len()).then_some(())?;
        let names: Vec<&str> = self.names.iter().map(String::as_str).collect();
        blue_lang_runtime::record::value_of(&self.key, &names, values)
    }
}

/// What one field of a record the seam carries holds: a word, a Str, or a
/// list of Ints.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
    Int,
    Bool,
    Float,
    Str,
    List,
}

impl Kind {
    fn of(ty: Option<&Spanned>) -> Option<Self> {
        let Some(ty) = ty else {
            return Some(Self::Int);
        };
        if let Some([l, i]) = ty.as_list() {
            return (l.as_symbol() == Some("List") && i.as_symbol() == Some("Int"))
                .then_some(Self::List);
        }
        match ty.as_symbol()? {
            "Int" => Some(Self::Int),
            "Bool" => Some(Self::Bool),
            "Float" => Some(Self::Float),
            "Str" => Some(Self::Str),
            "List" => Some(Self::List),
            _ => None,
        }
    }

    fn word(self, v: &Value) -> Option<i64> {
        match (self, v) {
            (Self::Int, Value::Int(n)) => Some(*n),
            (Self::Bool, Value::Bool(b)) => Some(i64::from(*b)),
            (Self::Float, Value::Float(x)) => Some(x.to_bits().cast_signed()),
            _ => None,
        }
    }

    fn value(self, w: i64) -> Option<Value> {
        match self {
            Self::Int => Some(Value::Int(w)),
            Self::Bool => Some(Value::Bool(w != 0)),
            Self::Float => Some(Value::Float(f64::from_bits(w.cast_unsigned()))),
            Self::Str | Self::List => None,
        }
    }

    /// The field's own token, as a record that holds a Str or a list carries
    /// each.
    fn token(self, v: &Value) -> Option<String> {
        match (self, v) {
            (Self::Str, Value::Str(t)) => Some(str_token(t)),
            (Self::List, Value::List(xs)) => list_token(xs.iter()),
            (Self::Int, _) => self.word(v).map(|w| format!("i{w}")),
            (Self::Bool, _) => self.word(v).map(|w| format!("b{w}")),
            (Self::Float, _) => self.word(v).map(|w| format!("f{w}")),
            _ => None,
        }
    }

    fn of_token(self, t: &str) -> Option<Value> {
        let (tag, rest) = (t.as_bytes().first()?, t.get(1..)?);
        match (self, tag) {
            (Self::Str, b's') => str_of(rest),
            (Self::List, b'l') => list_of(rest),
            (Self::Int, b'i') | (Self::Bool, b'b') | (Self::Float, b'f') => {
                rest.parse().ok().and_then(|w| self.value(w))
            }
            _ => None,
        }
    }
}

fn list_token<'a>(xs: impl IntoIterator<Item = &'a Value>) -> Option<String> {
    xs.into_iter()
        .map(|x| match x {
            Value::Int(n) => Some(n.to_string()),
            _ => None,
        })
        .collect::<Option<Vec<String>>>()
        .map(|ns| format!("l{}", ns.join(",")))
}

fn list_of(rest: &str) -> Option<Value> {
    if rest.is_empty() {
        return Some(Value::List(Default::default()));
    }
    rest.split(',')
        .map(|n| n.parse().ok().map(Value::Int))
        .collect::<Option<Vec<Value>>>()
        .map(|xs| Value::List(std::sync::Arc::new(xs.into())))
}

fn str_token(t: &str) -> String {
    t.bytes().fold(String::from("s"), |mut out, b| {
        out.push_str(&format!("{b:02x}"));
        out
    })
}

fn str_of(hex: &str) -> Option<Value> {
    if hex.len() % 2 != 0 {
        return None;
    }
    let bytes = (0..hex.len())
        .step_by(2)
        .map(|i| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok())
        .collect::<Option<Vec<u8>>>()?;
    String::from_utf8(bytes).ok().map(|t| Value::Str(t.into()))
}

/// The records of `forms` whose fields the seam carries, by the name a
/// signature writes.
fn records(forms: &[Spanned]) -> HashMap<String, Arc<Fields>> {
    forms
        .iter()
        .filter_map(blue_lang_syntax::record::record_parts)
        .filter_map(|r| {
            let key = r.name.as_symbol()?.to_string();
            let kinds = r
                .fields
                .iter()
                .map(|f| Kind::of(f.ty))
                .collect::<Option<Vec<Kind>>>()?;
            Some((
                blue_lang_runtime::record::name_of_key(&key),
                Arc::new(Fields {
                    names: r.field_names().iter().map(ToString::to_string).collect(),
                    kinds,
                    key,
                }),
            ))
        })
        .collect()
}

/// What a definition takes and answers, as the tier converts it across the
/// seam: an untyped definition is held to Ints, as before types crossed it.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Shape {
    Untyped,
    Typed(Vec<Word>, Word),
}

impl Shape {
    /// The shape `form` declares, or `None` when it names a type the seam
    /// does not carry.
    fn of(form: &Spanned, records: &HashMap<String, Arc<Fields>>) -> Option<Self> {
        let items = form.as_list()?;
        if items.first().and_then(Spanned::as_symbol) != Some("define-typed") {
            return Some(Self::Untyped);
        }
        let items_of = |t: &Spanned| match t.as_list()? {
            [l, r] if l.as_symbol() == Some("List") => {
                records.get(r.as_symbol()?).cloned().map(Word::Items)
            }
            _ => None,
        };
        let word = |t: &Spanned| {
            items_of(t).or_else(|| {
                match t.as_symbol().or_else(|| match t.as_list()? {
                    [l, i] if l.as_symbol() == Some("List") && i.as_symbol() == Some("Int") => {
                        Some("List")
                    }
                    [m, k, v]
                        if m.as_symbol() == Some("Map")
                            && k.as_symbol() == Some("Str")
                            && v.as_symbol() == Some("Int") =>
                    {
                        Some("Map(Str, Int)")
                    }
                    _ => None,
                })? {
                    "List" => Some(Word::List),
                    "Map(Str, Int)" => Some(Word::Map),
                    "Int" => Some(Word::Int),
                    "Bool" => Some(Word::Bool),
                    "Float" => Some(Word::Float),
                    "Str" => Some(Word::Str),
                    other => records.get(other).cloned().map(Word::Record),
                }
            })
        };
        let params = items
            .get(1)?
            .as_list()?
            .iter()
            .skip(1)
            .map(|p| p.as_list().and_then(|p| p.get(1)).and_then(word))
            .collect::<Option<Vec<Word>>>()?;
        Some(Self::Typed(params, word(items.get(2)?)?))
    }

    /// The arguments as the seam's words, or `None` when one is not what the
    /// signature names.
    fn words(&self, args: &[Value]) -> Option<Vec<i64>> {
        let take = |a: &Value, w: Word| match (a, w) {
            (Value::Int(n), Word::Int) => Some(*n),
            (Value::Bool(b), Word::Bool) => Some(i64::from(*b)),
            (Value::Float(x), Word::Float) => Some(x.to_bits().cast_signed()),
            _ => None,
        };
        if !self.in_words() {
            return None;
        }
        match self {
            Self::Untyped => args.iter().map(|a| take(a, Word::Int)).collect(),
            Self::Typed(ws, _) if ws.len() == args.len() => args
                .iter()
                .zip(ws)
                .map(|(a, w)| take(a, w.clone()))
                .collect(),
            Self::Typed(..) => None,
        }
    }

    /// Whether every argument and the answer fit one word each, so the word
    /// seam carries the call; a Str needs the token seam.
    fn in_words(&self) -> bool {
        match self {
            Self::Untyped => true,
            Self::Typed(ws, r) => ws.iter().chain([r]).all(|w| {
                !matches!(
                    w,
                    Word::Str | Word::List | Word::Record(_) | Word::Map | Word::Items(_)
                )
            }),
        }
    }

    /// Whether every word is an Int, so an executable takes bare decimals,
    /// as executables built before tokens did.
    fn plain(&self) -> bool {
        match self {
            Self::Untyped => true,
            Self::Typed(ws, r) => ws.iter().chain([r]).all(|w| *w == Word::Int),
        }
    }

    /// The arguments as value tokens (`native/seam/host_io.rs`, `decode`), or
    /// `None` when one is not what the signature names.
    fn tokens(&self, args: &[Value]) -> Option<Vec<String>> {
        let ws: Vec<Word> = match self {
            Self::Untyped => vec![Word::Int; args.len()],
            Self::Typed(ws, _) if ws.len() == args.len() => ws.clone(),
            Self::Typed(..) => return None,
        };
        args.iter()
            .zip(ws)
            .map(|(a, w)| match (a, w) {
                (Value::Int(n), Word::Int) => Some(format!("i{n}")),
                (Value::Bool(b), Word::Bool) => Some(format!("b{}", u8::from(*b))),
                (Value::Float(x), Word::Float) => Some(format!("f{}", x.to_bits().cast_signed())),
                (Value::List(xs), Word::List) => list_token(xs.iter()),
                (v @ Value::Map(m), Word::Map)
                    if blue_lang_runtime::record::name_of(v).is_none() =>
                {
                    m.iter()
                        .map(|(k, v)| match (k, v) {
                            (tatara_lisp_eval::MapKey::Str(k), Value::Int(n)) => {
                                Some(format!("{}={n}", str_token(k).get(1..)?))
                            }
                            _ => None,
                        })
                        .collect::<Option<Vec<String>>>()
                        .map(|es| format!("m{}", es.join(",")))
                }
                (v, Word::Record(f)) => f.token(v),
                (Value::List(xs), Word::Items(f)) => xs
                    .iter()
                    .map(|r| f.token(r))
                    .collect::<Option<Vec<String>>>()
                    .map(|ts| format!("L{}", ts.join("|"))),
                (Value::Str(t), Word::Str) => Some(str_token(t)),
                _ => None,
            })
            .collect()
    }

    /// The answer's token as the value the signature names, or `None` when it
    /// is not one. A bare decimal is an Int, as executables built before
    /// tokens answered.
    fn from_token(&self, token: &str) -> Option<Value> {
        let want = match self {
            Self::Untyped => Word::Int,
            Self::Typed(_, r) => r.clone(),
        };
        let (tag, rest) = (token.as_bytes().first()?, token.get(1..)?);
        match (tag, want) {
            (b'i', Word::Int) => rest.parse().ok().map(Value::Int),
            (b'b', Word::Bool) => match rest {
                "1" => Some(Value::Bool(true)),
                "0" => Some(Value::Bool(false)),
                _ => None,
            },
            (b'f', Word::Float) => rest
                .parse::<i64>()
                .ok()
                .map(|b| Value::Float(f64::from_bits(b.cast_unsigned()))),
            (b's', Word::Str) => str_of(rest),
            (b'R' | b'r', Word::Record(f)) => f.of_token(token),
            (b'L', Word::Items(_)) if rest.is_empty() => Some(Value::List(Default::default())),
            (b'L', Word::Items(f)) => rest
                .split('|')
                .map(|t| f.of_token(t))
                .collect::<Option<Vec<Value>>>()
                .map(|xs| Value::List(Arc::new(xs.into()))),
            (b'l', Word::List) => list_of(rest),
            (b'm', Word::Map) => {
                let mut m = tatara_lisp_eval::Map::new();
                if !rest.is_empty() {
                    for entry in rest.split(',') {
                        let (k, n) = entry.split_once('=')?;
                        let Value::Str(k) = str_of(k)? else {
                            return None;
                        };
                        m.insert(
                            tatara_lisp_eval::MapKey::Str(k),
                            Value::Int(n.parse().ok()?),
                        );
                    }
                }
                Some(Value::Map(Arc::new(m)))
            }
            (_, Word::Int) => token.parse().ok().map(Value::Int),
            _ => None,
        }
    }

    /// The seam's answer as the value the signature names.
    fn value(&self, v: i64) -> Value {
        match self {
            Self::Typed(_, Word::Bool) => Value::Bool(v != 0),
            Self::Typed(_, Word::Float) => Value::Float(f64::from_bits(v.cast_unsigned())),
            _ => Value::Int(v),
        }
    }
}

struct Target {
    name: Option<String>,
    artifact: PathBuf,
    library: Option<crate::dl::Entry>,
    shape: Shape,
    hash: DefHash,
    hot: bool,
    profiled: bool,
    from: u64,
}

/// How the tier decides, from `BLUE_NATIVE`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Mode {
    /// Unset: a call goes native only when its definition's outermost calls
    /// ran at least [`hot_from`] on average in earlier runs.
    Auto,
    /// `on`: every call with an artifact and Int arguments goes native.
    On,
    /// `off`: no call does.
    Off,
}

/// The mean an outermost call must have cost before [`Mode::Auto`] answers it
/// natively: well above what starting an artifact costs, so the default only
/// fires where the gain is known.
pub(crate) const HOT_NS: u64 = 20_000_000;

/// The mean an outermost call must have cost before [`Mode::Auto`] answers it
/// through the artifact's library: ten times what one call through the
/// library costs (about 20 µs, most of it the thread that holds the board's
/// stack), where [`HOT_NS`] is sized for starting a process.
pub(crate) const HOT_LIBRARY_NS: u64 = 200_000;

/// The mean from which a definition is hot: [`HOT_LIBRARY_NS`] when its
/// artifact's library loaded, else [`HOT_NS`]. A static binary (blue on Linux
/// is static musl) cannot load a library, so there every call starts the
/// executable and the process threshold holds.
pub(crate) fn hot_from(library: bool) -> u64 {
    if library {
        HOT_LIBRARY_NS
    } else {
        HOT_NS
    }
}

pub(crate) fn mode_of(value: Option<&str>) -> Mode {
    match value.map(|v| v.trim().to_ascii_lowercase()).as_deref() {
        None | Some("" | "auto") => Mode::Auto,
        Some("on" | "1" | "true" | "yes") => Mode::On,
        Some(_) => Mode::Off,
    }
}

pub(crate) fn mode() -> Mode {
    mode_of(std::env::var(ENV).ok().as_deref())
}

#[derive(Default)]
struct Timing {
    open: HashMap<Span, (u32, Option<std::time::Instant>)>,
    seen: HashMap<DefHash, blue_lang_mondou::store::Profiled>,
    tail: Option<(Span, DefHash)>,
}

impl Timing {
    fn close(&mut self, source: Span, hash: DefHash) {
        let Some(started) = self.open.get_mut(&source).and_then(|o| o.1.take()) else {
            return;
        };
        let ns = u64::try_from(started.elapsed().as_nanos()).unwrap_or(u64::MAX);
        let p = self.seen.entry(hash).or_default();
        *p = p.plus(blue_lang_mondou::store::Profiled {
            total_ns: ns,
            calls: 1,
        });
    }
}

/// The native tier over one program: each function definition whose
/// `def_hash` has an artifact, by the span its closure carries.
pub(crate) struct Tier {
    by_source: HashMap<Span, Target>,
    inner: Option<Arc<dyn CallObserver>>,
    timing: std::sync::Mutex<Timing>,
    answers: bool,
    seeding: bool,
}

impl Tier {
    /// The tier for a program about to run, looking each definition's
    /// artifact up with `find` and its profile with `profiled`; a definition
    /// with no artifact runs as before.
    pub(crate) fn over(
        w: &blue_lang_runtime::pipeline::Watched<'_>,
        mode: Mode,
        find: &dyn Fn(&DefHash) -> Option<PathBuf>,
        profiled: &dyn Fn(&DefHash) -> Option<blue_lang_mondou::store::Profiled>,
        inner: Option<Arc<dyn CallObserver>>,
    ) -> Arc<Self> {
        let hashes = blue_lang_mondou::hash_checked(w.program, w.lowered);
        let records = records(w.lowered);
        let mut by_source = HashMap::new();
        for d in w.definitions.iter() {
            let Some(hashed) = hashes.at(d.top_level) else {
                continue;
            };
            if hashed.key != *d.key || hashed.kind != DefKind::Function {
                continue;
            }
            let Some(artifact) = find(&hashed.hash) else {
                continue;
            };
            let Some(shape) = w
                .lowered
                .get(d.top_level)
                .and_then(|f| Shape::of(f, &records))
            else {
                continue;
            };
            let Some(items) = w.erased.get(d.top_level).and_then(Spanned::as_list) else {
                continue;
            };
            let source = match items.get(1).and_then(Spanned::as_symbol) {
                Some(_) => items.get(2).map(|l| (l.span, None)),
                None => Some((d.span, Some(d.key.to_string()))),
            };
            let mean = profiled(&hashed.hash).and_then(blue_lang_mondou::store::Profiled::mean_ns);
            let library = if mode == Mode::Off {
                None
            } else {
                blue_lang_mondou::store::native_library(&artifact).and_then(|l| crate::dl::open(&l))
            };
            let threshold = hot_from(library.is_some());
            let hot = match mode {
                Mode::On => true,
                Mode::Off => false,
                Mode::Auto => {
                    let held: &[&str] = if mean.is_some_and(|ns| ns >= threshold) {
                        &["artifact", "hot"]
                    } else {
                        &["artifact"]
                    };
                    blue_lang_runtime::kitei::fires("R7", held)
                }
            };
            let library = library.filter(|_| hot);
            if let Some((span, name)) = source {
                by_source.insert(
                    span,
                    Target {
                        name,
                        artifact,
                        library,
                        shape,
                        hash: hashed.hash,
                        hot,
                        profiled: mean.is_some(),
                        from: threshold,
                    },
                );
            }
        }
        Arc::new(Self {
            by_source,
            inner,
            timing: std::sync::Mutex::default(),
            answers: true,
            seeding: false,
        })
    }

    /// The tier a test run seeds the profile through (W1 of docs/FACTS.md):
    /// it answers no call, times every definition with an artifact, and
    /// records a definition's time only when it ran hot, so a definition its
    /// tests call cheaply stays unprofiled and the first real run times it.
    /// `None` when the program has no definition with an artifact.
    pub(crate) fn seeding(
        w: &blue_lang_runtime::pipeline::Watched<'_>,
        inner: Option<Arc<dyn CallObserver>>,
    ) -> Option<Arc<Self>> {
        if !seeds() {
            return None;
        }
        let tier = Self::over(
            w,
            Mode::Auto,
            &blue_lang_mondou::store::native_artifact,
            &blue_lang_mondou::store::profile,
            inner,
        );
        let mut tier = Arc::into_inner(tier)?;
        if tier.by_source.is_empty() {
            return None;
        }
        tier.answers = false;
        tier.seeding = true;
        Some(Arc::new(tier))
    }

    /// The definitions this run answers natively, and the ones it measures
    /// because no run has profiled them yet, each by the name a call uses.
    fn plan(&self) -> (Vec<String>, Vec<String>) {
        let named = |t: &Target| t.name.clone().unwrap_or_else(|| t.hash.hex());
        let mut hot: Vec<String> = self
            .by_source
            .values()
            .filter(|t| t.hot)
            .map(named)
            .collect();
        let mut fresh: Vec<String> = self
            .by_source
            .values()
            .filter(|t| !t.hot && !t.profiled)
            .map(named)
            .collect();
        hot.sort();
        fresh.sort();
        (hot, fresh)
    }

    fn target(&self, call_: &Call<'_>) -> Option<&Target> {
        let target = self.by_source.get(&call_.source)?;
        (target.name.as_deref() == call_.name.map(|n| &**n)).then_some(target)
    }

    /// The time this run's outermost calls of each definition took, added to
    /// the profile tier through `record`.
    /// When the tier seeds, only the times of definitions that ran hot.
    pub(crate) fn flush(&self, record: &dyn Fn(&DefHash, blue_lang_mondou::store::Profiled)) {
        let seen = self
            .timing
            .lock()
            .map(|mut t| std::mem::take(&mut t.seen))
            .unwrap_or_default();
        let from: HashMap<DefHash, u64> =
            self.by_source.values().map(|t| (t.hash, t.from)).collect();
        for (hash, p) in seen {
            let hot = p
                .mean_ns()
                .is_some_and(|ns| ns >= from.get(&hash).copied().unwrap_or(HOT_NS));
            if !self.seeding || hot {
                record(&hash, p);
            }
        }
    }
}

impl Drop for Tier {
    fn drop(&mut self) {
        self.flush(&blue_lang_mondou::store::record_profile);
    }
}

/// The planner `blue run` offers the pipeline by default: the native tier when
/// the program has a definition with an artifact that is hot or not yet
/// profiled, over the memo [`crate::memo::planned`] or [`crate::memo::costly`]
/// offers when `memo`; else that memo.
pub(crate) fn planned(
    w: &blue_lang_runtime::pipeline::Watched<'_>,
    repeating: &[(usize, String)],
    memo: bool,
    native: bool,
    slow: bool,
) -> Option<blue_lang_runtime::pipeline::Planned> {
    let memo = if memo {
        crate::memo::planned(w, repeating).or_else(|| crate::memo::costly(w, slow))
    } else {
        None
    };
    let current = mode();
    if !native || current == Mode::Off || !blue_lang_mondou::store::native_present() {
        return memo;
    }
    let (inner, memo_reason) = match memo {
        Some((o, r)) => (Some(o), Some(r)),
        None => (None, None),
    };
    let tier = Tier::over(
        w,
        current,
        &blue_lang_mondou::store::native_artifact,
        &blue_lang_mondou::store::profile,
        inner.clone(),
    );
    let (hot, fresh) = tier.plan();
    if hot.is_empty() && fresh.is_empty() {
        return inner.zip(memo_reason);
    }
    let mut reason = Vec::new();
    if !hot.is_empty() {
        reason.push(format!(
            "native code answers `{}`, whose calls ran {} ms or more in earlier runs ({} ms through a library)",
            hot.join("`, `"),
            HOT_NS / 1_000_000,
            HOT_LIBRARY_NS as f64 / 1_000_000.0
        ));
    }
    if !fresh.is_empty() {
        reason.push(format!(
            "the native tier times `{}`, which has an artifact and no profile yet",
            fresh.join("`, `")
        ));
    }
    reason.extend(memo_reason);
    Some((tier, reason.join("; ")))
}

/// Whether a test run seeds the profile: the tier is not off and a native
/// tier is present, checked before any hashing.
pub(crate) fn seeds() -> bool {
    mode() != Mode::Off && blue_lang_mondou::store::native_present()
}

/// The variable naming the command a run starts, detached, when it asks for
/// its program to be built (`nix run .#native-build`, which reads the
/// requests); unset, the requests wait for a builder the node runs itself.
pub(crate) const BUILDER_ENV: &str = "BLUE_NATIVE_BUILDER";

/// After a run of `file` whose evaluation took `took`: ask for the program to
/// be built into this node's native tier when the tier decides by profile
/// ([`Mode::Auto`]), a native tier is present, and the evaluation took
/// [`HOT_NS`] or more, the cost from which a definition earns native code even
/// as a process; start the builder [`BUILDER_ENV`] names when this run asked.
/// Answers whether it asked.
pub(crate) fn ask_for_build(file: &std::path::Path, took: std::time::Duration) -> bool {
    if mode() != Mode::Auto
        || took.as_nanos() < u128::from(HOT_NS)
        || !blue_lang_mondou::store::native_present()
    {
        return false;
    }
    let (Ok(text), Ok(path)) = (std::fs::read(file), file.canonicalize()) else {
        return false;
    };
    let asked = blue_lang_mondou::store::want_native(&text, &path);
    if asked {
        if let Some(builder) = std::env::var_os(BUILDER_ENV).filter(|b| !b.is_empty()) {
            let _ = std::process::Command::new(builder)
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn();
        }
    }
    asked
}

/// Run one artifact on its arguments' text: the one line it answered, or
/// `None` when it did not answer (a fault, arguments it refuses, an output
/// that is not one line).
fn answer(artifact: &std::path::Path, args: impl IntoIterator<Item = String>) -> Option<String> {
    let out = std::process::Command::new(artifact)
        .args(args)
        .stdin(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let text = String::from_utf8(out.stdout).ok()?;
    let mut lines = text.lines();
    let value = lines.next()?.trim().to_string();
    lines.next().is_none().then_some(value)
}

impl CallObserver for Tier {
    fn enter(&self, call_: &Call<'_>, args: &[Value]) -> Option<Value> {
        if let Some(answered) = self.inner.as_ref().and_then(|i| i.enter(call_, args)) {
            return Some(answered);
        }
        if let Ok(mut t) = self.timing.lock() {
            if let Some((source, hash)) = t.tail.take() {
                if source != call_.source {
                    t.close(source, hash);
                }
            }
        }
        let target = self.target(call_)?;
        if self.answers && target.hot {
            let shape = &target.shape;
            let answered = match target.library {
                Some(entry) if shape.in_words() => shape
                    .words(args)
                    .and_then(|words| crate::dl::call(entry, &words))
                    .map(|v| shape.value(v)),
                Some(entry) => shape
                    .tokens(args)
                    .and_then(|t| crate::dl::call_tokens(entry, &t.join(" ")))
                    .and_then(|token| shape.from_token(&token)),
                None if shape.plain() => shape
                    .words(args)
                    .and_then(|words| answer(&target.artifact, words.iter().map(i64::to_string)))
                    .and_then(|token| shape.from_token(&token)),
                None => shape
                    .tokens(args)
                    .and_then(|t| answer(&target.artifact, t))
                    .and_then(|token| shape.from_token(&token)),
            };
            if answered.is_some() {
                return answered;
            }
        }
        if let Ok(mut t) = self.timing.lock() {
            let open = t.open.entry(call_.source).or_insert((0, None));
            if open.0 == 0 && open.1.is_none() {
                open.1 = Some(std::time::Instant::now());
            }
            open.0 += 1;
        }
        None
    }

    fn leave(&self, call_: &Call<'_>, exit: Exit<'_>) {
        if let Some(inner) = &self.inner {
            inner.leave(call_, exit);
        }
        if matches!(exit, Exit::Supplied(_)) {
            return;
        }
        let Some(target) = self.target(call_) else {
            return;
        };
        let hash = target.hash;
        if let Ok(mut t) = self.timing.lock() {
            let Some(open) = t.open.get_mut(&call_.source) else {
                return;
            };
            open.0 = open.0.saturating_sub(1);
            if open.0 > 0 {
                return;
            }
            if matches!(exit, Exit::TailCalled) {
                t.tail = Some((call_.source, hash));
                return;
            }
            t.close(call_.source, hash);
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use super::*;

    fn shape(src: &str) -> Option<Shape> {
        let forms = tatara_lisp::read_spanned(src).expect("forms");
        let records = records(&forms);
        Shape::of(forms.last().expect("a form"), &records)
    }

    #[test]
    fn a_signature_names_what_crosses_the_seam() {
        assert_eq!(shape("(define (%root/f x) x)"), Some(Shape::Untyped));
        let pick =
            shape("(define-typed (%root/pick (b Bool) (x Int)) Int (if b x 0))").expect("a shape");
        assert_eq!(pick, Shape::Typed(vec![Word::Bool, Word::Int], Word::Int));
        assert_eq!(
            pick.words(&[Value::Bool(true), Value::Int(7)]),
            Some(vec![1, 7])
        );
        assert_eq!(pick.words(&[Value::Int(1), Value::Int(7)]), None);
        assert_eq!(pick.words(&[Value::Bool(true)]), None);
        let small = shape("(define-typed (%root/small (n Int)) Bool (< n 3))").expect("a shape");
        assert!(matches!(small.value(0), Value::Bool(false)));
        assert!(matches!(small.value(1), Value::Bool(true)));
        assert_eq!(shape("(define-typed (%root/s (t String)) Int 0)"), None);
    }

    #[test]
    fn a_float_crosses_the_seam_as_its_bits_both_ways() {
        let half = shape("(define-typed (%root/half (x Float)) Float (* x 0.5))").expect("a shape");
        assert_eq!(half, Shape::Typed(vec![Word::Float], Word::Float));
        let bits = (-2.5f64).to_bits().cast_signed();
        assert_eq!(half.words(&[Value::Float(-2.5)]), Some(vec![bits]));
        assert_eq!(half.words(&[Value::Int(3)]), None);
        assert!(matches!(half.value(bits), Value::Float(x) if x == -2.5));
        assert!(matches!(half.value(0), Value::Float(x) if x == 0.0));
    }

    fn checked(src: &str) -> blue_lang_runtime::pipeline::Checked {
        let loader = blue_lang_pkg::load_path::LoadPath::for_entry(
            &std::env::temp_dir().join("native-test.b"),
        );
        let c = blue_lang_runtime::pipeline::check_entry(
            blue_lang_runtime::uses::Entry::anonymous(src),
            &loader,
            None,
            blue_lang_runtime::pipeline::Checking::Program,
        )
        .expect("checks");
        assert!(c.outcome.ok(), "{:?}", c.outcome.diagnostics);
        c
    }

    fn slices(src: &str) -> BTreeMap<String, (String, String)> {
        let c = checked(src);
        let tree = c
            .resolve()
            .resolved_tree(c.program.forms(), blue_lang_check::names::Rule::Namespaced);
        let v = defs(&c.program, &c.lowered(), &tree).expect("aligned");
        v.as_array()
            .expect("a list")
            .iter()
            .map(|d| {
                (
                    d["key"].as_str().expect("key").to_string(),
                    (
                        d["hash"].as_str().expect("hash").to_string(),
                        d["slice"].as_str().expect("slice").to_string(),
                    ),
                )
            })
            .collect()
    }

    const BASE: &str = "def sq(x: Int) -> Int\n  x * x\nend\n\ndef sum(n: Int, acc: Int) -> Int\n  if n == 0\n    acc\n  else\n    sum(n - 1, acc + sq(n))\n  end\nend\n\ndef fib(n: Int) -> Int\n  if n < 2\n    n\n  else\n    fib(n - 1) + fib(n - 2)\n  end\nend\n";

    #[test]
    fn a_slice_holds_what_its_definition_reaches_named_by_hash() {
        let s = slices(BASE);
        let (sq_hash, sq_slice) = &s["%root/sq"];
        let (_, sum_slice) = &s["%root/sum"];
        let (_, fib_slice) = &s["%root/fib"];
        let sq_name = format!("%root/d_{}", sq_hash.trim_start_matches("b3:"));
        assert!(sq_slice.contains(&sq_name), "{sq_slice}");
        assert!(sum_slice.contains(&sq_name), "{sum_slice}");
        assert!(!fib_slice.contains(&sq_name), "{fib_slice}");
        assert!(!fib_slice.contains("%root/fib"), "{fib_slice}");
        assert_eq!(sq_slice.lines().count(), 1);
        assert_eq!(sum_slice.lines().count(), 2);
    }

    #[test]
    fn an_edit_moves_what_reaches_it_and_a_rename_moves_nothing() {
        let base = slices(BASE);
        let edited = slices(&BASE.replace("x * x", "x * x + 1"));
        let renamed = slices(&BASE.replace("fib", "fibonacci"));
        assert_ne!(base["%root/sq"], edited["%root/sq"]);
        assert_ne!(base["%root/sum"], edited["%root/sum"]);
        assert_eq!(base["%root/fib"], edited["%root/fib"]);
        assert_eq!(base["%root/fib"], renamed["%root/fibonacci"]);
    }

    #[test]
    fn the_hash_is_the_one_def_hash_answers() {
        let c = checked(BASE);
        let lowered = c.lowered();
        let ids = blue_lang_mondou::def_hash::identified(
            &lowered,
            &blue_lang_mondou::program_docs(&c.program),
            None,
        );
        let s = slices(BASE);
        for key in ["%root/sq", "%root/sum", "%root/fib"] {
            assert_eq!(ids[key], s[key].0, "{key}");
        }
    }

    #[test]
    fn the_tier_decides_by_profile_unless_named() {
        assert_eq!(mode_of(None), Mode::Auto);
        assert_eq!(mode_of(Some("auto")), Mode::Auto);
        assert_eq!(mode_of(Some("off")), Mode::Off);
        assert_eq!(mode_of(Some("maybe")), Mode::Off);
        assert_eq!(mode_of(Some(" On ")), Mode::On);
        assert_eq!(mode_of(Some("1")), Mode::On);
    }

    #[test]
    fn an_artifact_that_does_not_answer_one_line_is_no_answer() {
        assert_eq!(
            answer(std::path::Path::new("/no/such/artifact"), ["1".to_string()]),
            None
        );
    }

    #[test]
    fn a_list_of_ints_crosses_the_seam_as_a_token_both_ways() {
        let sum = shape("(define-typed (%root/s (xs (List Int))) (List Int) xs)").expect("a shape");
        assert_eq!(sum, Shape::Typed(vec![Word::List], Word::List));
        assert!(!sum.in_words() && !sum.plain());
        let xs = Value::List(std::sync::Arc::new(
            vec![Value::Int(-1), Value::Int(20)].into(),
        ));
        assert_eq!(sum.tokens(&[xs]), Some(vec!["l-1,20".to_string()]));
        let strs = Value::List(std::sync::Arc::new(vec![Value::Str("a".into())].into()));
        assert_eq!(sum.tokens(&[strs]), None);
        assert!(matches!(sum.from_token("l3,4"), Some(Value::List(l)) if l.len() == 2));
        assert!(matches!(sum.from_token("l"), Some(Value::List(l)) if l.is_empty()));
        assert!(sum.from_token("l3,x").is_none());
        let bare = shape("(define-typed (%root/b (xs List)) Int 0)").expect("a shape");
        assert_eq!(bare, Shape::Typed(vec![Word::List], Word::Int));
    }

    #[test]
    fn a_record_of_ints_crosses_the_seam_as_its_fields_in_declared_order() {
        let shift = shape(
            "(blue-record %root/pt %root/pt? (:y Int) (:x Int)) (define-typed (%root/s (p pt) (d Int)) pt p)",
        )
        .expect("a shape");
        assert!(!shift.in_words() && !shift.plain());
        let p = blue_lang_runtime::record::value_of(
            "%root/pt",
            &["y", "x"],
            vec![Value::Int(2), Value::Int(1)],
        )
        .expect("a record");
        assert_eq!(
            shift.tokens(&[p.clone(), Value::Int(5)]),
            Some(vec!["r2,1".to_string(), "i5".to_string()])
        );
        let back = shift.from_token("r2,1").expect("a record");
        assert!(blue_lang_runtime::stdlib::blue_equal(&back, &p));
        assert!(shift.from_token("r2").is_none());
        let other = blue_lang_runtime::record::value_of(
            "%root/qt",
            &["y", "x"],
            vec![Value::Int(2), Value::Int(1)],
        )
        .expect("a record");
        assert_eq!(shift.tokens(&[other, Value::Int(5)]), None);
        assert_eq!(
            shape(
                "(blue-record %root/pt %root/pt? (:y (List Str))) (define-typed (%root/s (p pt)) Int 0)"
            ),
            None
        );
    }

    #[test]
    fn a_record_that_holds_a_str_crosses_the_seam_as_each_field_s_own_token() {
        let named = shape(
            "(blue-record %root/tag %root/tag? (:label Str) (:n Int)) (define-typed (%root/k (t tag)) tag t)",
        )
        .expect("a shape");
        let t = blue_lang_runtime::record::value_of(
            "%root/tag",
            &["label", "n"],
            vec![Value::Str("é,1".into()), Value::Int(3)],
        )
        .expect("a record");
        assert_eq!(
            named.tokens(std::slice::from_ref(&t)),
            Some(vec!["Rsc3a92c31;i3".to_string()])
        );
        let back = named.from_token("Rsc3a92c31;i3").expect("a record");
        assert!(blue_lang_runtime::stdlib::blue_equal(&back, &t));
        assert!(named.from_token("rsc3a92c31,3").is_none());
        assert!(named.from_token("Ri3;sc3a9").is_none());
        assert!(named.from_token("Rsc3a9").is_none());
    }

    #[test]
    fn a_record_that_holds_a_list_carries_the_list_s_own_token_between_semicolons() {
        let held = shape(
            "(blue-record %root/bag %root/bag? (:xs (List Int)) (:n Int)) (define-typed (%root/k (b bag)) bag b)",
        )
        .expect("a shape");
        let xs = Value::List(std::sync::Arc::new(
            vec![Value::Int(1), Value::Int(-2)].into(),
        ));
        let b =
            blue_lang_runtime::record::value_of("%root/bag", &["xs", "n"], vec![xs, Value::Int(3)])
                .expect("a record");
        assert_eq!(
            held.tokens(std::slice::from_ref(&b)),
            Some(vec!["Rl1,-2;i3".to_string()])
        );
        let back = held.from_token("Rl1,-2;i3").expect("a record");
        assert!(blue_lang_runtime::stdlib::blue_equal(&back, &b));
        assert!(held.from_token("Rl;i3").is_some());
        assert!(held.from_token("Ri3;l1").is_none());
        let floats = Value::List(std::sync::Arc::new(vec![Value::Float(1.0)].into()));
        let bad = blue_lang_runtime::record::value_of(
            "%root/bag",
            &["xs", "n"],
            vec![floats, Value::Int(3)],
        )
        .expect("a record");
        assert_eq!(held.tokens(&[bad]), None);
    }

    #[test]
    fn a_list_of_records_crosses_the_seam_as_each_record_s_token_between_bars() {
        let walk = shape(
            "(blue-record %root/pt %root/pt? :x :y) (blue-record %root/tag %root/tag? (:label Str) (:n Int)) (define-typed (%root/w (ps (List pt)) (ts (List tag))) (List pt) ps)",
        )
        .expect("a shape");
        assert!(!walk.in_words());
        let pt = |x, y| {
            blue_lang_runtime::record::value_of(
                "%root/pt",
                &["x", "y"],
                vec![Value::Int(x), Value::Int(y)],
            )
            .expect("a record")
        };
        let tag = blue_lang_runtime::record::value_of(
            "%root/tag",
            &["label", "n"],
            vec![Value::Str("é".into()), Value::Int(3)],
        )
        .expect("a record");
        let list = |xs: Vec<Value>| Value::List(std::sync::Arc::new(xs.into()));
        let ps = list(vec![pt(1, 2), pt(-3, 4)]);
        assert_eq!(
            walk.tokens(&[ps.clone(), list(vec![tag.clone(), tag.clone()])]),
            Some(vec![
                "Lr1,2|r-3,4".to_string(),
                "LRsc3a9;i3|Rsc3a9;i3".to_string()
            ])
        );
        assert_eq!(
            walk.tokens(&[list(Vec::new()), list(Vec::new())]),
            Some(vec!["L".to_string(), "L".to_string()])
        );
        let back = walk.from_token("Lr1,2|r-3,4").expect("a list");
        assert!(blue_lang_runtime::stdlib::blue_equal(&back, &ps));
        assert!(blue_lang_runtime::stdlib::blue_equal(
            &walk.from_token("L").expect("a list"),
            &list(Vec::new())
        ));
        assert!(walk.from_token("Lr1,2|r3").is_none());
        assert!(walk.from_token("Lr1,2|Ri3;i4").is_none());
        assert!(walk.from_token("lr1,2").is_none());
        assert_eq!(
            walk.tokens(&[list(vec![pt(1, 2), tag.clone()]), list(Vec::new())]),
            None
        );
        assert_eq!(
            walk.tokens(&[list(vec![Value::Int(1)]), list(Vec::new())]),
            None
        );
    }

    #[test]
    fn a_record_of_bools_and_floats_crosses_the_seam_as_each_field_s_word() {
        let keep = shape(
            "(blue-record %root/m %root/m? (:on Bool) (:w Float) :n) (define-typed (%root/k (r m)) m r)",
        )
        .expect("a shape");
        let r = blue_lang_runtime::record::value_of(
            "%root/m",
            &["on", "w", "n"],
            vec![Value::Bool(true), Value::Float(1.5), Value::Int(3)],
        )
        .expect("a record");
        let bits = 1.5f64.to_bits().cast_signed();
        assert_eq!(
            keep.tokens(std::slice::from_ref(&r)),
            Some(vec![format!("r1,{bits},3")])
        );
        let back = keep.from_token(&format!("r1,{bits},3")).expect("a record");
        assert!(blue_lang_runtime::stdlib::blue_equal(&back, &r));
        assert!(keep.from_token("r1,2").is_none());
        let wrong = blue_lang_runtime::record::value_of(
            "%root/m",
            &["on", "w", "n"],
            vec![Value::Int(1), Value::Float(1.5), Value::Int(3)],
        )
        .expect("a record");
        assert_eq!(keep.tokens(&[wrong]), None);
    }

    #[test]
    fn a_map_of_strs_to_ints_crosses_the_seam_as_its_entries() {
        let put = shape("(define-typed (%root/p (m (Map Str Int)) (k Str)) (Map Str Int) m)")
            .expect("a shape");
        assert!(!put.in_words() && !put.plain());
        let mut entries = tatara_lisp_eval::Map::new();
        entries.insert(tatara_lisp_eval::MapKey::Str("é".into()), Value::Int(3));
        entries.insert(tatara_lisp_eval::MapKey::Str("".into()), Value::Int(-1));
        let m = Value::Map(Arc::new(entries));
        let tokens = put
            .tokens(&[m.clone(), Value::Str("a".into())])
            .expect("tokens");
        assert_eq!(tokens[1], "s61");
        let back = put.from_token(&tokens[0]).expect("a map");
        assert!(blue_lang_runtime::stdlib::blue_equal(&back, &m));
        assert!(matches!(put.from_token("m"), Some(Value::Map(e)) if e.is_empty()));
        assert!(put.from_token("m61").is_none());
        let mut keyed = tatara_lisp_eval::Map::new();
        keyed.insert(tatara_lisp_eval::MapKey::Keyword("a".into()), Value::Int(1));
        assert_eq!(
            put.tokens(&[Value::Map(Arc::new(keyed)), Value::Str("a".into())]),
            None
        );
    }

    #[test]
    fn a_str_crosses_the_seam_as_a_token_both_ways() {
        let greet =
            shape("(define-typed (%root/g (s Str) (n Int)) Str (concat s n))").expect("a shape");
        assert!(!greet.in_words() && !greet.plain());
        assert_eq!(greet.words(&[Value::Str("é".into()), Value::Int(2)]), None);
        assert_eq!(
            greet.tokens(&[Value::Str("é!".into()), Value::Int(2)]),
            Some(vec!["sc3a921".to_string(), "i2".to_string()])
        );
        assert!(matches!(greet.from_token("sc3a921"), Some(Value::Str(t)) if &*t == "é!"));
        assert!(greet.from_token("i2").is_none());
        let n = shape("(define-typed (%root/n (x Int)) Int x)").expect("a shape");
        assert!(n.plain());
        assert!(matches!(n.from_token("42"), Some(Value::Int(42))));
        assert!(matches!(n.from_token("i-7"), Some(Value::Int(-7))));
    }
}