eurydice_engine 0.1.0

Dice probability engine implementing the AnyDice language, using the Icepool algorithm
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
//! A simple tree walking interpreter.

use std::{
    collections::{HashMap, HashSet},
    sync::Arc,
};

pub(crate) use crate::value::sum_pool;
use crate::{
    ast::{
        self, BareListItem, Expression, FunctionDefinition, ListItem, PositionOrder, SetParam,
        Statement, StaticType, WithRange,
    },
    diagnostic::{
        Diagnostic, DiagnosticCode, DiagnosticLabel, EvaluationFrame, SourceId, SourceRange,
        TraceBinding, missing_return_warning, preview_value,
    },
    dice::{MultisetCrossProductIterator, Pool},
    engine::PrintEvent,
    error::{NonAdditiveSubject, ShapeMismatchError},
    operators::{apply_binary_op, apply_unary_op},
    primitives::{
        EXPLODE_ON_PRIMITIVE, EXPLODE_PRIMITIVE, Primitive, REROLL_ON_PRIMITIVE, REROLL_PRIMITIVE,
        register_primitives,
    },
    value::{display_requires_summing, sum_elements},
};
pub use crate::{
    error::{ArityMismatch, RuntimeError},
    value::{ElementValue, RuntimeValue, SymbolTable},
};

/// Runtime bindings, organized as a stack of dynamically scoped function
/// frames.
#[derive(Debug)]
struct ValEnv {
    frames: Vec<HashMap<String, RuntimeValue>>,
}

impl ValEnv {
    fn new() -> Self {
        Self {
            frames: vec![HashMap::new()],
        }
    }

    fn push_frame(&mut self) {
        self.frames.push(HashMap::new());
    }

    fn pop_frame(&mut self) {
        assert!(
            self.frames.len() > 1,
            "the global environment frame cannot be popped"
        );
        self.frames.pop();
    }

    fn get(&self, key: &str) -> Option<RuntimeValue> {
        self.frames
            .iter()
            .rev()
            .find_map(|frame| frame.get(key))
            .cloned()
    }

    fn insert(&mut self, key: String, value: RuntimeValue) {
        self.frames
            .last_mut()
            .expect("an environment always has a global frame")
            .insert(key, value);
    }

    fn contains(&self, key: &str) -> bool {
        self.frames
            .iter()
            .rev()
            .any(|frame| frame.contains_key(key))
    }

    fn names(&self) -> impl Iterator<Item = &str> {
        self.frames
            .iter()
            .rev()
            .flat_map(|frame| frame.keys().map(String::as_str))
    }
}

#[derive(Debug, Clone)]
pub enum Function {
    Primitive(&'static Primitive),
    UserDefined(Arc<UserFunction>),
}

#[derive(Debug, Clone)]
pub struct UserFunction {
    definition: FunctionDefinition,
    arg_types: Vec<Option<StaticType>>,
    source_id: SourceId,
}

impl Function {
    /// The shape each argument is converted to, where the function names one.
    ///
    /// Shape is all a signature can ask for: `:n`, `:s` and `:d` say whether an
    /// argument arrives as a single value, a sequence or a die, and nothing
    /// says anything about what is inside it.
    fn get_arg_types(&self) -> Vec<Option<StaticType>> {
        match self {
            Function::Primitive(primitive) => primitive.arg_types.to_vec(),
            Function::UserDefined(function) => function.arg_types.clone(),
        }
    }
}

struct EvalContext {
    recursion_depth: usize,
    block_depth: usize,
    source_id: SourceId,
}

impl EvalContext {
    fn new(source_id: SourceId) -> Self {
        Self {
            recursion_depth: 0,
            block_depth: 0,
            source_id,
        }
    }

    fn nested_block(&self) -> Self {
        Self {
            recursion_depth: self.recursion_depth,
            block_depth: self.block_depth + 1,
            source_id: self.source_id,
        }
    }
}

pub struct Evaluator {
    env: ValEnv,
    outputs: Vec<EvaluatedOutput>,
    functions: HashMap<String, Function>,
    symbols: SymbolTable,
    explode_depth: usize,
    recursion_depth_limit: usize,
    lowest_first: bool,
    print_callback: Option<Box<dyn FnMut(PrintEvent) + Send>>,
    source_id: SourceId,
    diagnostics: Vec<Diagnostic>,
    /// Warnings already reported, so repeated evaluations of the same
    /// expression do not build a diagnostic only to discard it.
    warned: HashSet<(DiagnosticCode, SourceRange)>,
}

/// A top-level output and its presentation metadata.
#[derive(Debug, Clone)]
pub struct EvaluatedOutput {
    pub value: RuntimeValue,
    pub name: String,
    pub field_names: Option<Vec<String>>,
}

impl Default for Evaluator {
    fn default() -> Self {
        Self::new()
    }
}

impl Evaluator {
    pub fn new() -> Self {
        let mut functions = HashMap::new();
        register_primitives(&mut functions);
        Self {
            env: ValEnv::new(),
            outputs: Vec::new(),
            functions,
            symbols: SymbolTable::default(),
            explode_depth: 2,
            recursion_depth_limit: 10,
            lowest_first: false,
            print_callback: None,
            source_id: SourceId(0),
            diagnostics: Vec::new(),
            warned: HashSet::new(),
        }
    }

    pub fn begin_submission(&mut self, source_id: SourceId) {
        self.source_id = source_id;
        self.diagnostics.clear();
        self.warned.clear();
    }

    pub fn take_diagnostics(&mut self) -> Vec<Diagnostic> {
        std::mem::take(&mut self.diagnostics)
    }

    /// The sources a diagnostic can still be asked to point into.
    ///
    /// Only function bodies outlive their submission: a diagnostic raised
    /// inside one is rendered against the source that defined it, however long
    /// ago that was. Everything else is unreachable once the submission ends.
    pub(crate) fn live_source_ids(&self) -> HashSet<SourceId> {
        self.functions
            .values()
            .filter_map(|function| match function {
                Function::UserDefined(function) => Some(function.source_id),
                Function::Primitive(_) => None,
            })
            .collect()
    }

