Assembler/src/error_analyzer.c
2023-09-07 18:41:46 +02:00

123 lines
3.7 KiB
C

#include "../header/error_analyzer.h"
#include "../header/instruction_table.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
unsigned int check_token_errors(char tokens[][MAX_TOKEN_SIZE], shash_hashtable_t instruction_information_table, shash_hashtable_t label_table)
{
printf("=====================\nErrors found:\n");
unsigned int error_count = 0;
for (int i = 0; tokens[i][0] != EOF; i++)
{
instruction_information_t *current_token_info = shash_get(tokens[i], (unsigned int)strlen(tokens[i]), &instruction_information_table);
if (current_token_info == NULL)
{
// Couldn't find the instruction
printf("ERROR: Insruction %s does not exist\n", tokens[i]);
error_count++;
// Loop to the next ;
for (; tokens[i][0] != ';'; i++)
{
if (tokens[i][0] == EOF)
break;
}
continue;
}
if (current_token_info->requires_adress == 1)
{
switch (current_token_info->supports_adress_label)
{
case 1:
{
// Check label at next token
i++;
// Only execute the label recognition if the adress part is not a number/is a label
if(atoi(tokens[i]) == 0)
{
unsigned int *label_addr = shash_get(tokens[i], strlen(tokens[i]), &label_table);
if(label_addr == NULL)
{
printf("ERROR: Label %s has not been defined (Used at token %d)\n", tokens[i], i);
}
// Check that the next token is a ;
i++;
if (tokens[i][0] != ';')
{
printf("ERROR: Expected end of instruction at %d but found \"%s\"\n", i, tokens[i]);
error_count++;
// Loop to the next ;
for (; tokens[i][0] != ';'; i++)
{
if (tokens[i][0] == EOF)
break;
}
}
break;
}
}
case 0:
{
// Check the adress stored at the next token
i++;
if(tokens[i][0] == ';')
{
printf("ERROR: expected adress at token %d\n", i);
error_count++;
break;
}
int adress = atoi(tokens[i]);
if (adress > MAX_MEMORY || adress < 1)
{
printf("ERROR: Adress %s at token %d is invalid\n", tokens[i], i);
error_count++;
}
// Check that the next token is a ;
i++;
if (tokens[i][0] != ';')
{
printf("ERROR: Expected end of instruction at %d but found \"%s\"\n", i, tokens[i]);
error_count++;
// Loop to the next ;
for (; tokens[i][0] != ';'; i++)
{
if (tokens[i][0] == EOF)
break;
}
}
break;
}
}
}
else
{
// Check that the next token is a ;
i++;
if (tokens[i][0] != ';')
{
printf("ERROR: Expected end of instruction at %d but found \"%s\"\n", i, tokens[i]);
error_count++;
// Loop to the next ;
for (; tokens[i][0] != ';'; i++)
{
if (tokens[i][0] == EOF)
break;
}
}
}
}
return error_count;
}