1 /*
2  * Copyright (c) 2011-2014, Wind River Systems, Inc.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /**
8  * @file
9  * @brief Macro utilities
10  *
11  * Macro utilities are the public interface for C/C++ code and device tree
12  * related implementation.  In general, C/C++ will include <sys/util.h>
13  * instead this file directly.  For device tree implementation, this file
14  * should be include instead <sys/util_internal.h>
15  */
16 
17 #ifndef ZEPHYR_INCLUDE_SYS_UTIL_MACROS_H_
18 #define ZEPHYR_INCLUDE_SYS_UTIL_MACROS_H_
19 
20 #ifdef __cplusplus
21 extern "C" {
22 #endif
23 
24 /**
25  * @addtogroup sys-util
26  * @{
27  */
28 
29 /*
30  * Most of the eldritch implementation details for all the macrobatics
31  * below (APIs like IS_ENABLED(), COND_CODE_1(), etc.) are hidden away
32  * in this file.
33  */
34 #include <sys/util_internal.h>
35 
36 #ifndef BIT
37 #if defined(_ASMLANGUAGE)
38 #define BIT(n)  (1 << (n))
39 #else
40 /**
41  * @brief Unsigned integer with bit position @p n set (signed in
42  * assembly language).
43  */
44 #define BIT(n)  (1UL << (n))
45 #endif
46 #endif
47 
48 /** @brief 64-bit unsigned integer with bit position @p _n set. */
49 #define BIT64(_n) (1ULL << (_n))
50 
51 /**
52  * @brief Set or clear a bit depending on a boolean value
53  *
54  * The argument @p var is a variable whose value is written to as a
55  * side effect.
56  *
57  * @param var Variable to be altered
58  * @param bit Bit number
59  * @param set if 0, clears @p bit in @p var; any other value sets @p bit
60  */
61 #define WRITE_BIT(var, bit, set) \
62 	((var) = (set) ? ((var) | BIT(bit)) : ((var) & ~BIT(bit)))
63 
64 /**
65  * @brief Bit mask with bits 0 through <tt>n-1</tt> (inclusive) set,
66  * or 0 if @p n is 0.
67  */
68 #define BIT_MASK(n) (BIT(n) - 1UL)
69 
70 /**
71  * @brief 64-bit bit mask with bits 0 through <tt>n-1</tt> (inclusive) set,
72  * or 0 if @p n is 0.
73  */
74 #define BIT64_MASK(n) (BIT64(n) - 1ULL)
75 
76 /**
77  * @brief Check for macro definition in compiler-visible expressions
78  *
79  * This trick was pioneered in Linux as the config_enabled() macro. It
80  * has the effect of taking a macro value that may be defined to "1"
81  * or may not be defined at all and turning it into a literal
82  * expression that can be handled by the C compiler instead of just
83  * the preprocessor. It is often used with a @p CONFIG_FOO macro which
84  * may be defined to 1 via Kconfig, or left undefined.
85  *
86  * That is, it works similarly to <tt>\#if defined(CONFIG_FOO)</tt>
87  * except that its expansion is a C expression. Thus, much <tt>\#ifdef</tt>
88  * usage can be replaced with equivalents like:
89  *
90  *     if (IS_ENABLED(CONFIG_FOO)) {
91  *             do_something_with_foo
92  *     }
93  *
94  * This is cleaner since the compiler can generate errors and warnings
95  * for @p do_something_with_foo even when @p CONFIG_FOO is undefined.
96  *
97  * @param config_macro Macro to check
98  * @return 1 if @p config_macro is defined to 1, 0 otherwise (including
99  *         if @p config_macro is not defined)
100  */
101 #define IS_ENABLED(config_macro) Z_IS_ENABLED1(config_macro)
102 /* INTERNAL: the first pass above is just to expand any existing
103  * macros, we need the macro value to be e.g. a literal "1" at
104  * expansion time in the next macro, not "(1)", etc... Standard
105  * recursive expansion does not work.
106  */
107 
108 /**
109  * @brief Insert code depending on whether @p _flag expands to 1 or not.
110  *
111  * This relies on similar tricks as IS_ENABLED(), but as the result of
112  * @p _flag expansion, results in either @p _if_1_code or @p
113  * _else_code is expanded.
114  *
115  * To prevent the preprocessor from treating commas as argument
116  * separators, the @p _if_1_code and @p _else_code expressions must be
117  * inside brackets/parentheses: <tt>()</tt>. These are stripped away
118  * during macro expansion.
119  *
120  * Example:
121  *
122  *     COND_CODE_1(CONFIG_FLAG, (uint32_t x;), (there_is_no_flag();))
123  *
124  * If @p CONFIG_FLAG is defined to 1, this expands to:
125  *
126  *     uint32_t x;
127  *
128  * It expands to <tt>there_is_no_flag();</tt> otherwise.
129  *
130  * This could be used as an alternative to:
131  *
132  *     #if defined(CONFIG_FLAG) && (CONFIG_FLAG == 1)
133  *     #define MAYBE_DECLARE(x) uint32_t x
134  *     #else
135  *     #define MAYBE_DECLARE(x) there_is_no_flag()
136  *     #endif
137  *
138  *     MAYBE_DECLARE(x);
139  *
140  * However, the advantage of COND_CODE_1() is that code is resolved in
141  * place where it is used, while the @p \#if method defines @p
142  * MAYBE_DECLARE on two lines and requires it to be invoked again on a
143  * separate line. This makes COND_CODE_1() more concise and also
144  * sometimes more useful when used within another macro's expansion.
145  *
146  * @note @p _flag can be the result of preprocessor expansion, e.g.
147  *	 an expression involving <tt>NUM_VA_ARGS_LESS_1(...)</tt>.
148  *	 However, @p _if_1_code is only expanded if @p _flag expands
149  *	 to the integer literal 1. Integer expressions that evaluate
150  *	 to 1, e.g. after doing some arithmetic, will not work.
151  *
152  * @param _flag evaluated flag
153  * @param _if_1_code result if @p _flag expands to 1; must be in parentheses
154  * @param _else_code result otherwise; must be in parentheses
155  */
156 #define COND_CODE_1(_flag, _if_1_code, _else_code) \
157 	Z_COND_CODE_1(_flag, _if_1_code, _else_code)
158 
159 /**
160  * @brief Like COND_CODE_1() except tests if @p _flag is 0.
161  *
162  * This is like COND_CODE_1(), except that it tests whether @p _flag
163  * expands to the integer literal 0. It expands to @p _if_0_code if
164  * so, and @p _else_code otherwise; both of these must be enclosed in
165  * parentheses.
166  *
167  * @param _flag evaluated flag
168  * @param _if_0_code result if @p _flag expands to 0; must be in parentheses
169  * @param _else_code result otherwise; must be in parentheses
170  * @see COND_CODE_1()
171  */
172 #define COND_CODE_0(_flag, _if_0_code, _else_code) \
173 	Z_COND_CODE_0(_flag, _if_0_code, _else_code)
174 
175 /**
176  * @brief Insert code if @p _flag is defined and equals 1.
177  *
178  * Like COND_CODE_1(), this expands to @p _code if @p _flag is defined to 1;
179  * it expands to nothing otherwise.
180  *
181  * Example:
182  *
183  *     IF_ENABLED(CONFIG_FLAG, (uint32_t foo;))
184  *
185  * If @p CONFIG_FLAG is defined to 1, this expands to:
186  *
187  *     uint32_t foo;
188  *
189  * and to nothing otherwise.
190  *
191  * It can be considered as a more compact alternative to:
192  *
193  *     #if defined(CONFIG_FLAG) && (CONFIG_FLAG == 1)
194  *     uint32_t foo;
195  *     #endif
196  *
197  * @param _flag evaluated flag
198  * @param _code result if @p _flag expands to 1; must be in parentheses
199  */
200 #define IF_ENABLED(_flag, _code) \
201 	COND_CODE_1(_flag, _code, ())
202 
203 /**
204  * @brief Check if a macro has a replacement expression
205  *
206  * If @p a is a macro defined to a nonempty value, this will return
207  * true, otherwise it will return false. It only works with defined
208  * macros, so an additional @p \#ifdef test may be needed in some cases.
209  *
210  * This macro may be used with COND_CODE_1() and COND_CODE_0() while
211  * processing <tt>__VA_ARGS__</tt> to avoid processing empty arguments.
212  *
213  * Note that this macro is intended to check macro names that evaluate
214  * to replacement lists being empty or containing numbers or macro name
215  * like tokens.
216  *
217  * @note Not all arguments are accepted by this macro and compilation will fail
218  *	 if argument cannot be concatenated with literal constant. That will
219  *	 happen if argument does not start with letter or number. Example
220  *	 arguments that will fail during compilation: .arg, (arg), "arg", {arg}.
221  *
222  * Example:
223  *
224  *	#define EMPTY
225  *	#define NON_EMPTY	1
226  *	#undef  UNDEFINED
227  *	IS_EMPTY(EMPTY)
228  *	IS_EMPTY(NON_EMPTY)
229  *	IS_EMPTY(UNDEFINED)
230  *	#if defined(EMPTY) && IS_EMPTY(EMPTY) == true
231  *	some_conditional_code
232  *	#endif
233  *
234  * In above examples, the invocations of IS_EMPTY(...) return @p true,
235  * @p false, and @p true; @p some_conditional_code is included.
236  *
237  * @param a macro to check for emptiness
238  */
239 #define IS_EMPTY(a) Z_IS_EMPTY_(a, 1, 0,)
240 
241 /**
242  * @brief Remove empty arguments from list.
243  *
244  * During macro expansion, <tt>__VA_ARGS__</tt> and other preprocessor
245  * generated lists may contain empty elements, e.g.:
246  *
247  *	#define LIST ,a,b,,d,
248  *
249  * Using EMPTY to show each empty element, LIST contains:
250  *
251  *      EMPTY, a, b, EMPTY, d
252  *
253  * When processing such lists, e.g. using FOR_EACH(), all empty elements
254  * will be processed, and may require filtering out.
255  * To make that process easier, it is enough to invoke LIST_DROP_EMPTY
256  * which will remove all empty elements.
257  *
258  * Example:
259  *
260  *	LIST_DROP_EMPTY(LIST)
261  *
262  * expands to:
263  *
264  *	a, b, d
265  *
266  * @param ... list to be processed
267  */
268 #define LIST_DROP_EMPTY(...) \
269 	Z_LIST_DROP_FIRST(FOR_EACH(Z_LIST_NO_EMPTIES, (), __VA_ARGS__))
270 
271 /**
272  * @brief Macro with an empty expansion
273  *
274  * This trivial definition is provided for readability when a macro
275  * should expand to an empty result, which e.g. is sometimes needed to
276  * silence checkpatch.
277  *
278  * Example:
279  *
280  *	#define LIST_ITEM(n) , item##n
281  *
282  * The above would cause checkpatch to complain, but:
283  *
284  *	#define LIST_ITEM(n) EMPTY, item##n
285  *
286  * would not.
287  */
288 #define EMPTY
289 
290 /**
291  * @brief Macro that expands to its argument
292  *
293  * This is useful in macros like @c FOR_EACH() when there is no
294  * transformation required on the list elements.
295  *
296  * @param V any value
297  */
298 #define IDENTITY(V) V
299 
300 /**
301  * @brief Get nth argument from argument list.
302  *
303  * @param N Argument index to fetch. Counter from 1.
304  * @param ... Variable list of argments from which one argument is returned.
305  *
306  * @return Nth argument.
307  */
308 #define GET_ARG_N(N, ...) Z_GET_ARG_##N(__VA_ARGS__)
309 
310 /**
311  * @brief Strips n first arguments from the argument list.
312  *
313  * @param N Number of arguments to discard.
314  * @param ... Variable list of argments.
315  *
316  * @return argument list without N first arguments.
317  */
318 #define GET_ARGS_LESS_N(N, ...) Z_GET_ARGS_LESS_##N(__VA_ARGS__)
319 
320 /**
321  * @brief Like <tt>a || b</tt>, but does evaluation and
322  * short-circuiting at C preprocessor time.
323  *
324  * This is not the same as the binary @p || operator; in particular,
325  * @p a should expand to an integer literal 0 or 1. However, @p b
326  * can be any value.
327  *
328  * This can be useful when @p b is an expression that would cause a
329  * build error when @p a is 1.
330  */
331 #define UTIL_OR(a, b) COND_CODE_1(UTIL_BOOL(a), (a), (b))
332 
333 /**
334  * @brief Like <tt>a && b</tt>, but does evaluation and
335  * short-circuiting at C preprocessor time.
336  *
337  * This is not the same as the binary @p &&, however; in particular,
338  * @p a should expand to an integer literal 0 or 1. However, @p b
339  * can be any value.
340  *
341  * This can be useful when @p b is an expression that would cause a
342  * build error when @p a is 0.
343  */
344 #define UTIL_AND(a, b) COND_CODE_1(UTIL_BOOL(a), (b), (0))
345 
346 /**
347  * @brief Generates a sequence of code.
348  *
349  * Example:
350  *
351  *     #define FOO(i, _) MY_PWM ## i ,
352  *     { UTIL_LISTIFY(PWM_COUNT, FOO) }
353  *
354  * The above two lines expand to:
355  *
356  *    { MY_PWM0 , MY_PWM1 , }
357  *
358  * @param LEN The length of the sequence. Must be an integer literal less
359  *            than 255.
360  * @param F A macro function that accepts at least two arguments:
361  *          <tt>F(i, ...)</tt>. @p F is called repeatedly in the expansion.
362  *          Its first argument @p i is the index in the sequence, and
363  *          the variable list of arguments passed to UTIL_LISTIFY are passed
364  *          through to @p F.
365  *
366  * @note Calling UTIL_LISTIFY with undefined arguments has undefined
367  * behavior.
368  */
369 #define UTIL_LISTIFY(LEN, F, ...) UTIL_CAT(Z_UTIL_LISTIFY_, LEN)(F, __VA_ARGS__)
370 
371 /**
372  * @brief Call a macro @p F on each provided argument with a given
373  *        separator between each call.
374  *
375  * Example:
376  *
377  *     #define F(x) int a##x
378  *     FOR_EACH(F, (;), 4, 5, 6);
379  *
380  * This expands to:
381  *
382  *     int a4;
383  *     int a5;
384  *     int a6;
385  *
386  * @param F Macro to invoke
387  * @param sep Separator (e.g. comma or semicolon). Must be in parentheses;
388  *            this is required to enable providing a comma as separator.
389  * @param ... Variable argument list. The macro @p F is invoked as
390  *            <tt>F(element)</tt> for each element in the list.
391  */
392 #define FOR_EACH(F, sep, ...) \
393 	Z_FOR_EACH(F, sep, REVERSE_ARGS(__VA_ARGS__))
394 
395 /**
396  * @brief Like FOR_EACH(), but with a terminator instead of a separator,
397  *        and drops empty elements from the argument list
398  *
399  * The @p sep argument to <tt>FOR_EACH(F, (sep), a, b)</tt> is a
400  * separator which is placed between calls to @p F, like this:
401  *
402  *     FOR_EACH(F, (sep), a, b) // F(a) sep F(b)
403  *                              //               ^^^ no sep here!
404  *
405  * By contrast, the @p term argument to <tt>FOR_EACH_NONEMPTY_TERM(F, (term),
406  * a, b)</tt> is added after each time @p F appears in the expansion:
407  *
408  *     FOR_EACH_NONEMPTY_TERM(F, (term), a, b) // F(a) term F(b) term
409  *                                             //                ^^^^
410  *
411  * Further, any empty elements are dropped:
412  *
413  *     FOR_EACH_NONEMPTY_TERM(F, (term), a, EMPTY, b) // F(a) term F(b) term
414  *
415  * This is more convenient in some cases, because FOR_EACH_NONEMPTY_TERM()
416  * expands to nothing when given an empty argument list, and it's
417  * often cumbersome to write a macro @p F that does the right thing
418  * even when given an empty argument.
419  *
420  * One example is when <tt>__VA_ARGS__</tt> may or may not be empty,
421  * and the results are embedded in a larger initializer:
422  *
423  *     #define SQUARE(x) ((x)*(x))
424  *
425  *     int my_array[] = {
426  *             FOR_EACH_NONEMPTY_TERM(SQUARE, (,), FOO(...))
427  *             FOR_EACH_NONEMPTY_TERM(SQUARE, (,), BAR(...))
428  *             FOR_EACH_NONEMPTY_TERM(SQUARE, (,), BAZ(...))
429  *     };
430  *
431  * This is more convenient than:
432  *
433  * 1. figuring out whether the @p FOO, @p BAR, and @p BAZ expansions
434  *    are empty and adding a comma manually (or not) between FOR_EACH()
435  *    calls
436  * 2. rewriting SQUARE so it reacts appropriately when "x" is empty
437  *    (which would be necessary if e.g. @p FOO expands to nothing)
438  *
439  * @param F Macro to invoke on each nonempty element of the variable
440  *          arguments
441  * @param term Terminator (e.g. comma or semicolon) placed after each
442  *             invocation of F. Must be in parentheses; this is required
443  *             to enable providing a comma as separator.
444  * @param ... Variable argument list. The macro @p F is invoked as
445  *            <tt>F(element)</tt> for each nonempty element in the list.
446  */
447 #define FOR_EACH_NONEMPTY_TERM(F, term, ...)				\
448 	COND_CODE_0(							\
449 		/* are there zero non-empty arguments ? */		\
450 		NUM_VA_ARGS_LESS_1(LIST_DROP_EMPTY(__VA_ARGS__, _)),	\
451 		/* if so, expand to nothing */				\
452 		(),							\
453 		/* otherwise, expand to: */				\
454 		(/* FOR_EACH() on nonempty elements, */		\
455 			FOR_EACH(F, term, LIST_DROP_EMPTY(__VA_ARGS__))	\
456 			/* plus a final terminator */			\
457 			__DEBRACKET term				\
458 		))
459 
460 /**
461  * @brief Call macro @p F on each provided argument, with the argument's index
462  *        as an additional parameter.
463  *
464  * This is like FOR_EACH(), except @p F should be a macro which takes two
465  * arguments: <tt>F(index, variable_arg)</tt>.
466  *
467  * Example:
468  *
469  *     #define F(idx, x) int a##idx = x
470  *     FOR_EACH_IDX(F, (;), 4, 5, 6);
471  *
472  * This expands to:
473  *
474  *     int a0 = 4;
475  *     int a1 = 5;
476  *     int a2 = 6;
477  *
478  * @param F Macro to invoke
479  * @param sep Separator (e.g. comma or semicolon). Must be in parentheses;
480  *            this is required to enable providing a comma as separator.
481  * @param ... Variable argument list. The macro @p F is invoked as
482  *            <tt>F(index, element)</tt> for each element in the list.
483  */
484 #define FOR_EACH_IDX(F, sep, ...) \
485 	Z_FOR_EACH_IDX(F, sep, REVERSE_ARGS(__VA_ARGS__))
486 
487 /**
488  * @brief Call macro @p F on each provided argument, with an additional fixed
489  *	  argument as a parameter.
490  *
491  * This is like FOR_EACH(), except @p F should be a macro which takes two
492  * arguments: <tt>F(variable_arg, fixed_arg)</tt>.
493  *
494  * Example:
495  *
496  *     static void func(int val, void *dev);
497  *     FOR_EACH_FIXED_ARG(func, (;), dev, 4, 5, 6);
498  *
499  * This expands to:
500  *
501  *     func(4, dev);
502  *     func(5, dev);
503  *     func(6, dev);
504  *
505  * @param F Macro to invoke
506  * @param sep Separator (e.g. comma or semicolon). Must be in parentheses;
507  *            this is required to enable providing a comma as separator.
508  * @param fixed_arg Fixed argument passed to @p F as the second macro parameter.
509  * @param ... Variable argument list. The macro @p F is invoked as
510  *            <tt>F(element, fixed_arg)</tt> for each element in the list.
511  */
512 #define FOR_EACH_FIXED_ARG(F, sep, fixed_arg, ...) \
513 	Z_FOR_EACH_FIXED_ARG(F, sep, fixed_arg, REVERSE_ARGS(__VA_ARGS__))
514 
515 /**
516  * @brief Calls macro @p F for each variable argument with an index and fixed
517  *        argument
518  *
519  * This is like the combination of FOR_EACH_IDX() with FOR_EACH_FIXED_ARG().
520  *
521  * Example:
522  *
523  *     #define F(idx, x, fixed_arg) int fixed_arg##idx = x
524  *     FOR_EACH_IDX_FIXED_ARG(F, (;), a, 4, 5, 6);
525  *
526  * This expands to:
527  *
528  *     int a0 = 4;
529  *     int a1 = 5;
530  *     int a2 = 6;
531  *
532  * @param F Macro to invoke
533  * @param sep Separator (e.g. comma or semicolon). Must be in parentheses;
534  *            This is required to enable providing a comma as separator.
535  * @param fixed_arg Fixed argument passed to @p F as the third macro parameter.
536  * @param ... Variable list of arguments. The macro @p F is invoked as
537  *            <tt>F(index, element, fixed_arg)</tt> for each element in
538  *            the list.
539  */
540 #define FOR_EACH_IDX_FIXED_ARG(F, sep, fixed_arg, ...) \
541 	Z_FOR_EACH_IDX_FIXED_ARG(F, sep, fixed_arg, REVERSE_ARGS(__VA_ARGS__))
542 
543 /** @brief Reverse arguments order.
544  *
545  * @param ... Variable argument list.
546  */
547 #define REVERSE_ARGS(...) \
548 	Z_FOR_EACH_ENGINE(Z_FOR_EACH_EXEC, (,), Z_BYPASS, _, __VA_ARGS__)
549 
550 /**
551  * @brief Number of arguments in the variable arguments list minus one.
552  *
553  * @param ... List of arguments
554  * @return  Number of variadic arguments in the argument list, minus one
555  */
556 #define NUM_VA_ARGS_LESS_1(...) \
557 	NUM_VA_ARGS_LESS_1_IMPL(__VA_ARGS__, 63, 62, 61, \
558 	60, 59, 58, 57, 56, 55, 54, 53, 52, 51,		 \
559 	50, 49, 48, 47, 46, 45, 44, 43, 42, 41,		 \
560 	40, 39, 38, 37, 36, 35, 34, 33, 32, 31,		 \
561 	30, 29, 28, 27, 26, 25, 24, 23, 22, 21,		 \
562 	20, 19, 18, 17, 16, 15, 14, 13, 12, 11,		 \
563 	10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, ~)
564 
565 /**
566  * @brief Mapping macro that pastes results together
567  *
568  * This is similar to FOR_EACH() in that it invokes a macro repeatedly
569  * on each element of <tt>__VA_ARGS__</tt>. However, unlike FOR_EACH(),
570  * MACRO_MAP_CAT() pastes the results together into a single token.
571  *
572  * For example, with this macro FOO:
573  *
574  *     #define FOO(x) item_##x##_
575  *
576  * <tt>MACRO_MAP_CAT(FOO, a, b, c),</tt> expands to the token:
577  *
578  *     item_a_item_b_item_c_
579  *
580  * @param ... Macro to expand on each argument, followed by its
581  *            arguments. (The macro should take exactly one argument.)
582  * @return The results of expanding the macro on each argument, all pasted
583  *         together
584  */
585 #define MACRO_MAP_CAT(...) MACRO_MAP_CAT_(__VA_ARGS__)
586 
587 /**
588  * @brief Mapping macro that pastes a fixed number of results together
589  *
590  * Similar to @ref MACRO_MAP_CAT(), but expects a fixed number of
591  * arguments. If more arguments are given than are expected, the rest
592  * are ignored.
593  *
594  * @param N   Number of arguments to map
595  * @param ... Macro to expand on each argument, followed by its
596  *            arguments. (The macro should take exactly one argument.)
597  * @return The results of expanding the macro on each argument, all pasted
598  *         together
599  */
600 #define MACRO_MAP_CAT_N(N, ...) MACRO_MAP_CAT_N_(N, __VA_ARGS__)
601 
602 /**
603  * @}
604  */
605 
606 #ifdef __cplusplus
607 }
608 #endif
609 
610 #endif /* ZEPHYR_INCLUDE_SYS_UTIL_MACROS_H_ */
611