    pub(crate) fn variable_suggestions(&self, name: &str) -> Vec<String> {
        closest_names(name, self.env.names())
    }

    pub(crate) fn function_suggestions(&self, name: &str) -> Vec<String> {
        closest_names(name, self.functions.keys().map(String::as_str))
    }

    /// Whether this warning has not been reported for this span yet.
    ///
    /// Callers check this before building a diagnostic: warnings are raised
    /// from inside evaluation loops, where the same expression can be visited
    /// once per outcome of a pool.
    fn should_warn(
        &mut self,
        code: DiagnosticCode,
        source: SourceId,
        range: ast::ByteRange,
    ) -> bool {
        self.warned.insert((code, SourceRange { source, range }))
    }

    /// `subject` is a plural phrase naming the two uses; it is always followed
    /// by "refer to the same pool".
    fn warn_pool_reuse(&mut self, source: SourceId, range: ast::ByteRange, subject: &str) {
        const CODE: DiagnosticCode = DiagnosticCode::IndependentPoolReuse;
        if !self.should_warn(CODE, source, range) {
            return;
        }
        self.diagnostics.push(Diagnostic {
            code: CODE,
            summary: "The same dice pool is sampled independently more than once".to_string(),
            primary_label: DiagnosticLabel {
                range: SourceRange { source, range },
                message: Some(format!("{subject} refer to the same pool")),
            },
            secondary_labels: Vec::new(),
            help: Some(
                "Assigning a dice pool to a variable stores its distribution; it does not roll \
                 the dice and remember one result. To reuse one roll, pass the pool to an `n` \
                 parameter and reuse that parameter inside the function."
                    .to_string(),
            ),
            fix: None,
            trace: Vec::new(),
        });
    }

    fn warn_limit(
        &mut self,
        source: SourceId,
        range: ast::ByteRange,
        code: DiagnosticCode,
        setting: &str,
        value: usize,
        summary: &str,
    ) {
        if !self.should_warn(code, source, range) {
            return;
        }
        self.diagnostics.push(Diagnostic {
            code,
            summary: summary.to_string(),
            primary_label: DiagnosticLabel {
                range: SourceRange { source, range },
                message: Some(format!("`{setting}` is currently {value}")),
            },
            secondary_labels: Vec::new(),
            help: Some(format!(
                "The returned distribution is bounded by this setting. Change it with \
                 `set \"{setting}\" to N` if you need a different bound."
            )),
            fix: None,
            trace: Vec::new(),
        });
    }

    pub fn set_print_callback(&mut self, callback: Box<dyn FnMut(PrintEvent) + Send>) {
        self.print_callback = Some(callback);
    }

    /// The declared symbols, needed to render any value that may contain one.
    pub fn symbols(&self) -> &SymbolTable {
        &self.symbols
    }

    pub fn execute(&mut self, statement: &WithRange<Statement>) -> Result<(), RuntimeError> {
        let eval_context = EvalContext::new(self.source_id);
        let result = self.execute_statement(&eval_context, statement)?;
        debug_assert!(
            result.is_none(),
            "value returned from a top-level statement"
        );
        Ok(())
    }

    pub fn take_outputs(&mut self) -> Vec<EvaluatedOutput> {
        std::mem::take(&mut self.outputs)
    }

    /// Rejects a name that a declaration has already claimed.
    ///
    /// Assignments, loop variables and function parameters all bind a variable,
    /// and a declared name is unavailable to all three, so they report it the
    /// same way. Which one it was is shown by where the diagnostic points.
    fn validate_binding_name(&self, name: &str, range: ast::ByteRange) -> Result<(), RuntimeError> {
        if !self.symbols.contains(name) {
            return Ok(());
        }
        Err(RuntimeError::Semantic {
            code: DiagnosticCode::BindingConflict,
            range,
            message: format!(
                "`{name}` is a declared symbol, so it cannot be used as a variable name"
            ),
        })
    }

    fn define_symbols(
        &mut self,
        eval_context: &EvalContext,
        members: &[WithRange<String>],
        statement_range: ast::ByteRange,
    ) -> Result<(), RuntimeError> {
        if eval_context.recursion_depth != 0 || eval_context.block_depth != 0 {
            return Err(RuntimeError::Semantic {
                code: DiagnosticCode::TopLevelOnly,
                range: statement_range,
                message: "enum declarations are only allowed at the top level".to_string(),
            });
        }
        for member in members {
            if self.symbols.contains(&member.value) {
                return Err(RuntimeError::Semantic {
                    code: DiagnosticCode::BindingConflict,
                    range: member.range,
                    message: format!("symbol {} is already defined", member.value),
                });
            }
            if self.env.contains(&member.value) {
                return Err(RuntimeError::Semantic {
                    code: DiagnosticCode::BindingConflict,
                    range: member.range,
                    message: format!("{} is already bound as a variable", member.value),
                });
            }
            let symbol = self.symbols.define(member.value.clone());
            self.env.insert(
                member.value.clone(),
                RuntimeValue::Element(ElementValue::Symbol(symbol)),
            );
        }
        Ok(())
    }

