chiark / gitweb /
SIGTERM and wait for subprocesses on server shutdown.
[disorder] / lib / macros.c
1 /*
2  * This file is part of DisOrder
3  * Copyright (C) 2008 Richard Kettlewell
4  *
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 3 of the License, or
8  * (at your option) any later version.
9  * 
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  * 
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 /** @file lib/macros.c
20  * @brief Macro expansion
21  */
22
23 #include "common.h"
24
25 #include <ctype.h>
26 #include <sys/stat.h>
27 #include <fcntl.h>
28 #include <unistd.h>
29 #include <errno.h>
30
31 #include "hash.h"
32 #include "macros.h"
33 #include "mem.h"
34 #include "vector.h"
35 #include "log.h"
36 #include "sink.h"
37 #include "syscalls.h"
38 #include "printf.h"
39
40 VECTOR_TYPE(mx_node_vector, const struct mx_node *, xrealloc);
41
42 /** @brief Definition of an expansion */
43 struct expansion {
44   /** @brief Minimum permitted arguments */
45   int min;
46
47   /** @brief Maximum permitted arguments */
48   int max;
49
50   /** @brief Flags
51    *
52    * See:
53    * - @ref EXP_SIMPLE
54    * - @ref EXP_MAGIC
55    * - @ref EXP_MACRO
56    * - @ref EXP_TYPE_MASK
57    */
58   unsigned flags;
59
60   /** @brief Macro argument names */
61   char **args;
62
63   /** @brief Callback (cast to appropriate type)
64    *
65    * Cast to @ref mx_simple_callback or @ref mx_magic_callback as required. */
66   void (*callback)();
67
68   /** @brief Macro definition
69    *
70    * Only for @ref EXP_MACRO expansions. */
71   const struct mx_node *definition;
72 };
73
74 /** @brief Expansion takes pre-expanded strings
75  *
76  * @p callback is cast to @ref mx_simple_callback. */
77 #define EXP_SIMPLE 0x0000
78
79 /** @brief Expansion takes parsed templates, not strings
80  *
81  * @p callback is cast to @ref mx_magic_callback.  The callback must do its own
82  * expansion e.g. via mx_expandstr() where necessary. */
83 #define EXP_MAGIC 0x0001
84
85 /** @brief Expansion is a macro */
86 #define EXP_MACRO 0x0002
87
88 /** @brief Mask of types */
89 #define EXP_TYPE_MASK 0x0003
90
91 /** @brief Hash of all expansions
92  *
93  * Created by mx_register(), mx_register_macro() or mx_register_magic().
94  */
95 static hash *expansions;
96
97 static int mx__expand_macro(const struct expansion *e,
98                             const struct mx_node *m,
99                             struct sink *output,
100                             void *u);
101
102 /* Parsing ------------------------------------------------------------------ */
103
104 static int next_non_whitespace(const char *input,
105                                const char *end) {
106   while(input < end && isspace((unsigned char)*input))
107     ++input;
108   return input < end ? *input : -1;
109 }
110
111 /** @brief Parse a template
112  * @param filename Input filename (for diagnostics)
113  * @param line Line number (use 1 on initial call)
114  * @param input Start of text to parse
115  * @param end End of text to parse or NULL
116  * @return Pointer to parse tree root node
117  *
118  * Parses the text in [start, end) and returns an (immutable) parse
119  * tree representing it.
120  *
121  * If @p end is NULL then the whole string is parsed.
122  *
123  * Note that the @p filename value stored in the parse tree is @p filename,
124  * i.e. it is not copied.
125  */
126 const struct mx_node *mx_parse(const char *filename,
127                                int line,
128                                const char *input,
129                                const char *end) {
130   int braces, argument_start_line, obracket, cbracket;
131   const char *argument_start, *argument_end;
132   struct mx_node_vector v[1];
133   struct dynstr d[1];
134   struct mx_node *head = 0, **tailp = &head, *e;
135
136   if(!end)
137     end = input + strlen(input);
138   while(input < end) {
139     if(*input != '@') {
140       e = xmalloc(sizeof *e);
141       e->next = 0;
142       e->filename = filename;
143       e->line = line;
144       e->type = MX_TEXT;
145       dynstr_init(d);
146       /* Gather up text without any expansions in. */
147       while(input < end && *input != '@') {
148         if(*input == '\n')
149           ++line;
150         dynstr_append(d, *input++);
151       }
152       dynstr_terminate(d);
153       e->text = d->vec;
154       *tailp = e;
155       tailp = &e->next;
156       continue;
157     }
158     if(input + 1 < end)
159       switch(input[1]) {
160       case '@':
161         /* '@@' expands to '@' */
162         e = xmalloc(sizeof *e);
163         e->next = 0;
164         e->filename = filename;
165         e->line = line;
166         e->type = MX_TEXT;
167         e->text = "@";
168         *tailp = e;
169         tailp = &e->next;
170         input += 2;
171         continue;
172       case '#':
173         /* '@#' starts a (newline-eating comment), like dnl */
174         input += 2;
175         while(input < end && *input != '\n')
176           ++input;
177         if(*input == '\n') {
178           ++line;
179           ++input;
180         }
181         continue;
182       case '_':
183         /* '@_' expands to nothing.  It's there to allow dump to terminate
184          * expansions without having to know what follows. */
185         input += 2;
186         continue;
187       }
188     /* It's a full expansion */
189     ++input;
190     e = xmalloc(sizeof *e);
191     e->next = 0;
192     e->filename = filename;
193     e->line = line;
194     e->type = MX_EXPANSION;
195     /* Collect the expansion name.  Expansion names start with an alnum and
196      * consist of alnums and '-'.  We don't permit whitespace between the '@'
197      * and the name. */
198     dynstr_init(d);
199     if(input == end)
200       fatal(0, "%s:%d: invalid expansion syntax (truncated)",
201             filename, e->line);
202     if(!isalnum((unsigned char)*input))
203       fatal(0, "%s:%d: invalid expansion syntax (unexpected %#x)",
204             filename, e->line, (unsigned char)*input);
205     while(input < end && (isalnum((unsigned char)*input) || *input == '-'))
206       dynstr_append(d, *input++);
207     dynstr_terminate(d);
208     e->name = d->vec;
209     /* See what the bracket character is */
210     obracket = next_non_whitespace(input, end);
211     switch(obracket) {
212     case '(': cbracket = ')'; break;
213     case '[': cbracket = ']'; break;
214     case '{': cbracket = '}'; break;
215     default: cbracket = obracket = -1; break;      /* no arguments */
216     }
217     mx_node_vector_init(v);
218     if(obracket >= 0) {
219       /* Gather up arguments */
220       while(next_non_whitespace(input, end) == obracket) {
221         while(isspace((unsigned char)*input)) {
222           if(*input == '\n')
223             ++line;
224           ++input;
225         }
226         ++input;                        /* the bracket */
227         braces = 0;
228         /* Find the end of the argument */
229         argument_start = input;
230         argument_start_line = line;
231         while(input < end && (*input != cbracket || braces > 0)) {
232           const int c = *input++;
233
234           if(c == obracket)
235             ++braces;
236           else if(c == cbracket)
237             --braces;
238           else if(c == '\n')
239             ++line;
240         }
241         if(input >= end) {
242           /* We ran out of input without encountering a balanced cbracket */
243           fatal(0, "%s:%d: unterminated expansion argument '%.*s'",
244                 filename, argument_start_line,
245                 (int)(input - argument_start), argument_start);
246         }
247         /* Consistency check */
248         assert(*input == cbracket);
249         /* Record the end of the argument */
250         argument_end = input;
251         /* Step over the cbracket */
252         ++input;
253         /* Now we have an argument in [argument_start, argument_end), and we
254          * know its filename and initial line number.  This is sufficient to
255          * parse it. */
256         mx_node_vector_append(v, mx_parse(filename, argument_start_line,
257                                           argument_start, argument_end));
258       }
259     }
260     /* Guarantee a NULL terminator (for the case where there's more than one
261      * argument) */
262     mx_node_vector_terminate(v);
263     /* Fill in the remains of the node */
264     e->nargs = v->nvec;
265     e->args = v->vec;
266     *tailp = e;
267     tailp = &e->next;
268   }
269   return head;
270 }
271
272 static void mx__dump(struct dynstr *d, const struct mx_node *m) {
273   int n;
274   const struct mx_node *mm;
275
276   if(!m)
277     return;
278   switch(m->type) {
279   case MX_TEXT:
280     if(m->text[0] == '@')
281       dynstr_append(d, '@');
282     dynstr_append_string(d, m->text);
283     break;
284   case MX_EXPANSION:
285     dynstr_append(d, '@');
286     dynstr_append_string(d, m->name);
287     for(n = 0; n < m->nargs; ++n) {
288       dynstr_append(d, '{');
289       mx__dump(d, m->args[n]);
290       dynstr_append(d, '}');
291     }
292     /* If the next non-whitespace is '{', add @_ to stop it being
293      * misinterpreted */
294     mm = m->next;
295     while(mm && mm->type == MX_TEXT) {
296       switch(next_non_whitespace(mm->text, mm->text + strlen(mm->text))) {
297       case -1:
298         mm = mm->next;
299         continue;
300       case '{':
301         dynstr_append_string(d, "@_");
302         break;
303       default:
304         break;
305       }
306       break;
307     }
308     break;
309   default:
310     assert(!"invalid m->type");
311   }
312   mx__dump(d, m->next);
313 }
314
315 /** @brief Dump a parse macro expansion to a string
316  *
317  * Not of production quality!  Only intended for testing!
318  */
319 char *mx_dump(const struct mx_node *m) {
320   struct dynstr d[1];
321
322   dynstr_init(d);
323   mx__dump(d, m);
324   dynstr_terminate(d);
325   return d->vec;
326 }
327
328 /* Expansion registration --------------------------------------------------- */
329
330 static int mx__register(unsigned flags,
331                         const char *name,
332                         int min,
333                         int max,
334                         char **args,
335                         void (*callback)(),
336                         const struct mx_node *definition) {
337   struct expansion e[1];
338
339   if(!expansions)
340     expansions = hash_new(sizeof(struct expansion));
341   e->min = min;
342   e->max = max;
343   e->flags = flags;
344   e->args = args;
345   e->callback = callback;
346   e->definition = definition;
347   return hash_add(expansions, name, &e, HASH_INSERT_OR_REPLACE);
348 }
349
350 /** @brief Register a simple expansion rule
351  * @param name Name
352  * @param min Minimum number of arguments
353  * @param max Maximum number of arguments
354  * @param callback Callback to write output
355  */
356 void mx_register(const char *name,
357                  int min,
358                  int max,
359                  mx_simple_callback *callback) {
360   mx__register(EXP_SIMPLE,  name, min, max, 0, (void (*)())callback, 0);
361 }
362
363 /** @brief Register a magic expansion rule
364  * @param name Name
365  * @param min Minimum number of arguments
366  * @param max Maximum number of arguments
367  * @param callback Callback to write output
368  */
369 void mx_register_magic(const char *name,
370                        int min,
371                        int max,
372                        mx_magic_callback *callback) {
373   mx__register(EXP_MAGIC, name, min, max, 0, (void (*)())callback, 0);
374 }
375
376 /** @brief Register a macro
377  * @param name Name
378  * @param nargs Number of arguments
379  * @param args Argument names
380  * @param definition Macro definition
381  * @return 0 on success, negative on error
382  */
383 int mx_register_macro(const char *name,
384                       int nargs,
385                       char **args,
386                       const struct mx_node *definition) {
387   if(mx__register(EXP_MACRO, name, nargs, nargs, args,  0/*callback*/,
388                   definition)) {
389 #if 0
390     /* This locates the error to the definition, which may be a line or two
391      * beyond the @define command itself.  The backtrace generated by
392      * mx_expand() may help more. */
393     error(0, "%s:%d: duplicate definition of '%s'",
394           definition->filename, definition->line, name);
395 #endif
396     return -2;
397   }
398   return 0;
399 }
400
401 /* Expansion ---------------------------------------------------------------- */
402
403 /** @brief Expand a template
404  * @param m Where to start
405  * @param output Where to send output
406  * @param u User data
407  * @return 0 on success, non-0 on error
408  *
409  * Interpretation of return values:
410  * - 0 means success
411  * - -1 means an error writing to the sink.
412  * - other negative values mean errors generated from with the macro
413  *   expansion system
414  * - positive values are reserved for the application
415  *
416  * If any callback returns non-zero then that value is returned, abandoning
417  * further expansion.
418  */
419 int mx_expand(const struct mx_node *m,
420               struct sink *output,
421               void *u) {
422   const struct expansion *e;
423   int rc;
424
425   if(!m)
426     return 0;
427   switch(m->type) {
428   case MX_TEXT:
429     if(sink_writes(output, m->text) < 0)
430       return -1;
431     break;
432   case MX_EXPANSION:
433     rc = 0;
434     if(!(e = hash_find(expansions, m->name))) {
435       error(0, "%s:%d: unknown expansion name '%s'",
436             m->filename, m->line, m->name);
437       if(sink_printf(output, "[['%s' unknown]]", m->name) < 0)
438         return -1;
439     } else if(m->nargs < e->min) {
440       error(0, "%s:%d: expansion '%s' requires %d args, only %d given",
441             m->filename, m->line, m->name, e->min, m->nargs);
442       if(sink_printf(output, "[['%s' too few args]]", m->name) < 0)
443         return -1;
444     } else if(m->nargs > e->max) {
445       error(0, "%s:%d: expansion '%s' takes at most %d args, but %d given",
446             m->filename, m->line, m->name, e->max, m->nargs);
447       if(sink_printf(output, "[['%s' too many args]]", m->name) < 0)
448         return -1;
449     } else switch(e->flags & EXP_TYPE_MASK) {
450       case EXP_MAGIC: {
451         /* Magic callbacks we can call directly */
452         rc = ((mx_magic_callback *)e->callback)(m->nargs,
453                                                 m->args,
454                                                 output,
455                                                 u);
456         break;
457       }
458       case EXP_SIMPLE: {
459         /* For simple callbacks we expand their arguments for them. */
460         char **args = xcalloc(1 + m->nargs, sizeof (char *)), *argname;
461         int n;
462         
463         for(n = 0; n < m->nargs; ++n) {
464           /* Argument numbers are at least clear from looking at the text;
465            * adding names as well would be nice.  TODO */
466           byte_xasprintf(&argname, "argument #%d", n);
467           if((rc = mx_expandstr(m->args[n], &args[n], u, argname)))
468             break;
469         }
470         if(!rc) {
471           args[n] = NULL;
472           rc = ((mx_simple_callback *)e->callback)(m->nargs,
473                                                    args,
474                                                    output,
475                                                    u);
476         }
477         break;
478       }
479       case EXP_MACRO: {
480         /* Macros we expand by rewriting their definition with argument values
481          * substituted and then expanding that. */
482         rc = mx__expand_macro(e, m, output, u);
483         break;
484       }
485       default:
486         assert(!"impossible EXP_TYPE_MASK value");
487     }
488     if(rc) {
489       /* For non-IO errors we generate some backtrace */
490       if(rc != -1)
491         error(0,  "  ...in @%s at %s:%d",
492               m->name, m->filename, m->line);
493       return rc;
494     }
495     break;
496   default:
497     assert(!"invalid m->type");
498   }
499   return mx_expand(m->next, output, u);
500 }
501
502 /** @brief Expand a template storing the result in a string
503  * @param m Where to start
504  * @param sp Where to store string
505  * @param u User data
506  * @param what Token for backtrace, or NULL
507  * @return 0 on success, non-0 on error
508  *
509  * Same return conventions as mx_expand().  This wrapper is slightly more
510  * convenient to use from 'magic' expansions.
511  */
512 int mx_expandstr(const struct mx_node *m,
513                  char **sp,
514                  void *u,
515                  const char *what) {
516   struct dynstr d[1];
517   int rc;
518
519   dynstr_init(d);
520   if(!(rc = mx_expand(m, sink_dynstr(d), u))) {
521     dynstr_terminate(d);
522     *sp = d->vec;
523   } else
524     *sp = 0;
525   if(rc && rc != -1 && what)
526     error(0, "  ...in %s at %s:%d", what, m->filename, m->line);
527   return rc;
528 }
529
530 /** @brief Expand a template file
531  * @param path Filename
532  * @param output Where to send output
533  * @param u User data
534  * @return 0 on success, non-0 on error
535  *
536  * Same return conventions as mx_expand().
537  */
538 int mx_expand_file(const char *path,
539                    struct sink *output,
540                    void *u) {
541   int fd, n, rc;
542   struct stat sb;
543   char *b;
544   off_t sofar;
545   const struct mx_node *m;
546
547   if((fd = open(path, O_RDONLY)) < 0)
548     fatal(errno, "error opening %s", path);
549   if(fstat(fd, &sb) < 0)
550     fatal(errno, "error statting %s", path);
551   if(!S_ISREG(sb.st_mode))
552     fatal(0, "%s: not a regular file", path);
553   sofar = 0;
554   b = xmalloc_noptr(sb.st_size);
555   while(sofar < sb.st_size) {
556     n = read(fd, b + sofar, sb.st_size - sofar);
557     if(n > 0)
558       sofar += n;
559     else if(n == 0)
560       fatal(0, "unexpected EOF reading %s", path);
561     else if(errno != EINTR)
562       fatal(errno, "error reading %s", path);
563   }
564   xclose(fd);
565   m = mx_parse(path, 1, b, b + sb.st_size);
566   rc = mx_expand(m, output, u);
567   if(rc && rc != -1)
568     /* Mention inclusion in backtrace */
569     error(0, "  ...in inclusion of file '%s'", path);
570   return rc;
571 }
572
573 /* Macros ------------------------------------------------------------------- */
574
575 /** @brief Rewrite a parse tree substituting sub-expansions
576  * @param m Parse tree to rewrite (from macro definition)
577  * @param ... Name/value pairs to rewrite
578  * @return Rewritten parse tree
579  *
580  * The name/value pair list consists of pairs of strings and is terminated by
581  * (char *)0.  Names and values are both copied so need not survive the call.
582  */
583 const struct mx_node *mx_rewritel(const struct mx_node *m,
584                                   ...) {
585   va_list ap;
586   hash *h = hash_new(sizeof (struct mx_node *));
587   const char *n, *v;
588   struct mx_node *e;
589
590   va_start(ap, m);
591   while((n = va_arg(ap, const char *))) {
592     v = va_arg(ap, const char *);
593     e = xmalloc(sizeof *e);
594     e->next = 0;
595     e->filename = m->filename;
596     e->line = m->line;
597     e->type = MX_TEXT;
598     e->text = xstrdup(v);
599     hash_add(h, n, &e, HASH_INSERT);
600     /* hash_add() copies n */
601   }
602   return mx_rewrite(m, h);
603 }
604
605 /** @brief Rewrite a parse tree substituting in macro arguments
606  * @param definition Parse tree to rewrite (from macro definition)
607  * @param h Hash mapping argument names to argument values
608  * @return Rewritten parse tree
609  */
610 const struct mx_node *mx_rewrite(const struct mx_node *definition,
611                                  hash *h) {
612   const struct mx_node *head = 0, **tailp = &head, *argvalue, *m, *mm, **ap;
613   struct mx_node *nm;
614   int n;
615   
616   for(m = definition; m; m = m->next) {
617     switch(m->type) {
618     case MX_TEXT:
619       nm = xmalloc(sizeof *nm);
620       *nm = *m;                          /* Dumb copy of text node fields */
621       nm->next = 0;                      /* Maintain list structure */
622       *tailp = nm;
623       tailp = (const struct mx_node **)&nm->next;
624       break;
625     case MX_EXPANSION:
626       if(m->nargs == 0
627          && (ap = hash_find(h, m->name))) {
628         /* This expansion has no arguments and its name matches one of the
629          * macro arguments.  (Even if it's a valid expansion name we override
630          * it.)  We insert its value at this point.  We do NOT recursively
631          * rewrite the argument's value - it is outside the lexical scope of
632          * the argument name.
633          *
634          * We need to recreate the list structure but a shallow copy will
635          * suffice here.
636          */
637         argvalue = *ap;
638         for(mm = argvalue; mm; mm = mm->next) {
639           nm = xmalloc(sizeof *nm);
640           *nm = *mm;
641           nm->next = 0;
642           *tailp = nm;
643           tailp = (const struct mx_node **)&nm->next;
644         }
645       } else {
646         /* This is some other expansion.  We recursively rewrite its argument
647          * values according to h. */
648         nm = xmalloc(sizeof *nm);
649         *nm = *m;
650         nm->args = xcalloc(nm->nargs, sizeof (struct mx_node *));
651         for(n = 0; n < nm->nargs; ++n)
652           nm->args[n] = mx_rewrite(m->args[n], h);
653         nm->next = 0;
654         *tailp = nm;
655         tailp = (const struct mx_node **)&nm->next;
656       }
657       break;
658     default:
659       assert(!"invalid m->type");
660     }
661   }
662   *tailp = 0;                           /* Mark end of list */
663   return head;
664 }
665
666 /** @brief Expand a macro
667  * @param e Macro definition
668  * @param m Macro expansion
669  * @param output Where to send output
670  * @param u User data
671  * @return 0 on success, non-0 on error
672  */
673 static int mx__expand_macro(const struct expansion *e,
674                             const struct mx_node *m,
675                             struct sink *output,
676                             void *u) {
677   hash *h = hash_new(sizeof (struct mx_node *));
678   int n;
679
680   /* We store the macro arguments in a hash.  Currently there is no check for
681    * duplicate argument names (and this would be the wrong place for it
682    * anyway); if you do that you just lose in some undefined way. */
683   for(n = 0; n < m->nargs; ++n)
684     hash_add(h, e->args[n], &m->args[n], HASH_INSERT);
685   /* Generate a rewritten parse tree */
686   m = mx_rewrite(e->definition, h);
687   /* Expand the result */
688   return mx_expand(m, output, u);
689   /* mx_expand() will update the backtrace */
690 }
691
692 /*
693 Local Variables:
694 c-basic-offset:2
695 comment-column:40
696 fill-column:79
697 indent-tabs-mode:nil
698 End:
699 */