Er.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #define _POSIX_C_SOURCE 200112L
  16. #include "exception/Er.h"
  17. #include "util/CString.h"
  18. #include <stdarg.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. Gcc_USE_RET
  22. struct Er_Ret* Er__raise(char* file, int line, struct Allocator* alloc, char* format, ...)
  23. {
  24. va_list args;
  25. va_start(args, format);
  26. if (alloc) {
  27. int written = snprintf(NULL, 0, "%s:%d ", file, line);
  28. Assert_true(written >= 0);
  29. va_list argsCopy;
  30. va_copy(argsCopy, args);
  31. int written2 = vsnprintf(NULL, 0, format, argsCopy);
  32. Assert_true(written2 >= 0);
  33. va_end(argsCopy);
  34. int len = written + written2 + 1;
  35. char* buf = Allocator_calloc(alloc, len, 1);
  36. snprintf(buf, len, "%s:%d ", file, line);
  37. vsnprintf(&buf[written], len - written, format, args);
  38. struct Er_Ret* res = Allocator_calloc(alloc, sizeof(struct Er_Ret), 1);
  39. res->message = buf;
  40. va_end(args);
  41. return res;
  42. } else {
  43. fprintf(stderr, "%s:%d ", file, line);
  44. vfprintf(stderr, format, args);
  45. fprintf(stderr, "\n");
  46. }
  47. abort();
  48. exit(100);
  49. }
  50. void Er__assertFail(struct Er_Ret* er)
  51. {
  52. if (!er) { return; }
  53. fprintf(stderr, "%s\n", er->message);
  54. abort();
  55. exit(100);
  56. }