|
| 1 | +/* test_opcode_roundtrip.c |
| 2 | + * Verifies that a chunk with opcodes and constants round-trips through |
| 3 | + * write_chunk_to_file() and read_chunk_from_file() preserving bytes. |
| 4 | + */ |
| 5 | + |
| 6 | +#include <stdio.h> |
| 7 | +#include <stdlib.h> |
| 8 | +#include <string.h> |
| 9 | +#include <assert.h> |
| 10 | +#include "bytecode.h" |
| 11 | + |
| 12 | +int main(void) { |
| 13 | + const char *tmp = "tests/tmp_opcode_rt.proxbc"; |
| 14 | + |
| 15 | + Chunk c; |
| 16 | + chunk_init(&c); |
| 17 | + |
| 18 | + /* Add a couple constants */ |
| 19 | + Value v1; v1.type = VAL_NUMBER; v1.as.number = 3.14; consttable_add(&c.constants, v1); |
| 20 | + Value v2; v2.type = VAL_STRING; v2.as.string.length = 5; v2.as.string.chars = strdup("hello"); consttable_add(&c.constants, v2); |
| 21 | + |
| 22 | + /* Emit instructions */ |
| 23 | + emit_opcode(&c, OP_PUSH_CONST); |
| 24 | + emit_uleb128(&c, 0); |
| 25 | + emit_opcode(&c, OP_PUSH_CONST); |
| 26 | + emit_uleb128(&c, 1); |
| 27 | + emit_opcode(&c, OP_ADD); |
| 28 | + emit_opcode(&c, OP_HALT); |
| 29 | + |
| 30 | + if (write_chunk_to_file(tmp, &c) != 0) { |
| 31 | + fprintf(stderr, "Failed to write chunk to %s\n", tmp); |
| 32 | + chunk_free(&c); |
| 33 | + return 2; |
| 34 | + } |
| 35 | + |
| 36 | + Chunk out; |
| 37 | + if (read_chunk_from_file(tmp, &out) != 0) { |
| 38 | + fprintf(stderr, "Failed to read chunk back\n"); |
| 39 | + chunk_free(&c); |
| 40 | + return 3; |
| 41 | + } |
| 42 | + |
| 43 | + /* Compare code bytes */ |
| 44 | + if (out.code_len != c.code_len) { |
| 45 | + fprintf(stderr, "Code length mismatch: %zu vs %zu\n", out.code_len, c.code_len); |
| 46 | + chunk_free(&c); chunk_free(&out); return 4; |
| 47 | + } |
| 48 | + if (memcmp(out.code, c.code, c.code_len) != 0) { |
| 49 | + fprintf(stderr, "Code bytes differ\n"); |
| 50 | + chunk_free(&c); chunk_free(&out); return 5; |
| 51 | + } |
| 52 | + |
| 53 | + /* Compare constants count and first values */ |
| 54 | + if (out.constants.count != c.constants.count) { |
| 55 | + fprintf(stderr, "Const count mismatch: %zu vs %zu\n", out.constants.count, c.constants.count); |
| 56 | + chunk_free(&c); chunk_free(&out); return 6; |
| 57 | + } |
| 58 | + if (out.constants.items[0].type != VAL_NUMBER) { |
| 59 | + fprintf(stderr, "Const type mismatch for idx 0\n"); chunk_free(&c); chunk_free(&out); return 7; |
| 60 | + } |
| 61 | + |
| 62 | + /* Clean up */ |
| 63 | + chunk_free(&c); |
| 64 | + chunk_free(&out); |
| 65 | + |
| 66 | + /* Remove temporary file */ |
| 67 | + remove(tmp); |
| 68 | + |
| 69 | + printf("test_opcode_roundtrip: OK\n"); |
| 70 | + return 0; |
| 71 | +} |
0 commit comments