all repos — nand2tetris @ 2fd8ddb880bd1d0e07cd42f8204464c6c4885713

my nand2tetris progress

projects/08/src/codewriter.h

 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
#ifndef _CODEWRITER_H
#define _CODEWRITER_H

// 'codewriter.h' roughly corresponds to the 'CodeWriter' module specified in
// nand2tetris, with a few liberties taken.

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "parser.h"
#include "util.h"

#define _DEBUG

// memory mapping:
// 0-15     virtual registers R0-R15
// 16-255   static variables
// 256-2047 stack
#define SP       (0)   // points to word ahead of top of stack
#define LCL      (1)   // points to local segment
#define ARG      (2)   // points to argument segment
#define POINTER  (3)
#define THIS     (3)
#define THAT     (4)
#define TEMP     (5)
#define R13      (13)  // R13-R15 are scratch space that
#define R14      (14)  //  VM-generated assembly can use
#define R15      (15)  //  for whatever.
#define STATIC   (16)  // start of static variables segment (240 words, 16-255)

char *static_sym_name;

// static segment index indexes into map, retrieves hack assembly symbol offset
#define MAX_STATIC_SYMBOLS  (240)  // for whatever.
uint16_t static_symbol_map[MAX_STATIC_SYMBOLS];
uint8_t g_symbol_offset_bump = 0;  // holds current largest symbol offset, bumps


char comp_vm_funcs[] = "@__comp_funcs_end\n"
                       "0;JMP\n"
                       "\n"
                       "(__test_eq)\n"
                       "@SP\n"
                       "AM=M-1\n"           // RAM[SP]--, A = RAM[SP]
                       "D=M\n"              // D = RAM[SP] (top stack val)
                       "A=A-1\n"            // --A (--> bottom stack val)
                       "D=M-D\n"            // if D == 0, equal
                       "M=0\n"              // prematurely push false
                       "@__test_eq_neq\n"   // if D == 0, equal
                       "D;JNE\n"            // if D != 0, not equal, jump
                       "@SP\n"              // get SP
                       "A=M-1\n"            // get bottom stack val address
                       "M=-1\n"             // push 0xffff (true)
                       "(__test_eq_neq)\n"
                       "@R13\n"               // return address in RAM[R13]
                       "A=M\n"                // A = return address
                       "0;JMP\n"              // return
                       "\n"

                       "(__test_gt)\n"
                       "@SP\n"
                       "AM=M-1\n"           // RAM[SP]--, A = RAM[SP]
                       "D=M\n"              // D = RAM[SP] (top stack val)
                       "A=A-1\n"            // --A (--> bottom stack val)
                       "D=M-D\n"            // if (D - M) > 0; push true
                       "M=0\n"              // prematurely push false
                       "@__test_gt_neq\n"   // if D == 0, equal
                       "D;JLE\n"            // if D != 0, not equal, jump
                       "@SP\n"              // get SP
                       "A=M-1\n"            // get bottom stack val address
                       "M=-1\n"             // push 0xffff (true)
                       "(__test_gt_neq)\n"
                       "@R13\n"               // return address in RAM[R13]
                       "A=M\n"                // A = return address
                       "0;JMP\n"              // return
                       "\n"

                       "(__test_lt)\n"
                       "@SP\n"
                       "AM=M-1\n"           // RAM[SP]--, A = RAM[SP]
                       "D=M\n"              // D = RAM[SP] (top stack val)
                       "A=A-1\n"            // --A (--> bottom stack val)
                       "D=M-D\n"            // if (D - M) < 0; push true
                       "M=0\n"              // prematurely push false
                       "@__test_lt_neq\n"   // if D == 0, equal
                       "D;JGE\n"            // if D != 0, not equal, jump
                       "@SP\n"              // get SP
                       "A=M-1\n"            // get bottom stack val address
                       "M=-1\n"             // push 0xffff (true)
                       "(__test_lt_neq)\n"
                       "@R13\n"               // return address in RAM[R13]
                       "A=M\n"                // A = return address
                       "0;JMP\n"              // return
                       "\n"
                       "(__comp_funcs_end)\n";

char vm_init[] = "@256\n"       // start address of stack (nothing pushed yet)
                 "D=A\n"        // D = 256
                 "@SP\n"        // A = <constant representing address of SP>
                 "M=D\n"        // <memory pointed to by SP> = 256
                 "@Sys.init\n"  // jump to Sys.init function (not call since
                 "0;JMP\n\n";   // we don't need to set up the stack)
