//! Source-level admission, evaluation and transactional Core integration for //! ADR 0082. These tests use the same analysis/lower/driver entry as `check`. use std::cell::Cell; use std::collections::BTreeSet; use louise_comptime::CtfeDriverError; use louise_core::ir::{Expr, Program, Value}; use louise_core::static_value::StaticNode; use louise_db::{Analysis, ComptimeDiagnosticsError, Db}; use louise_diag::Diagnostic; struct Attempt { analysis: Analysis, result: Result>, } fn attempt(source: &str) -> Attempt { let mut db = Db::new(); db.add_module("main", "main.lse", source.to_owned()); let analysis = db.analyze(); let result = if analysis.diagnostics.iter().any(Diagnostic::is_error) { Err(analysis.diagnostics.clone()) } else { let program = louise_core::lower::lower(&analysis.hir, &analysis.typeck); louise_db::evaluate_comptime(&analysis, program) }; Attempt { analysis, result } } fn valid(source: &str) -> Program { let attempt = attempt(source); assert!( !attempt .analysis .diagnostics .iter() .any(Diagnostic::is_error), "source diagnostics: {:#?}", attempt.analysis.diagnostics ); attempt .result .unwrap_or_else(|diagnostics| panic!("CTFE rejected valid source: {diagnostics:#?}")) } fn invalid(source: &str, code: &str, fragment: &str) { let attempt = attempt(source); assert!( !attempt .analysis .diagnostics .iter() .any(Diagnostic::is_error), "the test must reach CTFE, not an earlier source error: {:#?}", attempt.analysis.diagnostics ); let diagnostics = attempt.result.expect_err("invalid CTFE source succeeded"); assert!( diagnostics.iter().any(|diagnostic| { diagnostic.code == code && (diagnostic.message.contains(fragment) || diagnostic.notes.iter().any(|note| note.contains(fragment))) }), "no [{code}] containing {fragment:?}: {diagnostics:#?}" ); } #[test] fn source_lookup_uses_full_evidence_preparation_and_keeps_callable_core() { let program = valid( r#"fn double :: x: a -> a where Num { x + x } @comptime fn lookup :: -> List<(String, Int)> { [("one", 1), ("two", double 2 + 1)] } fn read :: -> Int { match lookup() { [] -> 0, [(_, n), ..] -> n } } fn indirect :: -> Int { let table = lookup match table() { [] -> 0, [(_, n), ..] -> n } } "#, ); let lookup = program.fn_by_name("main.lookup").unwrap(); let read = program.fn_by_name("main.read").unwrap(); let indirect = program.fn_by_name("main.indirect").unwrap(); let value = &program.comptime[&lookup]; assert!(matches!( value.nodes()[value.root().0 as usize], StaticNode::Construct { .. } )); assert!(value.nodes().contains(&StaticNode::Int(5))); // Perceus and both backends receive a valid direct call. C substitutes // the static reference only after counting; its generated-C test proves // the call is gone. The ordinary interpreter needs no special root mode. assert!(calls(&program.fns[read as usize].body, lookup)); assert!( closes(&program.fns[indirect as usize].body, lookup), "taking the root as a value lost its callable wrapper" ); assert!(program.fns[lookup as usize].span.is_some()); assert_eq!(program.fns[lookup as usize].params.len(), 1); } #[test] fn immutable_constructor_tuple_string_and_float_bits_survive_source_evaluation() { let program = valid( r#"import std/float type Entry { Entry(name: String, values: (Int, List)) } @comptime fn unit :: -> () { () } @comptime fn entry :: -> Entry { Entry("quote \" NUL \0 λ 🦀", (42, [0.0, -0.0, float.from_bits 1])) } "#, ); let unit = program.fn_by_name("main.unit").unwrap(); assert_eq!(program.comptime[&unit].nodes(), &[StaticNode::Unit]); let entry = program.fn_by_name("main.entry").unwrap(); let nodes = &program.comptime[&entry]; for bits in [0.0f64.to_bits(), (-0.0f64).to_bits(), 1] { assert!(nodes.nodes().contains(&StaticNode::FloatBits(bits))); } assert!(nodes.nodes().iter().any(|node| matches!( node, StaticNode::Construct { name, .. } if name == "Entry" ))); assert!(nodes.nodes().iter().any(|node| matches!( node, StaticNode::String(text) if text.contains("λ 🦀") && text.contains('\0') ))); } #[test] fn root_admission_rejects_arguments_generics_constraints_rows_externs_and_capabilities() { for (source, fragment) in [ ( "@comptime\nfn with_arg :: x: Int -> Int { x }\n", "no source parameters", ), ( "@comptime\nfn generic :: -> a { panic \"generic\" }\n", "monomorphic and unconstrained", ), ( "@comptime\nfn constrained :: -> a where Show { panic \"constrained\" }\n", "monomorphic and unconstrained", ), ( "@comptime\nfn open :: -> Int / { 1 }\n", "closed and empty", ), ( "import std/io\n@comptime\nfn explicit :: -> () / { io.println \"no\" }\n", "closed and empty", ), ( "import std/os\n@comptime\nfn environment :: -> Option / { os.env \"PATH\" }\n", "closed and empty", ), ( "@comptime\n@extern c \"foreign\"\nfn foreign :: -> Int\n", "extern function", ), ] { invalid(source, "E0902", fragment); } } #[test] fn effectful_host_universes_are_rejected_before_execution() { // Every call is well typed under its real signature. CTFE admission then // rejects the nonempty row before evidence preparation or `run_direct`: // there are no roots, host calls, filesystem actions or runtime fallback. for (source, fragment) in [ ( "import std/time.{type clock}\n@comptime\nfn clock_root :: -> time.Duration / { time.monotonic () }\n", "closed and empty", ), ( "import std/random.{type random}\n@comptime\nfn random_root :: -> Int / { random.int 10 }\n", "closed and empty", ), ( "import std/process.{type proc}\n@comptime\nfn process_root :: -> process.Pid / { process.self () }\n", "closed and empty", ), ( "import std/file\n@comptime\nfn file_root :: -> Result / { file.read \"no\" }\n", "closed and empty", ), ( "import std/net\n@comptime\nfn net_root :: -> Result, String> / { net.resolve \"localhost\" }\n", "closed and empty", ), ] { invalid(source, "E0902", fragment); } // A closed row cannot smuggle a compiler-internal handler/region/root // protocol past the independent Core dependency gate. invalid( r#"effect ask { fn ask :: -> Int } fn handled :: -> Int { handle { ask () } with { ask -> 1, return value -> value } } @comptime fn root :: -> Int { handled () } "#, "E0902", "handle", ); } #[test] fn cycles_dynamic_calls_panics_and_division_have_distinct_diagnostics() { invalid( "@comptime\nfn cycle :: -> Int { cycle () }\n", "E0902", "recursive dependency", ); invalid( "fn ping :: -> Int { pong () }\nfn pong :: -> Int { ping () }\n@comptime\nfn enters :: -> Int { ping () }\n", "E0902", "recursive dependency", ); invalid( "@comptime\nfn dynamic :: -> Int { let f = fn { 1 }\n f () }\n", "E0902", "dynamic closure", ); invalid( "@extern c \"foreign\"\nfn foreign :: -> Int\n\n@comptime\nfn calls_foreign :: -> Int { foreign () }\n", "E0902", "not compile-time-safe", ); invalid( "@comptime\nfn fails :: -> Int { panic \"typed boom\" }\n", "E0903", "typed boom", ); invalid( "@comptime\nfn divides :: -> Int { 1 / 0 }\n", "E0903", "division by zero", ); } #[test] fn unsupported_actual_results_and_constructor_metadata_fail_closed() { invalid( "@comptime\nfn function_value :: -> fn() -> Int { fn { 42 } }\n", "E0904", "closure", ); invalid( "import std/int\n@comptime\nfn promoted :: -> Int { int.shift_left 1 64 }\n", "E0904", "promoted Int", ); invalid( "import std/float\nimport std/int\n@comptime\nfn nan :: -> Float { float.from_bits (int.shift_left 0x7FF8 48) }\n", "E0904", "non-finite Float", ); // A stored evidence closure is not guessed to be an ordinary one-field // record. The authoritative constructor layout leads to safe rejection. invalid( r#"type Packed { Packed(a) -> Packed where Show } @comptime fn packed :: -> Packed { Packed(1) } "#, "E0904", "closure", ); } #[test] fn a_later_failure_commits_no_earlier_root_or_partial_program() { let source = r#"@comptime fn first :: -> Int { 1 } fn caller :: -> Int { first () } @comptime fn second :: -> Int { 1 / 0 } "#; let mut db = Db::new(); db.add_module("main", "main.lse", source.to_owned()); let analysis = db.analyze(); assert!(!analysis.diagnostics.iter().any(Diagnostic::is_error)); let original = louise_core::lower::lower(&analysis.hir, &analysis.typeck); let first = original.fn_by_name("main.first").unwrap(); let caller = original.fn_by_name("main.caller").unwrap(); let before = format!("{original}"); assert!(original.comptime.is_empty()); assert!(calls(&original.fns[caller as usize].body, first)); let result = louise_db::evaluate_comptime(&analysis, original.clone()); let diagnostics = result.expect_err("the second root must fail"); assert_eq!(diagnostics.len(), 1); assert_eq!(diagnostics[0].code, "E0903"); assert!(original.comptime.is_empty()); assert_eq!(format!("{original}"), before); assert!(calls(&original.fns[caller as usize].body, first)); } #[test] fn runtime_errors_keep_the_marker_and_real_source_frames() { let source = "fn divide :: -> Int { 1 / 0 }\n\n@comptime\nfn caller :: -> Int { divide () + 1 }\n"; let mut db = Db::new(); let file = db.add_module("main", "main.lse", source.to_owned()); let analysis = db.analyze(); let program = louise_core::lower::lower(&analysis.hir, &analysis.typeck); let diagnostics = louise_db::evaluate_comptime(&analysis, program).unwrap_err(); assert_eq!(diagnostics.len(), 1); let diagnostic = &diagnostics[0]; assert_eq!(diagnostic.code, "E0903"); assert_eq!(diagnostic.primary.span.file, file); let range = diagnostic.primary.span.range; let start = u32::from(range.start()) as usize; let end = u32::from(range.end()) as usize; assert_eq!(&db.sources().get(file).text()[start..end], "@comptime"); assert!( diagnostic .secondary .iter() .any(|label| label.message.contains("divide")), "no real dependency frame: {diagnostic:#?}" ); } #[test] fn uncancelled_cancellable_paths_preserve_success_and_source_errors() { for source in [ "@comptime\nfn answer :: -> Int { 42 }\n", "@comptime\nfn fails :: -> Int { 1 / 0 }\n", ] { let mut db = Db::new(); db.add_module("main", "main.lse", source.to_owned()); let analysis = db.analyze(); assert!(!analysis.diagnostics.iter().any(Diagnostic::is_error)); let original = louise_core::lower::lower(&analysis.hir, &analysis.typeck); let expected = louise_comptime::evaluate_declarations( &analysis.hir, &analysis.typeck, original.clone(), ); let actual = louise_comptime::evaluate_declarations_with( &analysis.hir, &analysis.typeck, original, &|| false, ); match (expected, actual) { (Ok(expected), Ok(actual)) => { assert!(!expected.comptime.is_empty()); assert_eq!(actual.comptime, expected.comptime); assert_eq!(format!("{actual}"), format!("{expected}")); } (Err(expected), Err(CtfeDriverError::Diagnostics(actual))) => { assert_eq!(actual, expected); assert_eq!(actual[0].code, "E0903"); } (expected, actual) => { panic!("uncancelled result changed: {expected:?} versus {actual:?}") } } let expected = louise_db::semantic_diagnostics(&db, &analysis); let actual = louise_db::semantic_diagnostics_with(&db, &analysis, &|| false).unwrap(); assert_eq!(actual, expected); } } #[test] fn source_cancellation_is_typed_without_program_or_e0903() { let source = "@comptime\nfn answer :: -> Int { 1 }\n"; let mut db = Db::new(); db.add_module("main", "main.lse", source.to_owned()); let modules = db.user_modules(); let analysis = db.analyze(); assert!(!analysis.diagnostics.iter().any(Diagnostic::is_error)); let original = louise_core::lower::lower(&analysis.hir, &analysis.typeck); let before = format!("{original}"); let error = louise_comptime::evaluate_declarations_with( &analysis.hir, &analysis.typeck, original.clone(), &|| true, ) .unwrap_err(); assert_eq!(error, CtfeDriverError::Cancelled); assert!(original.comptime.is_empty()); assert_eq!(format!("{original}"), before); assert_eq!( louise_db::comptime_diagnostics_with(&db, &analysis, &|| true), Err(ComptimeDiagnosticsError::Cancelled) ); assert_eq!( louise_db::semantic_diagnostics_with(&db, &analysis, &|| true), Err(ComptimeDiagnosticsError::Cancelled) ); // The existing synchronous check/LSP interface remains uncancelled. assert!(louise_db::semantic_diagnostics(&db, &analysis).is_empty()); assert_eq!(db.user_modules(), modules); } #[test] fn cancellation_after_an_earlier_root_commits_no_partial_program() { let source = r#"@comptime fn first :: -> Int { 1 } @comptime fn second :: -> Int { 2 } fn caller :: -> Int { second () } "#; let mut db = Db::new(); db.add_module("main", "main.lse", source.to_owned()); let analysis = db.analyze(); assert!(!analysis.diagnostics.iter().any(Diagnostic::is_error)); let original = louise_core::lower::lower(&analysis.hir, &analysis.typeck); let first = original.fn_by_name("main.first").unwrap(); let second = original.fn_by_name("main.second").unwrap(); let caller = original.fn_by_name("main.caller").unwrap(); let before = format!("{original}"); // Count the actual direct reductions of the pure first root through the // selected API. The full transaction then cancels on the next poll, which // is the second root's initial reduction; there is no recursion or cycle. let module = analysis.hir.module_by_path("main").unwrap(); let first_def = analysis.hir.lookup_value(module, "first").unwrap(); let selected = BTreeSet::from([first_def]); let first_polls = Cell::new(0); let completed_first = louise_comptime::evaluate_declarations_for_with( &analysis.hir, &analysis.typeck, original.clone(), &selected, &|| { first_polls.set(first_polls.get() + 1); false }, ) .unwrap(); assert!(first_polls.get() > 0); assert!(completed_first.comptime.contains_key(&first)); assert!(!completed_first.comptime.contains_key(&second)); let polls = Cell::new(0); let error = louise_comptime::evaluate_declarations_with( &analysis.hir, &analysis.typeck, original.clone(), &|| { let poll = polls.get() + 1; polls.set(poll); poll > first_polls.get() }, ) .unwrap_err(); assert_eq!(error, CtfeDriverError::Cancelled); assert_eq!(polls.get(), first_polls.get() + 1); assert!(original.comptime.is_empty()); assert_eq!(format!("{original}"), before); assert!(calls(&original.fns[caller as usize].body, second)); } #[test] fn semantic_fip_errors_still_precede_and_avoid_cancellation() { let source = r#"@fip pub fn singleton :: n: Int -> List { [n] } @comptime fn answer :: -> Int { 1 } "#; let mut db = Db::new(); db.add_module("main", "main.lse", source.to_owned()); let analysis = db.analyze(); assert!(!analysis.diagnostics.iter().any(Diagnostic::is_error)); let polls = Cell::new(0); let diagnostics = louise_db::semantic_diagnostics_with(&db, &analysis, &|| { polls.set(polls.get() + 1); true }) .unwrap(); assert!( diagnostics .iter() .any(|diagnostic| diagnostic.code == "E0901") ); assert_eq!(polls.get(), 0); } fn closes(expr: &Expr, target: u32) -> bool { match expr { Expr::Let(_, value, rest, _) | Expr::LetN(_, value, rest, _) => { (matches!(value.as_ref(), Value::Closure(id, _) if *id == target) || match value.as_ref() { Value::Block(body) => closes(body, target), _ => false, }) || closes(rest, target) } Expr::Switch { cases, default, .. } => { cases.iter().any(|(_, body)| closes(body, target)) || default.as_deref().is_some_and(|body| closes(body, target)) } Expr::SwitchLit { cases, default, .. } => { cases.iter().any(|(_, body)| closes(body, target)) || closes(default, target) } Expr::Dup(_, rest) | Expr::Drop(_, rest) | Expr::Release { rest, .. } => { closes(rest, target) } Expr::Return(_) | Expr::ReturnN(_) | Expr::Exit(_) | Expr::Panic(_) => false, } } fn calls(expr: &Expr, target: u32) -> bool { match expr { Expr::Let(_, value, rest, _) | Expr::LetN(_, value, rest, _) => { (matches!(value.as_ref(), Value::CallFn(id, _) if *id == target) || match value.as_ref() { Value::Block(body) => calls(body, target), _ => false, }) || calls(rest, target) } Expr::Switch { cases, default, .. } => { cases.iter().any(|(_, body)| calls(body, target)) || default.as_deref().is_some_and(|body| calls(body, target)) } Expr::SwitchLit { cases, default, .. } => { cases.iter().any(|(_, body)| calls(body, target)) || calls(default, target) } Expr::Dup(_, rest) | Expr::Drop(_, rest) | Expr::Release { rest, .. } => { calls(rest, target) } Expr::Return(_) | Expr::ReturnN(_) | Expr::Exit(_) | Expr::Panic(_) => false, } }