tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

559 lignes · 19212 octetsBrut · Historique
1//! Source-level admission, evaluation and transactional Core integration for
2//! ADR 0082. These tests use the same analysis/lower/driver entry as `check`.
3
4use std::cell::Cell;
5use std::collections::BTreeSet;
6
7use louise_comptime::CtfeDriverError;
8use louise_core::ir::{Expr, Program, Value};
9use louise_core::static_value::StaticNode;
10use louise_db::{Analysis, ComptimeDiagnosticsError, Db};
11use louise_diag::Diagnostic;
12
13struct Attempt {
14 analysis: Analysis,
15 result: Result<Program, Vec<Diagnostic>>,
16}
17
18fn attempt(source: &str) -> Attempt {
19 let mut db = Db::new();
20 db.add_module("main", "main.lse", source.to_owned());
21 let analysis = db.analyze();
22 let result = if analysis.diagnostics.iter().any(Diagnostic::is_error) {
23 Err(analysis.diagnostics.clone())
24 } else {
25 let program = louise_core::lower::lower(&analysis.hir, &analysis.typeck);
26 louise_db::evaluate_comptime(&analysis, program)
27 };
28 Attempt { analysis, result }
29}
30
31fn valid(source: &str) -> Program {
32 let attempt = attempt(source);
33 assert!(
34 !attempt
35 .analysis
36 .diagnostics
37 .iter()
38 .any(Diagnostic::is_error),
39 "source diagnostics: {:#?}",
40 attempt.analysis.diagnostics
41 );
42 attempt
43 .result
44 .unwrap_or_else(|diagnostics| panic!("CTFE rejected valid source: {diagnostics:#?}"))
45}
46
47fn invalid(source: &str, code: &str, fragment: &str) {
48 let attempt = attempt(source);
49 assert!(
50 !attempt
51 .analysis
52 .diagnostics
53 .iter()
54 .any(Diagnostic::is_error),
55 "the test must reach CTFE, not an earlier source error: {:#?}",
56 attempt.analysis.diagnostics
57 );
58 let diagnostics = attempt.result.expect_err("invalid CTFE source succeeded");
59 assert!(
60 diagnostics.iter().any(|diagnostic| {
61 diagnostic.code == code
62 && (diagnostic.message.contains(fragment)
63 || diagnostic.notes.iter().any(|note| note.contains(fragment)))
64 }),
65 "no [{code}] containing {fragment:?}: {diagnostics:#?}"
66 );
67}
68
69#[test]
70fn source_lookup_uses_full_evidence_preparation_and_keeps_callable_core() {
71 let program = valid(
72 r#"fn double :: x: a -> a where Num<a> { x + x }
73
74@comptime
75fn lookup :: -> List<(String, Int)> {
76 [("one", 1), ("two", double 2 + 1)]
77}
78
79fn read :: -> Int {
80 match lookup() { [] -> 0, [(_, n), ..] -> n }
81}
82
83fn indirect :: -> Int {
84 let table = lookup
85 match table() { [] -> 0, [(_, n), ..] -> n }
86}
87"#,
88 );
89 let lookup = program.fn_by_name("main.lookup").unwrap();
90 let read = program.fn_by_name("main.read").unwrap();
91 let indirect = program.fn_by_name("main.indirect").unwrap();
92 let value = &program.comptime[&lookup];
93 assert!(matches!(
94 value.nodes()[value.root().0 as usize],
95 StaticNode::Construct { .. }
96 ));
97 assert!(value.nodes().contains(&StaticNode::Int(5)));
98 // Perceus and both backends receive a valid direct call. C substitutes
99 // the static reference only after counting; its generated-C test proves
100 // the call is gone. The ordinary interpreter needs no special root mode.
101 assert!(calls(&program.fns[read as usize].body, lookup));
102 assert!(
103 closes(&program.fns[indirect as usize].body, lookup),
104 "taking the root as a value lost its callable wrapper"
105 );
106 assert!(program.fns[lookup as usize].span.is_some());
107 assert_eq!(program.fns[lookup as usize].params.len(), 1);
108}
109
110#[test]
111fn immutable_constructor_tuple_string_and_float_bits_survive_source_evaluation() {
112 let program = valid(
113 r#"import std/float
114
115type Entry { Entry(name: String, values: (Int, List<Float>)) }
116
117@comptime
118fn unit :: -> () { () }
119
120@comptime
121fn entry :: -> Entry {
122 Entry("quote \" NUL \0 λ 🦀", (42, [0.0, -0.0, float.from_bits 1]))
123}
124"#,
125 );
126 let unit = program.fn_by_name("main.unit").unwrap();
127 assert_eq!(program.comptime[&unit].nodes(), &[StaticNode::Unit]);
128 let entry = program.fn_by_name("main.entry").unwrap();
129 let nodes = &program.comptime[&entry];
130 for bits in [0.0f64.to_bits(), (-0.0f64).to_bits(), 1] {
131 assert!(nodes.nodes().contains(&StaticNode::FloatBits(bits)));
132 }
133 assert!(nodes.nodes().iter().any(|node| matches!(
134 node,
135 StaticNode::Construct { name, .. } if name == "Entry"
136 )));
137 assert!(nodes.nodes().iter().any(|node| matches!(
138 node,
139 StaticNode::String(text) if text.contains("λ 🦀") && text.contains('\0')
140 )));
141}
142
143#[test]
144fn root_admission_rejects_arguments_generics_constraints_rows_externs_and_capabilities() {
145 for (source, fragment) in [
146 (
147 "@comptime\nfn with_arg :: x: Int -> Int { x }\n",
148 "no source parameters",
149 ),
150 (
151 "@comptime\nfn generic :: -> a { panic \"generic\" }\n",
152 "monomorphic and unconstrained",
153 ),
154 (
155 "@comptime\nfn constrained :: -> a where Show<a> { panic \"constrained\" }\n",
156 "monomorphic and unconstrained",
157 ),
158 (
159 "@comptime\nfn open :: -> Int / <e> { 1 }\n",
160 "closed and empty",
161 ),
162 (
163 "import std/io\n@comptime\nfn explicit :: -> () / <io> { io.println \"no\" }\n",
164 "closed and empty",
165 ),
166 (
167 "import std/os\n@comptime\nfn environment :: -> Option<String> / <io> { os.env \"PATH\" }\n",
168 "closed and empty",
169 ),
170 (
171 "@comptime\n@extern c \"foreign\"\nfn foreign :: -> Int\n",
172 "extern function",
173 ),
174 ] {
175 invalid(source, "E0902", fragment);
176 }
177}
178
179#[test]
180fn effectful_host_universes_are_rejected_before_execution() {
181 // Every call is well typed under its real signature. CTFE admission then
182 // rejects the nonempty row before evidence preparation or `run_direct`:
183 // there are no roots, host calls, filesystem actions or runtime fallback.
184 for (source, fragment) in [
185 (
186 "import std/time.{type clock}\n@comptime\nfn clock_root :: -> time.Duration / <clock> { time.monotonic () }\n",
187 "closed and empty",
188 ),
189 (
190 "import std/random.{type random}\n@comptime\nfn random_root :: -> Int / <random> { random.int 10 }\n",
191 "closed and empty",
192 ),
193 (
194 "import std/process.{type proc}\n@comptime\nfn process_root :: -> process.Pid / <proc> { process.self () }\n",
195 "closed and empty",
196 ),
197 (
198 "import std/file\n@comptime\nfn file_root :: -> Result<String, String> / <io> { file.read \"no\" }\n",
199 "closed and empty",
200 ),
201 (
202 "import std/net\n@comptime\nfn net_root :: -> Result<List<String>, String> / <io> { net.resolve \"localhost\" }\n",
203 "closed and empty",
204 ),
205 ] {
206 invalid(source, "E0902", fragment);
207 }
208
209 // A closed row cannot smuggle a compiler-internal handler/region/root
210 // protocol past the independent Core dependency gate.
211 invalid(
212 r#"effect ask { fn ask :: -> Int }
213
214fn handled :: -> Int {
215 handle { ask () } with { ask -> 1, return value -> value }
216}
217
218@comptime
219fn root :: -> Int { handled () }
220"#,
221 "E0902",
222 "handle",
223 );
224}
225
226#[test]
227fn cycles_dynamic_calls_panics_and_division_have_distinct_diagnostics() {
228 invalid(
229 "@comptime\nfn cycle :: -> Int { cycle () }\n",
230 "E0902",
231 "recursive dependency",
232 );
233 invalid(
234 "fn ping :: -> Int { pong () }\nfn pong :: -> Int { ping () }\n@comptime\nfn enters :: -> Int { ping () }\n",
235 "E0902",
236 "recursive dependency",
237 );
238 invalid(
239 "@comptime\nfn dynamic :: -> Int { let f = fn { 1 }\n f () }\n",
240 "E0902",
241 "dynamic closure",
242 );
243 invalid(
244 "@extern c \"foreign\"\nfn foreign :: -> Int\n\n@comptime\nfn calls_foreign :: -> Int { foreign () }\n",
245 "E0902",
246 "not compile-time-safe",
247 );
248 invalid(
249 "@comptime\nfn fails :: -> Int { panic \"typed boom\" }\n",
250 "E0903",
251 "typed boom",
252 );
253 invalid(
254 "@comptime\nfn divides :: -> Int { 1 / 0 }\n",
255 "E0903",
256 "division by zero",
257 );
258}
259
260#[test]
261fn unsupported_actual_results_and_constructor_metadata_fail_closed() {
262 invalid(
263 "@comptime\nfn function_value :: -> fn() -> Int { fn { 42 } }\n",
264 "E0904",
265 "closure",
266 );
267 invalid(
268 "import std/int\n@comptime\nfn promoted :: -> Int { int.shift_left 1 64 }\n",
269 "E0904",
270 "promoted Int",
271 );
272 invalid(
273 "import std/float\nimport std/int\n@comptime\nfn nan :: -> Float { float.from_bits (int.shift_left 0x7FF8 48) }\n",
274 "E0904",
275 "non-finite Float",
276 );
277
278 // A stored evidence closure is not guessed to be an ordinary one-field
279 // record. The authoritative constructor layout leads to safe rejection.
280 invalid(
281 r#"type Packed<a> { Packed(a) -> Packed<a> where Show<a> }
282
283@comptime
284fn packed :: -> Packed<Int> { Packed(1) }
285"#,
286 "E0904",
287 "closure",
288 );
289}
290
291#[test]
292fn a_later_failure_commits_no_earlier_root_or_partial_program() {
293 let source = r#"@comptime
294fn first :: -> Int { 1 }
295
296fn caller :: -> Int { first () }
297
298@comptime
299fn second :: -> Int { 1 / 0 }
300"#;
301 let mut db = Db::new();
302 db.add_module("main", "main.lse", source.to_owned());
303 let analysis = db.analyze();
304 assert!(!analysis.diagnostics.iter().any(Diagnostic::is_error));
305 let original = louise_core::lower::lower(&analysis.hir, &analysis.typeck);
306 let first = original.fn_by_name("main.first").unwrap();
307 let caller = original.fn_by_name("main.caller").unwrap();
308 let before = format!("{original}");
309 assert!(original.comptime.is_empty());
310 assert!(calls(&original.fns[caller as usize].body, first));
311
312 let result = louise_db::evaluate_comptime(&analysis, original.clone());
313 let diagnostics = result.expect_err("the second root must fail");
314 assert_eq!(diagnostics.len(), 1);
315 assert_eq!(diagnostics[0].code, "E0903");
316 assert!(original.comptime.is_empty());
317 assert_eq!(format!("{original}"), before);
318 assert!(calls(&original.fns[caller as usize].body, first));
319}
320
321#[test]
322fn runtime_errors_keep_the_marker_and_real_source_frames() {
323 let source =
324 "fn divide :: -> Int { 1 / 0 }\n\n@comptime\nfn caller :: -> Int { divide () + 1 }\n";
325 let mut db = Db::new();
326 let file = db.add_module("main", "main.lse", source.to_owned());
327 let analysis = db.analyze();
328 let program = louise_core::lower::lower(&analysis.hir, &analysis.typeck);
329 let diagnostics = louise_db::evaluate_comptime(&analysis, program).unwrap_err();
330 assert_eq!(diagnostics.len(), 1);
331 let diagnostic = &diagnostics[0];
332 assert_eq!(diagnostic.code, "E0903");
333 assert_eq!(diagnostic.primary.span.file, file);
334 let range = diagnostic.primary.span.range;
335 let start = u32::from(range.start()) as usize;
336 let end = u32::from(range.end()) as usize;
337 assert_eq!(&db.sources().get(file).text()[start..end], "@comptime");
338 assert!(
339 diagnostic
340 .secondary
341 .iter()
342 .any(|label| label.message.contains("divide")),
343 "no real dependency frame: {diagnostic:#?}"
344 );
345}
346
347#[test]
348fn uncancelled_cancellable_paths_preserve_success_and_source_errors() {
349 for source in [
350 "@comptime\nfn answer :: -> Int { 42 }\n",
351 "@comptime\nfn fails :: -> Int { 1 / 0 }\n",
352 ] {
353 let mut db = Db::new();
354 db.add_module("main", "main.lse", source.to_owned());
355 let analysis = db.analyze();
356 assert!(!analysis.diagnostics.iter().any(Diagnostic::is_error));
357 let original = louise_core::lower::lower(&analysis.hir, &analysis.typeck);
358 let expected = louise_comptime::evaluate_declarations(
359 &analysis.hir,
360 &analysis.typeck,
361 original.clone(),
362 );
363 let actual = louise_comptime::evaluate_declarations_with(
364 &analysis.hir,
365 &analysis.typeck,
366 original,
367 &|| false,
368 );
369 match (expected, actual) {
370 (Ok(expected), Ok(actual)) => {
371 assert!(!expected.comptime.is_empty());
372 assert_eq!(actual.comptime, expected.comptime);
373 assert_eq!(format!("{actual}"), format!("{expected}"));
374 }
375 (Err(expected), Err(CtfeDriverError::Diagnostics(actual))) => {
376 assert_eq!(actual, expected);
377 assert_eq!(actual[0].code, "E0903");
378 }
379 (expected, actual) => {
380 panic!("uncancelled result changed: {expected:?} versus {actual:?}")
381 }
382 }
383
384 let expected = louise_db::semantic_diagnostics(&db, &analysis);
385 let actual = louise_db::semantic_diagnostics_with(&db, &analysis, &|| false).unwrap();
386 assert_eq!(actual, expected);
387 }
388}
389
390#[test]
391fn source_cancellation_is_typed_without_program_or_e0903() {
392 let source = "@comptime\nfn answer :: -> Int { 1 }\n";
393 let mut db = Db::new();
394 db.add_module("main", "main.lse", source.to_owned());
395 let modules = db.user_modules();
396 let analysis = db.analyze();
397 assert!(!analysis.diagnostics.iter().any(Diagnostic::is_error));
398 let original = louise_core::lower::lower(&analysis.hir, &analysis.typeck);
399 let before = format!("{original}");
400 let error = louise_comptime::evaluate_declarations_with(
401 &analysis.hir,
402 &analysis.typeck,
403 original.clone(),
404 &|| true,
405 )
406 .unwrap_err();
407 assert_eq!(error, CtfeDriverError::Cancelled);
408 assert!(original.comptime.is_empty());
409 assert_eq!(format!("{original}"), before);
410
411 assert_eq!(
412 louise_db::comptime_diagnostics_with(&db, &analysis, &|| true),
413 Err(ComptimeDiagnosticsError::Cancelled)
414 );
415 assert_eq!(
416 louise_db::semantic_diagnostics_with(&db, &analysis, &|| true),
417 Err(ComptimeDiagnosticsError::Cancelled)
418 );
419 // The existing synchronous check/LSP interface remains uncancelled.
420 assert!(louise_db::semantic_diagnostics(&db, &analysis).is_empty());
421 assert_eq!(db.user_modules(), modules);
422}
423
424#[test]
425fn cancellation_after_an_earlier_root_commits_no_partial_program() {
426 let source = r#"@comptime
427fn first :: -> Int { 1 }
428
429@comptime
430fn second :: -> Int { 2 }
431
432fn caller :: -> Int { second () }
433"#;
434 let mut db = Db::new();
435 db.add_module("main", "main.lse", source.to_owned());
436 let analysis = db.analyze();
437 assert!(!analysis.diagnostics.iter().any(Diagnostic::is_error));
438 let original = louise_core::lower::lower(&analysis.hir, &analysis.typeck);
439 let first = original.fn_by_name("main.first").unwrap();
440 let second = original.fn_by_name("main.second").unwrap();
441 let caller = original.fn_by_name("main.caller").unwrap();
442 let before = format!("{original}");
443
444 // Count the actual direct reductions of the pure first root through the
445 // selected API. The full transaction then cancels on the next poll, which
446 // is the second root's initial reduction; there is no recursion or cycle.
447 let module = analysis.hir.module_by_path("main").unwrap();
448 let first_def = analysis.hir.lookup_value(module, "first").unwrap();
449 let selected = BTreeSet::from([first_def]);
450 let first_polls = Cell::new(0);
451 let completed_first = louise_comptime::evaluate_declarations_for_with(
452 &analysis.hir,
453 &analysis.typeck,
454 original.clone(),
455 &selected,
456 &|| {
457 first_polls.set(first_polls.get() + 1);
458 false
459 },
460 )
461 .unwrap();
462 assert!(first_polls.get() > 0);
463 assert!(completed_first.comptime.contains_key(&first));
464 assert!(!completed_first.comptime.contains_key(&second));
465
466 let polls = Cell::new(0);
467 let error = louise_comptime::evaluate_declarations_with(
468 &analysis.hir,
469 &analysis.typeck,
470 original.clone(),
471 &|| {
472 let poll = polls.get() + 1;
473 polls.set(poll);
474 poll > first_polls.get()
475 },
476 )
477 .unwrap_err();
478 assert_eq!(error, CtfeDriverError::Cancelled);
479 assert_eq!(polls.get(), first_polls.get() + 1);
480 assert!(original.comptime.is_empty());
481 assert_eq!(format!("{original}"), before);
482 assert!(calls(&original.fns[caller as usize].body, second));
483}
484
485#[test]
486fn semantic_fip_errors_still_precede_and_avoid_cancellation() {
487 let source = r#"@fip
488pub fn singleton :: n: Int -> List<Int> {
489 [n]
490}
491
492@comptime
493fn answer :: -> Int { 1 }
494"#;
495 let mut db = Db::new();
496 db.add_module("main", "main.lse", source.to_owned());
497 let analysis = db.analyze();
498 assert!(!analysis.diagnostics.iter().any(Diagnostic::is_error));
499 let polls = Cell::new(0);
500 let diagnostics = louise_db::semantic_diagnostics_with(&db, &analysis, &|| {
501 polls.set(polls.get() + 1);
502 true
503 })
504 .unwrap();
505 assert!(
506 diagnostics
507 .iter()
508 .any(|diagnostic| diagnostic.code == "E0901")
509 );
510 assert_eq!(polls.get(), 0);
511}
512
513fn closes(expr: &Expr, target: u32) -> bool {
514 match expr {
515 Expr::Let(_, value, rest, _) | Expr::LetN(_, value, rest, _) => {
516 (matches!(value.as_ref(), Value::Closure(id, _) if *id == target)
517 || match value.as_ref() {
518 Value::Block(body) => closes(body, target),
519 _ => false,
520 })
521 || closes(rest, target)
522 }
523 Expr::Switch { cases, default, .. } => {
524 cases.iter().any(|(_, body)| closes(body, target))
525 || default.as_deref().is_some_and(|body| closes(body, target))
526 }
527 Expr::SwitchLit { cases, default, .. } => {
528 cases.iter().any(|(_, body)| closes(body, target)) || closes(default, target)
529 }
530 Expr::Dup(_, rest) | Expr::Drop(_, rest) | Expr::Release { rest, .. } => {
531 closes(rest, target)
532 }
533 Expr::Return(_) | Expr::ReturnN(_) | Expr::Exit(_) | Expr::Panic(_) => false,
534 }
535}
536
537fn calls(expr: &Expr, target: u32) -> bool {
538 match expr {
539 Expr::Let(_, value, rest, _) | Expr::LetN(_, value, rest, _) => {
540 (matches!(value.as_ref(), Value::CallFn(id, _) if *id == target)
541 || match value.as_ref() {
542 Value::Block(body) => calls(body, target),
543 _ => false,
544 })
545 || calls(rest, target)
546 }
547 Expr::Switch { cases, default, .. } => {
548 cases.iter().any(|(_, body)| calls(body, target))
549 || default.as_deref().is_some_and(|body| calls(body, target))
550 }
551 Expr::SwitchLit { cases, default, .. } => {
552 cases.iter().any(|(_, body)| calls(body, target)) || calls(default, target)
553 }
554 Expr::Dup(_, rest) | Expr::Drop(_, rest) | Expr::Release { rest, .. } => {
555 calls(rest, target)
556 }
557 Expr::Return(_) | Expr::ReturnN(_) | Expr::Exit(_) | Expr::Panic(_) => false,
558 }
559}