Lines
98.65 %
Functions
100 %
Branches
use std::cell::RefCell;
use std::collections::BTreeSet;
use std::path::Path;
use std::sync::Once;
use tracing::field::{Field, Visit};
use tracing::{Event, Subscriber};
use tracing_subscriber::layer::{Context, SubscriberExt};
use tracing_subscriber::{Layer, Registry};
use super::{form_digest, function_owner};
use crate::compiler::Compiler;
use crate::compiler::behaviour_snapshot::declared_hosts;
use crate::compiler::expr::eval_value;
use crate::reader::Reader;
use crate::runtime::SymbolTable;
type Sites = Vec<(String, String)>;
thread_local! {
static SINK: RefCell<Option<Sites>> = const { RefCell::new(None) };
}
#[derive(Default)]
struct SiteVisitor {
surface: String,
key: String,
impl Visit for SiteVisitor {
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
match field.name() {
"surface" => self.surface = format!("{value:?}"),
"key" => self.key = format!("{value:?}"),
_ => {}
struct Recorder;
impl<S: Subscriber> Layer<S> for Recorder {
fn on_event(&self, event: &Event<'_>, _: Context<'_, S>) {
let mut site = SiteVisitor::default();
event.record(&mut site);
SINK.with(|sink| {
if let Some(sites) = sink.borrow_mut().as_mut() {
sites.push((site.surface, site.key));
});
/// The recorder is the process-wide default: a per-test subscriber leaves the
/// callsite interest cache racing with the other test threads' events.
fn install_recorder() {
static INSTALLED: Once = Once::new();
INSTALLED.call_once(|| {
let _ = tracing::subscriber::set_global_default(Registry::default().with(Recorder));
fn recorded(run: impl FnOnce()) -> Vec<(String, String)> {
install_recorder();
SINK.with(|sink| *sink.borrow_mut() = Some(Vec::new()));
run();
SINK.with(|sink| sink.borrow_mut().take().unwrap_or_default())
fn on_surface(sites: &[(String, String)], surface: &str) -> Vec<String> {
sites
.iter()
.filter(|(from, _)| from == surface)
.map(|(_, key)| key.clone())
.collect()
fn evaluated(source: &str) -> Vec<String> {
let sites = recorded(|| {
let program = Reader::parse(source).expect("parses");
let mut symbols = SymbolTable::with_builtins();
for expr in &program.exprs {
eval_value(&mut symbols, expr).expect("evaluates");
on_surface(&sites, "Eval")
fn compiled(source: &str) -> (Vec<String>, u64) {
let mut attempts = 0;
let mut compiler = Compiler::new();
compiler.compile(&program, &mut symbols).expect("compiles");
attempts = compiler.stats().unit_attempts;
(on_surface(&sites, "Codegen"), attempts)
fn distinct(keys: &[String]) -> BTreeSet<&str> {
keys.iter().map(String::as_str).collect()
const ACCUMULATE: &str = "(defun f (a) (let ((r nil)) (setf r (cons a r)) r))";
/// Source, the distinct keys codegen records, the distinct keys eval records.
fn rows() -> Vec<(String, usize, usize)> {
let row = |source: &str, codegen: usize, eval: usize| (source.to_string(), codegen, eval);
vec![
row("(let ((x (entity-count))) (+ x 1))", 0, 0),
row(
"(let ((x 0)) (setf x (entity-count)) (let ((y x)) y))",
1,
),
row("(let* ((a 0) (b 1)) (setf a b) (setf b a) b)", 2, 2),
"(let ((a 0)) (let ((b a)) (setf b 1) (setf a b) (+ a b)))",
2,
row("(do ((i 0 (+ i 1))) ((= i (entity-count)) i))", 1, 1),
row("(do* ((i 0 (+ i 1)) (j i)) ((= i (entity-count)) j))", 1, 1),
row("(do ((i 0 (+ i 1)) (j 0)) ((= i 2) j) (setf j i))", 2, 2),
row("(dolist (x '(1 2)) (print x))", 0, 0),
row("(dolist (x '(1 2)) (setf x 3) (print x))", 1, 1),
"(let ((acc nil)) (dolist (x '(1 2)) (setf acc (cons x acc))) (let ((y acc)) y))",
"(let ((n (entity-count))) (let ((f (lambda () n))) (setf n 2) (funcall f)))",
"(let ((a (entity-count))) (let ((c (lambda () a))) (let ((a 5)) (setf a 6) a)))",
"(labels ((g (a) (let ((r nil)) (setf r (cons a r)) r))) (list (g (entity-count)) (g 1/2)))",
"(defmacro my-incf (v) `(setf ,v (+ ,v 1))) (let ((x 0)) (my-incf x) x)",
"(defmacro my-push (e v) `(setf ,v (cons ,e ,v))) (let ((x nil)) (my-push 1 x) (my-push 2 x) x)",
row("(let ((x 0)) (let ((x 1) (y (setf x 2))) y))", 1, 1),
"(defmacro w (b) `(labels ((h () ,b)) (let ((x (h))) (setf x (h)) x))) (list (w 1) (w 1/2))",
]
#[test]
fn eval_and_codegen_name_each_assigned_binder_alike() {
for (source, codegen_sites, eval_sites) in rows() {
let by_eval = evaluated(&source);
let (by_codegen, _) = compiled(&source);
let (eval_keys, codegen_keys) = (distinct(&by_eval), distinct(&by_codegen));
assert_eq!(eval_keys.len(), eval_sites, "eval keys of {source}");
assert_eq!(
codegen_keys.len(),
codegen_sites,
"codegen keys of {source}"
);
assert!(
eval_keys.is_subset(&codegen_keys),
"{source}: eval {eval_keys:?} codegen {codegen_keys:?}"
fn a_dynamic_special_has_no_site() {
let source = "(defvar *s* 0) (let ((*s* 1)) (setf *s* 2) *s*)";
assert!(compiled(source).0.is_empty());
fn a_constant_argument_keys_the_binder_by_its_literal_type() {
let source = format!("{ACCUMULATE} (list (f 1) (f 1/2) (f 2) (f 2/1))");
assert_eq!(by_codegen.len(), 4);
assert_eq!(distinct(&by_codegen).len(), 2);
assert_eq!(by_codegen[0], by_codegen[2]);
assert_eq!(by_codegen[1], by_codegen[3]);
assert_ne!(by_codegen[2], by_codegen[3]);
assert_eq!(evaluated(&source), by_codegen);
fn a_macro_argument_keys_the_binder_by_its_literal_type() {
let source =
"(defmacro acc (x) `(let ((r nil)) (setf r (cons ,x r)) r)) (list (acc 1) (acc 1/2))";
let (by_codegen, _) = compiled(source);
fn runtime_arguments_of_two_types_share_one_key() {
format!("{ACCUMULATE} (list (f (entity-count)) (f (index->scalar (entity-count))))");
let (by_codegen, attempts) = compiled(&source);
assert_eq!(by_codegen.len() as u64, 2 * attempts);
assert_eq!(distinct(&by_codegen).len(), 1);
assert_eq!(distinct(&evaluated(&source)), distinct(&by_codegen));
fn a_binder_is_keyed_alike_in_every_attempt_of_a_unit() {
let source = "(defvar g 0) (let ((x 0)) (setf x g) (setf g 1/2) x)";
let (by_codegen, attempts) = compiled(source);
assert!(attempts > 1, "{attempts} attempts");
assert!(by_codegen.len() > 1, "{by_codegen:?}");
fn identical_binders_in_two_defuns_have_a_key_each() {
let source = "(defun a (xs) (let ((r nil)) (setf r (cons xs r)) r)) \
(defun b (xs) (let ((r nil)) (setf r (cons xs r)) r)) \
(list (a 1) (b 1))";
assert_eq!(by_codegen.len(), 2);
assert_eq!(distinct(&evaluated(source)), distinct(&by_codegen));
fn the_function_owner_tells_functions_apart() {
let body = |text| Reader::parse(text).expect("parses").exprs.remove(0);
let table = SymbolTable::new();
let (one, other) = (body("(+ x 1)"), body("(+ x 2)"));
function_owner(&table, Some("A"), &one),
function_owner(&table, Some("A"), &other)
assert_ne!(
function_owner(&table, Some("B"), &one)
function_owner(&table, None, &one),
function_owner(&table, None, &one.clone())
function_owner(&table, None, &other)
function_owner(&table, None, &one)
fn the_form_digest_tells_nesting_apart() {
let flat = Reader::parse("(a b c)").expect("parses").exprs;
let nested = Reader::parse("((a b) c)").expect("parses").exprs;
let other = Reader::parse("(a b c)").expect("parses").exprs;
let digest = |head, forms| form_digest(head, forms).0;
assert_eq!(digest("LET", &flat), digest("LET", &other));
assert_ne!(digest("LET", &flat), digest("LET", &nested));
assert_ne!(digest("LET", &flat), digest("LET*", &flat));
fn every_assigned_eval_key_of_the_acceptance_corpus_has_its_codegen_key() {
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/acceptance");
let mut eval_sites = 0;
for entry in std::fs::read_dir(dir).expect("corpus directory") {
let path = entry.expect("corpus entry").path();
// Eval stops simulating a loop after MAX_STATIC_LOOP_ITERS end tests, where
// codegen unrolls a forced loop further, so it keys a loop nested in a longer
// one under a scope codegen never has (value-neutral, ADR-0035 ledger).
if matches!(
path.file_name().and_then(|name| name.to_str()),
Some("nestloop-100x100.nms" | "nestloop-70x70.nms")
) {
continue;
let Ok(source) = std::fs::read_to_string(&path) else {
};
let Ok(program) = Reader::parse(&source) else {
return;
let hosts = declared_hosts(&source).specs();
symbols.register_host_fns(&hosts);
drop(Compiler::with_host_fns(hosts).compile(&program, &mut symbols));
let (by_eval, by_codegen) = (on_surface(&sites, "Eval"), on_surface(&sites, "Codegen"));
let codegen_keys = distinct(&by_codegen);
eval_sites += by_eval.len();
by_eval
.all(|key| codegen_keys.contains(key.as_str())),
"{}: eval {by_eval:?} codegen {by_codegen:?}",
path.display()
assert!(eval_sites > 300, "{eval_sites} eval sites");