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

+471
View File
@@ -0,0 +1,471 @@
use dever::compiler::{check::program, model::*, project::Module};
use dever::syntax::{diagnostic::Diagnostic, lex, parse, source::Source};
fn check(text: &str) -> Result<Program, Diagnostic> {
let source = Source::new(0, "app.dever", text.into());
let (tokens, diagnostics, _) = lex::scan_with_diagnostics(&source, 0..text.len());
if let Some(error) = diagnostics.into_iter().next() {
return Err(error);
}
let parsed = parse::parse(tokens);
assert!(parsed.diagnostics.is_empty(), "{:?}", parsed.diagnostics);
program::check(&parsed.declarations, &[Module::standalone()])
}
fn rejected(text: &str, code: &str, message: &str) {
let error = check(text).err().expect("program must be rejected");
assert_eq!(error.code, code, "{error}");
assert!(error.message.contains(message), "{error}");
}
#[test]
fn inline_rules_prove_coverage_in_the_current_scope() {
let source = |arms: &str| {
format!(
"flow allowed(level:Int) (out:Bool) {{ privileged = level > 1\nout = rule privileged {{ {arms} }} }}"
)
};
rejected(&source("true => true"), "C009", "does not cover");
rejected(&source("- => false\ntrue => true"), "C009", "overlap");
rejected(&source("true => true\nfalse => 3"), "C005", "expected");
rejected(
"flow f(a:Bool) (out:Bool) { out = rule unknown { - => a } }",
"C004",
"unknown rule selector",
);
}
#[test]
fn inline_rules_keep_failure_obligations_on_each_success_path() {
let prefix = "type State { Ready, error Broken }\nflow select(flag:Bool, value:State) (out:State) { out = rule flag { true => value\nfalse => ";
check(&format!("{prefix}value }} }}")).unwrap();
rejected(
&format!("{prefix}State.Ready }} }}"),
"C012",
"failure is not handled",
);
check("type State { Ready, error Broken }\nflow pass(value:State) (out:State) { out = rule value { Ready => State.Ready\nBroken => value } }").unwrap();
}
#[test]
fn rule_null_complements_narrow_every_concrete_optional_type() {
for kind in [
"DateTime",
"Date",
"Time",
"Duration",
"Float",
"Uuid",
"Bytes",
"Json",
"List<Int>",
"Map<Text, Int>",
"Item",
] {
let prefix = "type Item { number: Int }\n";
check(&format!("{prefix}rule f(value: {kind}?) (out: {kind})\n| value | out |\n| null | fail(Invalid) |\n| other | value |\n")).unwrap();
// 没有区分 null 的通配格仍不能声称输入非空。
rejected(
&format!(
"{prefix}rule f(value: {kind}?) (out: {kind})\n| value | out |\n| - | value |\n"
),
"C005",
"expected",
);
let overlap = check(&format!(
"{prefix}rule f(value: {kind}?) (out: Int)\n| value | out |\n| null | 0 |\n| - | 1 |\n"
))
.err()
.unwrap();
assert!(overlap.message.contains("overlap"), "{overlap}");
let missing = check(&format!(
"{prefix}rule f(value: {kind}?) (out: Int)\n| value | out |\n| null | 0 |\n"
))
.err()
.unwrap();
assert!(missing.message.contains("<non-null value>"), "{missing}");
}
}
#[test]
fn collection_nulls_require_a_concrete_element_context() {
for value in ["[null]", "[[null]]", "{ \"a\" = null }"] {
rejected(
&format!("f() (n: Int) {{ values = {value}\nn = length(values) }}"),
"C005",
"concrete",
);
}
check("f() (values: List<Text?>) { values = [null] }").unwrap();
check("f() (values: List<Text?>, lookup: Map<Int, Bool>) { values = append([], null)\nlookup = put({}, 1, true) }").unwrap();
rejected(
"f() (values: List<Text>) { values = append([], true) }",
"C005",
"expected",
);
}
#[test]
fn failures_propagate_without_wrappers_and_pure_calls_remain_infallible() {
let program = check("identity(x: Int) (y: Int) { y = x }\npositive(x: Int) (y: Int >= 1) { check x >= 1 else Invalid\ny = x }\nstart(x: Int) (y: Int) { y = positive(identity(x)) }\n").unwrap();
assert!(program.functions[0].failures.is_empty());
assert_eq!(
program.functions[1].failures,
[Failure::Api(ApiError::Invalid)].into()
);
assert_eq!(program.functions[2].failures, program.functions[1].failures);
}
#[test]
fn inputs_are_read_only_and_outputs_must_be_assigned() {
rejected("f(x: Int) (y: Int) { x = 2\ny = x }", "C005", "read-only");
rejected(
"type Item { count: Int }\nf(x: Item) (y: Item) { x.count = 2\ny = x }",
"C005",
"read-only",
);
rejected("f(x: Int) (y: Int) { z = x }", "C005", "not assigned");
rejected("f() (y: Int) { y = missing }", "C004", "unknown");
rejected(
"f(x: Int) (y: Int) { y = x }\ng() (y: Int) { y = f(true) }",
"C005",
"expected",
);
}
#[test]
fn bound_user_calls_are_not_reinterpreted_as_intrinsics() {
check("result(value: Int) (out: Int) { out = value }\nf() (out: Int) { out = result(1) }")
.unwrap();
rejected(
"fail(value: Int) (out: Int) { out = value }\nrule f(value: Bool) (x: Int, y: Int)\n| value | x | y |\n| - | fail(1) | - |\n",
"C009",
"every output",
);
}
#[test]
fn local_reassignment_creates_new_values_without_freezing_inferred_ranges() {
let program = check("f() (y: Int) { x = 1\nx = 2\ny = x }").unwrap();
let Body::Statements {
statements,
outputs,
..
} = &program.functions[0].body
else {
panic!()
};
assert_eq!(statements.len(), 3);
assert_eq!(outputs, &[2]);
assert_eq!(program.functions[0].locals.len(), 3);
rejected(
"f() (y: Int) { x: Int >= 1 = 1\nx = 0\ny = x }",
"C008",
"cannot prove",
);
}
#[test]
fn nullable_guard_establishes_one_nonnull_binding() {
let program = check("type Item { count: Int }\nf(item: Item?) (y: Int) { check item != null else NotFound\ny = item.count }").unwrap();
let Body::Statements { statements, .. } = &program.functions[0].body else {
panic!()
};
assert!(matches!(statements[0], Statement::NonNull { .. }));
assert_eq!(statements.len(), 2);
rejected(
"type Item { count: Int }\nf(item: Item?) (y: Int) { y = item.count }",
"C005",
"nullable",
);
rejected(
"f(x: Int?) (y: Int) { check x != null else Invalid\ncheck x != null else Invalid\ny = x }",
"C012",
"redundant",
);
}
#[test]
fn guards_narrow_ranges_and_assignment_invalidates_previous_facts() {
check("need(x: Int >= 1) (y: Int) { y = x }\nf(x: Int) (y: Int) { check x >= 1 else Invalid\ny = need(x) }").unwrap();
rejected(
"f(x: Int >= 1) (y: Int) { check x >= 1 else Invalid\ny = x }",
"C012",
"redundant",
);
rejected(
"f(x: Int >= 1) (y: Int) { check x < 1 else Invalid\ny = x }",
"C012",
"always fails",
);
rejected(
"need(x: Int >= 1) (y: Int) { y = x }\nf(x: Int) (y: Int) { local = x\ncheck local >= 1 else Invalid\nlocal = 0\ny = need(local) }",
"C008",
"cannot prove",
);
}
#[test]
fn integer_success_ranges_survive_possible_overflow() {
check("f(x: Int >= 0) (y: Int >= 1) { y = x + 1 }").unwrap();
check("f(x: Int >= 1) (y: Int >= 2) { y = x * 2 }").unwrap();
check("f(x: Int <= 0) (y: Int >= 0) { y = -x }").unwrap();
check("f(x: Int) (y: Int >= -9 and <= 9) { y = x % 10 }").unwrap();
rejected(
"f(x: Int >= 9223372036854775806) (y: Int) { y = x + 2 }",
"C008",
"always faults",
);
}
#[test]
fn arithmetic_preserves_exact_numbers_and_rejects_certain_faults() {
check("f() (x: Int, y: Decimal) { x = -9223372036854775808\ny = 0.1000000000000000000000000000000001 }").unwrap();
check("f() (x: Decimal) { x = 1 / 3 }").unwrap();
check("f(x: Float) (y: Float) { y = x / 0.0 }").unwrap();
for value in [
"9223372036854775807 + 1",
"-9223372036854775808 % -1",
"1 // 0",
] {
rejected(
&format!("f() (x: Int) {{ x = {value} }}"),
"C008",
"always faults",
);
}
rejected("f() (x: Decimal) { x = 1 / 0 }", "C008", "always faults");
}
#[test]
fn records_keep_source_evaluation_order_and_require_complete_fields() {
let program = check("type Pair { first: Int, second: Int }\nf() (value: Pair) { value = Pair { second = 2, first = 1 } }").unwrap();
let Body::Statements { statements, .. } = &program.functions[0].body else {
panic!()
};
let Statement::Assign { value, .. } = &statements[0] else {
panic!()
};
let ExpressionKind::Record(_, fields) = &value.kind else {
panic!()
};
assert_eq!(
fields.iter().map(|(index, _)| *index).collect::<Vec<_>>(),
vec![1, 0]
);
rejected(
"type Pair { first: Int, second: Int }\nf() (value: Pair) { value = Pair { first = 1 } }",
"C005",
"every declared field",
);
rejected(
"type Pair { first: Int, second: Int }\nf() (value: Pair) { value = Pair { first = 1, first = 2 } }",
"C005",
"duplicate",
);
}
#[test]
fn choice_short_names_work_in_comparisons_and_rules() {
check("type Status { Active, Inactive }\nf(status: Status) (yes: Bool) { yes = status == Active }").unwrap();
check("type Status { Active, Inactive }\nf(status: Status) (yes: Bool) { yes = Active == status }").unwrap();
check("type Status { Active, Inactive }\nrule f(status: Status) (next: Status)\n| status | next |\n| Active | Inactive |\n| Inactive | Active |\n").unwrap();
}
#[test]
fn rule_results_use_declared_ranges_and_column_complements() {
check("rule f(x: Int >= 1 and <= 9) (y: Int >= 1 and <= 9)\n| x | y |\n| < 5 | x |\n| other | x |\n").unwrap();
check("rule f(x: Int) (y: Int >= 0)\n| x | y |\n| < 0 | 0 |\n| other | x |\n").unwrap();
check("rule f(x: Int) (y: Int >= 1 and <= 3)\n| x | y |\n| 1, 3 | x |\n| other | 2 |\n")
.unwrap();
}
#[test]
fn ordinary_functions_cannot_hide_unused_results() {
rejected(
"value() (x: Int) { x = 1 }\nf() () { value() }",
"C005",
"zero-output",
);
check("stop() () { fail(Invalid) }\nf() () { stop() }").unwrap();
rejected(
"f() (x: Int) { fail(Invalid)\nx = 1 }",
"C012",
"unreachable",
);
}
#[test]
fn combined_payload_alternatives_keep_only_common_guarantees() {
check("type Value { Small(x: Int >= 1 and <= 3), Large(x: Int >= 8 and <= 9) }\nrule f(value: Value) (x: Int >= 1 and <= 9)\n| value | x |\n| Small(number), Large(number) | number |\n").unwrap();
rejected(
"type Value { Small(x: Int >= 1 and <= 3), Large(x: Int >= 8 and <= 9) }\nrule f(value: Value) (x: Int >= 1 and <= 3)\n| value | x |\n| Small(number), Large(number) | number |\n",
"C008",
"cannot prove",
);
}
#[test]
fn reassignment_after_narrowing_preserves_the_original_nullable_contract() {
check("f(input: Int?) (y: Int?) { local = input\ncheck local != null else Invalid\nlocal = null\ny = local }").unwrap();
check("f(input: Int) (y: Decimal) { y = input // 2 }").unwrap();
}
#[test]
fn recursive_types_and_invalid_map_keys_are_rejected_before_generation() {
for text in [
"type Node { next: Node? }",
"type Node { children: List<Node> }",
"type First { next: Second }\ntype Second { previous: First }",
] {
rejected(text, "C010", "recursive types");
}
for text in [
"type Bad { values: Map<Float, Int> }",
"f(values: Map<Decimal, Int>) () {}",
"f() () { values = { 1.2 = 1 } }",
"type Key { Value(x: Int) }\nf(values: Map<Key, Int>) () {}",
] {
rejected(text, "C005", "Map key");
}
check("type Key { First, Second }\nf(values: Map<Key, Int>) (next: Map<Key, Int>) { next = values }").unwrap();
}
#[test]
fn full_semantic_analysis_handles_ten_thousand_functions() {
let mut source = String::from("step0() (x: Int) { x = 0 }\n");
for index in 1..10_000 {
source.push_str(&format!(
"step{index}() (x: Int) {{ x = step{}() + 1 }}\n",
index - 1
));
}
let program = check(&source).unwrap();
assert_eq!(program.functions.len(), 10_000);
assert!(
program
.functions
.iter()
.all(|function| function.failures.is_empty()
&& function.failure_summary.output.is_some())
);
}
#[path = "program/constants.rs"]
mod constants;
#[path = "program/failure.rs"]
mod failure;
#[path = "program/flow.rs"]
mod flow;
#[path = "program/fold.rs"]
mod fold;
#[path = "program/handler.rs"]
mod handler;
#[path = "program/iteration.rs"]
mod iteration;
#[path = "program/ownership.rs"]
mod ownership;
#[test]
fn map_duplicate_constants_are_rejected_without_runtime_key_checks() {
for body in [
"{ \"key\" = 1, \"key\" = 2 }",
"{ true = 1, true = 2 }",
"{ -1 = 1, -1 = 2 }",
"{ 1 = 1, 1 + 0 = 2 }",
"{ Key.First = 1, Key.First = 2 }",
] {
rejected(
&format!("type Key {{ First, Second }}\nf() () {{ value = {body} }}"),
"C005",
"duplicate Map key",
);
}
check("f(first: Text, second: Text) (out: Map<Text, Int>) { out = { first = 1, second = 2 } }")
.unwrap();
}
#[test]
fn contains_borrows_elements_and_cannot_discharge_captured_failures() {
check("f(values: List<Text?>, value: Text?) (found: Bool) { found = contains(values, value) }")
.unwrap();
rejected(
"f(values: List<Int>) (found: Bool) { found = contains(values, true) }",
"C005",
"expected",
);
rejected(
"f(values: Map<Text, Int>) (found: Bool) { found = contains(values, \"a\") }",
"C005",
"accept",
);
rejected(
"type State { Ready, error Broken }\nf(values: List<State>) (found: Bool) { found = contains(values, State.Ready) }",
"C012",
"failure is not handled",
);
}
#[test]
fn map_updates_preserve_types_and_cannot_erase_failure_obligations() {
check("f(values: Map<Text, Int>) (out: Map<Text, Int>) { out = put(remove(values, \"old\"), \"new\", 1) }").unwrap();
rejected(
"f(values: Map<Text, Int>) (out: Map<Text, Int>) { out = put(values, 1, 2) }",
"C005",
"expected",
);
rejected(
"f(values: Map<Text, Int>) (out: Map<Text, Int>) { out = put(values, \"key\", true) }",
"C005",
"expected",
);
rejected(
"f(values: List<Int>) (out: List<Int>) { out = remove(values, 0) }",
"C005",
"accept",
);
for update in [
"remove(values, \"key\")",
"put(values, \"key\", State.Ready)",
] {
rejected(
&format!(
"type State {{ Ready, error Broken }}\nf(values: Map<Text, State>) (out: Map<Text, State>) {{ out = {update} }}"
),
"C012",
"failure is not handled",
);
}
check("type State { Ready, error Broken }\nf() (out: Map<Text, State>) { empty: Map<Text, State> = {}\nout = put(empty, \"key\", State.Broken) }").unwrap();
}
#[test]
fn map_entries_have_concrete_fields_and_keep_all_error_obligations() {
check("f(values: Map<Text, Int>) (out: List<MapEntry<Text, Int>>) { out = entries(values) }")
.unwrap();
check("type State { Ready, error Broken }\nf(values: Map<Text, State>) (out: List<MapEntry<Text, State>>) { out = entries(values) }").unwrap();
rejected(
"type State { Ready, error Broken }\nf(values: Map<Text, State>) (n: Int) { n = length(entries(values)) }",
"C012",
"failure is not handled",
);
rejected("f(value: MapEntry<Float, Text>) () {}", "C005", "Map key");
rejected(
"f(value: MapEntry<Text, Int>) (n: Int) { n = value.missing }",
"C004",
"unknown MapEntry field",
);
rejected(
"f(value: MapEntry<Text, Int>) (n: Int) { value.value = 2\nn = value.value }",
"C005",
"read-only",
);
rejected(
"f() (value: List<MapEntry<Text, Int>>) { values: Map<Text, Int> = {}\nvalue = entries(values) }\ncmd run = f",
"C005",
"wire boundary",
);
}
#[path = "program/settings.rs"]
mod settings;