Dever v0.0.2

This commit is contained in:
Codex committed 2026-11-27 06:03:56 +00:00
commit e6e175ebcf
816 files changed
+120349

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
use super::*;
#[test]
fn constants_keep_precise_values_and_ranges_without_runtime_checks() {
let program = check(
r#"
type State { Ready, error Broken }
const count: Int >= 1 = 4
const alias = count
const rate: Decimal = alias
const minimum = -9223372036854775808
const fraction = 0.1000000000000000000000000000000001
const empty: Text? = null
const state: State = Ready
const failure = State.Broken
f() (out: Int >= 1) { out = alias }
g() (out: Decimal) { out = rate + fraction }
stop() () { fail(failure) }
"#,
)
.unwrap();
assert_eq!(program.functions[0].constant_references.len(), 1);
assert_eq!(program.functions[1].constant_references.len(), 2);
assert_eq!(
program.functions[2].failures,
[Failure::Choice(1, 1)].into()
);
rejected(
"const count = 4\nf() () { check count >= 1 else Invalid }",
"C012",
"redundant",
);
rejected(
"type State { Ready, error Broken }\nconst broken = State.Broken\nf() (out: Int) { ignored = broken\nout = 1 }",
"C012",
"failure is not handled",
);
}
#[test]
fn constants_reject_dynamic_values_cycles_duplicates_and_invalid_literals() {
for text in [
"const value = [1]",
"const value = 1 + 2",
"const value = length(\"text\")",
"const value = not true",
"type Item { value: Int }\nconst value = Item { value = 1 }",
] {
rejected(text, "C005", "scalar literal");
}
rejected("const value = null", "C005", "concrete scalar");
rejected("const value = Ready", "C004", "unknown");
rejected("const value: Int >= 1 = 0", "C008", "cannot prove");
rejected("const value: Int = true", "C005", "expected");
rejected("const value = 1e999", "C008", "finite");
rejected("const value = 9223372036854775808", "C008", "outside");
rejected("const value = 1\nconst value = 2", "C001", "duplicate");
rejected(
"const value = 1\nvalue() (n: Int) { n = 2 }",
"C001",
"share a name",
);
rejected("const value = value", "C010", "cyclic constant");
rejected(
"const first = second\nconst second = 1",
"C004",
"preceding",
);
rejected(
"type State { Ready, Item(value: Int) }\nconst state = State.Ready",
"C005",
"payload-free",
);
}
#[test]
fn local_names_do_not_turn_into_constant_references() {
let program = check("const value = 4\nf(value: Int) (out: Int) { out = value }").unwrap();
assert!(program.functions[0].constant_references.is_empty());
check("const value = 4\ntype Item { value: Int }\nf(input: Item) (out: Int) { out = input.value }").unwrap();
}
+189
View File
@@ -0,0 +1,189 @@
use super::*;
#[test]
fn capture_preserves_nominal_errors_and_parameter_failure_propagation() {
let source = "type Problem { error Missing(message: Text) }\ntype Result { Ready(value: Int), error Failed(problem: Problem) }\nraise() (value: Int) { fail(Problem.Missing(\"missing\")) }\nmaybe(value: Int) (next: Int) { check value >= 1 else Problem.Missing(\"small\")\nnext = value }\nf() (out: Result) { out = result(raise()) }\ng() (out: Result) { out = result(maybe(raise())) }";
let program = check(source).unwrap();
assert!(program.functions[2].failures.is_empty());
assert_eq!(
program.functions[3].failures,
[Failure::Choice(1, 0)].into()
);
let Body::Statements { statements, .. } = &program.functions[2].body else {
panic!()
};
let Statement::Assign { value, .. } = &statements[0] else {
panic!()
};
let ExpressionKind::Capture(capture) = &value.kind else {
panic!()
};
assert_eq!(capture.errors, vec![(Failure::Choice(1, 0), 1, true)]);
rejected(
&source.replace("Failed(problem: Problem)", "Failed(problem: Int)"),
"C005",
"nominally matching",
);
rejected(
&source.replace(
"Failed(problem: Problem)",
"Failed(problem: Problem), error Again(problem: Problem)",
),
"C005",
"nominally matching",
);
rejected(
"type Result { Ready(value: Int) }\nf() (x: Int) { x = 1 }\ng() (value: Result) { value = result(f()) }",
"C012",
"infallible",
);
}
#[test]
fn capture_checks_zero_and_multiple_success_outputs_and_ranges() {
check("type Result { Done, error Failed }\nf() () { fail(Result.Failed) }\ng() (out: Result) { out = result(f()) }").unwrap();
check("type Result { Done(x: Int, text: Text), error Failed }\nf() (x: Int, text: Text) { fail(Result.Failed) }\ng() (out: Result) { out = result(f()) }").unwrap();
rejected(
"type Result { Done(x: Int >= 1), error Failed }\nf(input: Int) (x: Int) { check input != 0 else Result.Failed\nx = input }\ng(input: Int) (out: Result) { out = result(f(input)) }",
"C005",
"success fields",
);
}
const ERRORS: &str = "type Result { Ready(value: Int), error Failed(message: Text) }\ntype Box { result: Result, label: Text }\nraise() (value: Int) { fail(Result.Failed(\"bad\")) }\ncapture() (value: Result) { value = result(raise()) }\n";
#[test]
fn error_values_cannot_be_lost_by_assignment_projection_or_collection_access() {
for body in [
"f() () { lost = capture() }",
"f() (value: Result) { value = capture()\nvalue = Result.Ready(1) }",
"f() (value: Text) { box = Box { result = capture(), label = \"x\" }\nvalue = box.label }",
"f() (value: Int) { values = [capture()]\nvalue = length(values) }",
"f(value: Result) () {}",
"f(old: Result, next: Result?) (value: Result?) { value = next }",
] {
rejected(
&(ERRORS.to_owned() + body),
"C012",
"failure is not handled",
);
}
}
#[test]
fn returned_errors_recovery_and_aliases_keep_their_obligations() {
for body in [
"f() (value: Result) { value = capture() }",
"f() (value: Result?) { values: List<Result?> = [capture()]\nvalue = get(values, 0) }",
"f() (value: Result) { old = capture()\nvalue = Result.Failed(\"replacement\") }",
"identity(value: Result) (next: Result) { next = value }\nf() (value: Result) { first = capture()\nsecond = identity(first)\nvalue = first }",
"f(value: Result) (yes: Bool) recover(\"optional lookup is ignored\") { yes = true }",
"rule read(value: Result) (number: Int)\n| value | number |\n| Ready(number) | number |\n| Failed(message) | fail(value) |\n",
"rule read(value: Result) (next: Result)\n| value | next |\n| Ready(number) | Ready(number) |\n| Failed(message) | value |\n",
] {
check(&(ERRORS.to_owned() + body)).unwrap();
}
rejected(
&(ERRORS.to_owned()
+ "rule read(value: Result) (number: Int)\n| value | number |\n| Ready(number) | number |\n| Failed(message) | length(message) |\n"),
"C012",
"failure is not handled",
);
}
#[test]
fn conditional_recovery_does_not_handle_the_skipped_path() {
let recovery = "handled(value: Result) (yes: Bool) recover(\"optional probe is discarded\") { yes = true }\n";
for expression in [
"false and handled(value)",
"true or handled(value)",
"flag and handled(value)",
] {
rejected(
&format!(
"{ERRORS}{recovery}f(flag: Bool) (yes: Bool) {{ value = capture()\nyes = {expression} }}"
),
"C012",
"failure is not handled",
);
}
check(&format!(
"{ERRORS}{recovery}f() (yes: Bool) {{ value = capture()\nyes = true and handled(value) }}"
))
.unwrap();
}
#[test]
fn choice_complements_and_nullable_error_paths_use_proved_partitions() {
check(
"type Choice { A, B }\nrule f(value: Choice) (x: Int)\n| value | x |\n| A, other | 1 |\n",
)
.unwrap();
check(&format!("{ERRORS}rule read(value: Result?) (x: Int)\n| value | x |\n| null | 0 |\n| Ready(number) | number |\n| Failed(message) | fail(value) |\n")).unwrap();
rejected(
&format!("{ERRORS}f() (x: Int) {{ x = raise()\nx = 1 }}"),
"C012",
"unreachable",
);
}
#[test]
fn failure_analysis_skips_plain_records_and_reports_structural_limits() {
let mut source = String::from("type Root { error Failed }\n");
for index in 0..140 {
let inner = if index == 0 {
"Root".into()
} else {
format!("Level{}", index - 1)
};
source.push_str(&format!("type Level{index} {{ inner: {inner} }}\n"));
}
source.push_str("f(value: Level139) (out: Level139) { out = value }");
rejected(&source, "C015", "has not been proved");
check(&source.replace("error Failed", "value: Int")).unwrap();
check("type Box { values: List<Int> }\nf(box: Box) (out: List<Int>) { out = append(box.values, 1) }").unwrap();
}
#[test]
fn selecting_one_field_cannot_erase_an_error_routed_to_another_branch() {
let prefix = "type State { Ready, error Broken }\ntype Pair { left: State, right: State }\nrule route(flag: Bool, state: State) (out: Pair)\n| flag | state | out |\n| - | Ready | Pair { left = State.Ready, right = State.Ready } |\n| true | Broken | Pair { left = state, right = State.Ready } |\n| false | Broken | Pair { left = State.Ready, right = state } |\n";
check(&format!(
"{prefix}whole(flag: Bool, state: State) (out: Pair) {{ out = route(flag, state) }}"
))
.unwrap();
rejected(
&format!(
"{prefix}partial(flag: Bool, state: State) (out: State) {{ pair = route(flag, state)\nout = pair.left }}"
),
"C012",
"failure is not handled",
);
for body in [
"keep(flag: Bool, state: State) (out: State) { alias = state\npair = route(flag, state)\nout = alias }",
"copy(left: State, right: State) (out: Pair) { out = Pair { left = left, right = right } }\nkeep(state: State) (out: State) { pair = copy(state, state)\nout = pair.left }",
"ignore(state: State) () recover(\"optional result discarded\") {}\nkeep(flag: Bool, state: State) () { pair = route(flag, state)\nignore(pair.left)\nignore(pair.right) }",
"wrap(flag: Bool, state: State) (out: Pair) { out = route(flag, state) }\nkeep(flag: Bool, state: State) (out: State) { pair = wrap(flag, state)\nout = state }",
"loop keep(flag: Bool, states: List<State>) (out: List<Pair>)\n| each state in states | result |\n| out | list route(flag, state) |\n",
] {
check(&format!("{prefix}{body}")).unwrap();
}
for body in [
"wrap(flag: Bool, state: State) (out: Pair) { out = route(flag, state) }\npartial(flag: Bool, state: State) (out: State) { pair = wrap(flag, state)\nout = pair.left }",
"ignore(state: State) () recover(\"optional result discarded\") {}\npartial(flag: Bool, state: State) () { pair = route(flag, state)\nignore(pair.left) }",
"partial(flag: Bool, state: State) (out: State) { pair = route(flag, state)\nagain = route(flag, state)\nout = pair.left }",
"loop partial(flag: Bool, states: List<State>) (out: Pair?)\n| each state in states | result |\n| out | first route(flag, state) |\n",
] {
rejected(&format!("{prefix}{body}"), "C012", "failure is not handled");
}
}
#[test]
fn equivalent_error_routes_do_not_multiply_obligations() {
let mut source = String::from(
"type State { Ready, error Broken }\nrule keep(flag: Bool, state: State) (out: State)\n| flag | state | out |\n| - | Ready | state |\n| true | Broken | state |\n| false | Broken | state |\nf(flag: Bool, state: State) (out: State) { out = state\n",
);
for _ in 0..100 {
source.push_str("out = keep(flag, out)\n");
}
source.push('}');
check(&source).unwrap();
}
+125
View File
@@ -0,0 +1,125 @@
use super::*;
#[test]
fn domain_cannot_define_flow_even_without_io() {
let source = Source::new(
0,
"domain.dever",
"flow f() (out: Int)\n| step | kind | do |\n| out | calc | 1 |\n".into(),
);
let (tokens, diagnostics, _) = lex::scan_with_diagnostics(&source, 0..source.text.len());
assert!(diagnostics.is_empty(), "{diagnostics:?}");
let parsed = parse::parse(tokens);
assert!(parsed.diagnostics.is_empty());
let mut module = Module::standalone();
module.role = dever::compiler::project::Role::Domain;
let error = program::check(&parsed.declarations, &[module])
.err()
.unwrap();
assert_eq!(error.code, "C003");
}
#[test]
fn flow_uses_shared_range_refinement_and_real_call_kinds() {
let source = "rule price(remote: Bool) (fee: Int)\n| remote | fee |\n| true | 15 |\n| false | 8 |\nflow quote(remote: Bool, quantity: Int) (total: Int)\n| step | kind | do |\n| - | check | quantity > 0 else Invalid |\n| fee | rule | price(remote) |\n| total | calc | fee * quantity |\nflow start(remote: Bool, quantity: Int) (total: Int)\n| step | kind | do |\n| total | flow | quote(remote, quantity) |\n";
let program = check(source).unwrap();
let Body::Statements {
flow: Some(steps), ..
} = &program.functions[1].body
else {
panic!()
};
assert_eq!(
steps.iter().map(|step| step.kind).collect::<Vec<_>>(),
[StepKind::Check, StepKind::Rule, StepKind::Calc]
);
assert_eq!(
program.functions[2].failures,
[Failure::Api(ApiError::Invalid)].into()
);
rejected(
&source.replace("| fee | rule |", "| fee | calc |"),
"C005",
"kind must be rule",
);
rejected(
&source.replace("| total | flow |", "| total | calc |"),
"C005",
"kind must be flow",
);
}
#[test]
fn flow_bindings_are_unique_forward_only_and_complete() {
rejected(
"flow f(value: Int) (out: Int)\n| step | kind | do |\n| value | calc | 1 |\n| out | calc | value |\n",
"C005",
"cannot shadow",
);
rejected(
"flow f() (out: Int)\n| step | kind | do |\n| out | calc | 1 |\n| out | calc | 2 |\n",
"C005",
"must be new",
);
rejected(
"flow f() (out: Int)\n| step | kind | do |\n| out | calc | later |\n| later | calc | 2 |\n",
"C004",
"unassigned",
);
rejected(
"flow f() (out: Int)\n| step | kind | do |\n| other | calc | 1 |\n",
"C005",
"not assigned",
);
rejected(
"flow first(flag: Bool) (out: Int)\n| step | kind | do |\n| out | rule | second(flag) |\nrule second(flag: Bool) (out: Int)\n| flag | out |\n| true | first(flag) |\n| false | 0 |\n",
"C010",
"recursive",
);
}
#[test]
fn discarding_success_does_not_discard_failure_or_create_useless_values() {
let source = "work(value: Int) (answer: Int) { check value > 0 else Invalid\nanswer = value }\nflow f(value: Int) ()\n| step | kind | do |\n| - | calc | work(value) |\n";
let program = check(source).unwrap();
assert_eq!(
program.functions[1].failures,
[Failure::Api(ApiError::Invalid)].into()
);
rejected(
"flow f() ()\n| step | kind | do |\n| - | calc | 3 + 4 |\n",
"C005",
"discarded",
);
rejected(
"identity(value: Int) (answer: Int) { answer = value }\nflow f() ()\n| step | kind | do |\n| - | calc | identity(1) |\n",
"C005",
"discarded",
);
}
#[test]
fn flow_capture_and_handler_binding_keep_concrete_failure_obligations() {
let source = "type Reply { Ready(value: Int), error Rejected }\nwork(value: Int) (answer: Int) { check value > 0 else Reply.Rejected\nanswer = value }\nflow attempt(value: Int) (reply: Reply)\n| step | kind | do |\n| reply: Reply | calc | result(work(value)) |\nflow apply(value: Int, transform: handler(value: Int) (answer: Int)) (answer: Int)\n| step | kind | do |\n| answer | calc | transform(value) |\nrule identity(value: Int) (answer: Int)\n| value | answer |\n| - | value |\nflow start(value: Int) (answer: Int)\n| step | kind | do |\n| first | flow | apply(value, work) |\n| answer | flow | apply(first, identity) |\n";
let program = check(source).unwrap();
assert_eq!(
program
.functions
.iter()
.find(|f| f.signature.source_name.ends_with(".start"))
.unwrap()
.failures,
[Failure::Choice(1, 1)].into()
);
rejected(
&source
.replace("| reply: Reply |", "| discarded: Reply |")
.replace(
"| discarded: Reply | calc | result(work(value)) |",
"| discarded: Reply | calc | result(work(value)) |\n| reply | calc | Ready(0) |",
),
"C012",
"not handled",
);
check("type Reply { Ready(value: Int), error Rejected }\nrule work(value: Int) (answer: Int)\n| value | answer |\n| > 0 | value |\n| <= 0 | fail(Reply.Rejected) |\nflow capture(value: Int) (reply: Reply)\n| step | kind | do |\n| reply | rule | result(work(value)) |\n").unwrap();
}
+132
View File
@@ -0,0 +1,132 @@
use super::*;
#[test]
fn folds_keep_errors_across_fields_and_short_circuit() {
let prefix = "type State { Ready, error Broken }\ntype Pair { left: State, right: State }\nswap(previous: Pair) (out: Pair) { out = Pair { left = previous.right, right = previous.left } }\nloop rotate(values: List<Int>, seed: Pair) (out: Pair)\n| each value in values | result |\n| out | fold(acc = seed, swap(acc)) |\n";
check(prefix).unwrap();
check(&format!("{prefix}retained(values: List<Int>, seed: Pair) (out: Pair) {{ ignored = rotate(values, seed)\nout = seed }}")).unwrap();
rejected(
&format!(
"{prefix}missing(values: List<Int>, seed: Pair) (out: State) {{ ignored = rotate(values, seed)\nout = seed.left }}"
),
"C012",
"failure is not handled",
);
rejected(
&format!(
"{prefix}partial(values: List<Int>, seed: Pair) (out: State) {{ pair = rotate(values, seed)\nout = pair.left }}"
),
"C012",
"failure is not handled",
);
let stop = "type State { Ready, error Broken }\nadd(value: State, previous: List<State>) (acc: List<State>, stop: Bool) { acc = append(previous, value)\nstop = true }\nloop first(values: List<State>) (out: List<State>)\n| each value in values | result |\n| out | foldUntil(acc = [], add(value, acc)) |\n";
rejected(stop, "C012", "failure is not handled");
check(
&stop
.replace(
"(out: List<State>)\n| each",
"(out: List<State>, all: List<State>)\n| each",
)
.replace(
"foldUntil(acc = [], add(value, acc)) |",
"foldUntil(acc = [], add(value, acc)) |\n| all | list value |",
),
)
.unwrap();
check("type State { Ready, error Broken }\nnext(previous: State) (out: State) recover(\"discard optional state explicitly\") { out = State.Ready }\nloop reset(values: List<Int>, seed: State) (out: State)\n| each value in values | result |\n| out | fold(acc = seed, next(acc)) |\n").unwrap();
}
#[test]
fn fold_handler_binding_and_formatting_share_the_checked_call() {
let source = "add(value: Int, previous: Int) (out: Int) { out = value + previous }\nloop collect(values: List<Int>, update: handler(value: Int, previous: Int) (out: Int)) (out: Int)\n| each value in values | result |\n| out | fold(acc = 0, update(value, acc)) |\nstart(values: List<Int>) (out: Int) { out = collect(values, add) }\n";
check(source).unwrap();
let text = Source::new(0, "app.dever", source.into());
let (tokens, diagnostics, _) = lex::scan_with_diagnostics(&text, 0..source.len());
assert!(diagnostics.is_empty(), "{diagnostics:?}");
let parsed = parse::parse(tokens);
let formatted = dever::compiler::format::format(&parsed.declarations);
check(&formatted).unwrap();
assert!(formatted.contains("fold(acc = 0, update(value, acc))"));
let text = Source::new(0, "app.dever", formatted.clone());
let (tokens, diagnostics, _) = lex::scan_with_diagnostics(&text, 0..formatted.len());
assert!(diagnostics.is_empty(), "{diagnostics:?}");
let parsed = parse::parse(tokens);
assert_eq!(
formatted,
dever::compiler::format::format(&parsed.declarations)
);
}
#[test]
fn folds_use_output_context_and_require_a_named_typed_update() {
check("add(value: Int, previous: List<Int>) (out: List<Int>) { out = append(previous, value) }\nloop collect(values: List<Int>) (out: List<Int>)\n| each value in values | result |\n| out | fold(acc = [], add(value, acc)) |\n").unwrap();
check("find(value: Int) (acc: Int?, stop: Bool) { acc = value\nstop = value > 0 }\nloop search(values: List<Int>) (out: Int?)\n| each value in values | result |\n| out | foldUntil(previous = null, find(value)) |\n").unwrap();
for source in [
"loop f(values: List<Int>) (out: Int)\n| each value in values | result |\n| out | fold(acc = 0, acc + value) |\n",
"add(x: Int, y: Int) (out: Int) { out = x + y }\nloop f(values: List<Int>) (out: Int)\n| each value in values | result |\n| out | fold(value = 0, add(value, value)) |\n",
"add(x: Int, y: Int) (out: Int) { out = x + y }\nloop f(values: List<Int>) (out: Int)\n| each value in values | result |\n| out | fold(out = 0, add(value, out)) |\n",
"next(value: Int) (acc: Int, done: Bool) { acc = value\ndone = true }\nloop f(values: List<Int>) (out: Int)\n| each value in values | result |\n| out | foldUntil(acc = 0, next(value)) |\n",
"next(value: Int) (acc: Text) { acc = \"x\" }\nloop f(values: List<Int>) (out: Int)\n| each value in values | result |\n| out | fold(acc = 0, next(value)) |\n",
] {
assert_eq!(check(source).err().unwrap().code, "C005", "{source}");
}
rejected(
"next(x: Int, y: Int) (out: Int) { out = x + y }\nloop f(values: List<Int>) (out: Int)\n| each value in values | result |\n| out | fold(acc = value, next(value, acc)) |\n",
"C004",
"unknown",
);
rejected(
"next(x: Int, y: Int) (out: Int) { out = x + y }\nloop f(values: List<Int>) (out: Int)\n| each value in values | acc | result |\n| out | - | fold(acc = 0, next(value, acc)) |\n",
"C004",
"unknown",
);
}
#[test]
fn accumulator_ranges_hold_for_every_iteration_including_empty_input() {
let positive = "next(value: Int >= 0, previous: Int >= 0) (out: Int >= 0) { out = value + previous }\nloop f(values: List<Int>) (out: Int >= 0)\n| each value in values | value | result |\n| out | >= 0 | fold(acc = 0, next(value, acc)) |\n";
check(positive).unwrap();
rejected(
&positive.replace("acc = 0", "acc = -1"),
"C008",
"cannot prove",
);
rejected(
&positive.replace("(out: Int >= 0) {", "(out: Int) {"),
"C008",
"preserves",
);
rejected(
"next(value: Int, previous: Int >= 0 and <= 0) (out: Int) { out = value + previous }\nloop f(values: List<Int>) (out: Int)\n| each value in values | result |\n| out | fold(acc = 0, next(value, acc)) |\n",
"C008",
"cannot prove",
);
}
#[test]
fn accumulator_failures_are_checked_after_the_initial_iteration() {
let prefix = "type State { Ready, error Broken }\nrule next(flag: Bool) (out: State)\n| flag | out |\n| true | State.Ready |\n| false | State.Broken |\n";
rejected(
&format!(
"{prefix}add(flag: Bool, previous: List<State>) (out: List<State>) {{ out = append(previous, next(flag)) }}\nloop growing(values: List<Bool>, seed: List<State>) (out: List<State>)\n| each value in values | result |\n| out | fold(acc = seed, add(value, acc)) |\nmissing(values: List<Bool>, seed: List<State>) (out: List<State>) {{ ignored = growing(values, seed)\nout = seed }}"
),
"C012",
"failure is not handled",
);
rejected(
&format!(
"{prefix}loop f(values: List<Bool>) (out: State)\n| each value in values | result |\n| out | fold(acc = State.Ready, next(value)) |\n"
),
"C012",
"earlier accumulator failure",
);
check("type State { Ready, error Broken }\nready() (out: State) { out = State.Ready }\nloop f(values: List<Int>) (out: State)\n| each value in values | result |\n| out | fold(acc = State.Ready, ready()) |\n").unwrap();
check("type State { Ready, error Broken }\nkeep(previous: State) (out: State) { out = previous }\nloop f(values: List<Int>, seed: State) (out: State)\n| each value in values | result |\n| out | fold(acc = seed, keep(acc)) |\ng(values: List<Int>, seed: State) (out: State) { ignored = f(values, seed)\nout = seed }").unwrap();
let collect = "type State { Ready, error Broken }\nadd(value: State, previous: List<State>) (out: List<State>) { out = append(previous, value) }\nloop f(values: List<State>) (out: List<State>)\n| each value in values | result |\n| out | fold(acc = [], add(value, acc)) |\n";
check(collect).unwrap();
rejected(
&format!("{collect}g(values: List<State>) () {{ ignored = f(values) }}"),
"C012",
"failure is not handled",
);
}
+196
View File
@@ -0,0 +1,196 @@
use super::*;
#[test]
fn handler_specializes_only_used_bindings_and_forwards_static_arguments() {
let program = check(r#"
identity(value: Int) (out: Int) { out = value }
double(value: Int) (out: Int) { out = value * 2 }
apply(value: Int, transform: handler(value: Int) (out: Int)) (out: Int) { out = transform(value) }
forward(value: Int, transform: handler(value: Int) (out: Int)) (out: Int) { out = apply(value, transform) }
first() (out: Int) { out = forward(3, identity) }
second() (out: Int) { out = apply(4, double) + apply(5, identity) }
unused(transform: handler(value: Int) (out: Int)) (out: Int) { out = transform(1) }
"#).unwrap();
assert_eq!(program.functions.len(), 7);
assert_eq!(
program
.functions
.iter()
.filter(|f| f.signature.source_name.ends_with(".apply"))
.count(),
2
);
assert!(
program
.functions
.iter()
.all(|f| !f.signature.source_name.ends_with(".unused"))
);
assert!(
program
.functions
.iter()
.all(|f| !matches!(f.body, Body::Contract))
);
assert!(
program
.calls
.iter()
.all(|call| call.target < program.functions.len())
);
let ownership = dever::compiler::check::ownership::analyze(&program);
let _ = ownership;
}
#[test]
fn handler_contracts_check_types_named_outputs_and_range_variance() {
check(r#"
wide(value: Int) (out: Int >= 2) { check value >= 2 else Invalid
out = value }
apply(value: Int >= 2, transform: handler(value: Int >= 2) (out: Int >= 1)) (out: Int >= 1) { out = transform(value) }
start() (out: Int) { out = apply(2, wide) }
"#).unwrap();
for target in [
"target(value: Int >= 3) (out: Int >= 1) { out = value }",
"target(value: Int) (out: Int) { out = value }",
"target(value: Int) (wrong: Int >= 1) { wrong = 1 }",
"target(value: Text) (out: Int >= 1) { out = length(value) + 1 }",
] {
rejected(
&format!(
"{target}\napply(transform: handler(value: Int >= 2) (out: Int >= 1)) (out: Int) {{ out = transform(2) }}\nstart() (out: Int) {{ out = apply(target) }}"
),
"C005",
"handler input",
);
}
rejected(
"unused(transform: handler(value: Int) (out: Text)) (out: Int) { out = transform(1) }",
"C005",
"expected",
);
}
#[test]
fn handler_is_static_read_only_and_cannot_escape_into_values() {
rejected(
"bad(transform: handler(value: Int) (out: Int)) (out: Int) { transform = 1\nout = 0 }",
"C005",
"read-only",
);
rejected(
"type Bad { transform: handler() () }",
"C005",
"static input",
);
rejected(
"bad() (out: handler() ()) { out = bad }",
"C005",
"static input",
);
rejected(
"apply(transform: handler() (out: Int)) (out: Int) { out = transform() }\nstart(target: Int) (out: Int) { out = apply(target) }",
"C005",
"runtime values",
);
rejected(
"bad(transform: handler() (out: Int)) (out: Int) { saved = transform\nout = 1 }",
"C005",
"static arguments",
);
rejected(
"bad(transform: handler() (out: Int)) (out: Int) { out = transform() }\ncmd entry = bad",
"C005",
"static handler",
);
rejected(
"apply(transform: handler() (out: Int)) (out: Int) { out = transform() }\nstart() (out: Int) { out = apply(start) }",
"C010",
"recursive",
);
}
#[test]
fn handler_rule_columns_remain_declarative_and_do_not_generate_runtime_arguments() {
let source = r#"
identity(value: Int) (out: Int) { out = value }
rule apply(value: Int, transform: handler(value: Int) (out: Int)) (out: Int)
| value | transform | out |
| - | - | transform(value) |
start() (out: Int) { out = apply(9, identity) }
"#;
let program = check(source).unwrap();
assert_eq!(program.functions.len(), 3);
rejected(
&source.replace("| - | - |", "| - | 1 |"),
"C005",
"static handler column",
);
}
#[test]
fn handler_failures_propagate_and_captured_errors_keep_handling_obligations() {
let source = r#"
type Outcome { Done(value: Int), error Bad(message: Text) }
checked(value: Int) (out: Int) { check value >= 1 else Outcome.Bad("positive required")
out = value }
apply(value: Int, transform: handler(value: Int) (out: Int)) (out: Int) { out = transform(value) }
capture(value: Int, transform: handler(value: Int) (out: Int)) (out: Outcome) { out = result(transform(value)) }
start(value: Int) (out: Int) { out = apply(value, checked) }
wrapped(value: Int) (out: Outcome) { out = capture(value, checked) }
"#;
let program = check(source).unwrap();
let start = program
.functions
.iter()
.find(|f| f.signature.source_name.ends_with(".start"))
.unwrap();
assert_eq!(start.failures, [Failure::Choice(1, 1)].into());
rejected(
&source.replace(
"out = result(transform(value))",
"lost: Outcome = result(transform(value))\nout = Done(0)",
),
"C012",
"not handled",
);
rejected(
&source.replace("Outcome.Bad(\"positive required\")", "Invalid"),
"C005",
"matching branch",
);
}
#[test]
fn handler_only_rules_keep_the_source_input_requirement() {
check("value() (out: Int) { out = 1 }\nrule apply(transform: handler() (out: Int)) (out: Int)\n| transform | out |\n| - | transform() |\nstart() (out: Int) { out = apply(value) }").unwrap();
rejected(
"rule empty() (out: Int)\n| out |\n| 1 |",
"C009",
"at least one input",
);
}
#[test]
fn stronger_handler_outputs_remove_only_proved_instance_checks() {
let program = check("positive(value: Int) (out: Int >= 1) { out = 1 }\napply(value: Int, transform: handler(value: Int) (out: Int)) (out: Int >= 1) { checked = transform(value)\ncheck checked >= 1 else Invalid\nout = checked }\nstart() (out: Int) { out = apply(0, positive) }").unwrap();
let apply = program
.functions
.iter()
.find(|f| f.signature.source_name.ends_with(".apply"))
.unwrap();
assert!(apply.failures.is_empty());
let Body::Statements { statements, .. } = &apply.body else {
panic!()
};
assert!(
!statements
.iter()
.any(|statement| matches!(statement, Statement::Check { .. }))
);
rejected(
"apply(value: Int >= 1, transform: handler(value: Int) (out: Int)) (out: Int) { check value >= 1 else Invalid\nout = transform(value) }",
"C012",
"already guaranteed",
);
}
+356
View File
@@ -0,0 +1,356 @@
use super::*;
#[test]
fn walks_bind_a_named_step_and_preserve_the_concrete_state_contract() {
let next = "rule next(state: Int) (out: Walk<Int, Int>)\n| state | out |\n| > 0 | Next(state, state - 1) |\n| <= 0 | Done |\n";
check(&format!("{next}loop values(seed: Int) (out: List<Int>)\n| each value in walk(seed, next) | result |\n| out | list value |\n")).unwrap();
check(&format!("{next}loop values(seed: Int, step: handler(state: Int) (out: Walk<Int, Int>)) (out: List<Int>)\n| each value in walk(seed, step) | result |\n| out | list value |\nstart(seed: Int) (out: List<Int>) {{ out = values(seed, next) }}")).unwrap();
rejected(
"next(state: Int) (out: Walk<Int, Text>) { out = Next(state, \"\") }\nloop values() (out: List<Int>)\n| each value in walk(0, next) | result |\n| out | list value |\n",
"C005",
"preserve its state type",
);
rejected(
"next(state: Int >= 0) (out: Walk<Int, Int>) { out = Done }\nloop values() (out: List<Int>)\n| each value in walk(0, next) | result |\n| out | list value |\n",
"C008",
"after every Next",
);
rejected(
"next(state: Int) (out: Int) { out = state }\nloop values() (out: List<Int>)\n| each value in walk(0, next) | result |\n| out | list value |\n",
"C005",
"Walk<T, S>",
);
rejected(
"loop values(seed: Int) (out: List<Int>)\n| each value in walk(seed, values) | result |\n| out | list value |\n",
"C010",
"recursive",
);
check("walk(seed: Int) (out: List<Int>) { out = [seed] }\nloop values(seed: Int) (out: List<Int>)\n| each value in walk(seed) | result |\n| out | list value |\n").unwrap();
}
#[test]
fn walks_do_not_invent_future_failures_or_drop_current_state_failures() {
let next = "type State { Ready, error Broken }\nrule next(state: Int) (out: Walk<State, Int>)\n| state | out |\n| > 0 | Next(State.Broken, state - 1) |\n| <= 0 | Done |\n";
let first = format!(
"{next}loop first(seed: Int) (out: State?)\n| each value in walk(seed, next) | result |\n| out | first value |\n"
);
check(&first).unwrap();
rejected(
&format!("{first}missing(seed: Int) () {{ ignored = first(seed) }}"),
"C012",
"failure is not handled",
);
rejected(
&format!(
"{next}loop mixed(seed: Int) (out: State?, count: Int)\n| each value in walk(seed, next) | result |\n| out | first value |\n| count | count |\n"
),
"C012",
"failure is not handled",
);
let next = "type State { Ready, error Broken }\nrule next(state: State) (out: Walk<Int, State>)\n| state | out |\n| Ready | Next(1, State.Broken) |\n| Broken | fail(state) |\n";
rejected(
&format!(
"{next}loop first() (out: Int?)\n| each value in walk(State.Ready, next) | result |\n| out | first value |\n"
),
"C012",
"failure is not handled",
);
check(&format!("{next}loop all() (out: Int)\n| each value in walk(State.Ready, next) | result |\n| out | sum value |\n")).unwrap();
}
use dever::compiler::check::ownership;
#[test]
fn indexing_has_a_nominal_duplicate_failure_and_preserves_elements() {
let prefix = "loop unique(values: List<Int>) (out: Map<Int, Int>)\n| each value in values | result |\n| out | index value |\n";
let program = check(prefix).unwrap();
assert_eq!(
program.functions[0].failures,
[Failure::Choice(COLLECTION_ERROR, 0)].into()
);
check(&format!("{prefix}type Result {{ Ready(value: Map<Int, Int>), error Duplicate(reason: dever.collection.Error) }}\nf(values: List<Int>) (out: Result) {{ out = result(unique(values)) }}")).unwrap();
rejected(
&format!(
"{prefix}type Result {{ Ready(value: Map<Int, Int>), error Duplicate }}\nf(values: List<Int>) (out: Result) {{ out = result(unique(values)) }}"
),
"C005",
"nominally matching",
);
check("type State { Ready, error Broken }\nloop indexed(values: List<State>) (out: Map<Int, State>)\n| each value in values | result |\n| out | index 0 |\n").unwrap();
rejected(
"type State { Ready, error Broken }\nloop indexed(values: List<State>) (out: Map<Int, State>)\n| each value in values | value | result |\n| out | Ready | index 0 |\n",
"C012",
"failure is not handled",
);
check(
"rule raise(value: dever.collection.Error) ()\n| value | do |\n| DuplicateKey | fail(value) |\n",
)
.unwrap();
for kind in ["Map<Int, Text>", "Map<Int, List<Int>>", "Map<Text, Int>"] {
rejected(
&format!(
"loop f(values: List<Int>) (out: {kind})\n| each value in values | result |\n| out | index value |\n"
),
"C005",
"",
);
}
}
#[test]
fn grouping_keeps_source_elements_types_and_error_obligations() {
let prefix = "type State { Ready, error Broken }\n";
check(&format!("{prefix}loop all(values: List<State>) (out: Map<Int, List<State>>)\n| each value in values | result |\n| out | group 0 |\n")).unwrap();
rejected(
&format!(
"{prefix}loop missing(values: List<State>) (out: Map<Int, List<State>>)\n| each value in values | value | result |\n| out | Ready | group 0 |\n"
),
"C012",
"failure is not handled",
);
for (kind, columns, result) in [
("Map<Int, Int>", "", "group value"),
("Map<Int, List<Text>>", "", "group value"),
("Map<Text, List<Int>>", "", "group value"),
("Map<Int, List<Int>>", "take |", "1 | group value"),
("Map<Int, List<Int>>", "sort |", "[value.asc] | group value"),
] {
assert_eq!(check(&format!("loop f(values: List<Int>) (out: {kind})\n| each value in values | {columns} result |\n| out | {result} |\n")).err().unwrap().code, "C005");
}
let program = check("loop names(values: List<Text>) (out: Map<Int, List<Text>>)\n| each value in values | result |\n| out | group length(value) |\n").unwrap();
assert_eq!(ownership::analyze(&program)[0].parameters, [Storage::Owned]);
}
#[test]
fn loops_bind_each_output_once_and_share_the_call_kind() {
let program = check("loop total(values: List<Int>) (out: Int)\n| each value in values | result |\n| out | sum value |\nflow start(values: List<Int>) (out: Int)\n| step | kind | do |\n| out | loop | total(values) |\n").unwrap();
assert!(matches!(program.functions[0].body, Body::Loop(_)));
for source in [
"loop f(values: List<Int>) (n: Int)\n| each value in values | result |\n| n | count |\n| n | count |\n",
"loop f(values: List<Int>) (n: Int, missing: Int)\n| each value in values | result |\n| n | count |\n",
"loop f(values: List<Int>) (n: Int)\n| each value in values | result |\n| wrong | count |\n",
"loop f(values: List<Int>) (n: Bool)\n| each value in values | result |\n| n | sum value |\n",
"loop f(values: List<Float>) (n: Float?)\n| each value in values | result |\n| n | min value |\n",
"loop f(values: List<Int>) (n: Int)\n| each values in values | result |\n| n | count |\n",
"loop f(values: Int) (n: Int)\n| each value in values | result |\n| n | count |\n",
"loop f() (n: Int)\n| each value in range(1) | result |\n| n | count |\n",
"loop f(values: List<Int>) ()\n| each value in values | result |\n| - | count |\n",
"id(value: Int) (out: Int) { out = value }\nloop f(values: List<Int>) ()\n| each value in values | result |\n| - | do id(value) |\n",
] {
assert_eq!(check(source).err().unwrap().code, "C005", "{source}");
}
rejected(
"loop f(values: List<Int>) (n: Int >= 1)\n| each value in values | result |\n| n | count |\n",
"C008",
"empty input",
);
rejected(
"loop f(values: List<Int>) (n: Int, total: Int)\n| each value in values | result |\n| n | count |\n| total | sum n |\n",
"C004",
"unknown",
);
}
#[test]
fn loops_cannot_erase_error_elements_through_count_or_short_circuit() {
let prefix = "type State { Ready, error Broken }\n";
for aggregate in ["count", "first value"] {
let kind = if aggregate == "count" {
"Int"
} else {
"State?"
};
rejected(
&format!(
"{prefix}loop f(values: List<State>) (out: {kind})\n| each value in values | result |\n| out | {aggregate} |\n"
),
"C012",
"failure is not handled",
);
}
check(&format!("{prefix}loop f(values: List<State>) (out: List<State>)\n| each value in values | result |\n| out | list value |\n")).unwrap();
check(&format!("{prefix}rule consume(value: State) (out: Int)\n| value | out |\n| Ready | 1 |\n| Broken | fail(State.Broken) |\nloop f(values: List<State>) (out: Int)\n| each value in values | result |\n| out | sum consume(value) |\n")).unwrap();
rejected(
&format!(
"{prefix}loop empty(values: List<State>) (out: List<State>)\n| each value in values | result |\n| out | list value |\nf() (n: Int) {{ values: List<State> = []\nignored = append(empty(values), State.Broken)\nn = 1 }}"
),
"C012",
"failure is not handled",
);
rejected(
&format!(
"{prefix}loop f(values: List<Int>, state: State) (out: List<State>)\n| each value in values | result |\n| out | list state |\n"
),
"C012",
"failure is not handled",
);
}
#[test]
fn loop_ownership_borrows_captures_and_moves_elements_only_at_last_use() {
let program = check("loop sizes(values: List<Text>) (n: Int)\n| each value in values | result |\n| n | sum length(value) |\nloop copied(values: List<Text>) (out: List<Text>)\n| each value in values | result |\n| out | list value |\nloop repeated(values: List<Int>, label: Text) (out: List<Text>)\n| each value in values | result |\n| out | list label |\n").unwrap();
let decisions = ownership::analyze(&program);
assert_eq!(decisions[0].parameters, [Storage::Borrowed]);
assert!(
!decisions[0]
.reads
.values()
.any(|read| *read == Access::Clone)
);
assert_eq!(decisions[1].parameters, [Storage::Owned]);
assert!(
!decisions[1]
.reads
.values()
.any(|read| *read == Access::Clone)
);
assert_eq!(
decisions[2].parameters,
[Storage::Borrowed, Storage::Borrowed]
);
assert!(
decisions[2]
.reads
.values()
.any(|read| *read == Access::Clone)
);
}
#[test]
fn filters_are_infallible_typed_and_cannot_hide_error_elements() {
for (source, message) in [
(
"loop f(values: List<Int>) (n: Int)\n| each value in values | value | result |\n| n | other | count |\n",
"other",
),
(
"loop f(values: List<Int>) (n: Int)\n| each value in values | value | result |\n| n | true | count |\n",
"input type",
),
(
"checked(value: Int) (out: Int) { check value > 0 else Invalid\nout = value }\nloop f(values: List<Int>) (n: Int)\n| each value in values | checked(value) | result |\n| n | > 0 | count |\n",
"must not propagate",
),
] {
rejected(source, "C005", message);
}
rejected(
"type State { Ready, error Broken }\nloop f(values: List<State>) (out: List<State>)\n| each value in values | value | result |\n| out | Ready | list value |\n",
"C012",
"failure is not handled",
);
check("loop f(values: List<Text>) (n: Int)\n| each value in values | length(value) | result |\n| n | >= 1 | count |\n").unwrap();
}
#[test]
fn filter_facts_remove_repeated_checks_without_leaking_between_rows() {
check("positive(value: Int >= 1) (out: Int) { out = value }\nloop f(values: List<Int>) (out: List<Int>)\n| each value in values | value | result |\n| out | > 0 | list positive(value) |\n").unwrap();
rejected(
"positive(value: Int >= 1) (out: Int) { out = value }\nloop f(values: List<Int>) (first: List<Int>, second: List<Int>)\n| each value in values | value | result |\n| first | > 0 | list positive(value) |\n| second | - | list positive(value) |\n",
"C008",
"range",
);
check("loop f(values: List<Text?>) (out: List<Text>)\n| each value in values | value | result |\n| out | \"甲\" | list value |\n").unwrap();
}
#[test]
fn filter_payload_bindings_keep_variant_types_ranges_and_row_scope() {
let prefix = "type Event { Named(label: Text), Tagged(label: Text), Number(label: Int) }\n";
check(&format!("{prefix}loop f(values: List<Event>) (out: List<Text>)\n| each value in values | value | result |\n| out | Named(label), Tagged(label) | list label |\n")).unwrap();
for (condition, message) in [
("Named(value)", "shadows"),
("Named(label), Number(label)", "same names and types"),
("Named(label), -", "same names and types"),
("Named(label), Tagged(other)", "same names and types"),
] {
rejected(
&format!(
"{prefix}loop f(values: List<Event>) (out: List<Text>)\n| each value in values | value | result |\n| out | {condition} | list label |\n"
),
"C005",
message,
);
}
rejected(
&format!(
"{prefix}loop f(values: List<Event>) (labels: List<Text>, out: List<Text>)\n| each value in values | value | result |\n| labels | Named(label) | list label |\n| out | - | list label |\n"
),
"C004",
"unknown",
);
}
#[test]
fn filters_keep_every_error_variant_obligation_across_all_rows() {
let prefix = "type State { Ready, error Offline, error Denied }\n";
check(&format!("{prefix}loop f(values: List<State>) (offline: List<State>, denied: List<State>)\n| each value in values | value | result |\n| offline | Offline | list value |\n| denied | Denied | list value |\n")).unwrap();
check("type State { Ready, error Broken }\nloop f(values: List<State>) ()\n| each value in values | value | result |\n| - | Broken | do fail(value) |\n").unwrap();
rejected(
&format!(
"{prefix}loop f(values: List<State>) (offline: List<State>)\n| each value in values | value | result |\n| offline | Offline | list value |\n"
),
"C012",
"failure is not handled",
);
rejected(
"type State { Ready, error Broken }\nloop f(values: List<State>, enabled: Bool) (out: List<State>)\n| each value in values | value | enabled | result |\n| out | Broken | true | list value |\n",
"C012",
"failure is not handled",
);
rejected(
"type State { Ready, error Broken }\nloop f(values: List<State>) (out: State?)\n| each value in values | value | result |\n| out | Broken | first value |\n",
"C012",
"failure is not handled",
);
}
#[test]
fn take_is_list_only_initialized_from_inputs_and_cannot_discard_errors() {
rejected(
"loop f(values: List<Int>) (out: Int)\n| each value in values | take | result |\n| out | 1 | count |\n",
"C005",
"list rows",
);
rejected(
"loop f(values: List<Int>, size: Int) (out: List<Int>)\n| each value in values | take | result |\n| out | size | list value |\n",
"C008",
"nonnegative",
);
rejected(
"loop f(values: List<Int>) (out: List<Int>)\n| each value in values | take | result |\n| out | value | list value |\n",
"C004",
"unknown",
);
for size in ["0", "1"] {
rejected(
&format!(
"type State {{ Ready, error Broken }}\nloop f(values: List<State>) (out: List<State>)\n| each value in values | take | result |\n| out | {size} | list value |\n"
),
"C012",
"failure is not handled",
);
}
}
#[test]
fn sorting_requires_explicit_directions_and_infallible_total_order_keys() {
for (kind, keys, message) in [
("Int", "value.asc", "list of asc"),
("Int", "[value]", ".asc or .desc"),
("Int", "[value.random]", ".asc or .desc"),
("Int", "[]", "at least one key"),
("Float", "[value.asc]", "total order"),
("Text?", "[value.asc]", "total order"),
] {
rejected(
&format!(
"loop f(values: List<{kind}>) (out: List<{kind}>)\n| each value in values | sort | result |\n| out | {keys} | list value |\n"
),
"C005",
message,
);
}
rejected(
"loop f(values: List<Int>) (out: Int)\n| each value in values | sort | result |\n| out | [value.asc] | count |\n",
"C005",
"list rows",
);
rejected(
"positive(value: Int) (out: Int) { check value > 0 else Invalid\nout = value }\nloop f(values: List<Int>) (out: List<Int>)\n| each value in values | sort | result |\n| out | [positive(value).asc] | list value |\n",
"C005",
"must not propagate",
);
}
+216
View File
@@ -0,0 +1,216 @@
use super::*;
use dever::compiler::check::ownership;
fn decisions(text: &str) -> (Program, Vec<Ownership>) {
let program = check(text).unwrap();
let decisions = ownership::analyze(&program);
(program, decisions)
}
#[test]
fn disjoint_fields_move_without_cloning_the_record_or_other_fields() {
let (_, decisions) = decisions(
"type Pair { left: Text, right: Text }\nswap(value: Pair) (out: Pair) { out = Pair { left = value.right, right = value.left } }\nshared(value: Pair) (out: Pair, original: Pair) { out = Pair { left = value.right, right = value.left }\noriginal = value }\nsame(value: Pair) (out: Pair) { out = Pair { left = value.left, right = value.left } }",
);
assert!(
!decisions[0]
.reads
.values()
.any(|access| *access == Access::Clone)
);
assert_eq!(decisions[0].parameters, vec![Storage::Owned]);
assert_eq!(
decisions[1]
.reads
.values()
.filter(|access| **access == Access::Clone)
.count(),
2
);
assert_eq!(
decisions[2]
.reads
.values()
.filter(|access| **access == Access::Clone)
.count(),
1
);
}
#[test]
fn read_only_parameters_and_aliases_borrow_without_clones() {
let (_, decisions) = decisions(
"size(value: Text) (n: Int) { alias = value\nn = length(alias) }\nf(value: Text) (n: Int) { n = size(value) }",
);
for decision in &decisions {
assert_eq!(decision.parameters, vec![Storage::Borrowed]);
assert!(
!decision
.reads
.values()
.any(|access| matches!(access, Access::Clone | Access::Move))
);
}
assert_eq!(decisions[0].locals[1], Storage::Borrowed);
}
#[test]
fn outputs_move_at_last_use_and_copy_only_when_the_original_is_still_needed() {
let (_, decisions) = decisions(
"identity(value: Text) (out: Text) { out = value }\nf(value: Text) (first: Text, second: Text) { first = identity(value)\nsecond = value }",
);
assert_eq!(decisions[0].parameters, vec![Storage::Owned]);
assert_eq!(decisions[1].parameters, vec![Storage::Owned]);
assert_eq!(
decisions[1]
.reads
.values()
.filter(|access| **access == Access::Clone)
.count(),
1
);
assert_eq!(
decisions[0]
.reads
.values()
.filter(|access| **access == Access::Clone)
.count(),
0
);
}
#[test]
fn disjoint_rule_branches_do_not_force_copies_between_each_other() {
let (_, decisions) = decisions(
"rule choose(flag: Bool, value: Text) (out: Text)\n| flag | value | out |\n| true | - | value |\n| false | - | value |\n",
);
assert_eq!(
decisions[0].parameters,
vec![Storage::Owned, Storage::Owned]
);
assert_eq!(
decisions[0]
.reads
.values()
.filter(|access| **access == Access::Move)
.count(),
2
);
assert!(
!decisions[0]
.reads
.values()
.any(|access| *access == Access::Clone)
);
}
#[test]
fn scalar_field_reads_borrow_records_and_field_writes_move_after_computing_the_value() {
let (_, decisions) = decisions(
"type Item { name: Text, count: Int }\ncount(item: Item) (n: Int) { n = item.count }\nincrement(item: Item) (out: Item) { out = item\nout.count = out.count + 1 }",
);
assert_eq!(decisions[0].parameters, vec![Storage::Borrowed]);
assert_eq!(decisions[1].parameters, vec![Storage::Owned]);
assert!(
!decisions[1]
.reads
.values()
.any(|access| *access == Access::Clone)
);
}
#[test]
fn choice_payloads_move_together_but_clone_when_the_whole_value_is_returned() {
let (_, decisions) = decisions(
"type Pair { Both(first: Text, second: Text) }\nrule split(pair: Pair) (first: Text, second: Text)\n| pair | first | second |\n| Both(a, b) | a | b |\nrule keep(pair: Pair) (first: Text, whole: Pair)\n| pair | first | whole |\n| Both(a, b) | a | pair |\n",
);
assert_eq!(decisions[0].parameters, vec![Storage::Owned]);
assert!(
decisions[0]
.projections
.values()
.all(|access| *access == Access::Move)
);
assert_eq!(
decisions[1]
.projections
.values()
.filter(|access| **access == Access::Clone)
.count(),
1
);
}
#[test]
fn nonnull_check_borrows_or_moves_according_to_the_successful_use() {
let (_, decisions) = decisions(
"size(value: Text?) (n: Int) { check value != null else Invalid\nn = length(value) }\nread(value: Text?) (out: Text) { check value != null else Invalid\nout = value }",
);
assert_eq!(decisions[0].parameters, vec![Storage::Borrowed]);
assert_eq!(decisions[1].parameters, vec![Storage::Owned]);
assert_eq!(
decisions[0]
.projections
.values()
.copied()
.collect::<Vec<_>>(),
vec![Access::Borrow]
);
assert_eq!(
decisions[1]
.projections
.values()
.copied()
.collect::<Vec<_>>(),
vec![Access::Move]
);
}
#[test]
fn fresh_results_are_owned_locally_even_when_only_borrowed_later() {
let (_, decisions) = decisions(
"make() (value: Text?) { value = \"name\" }\nf() (n: Int) { value = make()\ncheck value != null else Invalid\nn = length(value) }",
);
assert_eq!(decisions[1].locals[0], Storage::Owned);
assert!(
!decisions[1]
.reads
.values()
.any(|access| *access == Access::Clone)
);
}
#[test]
fn borrowed_aliases_keep_owners_alive_only_until_the_last_read() {
let (_, decisions) = decisions(
"after(value: Text) (out: Text, n: Int) { alias = value\nout = value\nn = length(alias) }\nbefore(value: Text) (out: Text, n: Int) { alias = value\nn = length(alias)\nout = value }",
);
assert_eq!(
decisions[0]
.reads
.values()
.filter(|a| **a == Access::Clone)
.count(),
1
);
assert!(decisions[1].reads.values().all(|a| *a != Access::Clone));
}
#[test]
fn collection_lookup_borrows_until_the_last_element_use() {
let (_, decisions) = decisions(
"size(values: List<Text>, index: Int) (n: Int) { value = get(values, index)\ncheck value != null else NotFound\nn = length(value) }\nafter(values: List<Text>) (out: List<Text>, n: Int) { value = get(values, 0)\ncheck value != null else NotFound\nout = append(values, \"tail\")\nn = length(value) }\nbefore(values: List<Text>) (out: List<Text>, n: Int) { value = get(values, 0)\ncheck value != null else NotFound\nn = length(value)\nout = append(values, \"tail\") }",
);
assert_eq!(decisions[0].parameters[0], Storage::Borrowed);
assert_eq!(decisions[0].locals[2], Storage::Borrowed);
assert!(decisions[0].reads.values().all(|a| *a != Access::Clone));
assert_eq!(
decisions[1]
.reads
.values()
.filter(|a| **a == Access::Clone)
.count(),
1
);
assert!(decisions[2].reads.values().all(|a| *a != Access::Clone));
}
+73
View File
@@ -0,0 +1,73 @@
use super::*;
#[test]
fn settings_reject_unbounded_shapes_and_preserve_proven_ranges() {
for kind in ["Map<Text, Int>", "Bytes", "Json", "Result"] {
rejected(
&format!("type Result {{ Ready, error Failed }}\nsetting value: {kind}"),
"C005",
"setting",
);
}
rejected(
"setting value: handler(x: Int) (y: Int)",
"C005",
"handler is only allowed",
);
rejected(
"type Value { Data(value: Text) }\nsetting value: Value",
"C005",
"setting",
);
rejected("setting lower: Int >= 20 and <= 1", "C008", "range");
rejected(
"setting value: Int >= 1\nf() (out: Int >= 2) { out = value }",
"C008",
"cannot prove",
);
rejected(
"setting value: Int >= 1\nf() () { check value >= 1 else Invalid }",
"C012",
"already guaranteed",
);
check("setting value: Int >= 1\nf() (out: Int >= 1) { out = value }").unwrap();
}
#[test]
fn secret_cannot_be_compared_converted_or_output_through_containers() {
for source in [
"f(left: Secret, right: Secret) (out: Bool) { out = left == right }",
"type Box { key: Secret }\nf(left: Box, right: Box) (out: Bool) { out = left != right }",
"f(left: List<Secret>, right: List<Secret>) (out: Bool) { out = left == right }",
"f(values: List<Secret>, item: Secret) (out: Bool) { out = contains(values, item) }",
"type Token { Ready(key: Secret), Missing }\nf(left: Token, right: Token) (out: Bool) { out = left == right }",
"parts(value: Secret) (key: Secret, count: Int) { key = value\ncount = 1 }\nf(left: Secret, right: Secret) (out: Bool) { out = parts(left) == parts(right) }",
] {
rejected(source, "C005", "Secret cannot be compared");
}
for kind in ["Secret", "Secret?", "List<Secret>", "Box"] {
rejected(
&format!(
"type Box {{ value: Secret }}\nf(value: {kind}) (out: {kind}) {{ out = value }}\ncmd show = app.f"
),
"C005",
"Secret cannot be encoded or output",
);
}
rejected(
"f(value: Secret) (out: Text) { out = value }",
"C005",
"expected Text",
);
rejected(
"f(value: Secret) (out: Int) { out = length(value) }",
"C005",
"builtin does not accept",
);
rejected(
"const key: Secret = \"not-a-secret-constructor\"",
"C005",
"expected Secret",
);
check("setting key: Secret\nf(value: Secret?) (out: Bool) { out = value != null }").unwrap();
}