1
0

Jmp.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 <http://www.gnu.org/licenses/>.
  14. */
  15. #ifndef Jmp_H
  16. #define Jmp_H
  17. #include "exception/Except.h"
  18. #include <setjmp.h>
  19. /**
  20. * setjmp based exception handler.
  21. *
  22. * struct Jmp jmp;
  23. * Jmp_try(jmp) {
  24. * Do_somethingDangerous(&jmp.handler);
  25. * } Jmp_catch {
  26. * printf("failed %d %s", jmp.code, jmp.message);
  27. * }
  28. *
  29. * Provides an easy way to implement the most basic try/catch functionality.
  30. * the jmp structure must not be used for anything outside of the try block,
  31. * calling jmp.handler.exception outside of a try block is undefined behavior.
  32. */
  33. struct Jmp {
  34. /** The exception handler which will trigger the entry into the catch block. */
  35. struct Except handler;
  36. /** The exception message if in the catch block, otherwise undefined. */
  37. char* message;
  38. /** Internal setjmp buffer. */
  39. jmp_buf buf;
  40. };
  41. /** Internal callback, this should not be called directly. */
  42. Gcc_NORETURN
  43. static void Jmp_callback(char* message, struct Except* handler)
  44. {
  45. struct Jmp* jmp = (struct Jmp*) handler;
  46. jmp->message = message;
  47. longjmp(jmp->buf, 1);
  48. }
  49. #define Jmp_try(jmp) \
  50. jmp.handler.exception = Jmp_callback; \
  51. if (!setjmp(jmp.buf))
  52. // CHECKFILES_IGNORE squigly bracket will be added by the caller.
  53. #define Jmp_catch else
  54. #endif