all repos — nand2tetris @ d779bea5b6dad359f8817257386a56f2fa13bc0d

my nand2tetris progress

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
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "../bindump.h"

#define DEBUG(...)              printf(__VA_ARGS__)
#define die(err_msg)            perror(err_msg); exit(-1)
#define alert(...)              fprintf(stderr, __VA_ARGS__)

#define MAX_LINE_LEN            256


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;
}

static bool parse_a_type(const char *line, uint16_t *instruction)
{
	char c, a_field_str[6];  // TODO: eventually factor out use of array
	uint32_t a_field = 0;
	size_t i, a = 0;

	if (line[0] != '@') {
		alert("error: A-type instruction doesn't start with @\n");
		return false;
	}

	if (line[1] == '\0') {
		alert("error: A-type instruction empty after @\n");
		return false;
	}

	for (i = 1; (c = line[i]) != '\0' && a < 6; ++i) {
		if ('0' <= c && c <= '9') {
			if (a > 4) {
				alert("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
			alert("syntax error: invalid char '%c' found after @\n",
			      c);
			return false;
		}
	}

	a_field_str[a] = '\0';   // exit

	// TODO: extension: support negative numbers
	a_field = myatoi(a_field_str);
	if (a_field > 32767) {
		alert("error: %u > 32767, too large\n", a_field);
		return false;
	}

	*instruction = 0x0000 | (uint16_t) a_field;
	return true; // STUB, A-type MSB == 0 anyway
}

/* returns dest bits 0b00000ddd
 */
static bool parse_c_type_dest(const char *dest_line, uint8_t *dest)
{
	size_t len;

	for (len = 0; dest_line[len] != '='; ++len) {}  // read until '='

	if (len == 3) {
		if (dest_line[0] == 'A' && dest_line[1] == 'D' &&
		    dest_line[2] == 'M') {
			*dest = 0x7;
		} else {
			alert("syntax error: destination format incorrect\n");
			return false;
		}
	} else if (len == 2) {
		if (dest_line[0] == 'D' && dest_line[1] == 'M') {
			*dest = 0x3;
		} else if (dest_line[0] == 'A' && dest_line[1] == 'M') {
			*dest = 0x5;
		} else if (dest_line[0] == 'A' && dest_line[1] == 'D') {
			*dest = 0x6;
		} else {
			alert("syntax error: destination format incorrect\n");
			return false;
		}
	} else if (len == 1) {
		switch (dest_line[0]) {
		case 'M':
			*dest = 0x1;
			break;
		case 'D':
			*dest = 0x2;
			break;
		case 'A':
			*dest = 0x4;
			break;
		default:
			alert("syntax error: destination format incorrect\n");
			return false;
		}
	} else {
		alert("syntax error: dest field incorrect length %lu\n", len);
		return false;
	}

	return true;
}

/* returns comp bits 0b0acccccc
 */
static bool parse_c_type_comp(const char *comp_line, uint8_t *comp)
{
	size_t len;
	DEBUG("comp_line: %s\n", comp_line);

	*comp = 0x53;  // STUB: 0b01010011
	return true;
}

/* returns jump bits 0b00000jjj
 */
static bool parse_c_type_jump(const char *jump_line, uint8_t *jump)
{
	size_t len;
	char *err_1st_char = "syntax error: jump field doesn't start with 'J'\n";
	char *err_2nd_char = "syntax error: 2nd letter in jump field incorrect\n";
	char *err_3rd_char = "syntax error: 3rd letter in jump field incorrect\n";

	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) {
		alert("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 {
				alert(err_3rd_char); return false;
			}
			break;
		case 'E':                                  // if "JE_"
			if (jump_line[2] == 'Q') {         // if "JEQ"
				*jump = 0x2;
			} else {
				alert(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 {
				alert(err_3rd_char); return false;
			}
			break;
		case 'N':                                  // if "JN_"
			if (jump_line[2] == 'E') {         // if "JNE"
				*jump = 0x5;
			} else {
				alert(err_3rd_char); return false;
			}
			break;
		case 'M':                                  // if "JM_"
			if (jump_line[2] == 'P') {         // if "JMP"
				*jump = 0x7;
			} else {
				alert(err_3rd_char); return false;
			}
			break;
		default:
			alert(err_2nd_char);
			return false;
		}
	} else {
		alert(err_1st_char);
		return false;
	}

	return true;
}

/* Instruction format: 0b111accccccdddjjj
 * Assumes line begins with actual instruction (prepended whitespace stripped)
 */
static bool parse_c_type(const char *line, uint16_t *instruction)
{
	bool ret;
	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

	c = line[0];
	for (i = 0; c != ' ' && c != '\t' &&
	            c != '\n' && c != '\0'; ++i) {
		c = line[i];

		if (c == '=') {
			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 {
				alert("syntax error: destination field"
				      " incorrect length\n");
				return false;
			}
		} else if (c == ';') {
			if (1 <= i && i <= 7) {
				// this 'i+1' might be dangerous!
				jump_start = &line[i+1]; // after "[comp];"
			} else {
				alert("syntax error: jump field incorrect"
				      " length\n");
				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;
	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);
			break;
		} else if (c >= '!' && c < '~') {
			ret = parse_c_type(&line[i], instruction);
			break;
		} else {
			alert("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, size_t line_len, uint16_t *instruction)
{
	char c;
	bool slash_found = false;
	size_t i;

	if (line_len == 0 || line_len == 1)
		return false;

	// filter out comment lines
	//for (i = 0; (c = line[i]) != NULL; ++i) {
	for (i = 0; i < line_len; ++i) {
		c = line[i];

		if (c == ' ' || c == '\t') {
			continue;
		} else if (c == '/') {
			if (slash_found) {
				// second slash means this is a comment
				return false;
			}
			slash_found = true;
			continue;
		} else if (slash_found) {
			// this char not slash, but previous was: invalid syntax
			// TODO: add line, column numbers
			alert("syntax error: found '/', comments need '//'\n");
			return false;
		} else {
			// non-whitespace/slash char 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 in_line_len, i, count;
	char *in_file_path;
	FILE *fp;

	if (argc != 2) {                            // requires 1 argument
		die(usage_msg);
		exit(-1);
	}

	in_file_path = argv[1];
	fp = fopen(in_file_path, "r");
	if (fp == NULL) {
		die("failed to open file for reading\n");
		exit(-1);
	}

	count = 1;
	while (fgets(in_line, MAX_LINE_LEN, fp) != NULL) {
		in_line_len = strlen(in_line);

		for (i = 0; i < in_line_len; ++i) { // remove newlines
			if (in_line[i] == '\n') {
				in_line[i] = '\0';
				break;
			}
		}

		DEBUG("%lu|%s\n", count, in_line);
		result = parse_line(in_line, in_line_len, &instruction);
		if (result) {
			DEBUG("instruction: 0x%x  |  ", instruction);
			bindump_word16(instruction); // output instruction as binary
			putchar('\n');
		}
	++count;
	}

	return 0;
}