chiark / gitweb /
TABLE_FIND() now uses typeof. We're committed to GCC anyway so it
[disorder] / lib / macros-builtin.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 2 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, 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.
14  *
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
18  * USA
19  */
20
21 /** @file lib/macros-builtin.c
22  * @brief Built-in expansions
23  *
24  * This is a grab-bag of non-domain-specific expansions.  Documentation will be
25  * generated from the comments at the head of each function.
26  */
27
28 #include <config.h>
29 #include "types.h"
30
31 #include <stdio.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <assert.h>
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <sys/stat.h>
38 #include <sys/wait.h>
39
40 #include "hash.h"
41 #include "mem.h"
42 #include "macros.h"
43 #include "sink.h"
44 #include "syscalls.h"
45 #include "log.h"
46 #include "wstat.h"
47 #include "kvp.h"
48 #include "split.h"
49 #include "printf.h"
50 #include "vector.h"
51 #include "filepart.h"
52
53 static struct vector include_path;
54
55 /** @brief Return 1 if @p s is 'true' else 0 */
56 int mx_str2bool(const char *s) {
57   return !strcmp(s, "true");
58 }
59
60 /** @brief Return "true" if @p n is nonzero else "false" */
61 const char *mx_bool2str(int n) {
62   return n ? "true" : "false";
63 }
64
65 /** @brief Write a boolean result */
66 int mx_bool_result(struct sink *output, int result) {
67   if(sink_writes(output, mx_bool2str(result)) < 0)
68     return -1;
69   else
70     return 0;
71 }
72
73 /** @brief Search the include path */
74 char *mx_find(const char *name, int report) {
75   char *path;
76   int n;
77   
78   if(name[0] == '/') {
79     if(access(name, O_RDONLY) < 0) {
80       if(report)
81         error(errno, "cannot read %s", name);
82       return 0;
83     }
84     path = xstrdup(name);
85   } else {
86     /* Search the include path */
87     for(n = 0; n < include_path.nvec; ++n) {
88       byte_xasprintf(&path, "%s/%s", include_path.vec[n], name);
89       if(access(path, O_RDONLY) == 0)
90         break;
91     }
92     if(n >= include_path.nvec) {
93       if(report)
94         error(0, "cannot find '%s' in search path", name);
95       return 0;
96     }
97   }
98   return path;
99 }
100
101 /*! @include{TEMPLATE}@
102  *
103  * Includes TEMPLATE.
104  *
105  * TEMPLATE can be an absolute filename starting with a '/'; only the file with
106  * exactly this name will be included.
107  *
108  * Alternatively it can be a relative filename, not starting with a '/'.  In
109  * this case the file will be searched for in the include path.  When searching
110  * paths, unreadable files are treated as if they do not exist (rather than
111  * matching then producing an error).
112  *
113  * If the name chosen ends ".tmpl" then the file will be expanded as a
114  * template.  Anything else is included byte-for-byte without further
115  * modification.
116  *
117  * Only regular files are allowed (no devices, sockets or name pipes).
118  */
119 static int exp_include(int attribute((unused)) nargs,
120                        char **args,
121                        struct sink *output,
122                        void *u) {
123   const char *path;
124   int fd, n;
125   char buffer[4096];
126   struct stat sb;
127
128   if(!(path = mx_find(args[0], 1/*report*/))) {
129     if(sink_printf(output, "[[cannot find '%s']]", args[0]) < 0)
130       return 0;
131     return 0;
132   }
133   /* If it's a template expand it */
134   if(strlen(path) >= 5 && !strncmp(path + strlen(path) - 5, ".tmpl", 5))
135     return mx_expand_file(path, output, u);
136   /* Read the raw file.  As with mx_expand_file() we insist that the file is a
137    * regular file. */
138   if((fd = open(path, O_RDONLY)) < 0)
139     fatal(errno, "error opening %s", path);
140   if(fstat(fd, &sb) < 0)
141     fatal(errno, "error statting %s", path);
142   if(!S_ISREG(sb.st_mode))
143     fatal(0, "%s: not a regular file", path);
144   while((n = read(fd, buffer, sizeof buffer)) > 0) {
145     if(sink_write(output, buffer, n) < 0) {
146       xclose(fd);
147       return -1;
148     }
149   }
150   if(n < 0)
151     fatal(errno, "error reading %s", path);
152   xclose(fd);
153   return 0;
154 }
155
156 /*! @include{COMMAND}@
157  *
158  * Executes COMMAND via the shell (using "sh -c") and copies its
159  * standard output to the template output.  The shell command output
160  * is not expanded or modified in any other way.
161  *
162  * The shell command's standard error is copied to the error log.
163  *
164  * If the shell exits nonzero then this is reported to the error log
165  * but otherwise no special action is taken.
166  */
167 static int exp_shell(int attribute((unused)) nargs,
168                      char **args,
169                      struct sink *output,
170                      void attribute((unused)) *u) {
171   int w, p[2], n;
172   char buffer[4096];
173   pid_t pid;
174   
175   xpipe(p);
176   if(!(pid = xfork())) {
177     exitfn = _exit;
178     xclose(p[0]);
179     xdup2(p[1], 1);
180     xclose(p[1]);
181     execlp("sh", "sh", "-c", args[0], (char *)0);
182     fatal(errno, "error executing sh");
183   }
184   xclose(p[1]);
185   while((n = read(p[0], buffer, sizeof buffer))) {
186     if(n < 0) {
187       if(errno == EINTR)
188         continue;
189       else
190         fatal(errno, "error reading from pipe");
191     }
192     if(output->write(output, buffer, n) < 0)
193       return -1;
194   }
195   xclose(p[0]);
196   while((n = waitpid(pid, &w, 0)) < 0 && errno == EINTR)
197     ;
198   if(n < 0)
199     fatal(errno, "error calling waitpid");
200   if(w)
201     error(0, "shell command '%s' %s", args[0], wstat(w));
202   return 0;
203 }
204
205 /*! @if{CONDITION}{IF-TRUE}{IF-FALSE}@
206  *
207  * If CONDITION is "true" then evaluates to IF-TRUE.  Otherwise
208  * evaluates to IF-FALSE.  The IF-FALSE part is optional.
209  */
210 static int exp_if(int nargs,
211                   const struct mx_node **args,
212                   struct sink *output,
213                   void *u) {
214   char *s;
215   int rc;
216
217   if((rc = mx_expandstr(args[0], &s, u, "argument #0 (CONDITION)")))
218     return rc;
219   if(mx_str2bool(s))
220     return mx_expand(args[1], output, u);
221   else if(nargs > 2)
222     return mx_expand(args[2], output, u);
223   else
224     return 0;
225 }
226
227 /*! @and{BRANCH}{BRANCH}...@
228  *
229  * Expands to "true" if all the branches are "true" otherwise to "false".  If
230  * there are no brances then the result is "true".  Only as many branches as
231  * necessary to compute the answer are evaluated (starting from the first one),
232  * so if later branches have side effects they may not take place.
233  */
234 static int exp_and(int nargs,
235                    const struct mx_node **args,
236                    struct sink *output,
237                    void *u) {
238   int n, result = 1, rc;
239   char *s, *argname;
240
241   for(n = 0; n < nargs; ++n) {
242     byte_xasprintf(&argname, "argument #%d", n);
243     if((rc = mx_expandstr(args[n], &s, u, argname)))
244       return rc;
245     if(!mx_str2bool(s)) {
246       result = 0;
247       break;
248     }
249   }
250   return mx_bool_result(output, result);
251 }
252
253 /*! @or{BRANCH}{BRANCH}...@
254  *
255  * Expands to "true" if any of the branches are "true" otherwise to "false".
256  * If there are no brances then the result is "false".  Only as many branches
257  * as necessary to compute the answer are evaluated (starting from the first
258  * one), so if later branches have side effects they may not take place.
259  */
260 static int exp_or(int nargs,
261                   const struct mx_node **args,
262                   struct sink *output,
263                   void *u) {
264   int n, result = 0, rc;
265   char *s, *argname;
266
267   for(n = 0; n < nargs; ++n) {
268     byte_xasprintf(&argname, "argument #%d", n);
269     if((rc = mx_expandstr(args[n], &s, u, argname)))
270       return rc;
271     if(mx_str2bool(s)) {
272       result = 1;
273       break;
274     }
275   }
276   return mx_bool_result(output, result);
277 }
278
279 /*! @not{CONDITION}@
280  *
281  * Expands to "true" unless CONDITION is "true" in which case "false".
282  */
283 static int exp_not(int attribute((unused)) nargs,
284                    char **args,
285                    struct sink *output,
286                    void attribute((unused)) *u) {
287   return mx_bool_result(output, !mx_str2bool(args[0]));
288 }
289
290 /*! @#{...}@
291  *
292  * Expands to nothing.  The argument(s) are not fully evaluated, and no side
293  * effects occur.
294  */
295 static int exp_comment(int attribute((unused)) nargs,
296                        const struct mx_node attribute((unused)) **args,
297                        struct sink attribute((unused)) *output,
298                        void attribute((unused)) *u) {
299   return 0;
300 }
301
302 /*! @urlquote{STRING}@
303  *
304  * URL-quotes a string, i.e. replaces any characters not safe to use unquoted
305  * in a URL with %-encoded form.
306  */
307 static int exp_urlquote(int attribute((unused)) nargs,
308                         char **args,
309                         struct sink *output,
310                         void attribute((unused)) *u) {
311   if(sink_writes(output, urlencodestring(args[0])) < 0)
312     return -1;
313   else
314     return 0;
315 }
316
317 /*! @eq{S1}{S2}...@
318  *
319  * Expands to "true" if all the arguments are identical, otherwise to "false"
320  * (i.e. if any pair of arguments differs).
321  *
322  * If there are no arguments then expands to "true".  Evaluates all arguments
323  * (with their side effects) even if that's not strictly necessary to discover
324  * the result.
325  */
326 static int exp_eq(int nargs,
327                   char **args,
328                   struct sink *output,
329                   void attribute((unused)) *u) {
330   int n, result = 1;
331   
332   for(n = 1; n < nargs; ++n) {
333     if(strcmp(args[n], args[0])) {
334       result = 0;
335       break;
336     }
337   }
338   return mx_bool_result(output, result);
339 }
340
341 /*! @ne{S1}{S2}...@
342  *
343  * Expands to "true" if all of the arguments differ from one another, otherwise
344  * to "false" (i.e. if any value appears more than once).
345  *
346  * If there are no arguments then expands to "true".  Evaluates all arguments
347  * (with their side effects) even if that's not strictly necessary to discover
348  * the result.
349  */
350 static int exp_ne(int nargs,
351                   char **args,
352                   struct sink *output,
353                   void  attribute((unused))*u) {
354   hash *h = hash_new(sizeof (char *));
355   int n, result = 1;
356
357   for(n = 0; n < nargs; ++n)
358     if(hash_add(h, args[n], "", HASH_INSERT)) {
359       result = 0;
360       break;
361     }
362   return mx_bool_result(output, result);
363 }
364
365 /*! @discard{...}@
366  *
367  * Expands to nothing.  Unlike the comment expansion @#{...}, side effects of
368  * arguments are not suppressed.  So this can be used to surround a collection
369  * of macro definitions with whitespace, free text commentary, etc.
370  */
371 static int exp_discard(int attribute((unused)) nargs,
372                        char attribute((unused)) **args,
373                        struct sink attribute((unused)) *output,
374                        void attribute((unused)) *u) {
375   return 0;
376 }
377
378 /*! @define{NAME}{ARG1 ARG2...}{DEFINITION}@
379  *
380  * Define a macro.  The macro will be called NAME and will act like an
381  * expansion.  When it is expanded, the expansion is replaced by DEFINITION,
382  * with each occurence of @ARG1@ etc replaced by the parameters to the
383  * expansion.
384  */
385 static int exp_define(int attribute((unused)) nargs,
386                       const struct mx_node **args,
387                       struct sink attribute((unused)) *output,
388                       void attribute((unused)) *u) {
389   char **as, *name, *argnames;
390   int rc, nas;
391   
392   if((rc = mx_expandstr(args[0], &name, u, "argument #0 (NAME)")))
393     return rc;
394   if((rc = mx_expandstr(args[1], &argnames, u, "argument #1 (ARGS)")))
395     return rc;
396   as = split(argnames, &nas, 0, 0, 0);
397   mx_register_macro(name, nas, as, args[2]);
398   return 0;
399 }
400
401 /*! @basename{PATH}
402  *
403  * Expands to the UNQUOTED basename of PATH.
404  */
405 static int exp_basename(int attribute((unused)) nargs,
406                         char **args,
407                         struct sink attribute((unused)) *output,
408                         void attribute((unused)) *u) {
409   return sink_writes(output, d_basename(args[0])) < 0 ? -1 : 0;
410 }
411
412 /*! @dirname{PATH}
413  *
414  * Expands to the UNQUOTED directory name of PATH.
415  */
416 static int exp_dirname(int attribute((unused)) nargs,
417                        char **args,
418                        struct sink attribute((unused)) *output,
419                        void attribute((unused)) *u) {
420   return sink_writes(output, d_dirname(args[0])) < 0 ? -1 : 0;
421 }
422
423 /*! @q{STRING}
424  *
425  * Expands to STRING.
426  */
427 static int exp_q(int attribute((unused)) nargs,
428                  char **args,
429                  struct sink attribute((unused)) *output,
430                  void attribute((unused)) *u) {
431   return sink_writes(output, args[0]) < 0 ? -1 : 0;
432 }
433
434 /** @brief Register built-in expansions */
435 void mx_register_builtin(void) {
436   mx_register("basename", 1, 1, exp_basename);
437   mx_register("dirname", 1, 1, exp_dirname);
438   mx_register("discard", 0, INT_MAX, exp_discard);
439   mx_register("eq", 0, INT_MAX, exp_eq);
440   mx_register("include", 1, 1, exp_include);
441   mx_register("ne", 0, INT_MAX, exp_ne);
442   mx_register("not", 1, 1, exp_not);
443   mx_register("shell", 1, 1, exp_shell);
444   mx_register("urlquote", 1, 1, exp_urlquote);
445   mx_register("q", 1, 1, exp_q);
446   mx_register_magic("#", 0, INT_MAX, exp_comment);
447   mx_register_magic("and", 0, INT_MAX, exp_and);
448   mx_register_magic("define", 3, 3, exp_define);
449   mx_register_magic("if", 2, 3, exp_if);
450   mx_register_magic("or", 0, INT_MAX, exp_or);
451 }
452
453 /** @brief Add a directory to the search path
454  * @param s Directory to add
455  */
456 void mx_search_path(const char *s) {
457   vector_append(&include_path, xstrdup(s));
458 }
459
460 /*
461 Local Variables:
462 c-basic-offset:2
463 comment-column:40
464 fill-column:79
465 indent-tabs-mode:nil
466 End:
467 */