Files
sakurac/analyzer/checker/statements.sakura
T
2026-11-19 04:54:17 -06:00

1569 lines
62 KiB
Plaintext

#! @file statements.sakura
#! @author John Christman (sorakatadzuma@gmail.com)
#! @copyright Malunal Studios, LLC.
#! @license MIT
#!
#! Contains the checking of statements: blocks and the locals declared in
#! them, branches, loops, matches, and leaving by `return`, `break`, and
#! `continue`. Each statement says whether the block never goes on past it,
#! which tells a function that can end without returning a value, and where
#! the names an `is not` test gives are named for the rest of the block.
module sakura::analyzer;
#! What checking a statement says of what follows it.
pub enum flow : u8 {
goes_on, #! The block goes on past it.
leaves, #! The block never goes on past it: it returns, breaks, or continues on every path.
skips, #! It leaves, as decided while checking, so what follows is never checked.
}
#! Checks a block, whose locals are of its scope.
#! @param this The checker.
#! @param node The `block` node.
#! @returns Whether the block never goes on past its end.
pub def checker::check_block(&mut this, node: u32): flow {
return flow::goes_on if node == 0;
if this.kind_of(node) != nk::block {
# Nothing follows a statement standing for a block.
val made := this.check_stmt(node);
this.rest_pending = false;
return made;
}
val mark := this.scope_mark();
val proved := this.proved_params.length;
val outer := this.at.block;
val opened := this.at.opened;
val run := this.left_of(node);
val scope := this.lifetime_open(node);
this.at.block = node;
this.at.opened = mark;
val how := this.check_stmts(run, 0, this.run_length(run));
this.lifetime_close(scope);
this.at.block = outer;
this.at.opened = opened;
this.unbind_to(mark);
this.unprove_to(proved);
if how != flow::goes_on {
this.set_flag(node, rf::leaves);
}
return how;
}
#! Checks a block's statements from one on.
#! @param this The checker.
#! @param run The block's run of statements.
#! @param from The first to check.
#! @param count How many the block has.
#! @returns How they end: `leaves` where one leaves, and `skips` where one
#! leaves as decided while checking, so the rest are not checked.
def checker::check_stmts(&mut this, run: u32, from: u32, count: u32): flow {
var how := flow::goes_on;
var at := from;
while at < count {
val made := this.check_stmt(this.run_at(run, at));
at++;
# What follows an `if const` whose branch leaves holds where its condition
# fails, and where that is in several cases, is checked once for each.
if this.rest_pending {
this.rest_pending = false;
val cases := this.rest_cases.copy();
this.rest_cases = checker::cases::none();
return at < count ? this.check_rest(run, at, count, &cases) : how;
}
return flow::skips if made == flow::skips;
if made == flow::leaves {
how = flow::leaves;
}
}
return how;
}
#! Checks the statements of a block following an `if const` whose branch leaves
#! once for each case its condition fails in, as after `if const A && B {
#! return; }`, where `A` fails, and where `B` does.
#! @param this The checker.
#! @param run The block's run of statements.
#! @param from The first following it.
#! @param count How many the block has.
#! @param cases The cases.
#! @returns How they end: leaving only where they do in each case.
def checker::check_rest(&mut this, run: u32, from: u32, count: u32, cases: &checker::cases): flow {
val low := this.lowest_node(this.run_at(run, from));
val high := this.run_at(run, count - 1);
this.repeating++;
var all_leave := true;
for c in 0..cases.ends.length {
var pass := this.begin_case_at(cases, c, low, high, true);
if this.check_stmts(run, from, count) == flow::goes_on {
all_leave = false;
}
this.end_case(&mut pass);
}
this.end_repeat();
return all_leave ? flow::leaves : flow::goes_on;
}
#! Forgets the bounds proved since the mark.
#! @param this The checker.
#! @param mark How many bounds were proved before, as `proved_params` held.
def checker::unprove_to(&mut this, mark: u64): void {
if this.exact_facts != 0 {
for i in mark..this.proved_params.length {
if this.exact_fact(i) {
this.exact_facts--;
}
}
}
if this.proved_params.length > mark {
this.proved_params.resize(mark);
this.proved_bounds.resize(mark);
}
}
#! Gives each type parameter an `if const` condition tests the bound it tests,
#! where an instance decides the condition as `positive` says, as `apply_case`
#! does where a generic's own body does not: the parameter is the type it was given,
#! which meets the bound, and names what the bound asks for through it, as
#! `F::result` within `if const F is signature`, where `F` is a function's type.
#! @param this The checker.
#! @param condition The condition's node.
#! @param positive Whether the condition holds where the bounds are given.
def checker::give_bounds(&mut this, condition: u32, positive: bool): void {
match this.kind_of(condition) {
nk::is_test => {
return if this.node_has(condition, nf::negated) == positive || this.node_has(condition, nf::computed);
this.give_is(this.left_of(condition), this.record(condition, is_slot::target));
}
nk::binary => {
# Both sides of `&&` hold, and of `||`, each the instance decided holds.
val operator := this.token_kind(condition);
if operator == tk::logand || operator == tk::logor {
val both := (operator == tk::logand) == positive;
val left := this.left_of(condition);
val right := this.right_of(condition);
if both || this.decided_as(left, positive) {
this.give_bounds(left, positive);
}
if both || this.decided_as(right, positive) {
this.give_bounds(right, positive);
}
}
}
nk::unary => {
if this.token_kind(condition) == tk::negate {
this.give_bounds(this.left_of(condition), !positive);
}
}
else => {}
}
}
#! Whether an instance decided a condition holds, or fails, as `positive` says.
#! @param this The checker.
#! @param condition The condition's node.
#! @param positive Whether it is asked to hold.
#! @returns Whether it was decided so.
def checker::decided_as(&this, condition: u32, positive: bool): bool {
return this.is_known(condition) && (this.value_at(condition).magnitude != 0) == positive;
}
#! Gives the type parameter a test names the bound it tests, where an instance
#! decided it holds, as `give_bounds` says.
#! @param this The checker.
#! @param value What is tested, as `T`.
#! @param target The trait or type it is tested against.
def checker::give_is(&mut this, value: u32, target: u32): void {
return if this.kind_of(value) != nk::name;
val param := this.param_named(this.name_of(value));
return if param == 0;
val bound := this.tested_bound(target);
return if bound == 0;
this.proved_params.append(param);
this.proved_bounds.append(bound);
}
#! Checks a statement.
#! @param this The checker.
#! @param node The statement.
#! @returns How it ends: whether what follows it runs.
pub def checker::check_stmt(&mut this, node: u32): flow {
match this.kind_of(node) {
nk::block => return this.check_block(node);
nk::variable => {
this.local(node);
this.lifetime_event(node, lifetime_kind_of_event::bound);
}
nk::if_stmt => {
val scope := this.lifetime_open(node);
val made := this.check_if(node);
this.lifetime_close(scope);
return made;
}
nk::if_const => return this.check_if_const(node);
nk::when_block => return this.check_block(this.when_branch(node));
nk::while_stmt => {
val scope := this.lifetime_open(node);
this.check_while(node);
this.lifetime_close(scope);
}
nk::for_stmt => {
val scope := this.lifetime_open(node);
this.check_for(node);
this.lifetime_close(scope);
}
nk::match_stmt => return this.check_match_stmt(node);
nk::return_stmt => {
this.check_return(node);
this.lifetime_event(node, lifetime_kind_of_event::returned);
return flow::leaves;
}
nk::break_stmt, nk::continue_stmt => {
if this.at.loops == 0 {
this.report(node, ec::control, "`break` and `continue` leave a loop, and this is in none.");
}
return flow::leaves;
}
nk::expr_stmt => {
val inner := this.left_of(node);
val kind := this.settle_expr(inner);
this.check_handled(inner, kind);
return this.ends_program(inner) ? flow::leaves : flow::goes_on;
}
nk::contract => this.check_contract(node);
nk::error => {}
else => {
this.settle_expr(node);
}
}
return flow::goes_on;
}
#! Reports a value let go of where it is made that is `@nodiscard`: given by a
#! function marked so, or of a type marked so. An assignment is the value it
#! handles, and `_ = x` lets go of a value on purpose.
#! @param this The checker.
#! @param node The expression of the statement.
#! @param kind Its type.
def checker::check_handled(&mut this, node: u32, kind: u32): void {
return if this.kind_of(node) == nk::assign || kind == bt::error;
val named := this.unalias(kind);
val typed := this.types.kind_of(named) == ty::named && this.decls.has(this.types.first_of(named), df::nodiscard);
var called := false;
if this.kind_of(node) == nk::call {
val decl := this.ref_at(node);
called = decl != 0 && (decl & (ref_local | ref_type)) == 0 && this.decls.has(decl, df::nodiscard);
}
return if !typed && !called;
var text := string::from("`", nothing {});
if typed {
val described := this.describe(kind);
text.append(described.span);
} else {
text.append(this.decl_text(this.ref_at(node)));
}
text.append("` is `@nodiscard`, so what is made here is handled; `_ = ...` lets go of it on purpose.");
this.report_text(node, ec::unhandled, &text);
}
#! Whether an expression is a call of `system::exit`, `system::abort`, or
#! `fault`, after which the program never goes on, or of `compile_error`,
#! after which nothing in its branch is checked.
#! @param this The checker.
#! @param node The expression.
#! @returns Whether it is.
def checker::ends_program(&mut this, node: u32): bool {
return false if this.kind_of(node) != nk::call;
val decl := this.ref_at(node);
return false if decl == 0 || (decl & (ref_local | ref_type)) != 0;
val name := this.names.text(this.decls.names.p[decl]);
return (name == "exit" || name == "abort" || name == "fault" || name == "compile_error") && this.decls.has(decl, df::intrinsic);
}
#! Which contract a `contract` node is, as its word says.
#! @param this The checker.
#! @param node The `contract` node.
#! @returns Which it is.
pub def checker::clause_of(&this, node: u32): clause {
val word := this.name_of(node);
return word == names::expects_id ? clause::expects
: word == names::asserts_id ? clause::asserts
: clause::ensures;
}
#! A contract: its condition is a `bool`, and what it says failed a `strview`.
#! An `ensures` in a function's own block may name what the function returns,
#! as `ensures(r: r > 0)`, which only its condition sees. Its own type is the
#! `string` its report is made as where it fails.
#! @param this The checker.
#! @param node The `contract` node.
def checker::check_contract(&mut this, node: u32): void {
val condition := this.left_of(node);
val bound := this.record(node, contract_slot::bound);
val text := this.record(node, contract_slot::text);
this.set_type(node, this.std_type(word::string, span::<u32>::blank()));
val mark := this.scope_mark();
if bound != 0 {
val result := this.at.result;
if result == bt::void_type {
this.report(bound, ec::invalid, "An `ensures` names what the function returns, and this one returns nothing.");
} else if this.at.block != this.at.body {
this.report(bound, ec::invalid,
"An `ensures` names what the function returns only in the function's own block, which every `return` leaves.");
}
this.declare_local(bound, this.name_of(bound), result);
}
this.check_condition(condition);
this.unbind_to(mark);
if text != 0 {
this.check_expr(text, this.std_type(word::strview, span::<u32>::blank()));
}
this.refuse_changes(condition);
}
#! Reports what a contract's condition changes, by `=`, `+=` and the like, or
#! `++` and `--`, since `--contracts off` leaves the condition out, which would
#! change what the program does. What an anonymous function within it does is
#! its own.
#! @param this The checker.
#! @param condition The condition.
def checker::refuse_changes(&mut this, condition: u32): void {
var todo := vector::<u32>::new();
todo.append(condition);
while todo.length != 0 {
val at: u32 = todo.last;
todo.truncate();
continue if at == 0;
val kind := this.kind_of(at);
continue if kind == nk::lambda;
val token := this.token_kind(at);
if kind == nk::assign || kind == nk::postfix || (kind == nk::unary && (token == tk::increment || token == tk::decrement)) {
this.report(at, ec::invalid,
"A contract's condition changes nothing, since `--contracts off` leaves it out, and the program would then do otherwise.");
}
this.syn().children(at, &mut todo);
}
}
#! `old(e)` within an `ensures`: what `e` was where the `ensures` was reached,
#! read through references, kept as a copy until the `ensures` is checked, so
#! it is of a type that closes nothing.
#! @param this The checker.
#! @param node The `old_value` node.
#! @returns Its type, or the error type where it is not valid.
pub def checker::old_value(&mut this, node: u32): u32 {
val inner := this.left_of(node);
val own := this.settle_expr(inner);
return bt::error if own == bt::error;
val held := this.read_type(own);
if held != own && !this.convert(inner, held) {
return bt::error;
}
if this.closes(held) {
var text := string::from("`old` keeps a copy of what it is given until the `ensures` is checked, so it takes what closes nothing, as a number or a view, and `", nothing {});
val described := this.describe(held);
text.append(described.span);
text.append("` closes.");
this.report_text(inner, ec::owned, &text);
return bt::error;
}
return held;
}
#! A local variable or constant, or a function declared within a block, which
#! is named before its body is checked so it can call itself.
#! @param this The checker.
#! @param node The `variable` or `function` node.
def checker::local(&mut this, node: u32): void {
val name := this.name_of(node);
this.check_redeclared(node, name);
val written := this.record(node, variable_slot::type_expr);
val value := this.record(node, variable_slot::value);
var kind: u32 = written != 0 ? this.value_type(written) : 0;
if written != 0 && this.node_has(node, nf::variadic) && kind != bt::error {
this.report(written, ec::not_type, checker::pack_held);
kind = bt::error;
}
if this.node_has(node, nf::function) && value != 0 && this.kind_of(value) == nk::lambda {
kind = this.lambda_signature(value);
this.declare_local(node, name, kind);
this.check_expr(value, kind);
return;
}
if value != 0 && this.kind_of(value) == nk::undefined {
this.undefined_local(node, value, kind);
} else if value != 0 {
# A pointer bound to a name is no reference, which would keep what `&` makes.
if this.kind_of(value) == nk::cast {
this.infer_expr(value);
if this.types.kind_of(this.unalias(this.type_at(value))) == ty::pointer {
this.refuse_lent_temporary(value);
}
}
if kind != 0 {
this.check_expr(value, kind);
this.check_owned(value, kind);
} else {
val own := this.infer_expr(value);
kind = this.settle(own);
# A binding takes the value it is given: what a reference reaches is copied
# unless `&` is written, as `val e := &v[i]`.
if this.takes_value(value, kind) {
kind = this.types.first_of(this.unalias(kind));
}
if this.types.kind_of(kind) == ty::null_type || this.types.kind_of(kind) == ty::empty {
this.report(value, ec::mismatch, "Nothing gives the variable a type: write one, as `val p: *u8 = null;`.");
kind = bt::error;
} else if this.types.kind_of(this.unalias(kind)) == ty::pack {
this.report(value, ec::not_type, checker::pack_held);
kind = bt::error;
} else if kind != own && kind != bt::error {
this.set_convert(value, kind);
}
this.check_owned(value, kind);
}
} else if kind != 0 && !this.has_zero(kind, 0) {
var text := string::from("`", nothing {});
val named := this.describe(kind);
text.append(named.span);
text.append(this.types.kind_of(this.unalias(kind)) == ty::param
? "` may be a reference, which has no zero value, so the variable is given a value where it is declared, or the parameter is bounded by `zeroable`."
: "` has no zero value, so the variable is given a value where it is declared.");
this.report_text(node, ec::zero_value, &text);
}
this.declare_local(node, name, kind == 0 ? bt::error : kind);
# A constant's value that folding does not give, as a table of numbers, is
# run while checking, once the local has its type, but for one reading a
# local around it that only the program running gives, not another constant.
if this.node_has(node, nf::constant) && value != 0 && !this.is_known(value) && this.type_at(value) != bt::error {
if this.runtime_local_read(value) != 0 {
this.report(value, ec::constant, "A constant's value is known while compiling.");
} else {
var answer := evaluation_answer {};
if this.ask_evaluator(evaluation_kind::local, node, &mut answer) && answer.scalar {
this.set_value(value, answer.value);
}
}
}
if this.node_has(node, nf::constant) && value != 0 && this.is_known(value) {
this.set_value(node, this.value_at(value));
}
if this.node_has(node, nf::mutable) {
this.set_flag(node, rf::mutable);
}
}
#! `undefined` as a local's value, which leaves its memory as it is until the
#! program writes it: only a `var` with a type written, of what has a zero value
#! and closes nothing, since closing it, or reading it as a reference or a
#! function, would read what the memory happened to hold.
#! @param this The checker.
#! @param node The `variable` node.
#! @param value The `undefined` node.
#! @param kind The type written, or 0.
def checker::undefined_local(&mut this, node: u32, value: u32, kind: u32): void {
if !this.node_has(node, nf::mutable) {
this.report(value, ec::invalid,
"`undefined` leaves a variable's memory as it is until the program writes it, so it is a `var`'s value, never a `val`'s or a constant's.");
return;
}
if kind == 0 {
this.report(value, ec::invalid, "`undefined` gives the variable no type: write one, as `var buffer: u8[64] = undefined;`.");
return;
}
return if kind == bt::error;
this.set_type(value, kind);
if !this.has_zero(kind, 0) || this.closes(kind) {
var text := string::from("`", nothing {});
val named := this.describe(kind);
text.append(named.span);
text.append(this.closes(kind)
? "` closes, which would close what the memory happened to hold, so the variable is given a value: `undefined` is for what closes nothing, as numbers, pointers, and arrays of them."
: "` has no zero value, so the variable is given a value where it is declared, rather than `undefined`.");
this.report_text(value, ec::invalid, &text);
}
}
#! Reports a local declared where its block already declares one of its name,
#! or names one where an `is not` test before it leaves. One within the block,
#! or of a parameter, may hide it.
#! @param this The checker.
#! @param node The local's node.
#! @param name The ID of its name.
def checker::check_redeclared(&mut this, node: u32, name: u32): void {
return if name == names::underscore_id || name as u64 >= this.innermost.length;
val at: u32 = this.innermost[name];
return if at < this.at.opened || (this.bind_values[at] & ref_local) == 0;
val first: u32 = this.bind_values[at] & ref_mask;
this.report_related(node, ec::duplicate, "The block already declares a local of this name: name this one apart, or assign the first.",
this.at.file, first, "Declared first here.");
}
#! Declares a local of the type at the node, binding its name.
#! @param this The checker.
#! @param node The node declaring it, which records its type and which its
#! name refers to.
#! @param name The ID of its name.
#! @param kind Its type.
pub def checker::declare_local(&mut this, node: u32, name: u32, kind: u32): void {
this.set_type(node, kind);
this.mark_local(node);
this.bind(name, ref_local | node);
}
#! The function type an anonymous function's written types give.
#! @param this The checker.
#! @param node The `lambda` node.
#! @returns The function type.
def checker::lambda_signature(&mut this, node: u32): u32 {
var kinds := vector::<u32>::new();
val params := this.left_of(node);
for &param in this.run_view(params) {
kinds.append(this.resolve_type(this.left_of(param)));
}
val result := this.record(node, lambda_slot::result);
return this.types.function(kinds.span, result == 0 ? bt::void_type : this.resolve_type(result), false);
}
#! `if`, with the names its condition's `is` tests give named where they hold:
#! those of `x is f(v)` in the branch it guards, and those of `x is not f(v)` in
#! the `else`, and for the rest of the block where the branch always leaves.
#! @param this The checker.
#! @param node The `if_stmt` node.
#! @returns How it ends: `leaves` where both branches do.
def checker::check_if(&mut this, node: u32): flow {
val condition := this.left_of(node);
val then := this.record(node, if_slot::then);
val other := this.record(node, if_slot::other);
# A test naming what a value of a type not chosen yet holds names it as each
# way the type can be chosen, so the statement is checked in each.
val unchosen := this.unchosen_binding(condition);
if unchosen != 0 {
val made := this.stmt_ways(node, unchosen);
# What the condition names where it fails is named after a first branch
# that leaves, as the first way says.
if this.has_flag(then, rf::leaves) {
this.bind_tests(condition, false);
}
return made;
}
this.check_condition(condition);
val mark := this.scope_mark();
this.bind_tests(condition, true);
val then_flow := this.check_block(then);
this.unbind_to(mark);
var other_flow := flow::goes_on;
if other != 0 {
this.bind_tests(condition, false);
other_flow = this.check_block(other);
this.unbind_to(mark);
}
if then_flow != flow::goes_on {
this.bind_tests(condition, false);
}
return flow::leaves if other != 0 && then_flow != flow::goes_on && other_flow != flow::goes_on;
return flow::goes_on;
}
#! `if const`, whose condition is known while checking where it can be: only
#! the branch it takes is checked, and where that branch always leaves and
#! there is no `else`, nothing after it is either.
#! @param this The checker.
#! @param node The `if_const` node.
#! @returns How it ends: `skips` where the branch it takes leaves and there is
#! no `else`, so nothing after it is checked.
def checker::check_if_const(&mut this, node: u32): flow {
val condition := this.left_of(node);
val then := this.record(node, if_slot::then);
val other := this.record(node, if_slot::other);
this.check_condition(condition);
# What is proved within a generic's own body may decide it, as `if const
# !T::mutable` is where `T::mutable` was said not to hold.
if !this.is_known(condition) && this.proved_params.length != 0 {
val decided := this.decided_condition(condition);
if decided >= 0 {
this.set_value(condition, constant::truth(decided == 1));
}
}
# Where folding does not decide it, the evaluator does, running it, unless it
# reads a local only the program running gives a value, so only the branch
# it takes is checked.
if !this.is_known(condition) && this.undecided == 0 && !this.waits_for_instance() {
val read := this.runtime_local_read(condition);
if read != 0 {
this.report_runtime_read(read);
} else {
var answer := evaluation_answer {};
if this.ask_evaluator(evaluation_kind::condition, node, &mut answer) {
this.set_value(condition, answer.value);
}
}
}
# Where nothing decides it, as of a type parameter in a generic's own body,
# each branch is checked with what its condition says of type parameters, once
# for each case it holds in, and reports no `compile_error`, which only a
# branch taken does: a generic's instances each decide it, as `for const` over
# its type's members is left to each instance. A branch naming a parameter as
# a type, as `T is strview` does, is checked in each instance taking it rather
# than here, where it is still a parameter.
if !this.is_known(condition) {
this.undecided++;
val then_cases := this.cases_of(condition, true);
val other_cases := this.cases_of(condition, false);
if then_cases.over || other_cases.over {
var text := string::from("The condition holds, or fails, in more than ", nothing {});
val most := $"{checker::max_cases} cases, each of which its branch is checked in.";
text.append(most.span);
this.report_text(condition, ec::limit, &text);
}
val then_flow := this.check_cases(then, &then_cases);
var other_flow := flow::goes_on;
if other != 0 {
other_flow = this.check_cases(other, &other_cases);
} else if then_flow != flow::goes_on && other_cases.ends.length == 1 {
# What follows a branch that leaves holds where the condition fails, and
# where that is several cases, the block checks it once for each.
this.apply_case(&other_cases, 0, true);
} else if then_flow != flow::goes_on && other_cases.ends.length > 1 {
this.rest_cases = other_cases.copy();
this.rest_pending = true;
}
this.undecided--;
return other != 0 && then_flow != flow::goes_on && other_flow != flow::goes_on ? flow::leaves : flow::goes_on;
}
# The branch taken gets the bounds its condition tests, and with no `else`,
# what follows a branch not taken gets those it fails, as `T is not shown`.
val mark := this.proved_params.length;
if this.value_at(condition).magnitude != 0 {
this.give_bounds(condition, true);
val taken := this.check_block(then);
this.unprove_to(mark);
return taken != flow::goes_on && other == 0 ? flow::skips : taken;
}
this.give_bounds(condition, false);
return flow::goes_on if other == 0;
val taken := this.check_block(other);
this.unprove_to(mark);
return taken;
}
#! The first name within an expression that reads a local declared outside it
#! whose value only the program running gives: not a constant, nor one known
#! while checking, nor the declaration `for const` walks.
#! @param this The checker.
#! @param node The expression.
#! @returns The `name` node, or 0.
def checker::runtime_local_read(&mut this, node: u32): u32 {
var todo := vector::<u32>::new();
var seen := vector::<u32>::new();
var lowest := node;
todo.append(node);
while todo.length != 0 {
val at: u32 = todo.last;
todo.truncate();
continue if at == 0;
lowest = at < lowest ? at : lowest;
seen.append(at);
this.syn().children(at, &mut todo);
}
var first: u32 = 0;
for &each in seen {
continue if this.kind_of(each) != nk::name;
val ref := this.ref_at(each);
continue if (ref & ref_local) == 0;
val local := ref & ref_mask;
continue if local >= lowest && local <= node;
continue if this.is_known(local) || this.reflected_at(local) != checker::no_reflection;
continue if this.kind_of(local) == nk::variable && this.node_has(local, nf::constant);
first = first == 0 || each < first ? each : first;
}
return first;
}
#! Reports a local whose value only the program running gives, read by what is
#! computed while compiling.
#! @param this The checker.
#! @param read The `name` node reading it.
def checker::report_runtime_read(&mut this, read: u32): void {
var text := string::from("`", nothing {});
text.append(this.names.text(this.name_of(read)));
text.append("` only exists once the program runs, so the value computed while compiling cannot use it.");
this.report_text(read, ec::constant, &text);
}
#! `while`, with the names its condition gives named in its body.
#! @param this The checker.
#! @param node The `while_stmt` node.
def checker::check_while(&mut this, node: u32): void {
val condition := this.left_of(node);
val unchosen := this.unchosen_binding(condition);
if unchosen != 0 {
this.stmt_ways(node, unchosen);
return;
}
this.check_condition(condition);
val mark := this.scope_mark();
this.bind_tests(condition, true);
this.at.loops++;
this.check_block(this.right_of(node));
this.at.loops--;
this.unbind_to(mark);
}
#! `for`, over a range of integers or of an enum's members, the elements of a
#! fixed array, or what an iterator gives, by copy or by reference.
#! @param this The checker.
#! @param node The `for_stmt` node.
def checker::check_for(&mut this, node: u32): void {
val index := this.record(node, for_slot::index);
val variable := this.record(node, for_slot::variable);
val iterated := this.record(node, for_slot::iterated);
val end := this.record(node, for_slot::end);
val reference := this.node_has(node, nf::reference);
val mutable := this.node_has(node, nf::mutable);
val mark := this.scope_mark();
var element: u32 = bt::error;
val unrolled := this.node_has(node, nf::constant);
if unrolled && end != 0 {
this.unroll_range(node, variable, iterated, end);
this.unbind_to(mark);
return;
}
if unrolled {
# A pack of types, as `for const U in Ts` or `in T::args`, is named in turn.
val of := this.kind_of(iterated);
val types := of == nk::name || of == nk::path ? this.tested_type(iterated) : 0;
if types != 0 && types != bt::error && this.types.kind_of(this.unalias(types)) == ty::pack {
this.unroll_type_pack(node, variable, this.unalias(types));
this.unbind_to(mark);
return;
}
val kind := this.infer_expr(iterated);
val plain := this.unalias(this.reached(kind));
if this.types.kind_of(plain) == ty::pack {
this.unroll_pack(node, variable, plain, this.kind_of(iterated) == nk::name || this.is_writable(iterated));
this.unbind_to(mark);
return;
}
val list := this.reflected_at(iterated);
if list != checker::no_reflection && this.reflected_kind(list) == rk::list as u32 {
this.unroll_reflection(node, variable, list, kind);
this.unbind_to(mark);
return;
}
# Reflection of a generic's type parameters waits for each instance.
if !this.waits_for_instance() {
this.unsupported(node);
}
this.undecided++;
} else if end != 0 {
# A range whose end is a value of a type not chosen yet counts as each way
# the type can be chosen, so the statement is checked in each.
val from := this.infer_expr(iterated);
val to := this.infer_expr(end);
val chosen := from != bt::error && this.uses_ways(from) ? from : (to != bt::error && this.uses_ways(to) ? to : 0u);
if chosen != 0 {
this.unbind_to(mark);
this.stmt_ways(node, chosen);
return;
}
element = this.range_type(iterated, end);
} else {
# What a value of a type not chosen yet gives is walked as each way the type
# can be chosen, so the statement is checked in each.
val walked := this.infer_expr(iterated);
if walked != bt::error && this.uses_ways(walked) {
this.unbind_to(mark);
this.stmt_ways(node, walked);
return;
}
element = this.element_type(iterated, mutable);
}
# `for x in` takes each element's value, copied out of where it is, which a
# pass only reads, and `for &x in` refers to it in place. An element given by
# value is the pass's own.
var copied := false;
if this.decide(variable != 0 ? variable : node, rf::valued, !reference && this.has_value(element)) {
element = this.types.first_of(this.unalias(element));
copied = true;
if variable != 0 && this.closes(element) {
var text := string::from("`", nothing {});
val named := this.describe(element);
text.append(named.span);
text.append("` is closed where its scope ends, so each element has one owner, which still holds it: refer to each with `for &x in`.");
this.report_text(variable, ec::owned, &text);
}
}
if index != 0 {
this.declare_local(index, this.name_of(index), bt::uint64);
}
if variable != 0 {
this.declare_local(variable, this.name_of(variable), element);
if !copied {
this.set_flag(variable, rf::mutable);
}
}
# The place the loop walks is watched while its body is checked, which warns
# where the body changes it whole, as that may move what the loop reads next.
val place := end == 0 ? this.walked_place(iterated) : 0;
if place != 0 {
this.walked.append((this.at.table as u64 << 32) | place as u64);
}
this.at.loops++;
this.check_block(this.right_of(node));
this.at.loops--;
if place != 0 {
this.walked.truncate();
}
if unrolled {
this.undecided--;
}
this.unbind_to(mark);
}
#! `for const x in args` over a pack: its body is checked once for each of the
#! pack's values, with `x` that value at its own type, each with a result table
#! of its own, so `if const x is Show` is decided for each. In a generic's own
#! body, where the pack's types are not known, the body is checked once, with
#! `x` of what the pack's bounds say of each. `x` is the value itself, so it is
#! written where the pack can be: a variadic parameter, or a field of a pack
#! that can be written.
#! @param this The checker.
#! @param node The `for_stmt` node.
#! @param variable The node of the loop's variable.
#! @param pack The pack's type.
#! @param writes Whether the pack can be written.
def checker::unroll_pack(&mut this, node: u32, variable: u32, pack: u32, writes: bool): void {
val body := this.right_of(node);
if this.types.is_open_pack(pack) {
this.declare_local(variable, this.name_of(variable), this.types.param(this.types.first_of(pack)));
if writes {
this.set_flag(variable, rf::mutable);
}
this.at.loops++;
this.check_block(body);
this.at.loops--;
return;
}
val outer := this.at.table;
for i in 0..this.types.part_count(pack) {
val table := this.add_child_table(variable, body - variable + 1);
this.use_table(table);
val mark := this.scope_mark();
this.declare_local(variable, this.name_of(variable), this.pack_value_type(pack, i as u32));
if writes {
this.set_flag(variable, rf::mutable);
}
this.at.loops++;
this.check_block(body);
this.at.loops--;
this.unbind_to(mark);
this.use_table(outer);
}
}
#! `for const U in Ts` over a pack of types, as `Ts` of `def f<Ts...>()` or
#! `T::args` of a `generic`: its body is checked once for each type, with `U`
#! naming it, each with a result table of its own, as for a pack of values. A
#! constant among them, as `4` of `buffer<i32, 4>`, is named as a constant
#! parameter is. In a generic's own body, where the pack's types are not known,
#! the body is checked once, with `U` standing for each, bounded as they are.
#! @param this The checker.
#! @param node The `for_stmt` node.
#! @param variable The node of the loop's variable.
#! @param pack The pack's type.
def checker::unroll_type_pack(&mut this, node: u32, variable: u32, pack: u32): void {
val body := this.right_of(node);
val name := this.name_of(variable);
if this.types.is_open_pack(pack) {
val mark := this.scope_mark();
val kind := this.types.param(this.types.first_of(pack));
this.bind(name, ref_type | kind);
this.set_ref(variable, ref_type | kind);
this.at.loops++;
this.check_block(body);
this.at.loops--;
this.unbind_to(mark);
return;
}
val outer := this.at.table;
for i in 0..this.types.part_count(pack) {
val table := this.add_child_table(variable, body - variable + 1);
this.use_table(table);
val mark := this.scope_mark();
val kind := this.types.part_at(pack, i as u32);
this.bind(name, ref_type | kind);
this.set_ref(variable, ref_type | kind);
this.at.loops++;
this.check_block(body);
this.at.loops--;
this.unbind_to(mark);
this.use_table(outer);
}
}
#! The most passes `for const` unrolls a range to.
pub const checker::max_unrolled: u64 = 1024;
#! `for const i in start..end` over a range whose ends are known while
#! checking: its body is checked once for each number, from the start to just
#! before the end, or through it for `start..=end`, or for each member of an
#! enum between them, with `i` a constant of the range's type, each with a
#! result table of its own, so `if const i == 0` is decided for each. Within a
#! generic's own body, where an end waits for each instance, the body is
#! checked once, with `i` a value of the type.
#! @param this The checker.
#! @param node The `for_stmt` node.
#! @param variable The node of the loop's variable.
#! @param start The node of the range's start.
#! @param end The node of its end.
def checker::unroll_range(&mut this, node: u32, variable: u32, start: u32, end: u32): void {
val body := this.right_of(node);
val kind := this.range_type(start, end);
val named := variable != 0 ? variable : node;
if this.node_has(node, nf::reference) || this.record(node, for_slot::index) != 0 {
this.report(named, ec::invalid, this.node_has(node, nf::reference)
? "A range gives numbers, not references to them."
: "A range has no index apart from its numbers.");
return;
}
return if kind == bt::error;
var answer := evaluation_answer {};
val first_known := this.known_end(start, &mut answer);
val last_known := first_known && this.known_end(end, &mut answer);
if !first_known || !last_known {
# Without an evaluator, or with an error that keeps the program from running,
# they are not known, which says nothing more.
if !this.waits_for_instance() && !answer.noted && !this.failed && this.evaluator is some(_) {
this.report(first_known ? end : start, ec::constant,
"`for const` counts through a range whose ends are known while checking: literals, constants, and what a function gives of them.");
}
this.undecided++;
if variable != 0 {
this.declare_local(variable, this.name_of(variable), kind);
}
this.at.loops++;
this.check_block(body);
this.at.loops--;
this.undecided--;
return;
}
# How many numbers the range counts, from its start, or which members.
val first := this.value_at(start);
val last := this.value_at(end);
val inclusive := this.node_has(node, nf::inclusive);
val enumerated := this.named_kind(this.unalias(kind)) == dk::enum_type;
var members := vector::<constant>::new();
var count: u64 = 0;
if enumerated {
members = this.members_between(kind, &first, &last, inclusive);
count = members.length;
} else if !first.negative && !last.negative {
count = last.magnitude > first.magnitude ? last.magnitude - first.magnitude : 0;
} else if first.negative && last.negative {
count = first.magnitude > last.magnitude ? first.magnitude - last.magnitude : 0;
} else if first.negative {
count = first.magnitude > checker::max_unrolled || last.magnitude > checker::max_unrolled
? checker::max_unrolled + 1
: first.magnitude + last.magnitude;
}
# `a..=b` counts `b` too, where it counts any.
if !enumerated && inclusive
&& (count != 0 || (first.negative == last.negative && first.magnitude == last.magnitude)) {
count++;
}
if count > checker::max_unrolled {
this.report(named, ec::limit, "`for const` unrolls a range of at most 1024 numbers.");
return;
}
val outer := this.at.table;
for k in 0..count {
var value := constant::integer(first.magnitude + k, false);
if enumerated {
value = members[k];
} else if first.negative {
value = k >= first.magnitude
? constant::integer(k - first.magnitude, false)
: constant::integer(first.magnitude - k, true);
}
val table := this.add_child_table(variable, body - variable + 1);
this.use_table(table);
val mark := this.scope_mark();
this.declare_local(variable, this.name_of(variable), kind);
this.set_value(variable, value);
this.at.loops++;
this.check_block(body);
this.at.loops--;
this.unbind_to(mark);
this.use_table(outer);
}
}
#! Whether an end of a range is known while checking, working it out by running
#! it where folding did not.
#! @param this The checker.
#! @param node The end's node.
#! @param answer What running it answered, where it was run.
#! @returns Whether it is known, with its value at the node.
def checker::known_end(&mut this, node: u32, answer: &mut evaluation_answer): bool {
return true if this.is_known(node);
return false if this.waits_for_instance() || this.type_at(node) == bt::error;
return this.run_value(node, answer);
}
#! The type a range counts in: the integer type or the enum its ends share.
#! @param this The checker.
#! @param start The node of the range's start.
#! @param end The node of its end.
#! @returns The type, or the error type where the ends share none.
def checker::range_type(&mut this, start: u32, end: u32): u32 {
val a := this.infer_expr(start);
val b := this.infer_expr(end);
return bt::error if a == bt::error || b == bt::error;
val shared := this.common(this.read_type(a), this.read_type(b));
if shared == bt::error || !this.counted(shared) {
this.report_operands(start, a, b, "are the ends of a range, which are integers of one type or members of one enum");
return bt::error;
}
val settled := this.settle(shared);
this.convert(start, settled);
this.convert(end, settled);
return settled;
}
#! Whether a range counts in a type: an integer type, an enum, whose members
#! it counts through in the order of their values, or a type parameter bounded
#! by `integer` or `ordinal`.
#! @param this The checker.
#! @param kind The type.
#! @returns Whether it does.
def checker::counted(&mut this, kind: u32): bool {
val plain := this.unalias(kind);
return true if this.types.is_integer(plain) || this.named_kind(plain) == dk::enum_type;
val integer := this.std_decl(word::integer);
val ordinal := this.std_decl(word::ordinal);
return (integer != 0 && this.param_bounded(plain, integer)) || (ordinal != 0 && this.param_bounded(plain, ordinal));
}
#! The values of the members of an enum a range counts through, in order: from
#! its start up to its end, or through it where the range is `a..=b`.
#! @param this The checker.
#! @param kind The enum's type.
#! @param first The start's value.
#! @param last The end's value.
#! @param inclusive Whether the end is counted too.
#! @returns The values.
pub def checker::members_between(&mut this, kind: u32, first: &constant, last: &constant, inclusive: bool): vector<constant> {
val flip := this.member_flip(kind);
val from := first.bits() ^ flip;
val to := last.bits() ^ flip;
val order := this.member_order(kind);
var made := vector::<constant>::new();
for each in order {
if each >= from && (each < to || (inclusive && each == to)) {
made.append(constant::from_bits(each ^ flip, flip != 0));
}
}
return made;
}
#! `a..b`, or `a..=b`, as a value: std's `range<T>` of the integers or the
#! members of the enum its ends are. A range expected gives its ends its type,
#! as `val r: range<u8> = 0..9;`.
#! @param this The checker.
#! @param node The `range` node.
#! @param expected The type expected, or the error type.
#! @returns The range's type, or the error type.
def checker::range_value(&mut this, node: u32, expected: u32): u32 {
val decl := this.std_decl(word::range);
val start := this.left_of(node);
val end := this.right_of(node);
if decl == 0 {
this.infer_expr(start);
this.infer_expr(end);
this.report(node, ec::undefined, "A range is std's `range<T>`, which is not declared here.");
return bt::error;
}
var element: u32 = bt::error;
val wanted := this.unalias(expected);
if expected != bt::error && this.types.kind_of(wanted) == ty::named && this.types.first_of(wanted) == decl
&& this.types.part_count(wanted) == 1 && this.counted(this.types.part_at(wanted, 0)) {
element = this.types.part_at(wanted, 0);
this.check_expr(start, element);
this.check_expr(end, element);
} else {
element = this.range_type(start, end);
}
return bt::error if element == bt::error;
val args: u32[1] = [element];
return this.types.named(decl, args[0:1]);
}
#! The type of each element a loop over the value gives. A loop variable takes
#! what it is given: a reference to each element an array holds or an iterator
#! gives by reference, writing it with `&mut`, and each one an iterator gives by
#! value, which is then the loop's own.
#! @param this The checker.
#! @param node The node of what the loop walks.
#! @param mutable Whether the loop writes its elements, as `for &mut x` does.
#! @returns The element's type, or the error type where the value cannot be
#! walked.
def checker::element_type(&mut this, node: u32, mutable: bool): u32 {
var kind := this.infer_expr(node);
return bt::error if kind == bt::error;
# A literal of text is walked as the `strview` it settles as.
if this.types.kind_of(kind) == ty::untyped_text {
kind = this.settle_expr(node);
}
# A type parameter known to have a shape is walked as it.
val through := this.shaped(this.reached(kind));
val plain := this.unalias(through);
if this.types.kind_of(plain) == ty::fixed {
val element := this.types.first_of(plain);
if mutable && !this.reaches_writable(kind, node) {
this.report(node, ec::assignable, "`for &mut` changes the elements in place, so the array must be writable.");
}
return this.types.reference(element, mutable);
}
# What lends an iterator is walked by it, and an iterator is walked itself.
var cursor := through;
if !this.has_method(through, word::next) {
val lends := this.pick_iter(through, mutable);
if lends == 0 {
var text := string::from("`", nothing {});
val named := this.describe(kind);
text.append(named.span);
text.append("` is not iterated: a type is by lending an iterator through `iter`, or being one.");
this.report_text(node, ec::member, &text);
return bt::error;
}
cursor = this.types.first_of(this.method_type(lends, through));
}
val next := this.find_member(cursor, word::next);
return bt::error if next.decl == 0;
val given := this.types.first_of(this.method_type(next.decl, cursor));
val plain_given := this.unalias(given);
if this.named_kind(plain_given) != dk::union_type || this.types.part_count(plain_given) == 0 {
return bt::error;
}
# `next` gives each element in a `maybe`, as a reference where it is one.
val each := this.types.part_at(plain_given, 0);
if this.types.kind_of(each) == ty::reference {
return mutable ? each : this.types.reference(this.types.first_of(each), false);
}
return each;
}
#! The `iter` of a type lending its iterator: the one taking `&mut this` for
#! `for &mut`, or the one taking `&this`, or 0.
#! @param this The checker.
#! @param kind The type walked.
#! @param mutable Whether the loop writes its elements.
#! @returns The method's declaration, or 0.
pub def checker::pick_iter(&mut this, kind: u32, mutable: bool): u32 {
val found := this.find_member(kind, word::iter);
return 0 if found.decl == 0 || this.decls.kinds.p[found.decl] != dk::function;
var reads: u32 = 0;
var walk := this.decls.walk_overloads(found.decl);
while true {
val at := walk.next();
break if at == 0;
continue if !this.member_seen(at);
if this.decls.has(at, df::mut_this) == mutable {
return at;
}
if !this.decls.has(at, df::mut_this) && reads == 0 {
reads = at;
}
}
return mutable ? 0 : reads;
}
#! `return`, whose value converts to the function's result.
#! @param this The checker.
#! @param node The `return_stmt` node.
def checker::check_return(&mut this, node: u32): void {
val value := this.left_of(node);
val result := this.at.result;
# `return;` gives `void`, which converts to what the function gives where a
# `result<void, E>` or `maybe<void>` holds it.
if value == 0 {
val none := constant {};
if result != bt::void_type && result != bt::error && this.fits(bt::void_type, result, &none, false, 0) == fit::none {
this.report(node, ec::mismatch, "The function returns a value, which `return` gives.");
}
return;
}
# What gives nothing may be returned from a function giving nothing, as generic
# code returning what a call gives writes it.
if result == bt::void_type {
val given := this.read_type(this.infer_expr(value));
if given != bt::void_type && given != bt::error {
this.report(value, ec::mismatch, "The function returns nothing, so `return` gives no value.");
}
return;
}
this.check_expr(value, result);
# Returning a local hands it to the caller rather than copying it, and so does
# returning what a pointer points at, which only the program closes. What a local
# reference refers to is still copied.
val local := this.kind_of(value) == nk::name && (this.ref_at(value) & ref_local) != 0
&& this.types.kind_of(this.type_at(value)) != ty::reference;
val handed := local || (this.is_place(value) && this.pointed_at(value));
if !handed {
this.check_owned(value, result);
}
}
#! `value else fallback`: what a `result` or a `maybe` holds, or else what
#! stands in for it, a value or a block that leaves.
#! @param this The checker.
#! @param node The `fallback` node.
#! @param expected The type expected of its value, or the error type where
#! none is.
#! @returns The type held, or the error type where the value is neither a
#! `result` nor a `maybe`.
def checker::fallback(&mut this, node: u32, expected: u32): u32 {
val value := this.left_of(node);
val error := this.record(node, fallback_slot::error);
val other := this.record(node, fallback_slot::other);
val kind := this.infer_expr(value);
if kind == bt::error {
if other != 0 && this.kind_of(other) != nk::block { this.infer_expr(other); }
return bt::error;
}
val plain := this.unalias(this.read_type(kind));
var held: u32 = bt::error;
var fault: u32 = 0;
if this.is_std(plain, word::maybe) {
held = this.types.part_at(plain, 0);
} else if this.is_std(plain, word::result) {
held = this.types.part_at(plain, 0);
fault = this.types.part_at(plain, 1);
} else {
this.report_operand(node, kind, "`else` takes what a `result` or a `maybe` holds.");
return bt::error;
}
# A value that closes has one owner. A variable keeps what it holds, so taking
# a copy out of it would close it twice, where a value a call made is handed
# over, and the result owns the error it holds.
if this.is_place(value) && this.closes(held) {
var text := string::from("`", nothing {});
val named := this.describe(held);
text.append(named.span);
text.append("` is closed where its scope ends, so the variable tested owns it; name it in place with `if x is not value(&v) { ... }` instead.");
this.report_text(value, ec::owned, &text);
}
if error != 0 && fault != 0 && this.name_of(error) != names::underscore_id && this.closes(fault) {
var text := string::from("`", nothing {});
val named := this.describe(fault);
text.append(named.span);
text.append("` is closed where its scope ends, so the result owns the error; leave it unnamed, with `else (_)`, or test the result with `is` or `match`.");
this.report_text(error, ec::owned, &text);
}
if this.kind_of(other) == nk::block {
val mark := this.scope_mark();
if error != 0 {
if fault == 0 {
this.report(error, ec::invalid, "A `maybe` holds no error, so `else` names none.");
}
this.declare_local(error, this.name_of(error), fault == 0 ? bt::error : fault);
}
# A block stands in for `void` by ending, since it gives nothing.
if this.check_block(other) == flow::goes_on && this.unalias(held) != bt::void_type {
this.report(other, ec::control, "The block standing in for the value leaves, by `return`, `break`, or `continue`.");
}
this.unbind_to(mark);
return held;
}
this.check_expr(other, held);
this.check_owned(other, held);
return held;
}
#! A `match` statement.
#! @param this The checker.
#! @param node The `match_stmt` node.
#! @returns How it ends: `leaves` where it handles every case and every arm
#! leaves.
def checker::check_match_stmt(&mut this, node: u32): flow {
return this.check_match_const(node) if this.token_kind(node) == tk::kw_const;
var made := checker::matched { shared = bt::error, every = true, all_leave = true };
this.check_match(node, false, bt::error, &mut made);
return made.every && made.all_leave ? flow::leaves : flow::goes_on;
}
#! A `match` used as a value, whose arms share a type, or take the type
#! expected.
#! @param this The checker.
#! @param node The `match_value` node.
#! @param expected The type expected of its value, or the error type where
#! none is.
#! @returns The type its arms share, or the error type.
def checker::match_value(&mut this, node: u32, expected: u32): u32 {
return this.match_const_value(node, expected) if this.token_kind(node) == tk::kw_const;
var made := checker::matched { shared = 0, every = true, all_leave = true };
this.check_match(node, true, expected, &mut made);
if !made.every {
this.report(node, ec::arms, "A match used as a value handles every case, or ends with `else`.");
}
return expected != bt::error ? expected : (made.shared == 0 ? bt::error : this.settle(made.shared));
}
#! What checking a match finds.
pub struct checker::matched {
var shared: u32; #! The type its arms' values share.
var every: bool; #! Whether it handles every case.
var all_leave: bool; #! Whether every arm leaves.
}
#! Checks a match: on a union, its arms name fields; on an enum, members; and
#! on anything else, values compared with the subject.
#! @param this The checker.
#! @param node The match's node.
#! @param value Whether it is used as a value, whose arms are expressions.
#! @param expected The type expected of its value, or the error type where
#! none is.
#! @param made Where what checking finds is written.
def checker::check_match(&mut this, node: u32, value: bool, expected: u32, made: &mut checker::matched): void {
val subject := this.left_of(node);
val arms := this.right_of(node);
val kind := this.infer_expr(subject);
# A value of a type not chosen yet is matched as each way it can be chosen.
if kind != bt::error && this.uses_ways(kind) {
this.match_ways(node, value, expected, made, kind);
return;
}
val plain := this.unalias(this.read_type(kind));
val union_like := this.named_kind(plain) == dk::union_type;
val enum_like := this.named_kind(plain) == dk::enum_type;
if union_like && this.decls.has(this.types.first_of(plain), df::foreign) {
this.report(subject, ec::invalid, c_union_untagged);
}
var handled := vector::<u32>::new();
var has_else := false;
for &arm in this.run_view(arms) {
val patterns := this.left_of(arm);
val body := this.right_of(arm);
val mark := this.scope_mark();
val scope := this.lifetime_open(arm);
if patterns == 0 {
has_else = true;
}
for &pattern in this.run_view(patterns) {
if kind == bt::error {
continue;
}
if union_like {
this.union_pattern(pattern, plain, subject, &mut handled);
} else if enum_like {
this.enum_pattern(pattern, plain, &mut handled);
} else {
this.check_expr(pattern, this.read_type(kind));
this.check_compared(pattern, tk::equals, this.read_type(kind));
}
}
if value {
if expected != bt::error {
this.check_expr(body, expected);
if !this.gives_binding(arm) {
this.check_owned(body, expected);
}
} else {
val given := this.infer_expr(body);
if made.shared == 0 {
made.shared = given;
} else if made.shared != bt::error && given != bt::error {
val joined := this.common(made.shared, given);
if joined == bt::error {
this.report_operands(body, made.shared, given, "are the values of arms of one match, which share no type");
}
made.shared = joined;
}
}
} else if this.check_block(body) == flow::goes_on {
made.all_leave = false;
}
this.lifetime_close(scope);
this.unbind_to(mark);
}
if value && expected == bt::error && made.shared != 0 && made.shared != bt::error {
for &arm in this.run_view(arms) {
this.convert(this.right_of(arm), this.settle(made.shared));
if !this.gives_binding(arm) {
this.check_owned(this.right_of(arm), this.settle(made.shared));
}
}
}
# A match on a union or an enum handles each case, or ends with `else`.
made.every = has_else || kind == bt::error;
if !has_else && (union_like || enum_like) {
val decl := this.types.first_of(plain);
val run: u32 = this.decls.children.p[decl];
var count := 0u;
for &member in this.decls.list_view(run) {
continue if union_like && this.decls.kinds.p[member] != dk::field;
# A member given an earlier one's value is another name for it.
continue if enum_like && this.enum_canonical(decl, member) != member;
count++;
}
var distinct := 0u;
for i in 0..handled.length {
var seen := false;
for j in 0..i {
seen = seen || handled[j] == handled[i];
}
if !seen { distinct++; }
}
made.every = distinct >= count;
if !made.every && !value {
this.report(node, ec::arms, "The match does not handle every case; handle each, or end with `else`.");
}
}
}
#! Whether an arm's value is the value its pattern names, as `some(v) => v`,
#! which the arm hands over as it ends rather than copying it.
#! @param this The checker.
#! @param arm The arm's node.
#! @returns Whether it is.
def checker::gives_binding(&this, arm: u32): bool {
val body := this.right_of(arm);
val patterns := this.left_of(arm);
return false if this.kind_of(body) != nk::name || (this.ref_at(body) & ref_local) == 0;
return false if patterns == 0 || this.run_length(patterns) != 1;
val pattern := this.run_at(patterns, 0);
return false if this.kind_of(pattern) != nk::call || this.run_length(this.right_of(pattern)) != 1;
return this.run_at(this.right_of(pattern), 0) == (this.ref_at(body) & ref_mask);
}
#! An arm's pattern on a union: the field it names, as `data` or `data(text)`.
#! @param this The checker.
#! @param pattern The pattern's node.
#! @param kind The union's type.
#! @param subject The node of the value matched.
#! @param handled The fields the arms handle so far, which the field is added
#! to.
def checker::union_pattern(&mut this, pattern: u32, kind: u32, subject: u32, handled: &mut vector<u32>): void {
var name_node := pattern;
var binding: u32 = 0;
if this.kind_of(pattern) == nk::call {
name_node = this.left_of(pattern);
val run := this.right_of(pattern);
if this.run_length(run) == 1 {
binding = this.run_at(run, 0);
}
}
val decl := this.types.first_of(kind);
val field := this.kind_of(name_node) == nk::name ? this.decls.member(decl, this.name_of(name_node)) : 0;
if field == 0 || this.decls.kinds.p[field] != dk::field {
this.report(pattern, ec::arms, "An arm on a union names one of its fields.");
return;
}
handled.append(field);
this.set_ref(pattern, field);
this.check_reaches(name_node, kind, field);
if binding != 0 {
this.resolve(field);
val held := this.instantiated(this.decls.types.p[field], decl, kind);
this.declare_binding(binding, held, subject);
val named := this.kind_of(binding) == nk::reference ? this.left_of(binding) : binding;
this.bind(this.name_of(named), ref_local | named);
}
}
#! An arm's pattern on an enum: a member, named with or without its enum.
#! @param this The checker.
#! @param pattern The pattern's node.
#! @param kind The enum's type.
#! @param handled The members the arms handle so far, which the member is
#! added to.
def checker::enum_pattern(&mut this, pattern: u32, kind: u32, handled: &mut vector<u32>): void {
val decl := this.types.first_of(kind);
if this.kind_of(pattern) == nk::name {
val member := this.decls.member(decl, this.name_of(pattern));
if member != 0 && this.decls.kinds.p[member] == dk::enum_member {
this.resolve(member);
handled.append(this.enum_canonical(decl, member));
this.set_ref(pattern, member);
this.set_type(pattern, kind);
return;
}
}
this.check_expr(pattern, kind);
val ref := this.ref_at(pattern);
if ref != 0 && (ref & (ref_local | ref_type)) == 0 && this.decls.kinds.p[ref] == dk::enum_member {
handled.append(this.enum_canonical(decl, ref));
}
}
#! The first member of an enum of the same value as the member, which a member
#! given an earlier one's value is another name for.
#! @param this The checker.
#! @param decl The enum's declaration.
#! @param member The member's declaration.
#! @returns The first member of its value.
def checker::enum_canonical(&mut this, decl: u32, member: u32): u32 {
var value := constant {};
return member if !this.decl_value(member, &mut value);
val run: u32 = this.decls.children.p[decl];
for &each in this.decls.list_view(run) {
var other := constant {};
if this.decl_value(each, &mut other) && this.compare_constants(&value, &other) == 0 {
return each;
}
}
return member;
}