Erythro/src/Errors.c

96 lines
2.7 KiB
C

/*************/
/*GEMWIRE */
/* ERYTHRO*/
/*************/
#include <stdio.h>
#include <Defs.h>
#include <Data.h>
#include <stdarg.h>
void Safe() {
CurrentFile->CurrentSafeColumn = CurrentFile->CurrentColumn - 1;
}
void printLine(FILE* file, int ln) {
char buffer[256];
fgets(buffer, 256, file);
// Line number
printf("%03d|%s", ln + 1, buffer);
}
void printErrorLine(FILE* file, int ln) {
char firstBuffer[256], problemBuffer[256], tailBuffer[256];
// If highlight starts at column 0, don't try to print anything before it
if (CurrentFile->CurrentSafeColumn != 0)
fgets(firstBuffer, CurrentFile->CurrentSafeColumn, file);
// Print the safe column up to current column
fgets(problemBuffer, (CurrentFile->CurrentColumn > CurrentFile->CurrentSafeColumn ? CurrentFile->CurrentColumn - CurrentFile->CurrentSafeColumn : CurrentFile->CurrentColumn), file);
// Print the current column to the end of the line
if (CurrentFile->CurrentColumn > CurrentFile->CurrentSafeColumn)
fgets(tailBuffer, 256, file);
// Line number
printf("%03d|%s\033[0;31m%s\033[0m%s", ln + 1, firstBuffer, problemBuffer, tailBuffer);
}
void printHelpLine(int line, char* message) {
printf(" | %s", message);
}
void ErrorReport(char* message, ...) {
fflush(stdout);
char strbuf[256];
// Resolve varargs to a string
va_list args;
va_start(args, message);
vsprintf(strbuf, message, args);
va_end(args);
int line = CurrentFile->CurrentLine - 1;
FILE* file = fopen(CurrentFile->SourceName, "r");
int errorOnLastLine = CurrentFile->CurrentColumn == 0;
// Print context for the error - up to 2 lines above the error
if (line < 3) {
// If we're at 0 or 1, we need to be careful to not try to print -1 for example.
for (int i = 0; i < line; i++)
printLine(file, i);
} else {
// Skip to line - 2
char buffer[256];
int count = 0;
while (count < line - (errorOnLastLine ? 3 : 2)) {
fgets(buffer, 256, file);
count++;
}
if (errorOnLastLine)
printLine(file, line - 3);
printLine(file, line - 2);
if (!errorOnLastLine) printLine(file, line - 1);
}
if (errorOnLastLine) {
printErrorLine(file, line - 1);
printHelpLine(line, strbuf);
printLine(file, line);
if (!feof(file))
printLine(file, line + 1);
} else {
printErrorLine(file, line);
printHelpLine(line, strbuf);
if (!feof(file))
printLine(file, line + 1);
if (!feof(file))
printLine(file, line + 2);
}
exit(1);
}