You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

error.c 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "parse/parse.h"
  2. #include <stdio.h>
  3. #include <stdarg.h>
  4. #include "trace.h"
  5. void l2_parse_err(struct l2_parse_error *err, struct l2_token *tok, const char *fmt, ...) {
  6. err->line = tok->line;
  7. err->is_static = 0;
  8. err->ch = tok->ch;
  9. if (l2_token_get_kind(tok) == L2_TOK_ERROR) {
  10. l2_trace("Error token: %s", tok->v.str);
  11. err->message = tok->v.str;
  12. err->is_static = 1;
  13. return;
  14. }
  15. char buf[256];
  16. va_list va;
  17. va_start(va, fmt);
  18. int n = vsnprintf(buf, sizeof(buf), fmt, va);
  19. if (n < 0) {
  20. err->message = "Failed to generate error message!";
  21. err->is_static = 1;
  22. va_end(va);
  23. l2_trace("Parse error: %s", err->message);
  24. return;
  25. } else if ((size_t)n + 1 < sizeof(buf)) {
  26. err->message = malloc(n + 1);
  27. if (err->message == NULL) {
  28. err->message = "Failed to allocate error message!";
  29. err->is_static = 1;
  30. } else {
  31. strcpy(err->message, buf);
  32. }
  33. va_end(va);
  34. l2_trace("Parse error: %s", err->message);
  35. return;
  36. }
  37. // Need to allocate for this one
  38. err->message = malloc(n + 1);
  39. if (err->message == NULL) {
  40. err->message = "Failed to allocate error message!";
  41. err->is_static = 1;
  42. } else {
  43. vsnprintf(err->message, n + 1, fmt, va);
  44. }
  45. va_end(va);
  46. l2_trace("Parse error: %s", err->message);
  47. }
  48. void l2_parse_error_free(struct l2_parse_error *err) {
  49. if (!err->is_static) {
  50. free(err->message);
  51. }
  52. }