error.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * error.c - Error reporting
  3. *
  4. * Written 2009, 2010 by Werner Almesberger
  5. * Copyright 2009, 2010 by Werner Almesberger
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. */
  12. #include <stdarg.h>
  13. #include <stdlib.h>
  14. #include <stdio.h>
  15. #include "util.h"
  16. #include "error.h"
  17. extern char *yytext;
  18. int lineno = 1;
  19. void (*reporter)(const char *s) = report_to_stderr;
  20. void yywarn(const char *s)
  21. {
  22. /* we use yywarn only when starting */
  23. fprintf(stderr, "%d: warning: %s near \"%s\"\n", lineno, s, yytext);
  24. }
  25. void yyerrorf(const char *fmt, ...)
  26. {
  27. va_list ap;
  28. char *buf;
  29. int n;
  30. va_start(ap, fmt);
  31. n = vsnprintf(NULL, 0, fmt, ap);
  32. va_end(ap);
  33. buf = alloc_size(n+1);
  34. va_start(ap, fmt);
  35. vsnprintf(buf, n+1, fmt, ap);
  36. va_end(ap);
  37. fail("%s", buf);
  38. free(buf);
  39. }
  40. void yyerror(const char *s)
  41. {
  42. yyerrorf("%s", s);
  43. }
  44. void report_parse_error(const char *s)
  45. {
  46. fprintf(stderr, "%d: %s near \"%s\"\n", lineno, s, yytext);
  47. exit(1);
  48. }
  49. void report_to_stderr(const char *s)
  50. {
  51. fprintf(stderr, "%s\n", s);
  52. exit(1);
  53. }
  54. void fail(const char *fmt, ...)
  55. {
  56. va_list ap;
  57. char *s;
  58. va_start(ap, fmt);
  59. s = stralloc_vprintf(fmt, ap);
  60. va_end(ap);
  61. reporter(s);
  62. free(s);
  63. }