1 /*
2 * mp.h: header file providing macros for 'metaprogramming' custom
3 * loop constructions in standard C.
4 *
5 * Accompanies the article on the web at
6 * https://www.chiark.greenend.org.uk/~sgtatham/mp/
7 */
8
9 /*
10 * mp.h is copyright 2012 Simon Tatham.
11 *
12 * Permission is hereby granted, free of charge, to any person
13 * obtaining a copy of this software and associated documentation
14 * files (the "Software"), to deal in the Software without
15 * restriction, including without limitation the rights to use,
16 * copy, modify, merge, publish, distribute, sublicense, and/or
17 * sell copies of the Software, and to permit persons to whom the
18 * Software is furnished to do so, subject to the following
19 * conditions:
20 *
21 * The above copyright notice and this permission notice shall be
22 * included in all copies or substantial portions of the Software.
23 *
24 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
26 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
27 * NONINFRINGEMENT. IN NO EVENT SHALL SIMON TATHAM BE LIABLE FOR
28 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
29 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
30 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31 * SOFTWARE.
32 *
33 * $Id$
34 */
35
36 /*
37 * Macros beginning with 'MPI_' are internal to this header file, and
38 * intended only to be used by other macros defined _in_ this header
39 * file. Do not refer to them externally.
40 */
41
42 /* Standard trickery to allow us to macro-expand and then token-paste */
43 #define MPI_TOKPASTEINNER(x,y) x ## y
44 #define MPI_TOKPASTE(x,y) MPI_TOKPASTEINNER(x,y)
45
46 /* Method of constructing line-unique labels */
47 #define MPI_LABEL(id1,id2) \
48 MPI_TOKPASTE(MPI_LABEL_ ## id1 ## _ ## id2 ## _, __LINE__)
49
50 /*
51 * Macros beginning with 'MPP_' and 'MPS_' are building blocks
52 * intended for metaprogrammers to make useful control constructions
53 * from.
54 *
55 * The prefixes distinguish their syntactic role. MPP_ macros are
56 * statement _prefixes_; you would typically build a custom control
57 * structure by defining a macro expanding to a sequence of them. MPS_
58 * macros are actual statements, which you might use in the various
59 * parameters of MPP_ macros that are expected to be statement-shaped.
60 */
61
62 /*
63 * Safety considerations:
64 *
65 * - All of these macros are C89-safe, except for MPP_DECLARE if you
66 * pass an actual declaration and not just an assignment, since
67 * that one relies on the C99 (and C++) extension of being able to
68 * write a declaration in the initialisation clause of a for
69 * statement.
70 *
71 * - None of these macros uses switch, so case labels from a switch
72 * outside the whole lot may be written inside the suffixed
73 * statement/block.
74 *
75 * - All of these constructions use 'goto' with labels constructed
76 * programmatically, using __LINE__ to make them unique between
77 * multiple invocations of the same loop macro. So don't put two
78 * loop macros defined using these building blocks on the same
79 * source line.
80 *
81 * - All of these constructions can be prefixed to something that is
82 * syntactically a single C statement, and generate something that
83 * is also a single C statement. So they're if-else safe - you can
84 * use an unbraced one of these constructs followed by an unbraced
85 * statement within the then-clause of an outer if, and the else
86 * will still bind to what it looks as if it ought to.
87 *
88 * - Controlling what happens if the user writes a 'break' in the
89 * suffixed statement is unavoidably rather fiddly. The macros
90 * below fall into a few categories:
91 *
92 * + naturally transparent to 'break' (MPP_BEFORE, MPP_IF). Macros
93 * of this type will not affect the semantics of 'break' in the
94 * suffixed statement at all - it will terminate the next
95 * innermost loop or switch outside the construction.
96 *
97 * + artificially transparent to 'break', by means of deliberately
98 * catching and 'rethrowing' it. (MPP_BREAK_{THROW,CATCH};
99 * MPP_BREAK_HANDLER; MPP_FINALLY.) These macros will propagate
100 * a break outwards to the next containing loop, but in order to
101 * do so they require that there _be_ a next containing loop,
102 * since their expansion can't avoid including a break statement
103 * which they themselves do not wrap in a loop. So you should
104 * only use these when you know there is a containing loop (e.g.
105 * because MPP_WHILE or MPP_DO_WHILE precedes them in your
106 * construction).
107 *
108 * + loop constructions. (MPP_WHILE and MPP_DO_WHILE). These
109 * macros give 'break' the obvious semantics of terminating the
110 * loop they define.
111 *
112 * + break-unsafe macros, which have to include a C looping
113 * construction to do something not essentially loopy, and hence
114 * have the unfortunate side effect of causing 'break' to only
115 * terminate the suffixed statement itself. On the other hand,
116 * they can be used in contexts where there is no surrounding
117 * loop at all (which is why I don't just fix them to contain a
118 * built-in MPP_BREAK_{THROW,CATCH}).
119 *
120 * If you are using these macros to build a looping construct, then
121 * you will probably include an MPP_WHILE or MPP_DO_WHILE in your
122 * stack, and you'll want 'break' to terminate that. So you just
123 * need to be sure that break is correctly propagated from the
124 * suffixed statement back to that loop, which you can do by
125 * sticking to the break-transparent macros where possible and
126 * using MPP_BREAK_{THROW,CATCH} to bypass any break-unsafe macro
127 * such as MPP_DECLARE that you might need to use. Having done
128 * that, 'break' will do what the user expects.
129 *
130 * But if you're using the macros to wrap some context around a
131 * statement you still intend to be executed only once, there will
132 * be unavoidable side effects on 'break': you can't use the
133 * artificially break-unsafe macros because the user might use your
134 * construction in a context with no surrounding loop at all, so
135 * you must stick to the naturally break-transparent and the
136 * break-unsafe, and there aren't enough of the former to be really
137 * useful. So you must just live with 'break' acquiring unhelpful
138 * behaviour inside such a macro.
139 *
140 * - Almost none of these macros is transparent to 'continue'. The
141 * naturally break-transparent MPP_BEFORE is, but none of the rest
142 * can possibly be, because as soon as you include any loop
143 * construction in the stuff being prefixed to a statement, you
144 * introduce the invariant that 'continue' is equivalent to jumping
145 * to the end of the suffixed statement or block. This is not too
146 * bad if you're defining a custom loop construction (it was quite
147 * likely the behaviour you wanted for continue anyway), but if you
148 * were trying to use MPP_DECLARE and/or MPP_BEFORE_AND_AFTER to
149 * wrap a statement in some context but still only execute it once,
150 * you'd have to be aware of that limitation.
151 *
152 * - MPP_FINALLY and MPP_BREAK_HANDLER can only catch non-local exits
153 * from the block _by break_. They are not true C++ try/finally, so
154 * they can't catch other kinds of exit such as return, goto,
155 * longjmp or exit.
156 *
157 * - Finally, it almost goes without saying, but don't forget that
158 * snippets of code you use as parameters to these macros must
159 * avoid using commas not contained inside parentheses, or else the
160 * C preprocessor will consider the comma to end that macro
161 * parameter and start the next one. If there is any reason you
162 * really need an unbracketed comma, you can work around this by
163 * one of two methods:
164 * - define a macro that expands to a comma ('#define COMMA ,')
165 * and then use that macro in place of commas in your macro
166 * argument. It won't be expanded to an actual comma until after
167 * the argument-separation has finished.
168 * - if you're allowed to use C99, define a variadic macro that
169 * expands to its unmodified input argument list ('#define
170 * WRAP(...) __VA_ARGS__') and then enclose comma-using code in
171 * WRAP(). Again, this will protect the commas for just long
172 * enough.
173 */
174
175 /*
176 * MPP_BEFORE: run the code given in the argument 'before' and then
177 * the suffixed statement.
178 *
179 * 'before' should have the syntactic form of one or more declarations
180 * and statements, except that a trailing semicolon may be omitted.
181 * Any declarations will be in scope only within 'before', not within
182 * the suffixed statement.
183 *
184 * This macro, unusually among the collection, is naturally
185 * transparent to 'break' and also transparent to 'continue'.
186 */
187 #define MPP_BEFORE(labid,before) \
188 if (1) { \
189 before; \
190 goto MPI_LABEL(labid, body); \
191 } else \
192 MPI_LABEL(labid, body):
193
194 /*
195 * MPP_AFTER: run the suffixed statement, and then the code given in
196 * the argument 'after'.
197 *
198 * 'after' should have the syntactic form of one or more declarations
199 * and statements, except that a trailing semicolon may be omitted.
200 * Any declaration in 'after' will be in scope only within 'after'.
201 *
202 * This macro is break-unsafe - it causes a 'break' to terminate the
203 * suffixed statement only. If you need different behaviour, you can
204 * use MPP_BREAK_CATCH and MPP_BREAK_THROW to pass a break past it -
205 * but beware that in that case the 'after' clause will not be
206 * executed, so MPP_FINALLY or MPP_BREAK_HANDLER may be useful too.
207 */
208 #define MPP_AFTER(labid,after) \
209 if (1) \
210 goto MPI_LABEL(labid, body); \
211 else \
212 while (1) \
213 if (1) { \
214 after; \
215 break; \
216 } else \
217 MPI_LABEL(labid, body):
218
219 /*
220 * MPP_DECLARE: run the 'declaration' argument before the suffixed
221 * statement. The argument may have the form of either a C expression
222 * (e.g. an assignment) or a declaration; if the latter, it will be in
223 * scope within the suffixed statement.
224 *
225 * This macro is break-unsafe - it causes a 'break' to terminate the
226 * suffixed statement only. If you need different behaviour, you can
227 * use MPP_BREAK_CATCH and MPP_BREAK_THROW to pass a break past it.
228 */
229 #define MPP_DECLARE(labid, declaration) \
230 if (0) \
231 ; \
232 else \
233 for (declaration;;) \
234 if (1) { \
235 goto MPI_LABEL(labid, body); \
236 MPI_LABEL(labid, done): break; \
237 } else \
238 while (1) \
239 if (1) \
240 goto MPI_LABEL(labid, done); \
241 else \
242 MPI_LABEL(labid, body):
243 /* (The 'if(0) ; else' at the start of the above is just in case we
244 * encounter an old-style compiler that considers variables declared
245 * in for statements to have scope extending beyond the for statement.
246 * Putting another layer outside the 'for' ensures that the variable's
247 * scope is constrained to _that_ layer even if not to the for itself,
248 * and it doesn't leak into the calling scope. */
249
250 /*
251 * MPP_WHILE: run the suffixed statement within a 'while (condition)'
252 * loop.
253 *
254 * In fact, just writing 'while (condition)' works fine for this, but
255 * it's nice to make it look like the rest of these macros!
256 *
257 * This macro defines an actual loop, and 'break' in the suffixed
258 * statement terminates that loop as you would expect.
259 */
260 #define MPP_WHILE(labid, condition) \
261 while (condition)
262
263 /*
264 * MPP_DO_WHILE: run the suffixed statement within a loop with the
265 * semantics of 'do suffixed-statement while (condition)'.
266 *
267 * This macro defines an actual loop, and 'break' in the suffixed
268 * statement terminates that loop as you would expect.
269 */
270 #define MPP_DO_WHILE(labid, condition) \
271 if (1) \
272 goto MPI_LABEL(labid, body); \
273 else \
274 while (condition) \
275 MPI_LABEL(labid, body):
276
277 /*
278 * MPP_IF: run the suffixed statement only if 'condition' is true.
279 *
280 * This macro is naturally transparent to 'break' and also transparent
281 * to 'continue'.
282 */
283 #define MPP_IF(labid, condition) \
284 if (!(condition)) \
285 ; \
286 else
287
288 /*
289 * MPP_BREAK_THROW and MPP_BREAK_CATCH: propagate 'break' control flow
290 * transfers past other prefixes that mess about with them.
291 *
292 * Write an MPP_BREAK_CATCH, then other metaprogramming prefixes from
293 * this collection, and then an MPP_BREAK_THROW with the same label
294 * id. If the statement following the MPP_BREAK_THROW terminates by
295 * 'break', then the effect will be as if the MPP_BREAK_CATCH had
296 * terminated by 'break', regardless of how the in-between prefixes
297 * would have handled a 'break'.
298 *
299 * These macros are artificially transparent to 'break': they pass
300 * break through, but include a 'break' statement at the top level of
301 * MPP_BREAK_CATCH, so that must always be contained inside some loop
302 * or switch construction.
303 *
304 * We also provide MPS_BREAK_THROW, which is a statement-type macro
305 * that manufactures a break event and passes it to a specified
306 * MPP_BREAK_CATCH.
307 */
308 #define MPP_BREAK_CATCH(labid) \
309 if (0) \
310 MPI_LABEL(labid, catch): break; \
311 else
312
313 #define MPP_BREAK_THROW(labid) \
314 if (1) { \
315 goto MPI_LABEL(labid, body); \
316 MPI_LABEL(labid, finish):; \
317 } else \
318 while (1) \
319 if (1) \
320 goto MPI_LABEL(labid, catch); \
321 else \
322 while (1) \
323 if (1) \
324 goto MPI_LABEL(labid, finish); \
325 else \
326 MPI_LABEL(labid, body):
327
328 #define MPS_BREAK_THROW(labid) goto MPI_LABEL(labid, catch)
329
330 /*
331 * MPP_BREAK_HANDLER: handle a 'break' in the suffixed statement by
332 * executing the provided handler code and then terminating as if by
333 * break.
334 *
335 * 'handler' should have the syntactic form of one or more
336 * declarations and statements, except that a trailing semicolon may
337 * be omitted.
338 *
339 * This macro is artificially transparent to 'break': it passes break
340 * through, but includes a 'break' statement at the top level, so it
341 * must always be contained inside some loop or switch construction.
342 */
343 #define MPP_BREAK_HANDLER(labid, handler) \
344 if (1) { \
345 goto MPI_LABEL(labid, body); \
346 MPI_LABEL(labid, break): \
347 {handler;} \
348 break; \
349 MPI_LABEL(labid, finish):; \
350 } else \
351 while (1) \
352 if (1) \
353 goto MPI_LABEL(labid, break); \
354 else \
355 while (1) \
356 if (1) \
357 goto MPI_LABEL(labid, finish); \
358 else \
359 MPI_LABEL(labid, body):
360
361 /*
362 * MPP_FINALLY: execute the suffixed statement, and execute the
363 * provided 'finally' clause after it finishes. If it terminates by
364 * 'break', execute the same 'finally' clause but propagate the break
365 * to the containing statement.
366 *
367 * 'finally' should have the syntactic form of one or more
368 * declarations and statements, except that a trailing semicolon may
369 * be omitted.
370 *
371 * The 'finally' argument will be double-expanded. Of course it'll
372 * only be executed once in any given run, so that's not a concern for
373 * function side effects, but don't do anything fiddly like declaring
374 * a static variable to which you return a pointer and then expecting
375 * the pointer to be the same no matter which copy of 'finally' it
376 * came from.
377 *
378 * This macro is artificially transparent to 'break': it passes break
379 * through, but includes a 'break' statement at the top level, so it
380 * must always be contained inside some loop or switch construction.
381 */
382 #define MPP_FINALLY(labid, finally) \
383 if (1) { \
384 goto MPI_LABEL(labid, body); \
385 MPI_LABEL(labid, break): \
386 {finally;} \
387 break; \
388 MPI_LABEL(labid, finish): \
389 {finally;} \
390 } else \
391 while (1) \
392 if (1) \
393 goto MPI_LABEL(labid, break); \
394 else \
395 while (1) \
396 if (1) \
397 goto MPI_LABEL(labid, finish); \
398 else \
399 MPI_LABEL(labid, body):
400
401 /*
402 * MPP_BREAK_STOP: handle a 'break' in the suffixed statement by
403 * executing the provided handler code and then terminating as if
404 * normally.
405 *
406 * 'handler' should have the syntactic form of one or more
407 * declarations and statements, except that a trailing semicolon may
408 * be omitted.
409 */
410 #define MPP_BREAK_STOP(labid, handler) \
411 if (1) { \
412 goto MPI_LABEL(labid, body); \
413 MPI_LABEL(labid, break): \
414 {handler;} \
415 MPI_LABEL(labid, finish):; \
416 } else \
417 while (1) \
418 if (1) \
419 goto MPI_LABEL(labid, break); \
420 else \
421 while (1) \
422 if (1) \
423 goto MPI_LABEL(labid, finish); \
424 else \
425 MPI_LABEL(labid, body):
426
427 /*
428 * MPP_ELSE_ACCEPT, MPS_MAIN_INVOKE, MPS_ELSE_INVOKE: arrange to
429 * accept an optional 'else' clause after the suffixed statement, and
430 * provide two statement macros which jump to the main clause and the
431 * else clause. The main (non-else) clause will be be executed in the
432 * default case, and can be invoked again using MPS_MAIN_INVOKE;
433 * MPS_ELSE_INVOKE will invoke the else clause.
434 *
435 * Like MPP_BREAK_THROW and MPP_BREAK_CATCH, these macros should be
436 * used in groups with the same label id, so as to match them up to
437 * each other. MPS_ELSE_INVOKE and MPS_MAIN_INVOKE will go to the
438 * appropriate clauses corresponding to the MPP_ELSE_ACCEPT with the
439 * same id.
440 */
441 #define MPP_ELSE_ACCEPT(labid) \
442 if (1) \
443 goto MPI_LABEL(labid, body); \
444 else \
445 MPI_LABEL(labid, else): \
446 if (0) \
447 MPI_LABEL(labid, body):
448
449 #define MPS_MAIN_INVOKE(labid) \
450 goto MPI_LABEL(labid, body)
451
452 #define MPS_ELSE_INVOKE(labid) \
453 goto MPI_LABEL(labid, else)
454
455 /*
456 * MPP_ELSE_GENERAL: like MPP_ELSE_ACCEPT, but also lets you provide a
457 * snippet of code that will be run after the else clause terminates
458 * and one which will be run after the else clause breaks.
459 *
460 * You can use MPS_MAIN_INVOKE and MPS_ELSE_INVOKE with this as well
461 * as with MPP_ELSE_ACCEPT.
462 *
463 * Will mess up what happens after the main body, so you'll probably
464 * want to follow this macro with others such as MPP_AFTER and
465 * something to catch break in the main body too.
466 */
467 #define MPP_ELSE_GENERAL(labid, after, breakhandler) \
468 if (1) \
469 goto MPI_LABEL(labid, body); \
470 else \
471 while (1) \
472 if (1) { \
473 {breakhandler;} \
474 break; \
475 } else \
476 while (1) \
477 if (1) { \
478 {after;} \
479 break; \
480 } else \
481 MPI_LABEL(labid, else): \
482 if (0) \
483 MPI_LABEL(labid, body):