// TODO: add initializers for argument, local, static, constant, this, that

// TODO only output vm_stop when Main.main
char vm_stop[] = "(END)\n"   // starting address of stack (nothing pushed yet)
                 "@END\n"    // D = 256
                 "0;JMP\n";  // A = <constant representing address of SP>

void write_vm_init(FILE *fp)
{
	fprintf(fp, "%s", vm_init);  // can (un)comment to toggle init behavior
	fprintf(fp, "%s\n", comp_vm_funcs);
}

void write_vm_stop(FILE *fp)
{
	fprintf(fp, "\n%s", vm_stop);
}

static bool write_arithmetic(struct vm_instruction_t *vm_instr, FILE *fp)
{
	char binary_op_template[] = "@SP\n"
	                            "AM=M-1\n"  // RAM[SP]--, A = RAM[SP]
	                            "D=M\n"     // D = RAM[SP] (top stack val)
	                            "A=A-1\n"   // --A (--> bottom stack val)
	                            "%s";       // arithmetic op goes here
	char unary_op_template[] = "@SP\n"
	                           "A=M-1\n"    // A = SP - 1
	                           "%s";        // arithmetic op goes here

	char op_add[] = "M=D+M\n";
	char op_sub[] = "M=M-D\n";

	char op_eq[]  = "@%s_%lu_eq\n"   // <- static_sym_name, file_line_number
	                "D=A\n"
	                "@R13\n"
	                "M=D\n"
	                "@__test_eq\n"
	                "0;JMP\n"
	                "(%s_%lu_eq)\n" // return here
	                "\n";
	char op_gt[]  = "@%s_%lu_gt\n"  // <- static_sym_name, file_line_number
	                "D=A\n"
	                "@R13\n"
	                "M=D\n"
	                "@__test_gt\n"
	                "0;JMP\n"
	                "(%s_%lu_gt)\n" // return here
	                "\n";
	char op_lt[]  = "@%s_%lu_lt\n"  // <- static_sym_name, file_line_number
	                "D=A\n"
	                "@R13\n"
	                "M=D\n"
	                "@__test_lt\n"
	                "0;JMP\n"
	                "(%s_%lu_lt)\n" // return here
	                "\n";

	char op_and[] = "M=D&M\n";
	char op_or[]  = "M=D|M\n";

	char op_neg[] = "M=-M\n";
	char op_not[] = "M=!M\n";

	// binary operations
	if (!strncmp(vm_instr->arg1, "add", CMD_STR_MAX_LEN)) {
		fprintf(fp, binary_op_template, op_add);
	} else if (!strncmp(vm_instr->arg1, "sub", CMD_STR_MAX_LEN)) {
		fprintf(fp, binary_op_template, op_sub);
	} else if (!strncmp(vm_instr->arg1, "eq", CMD_STR_MAX_LEN)) {
		fprintf(fp, op_eq, static_sym_name, file_line_no,
		                   static_sym_name, file_line_no);
	} else if (!strncmp(vm_instr->arg1, "gt", CMD_STR_MAX_LEN)) {
		fprintf(fp, op_gt, static_sym_name, file_line_no,
		                   static_sym_name, file_line_no);
	} else if (!strncmp(vm_instr->arg1, "lt", CMD_STR_MAX_LEN)) {
		fprintf(fp, op_lt, static_sym_name, file_line_no,
		                   static_sym_name, file_line_no);
	} else if (!strncmp(vm_instr->arg1, "and", CMD_STR_MAX_LEN)) {
		fprintf(fp, binary_op_template, op_and);
	} else if (!strncmp(vm_instr->arg1, "or", CMD_STR_MAX_LEN)) {
		fprintf(fp, binary_op_template, op_or);
	// unary operations
	} else if (!strncmp(vm_instr->arg1, "neg", CMD_STR_MAX_LEN)) {
		fprintf(fp, unary_op_template, op_neg);
	} else if (!strncmp(vm_instr->arg1, "not", CMD_STR_MAX_LEN)) {
		fprintf(fp, unary_op_template, op_not);
	} else {
		err("error: invalid arithmetic op \"%s\"\n", vm_instr->arg1);
		return false;
	}

	return true;
}

