2 * This file is part of DisOrder
3 * Copyright (C) 2008 Richard Kettlewell
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
21 /** @file lib/macros.c
22 * @brief Macro expansion
42 VECTOR_TYPE(mx_node_vector
, const struct mx_node
*, xrealloc
);
44 /** @brief Definition of an expansion */
46 /** @brief Minimum permitted arguments */
49 /** @brief Maximum permitted arguments */
58 * - @ref EXP_TYPE_MASK
62 /** @brief Macro argument names */
65 /** @brief Callback (cast to appropriate type)
67 * Cast to @ref mx_simple_callback or @ref mx_magic_callback as required. */
70 /** @brief Macro definition
72 * Only for @ref EXP_MACRO expansions. */
73 const struct mx_node
*definition
;
76 /** @brief Expansion takes pre-expanded strings
78 * @p callback is cast to @ref mx_simple_callback. */
79 #define EXP_SIMPLE 0x0000
81 /** @brief Expansion takes parsed templates, not strings
83 * @p callback is cast to @ref mx_magic_callback. The callback must do its own
84 * expansion e.g. via mx_expandstr() where necessary. */
85 #define EXP_MAGIC 0x0001
87 /** @brief Expansion is a macro */
88 #define EXP_MACRO 0x0002
90 /** @brief Mask of types */
91 #define EXP_TYPE_MASK 0x0003
93 /** @brief Hash of all expansions
95 * Created by mx_register(), mx_register_macro() or mx_register_magic().
97 static hash
*expansions
;
99 static int mx__expand_macro(const struct expansion
*e
,
100 const struct mx_node
*m
,
104 /* Parsing ------------------------------------------------------------------ */
106 static int next_non_whitespace(const char *input
,
108 while(input
< end
&& isspace((unsigned char)*input
))
110 return input
< end ?
*input
: -1;
113 /** @brief Parse a template
114 * @param filename Input filename (for diagnostics)
115 * @param line Line number (use 1 on initial call)
116 * @param input Start of text to parse
117 * @param end End of text to parse or NULL
118 * @return Pointer to parse tree root node
120 * Parses the text in [start, end) and returns an (immutable) parse
121 * tree representing it.
123 * If @p end is NULL then the whole string is parsed.
125 * Note that the @p filename value stored in the parse tree is @p filename,
126 * i.e. it is not copied.
128 const struct mx_node
*mx_parse(const char *filename
,
132 int braces
, argument_start_line
, obracket
, cbracket
;
133 const char *argument_start
, *argument_end
;
134 struct mx_node_vector v
[1];
136 struct mx_node
*head
= 0, **tailp
= &head
, *e
;
139 end
= input
+ strlen(input
);
142 e
= xmalloc(sizeof *e
);
144 e
->filename
= filename
;
148 /* Gather up text without any expansions in. */
149 while(input
< end
&& *input
!= '@') {
152 dynstr_append(d
, *input
++);
163 /* '@@' expands to '@' */
164 e
= xmalloc(sizeof *e
);
166 e
->filename
= filename
;
175 /* '@#' starts a (newline-eating comment), like dnl */
177 while(input
< end
&& *input
!= '\n')
185 /* '@_' expands to nothing. It's there to allow dump to terminate
186 * expansions without having to know what follows. */
190 /* It's a full expansion */
192 e
= xmalloc(sizeof *e
);
194 e
->filename
= filename
;
196 e
->type
= MX_EXPANSION
;
197 /* Collect the expansion name. Expansion names start with an alnum and
198 * consist of alnums and '-'. We don't permit whitespace between the '@'
202 fatal(0, "%s:%d: invalid expansion syntax (truncated)",
204 if(!isalnum((unsigned char)*input
))
205 fatal(0, "%s:%d: invalid expansion syntax (unexpected %#x)",
206 filename
, e
->line
, (unsigned char)*input
);
207 while(input
< end
&& (isalnum((unsigned char)*input
) || *input
== '-'))
208 dynstr_append(d
, *input
++);
211 /* See what the bracket character is */
212 obracket
= next_non_whitespace(input
, end
);
214 case '(': cbracket
= ')'; break;
215 case '[': cbracket
= ']'; break;
216 case '{': cbracket
= '}'; break;
217 default: cbracket
= obracket
= -1; break; /* no arguments */
219 mx_node_vector_init(v
);
221 /* Gather up arguments */
222 while(next_non_whitespace(input
, end
) == obracket
) {
223 while(isspace((unsigned char)*input
)) {
228 ++input
; /* the bracket */
230 /* Find the end of the argument */
231 argument_start
= input
;
232 argument_start_line
= line
;
233 while(input
< end
&& (*input
!= cbracket
|| braces
> 0)) {
234 const int c
= *input
++;
238 else if(c
== cbracket
)
244 /* We ran out of input without encountering a balanced cbracket */
245 fatal(0, "%s:%d: unterminated expansion argument '%.*s'",
246 filename
, argument_start_line
,
247 (int)(input
- argument_start
), argument_start
);
249 /* Consistency check */
250 assert(*input
== cbracket
);
251 /* Record the end of the argument */
252 argument_end
= input
;
253 /* Step over the cbracket */
255 /* Now we have an argument in [argument_start, argument_end), and we
256 * know its filename and initial line number. This is sufficient to
258 mx_node_vector_append(v
, mx_parse(filename
, argument_start_line
,
259 argument_start
, argument_end
));
262 /* Guarantee a NULL terminator (for the case where there's more than one
264 mx_node_vector_terminate(v
);
265 /* Fill in the remains of the node */
274 static void mx__dump(struct dynstr
*d
, const struct mx_node
*m
) {
276 const struct mx_node
*mm
;
282 if(m
->text
[0] == '@')
283 dynstr_append(d
, '@');
284 dynstr_append_string(d
, m
->text
);
287 dynstr_append(d
, '@');
288 dynstr_append_string(d
, m
->name
);
289 for(n
= 0; n
< m
->nargs
; ++n
) {
290 dynstr_append(d
, '{');
291 mx__dump(d
, m
->args
[n
]);
292 dynstr_append(d
, '}');
294 /* If the next non-whitespace is '{', add @_ to stop it being
297 while(mm
&& mm
->type
== MX_TEXT
) {
298 switch(next_non_whitespace(mm
->text
, mm
->text
+ strlen(mm
->text
))) {
303 dynstr_append_string(d
, "@_");
312 assert(!"invalid m->type");
314 mx__dump(d
, m
->next
);
317 /** @brief Dump a parse macro expansion to a string
319 * Not of production quality! Only intended for testing!
321 char *mx_dump(const struct mx_node
*m
) {
330 /* Expansion registration --------------------------------------------------- */
332 static int mx__register(unsigned flags
,
338 const struct mx_node
*definition
) {
339 struct expansion e
[1];
342 expansions
= hash_new(sizeof(struct expansion
));
347 e
->callback
= callback
;
348 e
->definition
= definition
;
349 return hash_add(expansions
, name
, &e
, HASH_INSERT_OR_REPLACE
);
352 /** @brief Register a simple expansion rule
354 * @param min Minimum number of arguments
355 * @param max Maximum number of arguments
356 * @param callback Callback to write output
358 void mx_register(const char *name
,
361 mx_simple_callback
*callback
) {
362 mx__register(EXP_SIMPLE
, name
, min
, max
, 0, (void (*)())callback
, 0);
365 /** @brief Register a magic expansion rule
367 * @param min Minimum number of arguments
368 * @param max Maximum number of arguments
369 * @param callback Callback to write output
371 void mx_register_magic(const char *name
,
374 mx_magic_callback
*callback
) {
375 mx__register(EXP_MAGIC
, name
, min
, max
, 0, (void (*)())callback
, 0);
378 /** @brief Register a macro
380 * @param nargs Number of arguments
381 * @param args Argument names
382 * @param definition Macro definition
383 * @return 0 on success, negative on error
385 int mx_register_macro(const char *name
,
388 const struct mx_node
*definition
) {
389 if(mx__register(EXP_MACRO
, name
, nargs
, nargs
, args
, 0/*callback*/,
392 /* This locates the error to the definition, which may be a line or two
393 * beyond the @define command itself. The backtrace generated by
394 * mx_expand() may help more. */
395 error(0, "%s:%d: duplicate definition of '%s'",
396 definition
->filename
, definition
->line
, name
);
403 /* Expansion ---------------------------------------------------------------- */
405 /** @brief Expand a template
406 * @param m Where to start
407 * @param output Where to send output
409 * @return 0 on success, non-0 on error
411 * Interpretation of return values:
413 * - -1 means an error writing to the sink.
414 * - other negative values mean errors generated from with the macro
416 * - positive values are reserved for the application
418 * If any callback returns non-zero then that value is returned, abandoning
421 int mx_expand(const struct mx_node
*m
,
424 const struct expansion
*e
;
431 if(sink_writes(output
, m
->text
) < 0)
436 if(!(e
= hash_find(expansions
, m
->name
))) {
437 error(0, "%s:%d: unknown expansion name '%s'",
438 m
->filename
, m
->line
, m
->name
);
439 if(sink_printf(output
, "[['%s' unknown]]", m
->name
) < 0)
441 } else if(m
->nargs
< e
->min
) {
442 error(0, "%s:%d: expansion '%s' requires %d args, only %d given",
443 m
->filename
, m
->line
, m
->name
, e
->min
, m
->nargs
);
444 if(sink_printf(output
, "[['%s' too few args]]", m
->name
) < 0)
446 } else if(m
->nargs
> e
->max
) {
447 error(0, "%s:%d: expansion '%s' takes at most %d args, but %d given",
448 m
->filename
, m
->line
, m
->name
, e
->max
, m
->nargs
);
449 if(sink_printf(output
, "[['%s' too many args]]", m
->name
) < 0)
451 } else switch(e
->flags
& EXP_TYPE_MASK
) {
453 /* Magic callbacks we can call directly */
454 rc
= ((mx_magic_callback
*)e
->callback
)(m
->nargs
,
461 /* For simple callbacks we expand their arguments for them. */
462 char **args
= xcalloc(1 + m
->nargs
, sizeof (char *)), *argname
;
465 for(n
= 0; n
< m
->nargs
; ++n
) {
466 /* Argument numbers are at least clear from looking at the text;
467 * adding names as well would be nice. TODO */
468 byte_xasprintf(&argname
, "argument #%d", n
);
469 if((rc
= mx_expandstr(m
->args
[n
], &args
[n
], u
, argname
)))
474 rc
= ((mx_simple_callback
*)e
->callback
)(m
->nargs
,
482 /* Macros we expand by rewriting their definition with argument values
483 * substituted and then expanding that. */
484 rc
= mx__expand_macro(e
, m
, output
, u
);
488 assert(!"impossible EXP_TYPE_MASK value");
491 /* For non-IO errors we generate some backtrace */
493 error(0, " ...in @%s at %s:%d",
494 m
->name
, m
->filename
, m
->line
);
499 assert(!"invalid m->type");
501 return mx_expand(m
->next
, output
, u
);
504 /** @brief Expand a template storing the result in a string
505 * @param m Where to start
506 * @param sp Where to store string
508 * @param what Token for backtrace, or NULL
509 * @return 0 on success, non-0 on error
511 * Same return conventions as mx_expand(). This wrapper is slightly more
512 * convenient to use from 'magic' expansions.
514 int mx_expandstr(const struct mx_node
*m
,
522 if(!(rc
= mx_expand(m
, sink_dynstr(d
), u
))) {
527 if(rc
&& rc
!= -1 && what
)
528 error(0, " ...in %s at %s:%d", what
, m
->filename
, m
->line
);
532 /** @brief Expand a template file
533 * @param path Filename
534 * @param output Where to send output
536 * @return 0 on success, non-0 on error
538 * Same return conventions as mx_expand().
540 int mx_expand_file(const char *path
,
547 const struct mx_node
*m
;
549 if((fd
= open(path
, O_RDONLY
)) < 0)
550 fatal(errno
, "error opening %s", path
);
551 if(fstat(fd
, &sb
) < 0)
552 fatal(errno
, "error statting %s", path
);
553 if(!S_ISREG(sb
.st_mode
))
554 fatal(0, "%s: not a regular file", path
);
556 b
= xmalloc_noptr(sb
.st_size
);
557 while(sofar
< sb
.st_size
) {
558 n
= read(fd
, b
+ sofar
, sb
.st_size
- sofar
);
562 fatal(0, "unexpected EOF reading %s", path
);
563 else if(errno
!= EINTR
)
564 fatal(errno
, "error reading %s", path
);
567 m
= mx_parse(path
, 1, b
, b
+ sb
.st_size
);
568 rc
= mx_expand(m
, output
, u
);
570 /* Mention inclusion in backtrace */
571 error(0, " ...in inclusion of file '%s'", path
);
575 /* Macros ------------------------------------------------------------------- */
577 /** @brief Rewrite a parse tree substituting sub-expansions
578 * @param m Parse tree to rewrite (from macro definition)
579 * @param ... Name/value pairs to rewrite
580 * @return Rewritten parse tree
582 * The name/value pair list consists of pairs of strings and is terminated by
583 * (char *)0. Names and values are both copied so need not survive the call.
585 const struct mx_node
*mx_rewritel(const struct mx_node
*m
,
588 hash
*h
= hash_new(sizeof (struct mx_node
*));
593 while((n
= va_arg(ap
, const char *))) {
594 v
= va_arg(ap
, const char *);
595 e
= xmalloc(sizeof *e
);
597 e
->filename
= m
->filename
;
600 e
->text
= xstrdup(v
);
601 hash_add(h
, n
, &e
, HASH_INSERT
);
602 /* hash_add() copies n */
604 return mx_rewrite(m
, h
);
607 /** @brief Rewrite a parse tree substituting in macro arguments
608 * @param definition Parse tree to rewrite (from macro definition)
609 * @param h Hash mapping argument names to argument values
610 * @return Rewritten parse tree
612 const struct mx_node
*mx_rewrite(const struct mx_node
*definition
,
614 const struct mx_node
*head
= 0, **tailp
= &head
, *argvalue
, *m
, *mm
, **ap
;
618 for(m
= definition
; m
; m
= m
->next
) {
621 nm
= xmalloc(sizeof *nm
);
622 *nm
= *m
; /* Dumb copy of text node fields */
623 nm
->next
= 0; /* Maintain list structure */
625 tailp
= (const struct mx_node
**)&nm
->next
;
629 && (ap
= hash_find(h
, m
->name
))) {
630 /* This expansion has no arguments and its name matches one of the
631 * macro arguments. (Even if it's a valid expansion name we override
632 * it.) We insert its value at this point. We do NOT recursively
633 * rewrite the argument's value - it is outside the lexical scope of
636 * We need to recreate the list structure but a shallow copy will
640 for(mm
= argvalue
; mm
; mm
= mm
->next
) {
641 nm
= xmalloc(sizeof *nm
);
645 tailp
= (const struct mx_node
**)&nm
->next
;
648 /* This is some other expansion. We recursively rewrite its argument
649 * values according to h. */
650 nm
= xmalloc(sizeof *nm
);
652 nm
->args
= xcalloc(nm
->nargs
, sizeof (struct mx_node
*));
653 for(n
= 0; n
< nm
->nargs
; ++n
)
654 nm
->args
[n
] = mx_rewrite(m
->args
[n
], h
);
657 tailp
= (const struct mx_node
**)&nm
->next
;
661 assert(!"invalid m->type");
664 *tailp
= 0; /* Mark end of list */
668 /** @brief Expand a macro
669 * @param e Macro definition
670 * @param m Macro expansion
671 * @param output Where to send output
673 * @return 0 on success, non-0 on error
675 static int mx__expand_macro(const struct expansion
*e
,
676 const struct mx_node
*m
,
679 hash
*h
= hash_new(sizeof (struct mx_node
*));
682 /* We store the macro arguments in a hash. Currently there is no check for
683 * duplicate argument names (and this would be the wrong place for it
684 * anyway); if you do that you just lose in some undefined way. */
685 for(n
= 0; n
< m
->nargs
; ++n
)
686 hash_add(h
, e
->args
[n
], &m
->args
[n
], HASH_INSERT
);
687 /* Generate a rewritten parse tree */
688 m
= mx_rewrite(e
->definition
, h
);
689 /* Expand the result */
690 return mx_expand(m
, output
, u
);
691 /* mx_expand() will update the backtrace */