refactor a couple things
This commit is contained in:
95
src/assembler/program.c
Normal file
95
src/assembler/program.c
Normal file
@@ -0,0 +1,95 @@
|
||||
#include "program.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
Program newProgram(void) {
|
||||
Program program = {
|
||||
.at = malloc(sizeof(Instruction) * 16),
|
||||
.len = 0,
|
||||
.capacity = 16,
|
||||
.labels = {
|
||||
.at = malloc(sizeof(Instruction) * 16),
|
||||
.len = 0,
|
||||
.capacity = 16,
|
||||
}
|
||||
};
|
||||
|
||||
if (program.at == NULL || program.labels.at == NULL) {
|
||||
fprintf(stderr, "malloc failed while creating new program\n");
|
||||
exit(1);
|
||||
}
|
||||
return program;
|
||||
}
|
||||
|
||||
void addInstructionToProgram(Program* program, Instruction inst) {
|
||||
if (program->at == NULL) {
|
||||
fprintf(stderr, "unexpected NULL value when adding instruction to program\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (program->len + 1 >= program->capacity) {
|
||||
Instruction* tmp = malloc(sizeof(Instruction) * program->capacity * 2);
|
||||
if (tmp == NULL) {
|
||||
fprintf(stderr, "malloc failed while expanding program\n");
|
||||
exit(1);
|
||||
}
|
||||
program->at = tmp;
|
||||
program->capacity *= 2;
|
||||
}
|
||||
|
||||
program->at[program->len] = inst;
|
||||
program->len++;
|
||||
}
|
||||
|
||||
void addLabelToProgram(Program* program, const char* name, uint8_t position) {
|
||||
if (program->labels.at == NULL) {
|
||||
fprintf(stderr, "unexpected NULL value when adding label to program\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
if (program->labels.len + 1 >= program->labels.capacity) {
|
||||
Label* tmp = malloc(sizeof(Label) * program->labels.capacity * 2);
|
||||
if (tmp == NULL) {
|
||||
fprintf(stderr, "malloc failed while expanding program labels\n");
|
||||
exit(1);
|
||||
}
|
||||
program->labels.at = tmp;
|
||||
program->labels.capacity *= 2;
|
||||
}
|
||||
|
||||
char* nameCopy = malloc(strlen(name) + 1);
|
||||
if (nameCopy == NULL) {
|
||||
fprintf(stderr, "malloc failed while expanding program labels\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
strcpy(nameCopy, name);
|
||||
|
||||
program->labels.at[program->labels.len] = (Label) {
|
||||
.name = nameCopy,
|
||||
.position = position
|
||||
};
|
||||
program->labels.len++;
|
||||
}
|
||||
|
||||
void freeProgram(Program* program) {
|
||||
if (program->at != NULL) {
|
||||
free(program->at);
|
||||
}
|
||||
program->at = NULL;
|
||||
program->capacity = 0;
|
||||
program->len = 0;
|
||||
|
||||
if (program->labels.at != NULL) {
|
||||
for (size_t i = 0; i < program->labels.len; i++) {
|
||||
free(program->labels.at[i].name);
|
||||
}
|
||||
free(program->labels.at);
|
||||
}
|
||||
program->labels.at = NULL;
|
||||
program->labels.capacity = 0;
|
||||
program->labels.len = 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user