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
//! High-level source-to-distribution engine API.

use std::collections::HashSet;

#[cfg(feature = "serde")]
use serde::Serialize;

use crate::{
    ast::{Statement, WithRange},
    diagnostic::{
        Diagnostic, DiagnosticSource, Diagnostics, SourceId, UndefinedName, add_later_definition,
        parse_error, runtime_diagnostic, undefined_name,
    },
    eval::Evaluator,
    grammar,
    output::Distribution,
};

/// A named distribution produced by an `output` statement.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[non_exhaustive]
pub struct NamedDistribution {
    /// The output's name, either given by the user or generated by the engine.
    pub name: String,
    /// The distribution produced by the `output` statement.
    pub distribution: Distribution,
}

/// Outputs and diagnostics produced by one submission.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[must_use]
#[non_exhaustive]
pub struct RunReport {
    /// Outputs produced by the submission's `output` statements, in execution
    /// order.
    pub outputs: Vec<NamedDistribution>,
    /// Diagnostics produced by the submission.
    pub diagnostics: Diagnostics,
}

/// A `print` statement's name and value.
///
/// This is passed to the callback set by [`Engine::set_print_callback`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PrintEvent {
    /// The name given by the user, if any.
    pub name: Option<String>,
    /// The string representation of the printed value.
    pub value: String,
}

/// A parsed Eurydice program, ready to execute.
///
/// A program may depend on definitions from earlier submissions to an
/// [`Engine`]. It can be executed on any engine, any number of times; each
/// execution is a fresh submission.
#[derive(Debug, Clone)]
pub struct Program {
    /// The source this program was parsed from.
    text: String,
    /// This program's parsed AST.
    statements: Vec<WithRange<Statement>>,
}

impl Program {
    /// Compiles source without running it in an engine session.
    ///
    /// A parse failure comes back as [`Diagnostics`] carrying its own source,
    /// whose ID is zero. Running a source through [`Engine::run_source`]
    /// instead assigns the failure an ID from that engine's submission
    /// history.
    pub fn compile(source: impl Into<String>) -> Result<Self, Diagnostics> {
        let source = source.into();
        let source_id = SourceId(0);
        match parse_program(&source, source_id) {
            Ok(statements) => Ok(Self {
                text: source,
                statements,
            }),
            Err(diagnostic) => Err(Diagnostics {
                entries: vec![*diagnostic],
                sources: vec![DiagnosticSource {
                    id: source_id,
                    name: "source".to_string(),
                    text: source,
                }],
            }),
        }
    }

    /// The source text this program was parsed from.
    pub fn source(&self) -> &str {
        &self.text
    }
}

/// Stateful façade for parsing and evaluating Eurydice programs.
///
/// This maintains a global environment, and definitions and settings persist
/// between calls to [`Engine::run_program`] (or [`Engine::run_source`]), making
/// the API suitable for interactive sessions. Drop and re-create the
/// engine if you want to start over with a clean slate.
pub struct Engine {
    evaluator: Evaluator,
    next_source_id: u64,
    sources: Vec<DiagnosticSource>,
}

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

/// Opaque: an engine's contents are evaluator internals, and none of them mean
/// anything to a consumer. The impl exists so that a type holding an `Engine`
/// can still derive its own `Debug`.
impl std::fmt::Debug for Engine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Engine").finish_non_exhaustive()
    }
}

impl Engine {
    /// Initializes a new engine with default global state.
    pub fn new() -> Self {
        Self {
            evaluator: Evaluator::new(),
            next_source_id: 0,
            sources: Vec::new(),
        }
    }

    /// Installs the callback used by `print` statements.
    ///
    /// The callback must be safe to move between threads so the engine remains
    /// [`Send`]. It is still invoked synchronously by whichever thread calls a
    /// run method.
    pub fn set_print_callback<F>(&mut self, callback: F)
    where
        F: FnMut(PrintEvent) + Send + 'static,
    {
        self.evaluator.set_print_callback(Box::new(callback));
    }

    /// Executes a program as a fresh submission, returning its outputs and any
    /// diagnostics it produced.
    ///
    /// Each call assigns the program's text a new source ID, so a program may
    /// be run repeatedly and diagnostics from each run point into that
    /// run's own source text.
    ///
    /// A diagnostic may point into an earlier submission that defined a
    /// function, so the report carries the text of every source its own
    /// diagnostics reference.
    pub fn run_program(&mut self, program: &Program) -> RunReport {
        let source_id = self.begin_submission(&program.text);
        self.execute_report(&program.statements, source_id)
    }

