projects/06/assembler2/assembler2.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 |
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define DBGLOG printf #define err(...) (fprintf(stderr, __VA_ARGS__), \ fprintf(stderr, "%lu | %s\n", file_line_no, file_line), false) #define die(...) do { fprintf(stderr, __VA_ARGS__); exit(-1); } while (0) #define is_symbol_char(c) (('0' <= c && c <= '9') || ('A' <= c && c <= 'Z') \ || ('a' <= c && c <= 'z') || c == '_' || c == '.' \ || c == '$' || c == ':') #define is_whitespace(c) ((c == ' ' || c == '\t')) #define is_number(c) (('0' <= c && c <= '9')) #define MAX_LINE_LEN 256 // TODO: in/excludes NULL terminator? #define MAX_SYMBOL_LEN MAX_LINE_LEN - 2 + 1 // + 1 for NULL terminator size_t instruction_offset = 0; uint16_t rom[32768]; size_t rom_index = 0; char *file_line; // reference to currently-read line (for convenience) size_t file_line_no; // line number, regardless of line content // label and variable symbols are treated the same internally #define MAX_SYMBOLS 32768 char *reserved_strs[] = {"R0", "R1", "R2", "R3", "R4", "R5", "R6", "R7", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15", "SP", "LCL", "ARG", "THIS", "THAT", "SCREEN", "KBD"}; uint16_t reserved_vals[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 0x4000, 0x6000}; char symbol_strs[MAX_SYMBOLS + sizeof(reserved_vals)][MAX_SYMBOL_LEN]; uint16_t symbol_vals[MAX_SYMBOLS + sizeof(reserved_vals)]; uint16_t symbol_index; uint16_t next_var_address = 16; void print_binary_word16(uint16_t w) { unsigned char i; char binary_string[17]; for (i = 0; i < 16; ++i, w <<= 1) binary_string[i] = (((w >> 15) & 0x01) != 0) ? '1' : '0'; binary_string[16] = '\0'; printf("%s\n", binary_string); } static void print_rom_binary(uint16_t *rom, size_t rom_size) { size_t i; for (i = 0; i < rom_size; ++i) print_binary_word16(rom[i]); } static size_t skip_whitespace(const char *line, size_t n) { size_t i; for (i = 0; is_whitespace(line[i]) && i < n; ++i); return i; } static void debug_dump_all_symbols() { size_t i; DBGLOG("-------- DEBUG SYMBOL DUMP --------\n"); for (i = 0; i < symbol_index; ++i) DBGLOG("symbol (%s, %hu)\n", symbol_strs[i], symbol_vals[i]); DBGLOG("-------- END SYMBOL DUMP --------\n"); } static char *lookup_symbol(const char *str, uint16_t *val) { size_t i; for (i = 0; i < sizeof(symbol_strs) / sizeof(symbol_strs[0]); ++i) { if (strncmp(symbol_strs[i], str, MAX_SYMBOL_LEN) == 0) { *val = symbol_vals[i]; return symbol_strs[i]; } } return NULL; } static bool add_symbol(const char *str, uint16_t val) { uint16_t tmp; if (symbol_index > 32767) return err("error: failed to add symbol '%s': %hu > 32767\n", str, val); if (lookup_symbol(str, &tmp) != NULL) return err("error: failed to add symbol '%s': symbol already " "exists\n", str); strncpy(symbol_strs[symbol_index], str, MAX_SYMBOL_LEN); symbol_vals[symbol_index] = val; ++symbol_index; return true; } // pre-fill symbol lists with 'reserved' symbols and values static bool init_reserved_symbols() { size_t i; for (i = 0; i < sizeof(reserved_strs) / sizeof(reserved_strs[0]); ++i) if (!add_symbol(reserved_strs[i], reserved_vals[i])) return err("error: failed to init reserved symbols\n"); return true; } // assumes line[0] == '(' bool parse_line_for_label(const char *line) { size_t i; char c, label_str[MAX_SYMBOL_LEN + 1]; for (i = 1; i < MAX_SYMBOL_LEN; ++i) { c = line[i]; if (c == '\0' || c == ')') break; if (!is_symbol_char(c)) return err("error: invalid char '%c' in label\n", c); label_str[i - 1] = line[i]; } if (c != ')') return err("error: no matching ')' found for label\n"); label_str[i - 1] = '\0'; return add_symbol(label_str, (uint16_t)instruction_offset); } bool parse_c_type_dest(const char *dest_line, uint16_t *dest) { // also length check here since it's not being done in parse_c_type() *dest = 0x05; return true; } bool parse_c_type_comp(const char *comp_line, uint16_t *comp) { // also length check here since it's not being done in parse_c_type() *comp = 0x32; return true; } bool parse_c_type_jump(const char *jump_line, uint16_t *jump) { // also length check here since it's not being done in parse_c_type() *jump = 3; return true; } bool parse_c_type(const char *line, uint16_t *instruction) { size_t i; char c; const char *dest_start = NULL, *comp_start = NULL, *jump_start = NULL; uint16_t dest = 0, comp = 0, jump = 0; // TODO: remove, just use instruction c = line[0]; for (i = 0; !is_whitespace(c) && c != '\n' && c != '\0'; ++i) { c = line[i]; if (c == '=') { dest_start = &line[0]; comp_start = &line[i+1]; } else if (c == ';') jump_start = &line[i+1]; } DBGLOG("C-type, offset %lu, line %lu | %s \n", instruction_offset, file_line_no, line); // only comp field is mandatory; dest/jump are optional, may not exist if (comp_start == NULL) comp_start = &line[0]; if (!parse_c_type_comp(comp_start, &comp)) return false; if (dest_start != NULL) if (!parse_c_type_dest(dest_start, &dest)) return false; if (jump_start != NULL) if (!parse_c_type_jump(jump_start, &jump)) return false; *instruction = 0xe000 | (comp << 6) | (dest << 3) | jump; return true; } bool parse_a_type(const char *line, uint16_t *instruction) { char a_str[MAX_SYMBOL_LEN + 1], *sym_ptr; size_t i, a_str_len; uint16_t a_field = 0; for (i = 1; i < MAX_SYMBOL_LEN && is_symbol_char(line[i]); ++i) { a_str[i - 1] = line[i]; } if (!(is_whitespace(line[i]) || line[i] == '\0' || line[i] == '/')) return err("syntax error: invalid char '%c' in instruction\n", line[i]); a_str_len = i - 1; a_str[a_str_len] = '\0'; if (a_str_len == 0) return err("syntax error: instruction empty after @\n"); if (is_number(a_str[0])) { // @<string> probably number if (a_str_len > 5) return err("syntax error: instruction field '%s' too " "large\n", a_str); for (i = 0; i < 5 && is_number(a_str[i]); ++i) { if (!is_number(a_str[i])) return err("syntax error: '%s' not a valid " "number\n", a_str); a_field = (a_field * 10) + (a_str[i] - 0x30); } if (a_field > 0x7fff) return err("syntax error: %u > 32767, too large\n", a_field); } else { // @<string> probably symbol sym_ptr = lookup_symbol(a_str, &a_field); if (sym_ptr == NULL) { a_field = next_var_address++; if (!add_symbol(a_str, a_field)) return err("error: failed to add var '%s'\n", a_str); } } *instruction = a_field; return true; } // does not care about line length; exits at first newline or after relevant // portion parsed (allows for syntactically-incorrect lines, I know) bool parse_instruction(const char *line, uint16_t *instruction) { if (line[0] == '@') return parse_a_type(line, instruction); else if (line[0] >= '!' && line[0] < '~') return parse_c_type(line, instruction); return err("syntax error: invalid char '%c' found\n", line[0]); } // if first_pass == true: read labels and associate them with values // else: (second pass) parse instructions // Still unsure how I feel about doing handling both passes in one function. // It's hacky, but also space saving and elegant in a way. bool pass(FILE *in_file, bool first_pass) { bool ret = true, second_pass = !first_pass; char *line, in_line[MAX_LINE_LEN]; uint16_t instruction; size_t i, line_len; if (first_pass) if (!init_reserved_symbols()) return false; file_line_no = 0; instruction_offset = 0; while (fgets(in_line, MAX_LINE_LEN, in_file) != NULL) { // parse loop ++file_line_no; file_line = in_line; line = &in_line[skip_whitespace(in_line, MAX_LINE_LEN)]; line_len = 0; for (i = 0; line[i] != '\0'; ++i) { if (line[i] == '\n' || line[i] == '\r') { line[i] = '\0'; // remove newlines break; } ++line_len; // get line length } if (line_len == 0) // "empty" line continue; if (line_len > 1) if (line[0] == '/' && line[1] == '/') // comment found continue; if (line[0] == '(') { if (first_pass) { if (!parse_line_for_label(line)) ret = false; } else continue; } else { if (second_pass) { if (parse_instruction(line, &instruction)) rom[rom_index++] = instruction; else ret = false; } ++instruction_offset; continue; // first pass: if not label, ignore line } } if (first_pass) debug_dump_all_symbols(); return ret; } char *usage_msg = "Usage: assembler1 [path/to/file.asm]\n"; int main(int argc, char *argv[]) { FILE *in_file, *out_file; char *in_file_path, *out_file_path; if (argc != 3) // requires 2 arguments die(usage_msg); // TODO: eventually support STDOUT in_file_path = argv[1]; out_file_path = argv[2]; in_file = fopen(in_file_path, "r"); if (in_file == NULL) die("failed to open assembly file for reading\n"); if(!pass(in_file, true)) // first pass die("failed to parse labels/variables in file\n"); if (fseek(in_file, 0, SEEK_SET)) die("failed to re-read file from beginning\n"); DBGLOG("SECOND PASS\n"); if(!pass(in_file, false)) // second pass die("failed to parse assembly in file\n"); out_file = fopen(out_file_path, "wb"); if (out_file == NULL) die("failed to open output file for writing\n"); //fwrite(rom, rom_index, 1, out_fp); // TODO: double-check print_rom_binary(rom, rom_index); if (fclose(in_file)) die("failed to close assembly file\n"); if (fclose(out_file)) die("failed to close output file\n"); return 0; } |