projects/06/assembler1/assembler1.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 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 |
#include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define DBGLOG(...) printf(__VA_ARGS__) //#define DBGLOG(...) #define error(...) fprintf(stderr, __VA_ARGS__); \ fprintf(stderr, "%lu | %s\n", \ g_asm_line_number, g_asm_line); #define MAX_LINE_LEN 256 #define MAX_SYMBOL_STR_LEN MAX_LINE_LEN - 2 #define RESERVED_LABEL_NUM 23 #define MAX_SYMBOLS 32768 char *g_asm_line; // currently-read line for convenience size_t g_asm_line_number; // current line number size_t g_instruction_number = 0; // instruction offset struct symbol_t { char *symbolstr; uint16_t value; }; char *g_reserved_symbol_strs[RESERVED_LABEL_NUM] = {"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 g_reserved_symbol_values[RESERVED_LABEL_NUM] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 0x4000, 0x6000}; // label and variable symbols will effectively be treated the same; the only // difference is in their use (in a hack program) struct symbol_t *g_symbol_list[MAX_SYMBOLS + RESERVED_LABEL_NUM]; size_t g_symbol_list_len = 0; void print_binary_word16(uint16_t w) { unsigned char i, msb; char binary_string[17]; binary_string[16] = '\0'; for (i = 0; i < 16; ++i) { msb = (char)(w >> 15); if (msb != 0) binary_string[i] = '1'; else binary_string[i] = '0'; w <<= 1; } printf("%s", binary_string); } static uint32_t myatoi(const char *a_field_str) { size_t i; uint32_t ret = 0; for (i = 0; i < 5 && '0' <= a_field_str[i] && a_field_str[i] <= '9'; ++i) { ret = (ret * 10) + (a_field_str[i] - 0x30); } return ret; } void debug_dump_all_symbols() { size_t i; struct symbol_t *symbol; DBGLOG("-------- DEBUG SYMBOL DUMP --------\n"); for (i = 0; i < g_symbol_list_len; ++i) { symbol = g_symbol_list[i]; DBGLOG("symbol (%s, %hu)\n", symbol->symbolstr, symbol->value); } DBGLOG("-------- END SYMBOL DUMP --------\n"); g_symbol_list_len = 0; } void free_all_symbols() { size_t i; struct symbol_t *symbol; for (i = 0; i < g_symbol_list_len; ++i) { symbol = g_symbol_list[i]; free(symbol->symbolstr); // not checking NULL free(symbol); } g_symbol_list_len = 0; } struct symbol_t *create_symbol(const char *str, uint16_t value) { size_t len, i; struct symbol_t *symbol; char *symbolstr; //DBGLOG("creating symbol {'%s', %hu} ...\n", str, value); len = strlen(str); if (len == 0) { error("error creating empty label\n"); return NULL; } symbol = malloc(sizeof(struct symbol_t)); symbolstr = malloc(len + 1); if (symbol == NULL || symbolstr == NULL) { error("error creating label: malloc() returned NULL\n"); exit(-1); } for (i = 0; i < len; ++i) { symbolstr[i] = str[i]; } symbolstr[len] = '\0'; symbol->symbolstr = symbolstr; symbol->value = value; return symbol; } struct symbol_t *lookup_symbol(char *str) { size_t i; int diff; struct symbol_t *symbol; for (i = 0; i < g_symbol_list_len; ++i) { symbol = g_symbol_list[i]; diff = strncmp(str, symbol->symbolstr, MAX_SYMBOL_STR_LEN); if (!diff) { return symbol; } } return NULL; // symbol not found } bool add_symbol(struct symbol_t *symbol) { struct symbol_t *symbol_already_present; if (g_symbol_list_len > (MAX_SYMBOLS + RESERVED_LABEL_NUM)) { error("internal: symbol list full, over %d symbols\n", (MAX_SYMBOLS + RESERVED_LABEL_NUM)); return false; } symbol_already_present = lookup_symbol(symbol->symbolstr); if (symbol_already_present != NULL) { // if present error("error: failed to add symbol %s: already found in list\n", symbol->symbolstr); return false; } g_symbol_list[g_symbol_list_len] = symbol; ++g_symbol_list_len; return true; } // pre-fill list with 'reserved' symbols and values bool init_symbol_list() { size_t i; struct symbol_t *s; for (i = 0; i < RESERVED_LABEL_NUM; ++i) { //DBGLOG("init_symbol_list: adding symbol {%s, %hu}\n", // g_reserved_symbol_strs[i], g_reserved_symbol_values[i]); if((s = create_symbol(g_reserved_symbol_strs[i], g_reserved_symbol_values[i])) == NULL) { //DBGLOG("init_symbol_list: failed to create symbol\n"); return false; // failed to create symbol } if (!add_symbol(s)) { //DBGLOG("init_symbol_list: failed to add symbol\n"); return false; // failed to add symbol } } return true; } // assumes line[0] == '(' bool parse_label(const char *line) { size_t i; uint16_t value; char c, labelstr[MAX_SYMBOL_STR_LEN + 1]; struct symbol_t *symbol; //DBGLOG("Parsing label: line %lu | %s\n", g_asm_line_number, line); if (line[0] != '(') { // just to be safe return false; // not a label; label's look like (THIS) } for (i = 1; (c = line[i]) != '\0'; ++i) { if (i == 1 && ('0' <= c && c <= '9')) { error("syntax error: label starts with a number\n"); return false; } // parse characters until closing ')' if (i > MAX_SYMBOL_STR_LEN) { error("syntax error: label is too long (> %d chars)\n", MAX_SYMBOL_STR_LEN); return false; } else if (c == ')') { if (i == 1) { error("syntax error: empty label '()'\n"); return false; } labelstr[i-1] = '\0'; // create label, add to symbol list value = (uint16_t)g_instruction_number; // safe. won't // be > 65535 symbol = create_symbol(labelstr, value); if (symbol == NULL) return false; return add_symbol(symbol); break; } else if (('0' <= c && c <= '9') || ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || c == '_') { // TODO TODO: enforce label name NOT start with a number! labelstr[i-1] = c; } else { error("syntax error: disallowed character '%hhu' found" " in label\n", c); return false; } } if (c == '\0') { // should_ be ')' after break if all goes as expected error("syntax error: no matching ')' found for label"); } return false; } bool parse_line_for_label(const char *line) { char c; size_t i; for (i = 0; (c = line[i]) != '\0'; ++i) { if (c == ' ' || c == '\t') { continue; } else if (i == 0 && c == '\0') { return false; } else if (c == '/') { // likely comment return false; } else if (c == '(') { return parse_label(&line[i]); } else if (('!' <= c && c <= '\'') || ('*' <= c && c <= '~')) { ++g_instruction_number; // likely instruction found return false; } else { error("syntax error: invalid character '%c' found in " "line\n", c); } } return false; } static bool parse_a_type(const char *line, uint16_t *instruction) { char c, a_field_str[6]; uint32_t a_field = 0; size_t i, a = 0; //DBGLOG("line: %s\n", line); if (line[0] != '@') { error("syntax error: A-type instruction doesn't start with @\n"); return false; } c = line[1]; if (c == '\0') { error("syntax error: A-type instruction empty after @\n"); return false; } if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z')) { // parse symbol/label, handle appropriately // lookup symbol // if (symbol already exists as label) // a_field = symbol value from table // else // calc new variable value // put symbol in table w/ new variable value // a_field = new value // increment global variable value counter DBGLOG("Found label/variable in A-instruction '%s'\n", line); a_field = 65; // STUB!!! } else { for (i = 1; (c = line[i]) != '\0' && a < 6; ++i) { if ('0' <= c && c <= '9') { if (a > 4) { error("error: @<number> too long\n"); return false; } a_field_str[a] = c; // get number a++; } else if ((c == ' ' || c == '\t' || c == '/') && i > 1) { break; } else { // any other character error("syntax error: invalid char '%c' found " "after @\n", c); return false; } } a_field_str[a] = '\0'; // TODO: basic check on a_field_str length? at least 1? a_field = myatoi(a_field_str); // TODO: maybe negative number support? } if (a_field > 32767) { error("error: %u > 32767, too large\n", a_field); return false; } *instruction = 0x0000 | (uint16_t) a_field; return true; } /* returns dest bits 0b00000ddd * Note: order doesn't matter for multi-register dest (but officially it should) */ static bool parse_c_type_dest(const char *dest_line, uint8_t *dest) { size_t len; //DBGLOG("dest_line: %s\n", dest_line); for (len = 0; dest_line[len] != '='; ++len) { // read until '=' if (dest_line[len] == 'A') { if (*dest & 0x04) { // if A register already set error("syntax error: A register set twice\n"); return false; } *dest |= 0x04; } else if (dest_line[len] == 'D') { if (*dest & 0x02) { // if D register already set error("syntax error: D register set twice\n"); return false; } *dest |= 0x02; } else if (dest_line[len] == 'M') { if (*dest & 0x01) { // if M register already set error("syntax error: M register set twice\n"); return false; } *dest |= 0x01; } else { error("syntax error: invalid destination register %c\n", dest_line[len]); return false; } if (len >= 3) { error("syntax error: dest field incorrect length %lu\n", len); return false; } } if (len == 0) { error("syntax error: dest field empty\n"); return false; } return true; } /* returns comp bits 0b0acccccc */ static bool parse_c_type_comp(const char *comp_line, uint8_t *comp) { size_t len; //DBGLOG("comp_line: %s\n", comp_line); for (len = 0; comp_line[len] == '0' || comp_line[len] == '1' || comp_line[len] == '-' || comp_line[len] == 'D' || comp_line[len] == 'A' || comp_line[len] == 'M' || comp_line[len] == '!' || comp_line[len] == '+' || comp_line[len] == '&' || comp_line[len] == '|'; ++len) {} if (len == 1) { // 0 1 D A M switch (comp_line[0]) { case '0': *comp = 0x2a; break; // 0 101010 case '1': *comp = 0x3f; break; // 0 111111 case 'D': *comp = 0x0c; break; // 0 001100 case 'A': *comp = 0x30; break; // 0 110000 case 'M': *comp = 0x70; break; // 1 110000 default: error("syntax error: comp field incorrect value\n"); return false; } } else if (len == 2) { // -1 !D !A !M -D -A -M if (comp_line[0] == '-') { switch (comp_line[1]) { case '1': *comp = 0x3a; break; // 0 111010 case 'D': *comp = 0x0f; break; // 0 001111 case 'A': *comp = 0x33; break; // 0 110011 case 'M': *comp = 0x73; break; // 1 110011 default: error("syntax error: comp field incorrect value\n"); return false; } } else if (comp_line[0] == '!') { switch (comp_line[1]) { case 'D': *comp = 0x0d; break; // 0 001101 case 'A': *comp = 0x31; break; // 0 110001 case 'M': *comp = 0x71; break; // 1 110001 default: error("syntax error: comp field incorrect value\n"); return false; } } else { error("syntax error: comp field incorrect value\n"); return false; } } else if (len == 3) { if (comp_line[0] == 'D') { if (comp_line[2] == '1') { // D+1 D-1 if (comp_line[1] == '+') { *comp = 0x1f; // 0 011111 } else if (comp_line[1] == '-') { *comp = 0x0e; // 0 001110 } else { error("syntax error: comp field " "incorrect value\n"); return false; } } else { // D+A D+M D-A D-M D&A D&M D|A D|M if (comp_line[2] == 'M') { *comp = 0x40; // _1_ 000000 } else if (comp_line[2] == 'A') { *comp = 0x00; // _0_ 000000 } else { error("syntax error: comp field " "incorrect value\n"); return false; } switch (comp_line[1]) { case '+': *comp |= 0x02; break; // 000010 case '-': *comp |= 0x13; break; // 010011 case '&': *comp |= 0x00; break; // 000000 case '|': *comp |= 0x15; break; // 010101 default: error("syntax error: comp field " "incorrect value\n"); return false; } } } else { // A+1 M+1 A-1 M-1 A-D M-D if (comp_line[0] == 'M') { *comp = 0x40; // _1_ 000000 } else if (comp_line[0] == 'A') { *comp = 0x00; // _0_ 000000 } else { error("syntax error: comp field incorrect value\n"); return false; } if (comp_line[1] == '+' && comp_line[2] == '1') { *comp |= 0x37; // 1 110111 } else if (comp_line[1] == '-' && comp_line[2] == '1') { *comp |= 0x32; // 1 110010 } else if (comp_line[1] == '-' && comp_line[2] == 'D') { *comp |= 0x07; // 1 000111 } else { error("syntax error: comp field incorrect value\n"); return false; } } } else { error("syntax error: comp field incorrect length %lu\n", len); return false; } return true; } /* returns jump bits 0b00000jjj */ static bool parse_c_type_jump(const char *jump_line, uint8_t *jump) { size_t len; char *err_3rd_char = "syntax error: 3rd letter in jump field incorrect\n"; //DBGLOG("jump_line: %s\n", jump_line); for (len = 0; jump_line[len] == 'J' || jump_line[len] == 'G' || jump_line[len] == 'T' || jump_line[len] == 'E' || jump_line[len] == 'Q' || jump_line[len] == 'L' || jump_line[len] == 'N' || jump_line[len] == 'M' || jump_line[len] == 'P'; ++len) {} if (len != 3) { error("syntax error: jump field incorrect length %lu\n", len); return false; } if (jump_line[0] == 'J') { // if "J__" switch (jump_line[1]) { case 'G': // if "JG_" if (jump_line[2] == 'T') { // if "JGT" *jump = 0x1; } else if (jump_line[2] == 'E') { // if "JGE" *jump = 0x3; } else { error(err_3rd_char); return false; } break; case 'E': // if "JE_" if (jump_line[2] == 'Q') { // if "JEQ" *jump = 0x2; } else { error(err_3rd_char); return false; } break; case 'L': // if "JL_" if (jump_line[2] == 'T') { // if "JLT" *jump = 0x4; } else if (jump_line[2] == 'E') { // if "JLE" *jump = 0x6; } else { error(err_3rd_char); return false; } break; case 'N': // if "JN_" if (jump_line[2] == 'E') { // if "JNE" *jump = 0x5; } else { error(err_3rd_char); return false; } break; case 'M': // if "JM_" if (jump_line[2] == 'P') { // if "JMP" *jump = 0x7; } else { error(err_3rd_char); return false; } break; default: error("syntax error: 2nd letter in jump field incorrect\n"); return false; } } else { error("syntax error: jump field doesn't start with 'J'\n"); return false; } return true; } /* Instruction format: 0b111accccccdddjjj * Assumes line begins with actual instruction (prepended whitespace stripped) * TODO: eventually just replace all wasteful c-instruction parsing w/ strcmp() */ static bool parse_c_type(const char *line, uint16_t *instruction) { bool ret = false; char c; const char *dest_start = NULL; const char *comp_start = NULL; const char *jump_start = NULL; size_t i = 0; uint8_t dest = 0; // default value when not present uint8_t comp = 0; uint8_t jump = 0; // default value when not present // set pointers to comp, dest, and/or jump field (if applicable) c = line[0]; for (i = 0; c != ' ' && c != '\t' && c != '\n' && c != '\0'; ++i) { // read until end of line c = line[i]; if (c == '=') { // indicates dest field if (1 <= i && i <= 3) { dest_start = &line[0]; // start of line // this 'i+1' might be dangerous! comp_start = &line[i+1]; // after "[dest]=" } else { error("syntax error: dest incorrect length %lu\n", i); return false; } } else if (c == ';') { // indicates jump field if (1 <= i && i <= 7) { // this 'i+1' might be dangerous! jump_start = &line[i+1]; // after "[comp];" } else { error("syntax error: jump incorrect length %lu\n", i); return false; } } } // Only the comp field is mandatory for assembly instructions; // dest and jump fields are optional, and may/may not be present if (comp_start == NULL) { comp_start = &line[0]; // start of line (no dest field) } ret = parse_c_type_comp(comp_start, &comp); if (!ret) { return false; } if (dest_start != NULL) { ret = parse_c_type_dest(dest_start, &dest); if (!ret) { return false; } } if (jump_start != NULL) { ret = parse_c_type_jump(jump_start, &jump); if (!ret) { return false; } } *instruction = 0xe000 | ((uint16_t)comp << 6) | ((uint16_t)dest << 3) | ((uint16_t)jump); return true; } // does not care about line line length; exits at first newline or after // relevant portion parsed (allows for syntactically-incorrect lines, I know) static bool parse_next_instruction(const char *line, uint16_t *instruction) { bool ret = false; char c; size_t i = 0; while ((c = line[i]) != '\0') { if (c == ' ' || c == '\t') ; // skip any whitespace at start of line else if (c == '@') { ret = parse_a_type(&line[i], instruction); ++g_instruction_number; break; } else if (c >= '!' && c < '~') { ret = parse_c_type(&line[i], instruction); ++g_instruction_number; break; } else { error("syntax error: line '%s' incorrectly formatted\n", line); } ++i; } return ret; } // return false for comment or invalid assembly instruction bool parse_line(const char *line, uint16_t *instruction) { char c; bool slash_found = false; size_t i; // filter out comment lines for (i = 0; (c = line[i]) != '\0'; ++i) { if (c == ' ' || c == '\t') { continue; } else if (i == 0 && c == '\0') { return false; // originally bugfix } else if (c == '/') { if (slash_found) { // second slash means comment return false; } slash_found = true; continue; } else if (slash_found) { // this char not slash, but previous was: invalid syntax error("syntax error: found '/', comments need '//'\n"); return false; } else if (c == '(') { // found label, ignore and return return false; } else { // non-whitespace/slash discovered break; } } // comment not found, so attempting to parse instruction return parse_next_instruction(line, instruction); } char *usage_msg = "Usage: assembler1 [path/to/file.asm]\n"; int main(int argc, char *argv[]) { bool result = false; uint16_t instruction; char in_line[MAX_LINE_LEN]; size_t i, file_line, in_line_len; char *in_file_path; FILE *fp; if (argc != 2) { // requires 1 argument fprintf(stderr, usage_msg); exit(-1); } in_file_path = argv[1]; fp = fopen(in_file_path, "r"); if (fp == NULL) { fprintf(stderr, "failed to open file %s for reading\n", in_file_path); exit(-1); } if(!init_symbol_list()) { fprintf(stderr, "internal: failed to initialize symbol list\n"); exit(-1); } DBGLOG("Symbol initialization complete.\n"); file_line = 1; // first pass to read labels and associate with values while (fgets(in_line, MAX_LINE_LEN, fp) != NULL) { // parse loop for (i = 0; in_line[i] != '\0'; ++i) { // remove newlines if (in_line[i] == '\n' || in_line[i] == '\r') { in_line[i] = '\0'; break; } ++in_line_len; } if (in_line_len == 0 || in_line_len == 1) continue; g_asm_line = in_line; g_asm_line_number = file_line; result = parse_line_for_label(in_line); if (result) { DBGLOG("DEBUG: label found in line %s\n", in_line); } ++file_line; } if (fclose(fp)) { fprintf(stderr, "Error closing file %s. Aborting...\n", in_file_path); } // TODO: keep file open, restart read from beginning fp = fopen(in_file_path, "r"); if (fp == NULL) { fprintf(stderr, "failed to open file %s for reading\n", in_file_path); exit(-1); } file_line = 1; while (fgets(in_line, MAX_LINE_LEN, fp) != NULL) { // parse loop for (i = 0; in_line[i] != '\0'; ++i) { // remove newlines if (in_line[i] == '\n' || in_line[i] == '\r') { in_line[i] = '\0'; break; } ++in_line_len; } if (in_line_len == 0 || in_line_len == 1) continue; g_asm_line = in_line; g_asm_line_number = file_line; result = parse_line(in_line, &instruction); if (result) { print_binary_word16(instruction); putchar('\n'); } ++file_line; } debug_dump_all_symbols(); free_all_symbols(); if (fclose(fp)) { fprintf(stderr, "Failed to close file %s\n", in_file_path); exit(-1); } return 0; } |