    /// Parses source and executes it as a fresh submission, returning its
    /// outputs and any diagnostics it produced.
    ///
    /// To run one program repeatedly, compile it once with [`Program::compile`]
    /// and call [`Engine::run_program`] directly.
    pub fn run_source(&mut self, source: &str) -> RunReport {
        let source_id = self.begin_submission(source);
        match parse_program(source, source_id) {
            Ok(statements) => self.execute_report(&statements, source_id),
            Err(diagnostic) => self.report(Vec::new(), vec![*diagnostic]),
        }
    }

    /// Starts a fresh submission and returns the ID assigned to its source.
    fn begin_submission(&mut self, source: &str) -> SourceId {
        self.collect_garbage();
        let source_id = self.register_source(source);
        // Outputs belong to one submission and must never leak out of a failed
        // previous run.
        self.evaluator.take_outputs();
        self.evaluator.begin_submission(source_id);
        source_id
    }

    fn execute_report(
        &mut self,
        statements: &[WithRange<Statement>],
        source_id: SourceId,
    ) -> RunReport {
        let outcome = self.execute(statements, source_id);
        // Warnings are collected during evaluation, so they precede the error
        // that stopped the submission.
        let mut diagnostics = self.evaluator.take_diagnostics();
        let outputs = match outcome {
            Ok(outputs) => outputs,
            // Outputs from a failed submission are discarded.
            Err(diagnostic) => {
                diagnostics.push(*diagnostic);
                Vec::new()
            }
        };
        self.report(outputs, diagnostics)
    }

    /// A source outlives its submission only while a persisted function can
    /// still be traced back to it. Dropping the rest keeps an interactive
    /// session — which resubmits a growing program on every keystroke — from
    /// grinding to a halt.
    fn collect_garbage(&mut self) {
        let live = self.evaluator.live_source_ids();
        self.sources.retain(|source| live.contains(&source.id));
    }

    /// Records a submission's source text so diagnostics can point into it.
    fn register_source(&mut self, text: &str) -> SourceId {
        let source_id = SourceId(self.next_source_id);
        self.next_source_id += 1;
        self.sources.push(DiagnosticSource {
            id: source_id,
            name: format!("submission {}", source_id.0 + 1),
            text: text.to_string(),
        });
        source_id
    }

    fn report(&self, outputs: Vec<NamedDistribution>, diagnostics: Vec<Diagnostic>) -> RunReport {
        let sources = self.referenced_sources(&diagnostics);
        RunReport {
            outputs,
            diagnostics: Diagnostics {
                entries: diagnostics,
                sources,
            },
        }
    }

    /// The sources the report needs to render, in submission order.
    fn referenced_sources(&self, diagnostics: &[Diagnostic]) -> Vec<DiagnosticSource> {
        let mut referenced = diagnostics
            .iter()
            .flat_map(|diagnostic| {
                let labels = diagnostic.labels().map(|label| label.range.source);
                let fixes = diagnostic.fix.iter().map(|fix| fix.range.source);
                let frames = diagnostic.trace.iter().flat_map(|frame| {
                    std::iter::once(frame.call.source)
                        .chain(frame.definition.map(|range| range.source))
                });
                labels.chain(fixes).chain(frames)
            })
            .collect::<HashSet<_>>();
        // The current submission is always included: a frontend renders it
        // whether or not anything went wrong in it.
        referenced.extend(self.sources.last().map(|source| source.id));
        self.sources
            .iter()
            .filter(|source| referenced.contains(&source.id))
            .cloned()
            .collect()
    }

    fn execute(
        &mut self,
        statements: &[WithRange<Statement>],
        source_id: SourceId,
    ) -> Result<Vec<NamedDistribution>, Box<Diagnostic>> {
        for (statement_index, statement) in statements.iter().enumerate() {
            if let Err(error) = self.evaluator.execute(statement) {
                self.evaluator.take_outputs();
                let suggestions = match undefined_name(&error) {
                    Some(UndefinedName::Variable(name)) => {
                        self.evaluator.variable_suggestions(name)
                    }
                    Some(UndefinedName::Function(name)) => {
                        self.evaluator.function_suggestions(name)
                    }
                    None => Vec::new(),
                };
                let mut diagnostic =
                    runtime_diagnostic(&error, source_id, &suggestions, self.evaluator.symbols());
                add_later_definition(
                    &mut diagnostic,
                    &error,
                    &statements[statement_index + 1..],
                    source_id,
                );
                return Err(Box::new(diagnostic));
            }
        }

        let outputs = self.evaluator.take_outputs();
        let symbols = self.evaluator.symbols();
        Ok(outputs
            .into_iter()
            .map(|output| NamedDistribution {
                name: output.name,
                distribution: Distribution::from_runtime(output.value, output.field_names, symbols),
            })
            .collect())
    }
}

