maint: fix a type coercion flagged by -Wformat.
[m4/ericb.git] / modules / m4.c
blob1d2f7f53e7be55a8b96877f8491ab4a03dc54921
1 /* GNU m4 -- A simple macro processor
2 Copyright (C) 2000, 2002-2004, 2006-2010, 2013 Free Software
3 Foundation, Inc.
5 This file is part of GNU M4.
7 GNU M4 is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
12 GNU M4 is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>.
21 #include <config.h>
23 /* Build using only the exported interfaces, unless NDEBUG is set, in
24 which case use private symbols to speed things up as much as possible. */
25 #ifndef NDEBUG
26 # include <m4/m4module.h>
27 #else
28 # include "m4private.h"
29 #endif
31 #include "execute.h"
32 #include "memchr2.h"
33 #include "memcmp2.h"
34 #include "quotearg.h"
35 #include "stdlib--.h"
36 #include "tempname.h"
37 #include "unistd--.h"
39 #include <modules/m4.h>
41 extern void m4_set_sysval (int);
42 extern void m4_sysval_flush (m4 *, bool);
43 extern void m4_dump_symbols (m4 *, m4_dump_symbol_data *, size_t,
44 m4_macro_args *, bool);
45 extern const char *m4_expand_ranges (const char *, size_t *, m4_obstack *);
46 extern void m4_make_temp (m4 *, m4_obstack *, const m4_call_info *,
47 const char *, size_t, bool);
49 /* Maintain each of the builtins implemented in this modules along
50 with their details in a single table for easy maintenance.
52 function macros blind side minargs maxargs */
53 #define builtin_functions \
54 BUILTIN (changecom, false, false, false, 0, 2 ) \
55 BUILTIN (changequote, false, false, false, 0, 2 ) \
56 BUILTIN (decr, false, true, true, 1, 1 ) \
57 BUILTIN (define, true, true, false, 1, 2 ) \
58 BUILTIN (defn, true, true, false, 1, -1 ) \
59 BUILTIN (divert, false, false, false, 0, 2 ) \
60 BUILTIN (divnum, false, false, false, 0, 0 ) \
61 BUILTIN (dnl, false, false, false, 0, 0 ) \
62 BUILTIN (dumpdef, true, false, false, 0, -1 ) \
63 BUILTIN (errprint, false, true, false, 1, -1 ) \
64 BUILTIN (eval, false, true, true, 1, 3 ) \
65 BUILTIN (ifdef, true, true, false, 2, 3 ) \
66 BUILTIN (ifelse, true, true, false, 1, -1 ) \
67 BUILTIN (include, false, true, false, 1, 1 ) \
68 BUILTIN (incr, false, true, true, 1, 1 ) \
69 BUILTIN (index, false, true, true, 2, 3 ) \
70 BUILTIN (len, false, true, true, 1, 1 ) \
71 BUILTIN (m4exit, false, false, false, 0, 1 ) \
72 BUILTIN (m4wrap, true, true, false, 1, -1 ) \
73 BUILTIN (maketemp, false, true, false, 1, 1 ) \
74 BUILTIN (mkstemp, false, true, false, 1, 1 ) \
75 BUILTIN (popdef, true, true, false, 1, -1 ) \
76 BUILTIN (pushdef, true, true, false, 1, 2 ) \
77 BUILTIN (shift, true, true, false, 1, -1 ) \
78 BUILTIN (sinclude, false, true, false, 1, 1 ) \
79 BUILTIN (substr, false, true, true, 2, 4 ) \
80 BUILTIN (syscmd, false, true, true, 1, 1 ) \
81 BUILTIN (sysval, false, false, false, 0, 0 ) \
82 BUILTIN (traceoff, true, false, false, 0, -1 ) \
83 BUILTIN (traceon, true, false, false, 0, -1 ) \
84 BUILTIN (translit, false, true, true, 2, 3 ) \
85 BUILTIN (undefine, true, true, false, 1, -1 ) \
86 BUILTIN (undivert, false, false, false, 0, -1 ) \
89 typedef intmax_t number;
90 typedef uintmax_t unumber;
92 static void include (m4 *context, m4_obstack *obs, size_t argc,
93 m4_macro_args *argv, bool silent);
94 static int dumpdef_cmp_CB (const void *s1, const void *s2);
95 static void * dump_symbol_CB (m4_symbol_table *, const char *, size_t,
96 m4_symbol *symbol, void *userdata);
97 static const char *ntoa (number value, int radix);
98 static void numb_obstack (m4_obstack *obs, number value,
99 int radix, int min);
102 /* Generate prototypes for each builtin handler function. */
103 #define BUILTIN(handler, macros, blind, side, min, max) M4BUILTIN (handler)
104 builtin_functions
105 #undef BUILTIN
108 /* Generate a table for mapping m4 symbol names to handler functions. */
109 static const m4_builtin m4_builtin_table[] =
111 #define BUILTIN(handler, macros, blind, side, min, max) \
112 M4BUILTIN_ENTRY (handler, #handler, macros, blind, side, min, max)
114 builtin_functions
115 #undef BUILTIN
117 { NULL, NULL, 0, 0, 0 },
121 void
122 include_m4 (m4 *context, m4_module *module, m4_obstack *obs)
124 m4_install_builtins (context, module, m4_builtin_table);
129 /* The rest of this file is code for builtins and expansion of user
130 defined macros. All the functions for builtins have a prototype as:
132 void builtin_MACRONAME (m4_obstack *obs, int argc, char *argv[]);
134 The function are expected to leave their expansion on the obstack OBS,
135 as an unfinished object. ARGV is a table of ARGC pointers to the
136 individual arguments to the macro. Please note that in general
137 argv[argc] != NULL. */
139 M4BUILTIN_HANDLER (define)
141 const m4_call_info *me = m4_arg_info (argv);
143 if (m4_is_arg_text (argv, 1))
145 m4_symbol_value *value = m4_symbol_value_create ();
147 if (m4_symbol_value_copy (context, value, m4_arg_symbol (argv, 2)))
148 m4_warn (context, 0, me, _("cannot concatenate builtins"));
149 m4_symbol_define (M4SYMTAB, M4ARG (1), M4ARGLEN (1), value);
151 else
152 m4_warn (context, 0, me, _("invalid macro name ignored"));
155 M4BUILTIN_HANDLER (undefine)
157 size_t i;
158 for (i = 1; i < argc; i++)
159 if (m4_symbol_value_lookup (context, argv, i, true))
160 m4_symbol_delete (M4SYMTAB, M4ARG (i), M4ARGLEN (i));
163 M4BUILTIN_HANDLER (pushdef)
165 const m4_call_info *me = m4_arg_info (argv);
167 if (m4_is_arg_text (argv, 1))
169 m4_symbol_value *value = m4_symbol_value_create ();
171 if (m4_symbol_value_copy (context, value, m4_arg_symbol (argv, 2)))
172 m4_warn (context, 0, me, _("cannot concatenate builtins"));
173 m4_symbol_pushdef (M4SYMTAB, M4ARG (1), M4ARGLEN (1), value);
175 else
176 m4_warn (context, 0, me, _("invalid macro name ignored"));
179 M4BUILTIN_HANDLER (popdef)
181 size_t i;
182 for (i = 1; i < argc; i++)
183 if (m4_symbol_value_lookup (context, argv, i, true))
184 m4_symbol_popdef (M4SYMTAB, M4ARG (i), M4ARGLEN (i));
189 /* --- CONDITIONALS OF M4 --- */
192 M4BUILTIN_HANDLER (ifdef)
194 m4_push_arg (context, obs, argv,
195 m4_symbol_value_lookup (context, argv, 1, false) ? 2 : 3);
198 M4BUILTIN_HANDLER (ifelse)
200 const m4_call_info *me = m4_arg_info (argv);
201 size_t i;
203 /* The valid ranges of argc for ifelse is discontinuous, we cannot
204 rely on the regular mechanisms. */
205 if (argc == 2 || m4_bad_argc (context, argc, me, 3, -1, false))
206 return;
207 else if (argc % 3 == 0)
208 /* Diagnose excess arguments if 5, 8, 11, etc., actual arguments. */
209 m4_bad_argc (context, argc, me, 0, argc - 2, false);
211 i = 1;
212 argc--;
214 while (true)
216 if (m4_arg_equal (context, argv, i, i + 1))
218 m4_push_arg (context, obs, argv, i + 2);
219 return;
221 switch (argc)
223 case 3:
224 return;
226 case 4:
227 case 5:
228 m4_push_arg (context, obs, argv, i + 3);
229 return;
231 default:
232 argc -= 3;
233 i += 3;
239 /* qsort comparison routine, for sorting the table made in m4_dumpdef (). */
240 static int
241 dumpdef_cmp_CB (const void *s1, const void *s2)
243 const m4_string *a = (const m4_string *) s1;
244 const m4_string *b = (const m4_string *) s2;
245 return memcmp2 (a->str, a->len, b->str, b->len);
248 /* The function m4_dump_symbols () is for use by "dumpdef". It builds up a
249 table of all defined symbol names. */
250 static void *
251 dump_symbol_CB (m4_symbol_table *ignored M4_GNUC_UNUSED, const char *name,
252 size_t len, m4_symbol *symbol, void *userdata)
254 m4_dump_symbol_data *symbol_data = (m4_dump_symbol_data *) userdata;
255 m4_string *key;
257 assert (name);
258 assert (symbol);
259 assert (!m4_is_symbol_value_void (m4_get_symbol_value (symbol)));
261 if (symbol_data->size == 0)
263 char *base;
264 size_t offset = obstack_object_size (symbol_data->obs);
265 obstack_blank (symbol_data->obs, sizeof *symbol_data->base);
266 symbol_data->size = (obstack_room (symbol_data->obs)
267 / sizeof *symbol_data->base);
268 base = (char *) obstack_base (symbol_data->obs) + offset;
269 symbol_data->base = (m4_string *) base;
271 else
273 obstack_blank_fast (symbol_data->obs, sizeof *symbol_data->base);
274 symbol_data->size--;
277 /* Safe to cast away const, since m4_dump_symbols adds it back. */
278 key = (m4_string *) symbol_data->base++;
279 key->str = (char *) name;
280 key->len = len;
281 return NULL;
284 /* If there are no arguments, build a sorted list of all defined
285 symbols, otherwise, only the specified symbols. */
286 void
287 m4_dump_symbols (m4 *context, m4_dump_symbol_data *data, size_t argc,
288 m4_macro_args *argv, bool complain)
290 assert (obstack_object_size (data->obs) == 0);
291 data->size = obstack_room (data->obs) / sizeof *data->base;
292 data->base = (m4_string *) obstack_base (data->obs);
294 if (argc == 1)
295 m4_symtab_apply (M4SYMTAB, false, dump_symbol_CB, data);
296 else
298 size_t i;
299 m4_symbol *symbol;
301 for (i = 1; i < argc; i++)
303 symbol = m4_symbol_value_lookup (context, argv, i, complain);
304 if (symbol)
305 dump_symbol_CB (NULL, M4ARG (i), M4ARGLEN (i), symbol, data);
309 data->size = obstack_object_size (data->obs) / sizeof *data->base;
310 data->base = (m4_string *) obstack_finish (data->obs);
311 /* Safe to cast away const, since we don't modify entries. */
312 qsort ((m4_string *) data->base, data->size, sizeof *data->base,
313 dumpdef_cmp_CB);
317 /* Implementation of "dumpdef" itself. It builds up a table of pointers to
318 symbols, sorts it and prints the sorted table. */
319 M4BUILTIN_HANDLER (dumpdef)
321 m4_dump_symbol_data data;
322 const m4_string_pair *quotes = NULL;
323 bool stack = m4_is_debug_bit (context, M4_DEBUG_TRACE_STACK);
324 size_t arg_length = m4_get_max_debug_arg_length_opt (context);
325 bool module = m4_is_debug_bit (context, M4_DEBUG_TRACE_MODULE);
326 FILE *output = (m4_is_debug_bit (context, M4_DEBUG_TRACE_OUTPUT_DUMPDEF)
327 ? stderr : m4_get_debug_file (context));
329 if (!output)
330 return;
331 if (m4_is_debug_bit (context, M4_DEBUG_TRACE_QUOTE))
332 quotes = m4_get_syntax_quotes (M4SYNTAX);
333 data.obs = m4_arg_scratch (context);
334 m4_dump_symbols (context, &data, argc, argv, true);
335 m4_sysval_flush (context, false);
337 for (; data.size > 0; --data.size, data.base++)
339 m4_symbol *symbol = m4_symbol_lookup (M4SYMTAB, data.base->str,
340 data.base->len);
341 char *value;
342 size_t len;
343 assert (symbol);
345 /* TODO - add debugmode(b) option to control quoting style. */
346 obstack_grow (obs, data.base->str, data.base->len);
347 obstack_1grow (obs, ':');
348 obstack_1grow (obs, '\t');
349 m4_symbol_print (context, symbol, obs, quotes, stack, arg_length,
350 module);
351 obstack_1grow (obs, '\n');
352 len = obstack_object_size (obs);
353 value = (char *) obstack_finish (obs);
354 fwrite (value, 1, len, output);
355 obstack_free (obs, value);
359 /* The macro "defn" returns the quoted definition of the macro named by
360 the first argument. If the macro is builtin, it will push a special
361 macro-definition token on the input stack. */
362 M4BUILTIN_HANDLER (defn)
364 const m4_call_info *me = m4_arg_info (argv);
365 size_t i;
367 for (i = 1; i < argc; i++)
369 m4_symbol *symbol = m4_symbol_value_lookup (context, argv, i, true);
371 if (!symbol)
373 else if (m4_is_symbol_text (symbol))
374 m4_shipout_string (context, obs, m4_get_symbol_text (symbol),
375 m4_get_symbol_len (symbol), true);
376 else if (m4_is_symbol_func (symbol))
377 m4_push_builtin (context, obs, m4_get_symbol_value (symbol));
378 else if (m4_is_symbol_placeholder (symbol))
379 m4_warn (context, 0, me,
380 _("%s: builtin %s requested by frozen file not found"),
381 quotearg_n_mem (2, M4ARG (i), M4ARGLEN (i)),
382 quotearg_style (locale_quoting_style,
383 m4_get_symbol_placeholder (symbol)));
384 else
386 assert (!"Bad token data type in m4_defn");
387 abort ();
393 /* This section contains macros to handle the builtins "syscmd"
394 and "sysval". */
396 /* Exit code from last "syscmd" command. */
397 /* FIXME - we should preserve this value across freezing. See
398 http://lists.gnu.org/archive/html/bug-m4/2006-06/msg00059.html
399 for ideas on how do to that. */
400 static int m4_sysval = 0;
402 void
403 m4_set_sysval (int value)
405 m4_sysval = value;
408 /* Flush a given output STREAM. If REPORT, also print an error
409 message and clear the stream error bit. */
410 static void
411 sysval_flush_helper (m4 *context, FILE *stream, bool report)
413 if (fflush (stream) == EOF && report)
415 m4_error (context, 0, errno, NULL, _("write error"));
416 clearerr (stream);
420 /* Flush all user output streams, prior to doing something that can
421 could lose unflushed data or interleave debug and normal output
422 incorrectly. If REPORT, then print an error message on failure and
423 clear the stream error bit; otherwise a subsequent ferror can track
424 that an error occurred. */
425 void
426 m4_sysval_flush (m4 *context, bool report)
428 FILE *debug_file = m4_get_debug_file (context);
430 if (debug_file != stdout)
431 sysval_flush_helper (context, stdout, report);
432 if (debug_file != stderr)
433 /* If we have problems with stderr, we can't really report that
434 problem to stderr. The closeout module will ensure the exit
435 status reflects the problem, though. */
436 fflush (stderr);
437 if (debug_file != NULL)
438 sysval_flush_helper (context, debug_file, report);
439 /* POSIX requires that if m4 doesn't consume all input, but stdin is
440 opened on a seekable file, that the file pointer be left at the
441 next character on exit (but places no restrictions on the file
442 pointer location on a non-seekable file). It also requires that
443 fflush() followed by fseeko() on an input file set the underlying
444 file pointer, and gnulib guarantees these semantics. However,
445 fflush() on a non-seekable file can lose buffered data, which we
446 might otherwise want to process after syscmd. Hence, we must
447 check whether stdin is seekable. We must also be tolerant of
448 operating with stdin closed, so we don't report any failures in
449 this attempt. The stdio-safer module and friends are essential,
450 so that if stdin was closed, this lseek is not on some other file
451 that we have since opened. */
452 if (lseek (STDIN_FILENO, 0, SEEK_CUR) >= 0
453 && fflush (stdin) == 0)
455 fseeko (stdin, 0, SEEK_CUR);
459 M4BUILTIN_HANDLER (syscmd)
461 const m4_call_info *me = m4_arg_info (argv);
462 const char *cmd = M4ARG (1);
463 size_t len = M4ARGLEN (1);
464 int status;
465 int sig_status;
466 const char *prog_args[4] = { "sh", "-c" };
468 if (m4_get_safer_opt (context))
470 m4_error (context, 0, 0, m4_arg_info (argv), _("disabled by --safer"));
471 return;
473 if (strlen (cmd) != len)
474 m4_warn (context, 0, me, _("argument %s truncated"),
475 quotearg_style_mem (locale_quoting_style, cmd, len));
477 /* Optimize the empty command. */
478 if (!*cmd)
480 m4_set_sysval (0);
481 return;
483 m4_sysval_flush (context, false);
484 #if W32_NATIVE
485 if (strstr (M4_SYSCMD_SHELL, "cmd"))
487 prog_args[0] = "cmd";
488 prog_args[1] = "/c";
490 #endif
491 prog_args[2] = cmd;
492 errno = 0;
493 status = execute (m4_info_name (me), M4_SYSCMD_SHELL, (char **) prog_args,
494 false, false, false, false, true, false, &sig_status);
495 if (sig_status)
497 assert (status == 127);
498 m4_sysval = sig_status << 8;
500 else
502 if (status == 127 && errno)
503 m4_warn (context, errno, me, _("cannot run command %s"),
504 quotearg_style (locale_quoting_style, cmd));
505 m4_sysval = status;
510 M4BUILTIN_HANDLER (sysval)
512 m4_shipout_int (obs, m4_sysval);
516 M4BUILTIN_HANDLER (incr)
518 int value;
520 if (!m4_numeric_arg (context, m4_arg_info (argv), M4ARG (1), M4ARGLEN (1),
521 &value))
522 return;
524 m4_shipout_int (obs, value + 1);
527 M4BUILTIN_HANDLER (decr)
529 int value;
531 if (!m4_numeric_arg (context, m4_arg_info (argv), M4ARG (1), M4ARGLEN (1),
532 &value))
533 return;
535 m4_shipout_int (obs, value - 1);
539 /* This section contains the macros "divert", "undivert" and "divnum" for
540 handling diversion. The utility functions used lives in output.c. */
542 /* Divert further output to the diversion given by ARGV[1]. Out of range
543 means discard further output. */
544 M4BUILTIN_HANDLER (divert)
546 int i = 0;
548 if (argc >= 2 && !m4_numeric_arg (context, m4_arg_info (argv), M4ARG (1),
549 M4ARGLEN (1), &i))
550 return;
551 m4_make_diversion (context, i);
552 m4_divert_text (context, NULL, M4ARG (2), M4ARGLEN (2),
553 m4_get_current_line (context));
556 /* Expand to the current diversion number. */
557 M4BUILTIN_HANDLER (divnum)
559 m4_shipout_int (obs, m4_get_current_diversion (context));
562 /* Bring back the diversion given by the argument list. If none is
563 specified, bring back all diversions. GNU specific is the option
564 of undiverting the named file, by passing a non-numeric argument to
565 undivert (). */
567 M4BUILTIN_HANDLER (undivert)
569 size_t i = 0;
570 const m4_call_info *me = m4_arg_info (argv);
572 if (argc == 1)
573 m4_undivert_all (context);
574 else
575 for (i = 1; i < argc; i++)
577 const char *str = M4ARG (i);
578 size_t len = M4ARGLEN (i);
579 char *endp;
580 int diversion = strtol (str, &endp, 10);
581 if (endp - str == len && !isspace ((unsigned char) *str))
582 m4_insert_diversion (context, diversion);
583 else if (m4_get_posixly_correct_opt (context))
584 m4_warn (context, 0, me, _("non-numeric argument %s"),
585 quotearg_style_mem (locale_quoting_style, str, len));
586 else if (strlen (str) != len)
587 m4_warn (context, 0, me, _("invalid file name %s"),
588 quotearg_style_mem (locale_quoting_style, str, len));
589 else
591 char *filepath = m4_path_search (context, str, NULL);
592 FILE *fp = m4_fopen (context, filepath, "r");
594 free (filepath);
595 if (fp != NULL)
597 m4_insert_file (context, fp);
598 if (fclose (fp) == EOF)
599 m4_error (context, 0, errno, me, _("error undiverting %s"),
600 quotearg_style (locale_quoting_style, str));
602 else
603 m4_error (context, 0, errno, me, _("cannot undivert %s"),
604 quotearg_style (locale_quoting_style, str));
610 /* This section contains various macros, which does not fall into
611 any specific group. These are "dnl", "shift", "changequote",
612 "changecom" and "changesyntax" */
614 /* Delete all subsequent whitespace from input. The function skip_line ()
615 lives in input.c. */
616 M4BUILTIN_HANDLER (dnl)
618 m4_skip_line (context, m4_arg_info (argv));
621 /* Shift all arguments one to the left, discarding the first argument.
622 Each output argument is quoted with the current quotes. */
623 M4BUILTIN_HANDLER (shift)
625 m4_push_args (context, obs, argv, true, true);
628 /* Change the current quotes. The function set_quotes () lives in
629 syntax.c. */
630 M4BUILTIN_HANDLER (changequote)
632 m4_set_quotes (M4SYNTAX,
633 (argc >= 2) ? M4ARG (1) : NULL, M4ARGLEN (1),
634 (argc >= 3) ? M4ARG (2) : NULL, M4ARGLEN (2));
637 /* Change the current comment delimiters. The function set_comment ()
638 lives in syntax.c. */
639 M4BUILTIN_HANDLER (changecom)
641 m4_set_comment (M4SYNTAX,
642 (argc >= 2) ? M4ARG (1) : NULL, M4ARGLEN (1),
643 (argc >= 3) ? M4ARG (2) : NULL, M4ARGLEN (2));
647 /* This section contains macros for inclusion of other files -- "include"
648 and "sinclude". This differs from bringing back diversions, in that
649 the input is scanned before being copied to the output. */
651 static void
652 include (m4 *context, m4_obstack *obs, size_t argc, m4_macro_args *argv, bool silent)
654 const m4_call_info *me = m4_arg_info (argv);
655 const char *arg = M4ARG (1);
656 size_t len = M4ARGLEN (1);
658 if (strlen (arg) != len)
659 m4_warn (context, 0, me, _("argument %s truncated"),
660 quotearg_style_mem (locale_quoting_style, arg, len));
661 m4_load_filename (context, me, arg, obs, silent);
664 /* Include a file, complaining in case of errors. */
665 M4BUILTIN_HANDLER (include)
667 include (context, obs, argc, argv, false);
670 /* Include a file, ignoring errors. */
671 M4BUILTIN_HANDLER (sinclude)
673 include (context, obs, argc, argv, true);
677 /* More miscellaneous builtins -- "maketemp", "errprint". */
679 /* Add trailing `X' to PATTERN of length LEN as necessary, then
680 securely create the temporary file system object. If DIR, create a
681 directory instead of a file. Report errors on behalf of CALLER. If
682 successful, output the quoted resulting name on OBS. */
683 void
684 m4_make_temp (m4 *context, m4_obstack *obs, const m4_call_info *caller,
685 const char *pattern, size_t len, bool dir)
687 int fd;
688 int i;
689 char *name;
690 const m4_string_pair *quotes = m4_get_syntax_quotes (M4SYNTAX);
692 if (m4_get_safer_opt (context))
694 m4_error (context, 0, 0, caller, _("disabled by --safer"));
695 return;
698 /* Guarantee that there are six trailing 'X' characters, even if the
699 user forgot to supply them. Output must be quoted if
700 successful. */
701 assert (obstack_object_size (obs) == 0);
702 obstack_grow (obs, quotes->str1, quotes->len1);
703 if (strlen (pattern) < len)
705 m4_warn (context, 0, caller, _("argument %s truncated"),
706 quotearg_style_mem (locale_quoting_style, pattern, len));
707 len = strlen (pattern);
709 obstack_grow (obs, pattern, len);
710 for (i = 0; len > 0 && i < 6; i++)
711 if (pattern[--len] != 'X')
712 break;
713 obstack_grow0 (obs, "XXXXXX", 6 - i);
714 name = (char *) obstack_base (obs) + quotes->len1;
716 /* Make the temporary object. */
717 errno = 0;
718 fd = gen_tempname (name, 0, 0, dir ? GT_DIR : GT_FILE);
719 if (fd < 0)
721 /* This use of _() will need to change if xgettext ever changes
722 its undocumented behavior of parsing both string options. */
724 m4_warn (context, errno, caller,
725 _(dir ? "cannot create directory from template %s"
726 : "cannot create file from template %s"),
727 quotearg_style (locale_quoting_style, pattern));
728 obstack_free (obs, obstack_finish (obs));
730 else
732 if (!dir)
733 close (fd);
734 /* Remove NUL, then finish quote. */
735 obstack_blank (obs, -1);
736 obstack_grow (obs, quotes->str2, quotes->len2);
740 /* Use the first argument as at template for a temporary file name. */
741 M4BUILTIN_HANDLER (maketemp)
743 const m4_call_info *me = m4_arg_info (argv);
744 m4_warn (context, 0, me, _("recommend using mkstemp instead"));
745 if (m4_get_posixly_correct_opt (context))
747 /* POSIX states "any trailing 'X' characters [are] replaced with
748 the current process ID as a string", without referencing the
749 file system. Horribly insecure, but we have to do it.
751 For reference, Solaris m4 does:
752 maketemp() -> `'
753 maketemp(X) -> `X'
754 maketemp(XX) -> `Xn', where n is last digit of pid
755 maketemp(XXXXXXXX) -> `X00nnnnn', where nnnnn is 16-bit pid
757 const char *str = M4ARG (1);
758 size_t len = M4ARGLEN (1);
759 size_t i;
760 m4_obstack *scratch = m4_arg_scratch (context);
761 size_t pid_len = obstack_printf (scratch, "%lu",
762 (unsigned long) getpid ());
763 char *pid = (char *) obstack_copy0 (scratch, "", 0);
765 for (i = len; i > 1; i--)
766 if (str[i - 1] != 'X')
767 break;
768 obstack_grow (obs, str, i);
769 if (len - i < pid_len)
770 obstack_grow (obs, pid + pid_len - (len - i), len - i);
771 else
772 obstack_printf (obs, "%.*d%s", (int) (len - i - pid_len), 0, pid);
774 else
775 m4_make_temp (context, obs, me, M4ARG (1), M4ARGLEN (1), false);
778 /* Use the first argument as a template for a temporary file name. */
779 M4BUILTIN_HANDLER (mkstemp)
781 m4_make_temp (context, obs, m4_arg_info (argv), M4ARG (1), M4ARGLEN (1),
782 false);
785 /* Print all arguments on standard error. */
786 M4BUILTIN_HANDLER (errprint)
788 size_t i;
790 m4_sysval_flush (context, false);
791 /* The close_stdin module makes it safe to skip checking the return
792 values here. */
793 fwrite (M4ARG (1), 1, M4ARGLEN (1), stderr);
794 for (i = 2; i < m4_arg_argc (argv); i++)
796 fputc (' ', stderr);
797 fwrite (M4ARG (i), 1, M4ARGLEN (i), stderr);
799 fflush (stderr);
803 /* This section contains various macros for exiting, saving input until
804 EOF is seen, and tracing macro calls. That is: "m4exit", "m4wrap",
805 "traceon" and "traceoff". */
807 /* Exit immediately, with exitcode specified by the first argument, 0 if no
808 arguments are present. */
809 M4BUILTIN_HANDLER (m4exit)
811 const m4_call_info *me = m4_arg_info (argv);
812 int exit_code = EXIT_SUCCESS;
814 /* Warn on bad arguments, but still exit. */
815 if (argc >= 2 && !m4_numeric_arg (context, me, M4ARG (1), M4ARGLEN (1),
816 &exit_code))
817 exit_code = EXIT_FAILURE;
818 if (exit_code < 0 || exit_code > 255)
820 m4_warn (context, 0, me, _("exit status out of range: `%d'"), exit_code);
821 exit_code = EXIT_FAILURE;
824 /* Ensure that atexit handlers see correct nonzero status. */
825 if (exit_code != EXIT_SUCCESS)
826 m4_set_exit_failure (exit_code);
828 /* Change debug stream back to stderr, to force flushing debug
829 stream and detect any errors. */
830 m4_debug_set_output (context, me, NULL);
831 m4_sysval_flush (context, true);
833 /* Check for saved error. */
834 if (exit_code == 0 && m4_get_exit_status (context) != 0)
835 exit_code = m4_get_exit_status (context);
836 exit (exit_code);
839 /* Save the argument text until EOF has been seen, allowing for user
840 specified cleanup action. GNU version saves all arguments, the standard
841 version only the first. */
842 M4BUILTIN_HANDLER (m4wrap)
844 m4_wrap_args (context, argv);
847 /* Enable tracing of all specified macros, or all, if none is specified.
848 Tracing is disabled by default, when a macro is defined. This can be
849 overridden by the "t" debug flag. */
851 M4BUILTIN_HANDLER (traceon)
853 const m4_call_info *me = m4_arg_info (argv);
854 size_t i;
856 if (argc == 1)
857 m4_set_debug_level_opt (context, (m4_get_debug_level_opt (context)
858 | M4_DEBUG_TRACE_ALL));
859 else
860 for (i = 1; i < argc; i++)
861 if (m4_is_arg_text (argv, i))
862 m4_set_symbol_name_traced (M4SYMTAB, M4ARG (i), M4ARGLEN (i), true);
863 else
864 m4_warn (context, 0, me, _("invalid macro name ignored"));
867 /* Disable tracing of all specified macros, or all, if none is specified. */
868 M4BUILTIN_HANDLER (traceoff)
870 const m4_call_info *me = m4_arg_info (argv);
871 size_t i;
873 if (argc == 1)
874 m4_set_debug_level_opt (context, (m4_get_debug_level_opt (context)
875 & ~M4_DEBUG_TRACE_ALL));
876 else
877 for (i = 1; i < argc; i++)
878 if (m4_is_arg_text (argv, i))
879 m4_set_symbol_name_traced (M4SYMTAB, M4ARG (i), M4ARGLEN (i), false);
880 else
881 m4_warn (context, 0, me, _("invalid macro name ignored"));
885 /* This section contains text processing macros: "len", "index",
886 "substr", "translit", "format", "regexp" and "patsubst". The last
887 three are GNU specific. */
889 /* Expand to the length of the first argument. */
890 M4BUILTIN_HANDLER (len)
892 m4_shipout_int (obs, M4ARGLEN (1));
895 /* The macro expands to the first index of the second argument in the
896 first argument. As an extension, start the search at the index
897 indicated by the third argument. */
898 M4BUILTIN_HANDLER (index)
900 const char *haystack = M4ARG (1);
901 size_t haystack_len = M4ARGLEN (1);
902 const char *needle = M4ARG (2);
903 const char *result = NULL;
904 int offset = 0;
905 int retval = -1;
907 if (!m4_arg_empty (argv, 3) && !m4_numeric_arg (context, m4_arg_info (argv),
908 M4ARG (3), M4ARGLEN (3),
909 &offset))
910 return;
911 if (offset < 0)
913 offset += haystack_len;
914 if (offset < 0)
915 offset = 0;
917 else if (haystack_len < offset)
919 m4_shipout_int (obs, -1);
920 return;
923 /* Rely on the optimizations guaranteed by gnulib's memmem
924 module. */
925 result = (char *) memmem (haystack + offset, haystack_len - offset, needle,
926 M4ARGLEN (2));
927 if (result)
928 retval = result - haystack;
930 m4_shipout_int (obs, retval);
933 /* The macro "substr" extracts substrings from the first argument,
934 starting from the index given by the second argument, extending for
935 a length given by the third argument. If the third argument is
936 missing or empty, the substring extends to the end of the first
937 argument. As an extension, negative arguments are treated as
938 indices relative to the string length. Also, if a fourth argument
939 is supplied, the original string is output with the selected
940 substring replaced by the argument. */
941 M4BUILTIN_HANDLER (substr)
943 const m4_call_info *me = m4_arg_info (argv);
944 const char *str = M4ARG (1);
945 int start = 0;
946 int end;
947 int length;
949 if (argc <= 2)
951 m4_push_arg (context, obs, argv, 1);
952 return;
955 length = M4ARGLEN (1);
956 if (!m4_arg_empty (argv, 2)
957 && !m4_numeric_arg (context, me, M4ARG (2), M4ARGLEN (2), &start))
958 return;
959 if (start < 0)
960 start += length;
962 if (m4_arg_empty (argv, 3))
963 end = length;
964 else
966 if (!m4_numeric_arg (context, me, M4ARG (3), M4ARGLEN (3), &end))
967 return;
968 if (end < 0)
969 end += length;
970 else
971 end += start;
974 if (5 <= argc)
976 /* Replacement text provided. */
977 if (end < start)
978 end = start;
979 if (end < 0 || length < start)
981 m4_warn (context, 0, me, _("substring out of range"));
982 return;
984 if (start < 0)
985 start = 0;
986 if (length < end)
987 end = length;
988 obstack_grow (obs, str, start);
989 m4_push_arg (context, obs, argv, 4);
990 obstack_grow (obs, str + end, length - end);
991 return;
994 if (start < 0)
995 start = 0;
996 if (length < end)
997 end = length;
998 if (end <= start)
999 return;
1001 obstack_grow (obs, str + start, end - start);
1005 /* Any ranges in string S of length *LEN are expanded, using OBS for
1006 scratch space, and the expansion returned. *LEN is set to the
1007 expanded length. A single - (dash) can be included in the strings
1008 by being the first or the last character in the string. If the
1009 first character in a range is after the first in the character set,
1010 the range is made backwards, thus 9-0 is the string 9876543210. */
1011 const char *
1012 m4_expand_ranges (const char *s, size_t *len, m4_obstack *obs)
1014 unsigned char from;
1015 unsigned char to;
1016 const char *end = s + *len;
1018 assert (obstack_object_size (obs) == 0);
1019 assert (s != end);
1020 from = *s++;
1021 obstack_1grow (obs, from);
1023 for ( ; s != end; from = *s++)
1025 if (*s == '-')
1027 if (++s == end)
1029 /* trailing dash */
1030 obstack_1grow (obs, '-');
1031 break;
1033 to = *s;
1034 if (from <= to)
1036 while (from++ < to)
1037 obstack_1grow (obs, from);
1039 else
1041 while (--from >= to)
1042 obstack_1grow (obs, from);
1045 else
1046 obstack_1grow (obs, *s);
1048 *len = obstack_object_size (obs);
1049 return (char *) obstack_finish (obs);
1052 /* The macro "translit" translates all characters in the first
1053 argument, which are present in the second argument, into the
1054 corresponding character from the third argument. If the third
1055 argument is shorter than the second, the extra characters in the
1056 second argument are deleted from the first. */
1057 M4BUILTIN_HANDLER (translit)
1059 const char *data;
1060 const char *from;
1061 const char *to;
1062 size_t from_len;
1063 size_t to_len;
1064 char map[UCHAR_MAX + 1];
1065 char found[UCHAR_MAX + 1];
1066 unsigned char ch;
1068 enum { ASIS, REPLACE, DELETE };
1070 if (m4_arg_empty (argv, 1) || m4_arg_empty (argv, 2))
1072 m4_push_arg (context, obs, argv, 1);
1073 return;
1076 from = M4ARG (2);
1077 from_len = M4ARGLEN (2);
1079 to = M4ARG (3);
1080 to_len = M4ARGLEN (3);
1081 if (memchr (to, '-', to_len) != NULL)
1082 to = m4_expand_ranges (to, &to_len, m4_arg_scratch (context));
1084 /* If there are only one or two bytes to replace, it is faster to
1085 use memchr2. Using expand_ranges does nothing unless there are
1086 at least three bytes. */
1087 if (from_len <= 2)
1089 const char *p;
1090 size_t len = M4ARGLEN (1);
1091 int second = from[from_len / 2];
1092 data = M4ARG (1);
1093 while ((p = (char *) memchr2 (data, from[0], second, len)))
1095 obstack_grow (obs, data, p - data);
1096 len -= p - data + 1;
1097 data = p + 1;
1098 if (*p == from[0] && to_len)
1099 obstack_1grow (obs, to[0]);
1100 else if (*p == second && 1 < to_len)
1101 obstack_1grow (obs, to[1]);
1103 obstack_grow (obs, data, len);
1104 return;
1107 if (memchr (from, '-', from_len) != NULL)
1108 from = m4_expand_ranges (from, &from_len, m4_arg_scratch (context));
1110 /* Calling memchr(from) for each character in data is quadratic,
1111 since both strings can be arbitrarily long. Instead, create a
1112 from-to mapping in one pass of from, then use that map in one
1113 pass of data, for linear behavior. Traditional behavior is that
1114 only the first instance of a character in from is consulted,
1115 hence the found map. */
1116 memset (map, 0, sizeof map);
1117 memset (found, 0, sizeof found);
1118 while (from_len--)
1120 ch = *from++;
1121 if (found[ch] == ASIS)
1123 if (to_len)
1125 found[ch] = REPLACE;
1126 map[ch] = *to;
1128 else
1129 found[ch] = DELETE;
1131 if (to_len)
1133 to++;
1134 to_len--;
1138 data = M4ARG (1);
1139 from_len = M4ARGLEN (1);
1140 while (from_len--)
1142 ch = *data++;
1143 switch (found[ch])
1145 case ASIS:
1146 obstack_1grow (obs, ch);
1147 break;
1148 case REPLACE:
1149 obstack_1grow (obs, map[ch]);
1150 break;
1151 case DELETE:
1152 break;
1153 default:
1154 assert (!"translit");
1155 abort ();
1162 /* The rest of this file contains the functions to evaluate integer
1163 * expressions for the "eval" macro. `number' should be at least 32 bits.
1165 #define numb_set(ans, x) ((ans) = (x))
1166 #define numb_set_si(ans, si) (*(ans) = (number) (si))
1168 #define numb_ZERO ((number) 0)
1169 #define numb_ONE ((number) 1)
1171 #define numb_init(x) ((x) = numb_ZERO)
1172 #define numb_fini(x)
1174 #define numb_incr(n) ((n) += numb_ONE)
1175 #define numb_decr(n) ((n) -= numb_ONE)
1177 #define numb_zerop(x) ((x) == numb_ZERO)
1178 #define numb_positivep(x) ((x) > numb_ZERO)
1179 #define numb_negativep(x) ((x) < numb_ZERO)
1181 #define numb_eq(x, y) ((x) = ((x) == (y)))
1182 #define numb_ne(x, y) ((x) = ((x) != (y)))
1183 #define numb_lt(x, y) ((x) = ((x) < (y)))
1184 #define numb_le(x, y) ((x) = ((x) <= (y)))
1185 #define numb_gt(x, y) ((x) = ((x) > (y)))
1186 #define numb_ge(x, y) ((x) = ((x) >= (y)))
1188 #define numb_lnot(x) ((x) = (!(x)))
1189 #define numb_lior(x, y) ((x) = ((x) || (y)))
1190 #define numb_land(x, y) ((x) = ((x) && (y)))
1192 #define numb_not(c, x) (*(x) = ~ *(x))
1193 #define numb_eor(c, x, y) (*(x) = *(x) ^ *(y))
1194 #define numb_ior(c, x, y) (*(x) = *(x) | *(y))
1195 #define numb_and(c, x, y) (*(x) = *(x) & *(y))
1197 #define numb_plus(x, y) ((x) = ((x) + (y)))
1198 #define numb_minus(x, y) ((x) = ((x) - (y)))
1199 #define numb_negate(x) ((x) = (- (x)))
1201 #define numb_times(x, y) ((x) = ((x) * (y)))
1202 /* Be careful of x86 SIGFPE. */
1203 #define numb_ratio(x, y) \
1204 (((y) == -1) ? (numb_negate (x)) : ((x) /= (y)))
1205 #define numb_divide(x, y) \
1206 ((*(y) == -1) ? (numb_negate (*(y))) : (*(x) /= *(y)))
1207 #define numb_modulo(c, x, y) \
1208 ((*(y) == -1) ? (*(x) = numb_ZERO) : (*(x) %= *(y)))
1209 /* numb_invert is only used in the context of x**-y, which integral math
1210 does not support. */
1211 #define numb_invert(x) return NEGATIVE_EXPONENT
1213 /* Minimize undefined C behavior (shifting by a negative number,
1214 shifting by the width or greater, left shift overflow, or right
1215 shift of a negative number). Implement Java wrap-around semantics,
1216 with implicit masking of shift amount. This code assumes that the
1217 implementation-defined overflow when casting unsigned to signed is
1218 a silent twos-complement wrap-around. */
1219 #define shift_mask (sizeof (number) * CHAR_BIT - 1)
1220 #define numb_lshift(c, x, y) \
1221 (*(x) = (number) ((unumber) *(x) << (*(y) & shift_mask)))
1222 #define numb_rshift(c, x, y) \
1223 (*(x) = (number) (*(x) < 0 \
1224 ? ~(~(unumber) *(x) >> (*(y) & shift_mask)) \
1225 : (unumber) *(x) >> (*(y) & shift_mask)))
1226 #define numb_urshift(c, x, y) \
1227 (*(x) = (number) ((unumber) *(x) >> (*(y) & shift_mask)))
1230 /* The function ntoa () converts VALUE to a signed ASCII representation in
1231 radix RADIX. Radix must be between 2 and 36, inclusive. */
1232 static const char *
1233 ntoa (number value, int radix)
1235 /* Digits for number to ASCII conversions. */
1236 static char const ntoa_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
1238 bool negative;
1239 unumber uvalue;
1240 /* Sized for radix 2, plus sign and trailing NUL. */
1241 static char str[sizeof value * CHAR_BIT + 2];
1242 char *s = &str[sizeof str];
1244 *--s = '\0';
1246 if (value < 0)
1248 negative = true;
1249 uvalue = (unumber) -value;
1251 else
1253 negative = false;
1254 uvalue = (unumber) value;
1259 *--s = ntoa_digits[uvalue % radix];
1260 uvalue /= radix;
1262 while (uvalue > 0);
1264 if (negative)
1265 *--s = '-';
1266 return s;
1269 static void
1270 numb_obstack (m4_obstack *obs, number value, int radix, int min)
1272 const char *s;
1273 size_t len;
1274 unumber uvalue;
1276 if (radix == 1)
1278 if (value < 0)
1280 obstack_1grow (obs, '-');
1281 uvalue = -value;
1283 else
1284 uvalue = value;
1285 if (uvalue < min)
1287 obstack_blank (obs, min - uvalue);
1288 memset ((char *) obstack_next_free (obs) - (min - uvalue), '0',
1289 min - uvalue);
1291 obstack_blank (obs, uvalue);
1292 memset ((char *) obstack_next_free (obs) - uvalue, '1', uvalue);
1293 return;
1296 s = ntoa (value, radix);
1298 if (*s == '-')
1300 obstack_1grow (obs, '-');
1301 s++;
1303 len = strlen (s);
1304 if (len < min)
1306 min -= len;
1307 obstack_blank (obs, min);
1308 memset ((char *) obstack_next_free (obs) - min, '0', min);
1310 obstack_grow (obs, s, len);
1314 static void
1315 numb_initialise (void)
1320 /* This macro defines the top level code for the "eval" builtin. The
1321 actual work is done in the function m4_evaluate (), which lives in
1322 evalparse.c. */
1323 #define m4_evaluate builtin_eval
1324 #include "evalparse.c"