all repos — nand2tetris @ aebb96453a070c3eb8f4e0fe82b8ae3e46d181bb

my nand2tetris progress

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

#define DBGLOG printf

#define symbol_char_ok(c) (('0' <= c && c <= '9') || ('A' <= c && c <= 'Z') \
                        || ('a' <= c && c <= 'z') || c == '_' || c == '.'   \
                                                  || c == '$' || c == ':')

#define error(...) fprintf(stderr, __VA_ARGS__)
#define die(...)   do { fprintf(stderr, __VA_ARGS__); exit(-1); } while (0)

#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;  // (TODO), used to be g_instruction_number

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;


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

// TODO refactor
void binprint_rom(uint16_t *rom, size_t rom_size)
{
	size_t i;
	printf("rom_index = %lu, rom_size = %lu\n", rom_index, rom_size);
	for (i = 0; i < rom_size; ++i) {
		print_binary_word16(rom[i]);
		putchar('\n');
	}
}

/*
static uint32_t myatoi(const char *str)
{
	size_t i;
	uint32_t ret = 0;

	for (i = 0; i < 5 && '0' <= str[i] && str[i] <= '9'; ++i) {
		ret = (ret * 10) + (str[i] - 0x30);
	}

	return ret;
}
*/

size_t skip_whitespace(const char *line, size_t n)
{
	size_t i = 0;
	while ((line[i] == ' ' || line[i] == '\t') && i < n)
		++i;
	return i;
}

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

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]; // TODO: double check
		}
	}
	return NULL;
}

bool add_symbol(const char *str, uint16_t val)
{
	uint16_t tmp;

	if (symbol_index > 32767) {
		// TODO: print appropriate error message
		return false;
	}

	if (lookup_symbol(str, &tmp) != NULL) {
		// TODO: print appropriate error message
		return false;
	}

	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
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])) {
			error("error: failed to initialize reserved symbols\n");
			return false;
		}
	}

	return true;
}

// assumes line[0] == '('
bool parse_line_for_label(const char *line) {
	size_t i;
	char c, label_str[MAX_SYMBOL_LEN + 1];

	DBGLOG("parsing label: line %lu | %s\n", file_line_no, line);
	for (i = 1; i < MAX_SYMBOL_LEN; ++i) {
		c = line[i];
		if (c == '\0' || c == ')')
			break;
		if (!symbol_char_ok(c)) {
			error("error: label contains invalid char %c\n", c);
			return false;
		}
		label_str[i - 1] = line[i];
	}

	if (c != ')') {
		error("error: no matching ')' found for label\n");
		return false;
	}

	label_str[i - 1] = '\0';

	//return add_symbol(label_str, 65);
	return add_symbol(label_str, (uint16_t)instruction_offset);
}

bool parse_instruction(const char *line, uint16_t *instruction)
{
	static uint16_t val = 0x56;
	DBGLOG("parsing instruction in line %lu | %s\n", file_line_no, line);
	*instruction = val++;
	return true; // STUB TODO: remove
}

// 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 result = true; 
	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;
	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)];

		// remove newlines and get line length
		line_len = 0;
		for (i = 0; line[i] != '\0'; ++i) {
			if (line[i] == '\n' || line[i] == '\r') {
				line[i] = '\0';
				break;
			}
			++line_len;
		}

		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))
					result = false;
			} else
				continue;
		} else {
			if (!first_pass) {
				if (parse_instruction(line, &instruction))
					rom[rom_index++] = instruction;
			}
			++instruction_offset;
			continue;  // first pass: if not label, ignore line
		}
	}

	if (first_pass)
		debug_dump_all_symbols();

	return result;
}


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");

	DBGLOG("FIRST PASS\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
	binprint_rom(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;
}