    /// Executes a statement; returns a value if a `return` statement is
    /// encountered.
    fn execute_statement(
        &mut self,
        eval_context: &EvalContext,
        statement: &WithRange<Statement>,
    ) -> Result<Option<RuntimeValue>, RuntimeError> {
        match &statement.value {
            Statement::Assignment { name, value } => {
                self.validate_binding_name(&name.value, name.range)?;
                let value = self.evaluate(eval_context, value)?;
                self.env.insert(name.value.clone(), value);
            }
            Statement::FunctionDefinition(fd) => {
                if self.should_warn(
                    DiagnosticCode::MissingResult,
                    eval_context.source_id,
                    fd.name.range,
                ) && let Some(warning) = missing_return_warning(eval_context.source_id, fd)
                {
                    self.diagnostics.push(warning);
                }
                for arg in &fd.args {
                    self.validate_binding_name(&arg.value.name, arg.range)?;
                }
                let arg_types = fd.args.iter().map(|arg| arg.value.ty).collect();
                self.functions.insert(
                    fd.name.value.clone(),
                    Function::UserDefined(Arc::new(UserFunction {
                        definition: fd.clone(),
                        arg_types,
                        source_id: eval_context.source_id,
                    })),
                );
            }
            Statement::SymbolDefinitions(members) => {
                self.define_symbols(eval_context, members, statement.range)?;
            }
            Statement::Output {
                expr,
                named,
                labeled,
            } => {
                if eval_context.recursion_depth != 0 {
                    return Err(RuntimeError::OutputNotAtTopLevel {
                        range: statement.range,
                    });
                }
                let value = self.evaluate(eval_context, expr)?;
                // `output` displays the summed pool, so reject one that cannot be
                // summed here: the conversion in `output.rs` runs after evaluation and
                // has no way to report an error.
                let summed = match &value {
                    RuntimeValue::Pool(pool) => Some(
                        sum_pool(pool)
                            .map_err(|error| error.into_error(expr.range, "displaying a pool"))?,
                    ),
                    _ => None,
                };
                let displayed: Vec<&ElementValue> = match (&value, &summed) {
                    (_, Some(pool)) => pool
                        .ordered_outcomes()
                        .iter()
                        .map(|(outcome, _)| outcome)
                        .collect(),
                    (RuntimeValue::List(values), None) => values.iter().collect(),
                    (RuntimeValue::Element(value), None) => vec![value],
                    (RuntimeValue::Pool(_), None) => {
                        unreachable!("a pool value is always summed above")
                    }
                };
                // Every outcome agrees on its shape from here on, so the first
                // one speaks for all of them.
                reject_mixed_output_shapes(&displayed, expr.range)?;
                let field_names = if let Some(labels) = labeled {
                    let Some(ElementValue::Tuple(fields)) = displayed.first() else {
                        return Err(RuntimeError::LabelsOnNonTupleOutput {
                            range: labels.range,
                            value_range: expr.range,
                            value,
                        });
                    };
                    if labels.value.len() != fields.len() {
                        return Err(RuntimeError::OutputLabelCountMismatch {
                            range: labels.range,
                            expected: fields.len(),
                            found: labels.value.len(),
                        });
                    }
                    Some(
                        labels
                            .value
                            .iter()
                            .map(|label| {
                                interpolate_variable_names(label, &self.env, &self.symbols)
                            })
                            .collect::<Result<Vec<_>, _>>()?,
                    )
                } else {
                    None
                };
                let name = match named {
                    Some(name) => interpolate_variable_names(name, &self.env, &self.symbols)?,
                    None => format!("output {}", self.outputs.len() + 1),
                };
                // Hand on the pool already summed above, so that displaying it
                // does not repeat the summation.
                let value = match (&value, summed) {
                    (RuntimeValue::Pool(pool), Some(summed)) if display_requires_summing(pool) => {
                        RuntimeValue::Pool(Arc::new(summed))
                    }
                    _ => value,
                };
                self.outputs.push(EvaluatedOutput {
                    value,
                    name,
                    field_names,
                });
            }
            Statement::Print { expr, named } => {
                let value = self.evaluate(eval_context, expr)?;
                let name = named
                    .as_ref()
                    .map(|name| interpolate_variable_names(name, &self.env, &self.symbols))
                    .transpose()?;
                let event = PrintEvent {
                    name,
                    value: value.display(&self.symbols).to_string(),
                };
                if let Some(callback) = &mut self.print_callback {
                    callback(event);
                }
            }
            Statement::Return { value } => {
                if eval_context.recursion_depth == 0 {
                    return Err(RuntimeError::ReturnOutsideFunction {
                        range: statement.range,
                    });
                }
                let value = self.evaluate(eval_context, value)?;
                return Ok(Some(value));
            }
            Statement::If {
                condition,
                then_block,
                else_block,
            } => {
                let condition_value = self.evaluate(eval_context, condition)?;
                let cond_value = match condition_value {
                    RuntimeValue::Element(ElementValue::AdditiveIdentity) => 0,
                    RuntimeValue::Element(ElementValue::Int(i)) => i,
                    _ => {
                        return Err(RuntimeError::InvalidCondition {
                            range: condition.range,
                            value: condition_value,
                        });
                    }
                };
                let block = if cond_value != 0 {
                    then_block
                } else if let Some(block) = else_block {
                    block
                } else {
                    return Ok(None);
                };
                let nested_context = eval_context.nested_block();
                for statement in block {
                    let res = self.execute_statement(&nested_context, statement)?;
                    if res.is_some() {
                        return Ok(res);
                    }
                }
            }
            Statement::Loop {
                variable,
                range_expression,
                body,
            } => {
                self.validate_binding_name(&variable.value, variable.range)?;
                let range = self.evaluate(eval_context, range_expression)?;
                let range = match range {
                    RuntimeValue::List(range) => range,
                    _ => {
                        return Err(RuntimeError::LoopOverNonSequence {
                            range: range_expression.range,
                            value: range,
                        });
                    }
                };
                let nested_context = eval_context.nested_block();
                for value in range.iter() {
                    self.env
                        .insert(variable.value.clone(), RuntimeValue::Element(value.clone()));
                    for statement in body {
                        let res = self.execute_statement(&nested_context, statement)?;
                        if res.is_some() {
                            return Ok(res);
                        }
                    }
                }
            }
            Statement::Set(s) => {
                if eval_context.recursion_depth != 0 {
                    return Err(RuntimeError::SetNotAtTopLevel {
                        range: statement.range,
                    });
                }
                match s {
                    SetParam::PositionOrder(order) => {
                        self.lowest_first = *order == PositionOrder::Ascending
                    }
                    SetParam::ExplodeDepth(d) => self.explode_depth = *d,
                    SetParam::MaximumFunctionDepth(d) => self.recursion_depth_limit = *d,
                }
            }
        }
        Ok(None)
    }

