CS-PROJECTS / c02_assembler / SymbolTable.c
SymbolTable.c
Raw
#include "SymbolTable.h"

#include <inttypes.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>

DataSymbol dataSymbols[NUM_SYMBOLS] = {0};
TextSymbol textSymbols[NUM_SYMBOLS] = {0};

void makeTable(FILE *outF)
{
   int x = -1, j = -1, i = 0;

   while (dataSymbols[i].binary)
   {
      char key[sizeof(dataSymbols[i].key) + 1];

      j = -1;
      while (dataSymbols[i].key[++j] != 0)
         key[j] = dataSymbols[i].key[j];

      fprintf(outF, "0x%08X\t%s\n", dataSymbols[i++].address, key);
   }

   while (textSymbols[++x].key != NULL)
      fprintf(outF, "0x%08X\t%s\n", textSymbols[x].address, textSymbols[x].key);
}

void cleanTable()
{
   int i = -1, x = -1;
   while (dataSymbols[++i].binary)
      free(dataSymbols[i].binary),
          free(dataSymbols[i].type);
   while (textSymbols[++x].key)
      free(textSymbols[x].key);
}

char *decToBinary(char *dec)
{
   int16_t n = atol(dec);
   int i = 0, s = 15;
   char *binaryNum = calloc(IMM_LENGTH, sizeof(char));
   while (s >= 0)
      binaryNum[i++] = ((n >> s--) & 1) ? '1' : '0';
   return binaryNum;
}

char *decToBinary26(char *dec)
{
   int n = atoi(dec), i = 0, s = 25;
   char *binaryNum = calloc(27, sizeof(char));
   while (s >= 0)
      binaryNum[i++] = ((n >> s--) & 1) ? '1' : '0';
   return binaryNum;
}

char *unDecToBinary(char *dec)
{
   uint16_t n;
   sscanf(dec, "%hd", &n);
   int i = 0, s = 15;
   char *binaryNum = calloc(IMM_LENGTH, sizeof(char));
   while (s >= 0)
      binaryNum[i++] = ((n >> s--) & 1) ? '1' : '0';
   return binaryNum;
}

uint16_t findImm(char *word)
{
   int i = -1;
   while (dataSymbols[++i].binary)
      if (!strcmp(word, dataSymbols[i].key))
         return dataSymbols[i].address;
   return 0;
}