Lines
96.72 %
Functions
91.67 %
Branches
100 %
//! P11: a constant-control DO is unrolled with its effects kept; its
//! variable is constant data no store may rebind; a loop whose control is
//! not constant, or that stores to its variable, runs at runtime.
use crate::compiler::behaviour_oracle::{Outcome, observe};
use crate::compiler::{CompileMode, Compiler};
use crate::reader::Reader;
use crate::runtime::SymbolTable;
fn outcome(source: &str) -> (Outcome, Vec<String>) {
let (behaviours, _) = observe(source, CompileMode::Script, &[]);
let first = behaviours.into_iter().next().expect("a world");
let logs = first
.output
.iter()
.map(|(_, line)| format!("{line:?}"))
.collect();
(first.outcome, logs)
}
fn value(source: &str) -> String {
match outcome(source).0 {
Outcome::Value(value) => value,
other => panic!("{source}: {other:?}"),
fn compile_error(source: &str) -> String {
let program = Reader::parse(source).unwrap_or_else(|err| panic!("{err}"));
let mut symbols = SymbolTable::with_builtins_for_wasm();
match Compiler::new().compile(&program, &mut symbols) {
Ok(_) => panic!("{source} compiled"),
Err(err) => err.to_string(),
#[test]
fn a_constant_control_do_keeps_its_global_stores() {
assert!(
value("(defvar *g* 0) (do ((i 0 (+ i 1))) ((> i 3)) (setf *g* (+ *g* i))) *g*")
.contains("Index(6)")
);
value("(defvar *g* 0) (do* ((i 0 (+ i 1)) (j i i)) ((> i 3)) (setf *g* (+ *g* j))) *g*")
fn a_do_with_a_macro_body_unrolls_with_the_variable_as_data() {
let (_, logs) = outcome(
"(defmacro emit-k () (if (= k 0) '(print \"a\") '(print \"b\"))) (do ((k 0 (+ k 1))) ((> k 1)) (emit-k))",
assert_eq!(logs, vec!["Text(\"a\")", "Text(\"b\")"]);
fn a_store_to_an_unrolled_loop_variable_is_refused() {
let err = compile_error(
"(defmacro bump (v) (list 'setf v 7)) (do ((k 0 (+ k 1))) ((>= k 2)) (bump k) (print k))",
assert!(err.contains("may not be assigned"), "{err}");
let direct = value("(do ((k 0 (+ k 1))) ((>= k 2)) (setf k 5))");
direct.contains("Nil"),
"a body that stores to its variable runs at runtime: {direct}"
fn a_loop_whose_control_is_not_constant_runs_at_runtime() {
value("(defvar n 3) (setf n 2) (do ((i 0 (+ i 1))) ((>= i n) i))").contains("Index(2)")
fn a_loop_too_long_to_unroll_within_the_budget_compiles_as_a_runtime_loop() {
let source = "(defmacro inc () '(setf *g* (+ *g* 1))) (defvar *g* 0) (do ((i 0 (+ i 1))) ((> i 100000000)) (inc)) *g*";
let program = Reader::parse(source).expect("parses");
assert!(Compiler::new().compile(&program, &mut symbols).is_ok());
fn a_do_init_store_is_kept() {
assert!(value("(let ((x 0)) (do ((z (setf x 5) z)) (t)) x)").contains("Index(5)"));
fn a_result_form_that_stores_to_a_loop_variable_runs_at_runtime() {
assert!(value("(do ((i 0 (+ i 1))) ((= i 3) (setf i 8) i))").contains("Index(8)"));
assert!(value("(do* ((i 0 (+ i 1))) ((>= i 2) (setf i (+ i 10)) i))").contains("Index(12)"));