    fn evaluate(
        &mut self,
        eval_context: &EvalContext,
        expression: &WithRange<Expression>,
    ) -> Result<RuntimeValue, RuntimeError> {
        match &expression.value {
            Expression::UnaryOp { op, operand } => {
                let value = self.evaluate(eval_context, operand)?;
                apply_unary_op(op, &value)
            }
            Expression::BinaryOp { op, left, right } => {
                let left_value = self.evaluate(eval_context, left)?;
                let right_value = self.evaluate(eval_context, right)?;
                if same_pool(&left_value, &right_value) {
                    let subject = match (&left.value, &right.value) {
                        (Expression::Reference(left), Expression::Reference(right))
                            if left == right =>
                        {
                            format!("Both uses of `{left}`")
                        }
                        (Expression::Reference(left), Expression::Reference(right)) => {
                            format!("`{left}` and `{right}`")
                        }
                        _ => "Both operands".to_string(),
                    };
                    self.warn_pool_reuse(eval_context.source_id, op.range, &subject);
                }
                Ok(apply_binary_op(
                    op,
                    &left_value,
                    left.range,
                    &right_value,
                    self.lowest_first,
                )?)
            }
            Expression::List(list) => {
                let items = list
                    .items
                    .iter()
                    .map(|item| self.evaluate_list_literal_item(eval_context, item))
                    .collect::<Result<Vec<_>, _>>()?;
                // A sequence holds whatever it was written with; nothing here
                // asks the items to agree. An operation that later needs them
                // to is where a disagreement surfaces.
                let mut flattened = Vec::new();
                for (item, source) in items.iter().zip(list.items.iter()) {
                    flattened.extend(item.to_list(1).map_err(|mismatch| {
                        mismatch.into_error(
                            list_item_range(source),
                            "flattening a pool into a sequence",
                            NonAdditiveSubject::Sequence(item.elements().len()),
                        )
                    })?);
                }
                Ok(RuntimeValue::List(Arc::new(flattened)))
            }
            Expression::FunctionCall { name, args } => {
                let func = self
                    .functions
                    .get(&name.value)
                    .ok_or_else(|| RuntimeError::UndefinedFunction {
                        range: expression.range,
                        name: name.value.clone(),
                        arity_mismatch: arity_mismatch(&self.functions, &name.value, args),
                    })?
                    .clone();
                let ranges = args.iter().map(|arg| arg.range).collect::<Vec<_>>();
                let args = args
                    .iter()
                    .map(|arg| self.evaluate(eval_context, arg))
                    .collect::<Result<Vec<_>, _>>()?;
                let args = args
                    .into_iter()
                    .zip(ranges.iter())
                    .map(|(arg, range)| WithRange {
                        value: arg,
                        range: *range,
                    })
                    .collect::<Vec<_>>();
                let func_with_range = WithRange {
                    value: func,
                    range: name.range,
                };
                self.evaluate_function_call(eval_context, &func_with_range, args)
            }
            Expression::Reference(name) => {
                self.env
                    .get(name)
                    .ok_or_else(|| RuntimeError::UndefinedReference {
                        range: expression.range,
                        name: name.clone(),
                    })
            }
            Expression::Int(i) => Ok(RuntimeValue::Element(ElementValue::Int(*i))),
        }
    }

    /// Evaluates a list literal item.
    ///
    /// This doesn't take precomputed values, because literals can contain
    /// special non-expression syntax.
    fn evaluate_list_literal_item(
        &mut self,
        eval_context: &EvalContext,
        item: &ListItem,
    ) -> Result<RuntimeValue, RuntimeError> {
        let repeat_count = match &item.repeat {
            Some(repeat) => match self.evaluate(eval_context, repeat)? {
                RuntimeValue::Element(ElementValue::AdditiveIdentity) => 0,
                RuntimeValue::Element(ElementValue::Int(i)) => {
                    usize::try_from(i.max(0)).expect("converting a positive i32 into usize")
                }
                repeat_value => {
                    return Err(RuntimeError::InvalidRepeatExpression {
                        range: repeat.range,
                        value: repeat_value,
                    });
                }
            },
            None => 1,
        };
        let base = match &item.item {
            BareListItem::Expr(expression) => self.evaluate(eval_context, expression),
            BareListItem::Range(start_expr, end_expr) => {
                let start = self.evaluate(eval_context, start_expr)?;
                let start = match start {
                    RuntimeValue::Element(ElementValue::AdditiveIdentity) => 0,
                    RuntimeValue::Element(ElementValue::Int(i)) => i,
                    _ => {
                        return Err(RuntimeError::RangeHasNonSequenceEndpoints {
                            range: start_expr.range,
                            value: start,
                        });
                    }
                };
                let end = self.evaluate(eval_context, end_expr)?;
                let end = match end {
                    RuntimeValue::Element(ElementValue::AdditiveIdentity) => 0,
                    RuntimeValue::Element(ElementValue::Int(i)) => i,
                    _ => {
                        return Err(RuntimeError::RangeHasNonSequenceEndpoints {
                            range: end_expr.range,
                            value: end,
                        });
                    }
                };
                Ok(RuntimeValue::List(Arc::new(
                    (start..=end).map(ElementValue::Int).collect(),
                )))
            }
        }?;
        let item_range = match &item.item {
            BareListItem::Expr(expression) => expression.range,
            BareListItem::Range(start_expr, end_expr) => {
                (start_expr.range.start, end_expr.range.end).into()
            }
        };
        let elements = base.to_list(repeat_count).map_err(|mismatch| {
            mismatch.into_error(
                item_range,
                "flattening a pool into a sequence",
                NonAdditiveSubject::Sequence(base.elements().len()),
            )
        })?;
        Ok(RuntimeValue::List(Arc::new(elements)))
    }