static bool resolve_static_address(struct vm_instruction_t *vm_instr,
                                   uint16_t *addr)
{
	uint16_t symbol_offset;
	if (vm_instr->arg2 >= MAX_STATIC_SYMBOLS) {
		err("error: arg2 too large, >= %u\n", MAX_STATIC_SYMBOLS);
		return false;
	}

	symbol_offset = static_symbol_map[vm_instr->arg2];
	if (symbol_offset == 0xffff) {  // new offset not in map (-1 special)
		if (g_symbol_offset_bump >= MAX_STATIC_SYMBOLS) {
			err("error: symbol offset grew too large (>= %u), "
			    "too many static variables\n", MAX_STATIC_SYMBOLS);
			return false;
		}
		static_symbol_map[vm_instr->arg2] = g_symbol_offset_bump;
		*addr = g_symbol_offset_bump;
		++g_symbol_offset_bump;  // bump global symbol offset
	} else {
		// offset found in map, return symbol value/index
		*addr = symbol_offset;
	}

	return true;
}

// push 16-bit value from segment offset onto top of stack
static bool write_push(struct vm_instruction_t *vm_instr, FILE *fp)
{
	uint16_t addr, arg2 = vm_instr->arg2;

	// TODO: could add SP counter/check to catch overflows
	char const_template[] = "@%hu\n"       // A = constant
	                        "D=A\n%s";     // D = constant
	char addr_template[] = "@%hu\n"        // A = segment + index
	                       "D=M\n%s";      // D = RAM[segment + index]
	char static_template[] = "@%s.%hu\n"   // A = segment + index
	                         "D=M\n%s";    // D = RAM[segment + index]
	char indirect_template[] = "@%hu\n"    // A = segment
	                           "D=M\n"     // D = RAM[segment]
	                           "@%hu\n"    // A = index
	                           "A=A+D\n"   // A = segment + index
	                           "D=M\n%s";  // D = RAM[segment + index]
	char push_boilerplate[] = "@SP\n"
	                          "M=M+1\n"   // RAM[SP]++    // inc SP
	                          "A=M-1\n"   // A = RAM[SP] - 1 // prev top
	                          "M=D\n";    // RAM[SP] = constant

	if (!strcmp(vm_instr->arg1, "constant")) {
		// TODO: check size of constant (allowed to be > 32,767?)
		// TODO: look in nand2tetris forums in case issue already noted
		fprintf(fp, const_template, arg2, push_boilerplate);
	} else if (!strcmp(vm_instr->arg1, "argument")) {
		fprintf(fp, indirect_template, ARG, arg2, push_boilerplate);
	} else if (!strcmp(vm_instr->arg1, "local")) {
		fprintf(fp, indirect_template, LCL, arg2, push_boilerplate);
	} else if (!strcmp(vm_instr->arg1, "static")) {
		if (!resolve_static_address(vm_instr, &addr)) {
			return false;
		}
		fprintf(fp, static_template, static_sym_name, addr,
		        push_boilerplate);
	} else if (!strcmp(vm_instr->arg1, "this")) {
		fprintf(fp, indirect_template, THIS, arg2, push_boilerplate);
	} else if (!strcmp(vm_instr->arg1, "that")) {
		fprintf(fp, indirect_template, THAT, arg2, push_boilerplate);
	} else if (!strcmp(vm_instr->arg1, "pointer")) {
		addr = POINTER + vm_instr->arg2;
		fprintf(fp, addr_template, addr, push_boilerplate);
	} else if (!strcmp(vm_instr->arg1, "temp")) {
		addr = TEMP + vm_instr->arg2;
		fprintf(fp, addr_template, addr, push_boilerplate);
	} else {
		err("error: invalid segment name \"%s\"\n",
		    vm_instr->arg1);
		return false;
	}

	return true;
}

