#! @file evaluation.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains constant evaluation, which runs once a program checks: a program #! computing its constants, and the conditions of the `if const` statements the #! checker left undecided, is lowered and run in the machine, as #! `sources/evaluator.c` does. Each `compile_error` the checker left to it is #! then reported where the branches around it are those chosen, with its text #! worked out last, where the checker could not read it. #! #! 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 the constant, 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; #! Evaluates what checking left to evaluating, noting what goes wrong as the #! checker notes what it finds. #! @param checker The checker, which checked the program without notes. #! @returns What was worked out. pub def evaluate(checker: &mut checker): outcomes { var made := outcomes::new(); var lowered := lowerer::new(checker, lowering { verify = true, evaluating = true }); lowered.compile(); return made if lowered.evaluations.length == 0; if lowered.problems.length != 0 { for i in 0..lowered.problems.length { var text := string::from("Evaluating could not lower this program: ", nothing {}); text.append(lowered.problems[i].view()); lowered.report_evaluation(0xFFFFFFFF, &mut text); } return made; } var running := interpreter::new(&mut lowered, interpreting { evaluating = true }); val count := running.c.evaluations.length; running.ready.resize(count); var states := vector::::new(); states.resize(count); for i in 0..count { # The text of a `compile_error` waits for the branches around it. continue if running.c.evaluations[i].text; running.evaluate_one(i as u32, 0, &mut states, &mut made); } running.report_held(&mut states, &mut made); return made; } #! Reports each `compile_error` the checker left to evaluating whose branches #! of `if const` are each the one its condition chose, evaluating its text #! first where the checker could not read it. #! @param this The machine. #! @param states How far each evaluation got. #! @param out What was worked out. def interpreter::report_held(&mut this, states: &mut vector, out: &mut outcomes): void { for i in 0..this.c.checker.held_errors.length { val held := &this.c.checker.held_errors[i]; var chosen := true; for b in held.first..held.first + held.count { val branch: checker::branch = this.c.checker.held_branches[b as u64]; if out.decisions.get(&node_key(branch.table, branch.node)) is some(holds) { chosen = chosen && holds == branch.holds; } else { chosen = false; } } continue if !chosen; var text := string::new(nothing {}); if held.computed { val key := node_key(held.table, held.node); val index := this.c.evaluation_ids.get(&key) else { continue; }; continue if !this.evaluate_one(index, 0, states, out); text.append(out.texts[key].view()); } this.c.checker.report_held(i as u32, &mut text); } } #! 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.view()); 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, 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::::new(), addresses = vector::::new(), blocks = vector::::new() }; while true { this.budget = evaluation_budget; val why := this.invoke(held.function, span::::empty()); # 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::::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::::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; #! The value, then each block of memory it points into. var bases: vector; #! Where each unit's memory was, so memory reached twice is kept once. var blocks: vector; #! 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::::new(), bases = vector::::new(), blocks = vector::::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::::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::::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.view().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; }