    fn evaluate_function_call(
        &mut self,
        eval_context: &EvalContext,
        function: &WithRange<Function>,
        args: Vec<WithRange<RuntimeValue>>,
    ) -> Result<RuntimeValue, RuntimeError> {
        if eval_context.recursion_depth >= self.recursion_depth_limit {
            self.warn_limit(
                eval_context.source_id,
                function.range,
                DiagnosticCode::MaximumFunctionDepth,
                "maximum function depth",
                self.recursion_depth_limit,
                "Maximum function depth stopped this call",
            );
            return Ok(RuntimeValue::empty_list());
        }

        // First, convert the arguments to the expected types.
        let expected_types = function.value.get_arg_types();
        if expected_types.len() != args.len() {
            panic!(
                "wrong number of arguments; this should have been caught by function name matching"
            );
        }
        for left_index in 0..args.len() {
            for right_index in left_index + 1..args.len() {
                let samples_left =
                    expected_types[left_index].is_some_and(|shape| shape != StaticType::Pool);
                let samples_right =
                    expected_types[right_index].is_some_and(|shape| shape != StaticType::Pool);
                if samples_left
                    && samples_right
                    && same_pool(&args[left_index].value, &args[right_index].value)
                {
                    self.warn_pool_reuse(
                        eval_context.source_id,
                        function.range,
                        &format!("Arguments {} and {}", left_index + 1, right_index + 1),
                    );
                }
            }
        }
        let arg_ranges = args.iter().map(|arg| arg.range).collect::<Vec<_>>();
        let args = args
            .into_iter()
            .zip(expected_types.iter())
            .map(|(arg, expected)| coerce_arg(arg.value, *expected, arg.range))
            .collect::<Result<Vec<_>, _>>()?;

        // This vector will contain references to pools which match an int or list
        // arguments. These are the pools over which we need to iterate to get
        // the argument values.
        let mut pools = Vec::new();
        // Contains (index, is_element) for the corresponding pool.
        let mut pool_iterator_info = Vec::new();
        for (i, (arg, expected_type)) in args.iter().zip(expected_types.iter()).enumerate() {
            let pool = match arg {
                RuntimeValue::Pool(p) => Some(p),
                _ => None,
            };
            if let (Some(p), Some(shape)) = (pool, expected_type) {
                if !matches!(shape, StaticType::Int | StaticType::List) {
                    continue;
                }
                // If the expected type is an Int, `coerce_arg` has already turned the pool into
                // a sum, with outcomes of length 1.
                pools.push(p);
                pool_iterator_info.push((i, *shape == StaticType::Int));
            }
        }

        if pools.is_empty() {
            return self.call_function(eval_context, function, &args, &arg_ranges);
        }

        let cross_product_iterator = MultisetCrossProductIterator::new(
            pools.iter().map(|p| p.multiset_iterator()).collect(),
        );

        let mut args = args.clone();
        let mut results = Vec::new();
        for (values, weight) in cross_product_iterator {
            for ((i, is_element), value) in pool_iterator_info.iter().zip(values.iter()) {
                if *is_element {
                    args[*i] = RuntimeValue::Element(value[0].clone());
                } else {
                    args[*i] = RuntimeValue::List(Arc::new(reverse_if(!self.lowest_first, value)));
                }
            }
            results.push((
                self.call_function(eval_context, function, &args, &arg_ranges)?,
                weight,
            ));
        }

        // Each result becomes one distribution, and the distributions are
        // mixed. Nothing requires the results to agree with each other: a call
        // that returns a number for one multiset and a tuple for another
        // produces a die that holds both, and it is displaying or summing that
        // die which says they cannot be reconciled.
        const COMBINING: &str = "combining the results of a function evaluated over a pool";
        let mut result_distributions = Vec::new();
        for (result, weight) in results {
            if let RuntimeValue::Pool(ref pool) = result {
                // The empty die is ignored in this context, but the empty list is not.
                if pool.ordered_outcomes().is_empty() {
                    continue;
                }
            }
            let pool = result.to_pool().map_err(|mismatch| {
                mismatch.into_error(
                    function.range,
                    COMBINING,
                    NonAdditiveSubject::Sequence(result.elements().len()),
                )
            })?;
            let summed =
                sum_pool(&pool).map_err(|error| error.into_error(function.range, COMBINING))?;
            result_distributions.push((weight, summed));
        }
        Ok(RuntimeValue::Pool(Arc::new(Pool::from_mixture(
            result_distributions,
        ))))
    }

