#! @file evaluator.sakura #! @author John Christman (sorakatadzuma@gmail.com) #! @copyright Malunal Studios, LLC. #! @license MIT #! #! Contains the evaluator, which runs code while checking where a value must be #! known and folding its operators does not give it: a constant's value that #! calls a function, or the length of a fixed array. It runs over the checked #! results of what it runs, so it needs nothing of its own made first, and #! what goes wrong, as an index past the end or a run that never ends, is #! reported at what asked for the value. #! #! It runs integers, floats, and `bool`, and fixed arrays of them, through #! locals, assignments, branches, loops, and calls of functions that are not #! generic. What it does not run leaves the value unknown, as before. import std::containers; module sakura::analyzer; #! A value the evaluator holds: a constant, or a fixed array whose elements #! are `count` constants from `start` of the heap. pub struct ev { var array: bool; #! Whether it is an array, rather than a constant. var scalar: constant; #! The constant, where it is one. var start: u32; #! Where the array's elements begin on the heap. var count: u32; #! How many elements the array holds. } #! How evaluating a statement ended. pub enum eflow : u8 { goes_on, #! It went on to its end. returns, #! It returned, with the value in `ev_result`. breaks, #! It broke out of a loop. continues, #! It went on to a loop's next turn. fails, #! It went wrong, which was reported, or it ran into what the evaluator does not run. } #! The most steps an evaluation takes, past which it is reported as never #! ending. pub const checker::max_steps: u64 = 10000000; #! How deeply evaluated calls nest. pub const checker::max_calls: u32 = 200; #! Works out the value of the expression, which checking did not, by running #! it, reporting at `site` what goes wrong. #! @param this The checker. #! @param node The expression. #! @param site The node that asked for the value, which a failure is reported #! at. #! @param out Where the value is written. #! @returns Whether it was worked out, with the value in `out`. pub def checker::evaluate(&mut this, node: u32, site: u32, out: &mut ev): bool { this.ev_steps = 0; this.ev_depth = 0; this.ev_site = site; this.ev_file = this.at.file; this.ev_failed = false; this.ev_frames.append(dict::::new()); val held := this.ev_expr(node, out); this.ev_frames.truncate(); return held && !this.ev_failed; } #! Reports what went wrong while evaluating, at what asked for the value. #! @param this The checker. #! @param detail What went wrong, finishing the note's sentence. def checker::ev_fault(&mut this, detail: strview): void { return if this.ev_failed; this.ev_failed = true; var text := string::from("The value could not be worked out while compiling: ", nothing {}); text.append(detail); this.report_in(this.ev_file, this.ev_site, ec::constant, text.view()); } #! Takes one step, reporting a run that never ends. #! @param this The checker. #! @returns Whether evaluation may go on, which it may not past `max_steps`. def checker::ev_step(&mut this): bool { this.ev_steps++; if this.ev_steps > checker::max_steps { this.ev_fault("it runs for too long, as one that never ends does."); return false; } return true; } def checker::ev_scalar(&this, value: constant): ev { return ev { scalar = value }; } #! The local of the frame being run at the node, or false. #! @param this The checker. #! @param node The node declaring the local. #! @param out Where its value is written. #! @returns Whether the frame holds it. def checker::ev_local(&mut this, node: u32, out: &mut ev): bool { val top := this.ev_frames.length - 1; return false if !this.ev_frames[top].contains(&node); val held: ev = this.ev_frames[top][node]; out = held; return true; } def checker::ev_set_local(&mut this, node: u32, value: ev): void { val top := this.ev_frames.length - 1; this.ev_frames[top].set(node, value); } #! A copy of an array, with elements of its own, so assigning one copies it. #! @param this The checker. #! @param value The value, which is given back as it is where it is no array. #! @returns The copy. def checker::ev_copy(&mut this, value: ev): ev { return value if !value.array; val start := this.ev_heap.length as u32; for i in 0..value.count { val element: constant = this.ev_heap[value.start as u64 + i as u64]; this.ev_heap.append(element); } return ev { array = true, start = start, count = value.count }; } #! The constant made to fit an integer type of its bits, wrapping as the #! program running wraps. #! @param this The checker. #! @param value The constant. #! @param kind The integer type. #! @returns The constant wrapped to its bits. def checker::ev_wrap(&mut this, value: constant, kind: u32): constant { val plain := this.unalias(kind); val tkd := this.types.kind_of(plain); return value if value.floating || (tkd != ty::signed && tkd != ty::unsigned); val bits := this.types.first_of(plain); var raw := value.bits(); if bits < 64 { raw &= (1u << bits as u64) - 1; if tkd == ty::signed && (raw >> (bits - 1) as u64) != 0 { raw |= ~((1u << bits as u64) - 1); } } return constant::from_bits(raw, tkd == ty::signed); } #! Evaluates an expression. #! @param this The checker. #! @param node The expression. #! @param out Where its value is written. #! @returns Whether it was evaluated. def checker::ev_expr(&mut this, node: u32, out: &mut ev): bool { return false if !this.ev_step() || node == 0; if this.is_known(node) { out = this.ev_scalar(this.value_at(node)); return true; } match this.kind_of(node) { nk::name => { val ref := this.ref_at(node); if (ref & ref_local) != 0 { var held := ev {}; if !this.ev_local(ref & ref_mask, &mut held) { return false; } out = held; return true; } return this.ev_global(ref, out); } nk::path => return this.ev_global(this.ref_at(node), out); nk::unary => { var operand := ev {}; return false if !this.ev_expr(this.left_of(node), &mut operand) || operand.array; val value := operand.scalar; match this.token_kind(node) { tk::minus => out = this.ev_scalar(value.floating ? constant::real_of(-value.real) : constant::integer(value.magnitude, !value.negative)); tk::negate => out = this.ev_scalar(constant::truth(value.magnitude == 0)); tk::bitnot => out = this.ev_scalar(constant::from_bits(~value.bits(), this.types.is_signed(this.type_at(node)))); else => return false; } out.scalar = this.ev_wrap(out.scalar, this.type_at(node)); return true; } nk::binary => { val operator := this.token_kind(node); var left := ev {}; return false if !this.ev_expr(this.left_of(node), &mut left) || left.array; if operator == tk::logand || operator == tk::logor { val holds := left.scalar.magnitude != 0; if (operator == tk::logand && !holds) || (operator == tk::logor && holds) { out = this.ev_scalar(constant::truth(holds)); return true; } } var right := ev {}; return false if !this.ev_expr(this.right_of(node), &mut right) || right.array; var made := constant {}; if !this.fold_binary(operator, &left.scalar, &right.scalar, this.types.is_signed(this.type_at(this.left_of(node))), &mut made) { this.ev_fault("an operator overflows 64 bits, or divides by zero."); return false; } out = this.ev_scalar(this.ev_wrap(made, this.type_at(node))); return true; } nk::ternary => { var condition := ev {}; return false if !this.ev_expr(this.left_of(node), &mut condition); return this.ev_expr(this.record(node, condition.scalar.magnitude != 0 ? if_slot::then : if_slot::other), out); } nk::cast => { var value := ev {}; return false if !this.ev_expr(this.left_of(node), &mut value) || value.array; val target := this.unalias(this.type_at(node)); var held := value.scalar; if this.types.is_float(target) && !held.floating { held = constant::real_of(held.as_real()); } else if this.types.is_integer(target) && held.floating { held = constant::integer((held.real < 0.0 ? -held.real : held.real) as u64, held.real < 0.0); } out = this.ev_scalar(this.ev_wrap(held, target)); return true; } nk::array => { val run := this.left_of(node); var items := vector::::new(); for &each in this.run_view(run) { var element := ev {}; return false if !this.ev_expr(each, &mut element) || element.array; items.append(element.scalar); } this.ev_heap.extend(items.view()); out = ev { array = true, start = this.ev_heap.length as u32 - items.length as u32, count = items.length as u32 }; return true; } nk::index => { var object := ev {}; var at := ev {}; return false if !this.ev_expr(this.left_of(node), &mut object) || !object.array; return false if !this.ev_expr(this.right_of(node), &mut at) || at.array; if at.scalar.negative || at.scalar.magnitude >= object.count as u64 { this.ev_fault("an index is past the end of the array."); return false; } out = this.ev_scalar(this.ev_heap[object.start as u64 + at.scalar.magnitude]); return true; } nk::member => { var object := ev {}; return false if !this.ev_expr(this.left_of(node), &mut object); if object.array && this.name_of(node) == word::length { out = this.ev_scalar(constant::integer(object.count as u64, false)); return true; } return false; } nk::assign => return this.ev_assign(node, out); nk::postfix => return this.ev_step_place(node, this.left_of(node), true, out); nk::call => return this.ev_call(node, out); else => return false; } return false; } #! The value of a global constant or an enum member, evaluated where checking #! did not give it. #! @param this The checker. #! @param ref The declaration. #! @param out Where its value is written. #! @returns Whether it was evaluated. def checker::ev_global(&mut this, ref: u32, out: &mut ev): bool { return false if ref == 0 || (ref & (ref_local | ref_type)) != 0; var value := constant {}; if this.decl_value(ref, &mut value) { out = this.ev_scalar(value); return true; } if this.ev_arrays.get(&ref) is some(got) { out = got; return true; } return false; } #! `x = y`, `x op= y`, and the place each writes: a local, or an element of an #! array a local holds. #! @param this The checker. #! @param node The `assign` node. #! @param out Where the value assigned is written. #! @returns Whether it was evaluated. def checker::ev_assign(&mut this, node: u32, out: &mut ev): bool { val target := this.left_of(node); val value := this.right_of(node); var given := ev {}; return false if !this.ev_expr(value, &mut given); val operator := this.token_kind(node); if operator != tk::assign { var current := ev {}; return false if !this.ev_expr(target, &mut current) || current.array || given.array; var made := constant {}; if !this.fold_binary(operator.applied(), ¤t.scalar, &given.scalar, this.types.is_signed(this.type_at(target)), &mut made) { this.ev_fault("an operator overflows 64 bits, or divides by zero."); return false; } given = this.ev_scalar(this.ev_wrap(made, this.type_at(target))); } else { given = this.ev_copy(given); if !given.array { given.scalar = this.ev_wrap(given.scalar, this.type_at(target)); } } return false if !this.ev_write(target, given); out = given; return true; } #! Writes the value to a place: a local, or an element of an array a local #! holds. #! @param this The checker. #! @param target The node of the place. #! @param value The value to write. #! @returns Whether it was written. def checker::ev_write(&mut this, target: u32, value: ev): bool { match this.kind_of(target) { nk::name => { val ref := this.ref_at(target); return false if (ref & ref_local) == 0; this.ev_set_local(ref & ref_mask, value); return true; } nk::index => { var object := ev {}; var at := ev {}; return false if !this.ev_expr(this.left_of(target), &mut object) || !object.array || value.array; return false if !this.ev_expr(this.right_of(target), &mut at); if at.scalar.negative || at.scalar.magnitude >= object.count as u64 { this.ev_fault("an index is past the end of the array."); return false; } this.ev_heap[object.start as u64 + at.scalar.magnitude] = value.scalar; return true; } else => return false; } return false; } #! `x++` and `x--`, which give the value from before. #! @param this The checker. #! @param node The operator's node. #! @param target The node of the number changed. #! @param after Whether the operator follows its operand, as `x++`, giving #! the value from before. #! @param out Where the value it gives is written. #! @returns Whether it was evaluated. def checker::ev_step_place(&mut this, node: u32, target: u32, after: bool, out: &mut ev): bool { var current := ev {}; return false if !this.ev_expr(target, &mut current) || current.array; val one := constant::integer(1, false); var made := constant {}; val operator := this.token_kind(node) == tk::increment ? tk::plus : tk::minus; return false if !this.fold_binary(operator, ¤t.scalar, &one, true, &mut made); return false if !this.ev_write(target, this.ev_scalar(this.ev_wrap(made, this.type_at(target)))); out = current; return true; } #! A call of a function that is not generic, with its arguments evaluated, run #! over its checked body in a frame of its own. #! @param this The checker. #! @param node The `call` node. #! @param out Where what it gives is written. #! @returns Whether it was evaluated. def checker::ev_call(&mut this, node: u32, out: &mut ev): bool { val decl := this.ref_at(node); return false if decl == 0 || (decl & (ref_local | ref_type)) != 0; return false if this.decls.kinds.p[decl] != dk::function || this.decls.has(decl, df::generic); return false if this.decls.has(decl, df::intrinsic) || this.decls.has(decl, df::foreign) || this.decls.has(decl, df::method); if this.ev_depth >= checker::max_calls { this.ev_fault("its calls nest too deeply, as one calling itself without end does."); return false; } var args := vector::::new(); val run := this.right_of(node); for &arg in this.run_view(run) { var value := ev {}; return false if !this.ev_expr(arg, &mut value); args.append(this.ev_copy(value)); } # The function's body is checked first, so its results are there to run. this.check_decl(decl); val saved := this.at; this.use_table(this.units[this.decls.files.p[decl]].table); val fnode: u32 = this.decls.nodes.p[decl]; val params := this.record(fnode, function_slot::params); val body := this.record(fnode, function_slot::body); if body == 0 || this.run_length(params) != args.length as u32 { this.at = saved; return false; } var frame := dict::::new(); for i in 0..args.length { frame.set(this.run_at(params, i as u32), args[i]); } this.ev_frames.append(move(&mut frame)); this.ev_depth++; this.ev_result = ev {}; val how := this.ev_block(body); this.ev_depth--; this.ev_frames.truncate(); this.at = saved; return false if how == eflow::fails; out = this.ev_result; return true; } #! Runs a block or a statement. #! @param this The checker. #! @param node The block or statement. #! @returns How it ended. def checker::ev_block(&mut this, node: u32): eflow { return eflow::goes_on if node == 0; if this.kind_of(node) != nk::block { return this.ev_stmt(node); } val run := this.left_of(node); for &stmt in this.run_view(run) { val how := this.ev_stmt(stmt); return how if how != eflow::goes_on; } return eflow::goes_on; } #! Runs a statement. #! @param this The checker. #! @param node The statement. #! @returns How it ended. def checker::ev_stmt(&mut this, node: u32): eflow { return eflow::fails if !this.ev_step(); match this.kind_of(node) { nk::block => return this.ev_block(node); nk::variable => { val value := this.record(node, variable_slot::value); var held := ev {}; # `undefined` memory holds what it may, which zeroes are. if value != 0 && this.kind_of(value) != nk::undefined { return eflow::fails if !this.ev_expr(value, &mut held); held = this.ev_copy(held); if !held.array { held.scalar = this.ev_wrap(held.scalar, this.type_at(node)); } } else { held = this.ev_zero(this.type_at(node)); } this.ev_set_local(node, held); return eflow::goes_on; } nk::expr_stmt => { var ignored := ev {}; return this.ev_expr(this.left_of(node), &mut ignored) ? eflow::goes_on : eflow::fails; } nk::if_stmt, nk::if_const => { var condition := ev {}; return eflow::fails if !this.ev_expr(this.left_of(node), &mut condition); return this.ev_block(this.record(node, condition.scalar.magnitude != 0 ? if_slot::then : if_slot::other)); } nk::while_stmt => { while true { var condition := ev {}; return eflow::fails if !this.ev_expr(this.left_of(node), &mut condition); break if condition.scalar.magnitude == 0; val how := this.ev_block(this.right_of(node)); return how if how == eflow::returns || how == eflow::fails; break if how == eflow::breaks; } return eflow::goes_on; } nk::for_stmt => return this.ev_for(node); nk::return_stmt => { val value := this.left_of(node); this.ev_result = ev {}; if value != 0 { var held := ev {}; return eflow::fails if !this.ev_expr(value, &mut held); this.ev_result = this.ev_copy(held); } return eflow::returns; } nk::break_stmt => return eflow::breaks; nk::continue_stmt => return eflow::continues; # A contract that fails, and an `ensures`, are left to the machine, which # says what failed. nk::contract => { return eflow::goes_on if this.contracts_off; return eflow::fails if this.clause_of(node) == clause::ensures; var condition := ev {}; return eflow::fails if !this.ev_expr(this.left_of(node), &mut condition); return condition.scalar.magnitude != 0 ? eflow::goes_on : eflow::fails; } else => return eflow::fails; } return eflow::fails; } #! `for i in a..b` or `a..=b`, over integers or the members of an enum, and #! `for x in a` over an array, by copy. #! @param this The checker. #! @param node The `for_stmt` node. #! @returns How it ended. def checker::ev_for(&mut this, node: u32): eflow { 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 index := this.record(node, for_slot::index); return eflow::fails if this.node_has(node, nf::reference) || this.node_has(node, nf::constant); var first := ev {}; return eflow::fails if !this.ev_expr(iterated, &mut first); var count: u64 = 0; var from := constant {}; var members := vector::::new(); var enumerated := false; if end != 0 { var last := ev {}; return eflow::fails if !this.ev_expr(end, &mut last) || first.array || last.array; from = first.scalar; val inclusive := this.node_has(node, nf::inclusive); val kind := this.unalias(this.type_at(variable != 0 ? variable : iterated)); enumerated = this.named_kind(kind) == dk::enum_type; val order := this.compare_constants(&first.scalar, &last.scalar); if enumerated { members = this.members_between(kind, &first.scalar, &last.scalar, inclusive); count = members.length; } else if order < 0 { var span := constant {}; this.fold_binary(tk::minus, &last.scalar, &first.scalar, true, &mut span); count = span.magnitude; } # `a..=b` gives `b` too, where it gives any, the count held at the most a # word holds, which the evaluator's steps stop long before. if !enumerated && inclusive && order <= 0 { count = count == 0xFFFFFFFFFFFFFFFFu ? count : count + 1; } } else { return eflow::fails if !first.array; count = first.count as u64; } for i in 0..count { if enumerated { this.ev_set_local(variable, this.ev_scalar(members[i])); } else if end != 0 { var at := constant {}; val step := constant::integer(i, false); this.fold_binary(tk::plus, &from, &step, true, &mut at); this.ev_set_local(variable, this.ev_scalar(at)); } else { this.ev_set_local(variable, this.ev_scalar(this.ev_heap[first.start as u64 + i])); } if index != 0 { this.ev_set_local(index, this.ev_scalar(constant::integer(i, false))); } val how := this.ev_block(this.right_of(node)); return how if how == eflow::returns || how == eflow::fails; break if how == eflow::breaks; } return eflow::goes_on; } #! The zero value of a type the evaluator holds. #! @param this The checker. #! @param kind The type. #! @returns Its zero value. def checker::ev_zero(&mut this, kind: u32): ev { val plain := this.unalias(kind); if this.types.kind_of(plain) == ty::fixed { val start := this.ev_heap.length as u32; val count := this.types.second_of(plain); val element := this.types.is_float(this.unalias(this.types.first_of(plain))); for _ in 0..count { this.ev_heap.append(element ? constant::real_of(0.0) : constant {}); } return ev { array = true, start = start, count = count }; } return this.ev_scalar(this.types.is_float(plain) ? constant::real_of(0.0) : constant {}); }