aboutsummaryrefslogtreecommitdiff
path: root/src/compiler/error_helper/error_helper.c
blob: fd648e42805bab6e75f755c1fa37c3bd527a744c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "error_helper.h"

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>

void printError(char const *error, SourceCode code, char const *begin,
                char const *end, ...) {
  va_list args;
  va_start(args, end);
  char *errorStr;
  vasprintf(&errorStr, error, args);

  char const *lineBegin = code;
  int line = 1;

  char const *iter = code;
  for (; iter < begin; ++iter) {
    const char c = *iter;
    switch (c) {
      case '\0':
        fprintf(stderr,
                "Compiler Internal Error: in printing errors at compiler %s:%d",
                __FILE_NAME__, __LINE__);
        exit(1);
      case '\n':
        lineBegin = iter + 1;
        ++line;
        break;
    }
  }
  char const *lineEnd = end;

  for (;; ++iter) {
    const char c = *iter;
    switch (c) {
      case '\0':
        if (iter < end) {
          fprintf(
              stderr,
              "Compiler Internal Error: in printing errors at compiler %s:%d",
              __FILE_NAME__, __LINE__);
          exit(1);
        }
        lineEnd = iter;
        goto AFTER_LOOP;
      case '\n':
        lineEnd = iter;
        if (iter >= end) {
          goto AFTER_LOOP;
        }
        break;
    }
  }
AFTER_LOOP:

  fprintf(stderr, "Error: %s at line %d\n", errorStr, line);

  int printed = 0;
  for (iter = lineBegin; iter < lineEnd; ++iter) {
    fprintf(stderr, "%c", *iter);
    if (*iter == '\n') {
    PRINT_LINE:
      for (int i = 0; i < printed; ++i) {
        const char *ch = iter - printed + i;
        if (begin <= ch && ch < end) {
          fprintf(stderr, "^");
        } else {
          fprintf(stderr, " ");
        }
      }
      if (iter + 1 != lineEnd) {
        fprintf(stderr, "\n");
        printed = 0;
      }
    } else if (iter + 1 == lineEnd) {
      fprintf(stderr, "\n");
      goto PRINT_LINE;
    } else {
      ++printed;
    }
  }
  fprintf(stderr, "\n");
  free(errorStr);
}