    fn call_function(
        &mut self,
        eval_context: &EvalContext,
        function: &WithRange<Function>,
        args: &[RuntimeValue],
        arg_ranges: &[ast::ByteRange],
    ) -> Result<RuntimeValue, RuntimeError> {
        match &function.value {
            Function::Primitive(primitive) => {
                if transform_depth_affects_result(primitive.identifier, args) {
                    self.warn_limit(
                        eval_context.source_id,
                        function.range,
                        DiagnosticCode::ExplodeDepth,
                        "explode depth",
                        self.explode_depth,
                        "Explode depth bounds this distribution",
                    );
                }
                (primitive.execute)(
                    args,
                    crate::primitives::PrimitiveCtx {
                        arg_ranges,
                        explode_depth: self.explode_depth,
                        lowest_first: self.lowest_first,
                        function_range: function.range,
                        identifier: primitive.identifier,
                    },
                )
            }
            Function::UserDefined(user_function) => {
                self.env.push_frame();
                for (arg, formal) in args.iter().zip(user_function.definition.args.iter()) {
                    self.env.insert(formal.value.name.clone(), arg.clone());
                }
                let new_context = EvalContext {
                    recursion_depth: eval_context.recursion_depth + 1,
                    block_depth: eval_context.block_depth + 1,
                    source_id: user_function.source_id,
                };
                let result: Result<RuntimeValue, RuntimeError> = (|| {
                    let mut result = None;
                    for statement in &user_function.definition.body {
                        result = self.execute_statement(&new_context, statement)?;
                        if result.is_some() {
                            break;
                        }
                    }
                    // If there's no result, there was no return statement in the function.
                    Ok(result.unwrap_or_else(RuntimeValue::empty_pool))
                })();
                self.env.pop_frame();
                result.map_err(|source| {
                    let range = source.range();
                    RuntimeError::InFunction {
                        range,
                        source: Box::new(source),
                        body_source: user_function.source_id,
                        frame: Box::new(EvaluationFrame {
                            function: user_function.definition.name.value.clone(),
                            call: SourceRange {
                                source: eval_context.source_id,
                                range: function.range,
                            },
                            definition: Some(SourceRange {
                                source: user_function.source_id,
                                range: user_function.definition.name.range,
                            }),
                            bindings: user_function
                                .definition
                                .args
                                .iter()
                                .zip(args)
                                .map(|(formal, value)| TraceBinding {
                                    name: formal.value.name.clone(),
                                    value: preview_value(value, &self.symbols),
                                })
                                .collect(),
                        }),
                    }
                })
            }
        }
    }
}

/// Splits a function identifier such as `"field {} of {}"` into its words and
/// its number of argument positions.
fn identifier_shape(identifier: &str) -> (String, usize) {
    let mut words = Vec::new();
    let mut arity = 0;
    for token in identifier.split_whitespace() {
        if token == "{}" {
            arity += 1;
        } else {
            words.push(token);
        }
    }
    (words.join(" "), arity)
}

/// Detects a call that did not resolve, but whose words name a function taking
/// a different number of arguments.
///
/// This is overwhelmingly caused by two adjacent arguments being parsed as one
/// expression: `d` binds tighter than argument separation, so `[tuple d6 d8]`
/// reads as the single argument `(d6)d8`. Reporting the mismatch turns a
/// confusing "no such function" into an actionable fix.
fn arity_mismatch(
    functions: &HashMap<String, Function>,
    name: &str,
    args: &[WithRange<Expression>],
) -> Option<ArityMismatch> {
    let (words, arity) = identifier_shape(name);
    let mut available = functions
        .keys()
        .filter_map(|identifier| {
            let (other_words, other_arity) = identifier_shape(identifier);
            (other_words == words && other_arity != arity).then_some(other_arity)
        })
        .collect::<Vec<_>>();
    if available.is_empty() {
        return None;
    }
    available.sort_unstable();
    available.dedup();
    // A comma can only be missing if the call passed too few arguments; if
    // every known arity is smaller, the caller passed too many instead.
    let comma_insertion = available
        .iter()
        .any(|other| *other > arity)
        .then(|| comma_insertion(args))
        .flatten();
    Some(ArityMismatch {
        words,
        available,
        found: arity,
        comma_insertion,
    })
}

/// Where a comma would split a single argument that is really two dice.
///
/// `d` binds tighter than argument separation, so `[tuple d6 d8]` parses as the
/// one argument `(d6)d8`. Wherever the left side of a `d` is itself a dice
/// roll, the two sides were written as separate arguments, and the leftmost
/// such `d` is where the first comma belongs. Reading this off the parse tree
/// rather than the source text means the fix cannot disagree with how the call
/// was actually parsed.
fn comma_insertion(args: &[WithRange<Expression>]) -> Option<usize> {
    let [only] = args else {
        return None;
    };
    let mut expression = &only.value;
    let mut insertion = None;
    while let Expression::BinaryOp { op, left, .. } = expression {
        if op.value != ast::BinaryOp::D || !rolls_dice(&left.value) {
            break;
        }
        insertion = Some(left.range.end);
        expression = &left.value;
    }
    insertion
}

/// Whether an expression rolls dice at its outermost level, so that a `d` to
/// its right cannot have been reading it as a die count.
fn rolls_dice(expression: &Expression) -> bool {
    match expression {
        Expression::UnaryOp { op, .. } => op.value == ast::UnaryOp::D,
        Expression::BinaryOp { op, left, .. } => {
            op.value == ast::BinaryOp::D || rolls_dice(&left.value)
        }
        _ => false,
    }
}

/// Rejects an output whose outcomes cannot share one shape.
///
/// A displayed distribution has one shape, so this is the last chance to reject
/// outcomes that do not agree on it — and the only one, since nothing on the
/// way here required them to. This rejects:
///
/// - outcomes of different *shapes*, a number in one and a tuple in another, or
///   tuples of different arity. `{1, [tuple 1 2]}` is a perfectly good sequence
///   that `print` will show; it just cannot be drawn as one distribution.
///
/// [`crate::output`] runs after evaluation and cannot report an error, so
/// anything it would rather not meet has to be stopped here.
fn reject_mixed_output_shapes(
    outcomes: &[&ElementValue],
    range: ast::ByteRange,
) -> Result<(), RuntimeError> {
    let shape_of = |outcome: &ElementValue| match outcome {
        ElementValue::Tuple(fields) => Some(fields.len()),
        _ => None,
    };
    // The empty sum has no shape of its own — it takes the one around it — so
    // it is not what settles the shape and never disagrees with it.
    let shaped = |outcome: &&&ElementValue| !matches!(outcome, ElementValue::AdditiveIdentity);
    let Some(first) = outcomes.iter().find(shaped) else {
        return Ok(());
    };
    let shape = shape_of(first);
    if let Some(other) = outcomes
        .iter()
        .filter(shaped)
        .find(|outcome| shape_of(outcome) != shape)
    {
        return Err(RuntimeError::ShapeMismatch(Box::new(ShapeMismatchError {
            range,
            action: "displaying a distribution",
            first: (*first).clone(),
            second: (*other).clone(),
        })));
    }
    Ok(())
}

/// Where a list element was written, so a diagnostic can point at it.
fn list_item_range(item: &ListItem) -> ast::ByteRange {
    match &item.item {
        BareListItem::Expr(expr) => expr.range,
        BareListItem::Range(start, end) => ast::ByteRange {
            start: start.range.start,
            end: end.range.end,
        },
    }
}

/// Converts an argument to the shape its parameter is declared with.
///
/// Only the shape: `:n`, `:s` and `:d` say how a value arrives, never what it
/// holds. The one conversion that can fail is summing, which a sequence or pool
/// of values that cannot be added discovers here.
fn coerce_arg(
    arg: RuntimeValue,
    expected: Option<StaticType>,
    range: ast::ByteRange,
) -> Result<RuntimeValue, RuntimeError> {
    let Some(expected) = expected else {
        return Ok(arg);
    };
    const SUMMING: &str = "passing a value to a parameter that expects a single value";
    let coerced = match (arg, expected) {
        (value @ RuntimeValue::Element(_), StaticType::Int) => Ok(value),
        (RuntimeValue::Element(value), StaticType::List) => {
            Ok(RuntimeValue::List(Arc::new(vec![value])))
        }
        (RuntimeValue::Element(value), StaticType::Pool) => Ok(RuntimeValue::Pool(Arc::new(
            Pool::from_list(1, vec![value]),
        ))),
        (RuntimeValue::List(list), StaticType::Int) => sum_elements(&list)
            .map(RuntimeValue::Element)
            .map_err(|mismatch| {
                mismatch.into_error(range, SUMMING, NonAdditiveSubject::Sequence(list.len()))
            }),
        (value @ RuntimeValue::List(_), StaticType::List) => Ok(value),
        (RuntimeValue::List(list), StaticType::Pool) => Ok(RuntimeValue::Pool(Arc::new(
            Pool::from_list(1, (*list).clone()),
        ))),
        (RuntimeValue::Pool(pool), StaticType::Int) => {
            let summed = sum_pool(&pool).map_err(|error| error.into_error(range, SUMMING))?;
            Ok(RuntimeValue::Pool(Arc::new(summed)))
        }
        (value @ RuntimeValue::Pool(_), _) => Ok(value),
    }?;
    // Where a single value is required and the empty sum has still met nothing
    // to take its shape from, it becomes the integer 0.
    if expected == StaticType::Int
        && matches!(
            coerced,
            RuntimeValue::Element(ElementValue::AdditiveIdentity)
        )
    {
        return Ok(RuntimeValue::Element(ElementValue::Int(0)));
    }
    Ok(coerced)
}

fn interpolate_variable_names(
    template: &WithRange<String>,
    vars: &ValEnv,
    symbols: &SymbolTable,
) -> Result<String, RuntimeError> {
    let mut result = String::new();
    let mut char_iter = template.value.chars();
    while let Some(chr) = char_iter.next() {
        if chr == '[' {
            let mut valid_end = false;
            let mut name = String::new();
            for chr in char_iter.by_ref() {
                if chr == ']' {
                    valid_end = true;
                    break;
                }
                name.push(chr);
            }
            if !valid_end
                || name.is_empty()
                || name.chars().any(|c| !c.is_ascii_uppercase() && c != '_')
            {
                result.push('[');
                result.push_str(&name);
                if valid_end {
                    result.push(']');
                }
            } else if let Some(value) = vars.get(&name) {
                // A name is prose, so the empty sum reads better as the `0` it
                // stands for than as `𝑒`.
                let value = match value {
                    RuntimeValue::Element(ElementValue::AdditiveIdentity) => {
                        RuntimeValue::Element(ElementValue::Int(0))
                    }
                    value => value,
                };
                result.push_str(&value.display(symbols).to_string());
            } else {
                return Err(RuntimeError::UndefinedReference {
                    range: template.range,
                    name,
                });
            }
        } else {
            result.push(chr);
        }
    }
    Ok(result)
}

fn reverse_if<T: Clone>(should_reverse: bool, values: &[T]) -> Vec<T> {
    if should_reverse {
        values.iter().cloned().rev().collect()
    } else {
        values.into()
    }
}

fn same_pool(left: &RuntimeValue, right: &RuntimeValue) -> bool {
    matches!(
        (left, right),
        (RuntimeValue::Pool(left), RuntimeValue::Pool(right))
            if Arc::ptr_eq(left, right)
    )
}

fn transform_depth_affects_result(identifier: &str, args: &[RuntimeValue]) -> bool {
    // Taken from the registry rather than matched by prefix, so renaming or
    // adding a primitive cannot silently change which calls are bounded.
    let bounded_by_depth = [
        EXPLODE_PRIMITIVE.identifier,
        EXPLODE_ON_PRIMITIVE.identifier,
        REROLL_PRIMITIVE.identifier,
        REROLL_ON_PRIMITIVE.identifier,
    ];
    if !bounded_by_depth.contains(&identifier) {
        return false;
    }
    let Some(RuntimeValue::Pool(pool)) = args.first() else {
        return false;
    };
    if pool.ordered_outcomes().is_empty() {
        return false;
    }
    let Some(condition) = args.get(1) else {
        // Bare explode/reroll triggers on the highest outcome, which exists for
        // every nonempty pool.
        return true;
    };
    let RuntimeValue::List(condition) = condition else {
        return false;
    };
    pool.ordered_outcomes()
        .iter()
        .any(|(outcome, _)| condition.contains(outcome))
}

fn closest_names<'a>(needle: &str, candidates: impl Iterator<Item = &'a str>) -> Vec<String> {
    let mut ranked = candidates
        .map(|candidate| (edit_distance(needle, candidate), candidate))
        .collect::<Vec<_>>();
    ranked.sort();
    ranked.dedup_by(|left, right| left.1 == right.1);
    let threshold = 2.max(needle.chars().count() / 3);
    ranked
        .into_iter()
        .filter(|(distance, _)| *distance <= threshold)
        .take(3)
        .map(|(_, candidate)| candidate.to_string())
        .collect()
}

