chiark / gitweb /
Brown-paper-bag fixes.
[mLib] / exc.h
1 /* -*-c-*-
2  *
3  * $Id: exc.h,v 1.7 2004/04/08 01:36:11 mdw Exp $
4  *
5  * Structured exception handling in C
6  *
7  * (c) 1998 Straylight/Edgeware
8  */
9
10 /*----- Licensing notice --------------------------------------------------*
11  *
12  * This file is part of the mLib utilities library.
13  *
14  * mLib is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU Library General Public License as
16  * published by the Free Software Foundation; either version 2 of the
17  * License, or (at your option) any later version.
18  *
19  * mLib is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU Library General Public License for more details.
23  *
24  * You should have received a copy of the GNU Library General Public
25  * License along with mLib; if not, write to the Free
26  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
27  * MA 02111-1307, USA.
28  */
29
30 #ifndef MLIB_EXC_H
31 #define MLIB_EXC_H
32
33 #ifdef __cplusplus
34   extern "C" {
35 #endif
36
37 #include <setjmp.h>
38
39 /*----- Quick documentation -----------------------------------------------*
40  *
41  * This header file provides some exception handling facilities in C
42  * programs.  It modifies the syntax of the language slightly, using the
43  * preprocessor.
44  *
45  * The `throw' expression returns no value.  It has the syntax:
46  *
47  *   THROW ( expr , expr )
48  *
49  * The first expression must have type compatible with unsigned integer; it
50  * identifies an `exception type'.  The second must have type compatible
51  * with pointer to void; it contains the `exception data'.  Control is
52  * passed to the current exception handler.
53  *
54  * The `RETHROW' expression, valid only within an exception handler, causes
55  * the current exception to be thrown again.
56  *
57  * A `try' statement has the syntax:
58  *
59  *   TRY stat CATCH stat END_TRY;
60  *
61  * The first statement is called the `test'; the second is the `handler'.
62  * During execution of the test, the handler is added to a stack of
63  * active exception handlers; the topmost handler on this stack is called
64  * the `current' handler.  When execution of the test completes, the
65  * corresponding handler is removed from the stack.
66  *
67  * The test statement may complete in one of these ways:
68  *
69  *   * Normal completion -- control reaches the end of the statement
70  *     normally.
71  *
72  *   * Throwing an exception -- an exception is thrown when the handler is
73  *     the current exception handler.
74  *
75  *   * By executing a `break' statement.
76  *
77  *   * By executing the expression `EXIT_TRY' and transferring control to
78  *     a point outside the entire `try' statement (e.g., executing a `goto'
79  *     or `return' statement).
80  *
81  * Any other attempt to leave the test causes undefined behaviour.
82  *
83  * If an exception is thrown while the handler is the current exception
84  * handler, it is given control.  The variables `exc_type' and `exc_val'
85  * denote the exception type and value respectively -- they are passed
86  * unchanged from the `throw' expression which caused the exception.
87  * A handler is deactivated before it is invoked; if it causes an
88  * exception to be thrown (and does not contain a nested `try' statement)
89  * control will be passed to an earlier active handler.
90  *
91  * Control is passed to handlers using the `longjmp' function.
92  *
93  * Example:
94  *
95  *   TRY {
96  *     ... something dangerous ...
97  *   } CATCH switch (exc_type) {
98  *     case EXC_INTERESTING:
99  *       ... handle exception ...
100  *       break;
101  *     default:
102  *       ... do tidying up ...
103  *       RETHROW;
104  *   } END_TRY;
105  */
106
107 /*----- Exception type allocation -----------------------------------------*
108  *
109  * Nobody allocates exception types, so we'll just have to try to get along
110  * without too many collisions.  An exception type is an unsigned long,
111  * which gives us four bytes.  The top two bytes identify the library which
112  * `owns' the exception, with special values zero meaning `defined as part
113  * of the system' and 0xFFFF providing a shared space of types which can
114  * be used by anyone as long as they don't get seen by anyone else.
115  *
116  * The lower byte pair encodes a type number, and a value which defines
117  * the type of the value field (see below).
118  */
119
120 /* --- Type of an exception --- */
121
122 typedef unsigned long exc_extype;
123
124 /* --- Build a byte pair from two characters --- *
125  *
126  * Note the icky casting to handle signed chars.
127  */
128
129 #define EXC_PAIR(x, y) (((unsigned long)(unsigned char)(x) << 8) |      \
130                         (unsigned long)(unsigned char)(y))
131
132 /* --- Allocate an exception number --- */
133
134 #define EXC_ALLOC(owner, type) (((unsigned long)(owner) << 16) |        \
135                                 (unsigned long)(type))
136
137 /* --- Special owner codes --- */
138
139 #define EXC_GLOBAL 0u                   /* The global space defined here */
140 #define EXC_SHARED 0xFFFFu              /* The shared space for everyone */
141 #define EXC_MLIB EXC_PAIR('m', 'L')     /* Space for mLib exceptions */
142
143 /*----- Exception values --------------------------------------------------*
144  *
145  * Exception values can have several different types.  This is a mess, and
146  * C doesn't handle it too well, but we can try.  I'll encode the value type
147  * as part of the exception type, in the top bits of the bottom byte.  Messy?
148  * You betcha.
149  */
150
151 /* --- Encoding a value type in an extype --- */
152
153 #define EXC_TYPECODE(t, w) (((w) & ~0xC0u) | ((t) & 0xC0u))
154
155 /* --- The various value types --- */
156
157 #define EXC_NOVAL 0x00u                 /* No interesting value */
158 #define EXC_INTVAL 0x40u                /* Integer value */
159 #define EXC_PTRVAL 0x80u                /* Arbitrary pointer value */
160 #define EXC_STRVAL 0xC0u                /* Pointer to character string */
161
162 /* --- Allocating exceptions with appropriate types --- */
163
164 #define EXC_ALLOCN(o, t) EXC_TYPECODE(EXC_NOVAL,  EXC_ALLOC(o, t))
165 #define EXC_ALLOCI(o, t) EXC_TYPECODE(EXC_INTVAL, EXC_ALLOC(o, t))
166 #define EXC_ALLOCP(o, t) EXC_TYPECODE(EXC_PTRVAL, EXC_ALLOC(o, t))
167 #define EXC_ALLOCS(o, t) EXC_TYPECODE(EXC_STRVAL, EXC_ALLOC(o, t))
168
169 /* --- A union representing the type --- */
170
171 typedef union exc_exval {
172   int i;
173   void *p;
174   char *s;
175 } exc_exval;
176
177 /*----- Predefined exceptions ---------------------------------------------*/
178
179 /* --- @EXC_NOMEM@ --- *
180  *
181  * Value:       ---
182  *
183  * Meaning:     An attempt to allocate memory failed.
184  */
185
186 #define EXC_NOMEM EXC_ALLOCN(EXC_GLOBAL, 0u)
187
188 /* --- @EXC_ERRNO@ --- *
189  *
190  * Value:       @int errno@ = the error raised
191  *
192  * Meaning:     Some kind of OS error occurred.
193  */
194
195 #define EXC_ERRNO EXC_ALLOCI(EXC_GLOBAL, 1u)
196
197 /* --- @EXC_OSERROR@ --- *
198  *
199  * Value:       @os_error *e@ = pointer to error block
200  *
201  * Meaning:     For RISC OS programmers only: alternative way of propagating
202  *              errors.
203  */
204
205 #define EXC_OSERROR EXC_ALLOCP(EXC_GLOBAL, 1u)
206
207 /* --- @EXC_SIGNAL@ --- *
208  *
209  * Value:       @int sig@ = signal number
210  *
211  * Meaning:     Report the raising of a signal.
212  */
213
214 #define EXC_SIGNAL EXC_ALLOCI(EXC_GLOBAL, 2u)
215
216 /* --- @EXC_FAIL@ --- *
217  *
218  * Value:       @const char *p@ = pointer to expanatory string
219  *
220  * Meaning:     Miscellaneous error.
221  */
222
223 #define EXC_FAIL EXC_ALLOCS(EXC_GLOBAL, 0xFFu)
224
225 /*----- An exception handler block ----------------------------------------*/
226
227 /* --- Try to think of this as being opaque --- */
228
229 typedef struct __exc_hnd {
230   struct __exc_hnd *next;               /* Pointer to next record down */
231   exc_extype type;                      /* Type of this exception */
232   exc_exval val;                        /* Value of this exception */
233   jmp_buf buf;                          /* Jump buffer when exceptions hit */
234 } __exc_hnd;
235
236 /*----- Global variables --------------------------------------------------*/
237
238 extern __exc_hnd *__exc_list;           /* List of active handlers */
239
240 /*----- Macros ------------------------------------------------------------*/
241
242 /* --- References to current exception type and value --- */
243
244 #define exc_type (__exc_ec.type)
245 #define exc_val (__exc_ec.val)
246 #define exc_i (__exc_ec.val.i)
247 #define exc_p (__exc_ec.val.p)
248 #define exc_s (__exc_ec.val.s)
249
250 /* --- How it actually works --- *
251  *
252  * A `try' block is contained within a block which provides an exception
253  * handler buffer in automatic storage.  This block is a loop, to allow
254  * `break' to escape from it.  It adds the handler buffer to the top of a
255  * list, and does a `setjmp' to allow a return here following an exception.
256  * The `setjmp' returns zero for the `try' section, and nonzero if there's
257  * an exception to `catch'.  It looks a little like this:
258  *
259  *   do {
260  *     __exc_hnd h;
261  *     add_handler(&h);
262  *     if (!setjmp(h.buf)) {
263  *       do <try code> while (0);
264  *       remove_handler(&h);
265  *     } else
266  *       <catch code>
267  *   } while (0)
268  *
269  * Everything else is ugly hacking to make things work.
270  */
271
272 /* --- Trying things which may cause exceptions --- */
273
274 #define TRY do {                                                        \
275   volatile __exc_hnd __exc_ec;                                          \
276   __exc_ec.next = __exc_list;                                           \
277   __exc_list = (__exc_hnd *)&__exc_ec;                                  \
278   if (!setjmp(*(jmp_buf *)&__exc_ec.buf /* very nasty! */ )) { do
279
280 #define EXIT_TRY do __exc_list = __exc_ec.next; while (0)
281 #define CATCH while (0); EXIT_TRY; } else
282
283 #define END_TRY } while (0)
284
285 /* --- Raising exceptions --- */
286
287 #define THROW __exc_throw
288 #define RETHROW __exc_rethrow(__exc_ec.type, __exc_ec.val)
289
290 /*----- Functions ---------------------------------------------------------*/
291
292 /* --- @exc_uncaught@ --- *
293  *
294  * Arguments:   @void (*proc)(exc_extype type, exc_exval val) = new handler
295  *
296  * Returns:     Pointer to the old handler value.
297  *
298  * Use:         Sets the handler for uncaught exceptions.
299  */
300
301 typedef void (*exc__uncaught)(exc_extype /*type*/, exc_exval /*val*/);
302 extern exc__uncaught exc_uncaught(exc__uncaught /*proc*/);
303
304 /* --- @__exc_throw@ --- *
305  *
306  * Arguments:   @exc_extype type@ = type of exception to throw
307  *
308  * Returns:     Doesn't
309  *
310  * Use:         NOT FOR USER CONSUMPTION.  Reads an appropriate exception
311  *              value and throws an exception.
312  */
313
314 extern void __exc_throw(exc_extype /*type*/, ...);
315
316 /* --- @__exc_rethrow@ --- *
317  *
318  * Arguments:   @exc_extype type@ = type of exception to throw
319  *              @exc_exval val@ = value of exception to throw
320  *
321  * Returns:     Doesn't
322  *
323  * Use:         NOT FOR USER CONSUMPTION.  Does the donkey-work of raising
324  *              an exception.
325  */
326
327 extern void __exc_rethrow(exc_extype /*type*/, exc_exval /*val*/);
328
329 /*----- That's all, folks -------------------------------------------------*/
330
331 #ifdef __cplusplus
332   }
333 #endif
334
335 #endif