diff --git a/rtl/rot8.v b/rtl/rot8.v index 7d3dc31..35d3b23 100644 --- a/rtl/rot8.v +++ b/rtl/rot8.v @@ -1,56 +1,30 @@ -// ROT-8, the machine. +// ROT-8 execution core. The default machine has 64 eight-bit data cells. +// The program interface accepts either packed opcodes or one opcode per byte. +// A loop back edge pops the loop entry and jumps to '[' so it is tested again. // -// Eight instructions, three bit opcodes packed into a byte addressed program -// memory, a 64 cell by 8 bit data ring, and -- this is the part the software -// cannot check -- the hardware bracket strategy: a LIFO of loop entry positions -// instead of a backward scan, jumping back *onto* the '[' so it re-tests. -// -// * program memory is read as a 16 bit window (two byte reads), because a three -// bit instruction can straddle a byte boundary. A real board does this with -// a 16 bit wide ROM, two ROMs, or a shift register; the interface is written -// as two reads so all three are countable. -// * EPROM=1 selects the *other* legal program memory: one instruction per byte, -// opcode in D2..D0, `ip` straight into the address pins (what a single 27C512 -// does, see docs/ttl-schematic.md §4). Eight times the ROM, but no shift -// register, no alignment, one read per fetch. Both formats run the same -// tapes and must produce the same OUT stream and step count. -// * the data ring is 64 cells, so `dp` is a 6 bit counter whose wrap is free. -// * `,` blocks: `in_ready` goes high and the machine does not advance until -// `in_valid` is seen. Reading zero has to be an explicit event (`in_valid` -// with `in_data` zero), otherwise an idle keyboard would feed the program a -// stream of EOFs. -// * the step counter counts instructions, not cycles, and a bracket jump costs -// exactly one step -- the scan and the LIFO bookkeeping are free, which is -// what keeps the hardware's step counts comparable with the interpreters -// (see `--loop-stack --retest` in r8forge_tape_run). -// -// Opcodes, in the order the assembler packs them (ROT-8-viz's enum): +// Opcode order matches the R8Forge tape format: // 0 '>' STP 1 '<' BTP 2 '+' ROR 3 '-' FLB // 4 '[' BIZ 5 ']' RNZ 6 '.' OUT 7 ',' INP -// -// This file is the executable spec of the board. It has not been run yet: there -// is no Verilog simulator on the development machine, so rtl/README.md says -// how to run it and what to compare it against once one is available. `default_nettype none module rot8 #( parameter integer WIDTH = 8, // bits per data cell - parameter integer RING = 64, // data cells (power of two: free wrap) + parameter integer RING = 64, // number of data cells parameter integer IPW = 16, // instruction pointer width - parameter integer STACKW = 4, // loop stack depth: 2^STACKW entries + parameter integer STACKW = 4, // stack pointer width; 2^STACKW - 1 usable entries parameter integer EPROM = 0 // 0: 3 bit packed stream, 1: one instruction per byte ) ( input wire clk, input wire rst_n, - input wire run, // 1: free run, 0: halted between steps - input wire step, // one instruction while run is 0 + input wire run, // 1: continuous run, 0: single-step mode + input wire step, // one-cycle request to execute one instruction - // program memory: two byte reads at prog_addr0 / prog_addr1 + // Packed mode uses both reads. EPROM mode uses prog_data0. output wire [IPW-1:0] prog_addr0, output wire [IPW-1:0] prog_addr1, input wire [7:0] prog_data0, input wire [7:0] prog_data1, - input wire [IPW-1:0] prog_len, // instruction count: ip == prog_len halts + input wire [IPW-1:0] prog_len, // instruction count; halt when ip reaches it // input: blocks until in_valid, one byte per ',' input wire in_valid, @@ -63,8 +37,6 @@ module rot8 #( // debug / panel output reg [IPW-1:0] ip, - // $clog2 rather than DPW here: a localparam declared in the body is not in - // scope in the port list, and the width has to be a constant expression output reg [$clog2(RING)-1:0] dp, output reg [31:0] steps, output reg halted @@ -78,14 +50,12 @@ module rot8 #( localparam [1:0] S_FETCH = 2'd0, S_SCAN = 2'd1, S_HALT = 2'd2; reg [1:0] state; + reg step_pending; reg [WIDTH-1:0] cells [0:RING-1]; reg [IPW-1:0] stack [0:(1<> 3; wire [2:0] bit_offset = bit_index[2:0]; @@ -96,18 +66,15 @@ module rot8 #( assign prog_addr0 = EPROM ? ip : byte_index; assign prog_addr1 = EPROM ? ip : (byte_index + 1'b1); - // in_ready means "the byte I am waiting for would be taken this cycle". It - // must NOT be qualified with !in_valid: a producer then never sees the - // acceptance edge and the handshake deadlocks (the first testbench did exactly - // that and hello, which reads nothing, was the only tape that could run). - // ...and it is only true when a byte would really be consumed this cycle: - // with run low (single step mode) or after a halt the machine is not going to - // take it, and a producer that trusts a high in_ready drops its byte. - assign in_ready = (state == S_FETCH) && (op_now == OP_INP) - && (run || step) && !halted; + // Input transfers when ready and valid are both high on the clock edge. + // Ready is independent of in_valid and stays low while paused or halted. + wire in_program = ip < prog_len; + wire execute_cycle = rst_n && !halted && in_program && (run || step || step_pending); + wire execute_fetch = execute_cycle && (state == S_FETCH); + assign in_ready = execute_fetch && (op_now == OP_INP); - // forward depth counter for the '[' skip - reg [STACKW:0] scan_depth; + // Number of unmatched '[' opcodes in the forward scan. + reg [IPW-1:0] scan_depth; integer i; always @(posedge clk or negedge rst_n) begin @@ -120,117 +87,120 @@ module rot8 #( halted <= 1'b0; out_valid <= 1'b0; out_data <= 8'd0; - scan_depth <= {(STACKW+1){1'b0}}; + scan_depth <= {IPW{1'b0}}; + step_pending <= 1'b0; for (i = 0; i < RING; i = i + 1) cells[i] <= {WIDTH{1'b0}}; end else begin out_valid <= 1'b0; - // ip == prog_len is the halt: the tape ran off its end - if (ip >= prog_len) begin + // No instruction or scan may change state once it reaches the tape end. + if (!in_program) begin halted <= 1'b1; state <= S_HALT; - end - - case (state) - S_FETCH: begin - if (!halted && (ip < prog_len) && (run || step)) begin - case (op_now) - OP_STP: begin - dp <= (dp == RING - 1) ? {DPW{1'b0}} : dp + 1'b1; - ip <= ip + 1'b1; - end - OP_BTP: begin - dp <= (dp == 0) ? (RING - 1) : dp - 1'b1; - ip <= ip + 1'b1; - end - OP_ROR: begin - cells[dp] <= {cells[dp][0], cells[dp][WIDTH-1:1]}; - ip <= ip + 1'b1; - end - OP_FLB: begin - cells[dp][0] <= ~cells[dp][0]; - ip <= ip + 1'b1; - end - OP_BIZ: begin - if (!cells[dp][0]) begin - // skip forward to the matching ']', then past it - scan_depth <= {{STACKW{1'b0}}, 1'b1}; - state <= S_SCAN; + step_pending <= 1'b0; + end else begin + case (state) + S_FETCH: begin + if (execute_fetch) begin + // Keep the request active until a blocking input or scan completes. + step_pending <= !run && ((op_now == OP_INP && !in_valid) + || (op_now == OP_BIZ && !cells[dp][0])); + case (op_now) + OP_STP: begin + dp <= (dp == RING - 1) ? {DPW{1'b0}} : dp + 1'b1; ip <= ip + 1'b1; - end else begin - // entering the loop: remember where it starts. A full stack - // is as malformed as an empty pop below -- halt instead of - // wrapping sp and silently jumping somewhere else later. - if (sp == {STACKW{1'b1}}) begin - halted <= 1'b1; - state <= S_HALT; + end + OP_BTP: begin + dp <= (dp == 0) ? (RING - 1) : dp - 1'b1; + ip <= ip + 1'b1; + end + OP_ROR: begin + cells[dp] <= {cells[dp][0], cells[dp][WIDTH-1:1]}; + ip <= ip + 1'b1; + end + OP_FLB: begin + cells[dp][0] <= ~cells[dp][0]; + ip <= ip + 1'b1; + end + OP_BIZ: begin + if (!cells[dp][0]) begin + // skip forward to the matching ']', then past it + scan_depth <= 1; + state <= S_SCAN; + ip <= ip + 1'b1; end else begin - stack[sp] <= ip; - sp <= sp + 1'b1; + // Save the loop entry unless incrementing sp would wrap. + if (sp == {STACKW{1'b1}}) begin + halted <= 1'b1; + state <= S_HALT; + end else begin + stack[sp] <= ip; + sp <= sp + 1'b1; + end + ip <= ip + 1'b1; end - ip <= ip + 1'b1; end - end - OP_RNZ: begin - if (cells[dp][0]) begin - // jump back ONTO the '[' (it re-tests, and re-pushes), so the - // entry is popped here - if (sp != 0) begin - ip <= stack[sp - 1'b1]; - sp <= sp - 1'b1; + OP_RNZ: begin + if (cells[dp][0]) begin + // Pop before returning to '['. A successful retest pushes it again. + if (sp != 0) begin + ip <= stack[sp - 1'b1]; + sp <= sp - 1'b1; + end else begin + // The requested back edge has no saved loop entry. + halted <= 1'b1; + state <= S_HALT; + end end else begin - // ']' with nothing entered: a malformed tape. Halt rather - // than index below the stack. - halted <= 1'b1; - state <= S_HALT; + if (sp != 0) + sp <= sp - 1'b1; // the loop finished + ip <= ip + 1'b1; end - end else begin - if (sp != 0) - sp <= sp - 1'b1; // the loop finished + end + OP_OUT: begin + out_valid <= 1'b1; + out_data <= cells[dp]; ip <= ip + 1'b1; end - end - OP_OUT: begin - out_valid <= 1'b1; - out_data <= cells[dp]; - ip <= ip + 1'b1; - end - OP_INP: begin - if (in_valid) begin - cells[dp] <= in_data[WIDTH-1:0]; - ip <= ip + 1'b1; + OP_INP: begin + if (in_valid) begin + cells[dp] <= in_data[WIDTH-1:0]; + ip <= ip + 1'b1; + end end - // else: hold every register; in_ready is already high - end - default: ip <= ip + 1'b1; - endcase - // a held ',', a scan or a halt does not count as an instruction - if (op_now != OP_INP || in_valid) - steps <= steps + 32'd1; - end - end - - S_SCAN: begin - // one opcode per cycle: forward only, and free (it is not a step) - if (run || step) begin - if (op_now == OP_BIZ) - scan_depth <= scan_depth + 1'b1; - else if (op_now == OP_RNZ) - scan_depth <= scan_depth - 1'b1; - ip <= ip + 1'b1; - if (op_now == OP_RNZ && scan_depth == 1) begin - state <= S_FETCH; // ip now points past the matching ']' + default: ip <= ip + 1'b1; + endcase + // A waiting ',' counts only when it receives a byte. + if (op_now != OP_INP || in_valid) + steps <= steps + 32'd1; end end - end - S_HALT: begin - halted <= 1'b1; - end + S_SCAN: begin + // Inspect one opcode per enabled cycle without incrementing steps. + if (execute_cycle) begin + if (!run && step) + step_pending <= 1'b1; + if (op_now == OP_BIZ) + scan_depth <= scan_depth + 1'b1; + else if (op_now == OP_RNZ) + scan_depth <= scan_depth - 1'b1; + ip <= ip + 1'b1; + if (op_now == OP_RNZ && scan_depth == 1) begin + state <= S_FETCH; // ip now points past the matching ']' + step_pending <= 1'b0; + end + end + end - default: state <= S_FETCH; - endcase + S_HALT: begin + halted <= 1'b1; + end + + default: state <= S_FETCH; + endcase + end end end diff --git a/rtl/tb_rot8.v b/rtl/tb_rot8.v index ec32d79..924cefc 100644 --- a/rtl/tb_rot8.v +++ b/rtl/tb_rot8.v @@ -1,20 +1,5 @@ -// Testbench for rot8.v: run one packed image and print what the machine printed, -// in the same shape as `r8forge_tape_run` so the two can be diffed. -// -// iverilog -o rot8_tb rtl/rot8.v rtl/tb_rot8.v -// vvp rot8_tb +HEX=hello.hex +LEN=727 -// -// The hex file comes from `r8forge_tape_pack hello.rot8 -o hello.r8t --hex -// hello.hex` (the body alone, one byte per line) and LEN from the comment on its -// first line. -// -// What it is for: the OUT stream and the step count have to match -// r8forge_tape_run hello.r8t --loop-stack --retest -// which is the combination the board implements. That one comparison validates -// the RTL, the packer and the bracket strategy at the same time. -// -// Not run yet: the development machine has no Verilog simulator (no iverilog, no -// verilator). See rtl/README.md. +// Run a program image and print the OUT bytes and step count for comparison +// with r8forge_tape_run --loop-stack --retest. See rtl/README.md for image formats. `timescale 1ns/1ps `default_nettype none @@ -51,6 +36,8 @@ module tb_rot8; reg [1023:0] hex_path; reg [1023:0] in_path; + integer hex_fd; + integer unsigned requested_length, image_bytes; integer in_fd = 0; reg in_eof = 0; integer next_char; @@ -59,11 +46,8 @@ module tb_rot8; assign prog_data1 = mem[prog_addr1]; assign prog_len = length; - // Input: characters from +INFILE, one per accepted ','. When the file runs out - // the machine is fed zeros, which is exactly what the interpreters do when - // their scripted input is exhausted (EOF reads as 0). Without +INFILE, - // in_valid stays low, so a tape that reads stops on the cycle cap and says so - // instead of hanging the simulator. + // Feed one byte per accepted ','. Exhausted input reads as zero. + // Without an input file, ',' waits until the testbench reaches its cycle limit. task take_char; begin next_char = $fgetc(in_fd); @@ -76,9 +60,7 @@ module tb_rot8; end endtask - // Compile with -DEPROM_MODE to model the one-instruction-per-byte ROM - // (27C512, see docs/ttl-schematic.md §4); the tape and the expected numbers - // are the same either way, only the image file differs (--hex vs --eprom --hex). + // In EPROM_MODE, supply an image generated with --eprom --hex. `ifdef EPROM_MODE localparam integer EPROM = 1; `else @@ -94,54 +76,64 @@ module tb_rot8; .out_valid(out_valid), .out_data(out_data), .ip(ip), .dp(dp), .steps(steps), .halted(halted)); - // 100 MHz: two cycles per instruction, so the cycle count is about twice the - // step count. A real board's clock is unrelated to the semantics. + // The simulation clock lets us count cycles separately from instructions. always #5 clk = ~clk; initial begin - if (!$value$plusargs("HEX=%s", hex_path)) begin - $display("tb_rot8: pass +HEX="); - $finish; + if (!$value$plusargs("HEX=%s", hex_path)) + $fatal(1, "Pass +HEX="); + if (!$value$plusargs("LEN=%d", requested_length)) + $fatal(1, "Pass +LEN="); + if (requested_length > (1 << MEMW) - 1) + $fatal(1, "Instruction count is too large: %0d", requested_length); + length = requested_length; + image_bytes = EPROM ? requested_length : (3 * requested_length + 7) / 8; + hex_fd = $fopen(hex_path, "rb"); + if (hex_fd == 0) + $fatal(1, "Cannot open program image %0s", hex_path); + $fclose(hex_fd); + if (image_bytes != 0) begin + $readmemh(hex_path, mem, 0, image_bytes - 1); + for (i = 0; i < image_bytes; i = i + 1) + if ((^mem[i]) === 1'bx) + $fatal(1, "Missing or invalid byte at offset %0d in %0s", i, hex_path); end - if (!$value$plusargs("LEN=%d", length)) begin - $display("tb_rot8: pass +LEN="); - $finish; + // A packed fetch can read one byte past the image for its fetch window. + mem[image_bytes] = 8'h00; + if ($value$plusargs("INFILE=%s", in_path)) begin + in_fd = $fopen(in_path, "rb"); + if (in_fd == 0) + $fatal(1, "Cannot open input file %0s", in_path); end - for (i = 0; i < (1< [input.txt] [eprom] -# 跑一张镜像,打印步数/拍数/扫描占比/最大栈深 -# -# 镜像来源(R8Forge,8 位 / 64 格的构建): -# r8forge examples/calc.r8asm > calc.rot8 -# r8forge_tape_pack calc.rot8 -o calc.r8t --hex calc.hex --verify -# r8forge_tape_pack calc.rot8 -o calc_e.r8t --eprom --hex calc_e.hex # 一字节一指令 -# -# 注意:Icarus 把 plusarg 原样传给 $readmemh,路径里有非 ASCII 字符时内存会**静默留空** -# (见 rtl/README.md 的坑 1)——所以这里一律先 cd 到镜像目录再用相对路径。 +# Run the input handshake regression or measure cycles for an existing ROM image. set -e + +usage() { + printf '%s\n' "Usage: $0 in-ready | step | states [input.txt] [eprom]" >&2 + exit 2 +} + +# Resolve image and input paths from the repository root, as in the examples. cd "$(dirname "$0")/.." - mode=${1:-in-ready} -build=$(mktemp -d) -trap 'rm -rf "$build"' EXIT - case "$mode" in in-ready) - iverilog -g2012 -o "$build/tb.vvp" rtl/rot8.v tests/tb_in_ready.v - exec vvp "$build/tb.vvp" + testbench=tests/tb_in_ready.v + set -- + ;; + step) + testbench=tests/tb_step.v + set -- ;; states) - hex=$2; len=$3; infile=$4; eprom=$5 - [ -n "$hex" ] && [ -n "$len" ] || { echo "usage: $0 states [input.txt] [eprom]"; exit 2; } - dir=$(cd "$(dirname "$hex")" && pwd); base=$(basename "$hex") - extra="" - [ -n "$infile" ] && extra="+INFILE=$(cd "$(dirname "$infile")" && pwd)/$(basename "$infile")" - if [ "$eprom" = "eprom" ]; then - iverilog -g2012 -DEPROM_MODE -o "$build/tb.vvp" rtl/rot8.v tests/tb_state_mix.v - else - iverilog -g2012 -o "$build/tb.vvp" rtl/rot8.v tests/tb_state_mix.v - fi - cd "$dir" - exec vvp "$build/tb.vvp" "+HEX=$base" "+LEN=$len" $extra - ;; - *) - echo "usage: $0 in-ready | states [input.txt] [eprom]"; exit 2 + [ "$#" -ge 3 ] && [ "$#" -le 5 ] || usage + image=$2 + length=$3 + input=${4:-} + testbench=tests/tb_state_mix.v + case "${5:-}" in + '') set -- ;; + eprom) set -- -DEPROM_MODE ;; + *) usage ;; + esac ;; + *) usage ;; esac + +build_dir=$(mktemp -d) +trap 'rm -r -- "$build_dir"' 0 +iverilog -g2012 "$@" -o "$build_dir/tb.vvp" rtl/rot8.v "$testbench" + +if [ "$mode" = states ]; then + # Use short ASCII file names for Icarus plusargs on Windows. + cp -- "$image" "$build_dir/program.hex" + set -- "+HEX=program.hex" "+LEN=$length" + if [ -n "$input" ]; then + cp -- "$input" "$build_dir/input.txt" + set -- "$@" "+INFILE=input.txt" + fi +fi +cd "$build_dir" +vvp tb.vvp "$@" diff --git a/tests/rtl_sim.cmake b/tests/rtl_sim.cmake index e9157fc..8e00206 100644 --- a/tests/rtl_sim.cmake +++ b/tests/rtl_sim.cmake @@ -1,22 +1,6 @@ -# Compare the RTL against the R8Forge interpreter, on a real tape. -# -# The one standard this machine answers to: same OUT stream, same step count as -# `r8forge_tape_run --loop-stack --retest` (the bracket discipline the board -# implements: jump back *onto* the [, so ] pops the loop stack on the jump). -# -# cmake -DRTL=rtl -# -DPACK=/build/Release/r8forge_tape_pack -# -DRUN=/build/Release/r8forge_tape_run -# -DR8FORGE=/build/Release/r8forge -# -DSOURCE=../R8Forge/examples/hello.r8asm -# -DWORK=build [-DINPUT="12 34 + ."] [-DTAPE_ARGS=""] -# -P tests/rtl_sim.cmake -# -# It assembles SOURCE, packs it, runs the interpreter, compiles rtl/rot8.v with -# iverilog, runs the testbench, and compares both the OUT stream and the step -# count. The RTL is the 8 bit / 64 cell machine, so SOURCE has to be a tape that -# fits in 64 cells (all the shipped examples do; the flagship peaks at 155 and -# therefore wraps, which still matches the interpreter but is not a good test). +# Compare OUT bytes and instruction counts against the R8Forge interpreter. +# See rtl/README.md for the toolchain setup and an invocation example. + foreach(var RTL PACK RUN R8FORGE SOURCE WORK) if(NOT DEFINED ${var}) message(FATAL_ERROR "rtl_sim.cmake needs -D${var}=...") @@ -28,6 +12,7 @@ endif() get_filename_component(rtl_dir "${RTL}" ABSOLUTE) get_filename_component(work_dir "${WORK}" ABSOLUTE) +get_filename_component(SOURCE "${SOURCE}" ABSOLUTE) get_filename_component(source_dir "${SOURCE}" DIRECTORY) file(MAKE_DIRECTORY "${work_dir}") @@ -37,15 +22,14 @@ if(NOT IVERILOG OR NOT VVP) message(FATAL_ERROR "rtl_sim needs iverilog and vvp on PATH") endif() -# The assembler resolves `%include "lib/..."` against the *working directory*, not -# against the source file, so it has to run from the R8Forge root (the parent of -# examples/). -DASSEMBLE_DIR overrides that when the source lives elsewhere. +# The assembler resolves includes from its working directory. Use the parent +# of examples/ or asm/ by default. if(NOT DEFINED ASSEMBLE_DIR) get_filename_component(ASSEMBLE_DIR "${source_dir}/.." ABSOLUTE) endif() execute_process(COMMAND ${R8FORGE} ${SOURCE} OUTPUT_VARIABLE text RESULT_VARIABLE rc WORKING_DIRECTORY ${ASSEMBLE_DIR}) -if(NOT rc EQUAL 0) +if(NOT rc STREQUAL "0") message(FATAL_ERROR "assembling ${SOURCE} in ${ASSEMBLE_DIR} failed: ${rc}") endif() string(LENGTH "${text}" length) @@ -53,7 +37,7 @@ file(WRITE ${work_dir}/rtl_sim.rot8 "${text}") execute_process(COMMAND ${PACK} ${work_dir}/rtl_sim.rot8 -o ${work_dir}/rtl_sim.r8t --hex ${work_dir}/rtl_sim.hex OUTPUT_VARIABLE packed RESULT_VARIABLE rc) -if(NOT rc EQUAL 0) +if(NOT rc STREQUAL "0") message(FATAL_ERROR "packing failed: ${rc} ${packed}") endif() message(STATUS "${packed}") @@ -67,7 +51,7 @@ else() -i "${INPUT}" OUTPUT_VARIABLE sw RESULT_VARIABLE rc) endif() -if(NOT rc EQUAL 0) +if(NOT rc STREQUAL "0") message(FATAL_ERROR "software run failed: ${rc} ${sw}") endif() @@ -75,29 +59,32 @@ execute_process(COMMAND ${IVERILOG} -g2012 -o rot8_tb.vvp ${rtl_dir}/rot8.v ${rtl_dir}/tb_rot8.v WORKING_DIRECTORY ${work_dir} OUTPUT_VARIABLE build_log RESULT_VARIABLE rc) -if(NOT rc EQUAL 0) - message(FATAL_ERROR "iverilog failed: ${build_log}") +if(NOT rc STREQUAL "0") + message(FATAL_ERROR "iverilog failed (${rc}): ${build_log}") endif() -# Run vvp *from the work directory* with relative file names. Icarus passes -# plusargs through as raw bytes, so an absolute path containing non-ASCII (this -# checkout lives under a Chinese directory name) arrives at $readmemh mangled and -# the memory silently stays empty -- the machine then runs a tape of opcode 0. +# Relative ASCII plusargs avoid path encoding issues in Icarus on Windows. execute_process(COMMAND ${VVP} rot8_tb.vvp +HEX=rtl_sim.hex +LEN=${length} +INFILE=rtl_sim_in.txt WORKING_DIRECTORY ${work_dir} OUTPUT_VARIABLE rtl RESULT_VARIABLE rc) -if(NOT rc EQUAL 0) +if(NOT rc STREQUAL "0") message(FATAL_ERROR "vvp failed: ${rc} ${rtl}") endif() -string(REGEX MATCH "out[^\n]*" rtl_out "${rtl}") - -string(REGEX MATCH "^out([^()]*) *\\(([0-9]+) steps" _ "${sw}") +set(out_pattern "out([^()\r\n]*) *\\(([0-9]+) steps") +string(REGEX MATCH "^${out_pattern}" sw_summary "${sw}") +if(sw_summary STREQUAL "") + message(FATAL_ERROR "Interpreter did not report an OUT stream and step count:\n${sw}") +endif() set(sw_values "${CMAKE_MATCH_1}") set(sw_steps "${CMAKE_MATCH_2}") -string(REGEX MATCH "^out([^()]*) *\\(([0-9]+) steps" _ "${rtl_out}") -set(rtl_values "${CMAKE_MATCH_1}") -set(rtl_steps "${CMAKE_MATCH_2}") + +string(REGEX MATCH "(^|\n)${out_pattern}" rtl_summary "${rtl}") +if(rtl_summary STREQUAL "") + message(FATAL_ERROR "RTL did not report an OUT stream and step count:\n${rtl}") +endif() +set(rtl_values "${CMAKE_MATCH_2}") +set(rtl_steps "${CMAKE_MATCH_3}") if(NOT sw_values STREQUAL rtl_values) message(FATAL_ERROR "OUT streams differ\n sw : ${sw_values}\n rtl: ${rtl_values}") diff --git a/tests/tb_in_ready.v b/tests/tb_in_ready.v index fac709e..f0da351 100644 --- a/tests/tb_in_ready.v +++ b/tests/tb_in_ready.v @@ -1,18 +1,6 @@ -// tests/tb_in_ready.v -- the in_ready contract, as a directed test. -// -// in_ready means "a byte handed over this cycle would really be consumed". -// Two historical bugs here, neither of which any tape found: -// * qualified with !in_valid -> deadlock (only a tape that reads input hangs, -// and it shows up as the cycle cap, not as a wrong answer; rtl/README.md 坑 2) -// * not qualified with run/step -> in single-step mode the machine is stopped -// but still says "send me a byte", so a producer that trusts it hands one -// over and loses it; the machine then waits forever on ',' -// -// Tape: instruction 0 = ',' (7), instruction 1 = '.' (6), packed into one byte -// (0b001_110_111 = 0x37) -- no assembler, no ROM image needed. -// -// iverilog -g2012 -o tb.vvp rtl/rot8.v tests/tb_in_ready.v && vvp tb.vvp - +// Verify input handshaking while paused, running, and halted. +// The test runs an in-memory tape: ',' opcode 7 followed by '.' opcode 6. +// Both opcodes fit in the first packed byte, 0x37. `timescale 1ns/1ps `default_nettype none @@ -48,7 +36,7 @@ module tb_in_ready; always #5 clk = ~clk; - task expect0(input exp, input got); + task expect_ready(input exp, input got); begin if (exp !== got) begin $display(" expected %0b got %0b -> FAIL", exp, got); @@ -59,26 +47,26 @@ module tb_in_ready; endtask initial begin - mem[0] = 8'h37; // 指令 0 = ',' (7), 指令 1 = '.' (6) + mem[0] = 8'h37; mem[1] = 8'h00; rst_n = 0; #20 rst_n = 1; #20; - $display("1. 单步模式停着(run=0):in_ready 必须是低"); + $display("1. Ready stays low while paused"); run = 0; step = 0; #30; - expect0(1'b0, in_ready); + expect_ready(1'b0, in_ready); - $display("2. run=0 时给一拍 in_valid:不能出现\"假接受\"(in_ready 全程低)"); + $display("2. A valid pulse while paused must leave the cell unchanged"); in_valid = 1; in_data = 8'h41; #10; - expect0(1'b0, in_ready); + expect_ready(1'b0, in_ready); in_valid = 0; #20; if (dut.cells[0] !== 8'h00) begin - $display(" cell0 = %02x -> FAIL(机器不该吃)", dut.cells[0]); + $display(" cell0 = %02x -> FAIL (unexpected input transfer)", dut.cells[0]); errors = errors + 1; end else - $display(" cell0 仍是 00 -> ok"); + $display(" cell0 remains 00 -> ok"); - $display("3. 电平式 in_valid 挂在 run=0 上,随后放开 run:必须吃掉"); + $display("3. Pending input is accepted when execution resumes"); in_valid = 1; in_data = 8'h43; #20; run = 1; #45; if (dut.cells[0] !== 8'h43) begin @@ -87,9 +75,9 @@ module tb_in_ready; end else $display(" cell0 = 43 -> ok"); - $display("4. 复位后 run=1 停在 ',' 上:in_ready 必须为高,且交出的字节进格"); + $display("4. A running input instruction asserts ready and stores the byte"); rst_n = 0; #20 rst_n = 1; run = 1; in_valid = 0; #25; - expect0(1'b1, in_ready); + expect_ready(1'b1, in_ready); in_valid = 1; in_data = 8'h42; #10 in_valid = 0; #25; if (dut.cells[0] !== 8'h42) begin $display(" cell0 = %02x -> FAIL", dut.cells[0]); @@ -97,15 +85,16 @@ module tb_in_ready; end else $display(" cell0 = 42 -> ok"); - $display("5. 停机后(ip >= prog_len):in_ready 必须是低"); + $display("5. Ready stays low after halting"); prog_len = 0; #40; if (!halted) begin - $display(" 没有停机 -> FAIL"); errors = errors + 1; + $display(" Expected the machine to halt -> FAIL"); errors = errors + 1; end - expect0(1'b0, in_ready); + expect_ready(1'b0, in_ready); - if (errors == 0) $display("ALL OK"); - else $display("%0d FAILURES", errors); + if (errors != 0) + $fatal(1, "%0d input handshake checks failed", errors); + $display("ALL OK"); $finish; end endmodule diff --git a/tests/tb_state_mix.v b/tests/tb_state_mix.v index d3d3570..b64fb53 100644 --- a/tests/tb_state_mix.v +++ b/tests/tb_state_mix.v @@ -1,17 +1,6 @@ -// tests/tb_state_mix.v -- 跑一张纸带,数周期花在哪:取指 / 括号扫描 / 停机。 -// -// 存在的理由:rtl/README.md 只说"和解释器步数一致",那对语义够用,但对**硬件预算** -// 不够 —— 步数不等于拍数。实测(8 位 / 64 格,见 docs/bracket-skip.md): -// -// hello 417 步 / 579 拍 (扫描 27%) 最大栈深 0 -// test 100142 步 / (扫描 53%) 最大栈深 4 -// calc 166741 步 / 698075 拍 (扫描 76%) 最大栈深 7 -// -// iverilog -g2012 -o tb_state_mix.vvp rtl/rot8.v tests/tb_state_mix.v -// vvp tb_state_mix.vvp +HEX=hello.hex +LEN=577 -// vvp tb_state_mix.vvp +HEX=calc.hex +LEN=51378 +INFILE=calc_in.txt -// vvp tb_state_mix.vvp +HEX=calc.hex +LEN=51378 +EPROM // 一字节一指令的镜像 - +// Count cycles in each RTL state and track the peak loop and scan depths. +// Compile with -DEPROM_MODE for one-instruction-per-byte images. +// Use tests/rtl_probe.sh states [input.txt] [eprom]. `timescale 1ns/1ps `default_nettype none @@ -22,7 +11,7 @@ module tb_state_mix; reg [15:0] length = 0; wire [15:0] prog_addr0, prog_addr1; - reg [7:0] prog_data0, prog_data1; + wire [7:0] prog_data0, prog_data1; wire in_ready, out_valid, halted; wire [7:0] out_data; wire [15:0] ip; @@ -31,7 +20,10 @@ module tb_state_mix; reg [7:0] mem [0:65535]; reg [1023:0] hex_path, in_path; - integer in_fd, next_char, i; + integer hex_fd; + integer unsigned requested_length, image_bytes; + integer in_fd = 0; + integer next_char, i; integer cycles = 0, c_fetch = 0, c_scan = 0, c_halt = 0; integer n_out = 0, stalls = 0, max_sp = 0, max_scan = 0; reg in_eof = 0; @@ -59,24 +51,46 @@ module tb_state_mix; begin next_char = $fgetc(in_fd); if (next_char < 0) begin - in_eof <= 1'b1; in_data <= 8'd0; + in_eof <= 1'b1; + in_data <= 8'd0; end else in_data <= next_char[7:0]; end endtask initial begin - if (!$value$plusargs("HEX=%s", hex_path)) begin $display("need +HEX="); $finish; end - if (!$value$plusargs("LEN=%d", length)) begin $display("need +LEN="); $finish; end - if ($test$plusargs("EPROM")) begin - // 一字节一指令的镜像里 ip 就是地址,长度也要按"字节数"给;这里不改指针, - // 只提醒调用方用 --eprom --hex 生成的镜像与同样的 +LEN。 + if (!$value$plusargs("HEX=%s", hex_path)) + $fatal(1, "Pass +HEX="); + if (!$value$plusargs("LEN=%d", requested_length)) + $fatal(1, "Pass +LEN="); + if (requested_length > (1 << 16) - 1) + $fatal(1, "Instruction count is too large: %0d", requested_length); + length = requested_length; + image_bytes = EPROM ? requested_length : (3 * requested_length + 7) / 8; + + hex_fd = $fopen(hex_path, "rb"); + if (hex_fd == 0) + $fatal(1, "Cannot open program image %0s", hex_path); + $fclose(hex_fd); + if (image_bytes != 0) begin + $readmemh(hex_path, mem, 0, image_bytes - 1); + for (i = 0; i < image_bytes; i = i + 1) + if ((^mem[i]) === 1'bx) + $fatal(1, "Missing or invalid byte at offset %0d in %0s", i, hex_path); end - for (i = 0; i < 65536; i = i + 1) mem[i] = 8'h00; - $readmemh(hex_path, mem); - if ($value$plusargs("INFILE=%s", in_path)) in_fd = $fopen(in_path, "r"); + // A packed fetch can read one byte past the image for its fetch window. + mem[image_bytes] = 8'h00; + if ($value$plusargs("INFILE=%s", in_path)) begin + in_fd = $fopen(in_path, "rb"); + if (in_fd == 0) + $fatal(1, "Cannot open input file %0s", in_path); + end + #20 rst_n = 1; - if (in_fd != 0) begin in_valid = 1'b1; take_char; end + if (in_fd != 0) begin + in_valid = 1'b1; + take_char; + end while (!halted && cycles < 200000000) begin @(posedge clk); cycles = cycles + 1; @@ -91,15 +105,18 @@ module tb_state_mix; if (in_ready && in_valid && in_fd != 0 && !in_eof) take_char; if (out_valid) n_out = n_out + 1; end - $display("%s%s", EPROM ? "[EPROM 1 byte/instruction] " : "[packed 3 bit/instruction] ", - halted ? "" : "NO HALT -- "); + if (!halted) + $fatal(1, "No halt after %0d cycles: ip %0d dp %0d, %0d input stalls", + cycles, ip, dp, stalls); + + $display("%s", EPROM ? "[EPROM 1 byte/instruction]" : "[packed 3 bit/instruction]"); $display("steps=%0d cycles=%0d outs=%0d stalls=%0d", steps, cycles, n_out, stalls); if (cycles > 0) $display(" S_FETCH=%0d (%0d%%) S_SCAN=%0d (%0d%%) S_HALT=%0d", - c_fetch, (100*c_fetch)/cycles, c_scan, (100*c_scan)/cycles, c_halt); + c_fetch, (64'd100*c_fetch)/cycles, c_scan, (64'd100*c_scan)/cycles, c_halt); if (steps > 0) $display(" cycles/step = %0d.%02d, max stack depth = %0d, max scan depth = %0d", - cycles/steps, (100*(cycles%steps))/steps, max_sp, max_scan); + cycles/steps, (64'd100*(cycles%steps))/steps, max_sp, max_scan); $finish; end endmodule diff --git a/tests/tb_step.v b/tests/tb_step.v new file mode 100644 index 0000000..7759b86 --- /dev/null +++ b/tests/tb_step.v @@ -0,0 +1,106 @@ +// Check tape bounds and single-step completion for scanning and input. +`timescale 1ns/1ps +`default_nettype none + +module tb_step; + reg clk = 0, rst_n = 1, run = 0, step = 0, in_valid = 0; + reg [7:0] in_data = 8'h41; + reg [7:0] length; + reg [7:0] rom [0:255]; + wire [7:0] address, ip; + wire ready, halted, out_valid; + wire [7:0] out_data; + wire [31:0] steps; + integer i; + + rot8 #(.IPW(8), .EPROM(1)) dut ( + .clk(clk), .rst_n(rst_n), .run(run), .step(step), + .prog_addr0(address), .prog_addr1(), .prog_data0(rom[address]), + .prog_data1(8'd0), .prog_len(length), .in_valid(in_valid), + .in_data(in_data), .in_ready(ready), .out_valid(out_valid), + .out_data(out_data), .ip(ip), .dp(), .steps(steps), .halted(halted)); + + always #5 clk = ~clk; + + task reset; + begin + rst_n = 0; + @(negedge clk); + if (ready !== 0) + $fatal(1, "Input advertised while in reset"); + rst_n = 1; + end + endtask + + task request_step; + begin + step = 1; + @(negedge clk); + step = 0; + end + endtask + + initial begin + // A ',' outside the image must not advertise a transfer. + length = 1; + rom[0] = 0; + rom[1] = 7; + run = 1; + reset; + @(negedge clk); + if (ip !== 1 || ready !== 0) + $fatal(1, "Invalid input handshake past program end"); + @(negedge clk); + if (halted !== 1) + $fatal(1, "Program failed to halt"); + + // The scanner must never consume a matching bracket outside the image. + rom[0] = 4; + rom[1] = 5; + reset; + repeat (2) @(negedge clk); + if (ip !== 1 || halted !== 1 || dut.state !== dut.S_HALT) + $fatal(1, "Scanner ran past program end"); + + // A skipped loop can nest deeper than the active loop stack. + run = 0; + length = 81; + for (i = 0; i < 40; i = i + 1) begin + rom[i] = 4; + rom[40 + i] = 5; + end + rom[80] = 6; + reset; + request_step; + repeat (82) @(negedge clk); + if (ip !== 80 || steps !== 1 || halted !== 0 || out_valid !== 0) + $fatal(1, "Single step failed to finish the skip and pause"); + request_step; + if (out_valid !== 1 || steps !== 2) + $fatal(1, "The next step failed to execute OUT"); + + // An input instruction can receive its byte after the step pulse ends. + length = 2; + rom[0] = 7; + rom[1] = 6; + reset; + request_step; + repeat (3) @(negedge clk); + if (ready !== 1 || ip !== 0 || steps !== 0) + $fatal(1, "Single-step input stopped waiting too early"); + in_valid = 1; + @(negedge clk); + in_valid = 0; + repeat (3) @(negedge clk); + if (ready !== 0 || ip !== 1 || steps !== 1 || out_valid !== 0) + $fatal(1, "Single-step input failed to store the byte and pause"); + request_step; + if (out_valid !== 1 || out_data !== 8'h41 || steps !== 2) + $fatal(1, "OUT did not return the single-step input byte"); + + $display("Single-step and tape boundary checks passed"); + $finish; + end +endmodule + +`default_nettype wire