fn edit_distance(left: &str, right: &str) -> usize {
    let right = right.chars().collect::<Vec<_>>();
    let mut previous = (0..=right.len()).collect::<Vec<_>>();
    for (left_index, left_character) in left.chars().enumerate() {
        let mut current = vec![left_index + 1];
        for (right_index, right_character) in right.iter().enumerate() {
            current.push(
                (previous[right_index + 1] + 1)
                    .min(current[right_index] + 1)
                    .min(previous[right_index] + usize::from(left_character != *right_character)),
            );
        }
        previous = current;
    }
    previous[right.len()]
}

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

    #[test]
    fn test_interpolate_variable_names() {
        fn ranged(s: &str) -> WithRange<String> {
            WithRange {
                value: s.to_string(),
                range: ast::ByteRange {
                    start: 0,
                    end: s.len(),
                },
            }
        }

        let symbols = SymbolTable::default();
        let mut env = ValEnv::new();
        env.insert("A".to_string(), 1.into());
        env.insert("B".to_string(), 2.into());
        env.insert("C".to_string(), 3.into());
        env.insert("_MY_VAR".to_string(), 4.into());
        env.insert(
            "IDENTITY".to_string(),
            RuntimeValue::Element(ElementValue::AdditiveIdentity),
        );
        assert_eq!(
            interpolate_variable_names(&ranged("A + B = [A] + [B]"), &env, &symbols).unwrap(),
            "A + B = 1 + 2"
        );
        assert!(
            interpolate_variable_names(&ranged("A + B = [A] + [B] + [INVALID]"), &env, &symbols)
                .is_err()
        );
        assert_eq!(
            interpolate_variable_names(&ranged("A + B = [A] + [B] + [invalid]"), &env, &symbols)
                .unwrap(),
            "A + B = 1 + 2 + [invalid]"
        );
        assert_eq!(
            interpolate_variable_names(&ranged("A + B = [A] + [B] + [C"), &env, &symbols).unwrap(),
            "A + B = 1 + 2 + [C"
        );
        assert_eq!(
            interpolate_variable_names(&ranged("[_MY_VAR], [IDENTITY]"), &env, &symbols).unwrap(),
            "4, 0"
        );
    }

    #[test]
    fn additive_identity_becomes_zero_where_an_argument_must_be_an_int() {
        let range = ast::ByteRange { start: 0, end: 0 };

        for argument in [
            RuntimeValue::Element(ElementValue::AdditiveIdentity),
            // An empty sequence sums to the empty sum on its way to an int.
            RuntimeValue::empty_list(),
        ] {
            assert_eq!(
                coerce_arg(argument.clone(), Some(StaticType::Int), range).unwrap(),
                RuntimeValue::Element(ElementValue::Int(0)),
                "{:?}",
                argument
            );
        }
    }

    #[test]
    fn additive_identity_is_inspectable_in_print_but_defaulted_in_output() {
        use std::sync::{Arc, Mutex};

        let printed = Arc::new(Mutex::new(None));
        let callback_result = Arc::clone(&printed);
        let mut evaluator = Evaluator::new();
        evaluator.set_print_callback(Box::new(move |event| {
            *callback_result.lock().unwrap() = Some((event.value, event.name));
        }));

        let statements = crate::grammar::BodyParser::new()
            .parse(r#"X: {} + {} print X named "[X]" output X named "[X]""#)
            .unwrap();
        for statement in statements {
            evaluator.execute(&statement).unwrap();
        }

        assert_eq!(
            printed.lock().unwrap().as_ref().unwrap(),
            &("\u{1d452}".to_string(), Some("0".to_string()))
        );
        let output = evaluator.take_outputs().remove(0);
        assert_eq!(output.name, "0");
        let distribution =
            crate::output::Distribution::from_runtime(output.value, None, evaluator.symbols());
        assert_eq!(
            distribution.entries().collect::<Vec<_>>(),
            [(&[0][..], 1.0)]
        );
    }

    #[test]
    fn test_division_by_zero() {
        use crate::ast::{BinaryOp, ByteRange};

        let left = 5.into();
        let right = 0.into();
        let op = WithRange {
            value: BinaryOp::Div,
            range: ByteRange { start: 0, end: 1 },
        };

        let result = apply_binary_op(&op, &left, ByteRange { start: 0, end: 1 }, &right, false);
        match result {
            Err(RuntimeError::MathError { message, .. }) => {
                assert!(message.contains("Cannot divide 5 by zero"));
            }
            _ => panic!("Expected MathError for division by zero"),
        }
    }

    #[test]
    fn test_negative_exponentiation() {
        use crate::ast::{BinaryOp, ByteRange};

        let left = 2.into();
        let right = (-3).into();
        let op = WithRange {
            value: BinaryOp::Pow,
            range: ByteRange { start: 0, end: 1 },
        };

        let result = apply_binary_op(&op, &left, ByteRange { start: 0, end: 1 }, &right, false);
        match result {
            Err(RuntimeError::MathError { message, .. }) => {
                assert!(message.contains("Cannot raise 2 to negative power -3"));
            }
            _ => panic!("Expected MathError for negative exponentiation"),
        }
    }

    /// Every overflowing operation names itself and the operands that
    /// overflowed, so the message points at the arithmetic that failed.
    #[test]
    fn test_arithmetic_overflow() {
        use crate::ast::{BinaryOp, ByteRange};

        for (binary_op, left, right, expected_operation, expected_operands) in [
            (
                BinaryOp::Add,
                i32::MAX,
                1,
                "Addition overflow",
                i32::MAX.to_string(),
            ),
            (
                BinaryOp::Sub,
                i32::MIN,
                1,
                "Subtraction overflow",
                i32::MIN.to_string(),
            ),
            (
                BinaryOp::Mul,
                i32::MAX,
                2,
                "Multiplication overflow",
                i32::MAX.to_string(),
            ),
            // 2^32 overflows i32.
            (BinaryOp::Pow, 2, 32, "Power overflow", "2 ^ 32".to_string()),
        ] {
            let range = ByteRange { start: 0, end: 1 };
            let op = WithRange {
                value: binary_op,
                range,
            };
            let left: RuntimeValue = left.into();
            let right: RuntimeValue = right.into();

            let result = apply_binary_op(&op, &left, range, &right, false);

            let Err(RuntimeError::MathError { message, .. }) = result else {
                panic!("expected a MathError for {expected_operation}, got {result:?}");
            };
            assert!(message.contains(expected_operation), "{message}");
            assert!(message.contains(&expected_operands), "{message}");
        }
    }
}