use dever::syntax::{ast::*, lex, parse, source::Source}; fn parsed(text: &str) -> parse::Parsed { let source = Source::new(0, "app.dever", text.into()); let (tokens, diagnostics, _) = lex::scan_with_diagnostics(&source, 0..text.len()); assert!(diagnostics.is_empty(), "{diagnostics:?}"); parse::parse(tokens) } #[test] fn randomized_utf8_inputs_parse_without_panics_and_format_idempotently() { let fragments = [ "rule ", "flow ", "type ", "x", "Int", "Bool", "中文", "😀", "\0", "\r\n", "|", "(", ")", "{", "}", "[", "]", ":", ",", "=", "-", "+", "\"", "\\", "0", "true", "false", " ", "\n", ]; let mut state = 0x4d595df4d0f33173_u64; let mut next = || { state = state .wrapping_mul(6364136223846793005) .wrapping_add(1442695040888963407); state }; let verify = |text: &str| { let source = Source::new(0, "app.dever", text.into()); let (tokens, diagnostics, _) = lex::scan_with_diagnostics(&source, 0..text.len()); if !diagnostics.is_empty() { return; } let first = parse::parse(tokens); if !first.diagnostics.is_empty() { return; } let formatted = dever::compiler::format::format(&first.declarations); let second = parsed(&formatted); assert!( second.diagnostics.is_empty(), "input: {text:?}; formatted: {formatted:?}" ); assert_eq!( formatted, dever::compiler::format::format(&second.declarations), "{text:?}" ); }; for _ in 0..2048 { let count = next() as usize % 128; let text = (0..count) .map(|_| fragments[next() as usize % fragments.len()]) .collect::(); verify(&text); } // 随机无效输入之外,保证覆盖真实可格式化的函数和三表。 for _ in 0..256 { let value = next() % 10000; verify(&format!("pick(x:Int)(out:Int){{out=x+{value}}}")); verify(&format!( "rule pick(x:Bool)(out:Int)\n|x|out|\n|true|{value}|\n|false|0|" )); verify(&format!( "flow pick(x:Int)(out:Int)\n|step|kind|do|\n|out|calc|x+{value}|" )); verify(&format!( "loop pick(xs:List)(out:Int)\n|each x in xs|result|\n|out|sum x+{value}|" )); } } #[test] fn utf8_source_locations_keep_scalar_and_editor_columns_separate() { let source = Source::new(3, "app.dever", "甲😀x\r\n乙\rz".into()); assert_eq!(source.position(7), (1, 3)); assert_eq!(source.editor_position(7), (0, 3)); assert_eq!(source.position(10), (2, 1)); assert_eq!(source.position(14), (3, 1)); } #[test] fn numeric_separators_and_check_else_have_real_tokens() { let source = Source::new( 0, "app.dever", "1_000 1.2_5 1.5e+1_0 check value else Invalid".into(), ); let (tokens, diagnostics, _) = lex::scan_with_diagnostics(&source, 0..source.text.len()); assert!(diagnostics.is_empty(), "{diagnostics:?}"); assert_eq!(tokens[0].kind, lex::token::Kind::Number("1_000".into())); assert_eq!(tokens[2].kind, lex::token::Kind::Number("1.5e+1_0".into())); for text in ["1_", "1__0", "1.2_", "1e_2", "if true", ";"] { let source = Source::new(0, "app.dever", text.into()); let (_, diagnostics, _) = lex::scan_with_diagnostics(&source, 0..text.len()); assert!(!diagnostics.is_empty(), "{text}"); } } #[test] fn comments_survive_formatting_without_changing_generated_rust() { use dever::compiler::{ check::{ownership, program}, emit, format, project::Module, }; let plain = r##"half(value: Int) (out: Int) { out = value // 2 } flow run(value: Int) (out: Int) | step | kind | do | | out | calc | half(value) | label() (out: Text) { out = "# /* 字符串 */" } "##; let annotated = r##"# 允许中文、😀 和不参与解析的词:return | } half(value:Int)(out:Int) { out=value /* 只取完整份额。 余数留给调用方。 */ // 2 # 取整 } flow run(value:Int)(out:Int) |step|kind|do| # 此处用与普通函数相同的整数除法。 |out|calc|half( # 使用原始输入。 value )| label()(out:Text){out="# /* 字符串 */"} /* 文件结尾。 */"##; let parse_source = |text: String| { let mut source = Source::new(0, "app.dever", text); let (tokens, diagnostics, comments) = lex::scan_with_diagnostics(&source, 0..source.text.len()); assert!(diagnostics.is_empty(), "{diagnostics:?}"); let parsed = parse::parse(tokens); assert!(parsed.diagnostics.is_empty(), "{:?}", parsed.diagnostics); source.comments = comments; (source, parsed.declarations) }; let (source, declarations) = parse_source(annotated.replace('\n', "\r\n")); let formatted = format::source(&source, &declarations).into_owned(); let (formatted_source, formatted_declarations) = parse_source(formatted.clone()); assert_eq!( formatted, format::source(&formatted_source, &formatted_declarations).as_ref() ); let comments = |source: &Source| { source .comments .iter() .map(|span| source.text[span.start..span.end].to_owned()) .collect::>() }; assert_eq!(comments(&formatted_source), comments(&source)); assert!(formatted.contains("/* 只取完整份额。\r\n 余数留给调用方。 */ // 2 # 取整")); let generated = |source: Source, declarations: Vec| { let program = program::check(&declarations, &[Module::standalone()]).unwrap(); emit::emit(&program, &ownership::analyze(&program), &[source]) .into_iter() .map(|(name, file)| (name, file.text)) .collect::>() }; let (plain_source, plain_declarations) = parse_source(plain.into()); let mut plain_rust = generated(plain_source, plain_declarations); let fault = "source: \"app.dever\", line: 2, column: 9"; let (_, code) = plain_rust .iter_mut() .find(|(_, code)| code.contains(fault)) .unwrap(); *code = code.replace(fault, "source: \"app.dever\", line: 3, column: 9"); assert_eq!( generated(formatted_source, formatted_declarations), plain_rust ); } #[test] fn unclosed_block_comment_reports_its_opening() { let text = "# 已结束的注释\rmain() (out: Int) { out = 1 /* 未闭合"; let source = Source::new(0, "app.dever", text.into()); let (_, diagnostics, comments) = lex::scan_with_diagnostics(&source, 0..text.len()); assert_eq!(comments.len(), 1); let [error] = diagnostics.as_slice() else { panic!("{diagnostics:?}") }; assert_eq!(error.code, "L007"); assert_eq!(&text[error.span.start..error.span.end], "/*"); assert_eq!(source.position(error.span.start).0, 2); } #[test] fn flow_cells_keep_multiline_expressions_and_explicit_guard_syntax() { let text = "flow example(value: Text?) (out: Text)\n| step | kind | do |\n| - | check | value != null else Invalid |\n| out: Text | calc | join(\n value, \"中文|\"\n) |\n"; let result = parsed(text); assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics); let Declaration::Function(function) = &result.declarations[0] else { panic!() }; let Body::Flow(steps) = &function.body else { panic!() }; assert_eq!(steps.len(), 2); assert!(matches!(steps[0].statement, Statement::Check { .. })); assert!(matches!( steps[1].statement, Statement::Assign { kind: Some(_), .. } )); let formatted = dever::compiler::format::format(&result.declarations); let again = parsed(&formatted); assert!(again.diagnostics.is_empty()); assert_eq!( formatted, dever::compiler::format::format(&again.declarations) ); for text in [ "flow f() ()\n| step | kind | do |\n", "flow f() ()\n| step | kind | do |\n| - | unknown | work() |\n", "flow f() ()\n| step | kind | do |\n| bound | check | true else Invalid |\n", "flow f() ()\n| step | kind | do |\n| - | calc | work() | extra |\n", ] { assert!(!parsed(text).diagnostics.is_empty(), "{text}"); } } #[test] fn rule_preserves_conditions_rows_and_multiline_cell_sources() { let text = r#"type Choice { Ready(value: Text) error Rejected(reason: Text) } rule describe(value: Choice) (label: Text) recover("display an explicit rejection") | name | value | label | | ready | Ready(text) | text | | rejected | Rejected(reason) | join( "失败|", reason ) | next() (value: Int) { value = 7 } "#; let result = parsed(text); assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics); assert_eq!(result.declarations.len(), 3); let Declaration::Function(function) = &result.declarations[1] else { panic!() }; let Body::Rule(rule) = &function.body else { panic!() }; assert_eq!(rule.rows.len(), 2); assert_eq!(rule.rows[1].name.as_ref().unwrap().0, "rejected"); let value = rule.rows[1].results[0].as_ref().unwrap(); assert_eq!( &text[value.span.start..value.span.end], "join(\n \"失败|\", reason\n )" ); } #[test] fn ordinary_functions_keep_explicit_checks_and_local_types() { let result = parsed( r#"type User { name: Text } requireName(user: User?) (name: Text) { check user != null else NotFound names: List = [] name = user.name } cmd name = app.requireName "#, ); assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics); let Declaration::Function(function) = &result.declarations[1] else { panic!() }; let Body::Statements(statements) = &function.body else { panic!() }; assert!(matches!(statements[0], Statement::Check { .. })); let Statement::Assign { kind: Some(kind), .. } = &statements[1] else { panic!() }; assert_eq!(kind.name, "List"); assert_eq!(kind.arguments[0].name, "Text"); } #[test] fn nested_container_types_and_numeric_bounds_are_unambiguous() { let result = parsed("f(values: Map>, x: Int < 10 and >= -3) (n: Int) { n = x }\n"); assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics); let Declaration::Function(function) = &result.declarations[0] else { panic!() }; assert_eq!( function.inputs[0].kind.arguments[1].arguments[0].name, "Int" ); assert_eq!(function.inputs[1].kind.bounds.len(), 2); } #[test] fn table_shape_errors_do_not_create_valid_definitions() { for text in [ "rule f(x: Bool) (y: Int)\n| x | y |\n| true | 1\n", "rule f(x: Bool) (y: Int)\n| x | y |\n| true | |\n", "rule f(x: Bool) (y: Int)\n| x | y |\n| true | 1 | 2 |\n", "rule f(x: Bool) (y: Int)\n| x | y |\n| --- | --- |\n", "f(x: true) (y: Int) { y = 1 }\n", "f() (y: Int) pure { y = 1 }\n", ] { let result = parsed(text); assert!(!result.diagnostics.is_empty(), "{text}"); assert!(result.declarations.is_empty(), "{text}"); } } #[test] fn later_valid_definitions_survive_a_local_parse_error() { let result = parsed("broken() (x: Int) { x = }\n\nvalid() (x: Int) { x = 3 }\n"); assert_eq!(result.diagnostics.len(), 1); assert_eq!(result.declarations.len(), 1); let Declaration::Function(function) = &result.declarations[0] else { panic!() }; assert_eq!(function.name, "valid"); } #[test] fn failure_rows_and_zero_output_rules_remain_explicit() { let result = parsed( "rule f(x: Bool) (a: Int, b: Int)\n| x | a | b |\n| true | 1 | -2 |\n| false | fail(Invalid) | - |\n\nrule act(x: Bool) ()\n| x | do |\n| - | send() |\n", ); assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics); let Declaration::Function(function) = &result.declarations[0] else { panic!() }; let Body::Rule(rule) = &function.body else { panic!() }; assert!(rule.rows[1].results[1].is_none()); assert!(matches!( rule.rows[0].results[1].as_ref().unwrap().kind, ExpressionKind::Unary(..) )); } #[test] fn formatting_is_idempotent_and_preserves_grouping_and_text() { let input = r#"type Region { Local, Remote } rule shipping(region: Region, goods: Decimal) (fee: Decimal) | region|goods|fee| | Local|>= 1_000|0| | Local|< 1_000|8| | Remote|-|15| calculate(a: Int, b: Int, c: Int) (value: Int) { value = a * (b + c) - (a - b) } message() (value: Text) { value = "雪|\u{0}\"\\" } "#; let first = parsed(input); assert!(first.diagnostics.is_empty(), "{:?}", first.diagnostics); let formatted = dever::compiler::format::format(&first.declarations); assert!(formatted.contains("a * (b + c) - (a - b)")); assert!(formatted.contains(">= 1000")); let second = parsed(&formatted); assert!( second.diagnostics.is_empty(), "{:?}\n{formatted}", second.diagnostics ); assert_eq!( formatted, dever::compiler::format::format(&second.declarations) ); assert_eq!(first.declarations.len(), second.declarations.len()); let Declaration::Function(function) = &second.declarations[3] else { panic!() }; let Body::Statements(statements) = &function.body else { panic!() }; let Statement::Assign { value, .. } = &statements[0] else { panic!() }; assert!( matches!(&value.kind, ExpressionKind::Literal(Literal::Text(text)) if text == "雪|\0\"\\") ); } #[test] fn handler_signatures_round_trip_without_erasing_invalid_modifiers() { for suffix in ["", "?", " >= 1", ""] { let input = format!( "apply(value: Int, transform: handler(value: Int >= 1) (out: Text){suffix}) (out: Text) {{ out = transform(value) }}" ); let first = parsed(&input); assert!(first.diagnostics.is_empty(), "{:?}", first.diagnostics); let formatted = dever::compiler::format::format(&first.declarations); assert!(formatted.contains(&format!("handler(value: Int >= 1) (out: Text){suffix}"))); let second = parsed(&formatted); assert!(second.diagnostics.is_empty()); assert_eq!( formatted, dever::compiler::format::format(&second.declarations) ); } } #[test] fn loop_filters_round_trip_without_reinterpreting_cell_text() { let text = "loop select(values: List) (chosen: List, count: Int)\n| each value in values | value | length(value) | sort | take | result |\n| chosen | \"a|b\", \"中文\" | > 1 | [length(value).desc, value.asc] | 2 | list value |\n| count | - | - | - | - | count |\n"; let result = parsed(text); assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics); let formatted = dever::compiler::format::format(&result.declarations); let again = parsed(&formatted); assert!(again.diagnostics.is_empty()); assert_eq!( formatted, dever::compiler::format::format(&again.declarations) ); for text in [ "loop f(values: List) (n: Int)\n| each value in values | value | result |\n| n | count |\n", "loop f(values: List) (n: Int)\n| each value in values | result |\n| n | - | count |\n", ] { assert!(!parsed(text).diagnostics.is_empty()); } } #[test] fn block_loop_format_preserves_record_selectors_and_unknown_outputs() { let input = r#"loop selected(items: List) (out: Int) item in (Rows { items = items }.items) { missing = rule (Flags { active = true }.active) { true => count false => skip } }"#; let first = parsed(input); assert!(first.diagnostics.is_empty()); let text = dever::compiler::format::format(&first.declarations); assert!(text.contains("missing = rule")); let again = parsed(&text); assert!(again.diagnostics.is_empty(), "{text}"); assert_eq!(text, dever::compiler::format::format(&again.declarations)); } #[test] fn block_rules_keep_selector_order_and_wildcards_after_format() { for (selectors, branches) in [ ("b", "- => 1"), ("(b, a)", "(-, -) => 1"), ("b", "true, false => 1"), ] { let input = format!( "rule pick(a: Bool, b: Bool) (out: Int) {selectors} {{ {branches} }}" ); let first = parsed(&input); assert!(first.diagnostics.is_empty(), "{:?}", first.diagnostics); let canonical = dever::compiler::format::format(&first.declarations); assert!( canonical.contains(&format!( " {selectors} {{ {branches} }}" )), "{canonical}" ); let second = parsed(&canonical); assert!(second.diagnostics.is_empty()); assert_eq!( canonical, dever::compiler::format::format(&second.declarations) ); } }