fn parse_program(
    source: &str,
    source_id: SourceId,
) -> Result<Vec<WithRange<Statement>>, Box<Diagnostic>> {
    grammar::BodyParser::new()
        .parse(source)
        .map_err(|error| Box::new(parse_error(error, source_id, source)))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::diagnostic::{DiagnosticCode, DiagnosticSeverity, SuggestedFix};

    /// The fix a diagnostic is expected to carry.
    fn fix(diagnostic: &Diagnostic) -> &SuggestedFix {
        diagnostic.fix.as_ref().expect("diagnostic carries a fix")
    }

    /// Runs a submission that is expected to succeed, returning its outputs.
    fn run(engine: &mut Engine, source: &str) -> Vec<NamedDistribution> {
        let report = engine.run_source(source);
        assert_eq!(report.diagnostics.first_error(), None, "{source}");
        report.outputs
    }

    fn entries(distribution: &Distribution) -> Vec<(Vec<i32>, f64)> {
        distribution
            .entries()
            .map(|(values, probability)| (values.to_vec(), probability))
            .collect()
    }

    /// The point of compiling separately: one parse, many runs. Each run is its
    /// own submission, so a program that binds a name binds it again.
    #[test]
    fn a_compiled_program_can_be_run_repeatedly() {
        let mut engine = Engine::new();
        let program = Program::compile("X: 1\noutput X named \"x\"").expect("parses");

        for _ in 0..3 {
            let report = engine.run_program(&program);
            assert_eq!(report.diagnostics.first_error(), None);
            assert_eq!(
                entries(&report.outputs[0].distribution),
                vec![(vec![1], 1.0)]
            );
        }
    }

    #[test]
    fn compiling_owned_source_reuses_its_string() {
        let source = "output 2d2".to_string();
        let source_ptr = source.as_ptr();

        let program = Program::compile(source).expect("parses");

        assert_eq!(program.text.as_ptr(), source_ptr);
    }

    /// A program carries its own text and holds no reference to the engine that
    /// parsed it, so it runs anywhere — including on an engine that has never
    /// seen the source.
    #[test]
    fn a_program_is_independent_of_the_engine_that_compiled_it() {
        let program = Program::compile("output 2d2").expect("parses");

        let report = Engine::new().run_program(&program);

        assert_eq!(report.diagnostics.first_error(), None);
        assert_eq!(
            entries(&report.outputs[0].distribution),
            vec![(vec![2], 0.25), (vec![3], 0.5), (vec![4], 0.25)]
        );
        // The run registered the program's text as its own submission, so the
        // report can be rendered without the caller supplying the source.
        assert_eq!(report.diagnostics.sources.len(), 1);
        assert_eq!(report.diagnostics.sources[0].text, "output 2d2");
    }

    /// A failed parse carries its source rather than a bare diagnostic, because
    /// rendering it needs the source the diagnostic points into.
    #[test]
    fn a_failed_compile_reports_against_its_own_source() {
        let diagnostics = Program::compile("output (1").expect_err("does not parse");

        let error = diagnostics.first_error().expect("a parse error");
        assert_eq!(error.code, DiagnosticCode::UnclosedDelimiter);
        let range = error.primary_label.range;
        assert_eq!(diagnostics.sources.len(), 1);
        assert_eq!(diagnostics.sources[0].id, range.source);
    }

    #[test]
    fn compile_errors_integrate_with_standard_error_handling() {
        fn compile() -> Result<(), Box<dyn std::error::Error>> {
            Program::compile("output (1")?;
            Ok(())
        }

        let error = compile().expect_err("does not parse");
        assert!(error.to_string().contains("syntax.unclosed_delimiter"));
    }

    #[test]
    fn submissions_are_named_in_order() {
        let mut engine = Engine::new();

        let report = engine.run_source("output MISSING");
        assert_eq!(
            report.diagnostics.sources.last().unwrap().name,
            "submission 1"
        );

        let report = engine.run_source("output ALSO_MISSING");
        assert_eq!(
            report.diagnostics.sources.last().unwrap().name,
            "submission 2"
        );
    }

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

        let first = Arc::new(Mutex::new(Vec::new()));
        let second = Arc::new(Mutex::new(Vec::new()));
        let mut engine = Engine::new();

        let events = Arc::clone(&first);
        engine.set_print_callback(move |event| events.lock().unwrap().push(event));
        let _ = engine.run_source("print 1\nprint 2 named \"two\"");

        let events = Arc::clone(&second);
        engine.set_print_callback(move |event| events.lock().unwrap().push(event));
        let _ = engine.run_source("print 3");

        let first = first.lock().unwrap();
        assert_eq!(first.len(), 2);
        assert_eq!(first[0].name, None);
        assert_eq!(first[0].value, "1");
        assert_eq!(first[1].name.as_deref(), Some("two"));
        assert_eq!(first[1].value, "2");

        let second = second.lock().unwrap();
        assert_eq!(second.len(), 1);
        assert_eq!(second[0].value, "3");
    }

    #[test]
    fn engine_is_send() {
        fn assert_send<T: Send>() {}

        assert_send::<Engine>();
    }

    #[test]
    fn runs_source_to_named_distributions() {
        let outputs = run(&mut Engine::new(), "output 2d2 named \"roll\"");

        assert_eq!(outputs.len(), 1);
        assert_eq!(outputs[0].name, "roll");
        assert_eq!(
            entries(&outputs[0].distribution),
            vec![(vec![2], 0.25), (vec![3], 0.5), (vec![4], 0.25)]
        );
    }

    #[cfg(feature = "serde")]
    #[test]
    fn run_reports_serialize_the_public_wire_values() {
        let report = Engine::new().run_source("D: d6\noutput D + D named \"sum\"");
        let serialized = serde_lexpr::to_string(&report).expect("report serializes");

        assert!(serialized.contains("evaluation.independent_pool_reuse"));
        assert!(serialized.contains("primary_label"));
        assert!(serialized.contains("secondary_labels"));
        assert!(serialized.contains("sum"));
        assert!(serialized.contains("D: d6\\noutput D + D"));
    }

    #[test]
    fn state_persists_between_runs() {
        let mut engine = Engine::new();
        run(&mut engine, "X: 4");

        let outputs = run(&mut engine, "output X");

        assert_eq!(entries(&outputs[0].distribution), vec![(vec![4], 1.0)]);
    }

    #[test]
    fn reports_parse_and_runtime_ranges() {
        let parse_report = Engine::new().run_source("output (");
        let parse_error = parse_report.diagnostics.first_error().unwrap();
        assert!(parse_error.code.is_incomplete());
        assert_eq!(parse_error.primary_label.range.range.start, 8);

        let runtime_report = Engine::new().run_source("output MISSING");
        let runtime_error = runtime_report.diagnostics.first_error().unwrap();
        assert!(!runtime_error.code.is_incomplete());
        assert_eq!(runtime_error.primary_label.range.range.start, 7);
    }

    #[test]
    fn failed_runs_do_not_leak_outputs() {
        let mut engine = Engine::new();
        assert!(
            engine
                .run_source("output 1\noutput MISSING")
                .diagnostics
                .first_error()
                .is_some()
        );

        assert!(run(&mut engine, "X: 1").is_empty());
    }

    #[test]
    fn reports_common_syntax_mistakes_with_fixes() {
        let cases = [
            ("X = 1", DiagnosticCode::AssignmentSeparator, ":"),
            ("output 1 == 1", DiagnosticCode::EqualityOperator, ""),
            ("output d6;", DiagnosticCode::UnexpectedSemicolon, ""),
            ("output x", DiagnosticCode::VariableCase, "X"),
            ("output total", DiagnosticCode::VariableCase, "TOTAL"),
            ("output (1", DiagnosticCode::UnclosedDelimiter, ")"),
        ];

        for (source, code, replacement) in cases {
            let report = Engine::new().run_source(source);
            let error = report.diagnostics.first_error().unwrap();
            assert_eq!(error.code, code);
            assert_eq!(fix(error).replacement, replacement);
        }
    }

    #[test]
    fn single_letter_function_names_are_accepted() {
        let mut engine = Engine::new();
        run(&mut engine, "function: f X:n { result: X }");

        let outputs = run(&mut engine, "output [f 3]");

        assert_eq!(entries(&outputs[0].distribution), vec![(vec![3], 1.0)]);
    }

    #[test]
    fn misplaced_keywords_are_not_mistaken_for_lowercase_variables() {
        let report = Engine::new().run_source("output result");
        let error = report.diagnostics.first_error().unwrap();

        assert_eq!(error.code, DiagnosticCode::UnexpectedToken);
        assert!(error.fix.is_none());
    }

    #[test]
    fn rejects_result_outside_a_function() {
        let report = Engine::new().run_source("result: 1");

        assert_eq!(
            report.diagnostics.first_error().map(|error| error.code),
            Some(DiagnosticCode::ResultOutsideFunction)
        );
    }

    #[test]
    fn unclosed_delimiters_ignore_strings_and_comments() {
        let cases = ["output (1 \\ ) \\", "output (1 \\\\\\ )"];

        for source in cases {
            let report = Engine::new().run_source(source);
            let error = report.diagnostics.first_error().unwrap();

            assert_eq!(error.code, DiagnosticCode::UnclosedDelimiter, "{source}");
            assert_eq!(fix(error).replacement, ")", "{source}");
        }
    }

    #[test]
    fn explains_that_top_level_expressions_need_output() {
        for source in ["1d6", "D: d6\nD + D"] {
            let report = Engine::new().run_source(source);
            let error = report.diagnostics.first_error().unwrap();

            assert_eq!(error.code, DiagnosticCode::UnexpectedToken);
            assert_eq!(
                error.help.as_deref(),
                Some("At the top level, expressions you want to show must start with `output`.")
            );
            assert!(error.fix.is_none());
        }
    }

    #[test]
    fn suggests_names_and_marks_definitions_that_execute_later() {
        let mut engine = Engine::new();
        run(&mut engine, "FOOD: 1");
        let report = engine.run_source("output FOO\nFOO: 2");
        let error = report.diagnostics.first_error().unwrap();

        assert_eq!(error.primary_label.message, None);
        assert!(
            error
                .help
                .as_deref()
                .is_some_and(|help| help.contains("Did you mean `FOOD`?")),
            "{:?}",
            error.help
        );
        assert!(
            error
                .help
                .as_deref()
                .is_some_and(|help| help.contains("this definition is not available yet")),
            "{:?}",
            error.help
        );
        assert!(
            error
                .secondary_labels
                .iter()
                .any(|label| label.message.as_deref() == Some("defined later"))
        );
    }

    #[test]
    fn suggests_a_comma_for_ambiguously_joined_dice_arguments() {
        // The comma goes after the first complete roll, however many were run
        // together, and a die count is never mistaken for one.
        for (source, remainder) in [
            ("output [tuple d6 d8]", " d8]"),
            ("output [tuple d6 d8 d10]", " d8 d10]"),
            ("output [tuple 2d6 d8]", " d8]"),
        ] {
            let report = Engine::new().run_source(source);
            let error = report.diagnostics.first_error().unwrap();

            assert_eq!(error.code, DiagnosticCode::UndefinedFunction, "{source}");
            let suggestion = fix(error);
            assert_eq!(
                &report.diagnostics.sources[0].text[suggestion.range.range.start..],
                remainder,
                "{source}"
            );
            assert_eq!(suggestion.replacement, ",", "{source}");
        }
    }

    /// A call can also pass too many arguments, which no comma would fix.
    #[test]
    fn does_not_suggest_a_comma_when_no_arity_takes_more_arguments() {
        let report = Engine::new().run_source("output [absolute 1, 2]");
        let error = report.diagnostics.first_error().unwrap();

        assert_eq!(error.code, DiagnosticCode::UndefinedFunction);
        assert!(error.fix.is_none());
    }

    #[test]
    fn traces_pool_expansion_with_the_failing_argument_value() {
        let source = "\
function: pick I:n {
  result: [field I of [tuple 10 20]]
}
output [pick d3]";
        let report = Engine::new().run_source(source);
        let error = report.diagnostics.first_error().unwrap();

        assert_eq!(error.code, DiagnosticCode::OutOfRange);
        assert_eq!(error.trace.len(), 1);
        assert_eq!(error.trace[0].function, "pick {}");
        assert_eq!(error.trace[0].bindings[0].name, "I");
        assert_eq!(error.trace[0].bindings[0].value, "3");
    }

    #[test]
    fn primitive_diagnostics_identify_invalid_field_arguments() {
        let source = "output [field d2 of 1]";
        let report = Engine::new().run_source(source);
        let error = report.diagnostics.first_error().unwrap();

        assert_eq!(error.code, DiagnosticCode::FunctionArgument);
        assert_eq!(
            error.summary,
            "`[field INDEX:n of TUPLE:n]` requires `INDEX` to be an integer and `TUPLE` to be a tuple"
        );
        assert!(error.secondary_labels.is_empty());
        let label = &error.primary_label;
        assert_eq!(&source[label.range.range.start..label.range.range.end], "1");
        let message = label.message.as_deref().unwrap();
        assert!(message.contains("`TUPLE` is an integer: `1`"));
        assert!(message.contains("expected a tuple"));
        assert_eq!(
            error.help.as_deref(),
            Some("Build a tuple with `[tuple A B]`. Tuple field positions start at 1.")
        );
    }

    #[test]
    fn primitive_diagnostics_report_every_bad_tuple_or_field_argument() {
        let nested = Engine::new().run_source("output [tuple [tuple 1, 2], [tuple 3, 4]]");
        let nested_error = nested.diagnostics.first_error().unwrap();
        assert_eq!(nested_error.code, DiagnosticCode::FunctionArgument);
        assert_eq!(
            nested_error.summary,
            "`[tuple A:n B:n]` cannot contain another tuple"
        );
        assert_eq!(nested_error.secondary_labels.len(), 1);
        assert!(
            nested_error
                .primary_label
                .message
                .as_deref()
                .unwrap()
                .contains("`A` is a tuple")
        );
        assert!(
            nested_error.secondary_labels[0]
                .message
                .as_deref()
                .unwrap()
                .contains("`B` is a tuple")
        );

        let field = Engine::new().run_source("output [field [tuple 1, 2] of 1]");
        let field_error = field.diagnostics.first_error().unwrap();
        assert_eq!(field_error.code, DiagnosticCode::FunctionArgument);
        assert_eq!(field_error.secondary_labels.len(), 1);
        assert!(
            field_error
                .primary_label
                .message
                .as_deref()
                .unwrap()
                .contains("`INDEX` is a tuple")
        );
        assert!(
            field_error.secondary_labels[0]
                .message
                .as_deref()
                .unwrap()
                .contains("`TUPLE` is an integer")
        );
    }

    /// The equality-based primitives are as total as `=` itself: a needle that
    /// could never match counts zero matches rather than failing.
    #[test]
    fn equality_primitives_count_no_matches_across_outcome_types() {
        for source in [
            "enum { A, B } output [{A} contains 1]",
            "enum { A, B } output [count {A} in {1}]",
            "enum { A, B } output [count {1} in 2d{A, B}]",
            "output [{[tuple 1, 2]} contains 1]",
        ] {
            let mut engine = Engine::new();
            let outputs = run(&mut engine, source);
            assert_eq!(
                entries(&outputs[0].distribution),
                vec![(vec![0], 1.0)],
                "{source}"
            );
        }
    }

    #[test]
    fn primitive_diagnostics_explain_outcome_and_value_constraints() {
        let bounds = Engine::new().run_source("output [field 3 of [tuple 1, 2]]");
        let bounds_error = bounds.diagnostics.first_error().unwrap();
        assert_eq!(bounds_error.code, DiagnosticCode::OutOfRange);
        assert_eq!(
            bounds_error.summary,
            "`[field INDEX:n of TUPLE:n]` cannot select field `3`"
        );
        assert!(
            bounds_error
                .primary_label
                .message
                .as_deref()
                .unwrap()
                .contains("expected an index from 1 through 2")
        );

        let negative = Engine::new().run_source("output [highest -1 of 2d6]");
        assert_eq!(
            negative.diagnostics.first_error().unwrap().summary,
            "`[highest COUNT:n of POOL:d]` needs a nonnegative count"
        );
    }

    #[test]
    fn non_primitive_type_errors_include_the_actual_value_and_type() {
        let cases = [
            (
                "loop X over d6 { print X }",
                DiagnosticCode::ExpectedSequence,
                "expected a sequence",
            ),
            (
                "if d6 { print 1 }",
                DiagnosticCode::ExpectedNumber,
                "expected an integer",
            ),
            (
                "output {1:d6}",
                DiagnosticCode::RepeatCount,
                "expected an integer",
            ),
            (
                "output {1..d6}",
                DiagnosticCode::RangeEndpoint,
                "expected an integer",
            ),
        ];

        for (source, code, expected_message) in cases {
            let report = Engine::new().run_source(source);
            let error = report.diagnostics.first_error().unwrap();
            assert_eq!(error.code, code, "{source}");
            let message = error.primary_label.message.as_deref().unwrap_or_default();
            // The label names the type that was found as well as the one the
            // position required.
            assert!(message.contains(expected_message), "{source}: {message}");
            assert!(message.contains("is a dice pool"), "{source}: {message}");
        }
    }

    #[test]
    fn output_label_errors_explain_the_output_shape_and_arity() {
        let non_tuple = Engine::new().run_source("output 1 labeled \"Value\"");
        let error = non_tuple.diagnostics.first_error().unwrap();
        assert_eq!(error.code, DiagnosticCode::LabelsRequireTuple);
        assert_eq!(error.secondary_labels.len(), 1);
        assert!(
            error
                .primary_label
                .message
                .as_deref()
                .is_some_and(|message| message.contains("`1` is an integer; expected a tuple"))
        );

        let wrong_count = Engine::new().run_source("output [tuple 1 2] labeled \"Only one\"");
        let error = wrong_count.diagnostics.first_error().unwrap();
        assert_eq!(
            error.summary,
            "This tuple has 2 fields, but 1 output label was provided"
        );
        assert_eq!(error.primary_label.message, None);
    }

    #[test]
    fn non_primitive_diagnostics_do_not_repeat_the_summary_as_a_label() {
        let report = Engine::new().run_source("output [missing]");
        assert_eq!(
            report
                .diagnostics
                .first_error()
                .unwrap()
                .primary_label
                .message,
            None
        );

        // A label may still carry something the summary does not. Adding two
        // symbols is reported at the value that cannot be added, which the
        // summary has no room to name.
        let report = Engine::new().run_source("enum { A, B } output A + B");
        let error = report.diagnostics.first_error().unwrap();
        assert_eq!(error.summary, "this operator requires numbers");
        assert_eq!(
            error.primary_label.message.as_deref(),
            Some("values like `B` are not numbers")
        );

        let operator = Engine::new().run_source("output d6 @ d6");
        let error = operator.diagnostics.first_error().unwrap();
        assert_eq!(
            error.summary,
            "Operator `@` expects an integer or a sequence"
        );
        assert_eq!(error.secondary_labels[0].message, None);
        assert!(
            error
                .primary_label
                .message
                .as_deref()
                .is_some_and(|message| message.contains("is a dice pool"))
        );
    }

    #[test]
    fn reports_carry_only_the_sources_they_point_into() {
        let mut engine = Engine::new();

        // The failed submission is still rendered against its own source.
        let failed = engine.run_source("output (");
        assert_eq!(failed.diagnostics.sources.len(), 1);
        assert_eq!(
            failed
                .diagnostics
                .first_error()
                .unwrap()
                .primary_label
                .range
                .source,
            SourceId(0)
        );

        let succeeded = engine.run_source("output 1");
        assert_eq!(succeeded.diagnostics.sources.len(), 1);
        assert_eq!(succeeded.diagnostics.sources[0].id, SourceId(1));
    }

    /// An interactive frontend resubmits a growing program on every keystroke,
    /// so anything the engine keeps per submission has to be released again.
    #[test]
    fn only_sources_behind_a_live_function_are_kept() {
        let mut engine = Engine::new();
        for _ in 0..10 {
            run(&mut engine, "X: 1\noutput X");
        }
        assert_eq!(engine.sources.len(), 1);

        run(&mut engine, "function: keep me { result: 1 }");
        run(&mut engine, "output 1");
        // The submission that defined `keep me` is still needed to render a
        // diagnostic raised inside its body.
        assert_eq!(engine.sources.len(), 2);

        // Redefining the function releases the source that first defined it.
        run(&mut engine, "function: keep me { result: 2 }");
        run(&mut engine, "output 1");
        assert_eq!(engine.sources.len(), 2);
    }

    #[test]
    fn diagnostics_retain_sources_for_persisted_functions() {
        let mut engine = Engine::new();
        run(&mut engine, "function: broken { result: MISSING }");
        let report = engine.run_source("output [broken]");
        let error = report.diagnostics.first_error().unwrap();

        assert_eq!(error.primary_label.range.source, SourceId(0));
        assert_eq!(error.trace[0].call.source, SourceId(1));
        assert_eq!(report.diagnostics.sources.len(), 2);
    }

    #[test]
    fn warns_when_the_same_pool_is_sampled_independently() {
        let report = Engine::new().run_source("D: d6\noutput D + D");
        assert!(report.diagnostics.first_error().is_none());
        assert_eq!(
            report.diagnostics.entries[0].code,
            DiagnosticCode::IndependentPoolReuse
        );
        let help = report.diagnostics.entries[0].help.as_deref().unwrap();
        assert!(help.contains("stores its distribution"));
        assert!(help.contains("To reuse one roll"));

        let no_warning = Engine::new().run_source("D: d6\noutput #D + #D");
        assert!(no_warning.diagnostics.entries.is_empty());
    }

    #[test]
    fn warns_when_a_function_can_finish_without_a_result() {
        let cases = [
            "function: empty {}",
            "function: partial X:n { if X { result: 1 } }",
        ];

        for source in cases {
            let report = Engine::new().run_source(source);
            let warning = &report.diagnostics.entries[0];
            assert_eq!(warning.code, DiagnosticCode::MissingResult, "{source}");
            assert_eq!(warning.code.severity(), DiagnosticSeverity::Warning);
            let help = warning.help.as_deref().unwrap();
            assert!(help.contains("produces an empty die"), "{source}");
            assert!(help.contains("Add `result:`"), "{source}");
            assert!(warning.fix.is_none());
        }
    }

    #[test]
    fn accepts_functions_that_return_on_every_path() {
        let cases = [
            "function: direct { result: 1 }",
            "function: branched X:n { if X { result: 1 } else { result: 2 } }",
            "function: fallback X:n { if X { result: 1 } result: 2 }",
            "function: chained X:n { if X { result: 1 } else if X = 2 { result: 2 } else { result: 3 } }",
            // Returning from a loop is only certain for a non-empty sequence,
            // but warning about the idiom would cost more than it catches.
            "function: first S:s { loop X over S { result: X } }",
        ];

        for source in cases {
            let report = Engine::new().run_source(source);
            assert!(report.diagnostics.entries.is_empty(), "{source}");
        }
    }

    /// An empty die displays as no outcomes at all — not as a single outcome at
    /// zero — and stays that way after passing through a function that demands
    /// `int` arguments.
    ///
    /// Summing an empty die turns its additive identity into a real outcome, so
    /// the display rule leaves it alone while its outcome type still says
    /// nothing about what it would have produced. Coercing it to an `int`
    /// parameter used to overwrite that type, which made `[explode d{}]`
    /// disagree with the `d{}` it was given.
    #[test]
    fn an_empty_die_outputs_no_outcomes_even_after_coercion() {
        // `explode` and `reroll` hand an empty die straight back, so what they
        // display is decided entirely by the coercion and the display rule.
        // `highest`/`lowest`/`middle` are not listed: they sum the dice they
        // keep, and the sum of no dice is `0`, which is a claim about those
        // primitives rather than about empty dice.
        for source in [
            "function: nothing {}\noutput [nothing]",
            "output d{}",
            "output [explode d{}]",
            "output [reroll d{}]",
        ] {
            let report = Engine::new().run_source(source);
            assert_eq!(report.diagnostics.first_error(), None, "{source}");
            assert_eq!(report.outputs.len(), 1, "{source}");
            assert!(
                report.outputs[0].distribution.entries().next().is_none(),
                "{source}"
            );
        }
    }

    /// Knowing what an empty die's faces *would* have been does not make it
    /// rollable, so a die with no faces displays as no outcomes whatever its
    /// outcome type. `d{}` and `d{5:0}` differ only in whether a face was
    /// written down, and neither has an outcome to show.
    #[test]
    fn an_empty_die_outputs_no_outcomes_whatever_its_type() {
        for source in ["output d{}", "output d{5:0}", "output d{[tuple 5 6]:0}"] {
            let report = Engine::new().run_source(source);
            assert_eq!(report.diagnostics.first_error(), None, "{source}");
            assert!(
                report.outputs[0].distribution.entries().next().is_none(),
                "{source}"
            );
        }
    }

    /// The contrast that keeps the rule honest: it asks about faces, not dice.
    /// `0d6` has faces and no dice, so it still sums — to the `0` that rolling
    /// no dice yields.
    #[test]
    fn rolling_no_dice_still_sums_to_zero() {
        for source in ["output 0d6", "output d0"] {
            let outputs = run(&mut Engine::new(), source);

            assert_eq!(
                entries(&outputs[0].distribution),
                vec![(vec![0], 1.0)],
                "{source}"
            );
        }
    }

    #[test]
    fn warns_when_depth_settings_bound_results() {
        let explode = Engine::new().run_source("output [explode d6]");
        assert_eq!(
            explode.diagnostics.entries[0].code,
            DiagnosticCode::ExplodeDepth
        );
        let help = explode.diagnostics.entries[0].help.as_deref().unwrap();
        assert!(help.contains("bounded by this setting"));
        assert!(help.contains("Change it with"));

        let recursion = Engine::new()
            .run_source("function: recurse N:n { result: [recurse N] }\noutput [recurse 1]");
        assert_eq!(
            recursion.diagnostics.entries[0].code,
            DiagnosticCode::MaximumFunctionDepth
        );
    }
}