// pop 16-bit value from top of stack into segment offset
static bool write_pop(struct vm_instruction_t *vm_instr, FILE *fp)
{
	// TODO: could add SP counter/check to catch overflows
	uint16_t addr, arg2 = vm_instr->arg2;
	char pop_indirect_template[] = "@%hu\n"    // @segment
	                               "D=M\n"     // D = segment
	                               "@%hu\n"    // @index
	                               "D=A+D\n"   // A = segment + index
	                               "@R13\n"
	                               "M=D\n"     // RAM[13] = segment + index
	                               "@SP\n"     // 
	                               "AM=M-1\n"  // 
	                               "D=M\n"     // 
	                               "@R13\n"    // 
	                               "A=M\n"     // 
	                               "M=D\n";    // 
	char pop_addr_template[] = "@SP\n"
	                           "AM=M-1\n"    // decrement SP
	                           "D=M\n"       // "pop" (read) value into D
	                           "@%hu\n"      // load address
	                           "M=D\n";      // "pop" (write) value to RAM
	char pop_static_template[] = "@SP\n"
	                             "AM=M-1\n"   // decrement SP
	                             "D=M\n"      // "pop" (read) value into D
	                             "@%s.%hu\n"  // A = segment + index
	                             "M=D\n";     // RAM[segment + index] = D

	if (!strcmp(vm_instr->arg1, "argument")) {
		fprintf(fp, pop_indirect_template, ARG, arg2);
	} else if (!strcmp(vm_instr->arg1, "local")) {
		fprintf(fp, pop_indirect_template, LCL, arg2);
	} else if (!strcmp(vm_instr->arg1, "static")) {
		if (!resolve_static_address(vm_instr, &addr)) {
			return false;
		}
		fprintf(fp, pop_static_template, static_sym_name, addr);
	} else if (!strcmp(vm_instr->arg1, "this")) {
		fprintf(fp, pop_indirect_template, THIS, arg2);
	} else if (!strcmp(vm_instr->arg1, "that")) {
		fprintf(fp, pop_indirect_template, THAT, arg2);
	} else if (!strcmp(vm_instr->arg1, "pointer")) {
		addr = POINTER + vm_instr->arg2;
		fprintf(fp, pop_addr_template, addr);
	} else if (!strcmp(vm_instr->arg1, "temp")) {
		addr = TEMP + vm_instr->arg2;
		fprintf(fp, pop_addr_template, addr);
	} else {
		err("error: invalid segment name \"%s\"\n",
		    vm_instr->arg1);
		return false;
	}

	return true;
}

static bool write_label(struct vm_instruction_t *vm_instr, FILE *fp)
{
	char label_asm[] = "(%s)\n";
	fprintf(fp, label_asm, vm_instr->arg1);
	return true;
}

static bool write_goto(struct vm_instruction_t *vm_instr, FILE *fp)
{
	char goto_asm[] = "@%s\n"
	                  "0;JMP\n";
	fprintf(fp, goto_asm, vm_instr->arg1);
	return true;
}

static bool write_if(struct vm_instruction_t *vm_instr, FILE *fp)
{
	char if_asm[] = "@SP\n"  // pop register D
	                "AM=M-1\n"
	                "D=M\n"     // pop value into D register
	                "@%s\n"
	                "D;JNE\n";
	fprintf(fp, if_asm, vm_instr->arg1);
	return true;
}

//////////
//
// The Elements of Computing Systems, 2nd edition, pg. 214
//
//      CALLING CONVENTIONS STACK DIAGRAM
//     ===================================
// Low memory addresses
//
//       ... similar blocks above ...
//          |--------------------| \
//          |  some value        |  | Local variables/working stack of _caller_
//          |--------------------|  | 
//          |  some value        |  | 
//          |--------------------| <  -------- BEGIN FUNCTION CALL --------
//   ARG -> |  argument 0        |  | Argument segment of _callee_:
//          |--------------------|  |     Pushed by caller before calling
//          |  argument 1        |  |     callee using 'call' command.
//          |--------------------|  | 
//          |       ...          |  | 
//          |--------------------| < 
// LCL-5 -> |  return address    |  | Saved frame of _caller_:
//          |--------------------|  |     Pushed by the VM when handling
// LCL-4 -> |  saved LCL         |  |     the 'call' command.
//          |--------------------|  |     When handling 'return', the VM
// LCL-3 -> |  saved ARG         |  |     pops these values and uses them
//          |--------------------|  |     for restoring the memory segments
// LCL-2 -> |  saved THIS        |  |     of, and returning to, the caller's
//          |--------------------|  |     code.
// LCL-1 -> |  saved THAT        |  | 
//          |--------------------| < 
//   LCL -> |  local 0           |  | The local segment of _callee_:
//          |--------------------|  |     Initialized by the VM when handling
//          |  local 1           |  |     the 'function' command.
//          |--------------------|  | 
//          |  working stack...  |  | Working stack of _callee_
//          |--------------------| < 
//    SP -> |   < undefined >    |  | 
//          +--------------------+  | 
//                   _||_           | 
// direction stack   \  /          /
// grows (up)         \/
//
// High memory addresses
//

