Files

660 lines
26 KiB
Plaintext
Raw Permalink Normal View History

2026-10-26 10:14:11 -05:00
#! @file evaluation.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains constant evaluation, which runs while a program is checked: the
#! checker asks for what only running gives, as a local constant, an array's
#! length a function gives, the condition of an `if const`, or the text of a
#! `compile_error`, and the program computing it is lowered and run in the
#! machine there and then. One lowerer and one machine live through checking,
#! so what one evaluation lowers is lowered once for all of them. Once the
#! program checks, the global constants it reached that nothing asked for, but
#! that it holds as data, are evaluated too.
#!
#! Each evaluation runs from its start. Reading a constant not yet evaluated
#! stops it, so that constant is evaluated first and the run begins again. A
#! constant keeps its value, and the memory it points into, which the program
#! is given as data; what a run allocated and the value does not keep must have
#! been released, since nothing of the program would hold it. What goes wrong is
#! noted at what asked for it, as the checker notes what it finds.
import sakura::analyzer;
import sakura::compiler;
module sakura::machine;
#! How far each evaluation got.
enum progress : u8 {
pending, #! Not run yet.
running, #! Running, or waiting for another it reads.
done, #! Done, its value kept.
failed, #! Stopped, which was noted.
}
#! How deeply constants may depend on one another, and values point into
#! memory pointing into memory.
const deepest_chain: u64 = 256;
#! The steps, as jumps and calls, each run of an evaluation may take.
const evaluation_budget: u64 = 16777216;
#! What evaluates while a program is checked: a lowerer of the program
#! evaluating and a machine running what it lowers, and what each evaluation
#! worked out.
pub struct compile_time : owning {
var lowered: &mut lowerer; #! The lowerer of the program evaluating.
var running: interpreter; #! The machine running it.
var states: vector<progress>; #! How far each evaluation got.
pub var outcomes: outcomes; #! What was worked out.
}
#! Makes what evaluates while a program is checked.
#! @param lowered The lowerer of the program evaluating, made of the checker.
#! @returns What evaluates.
pub def compile_time::new(lowered: &mut lowerer): compile_time {
return compile_time {
lowered = lowered,
running = interpreter::new(lowered, interpreting { evaluating = true }),
states = vector::<progress>::new(),
outcomes = outcomes::new()
};
}
#! Gives back what the machine holds.
#! @param this What evaluates.
pub def compile_time::close(&mut this): void {
this.running.close();
this.states.close();
}
#! Checks a program, evaluating what checking asks for as it goes, then the
#! global constants it reached that the program holds as data.
#! @param checker The checker, given the program's files.
#! @param runs Whether the program may be run, which one whose files did
#! not parse may not, so checking evaluates nothing.
#! @returns What was worked out.
#! @remarks The checker holds a function referring to what evaluates only while
#! it checks, and is given none again before it ends, which its
#! lifetime warning cannot see.
@allow
pub def check_evaluating(checker: &mut checker, runs: bool = true): outcomes {
return checked_alone(checker) if !runs;
var lowered := lowerer::new(checker, lowering { verify = true, evaluating = true });
var timing := compile_time::new(&mut lowered);
checker.evaluator = def(ask: &evaluation_ask, out: &mut evaluation_answer): void {
timing.answer(ask, out);
};
checker.check();
if !checker.failed {
timing.finish();
}
checker.evaluator = nothing {};
return move(&mut timing.outcomes);
}
# Checks a program that is not run, which evaluates nothing.
def checked_alone(checker: &mut checker): outcomes {
checker.check();
return outcomes::new();
}
#! Works out what the checker asks for: lowers the program computing it, and
#! what that calls, loads what is new into the machine, and runs it.
#! @param this What evaluates.
#! @param ask What is asked for.
#! @param out Where the answer is written: the value, where it is one a
#! constant holds, or the text, and whether a note was made of
#! what went wrong.
pub def compile_time::answer(&mut this, ask: &evaluation_ask, out: &mut evaluation_answer): void {
val key := node_key(ask.table, ask.node);
val index := this.lowered.evaluation_of(key, 0, ask.table, ask.node, ask.what == evaluation_kind::condition, ask.what == evaluation_kind::value);
out.noted = true;
val ran := this.run(index);
return if !ran;
out.worked = true;
out.noted = false;
val held: evaluation = this.lowered.evaluations[index];
if held.condition {
out.scalar = true;
out.value = constant::truth(this.outcomes.decisions.get(&key) is some(holds) && holds);
} else if held.text {
if this.outcomes.texts.get(&key) is some(&text) {
out.text = string::copy_of(&text);
}
} else if this.lowered.is_scalar_type(held.kind) && this.outcomes.values.get(&key) is some(&value) {
out.scalar = true;
out.value = this.lowered.constant_of(value.bytes.span, held.kind);
}
}
#! Evaluates the global constants the program reached and nothing asked for,
#! and the instances of those of generic types, whose values the program holds
#! as data.
#! @param this What evaluates.
pub def compile_time::finish(&mut this): void {
for id in 1..this.lowered.checker.decls.count {
val decl := id as u32;
continue if !this.lowered.checker.decls.has(decl, df::checked) || !this.lowered.needs_evaluation(decl);
_ = this.run(this.lowered.evaluation_of(decl_key(decl), decl, 0, 0, false, false));
}
# So are the instances of constants of generic types, as local constants are.
for i in 1..this.lowered.checker.instances.length {
continue if !this.lowered.needs_instance_evaluation(i as u32);
val held: instance = this.lowered.checker.instances[i];
val node: u32 = this.lowered.checker.decls.nodes.p[held.decl];
_ = this.run(this.lowered.evaluation_of(node_key(held.table, node), 0, held.table, node, false, false));
}
}
#! Lowers an evaluation and what it calls, loads what is new into the machine,
#! and runs it, noting what goes wrong.
#! @param this What evaluates.
#! @param index The evaluation.
#! @returns Whether it was worked out.
def compile_time::run(&mut this, index: u32): bool {
val problems := this.lowered.problems.length;
this.lowered.drain();
this.lowered.fill_retraits();
this.lowered.drain();
this.states.resize(this.lowered.evaluations.length);
if this.lowered.problems.length != problems {
# What checking what lowering reached found was noted where it was.
if !this.lowered.checker.failed {
for i in problems..this.lowered.problems.length {
var text := string::from("Evaluating could not lower this program: ", nothing {});
text.append(this.lowered.problems[i].span);
this.lowered.report_evaluation(index, &mut text);
}
}
this.states[index] = progress::failed;
return false;
}
if !this.running.refresh() {
var text := string::from("Evaluating holds more globals than the machine has room for while checking.", nothing {});
this.lowered.report_evaluation(index, &mut text);
this.states[index] = progress::failed;
return false;
}
return this.running.evaluate_one(index, 0, &mut this.states, &mut this.outcomes);
}
#! The constant a value of a number, `bool`, character, or enum is, from the
#! bytes evaluating kept of it.
#! @param this The compiler.
#! @param bytes The bytes.
#! @param kind Its type.
#! @returns The constant.
pub def lowerer::constant_of(&mut this, bytes: span<u8>, kind: u32): constant {
var plain := this.checker.unalias(kind);
if this.checker.named_kind(plain) == dk::enum_type {
plain = this.checker.unalias(this.checker.decls.targets.p[this.checker.types.first_of(plain)]);
}
var raw: u64 = 0;
val size := bytes.length < 8 ? bytes.length : 8;
for i in 0..size {
raw |= (bytes[i] as u64) << (8 * i as u64);
}
return constant::truth((raw & 0xFF) != 0) if this.checker.types.is_boolean(plain);
if this.checker.types.is_float(plain) {
if size == 4 {
var narrow := raw as u32;
return constant::real_of(((&mut narrow) as *mut f32)[0] as f64);
}
var wide := raw;
return constant::real_of(((&mut wide) as *mut f64)[0]);
}
val signed := this.checker.types.is_signed(plain);
if signed && size < 8 && size != 0 && (raw >> (8 * size as u64 - 1)) != 0 {
raw |= ~((1u << (8 * size as u64)) - 1);
}
return constant::from_bits(raw, signed);
}
#! Notes what went wrong evaluating, at the constant or condition.
#! @param this The compiler of the program evaluating.
#! @param index The evaluation, or `none` for none in particular.
#! @param text What the note says.
pub def lowerer::report_evaluation(&mut this, index: u32, text: &mut string): void {
val saved := this.checker.at;
var file: u32 = 0;
var node: u32 = 0;
if (index as u64) < this.evaluations.length {
val held: evaluation = this.evaluations[index];
if held.decl != 0 {
file = this.checker.decls.files.p[held.decl];
node = this.checker.decls.nodes.p[held.decl];
} else {
file = this.checker.tables.p[held.table].file;
node = held.node;
}
}
this.checker.at.instance = 0;
this.checker.report_in(file, node, ec::constant, text.span);
this.checker.at = saved;
}
#! What a note names an evaluation as: a constant by its name, or the
#! condition of `if const`.
#! @param this The compiler.
#! @param index The evaluation.
#! @returns The name.
def lowerer::evaluation_name(&mut this, index: u32): string {
val held: evaluation = this.evaluations[index];
return string::from("the condition of `if const`", nothing {}) if held.condition;
return string::from("the text of `compile_error`", nothing {}) if held.text;
return $"`{this.program.functions[held.function].name}`";
}
#! Evaluates one constant or condition, evaluating first those its run stops
#! at, and keeps what it worked out.
#! @param this The machine.
#! @param index The evaluation.
#! @param depth How many evaluations wait for it.
#! @param states How far each evaluation got.
#! @param out Where what is worked out is kept.
#! @returns Whether it was evaluated.
def interpreter::evaluate_one(&mut this, index: u32, depth: u64, states: &mut vector<progress>, out: &mut outcomes): bool {
val state: progress = states[index];
return state == progress::done if state == progress::done || state == progress::failed;
if depth > deepest_chain {
var text := string::from("Constants depend on one another too deeply to evaluate.", nothing {});
this.c.report_evaluation(index, &mut text);
states[index] = progress::failed;
return false;
}
states[index] = progress::running;
val held: evaluation = this.c.evaluations[index];
var kept := evaluated {
bytes = vector::<u8>::new(),
addresses = vector::<kept_address>::new(),
blocks = vector::<kept_block>::new()
};
while true {
this.budget = evaluation_budget;
val why := this.invoke(held.function, span::<u64>::blank());
# A run that finished keeps its value before anything is released, since
# the memory the value points into is memory the run still holds.
if why == halt::none && !held.condition {
if !this.keep_value(index, &mut kept) {
this.release_unkept();
states[index] = progress::failed;
return false;
}
}
# What a run allocated and its value does not keep, nothing of the program
# holds once it is done.
val leaked := this.release_unkept();
if why == halt::none && leaked != 0 {
var text := $"Evaluating {this.c.evaluation_name(index)} allocated memory it neither released nor kept, {leaked} block";
text.append(leaked == 1 ? "" : "s");
text.append(" of it, which only a running program could hold.");
this.c.report_evaluation(index, &mut text);
states[index] = progress::failed;
return false;
}
break if why == halt::none;
# A constant it reads is evaluated first, then it runs again from its start.
if why == halt::not_evaluated && (this.waiting as u64) < states.length {
if states[this.waiting] == progress::running {
var text := $"{this.c.evaluation_name(index)} depends on its own value, through the constants it reads.";
this.c.report_evaluation(index, &mut text);
states[index] = progress::failed;
return false;
}
if !this.evaluate_one(this.waiting, depth + 1, states, out) {
states[index] = progress::failed;
return false;
}
continue;
}
var text := $"Evaluating {this.c.evaluation_name(index)} stopped: {this.why_text(why)}";
for &each in this.trace {
text.append($"\n at {each.function} ({each.path}:{each.line}:{each.column})");
}
this.c.report_evaluation(index, &mut text);
this.fault_text.clear();
states[index] = progress::failed;
return false;
}
# A constant keeps its value, a condition whether it holds, and text what
# it says, read through the memory its value kept.
if held.condition {
val word := ((this.globals as u64 + held.offset) as *u8)[0];
out.decisions.set(held.key, word != 0);
} else if held.text {
out.texts.set(held.key, this.text_at(this.globals as u64 + held.offset, held.kind));
} else {
out.values.set(held.key, move(&mut kept));
}
this.ready[index] = true;
states[index] = progress::done;
return true;
}
#! The text a value holds, as a `strview` or a `string` does, copied from where
#! its bytes are.
#! @param this The machine.
#! @param at Where the value is.
#! @param kind Its type.
#! @returns The text, or empty text where the value holds none.
def interpreter::text_at(&mut this, at: u64, kind: u32): string {
var made := string::new(nothing {});
val layout := this.c.layout_of(kind);
val shape := this.c.layout_at(layout);
return made if !shape.texts;
val begins := this.c.field_at(layout, shape.text);
val many := this.c.field_at(layout, shape.text + 1);
val data := ((at + begins.offset) as *u64)[0];
if data != 0 {
made.append(span::<u8>::over(data as *u8, ((at + many.offset) as *u64)[0]));
}
return made;
}
#! Releases the blocks a run allocated that no value evaluated keeps.
#! @param this The machine.
#! @returns How many were released.
def interpreter::release_unkept(&mut this): u64 {
var gone := vector::<u64>::new();
for &entry in this.blocks {
if !this.kept.contains(&entry.key) {
gone.append(entry.key);
}
}
for &each in gone {
this.release(each);
}
return gone.length;
}
#! What keeping a value finds: the units of memory it reaches, the value first.
struct keeping {
var units: vector<kept_block>; #! The value, then each block of memory it points into.
var bases: vector<u64>; #! Where each unit's memory was, so memory reached twice is kept once.
var blocks: vector<bool>; #! Whether each unit is memory the run allocated.
var failed: bool; #! Whether the value cannot be kept, which was noted.
}
#! Keeps the value an evaluation computed: its bytes, laid out as its type is,
#! with the memory it points into.
#! @param this The machine.
#! @param index The evaluation.
#! @param out Where the value is kept.
#! @returns Whether it could be, which a note says where it could not.
def interpreter::keep_value(&mut this, index: u32, out: &mut evaluated): bool {
val held: evaluation = this.c.evaluations[index];
val layout := this.c.layout_of(held.kind);
val size := this.c.layout_at(layout).size;
var work := keeping {
units = vector::<kept_block>::new(),
bases = vector::<u64>::new(),
blocks = vector::<bool>::new()
};
this.add_unit(&mut work, this.globals as u64 + held.offset, size, 0, false);
this.walk(index, &mut work, 0, 0, layout, 0);
return false if work.failed;
# Addresses name the blocks past the value, which is not one of them.
for &mut unit in work.units {
for &mut each in unit.addresses {
if each.block != no_block && each.block != in_constant {
each.block = each.block - 1;
}
}
}
out.bytes = move(&mut work.units[0].bytes);
out.addresses = move(&mut work.units[0].addresses);
out.blocks.clear();
for u in 1..work.units.length {
out.blocks.append(move(&mut work.units[u]));
}
return true;
}
#! Adds a unit holding a copy of memory.
#! @param this The machine.
#! @param work What keeping found so far.
#! @param from Where the memory is.
#! @param size How many bytes it holds.
#! @param base Where it begins, so memory reached twice is kept once, or 0.
#! @param block Whether it is memory the run allocated.
#! @returns The unit's index.
def interpreter::add_unit(&mut this, work: &mut keeping, from: u64, size: u64, base: u64, block: bool): u32 {
var bytes := vector::<u8>::new();
bytes.resize(size);
if size != 0 {
memcpy(bytes.slice.data, from as *u8, size);
}
work.units.append(kept_block { bytes = move(&mut bytes), addresses = vector::<kept_address>::new() });
work.bases.append(base);
work.blocks.append(block);
return (work.units.length - 1) as u32;
}
#! Notes that a value holds the address of memory only the compiler has.
#! @param this The machine.
#! @param index The evaluation.
#! @param work What keeping found so far.
def interpreter::escaped(&mut this, index: u32, work: &mut keeping): void {
return if work.failed;
work.failed = true;
var text := this.c.evaluation_name(index);
text.append(" holds the address of memory only the compiler has, such as a variable of the value being computed or memory already released, which goes away once it has run. A constant keeps the memory it allocated and still holds, and the bytes of text, which the program is given again.");
this.c.report_evaluation(index, &mut text);
}
#! Whether values of a layout hold addresses, so their bytes are walked rather
#! than simply kept.
#! @param this The machine.
#! @param layout The layout.
#! @param depth How deeply within values it is.
#! @returns Whether they do.
def interpreter::holds_addresses(&mut this, layout: u32, depth: u64): bool {
return false if depth > deepest_chain;
val shape := this.c.layout_at(layout);
return match shape.kind {
lk::pointer, lk::reference, lk::trait_reference, lk::function => true,
lk::fixed => this.holds_addresses(shape.element - 1, depth + 1),
lk::record, lk::variant => this.fields_hold_addresses(layout, &shape, depth),
else => false
};
}
#! Whether any field of a struct or union holds addresses.
#! @param this The machine.
#! @param layout The layout.
#! @param shape The layout itself.
#! @param depth How deeply within values it is.
#! @returns Whether any does.
def interpreter::fields_hold_addresses(&mut this, layout: u32, shape: &layout, depth: u64): bool {
for i in 0..shape.count {
val field := this.c.field_at(layout, i as u32);
return true if this.holds_addresses(field.layout, depth + 1);
}
return false;
}
#! Walks bytes of a unit laid out as a layout, keeping the memory each address
#! within them points into, and noting where each address is.
#! @param this The machine.
#! @param index The evaluation.
#! @param work What keeping found so far.
#! @param unit The unit.
#! @param at Where the value is within it.
#! @param layout The value's layout.
#! @param depth How deeply within values it is.
def interpreter::walk(&mut this, index: u32, work: &mut keeping, unit: u32, at: u64, layout: u32, depth: u64): void {
return if work.failed;
if depth > deepest_chain {
work.failed = true;
var text := string::from("The value points into memory that points into memory too deeply to keep.", nothing {});
this.c.report_evaluation(index, &mut text);
return;
}
val shape := this.c.layout_at(layout);
val bytes := work.units[unit].bytes.span.data;
match shape.kind {
lk::pointer, lk::reference => {
val word := ((bytes as u64 + at) as *u64)[0];
return if word == 0;
var addend: u64 = 0;
# Another constant's value is data of the program already, so an address
# into it is kept as one into that data, which keeps nothing more.
var other: u32 = 0;
if this.constant_at(index, word, &mut other, &mut addend) {
val held: evaluation = this.c.evaluations[other];
work.units[unit].addresses.append(kept_address {
at = at, block = in_constant, addend = addend, decl = held.decl, table = held.table, node = held.node
});
return;
}
val target := this.promote(index, work, word, shape.element, depth, &mut addend);
return if work.failed;
work.units[unit].addresses.append(kept_address { at = at, block = target, addend = addend });
}
# A trait reference holds a vtable of the program evaluating, and a function
# value a closure's locals, neither of which outlives the run.
lk::trait_reference => this.escaped(index, work);
lk::function => {
val function := ((bytes as u64 + at) as *u64)[0];
if ((bytes as u64 + at + word_size) as *u64)[0] != 0 {
this.escaped(index, work);
return;
}
return if function == 0 || function - 1 >= this.c.program.functions.length;
val named := &this.c.program.functions[function - 1];
var made := kept_address { at = at, block = no_block, decl = named.decl, instance = named.instance };
if named.decl == 0 {
made.table = named.table;
made.node = named.node;
made.file = named.file;
}
work.units[unit].addresses.append(made);
}
lk::fixed => {
val size := this.c.layout_at(shape.element - 1).size;
for i in 0..shape.count {
this.walk(index, work, unit, at + i as u64 * size, shape.element - 1, depth + 1);
}
}
lk::record => {
for i in 0..shape.count {
val field := this.c.field_at(layout, i as u32);
this.walk(index, work, unit, at + field.offset, field.layout, depth + 1);
}
}
lk::variant => {
# A union holds the one its tag gives, and the bytes of the rest mean nothing.
val tag := held_field(&shape, ((bytes as u64 + at) as *u64)[0]);
if tag < shape.count as u64 {
val field := this.c.field_at(layout, tag as u32);
this.walk(index, work, unit, at + field.offset, field.layout, depth + 1);
}
}
else => {}
}
}
#! Whether an address points into the value of another constant, one evaluated
#! already, giving which and how far into it, where it does. An address just
#! past the end of one, as an empty view's may be, is of that one where no value
#! holds it.
#! @param this The machine.
#! @param index The evaluation whose value holds the address.
#! @param address The address.
#! @param found Where the constant's evaluation is written.
#! @param addend Where how far into its value the address points is written.
#! @returns Whether it does.
def interpreter::constant_at(&mut this, index: u32, address: u64, found: &mut u32, addend: &mut u64): bool {
var past := false;
for i in 0..this.c.evaluations.length {
continue if i == index as u64 || !this.ready[i];
val other: evaluation = this.c.evaluations[i];
continue if other.condition;
val base := this.globals as u64 + other.offset;
val size := this.c.layout_at(this.c.layout_of(other.kind)).size;
if address >= base && address < base + size {
found = i as u32;
addend = address - base;
return true;
}
if !past && address == base + size && size != 0 {
found = i as u32;
addend = size;
past = true;
}
}
return past;
}
#! Keeps the memory an address points into, giving the unit it became and how
#! far into it the address points: memory the run allocated and still holds,
#! which stays held for the rest of the evaluating, or the bytes of a datum.
#! Memory anywhere else is the compiler's own, which is noted.
#! @param this The machine.
#! @param index The evaluation.
#! @param work What keeping found so far.
#! @param address The address.
#! @param element One more than the layout of what it points at, or 0.
#! @param depth How deeply within values it is.
#! @param addend Where how far into the memory it points is written.
#! @returns The unit.
def interpreter::promote(&mut this, index: u32, work: &mut keeping, address: u64, element: u32, depth: u64, addend: &mut u64): u32 {
var base: u64 = 0;
var size: u64 = 0;
var block := false;
for &entry in this.blocks {
if address >= entry.key && address < entry.key + entry.value + 1 {
base = entry.key;
size = entry.value;
block = true;
break;
}
}
if !block {
for i in 0..this.data.length {
val data: u64 = this.data[i];
val length := this.c.program.data[i].bytes.length;
if address >= data && address < data + length {
base = data;
size = length == 0 ? 0 : length - 1;
break;
}
}
}
if base == 0 {
this.escaped(index, work);
return 0;
}
addend = address - base;
for u in 1..work.units.length {
return u as u32 if work.bases[u] == base;
}
val unit := this.add_unit(work, base, size, base, block);
if block {
this.kept.set(base, true);
}
# What the memory holds is read as a run of the elements the address gives,
# since memory of no elements, as that of text, holds no addresses.
return unit if element == 0;
val shape := this.c.layout_at(element - 1);
return unit if shape.size == 0 || !this.holds_addresses(element - 1, 0);
var at: u64 = 0;
while at + shape.size <= size && !work.failed {
this.walk(index, work, unit, at, element - 1, depth + 1);
at += shape.size;
}
return unit;
}