KCC - Kayte C Compiler 1.10.0
A C compiler implementation with preprocessor, lexer, parser, and code generator
Loading...
Searching...
No Matches
error.c
1#include "common_includes.h"
2#include "kcc.h"
3#include <stdio.h>
4#include <stdlib.h>
5#include <stdarg.h>
6#include <stdbool.h>
7#include <string.h>
8
9static int g_error_count = 0;
10
11void error_init(void) {
12 g_error_count = 0;
13}
14
15int error_count(void) {
16 return g_error_count;
17}
18
19bool error_has_errors(void) {
20 return g_error_count > 0;
21}
22
23void error_reset(void) {
24 g_error_count = 0;
25}
26
27static const char *error_type_to_string(ErrorType type) {
28 switch (type) {
29 case ERROR_LEXICAL: return "Lexical Error";
30 case ERROR_SYNTAX: return "Syntax Error";
31 case ERROR_SEMANTIC: return "Semantic Error";
32 case ERROR_INTERNAL: return "Internal Error";
33 case ERROR_FATAL: return "Fatal Error";
34 default: return "Unknown Error";
35 }
36}
37
38
39// Helper function to format message using vsnprintf
40static void print_formatted_message(FILE *stream, const char *format, va_list args) {
41 char buffer[1024]; // Adjust size as needed
42
43 // vsnprintf ensures no overflow and works with va_list
44 vsnprintf(buffer, sizeof(buffer), format, args);
45
46 fprintf(stream, "%s", buffer);
47}
48
49void error_fatal(const char *fmt, ...) {
50 va_list args;
51 va_start(args, fmt);
52
53 fprintf(stderr, "FATAL ERROR: ");
54 print_formatted_message(stderr, fmt, args);
55 fprintf(stderr, "\n");
56
57 va_end(args);
58
59 exit(EXIT_FAILURE);
60}
61
62void error_report(ErrorType type, int line, int column, const char *format, ...) {
63 fprintf(stderr, "%s", error_type_to_string(type));
64
65 if (line > 0) {
66 fprintf(stderr, " at line %d", line);
67 if (column > 0) {
68 fprintf(stderr, ", column %d", column);
69 }
70 }
71
72 fprintf(stderr, ": ");
73
74 va_list args;
75 va_start(args, format);
76 print_formatted_message(stderr, format, args);
77 va_end(args);
78
79 fprintf(stderr, "\n");
80
81 g_error_count++;
82
83 if (type == ERROR_FATAL) {
84 exit(EXIT_FAILURE);
85 }
86}
87
88void error_syntax(int line, int column, const char *format, ...) {
89 fprintf(stderr, "Syntax Error at line %d, column %d: ", line, column);
90
91 va_list args;
92 va_start(args, format);
93 print_formatted_message(stderr, format, args);
94 va_end(args);
95
96 fprintf(stderr, "\n");
97 g_error_count++;
98}
99
100void error_semantic(int line, int column, const char *format, ...) {
101 fprintf(stderr, "Semantic Error at line %d, column %d: ", line, column);
102
103 va_list args;
104 va_start(args, format);
105 print_formatted_message(stderr, format, args);
106 va_end(args);
107
108 fprintf(stderr, "\n");
109 g_error_count++;
110}