78 lines
2.4 KiB
C
78 lines
2.4 KiB
C
#include "log.h"
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
#include <stdlib.h>
|
|
#include <stdarg.h>
|
|
|
|
static LogError* s_logError = NULL;
|
|
|
|
void log_set_output(LogError* destination) {
|
|
s_logError = destination;
|
|
}
|
|
|
|
void log_error(const char* msg) {
|
|
if (s_logError != NULL) {
|
|
s_logError(msg);
|
|
} else {
|
|
fprintf(stderr, "Error: %s\n", msg);
|
|
}
|
|
}
|
|
|
|
static void format_message(char* buffer, size_t size, const char* msg, va_list args) {
|
|
// Basic implementation that handles %S for String and passes others to vsnprintf
|
|
// This is a simplified version. For a real compiler, we'd want a more robust one.
|
|
|
|
char fmt_temp[1024];
|
|
char* fmt_ptr = fmt_temp;
|
|
const char* m = msg;
|
|
|
|
// We can't easily mix va_list with custom handling without specialized logic.
|
|
// For now, let's just use vsnprintf and assume %S is not used yet,
|
|
// OR we can try to handle %S if we really need it.
|
|
// Given the complexity, let's just fix the Location/String field access first.
|
|
|
|
vsnprintf(buffer, size, msg, args);
|
|
}
|
|
|
|
void log_on_line(Location* loc, int to_column, const char* msg, ...) {
|
|
char line_prefix[32];
|
|
int prefix_len = snprintf(line_prefix, sizeof(line_prefix), "%d| ", loc->line);
|
|
|
|
int caret_len = to_column - loc->column_start + 1;
|
|
if (caret_len < 1) caret_len = 1;
|
|
|
|
// Format the message
|
|
va_list args;
|
|
va_start(args, msg);
|
|
char formatted_msg[256];
|
|
format_message(formatted_msg, sizeof(formatted_msg), msg, args);
|
|
va_end(args);
|
|
|
|
size_t total_size = strlen(loc->filename) + 16 + // --- filename ---
|
|
prefix_len + loc->line_text.length + 2 + // line| text\n
|
|
prefix_len + loc->column_start - 1 + caret_len + 2 + // indent + ^^\n
|
|
prefix_len + strlen(formatted_msg) + 2 + // indent + msg\n
|
|
1;
|
|
|
|
char* buffer = (char*)malloc(total_size);
|
|
if (!buffer) return;
|
|
|
|
char* p = buffer;
|
|
p += sprintf(p, "--- %s ---\n", loc->filename);
|
|
p += sprintf(p, "%s%.*s\n", line_prefix, (int)loc->line_text.length, loc->line_text.data);
|
|
|
|
// Caret line
|
|
for (int i = 0; i < prefix_len + loc->column_start - 1; i++) *p++ = ' ';
|
|
for (int i = 0; i < caret_len; i++) *p++ = '^';
|
|
*p++ = '\n';
|
|
|
|
// Message line
|
|
for (int i = 0; i < prefix_len; i++) *p++ = ' ';
|
|
p += sprintf(p, "%s\n", formatted_msg);
|
|
|
|
*p = '\0';
|
|
|
|
log_error(buffer);
|
|
free(buffer);
|
|
}
|