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,
};
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[non_exhaustive]
pub struct NamedDistribution {
pub name: String,
pub distribution: Distribution,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(Serialize))]
#[must_use]
#[non_exhaustive]
pub struct RunReport {
pub outputs: Vec<NamedDistribution>,
pub diagnostics: Diagnostics,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct PrintEvent {
pub name: Option<String>,
pub value: String,
}
#[derive(Debug, Clone)]
pub struct Program {
text: String,
statements: Vec<WithRange<Statement>>,
}
impl Program {
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,
}],
}),
}
}
pub fn source(&self) -> &str {
&self.text
}
}
pub struct Engine {
evaluator: Evaluator,
next_source_id: u64,
sources: Vec<DiagnosticSource>,
}
impl Default for Engine {
fn default() -> Self {
Self::new()
}
}
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 {
pub fn new() -> Self {
Self {
evaluator: Evaluator::new(),
next_source_id: 0,
sources: Vec::new(),
}
}
pub fn set_print_callback<F>(&mut self, callback: F)
where
F: FnMut(PrintEvent) + Send + 'static,
{
self.evaluator.set_print_callback(Box::new(callback));
}
pub fn run_program(&mut self, program: &Program) -> RunReport {
let source_id = self.begin_submission(&program.text);
self.execute_report(&program.statements, source_id)
}
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]),
}
}
fn begin_submission(&mut self, source: &str) -> SourceId {
self.collect_garbage();
let source_id = self.register_source(source);
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);
let mut diagnostics = self.evaluator.take_diagnostics();
let outputs = match outcome {
Ok(outputs) => outputs,
Err(diagnostic) => {
diagnostics.push(*diagnostic);
Vec::new()
}
};
self.report(outputs, diagnostics)
}
fn collect_garbage(&mut self) {
let live = self.evaluator.live_source_ids();
self.sources.retain(|source| live.contains(&source.id));
}
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,
},
}
}
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<_>>();
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};
fn fix(diagnostic: &Diagnostic) -> &SuggestedFix {
diagnostic.fix.as_ref().expect("diagnostic carries a fix")
}
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()
}
#[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);
}
#[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)]
);
assert_eq!(report.diagnostics.sources.len(), 1);
assert_eq!(report.diagnostics.sources[0].text, "output 2d2");
}
#[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() {
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}");
}
}
#[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")
);
}
#[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();
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
);
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();
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));
}
#[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");
assert_eq!(engine.sources.len(), 2);
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 } }",
"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}");
}
}
#[test]
fn an_empty_die_outputs_no_outcomes_even_after_coercion() {
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}"
);
}
}
#[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}"
);
}
}
#[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
);
}
}