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.
 
 
 
 

109 regels
4.3 KiB

  1. #pragma once
  2. #include "stdio.h"
  3. #include "math.h"
  4. #include "stdarg.h"
  5. #include "stdlib.h"
  6. #include "types.hpp"
  7. #include "print.hpp"
  8. struct Error {
  9. String type;
  10. String message;
  11. };
  12. Error* error = nullptr;
  13. auto delete_error() -> void {
  14. free(error);
  15. error = nullptr;
  16. }
  17. auto create_error(const char* c_func_name, const char* c_file_name,
  18. u32 c_file_line, String type, const char* format, ...) -> void {
  19. error = (Error*) malloc(sizeof(Error));
  20. va_list args;
  21. va_start(args, format);
  22. error->message.length = print_va_args_to_string(&(error->message.data), format, &args);
  23. va_end(args);
  24. error->type = type;
  25. print("\n%{color<}%{->Str} error:%{>color} %{->Str}\n",
  26. console_red, &(error->type), &(error->message));
  27. print("in");
  28. s32 spacing = 30-((s32)strlen(c_file_name) + (s32)log10(c_file_line));
  29. if (spacing < 1) spacing = 1;
  30. for (s32 i = 0; i < spacing; ++i)
  31. print(" ");
  32. print("%s (%u) ", c_file_name, c_file_line);
  33. print("-> %s\n", c_func_name);
  34. }
  35. #define __create_error(keyword, ...) \
  36. create_error( \
  37. __FUNCTION__, __FILE__, __LINE__, \
  38. make_heap_string(keyword), \
  39. __VA_ARGS__)
  40. #define create_assertion_error(...) \
  41. __create_error("assert", __VA_ARGS__)
  42. #define create_generic_error(...) \
  43. __create_error("generic", __VA_ARGS__)
  44. #ifdef assert
  45. #undef assert
  46. #endif
  47. #define assert(condition, ...) \
  48. do { \
  49. if (!(condition)) { \
  50. char* msg; \
  51. print_to_string(&msg, __VA_ARGS__); \
  52. create_assertion_error("Assertion-error: %s\n" \
  53. " condition: %s\n" \
  54. " in: %s:%d", \
  55. msg, #condition, \
  56. __FILE__, __LINE__ ); \
  57. } \
  58. } while(0)
  59. #define log_location() \
  60. do { \
  61. printf("in"); \
  62. s32 spacing = 30-((s32)strlen(__FILE__) + (s32)log10(__LINE__)); \
  63. if (spacing < 1) spacing = 1; \
  64. for (s32 i = 0; i < spacing;++i) \
  65. printf(" "); \
  66. printf("%s (%d) ", __FILE__, __LINE__); \
  67. printf("-> %s\n", __FUNCTION__); \
  68. } while(0)
  69. #define if_error_log_location_and_return(val) \
  70. do { \
  71. if (error) { \
  72. log_location(); \
  73. return val; \
  74. } \
  75. } while(0)
  76. #define try_or_else_return(val) \
  77. if (1) \
  78. goto label(body,__LINE__); \
  79. else \
  80. while (1) \
  81. if (1) { \
  82. if (error) { \
  83. log_location(); \
  84. return val; \
  85. } \
  86. break; \
  87. } \
  88. else label(body,__LINE__):
  89. #define check_error_struct try_or_else_return({})
  90. #define check_error_void try_or_else_return(;)
  91. #define check_error try_or_else_return(0)