module scheme // The ordinary loop can consume two pure operand loads with their // primitive call. Original bytecode stays intact; guarded or rejected operands // execute normally, preserving their individual errors and source locations. @[direct_array_access] fn (mut m Machine) fuse_primitive_operands(vm &VM, callable Value) bool { // Near a step limit, execute the original sequence so a denied operand or // application keeps its exact position and its ordering with other errors. if vm.options.max_steps > 0 && vm.options.max_steps - m.steps < 4 { return false } p := callable.procedure_pointer() if p.mode != .primitive || !isnil(p.env) || voidptr(p.owner) != voidptr(vm.owner) || (int(p.primitive) > int(Primitive.greater_equal) && p.primitive !in [.quotient, .remainder, .modulo, .vector_ref]) { return false } if m.ip + 2 >= m.function.instructions.len { return false } call := m.function.instructions[m.ip + 2] if call.op !in [.call, .tail_call] || call.a != 2 { return false } mut operands := [2]Value{} for i in 0 .. 2 { ins := m.function.instructions[m.ip + i] operands[i] = match ins.op { .constant { m.function.constants[int(ins.a)] } .local { m.env.ancestor(int(ins.a)).slots[int(ins.b)] } .global { slot := m.function.global_slots[int(ins.a)] if slot < 0 { return false } vm.globals[slot] } else { return false } } if operands[i].tag == .uninitialized { return false } } x, y := operands[0], operands[1] mut value := Value{} if x.tag == .integer && y.tag == .integer { if int(p.primitive) <= int(Primitive.greater_equal) { value = small_integer_call(p.primitive, x.whole(), y.whole()) if value.tag == .unspecified { return false } } else if p.primitive in [.quotient, .remainder, .modulo] { xv, yv := x.whole(), y.whole() if yv == 0 || (p.primitive == .quotient && xv == exact_min && yv == -1) { return false } value = small_integer_division(p.primitive, xv, yv, false, xv < 0, yv < 0) or { return false } } else { return false } } else if p.primitive == .vector_ref && x.tag == .vector && y.tag == .integer { index := y.whole() items := x.vector_pointer().items if index < 0 || index >= items.len { return false } value = unsafe { (&Value(items.data))[index] } } else { return false } // The global load was already charged. Preserve both operand loads, the // call instruction and its application, even with no instruction limit. m.steps += 4 m.ip += 3 m.origin = call.origin if call.op == .tail_call { m.finish_call(value) } else if m.ip < m.function.instructions.len && m.function.instructions[m.ip].op == .jump_false && (vm.options.max_steps == 0 || m.steps < vm.options.max_steps) { // A conditional consumes this result immediately. Preserve its separate // virtual charge and origin, without a temporary push/pop or dispatch. branch := m.function.instructions[m.ip] m.steps++ m.origin = branch.origin m.ip = if value.is_true() { m.ip + 1 } else { int(branch.a) } } else { m.push(value) } return true }