static bool write_function(struct vm_instruction_t *vm_instr, FILE *fp)
{
	size_t i, num_locals;
	num_locals = vm_instr->arg2;
	char set_local_boilerplate[] = "M=0\n"
	                               "A=A+1\n";
	char set_sp[] =                "D=A\n"     // D = number of locals
	                               "@SP\n"     // get address of SP
	                               "M=D\n";    // set SP to new value

	// (functionName)       // injects function entry label into the code
	// repeat nVars times:  // nVars = number of local variables
	//     push 0           // initializes local variable to 0
	fprintf(fp, "(%s)\n", vm_instr->arg1);  // write function label
	fprintf(fp, "@SP\n");                   // get SP
	for (i = 0; i < num_locals; ++i) {
		fprintf(fp, "%s", set_local_boilerplate);  // write 'push 0'
	}
	fprintf(fp, "%s", set_sp);

	return true;
}

static bool write_return(FILE *fp)
{
	/*
	 * frame = LCL             // frame is a temporary variable
	 * retAddr = *(frame - 5)  // put return address in a temporary variable
	 * *ARG = pop()            // repositions the return value for the caller
	 * SP = ARG+1              // repositions SP for the caller
	 * THAT = *(frame - 1)     // restores THAT for the caller
	 * THIS = *(frame - 2)     // restores THIS for the caller
	 * ARG = *(frame - 3)      // restores ARG for the caller
	 * LCL = *(frame - 4)      // restores LCL for the caller
	 * goto retAddr            // jump to where return address points
	 */
	char ret_boilerplate[] = "// *ARG = pop()\n"
	                         "@SP\n"
	                         "AM=M-1\n"  // decrement A and SP
	                         "D=M\n"     // "pop" (read) return value into D
	                         "@ARG\n"
	                         "A=M\n"     // A points to argument segment
	                         "M=D\n"     // *ARG = D // (D = pop())
	                         "// SP = ARG+1\n"
	                         "D=A+1\n"   // A still contains arg pointer
	                         "@SP\n"
	                         "M=D\n"
	                         "// frame = LCL\n"
	                         "// THAT = *(frame - 1)\n"
	                         "@LCL\n"
	                         "AM=M-1\n"  // decrement A and LCL
	                         "D=M\n"     // D = *(frame - 1)
	                         "@THAT\n"
	                         "M=D\n"     // THAT = D
	                         "// THIS = *(frame - 2)\n"
	                         "@LCL\n"
	                         "AM=M-1\n"  // decrement A and LCL
	                         "D=M\n"     // D = *(frame - 2)
	                         "@THIS\n"
	                         "M=D\n"
	                         "// ARG = *(frame - 3)\n"
	                         "@LCL\n"
	                         "AM=M-1\n"  // decrement A and LCL
	                         "D=M\n"     // D = *(frame - 3)
	                         "@ARG\n"
	                         "M=D\n"
	                         "// R13 = retAddr = *(frame - 5)\n"
	                         "@LCL\n"
	                         "AM=M-1\n"  // decrement A and LCL
	                                     // now LCL = LCL - 4
	                         "D=M-1\n"   // D = *(frame - 4 - 1)
	                         "@R13\n"
	                         "M=D\n"     // R13 = D (retAddr)
	                         "// LCL = *(frame - 4)\n"
	                         "@LCL\n"
	                         "A=M\n"     // put pointer in address reg.
	                         "D=M\n"     // D = prev. LCL value
	                         "@LCL\n"
	                         "M=D\n"     // write prev LCL value to LCL
	                         "// goto retAddr\n"
	                         "@R13\n"     // location of retAddr
	                         "A=M\n"      // A = retAddr
	                         "0;JMP\n"    // return
	                         "\n";

	fprintf(fp, "%s", ret_boilerplate);
	return true;
}

