Files
sakurac/compiler/emitter/statements.sakura
T

653 lines
26 KiB
Plaintext
Raw Normal View History

2026-10-26 10:14:11 -05:00
#! @file statements.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the lowering of statements: blocks and the locals declared in
#! them, branches, `if const` and `when`, loops, contracts, and leaving by
#! `return`, `break`, and `continue`, each closing what it leaves behind.
import sakura::analyzer;
module sakura::compiler;
#! Lowers a block, whose locals close where it ends. Statements after one the
#! checker found always leaves, as decided while checking, were never checked,
#! so they are not lowered either.
#! @param this The emitter.
#! @param node The block, or a statement standing for one.
pub def emitter::lower_block(&mut this, node: u32): void {
return if node == 0;
if this.c.checker.kind_of(node) != nk::block {
this.lower_statement(node);
return;
}
val mark := this.scope_mark();
val run := this.c.checker.left_of(node);
for i in 0..this.c.checker.run_length(run) {
val each := this.c.checker.run_at(run, i as u32);
this.lower_statement(each);
break if this.skips(each);
}
this.end_scope(mark, 0);
}
#! Whether a statement leaves where it was decided while checking, so the
#! checker checked nothing after it: an `if const` whose branch taken leaves,
#! with no `else`, or a block or `when` holding one.
#! @param this The emitter.
#! @param node The statement.
#! @returns Whether it does.
pub def emitter::skips(&mut this, node: u32): bool {
match this.c.checker.kind_of(node) {
nk::block => {
val run := this.c.checker.left_of(node);
for i in 0..this.c.checker.run_length(run) {
return true if this.skips(this.c.checker.run_at(run, i as u32));
}
}
nk::when_block => return this.skips(this.c.checker.when_branch(node));
nk::if_const => {
val condition := this.c.checker.left_of(node);
return false if !this.c.checker.is_known(condition);
val then := this.c.checker.record(node, if_slot::then);
val other := this.c.checker.record(node, if_slot::other);
if this.c.checker.value_at(condition).magnitude != 0 {
return this.skips(then) || (other == 0 && this.c.checker.has_flag(then, rf::leaves));
}
return other != 0 && this.skips(other);
}
else => {}
}
return false;
}
#! Lowers a statement.
#! @param this The emitter.
#! @param node The statement.
pub def emitter::lower_statement(&mut this, node: u32): void {
# A contract left out is no statement at all, so what follows takes no
# place of it.
return if this.c.checker.contracts_off && this.c.checker.kind_of(node) == nk::contract;
this.at_node(node);
match this.c.checker.kind_of(node) {
nk::block => this.lower_block(node);
nk::variable => this.local_statement(node);
nk::if_stmt => this.if_statement(node);
nk::if_const => this.if_const(node);
nk::when_block => this.lower_block(this.c.checker.when_branch(node));
nk::while_stmt => this.while_statement(node);
nk::for_stmt => this.for_statement(node);
nk::match_stmt => {
val mark := this.begin_statement();
this.lower_match(node, false);
this.end_statement(mark);
}
nk::return_stmt => {
val mark := this.begin_statement();
val value := this.c.checker.left_of(node);
if value != 0 && this.result != bt::void_type {
this.return_value(value, mark);
return;
}
# `return;` from a function giving more than nothing gives `void`, as a
# `result<void, E>` holds it.
if value == 0 && this.c.checker.unalias(this.result) != bt::void_type {
val none := operand::none(bt::void_type);
var made := this.convert(&none, this.result);
this.return_made(&mut made, 0, mark);
return;
}
# What gives nothing, returned from a function giving nothing, is done first.
if value != 0 {
this.value(value);
}
this.close_kept(mark.kept);
this.leave_kept(0);
this.close_locals(0, 0);
this.build.ret(span::<u32>::empty());
}
nk::break_stmt, nk::continue_stmt => this.leave_loop(this.c.checker.kind_of(node) == nk::break_stmt);
nk::contract => this.contract_statement(node);
nk::expr_stmt => {
val mark := this.begin_statement();
val inner := this.c.checker.left_of(node);
this.value(inner);
this.end_statement(mark);
# A call that ends the program, as `exit`, is never returned from.
if this.ends_program(inner) {
this.build.unreachable();
}
}
else => {}
}
}
#! Lowers a contract, as only a program checking contracts does: `expects` and
#! `asserts` are checked where they are, and an `ensures` is an entry among the
#! locals, which closing checks on each way out of its block, once what each
#! `old` within it reads is kept.
#! @param this The emitter.
#! @param node The `contract` node.
def emitter::contract_statement(&mut this, node: u32): void {
if this.c.checker.clause_of(node) != clause::ensures {
val mark := this.begin_statement();
this.check_contract(node);
this.end_statement(mark);
return;
}
this.keep_earlier(this.c.checker.left_of(node));
val index := this.declare(node, location {}, true);
this.locals[index].checks = true;
}
#! Keeps what each `old(e)` in an `ensures`'s condition reads, where the
#! `ensures` is reached, as a local the `old_value` node declares.
#! @param this The emitter.
#! @param condition The condition.
def emitter::keep_earlier(&mut this, condition: u32): void {
var walk := node_walk::new(condition);
while walk.more() {
val at := walk.next();
if this.c.checker.kind_of(at) == nk::old_value {
val held := this.c.checker.type_at(at);
val mark := this.begin_statement();
val made := this.value_as(this.c.checker.left_of(at), held);
val place := this.fresh_place(held);
this.store(&place, &made);
this.end_statement(mark);
this.declare(at, place, false);
continue;
}
this.c.scan_children(at, &mut walk);
}
}
#! Checks an `ensures` where its block is left, the name it gives what the
#! function returns standing for that. Where the way out returns nothing, as
#! where every way through the block returned before its end, it is never
#! reached.
#! @param this The emitter.
#! @param node The `contract` node.
pub def emitter::check_ensures(&mut this, node: u32): void {
return if this.build.ended();
val bound := this.c.checker.record(node, contract_slot::bound);
return if bound != 0 && !this.returning;
val locals := this.scope_mark();
if bound != 0 {
val place := this.new_place(bound, this.returned.kind);
this.store(&place, &this.returned);
this.declare(bound, place, false);
}
val mark := this.begin_statement();
this.check_contract(node);
this.end_statement(mark);
this.forget_locals(locals);
}
#! Lowers a contract's check: where its condition holds, the program goes on,
#! and where it does not, a block of its own, which nothing comes back from,
#! makes the report and stops the program with it, so a contract that holds
#! costs its condition and a branch.
#! @param this The emitter.
#! @param node The `contract` node.
def emitter::check_contract(&mut this, node: u32): void {
val saved := this.build.pos;
this.at_node(node);
val fine := this.build.new_block();
val failing := this.build.new_block();
this.branch_on(this.c.checker.left_of(node), fine, failing);
this.build.seal(failing);
this.build.switch_to(failing);
this.report_contract(node);
this.build.seal(fine);
this.build.switch_to(fine);
this.build.pos = saved;
}
#! Stops the program where a contract failed, saying which kind failed, what it
#! checked, as written or as its text says, and what the condition's operands
#! held, as `A pre-condition failed: b != 0, with b = 0.`
#! @param this The emitter.
#! @param node The `contract` node.
def emitter::report_contract(&mut this, node: u32): void {
val mark := this.begin_statement();
val condition := this.c.checker.left_of(node);
val text := this.c.checker.record(node, contract_slot::text);
val lead := match this.c.checker.clause_of(node) {
expects => "A pre-condition failed: ",
asserts => "An assertion failed: ",
ensures => "A post-condition failed: "
};
this.build.effect(op::format, span::<u32>::empty(), 0, 0);
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(lead), 0);
# Text written as a literal ends where the report's own full stop does.
if text != 0 && this.c.checker.kind_of(text) == nk::string {
var said := string::new(nothing {});
this.decode_literal(this.c.checker.text_of(text), &mut said);
if said.length != 0 && said[said.length - 1] == '.' {
said.resize(said.length - 1);
}
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(said.view()), 0);
} else if text != 0 {
val said := this.value(text);
this.format_sentence(&said);
} else {
var written := string::new(nothing {});
this.source_text(condition, &mut written);
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum(written.view()), 0);
}
this.write_values(condition, ", with ");
this.build.effect(op::format_text, span::<u32>::empty(), this.c.text_datum("."), 0);
# The program stops with the report, so nothing made here is closed.
var report := this.owned_text(this.c.checker.type_at(node));
this.adopt(&report);
val index := this.c.layout_of(this.c.checker.unalias(report.kind));
val data := this.c.field_at(index, 1);
val count := this.c.field_at(index, 2);
var words: u32[2] = [this.build.load(access::i64, report.address, data.offset), this.build.load(access::i64, report.address, count.offset)];
this.build.effect(op::fault, words[0:2], 0, 0);
this.build.unreachable();
this.drop_kept(mark.kept);
this.release(mark.cells);
}
#! Writes a view of text into the text being made without a full stop it ends
#! with, where the report's own ends it.
#! @param this The emitter.
#! @param text The view.
def emitter::format_sentence(&mut this, text: &operand): void {
var data := text.words[0];
var length := text.words[1];
if text.address != 0 {
data = this.build.load(access::i64, text.address, 0);
length = this.build.load(access::i64, text.address, word_size);
}
val held := this.build.variable(vt::word);
this.build.assign(held, length);
val looking := this.build.new_block();
val dropping := this.build.new_block();
val after := this.build.new_block();
this.build.branch(this.build.binary(op::ne, length, this.build.word(0)), looking, after);
this.build.seal(looking);
this.build.switch_to(looking);
val last := this.build.load(access::u8, this.build.binary(op::add, data, this.build.binary(op::sub, length, this.build.word(1))), 0);
this.build.branch(this.build.binary(op::eq, last, this.build.word('.' as u64)), dropping, after);
this.build.seal(dropping);
this.build.switch_to(dropping);
this.build.assign(held, this.build.binary(op::sub, length, this.build.word(1)));
this.build.jump(after);
this.build.seal(after);
this.build.switch_to(after);
var args: u32[2] = [data, this.build.read(held)];
this.build.effect(op::format_bytes, args[0:2], 0, 0);
}
#! Whether an expression ends the program: a call of `exit` or `abort`, which
#! the checker treats as leaving.
#! @param this The emitter.
#! @param node The expression.
#! @returns Whether it does.
def emitter::ends_program(&mut this, node: u32): bool {
return false if this.c.checker.kind_of(node) != nk::call;
val decl := this.c.checker.ref_at(node);
return false if decl == 0 || (decl & (ref_local | ref_type)) != 0;
return false if !this.c.checker.decls.has(decl, df::intrinsic);
val name := this.c.checker.names.text(this.c.checker.decls.names.p[decl]);
return name == "exit" || name == "abort" || name == "fault";
}
#! Lowers a local variable or constant. A constant known while compiling is no
#! local at all, being written wherever it is named.
#! @param this The emitter.
#! @param node The `variable` node.
def emitter::local_statement(&mut this, node: u32): void {
val value := this.c.checker.record(node, variable_slot::value);
val kind := this.c.checker.type_at(node);
if this.c.checker.node_has(node, nf::constant) && this.c.checker.is_known(node) {
return;
}
# A constant the checker did not work out is evaluated: read where it is
# once it is, while compiling, and where the program holds it as data after.
if this.c.checker.node_has(node, nf::constant) {
val key := node_key(this.table, node);
if this.c.options.evaluating {
val index := this.c.evaluation_of(key, 0, this.table, node, false);
this.build.effect(op::ready, span::<u32>::empty(), index, 0);
val offset: u64 = this.c.evaluations[index].offset;
val address := this.build.value(op::global, span::<u32>::empty(), vt::word, 0, offset);
this.declare(node, location { kind = kind, address = address }, false);
return;
}
val datum := this.c.evaluated_datum(key, kind);
if datum != no_block {
val address := this.build.value(op::datum, span::<u32>::empty(), vt::word, datum, 0);
this.declare(node, location { kind = kind, address = address }, false);
return;
}
}
# A function declared within a block is named in its own body, so its local
# is declared before its value is made.
if this.c.checker.node_has(node, nf::function) {
val place := this.new_place(node, kind);
this.declare(node, place, false);
val mark := this.begin_statement();
val made := this.value(value);
this.store(&place, &made);
this.end_statement(mark);
return;
}
val mark := this.begin_statement();
if value != 0 && this.refers_to_temporary(value) {
this.bound_temporary(node, value, kind, mark);
return;
}
# `undefined` leaves a cell as it is, and words, which cost nothing to give
# a value, are zero. Running with its memory checked, the cell is marked as
# never written, so reading it first stops the program.
if value != 0 && this.c.checker.kind_of(value) == nk::undefined {
val left := this.new_place(node, kind, ck::undefined);
if left.held {
this.zero(&left);
} else if this.c.options.checks {
this.build.forget(left.address, this.c.shape_of(kind).size);
}
this.end_statement(mark);
this.declare(node, left, false);
return;
}
val place := this.new_place(node, kind);
if value == 0 {
this.zero(&place);
this.defaults(&place);
} else {
val made := this.value_as(value, kind);
this.adopt(&made);
this.store(&place, &made);
}
this.end_statement(mark);
this.declare(node, place, this.c.checker.closes(kind));
}
#! Whether a value is a reference to a value that is no place, as
#! `&point { x = 1 }` or `&make()`, which the statement would hold.
#! @param this The emitter.
#! @param node The value's node.
#! @returns Whether it is.
def emitter::refers_to_temporary(&mut this, node: u32): bool {
return false if this.c.checker.kind_of(node) != nk::reference;
val inner := this.c.checker.left_of(node);
return false if this.c.checker.has_flag(node, rf::relent);
return !(this.c.checker.is_place(inner) && (!this.c.checker.is_known(inner) || this.stored(inner)));
}
#! Lowers a local whose value is a reference to a value that is no place, which
#! lives as long as the name does, as C++ has a temporary bound to a reference:
#! held in a cell of its own, as a local declared just before the name is, and
#! closed just after the name is.
#! @param this The emitter.
#! @param node The `variable` node.
#! @param value The `reference` node.
#! @param kind The local's type.
#! @param mark What the statement held before.
def emitter::bound_temporary(&mut this, node: u32, value: u32, kind: u32, mark: statement_mark): void {
val taken := this.c.checker.type_at(value);
val referent := this.c.checker.types.first_of(this.c.checker.unalias(taken));
val made := this.value_as(this.c.checker.left_of(value), referent);
this.adopt(&made);
val shape := this.c.shape_of(referent);
val cell := this.build.code.add_cell(round_up(shape.size == 0 ? word_size : shape.size, word_size) as u32,
shape.align < word_size ? word_size as u32 : shape.align as u32, ck::local, 0);
val held := location { kind = referent, address = this.build.cell_address(cell), framed = true };
this.store(&held, &made);
val referred := this.reference_to(&held, taken);
val converted := this.convert(&referred, kind);
val place := this.new_place(node, kind);
this.store(&place, &converted);
this.end_statement(mark);
this.declare(value, held, this.c.checker.closes(referent));
this.declare(node, place, this.c.checker.closes(kind));
}
#! Lowers `if`: the names its condition's tests give are declared before it runs,
#! and close where it ends, but those an `is not` test gives the rest of the
#! block where its branch always leaves.
#! @param this The emitter.
#! @param node The `if_stmt` node.
def emitter::if_statement(&mut this, node: u32): void {
val condition := this.c.checker.left_of(node);
val then := this.c.checker.record(node, if_slot::then);
val other := this.c.checker.record(node, if_slot::other);
val mark := this.begin_statement();
val locals := this.scope_mark();
this.declare_tests(condition);
val then_block := this.build.new_block();
val join := this.build.new_block();
val else_block := other != 0 ? this.build.new_block() : join;
this.branch_on(condition, then_block, else_block);
this.lower_branches(then, other, then_block, else_block, join);
# The names an `is not` test gives stay for the rest of the block, where the
# branch it guards always leaves.
val gives_rest := other == 0 && this.c.checker.has_flag(then, rf::leaves) && this.binds_where(condition, false);
if !gives_rest {
this.end_scope(locals, 0);
}
this.end_statement(mark);
}
#! Lowers `if const`: the branch the checker decided it takes, or where only the
#! program running decides it, as in a generic's instance whose condition the
#! checker left unknown, both, by the condition's value.
#! @param this The emitter.
#! @param node The `if_const` node.
def emitter::if_const(&mut this, node: u32): void {
val condition := this.c.checker.left_of(node);
val then := this.c.checker.record(node, if_slot::then);
val other := this.c.checker.record(node, if_slot::other);
if this.c.checker.is_known(condition) {
val taken := this.c.checker.value_at(condition).magnitude != 0 ? then : other;
this.lower_block(taken);
return;
}
# A condition evaluated decides the branch as one the checker decided does.
if this.c.evaluated.decisions.get(&node_key(this.table, node)) is some(holds) {
val taken := holds ? then : other;
this.lower_block(taken);
return;
}
val mark := this.begin_statement();
val then_block := this.build.new_block();
val join := this.build.new_block();
val else_block := other != 0 ? this.build.new_block() : join;
val cond := this.value_as(condition, bt::boolean);
this.build.branch(cond.words[0], then_block, else_block);
this.lower_branches(then, other, then_block, else_block, join);
this.end_statement(mark);
}
#! Lowers the branches of an `if` its condition branched to, each going on
#! where they join, and goes on there.
#! @param this The emitter.
#! @param then The block taken where the condition holds.
#! @param other The one taken where it does not, or 0.
#! @param then_block Where the first begins.
#! @param else_block Where the second begins, or `join`.
#! @param join Where they join.
def emitter::lower_branches(&mut this, then: u32, other: u32, then_block: u32, else_block: u32, join: u32): void {
this.build.seal(then_block);
if other != 0 {
this.build.seal(else_block);
}
this.build.switch_to(then_block);
this.lower_block(then);
this.build.jump(join);
if other != 0 {
this.build.switch_to(else_block);
this.lower_block(other);
this.build.jump(join);
}
this.build.seal(join);
this.build.switch_to(join);
}
#! Lowers `while`. Each pass, and each `continue`, closes what the condition
#! made, and the names its tests gave, before making them again.
#! @param this The emitter.
#! @param node The `while_stmt` node.
def emitter::while_statement(&mut this, node: u32): void {
val condition := this.c.checker.left_of(node);
val body := this.c.checker.right_of(node);
val head := this.build.new_block();
val exit := this.build.new_block();
val next := this.build.new_block();
this.build.jump(head);
this.build.switch_to(head);
val mark := this.begin_statement();
val locals := this.scope_mark();
this.declare_tests(condition);
val inside := this.build.new_block();
this.branch_on(condition, inside, exit);
this.build.seal(inside);
this.build.switch_to(inside);
this.safepoint();
this.loops.append(loop_info { exit = exit, next = next, locals = this.locals.length, kept = this.kept.length });
this.lower_block(body);
this.loops.truncate();
this.build.jump(next);
this.build.seal(next);
this.build.switch_to(next);
this.close_locals(locals, 0);
this.leave_kept(mark.kept);
# A `break` leaves with the names the test gave, which close here, and what the
# condition made closes where the statement ends.
this.close_loop(head, exit);
this.end_scope(locals, 0);
this.end_statement(mark);
}
#! Lowers `break` or `continue`: what the statements and scopes of the loop's
#! body hold is closed, and control goes to the loop's exit or its next pass.
#! @param this The emitter.
#! @param leaves Whether it is `break`.
def emitter::leave_loop(&mut this, leaves: bool): void {
return if this.loops.length == 0;
val held: loop_info = this.loops.last();
this.leave_kept(held.kept);
this.close_locals(held.locals, 0);
this.build.jump(leaves ? held.exit : held.next);
}
#! Lowers a condition as a branch: where it holds, to one block, and to another
#! where it does not. `&&` and `||` go to the second only where the first does
#! not decide.
#! @param this The emitter.
#! @param node The condition.
#! @param then Where it goes where the condition holds.
#! @param other Where it goes where it does not.
pub def emitter::branch_on(&mut this, node: u32, then: u32, other: u32): void {
if this.c.checker.is_known(node) {
this.build.jump(this.c.checker.value_at(node).magnitude != 0 ? then : other);
return;
}
if this.c.checker.kind_of(node) == nk::binary {
val operator := this.c.checker.token_kind(node);
if operator == tk::logand || operator == tk::logor {
val middle := this.build.new_block();
if operator == tk::logand {
this.branch_on(this.c.checker.left_of(node), middle, other);
} else {
this.branch_on(this.c.checker.left_of(node), then, middle);
}
this.build.seal(middle);
this.build.switch_to(middle);
this.branch_on(this.c.checker.right_of(node), then, other);
return;
}
}
if this.c.checker.kind_of(node) == nk::unary && this.c.checker.token_kind(node) == tk::negate {
this.branch_on(this.c.checker.left_of(node), other, then);
return;
}
val made := this.value_as(node, bt::boolean);
this.build.branch(made.words[0], then, other);
}
#! Declares the locals the tests of a condition name their values in, before
#! any of it runs, since `&&` and `||` may leave a test that would set one
#! unrun. One that closes starts zeroed, so closing it where it was never given
#! closes nothing.
#! @param this The emitter.
#! @param node The condition.
pub def emitter::declare_tests(&mut this, node: u32): void {
return if node == 0;
match this.c.checker.kind_of(node) {
nk::is_test => {
val binding := this.c.checker.named_binding(this.c.checker.record(node, is_slot::binding));
return if binding == 0;
val named := this.c.checker.kind_of(binding) == nk::reference ? this.c.checker.left_of(binding) : binding;
return if !this.c.checker.has_flag(named, rf::narrowed) || this.local_of(named) != 0;
val kind := this.c.checker.type_at(named);
val place := this.new_place(named, kind);
val closes := this.c.checker.closes(kind);
if closes {
this.zero(&place);
}
this.declare(named, place, closes);
}
nk::binary => {
val operator := this.c.checker.token_kind(node);
if operator == tk::logand || operator == tk::logor {
this.declare_tests(this.c.checker.left_of(node));
this.declare_tests(this.c.checker.right_of(node));
}
}
nk::unary => {
if this.c.checker.token_kind(node) == tk::negate {
this.declare_tests(this.c.checker.left_of(node));
}
}
else => {}
}
}
#! Whether a condition's tests name a value where it holds as `positive` says,
#! through `&&`, `||`, and `!`.
#! @param this The emitter.
#! @param node The condition.
#! @param positive Whether the condition holds where the value is named.
#! @returns Whether they do.
pub def emitter::binds_where(&mut this, node: u32, positive: bool): bool {
return false if node == 0;
match this.c.checker.kind_of(node) {
nk::is_test => {
return this.c.checker.named_binding(this.c.checker.record(node, is_slot::binding)) != 0
&& this.c.checker.node_has(node, nf::negated) != positive;
}
nk::binary => {
val operator := this.c.checker.token_kind(node);
return false if !((operator == tk::logand && positive) || (operator == tk::logor && !positive));
return this.binds_where(this.c.checker.left_of(node), positive)
|| this.binds_where(this.c.checker.right_of(node), positive);
}
nk::unary => {
return this.c.checker.token_kind(node) == tk::negate && this.binds_where(this.c.checker.left_of(node), !positive);
}
else => {}
}
return false;
}