static bool write_call(struct vm_instruction_t *vm_instr, FILE *fp)
{
	uint16_t new_arg;
	/*
	 * push retAddr          // generates a label and pushes it to the stack
	 * push LCL              // saves LCL of caller
	 * push ARG              // saves ARG of caller
	 * push THIS             // saves THIS of caller
	 * push THAT             // saves THAT of caller
	 * ARG = SP - 5 - nArgs  // repositions ARG
	 * LCL = SP              // repositions LCL
	 * goto functionName     // transfers control to the callee
	 * (retAddr)             // injects the return address label into the code
	 */
	// Note: I use a different convention for generating return address
	// labels. The book does FilenameFunctionname$ret.<0-n> for n returns,
	// but the extra bookkeeping will annoy me. So I'll just use the current
	// line number instead. This works because the function name also
	// contains the file name, and the file name combined with a line number
	// provides a uniqueness guarantee, so return addresses won't collide.
	char call_boilerplate[] = "// push retAddr\n"
	                          "@%s.%hu\n"     // will format to retAddr
	                          "D=A\n"         // D = retAddr as constant
	                          "@SP\n"
	                          "M=M+1\n"       // RAM[SP]++    // inc SP
	                          "A=M-1\n"       // A = RAM[SP] - 1 // prev top
	                          "M=D\n"         // RAM[SP] = local pointer
	                          "// push LCL\n"
	                          "@LCL\n"
	                          "D=M\n"         // D = current local pointer
	                          "@SP\n"
	                          "M=M+1\n"       // RAM[SP]++    // inc SP
	                          "A=M-1\n"       // A = RAM[SP] - 1 // prev top
	                          "M=D\n"         // RAM[SP] = arg pointer
	                          "// push ARG\n"
	                          "@ARG\n"
	                          "D=M\n"         // D = current arg pointer
	                          "@SP\n"
	                          "M=M+1\n"       // RAM[SP]++    // inc SP
	                          "A=M-1\n"       // A = RAM[SP] - 1 // prev top
	                          "M=D\n"         // RAM[SP] = arg
	                          "// push THIS\n"
	                          "@THIS\n"
	                          "D=M\n"         // D = current this
	                          "@SP\n"
	                          "M=M+1\n"       // RAM[SP]++    // inc SP
	                          "A=M-1\n"       // A = RAM[SP] - 1 // prev top
	                          "M=D\n"         // RAM[SP] = this
	                          "// push THAT\n"
	                          "@THAT\n"
	                          "D=M\n"         // D = current that
	                          "@SP\n"
	                          "M=M+1\n"       // RAM[SP]++    // inc SP
	                          "A=M-1\n"       // A = RAM[SP] - 1 // prev top
	                          "M=D\n"         // RAM[SP] = that
	                          "// ARG = SP - 5 - nArgs\n"
	                          "@SP\n"
	                          "D=M\n"         // D = SP
	                          "@%hu\n"        // will format to (5 + nArgs)
	                          "D=D-A\n"       // D = SP - 5 - nArgs
	                          "@ARG\n"
	                          "M=D\n"
	                          "// LCL = SP\n"
	                          "@SP\n"
	                          "D=M\n"         // D = SP
	                          "@LCL\n"
	                          "M=D\n"         // LCL = SP
	                          "// goto functionName\n"
	                          "@%s\n"
	                          "0;JMP\n"
	                          "// (retAddr)\n"
	                          "(%s.%hu)\n"
	                          "\n";

	//print_vm_instruction(vm_instr, fp);  // TODO remove me
	new_arg = 5 + vm_instr->arg2;  // probably breaks if arg2 > 32K lmfao
	fprintf(fp, call_boilerplate, vm_instr->arg1, file_line_no,
	                              new_arg, vm_instr->arg1,
	                              vm_instr->arg1, file_line_no);
	return true;
}

bool write_instruction(struct vm_instruction_t *vm_instr, FILE *fp)
{
	fprintf(fp, "\n// %lu: %s\n", file_line_no, vm_instr->line);

	switch (vm_instr->cmd) {
	case C_ARITHMETIC:
		return write_arithmetic(vm_instr, fp);
	case C_PUSH:
		return write_push(vm_instr, fp);
	case C_POP:
		return write_pop(vm_instr, fp);
	case C_LABEL:
		return write_label(vm_instr, fp);
	case C_GOTO:
		return write_goto(vm_instr, fp);
	case C_IF:
		return write_if(vm_instr, fp);
	case C_FUNCTION:
		return write_function(vm_instr, fp);
	case C_RETURN:
		return write_return(fp);
	case C_CALL:
		return write_call(vm_instr, fp);
	default:
		err("error: unrecognized instruction (%u)\n", vm_instr->cmd);
		return false;
	}

	return false;  // should never reach here tbh
}

#endif // _CODEWRITER_H