Typos in source code comments.
[m4.git] / modules / m4.c
blob0c9a14564b6b54ffa265c385fdb8cdc90db48237
1 /* GNU m4 -- A simple macro processor
2 Copyright (C) 2000, 2002, 2003, 2004, 2006, 2007, 2008 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 "stdlib--.h"
32 #include "tempname.h"
33 #include "unistd--.h"
35 #if HAVE_SYS_WAIT_H
36 # include <sys/wait.h>
37 #endif
39 #include <modules/m4.h>
41 /* Rename exported symbols for dlpreload()ing. */
42 #define m4_builtin_table m4_LTX_m4_builtin_table
44 #define m4_set_sysval m4_LTX_m4_set_sysval
45 #define m4_sysval_flush m4_LTX_m4_sysval_flush
46 #define m4_dump_symbols m4_LTX_m4_dump_symbols
47 #define m4_expand_ranges m4_LTX_m4_expand_ranges
48 #define m4_make_temp m4_LTX_m4_make_temp
50 extern void m4_set_sysval (int);
51 extern void m4_sysval_flush (m4 *, bool);
52 extern void m4_dump_symbols (m4 *, m4_dump_symbol_data *, size_t,
53 m4_macro_args *, bool);
54 extern const char *m4_expand_ranges (const char *, size_t *, m4_obstack *);
55 extern void m4_make_temp (m4 *, m4_obstack *, const m4_call_info *,
56 const char *, size_t, bool);
58 /* Maintain each of the builtins implemented in this modules along
59 with their details in a single table for easy maintenance.
61 function macros blind side minargs maxargs */
62 #define builtin_functions \
63 BUILTIN (changecom, false, false, false, 0, 2 ) \
64 BUILTIN (changequote, false, false, false, 0, 2 ) \
65 BUILTIN (decr, false, true, true, 1, 1 ) \
66 BUILTIN (define, true, true, false, 1, 2 ) \
67 BUILTIN (defn, true, true, false, 1, -1 ) \
68 BUILTIN (divert, false, false, false, 0, 2 ) \
69 BUILTIN (divnum, false, false, false, 0, 0 ) \
70 BUILTIN (dnl, false, false, false, 0, 0 ) \
71 BUILTIN (dumpdef, true, false, false, 0, -1 ) \
72 BUILTIN (errprint, false, true, false, 1, -1 ) \
73 BUILTIN (eval, false, true, true, 1, 3 ) \
74 BUILTIN (ifdef, true, true, false, 2, 3 ) \
75 BUILTIN (ifelse, true, true, false, 1, -1 ) \
76 BUILTIN (include, false, true, false, 1, 1 ) \
77 BUILTIN (incr, false, true, true, 1, 1 ) \
78 BUILTIN (index, false, true, true, 2, 2 ) \
79 BUILTIN (len, false, true, true, 1, 1 ) \
80 BUILTIN (m4exit, false, false, false, 0, 1 ) \
81 BUILTIN (m4wrap, true, true, false, 1, -1 ) \
82 BUILTIN (maketemp, false, true, false, 1, 1 ) \
83 BUILTIN (mkstemp, false, true, false, 1, 1 ) \
84 BUILTIN (popdef, true, true, false, 1, -1 ) \
85 BUILTIN (pushdef, true, true, false, 1, 2 ) \
86 BUILTIN (shift, true, true, false, 1, -1 ) \
87 BUILTIN (sinclude, false, true, false, 1, 1 ) \
88 BUILTIN (substr, false, true, true, 2, 3 ) \
89 BUILTIN (syscmd, false, true, true, 1, 1 ) \
90 BUILTIN (sysval, false, false, false, 0, 0 ) \
91 BUILTIN (traceoff, true, false, false, 0, -1 ) \
92 BUILTIN (traceon, true, false, false, 0, -1 ) \
93 BUILTIN (translit, false, true, true, 2, 3 ) \
94 BUILTIN (undefine, true, true, false, 1, -1 ) \
95 BUILTIN (undivert, false, false, false, 0, -1 ) \
98 typedef intmax_t number;
99 typedef uintmax_t unumber;
101 static void include (m4 *context, int argc, m4_macro_args *argv,
102 bool silent);
103 static int dumpdef_cmp_CB (const void *s1, const void *s2);
104 static void * dump_symbol_CB (m4_symbol_table *, const char *, size_t,
105 m4_symbol *symbol, void *userdata);
106 static const char *ntoa (number value, int radix);
107 static void numb_obstack (m4_obstack *obs, number value,
108 int radix, int min);
111 /* Generate prototypes for each builtin handler function. */
112 #define BUILTIN(handler, macros, blind, side, min, max) M4BUILTIN (handler)
113 builtin_functions
114 #undef BUILTIN
117 /* Generate a table for mapping m4 symbol names to handler functions. */
118 const m4_builtin m4_builtin_table[] =
120 #define BUILTIN(handler, macros, blind, side, min, max) \
121 M4BUILTIN_ENTRY (handler, #handler, macros, blind, side, min, max)
123 builtin_functions
124 #undef BUILTIN
126 { NULL, NULL, 0, 0, 0 },
131 /* This module cannot be safely unloaded from memory, incase the unload
132 is triggered by m4exit, and the module is removed while m4exit is in
133 progress. */
134 M4INIT_HANDLER (m4)
136 const char *err = m4_module_makeresident (module);
137 if (err)
138 m4_error (context, 0, 0, NULL, _("cannot make module `%s' resident: %s"),
139 m4_get_module_name (module), err);
144 /* The rest of this file is code for builtins and expansion of user
145 defined macros. All the functions for builtins have a prototype as:
147 void builtin_MACRONAME (m4_obstack *obs, int argc, char *argv[]);
149 The function are expected to leave their expansion on the obstack OBS,
150 as an unfinished object. ARGV is a table of ARGC pointers to the
151 individual arguments to the macro. Please note that in general
152 argv[argc] != NULL. */
154 M4BUILTIN_HANDLER (define)
156 const m4_call_info *me = m4_arg_info (argv);
158 if (m4_is_arg_text (argv, 1))
160 m4_symbol_value *value = m4_symbol_value_create ();
162 if (m4_symbol_value_copy (context, value, m4_arg_symbol (argv, 2)))
163 m4_warn (context, 0, me, _("cannot concatenate builtins"));
164 m4_symbol_define (M4SYMTAB, M4ARG (1), M4ARGLEN (1), value);
166 else
167 m4_warn (context, 0, me, _("invalid macro name ignored"));
170 M4BUILTIN_HANDLER (undefine)
172 size_t i;
173 for (i = 1; i < argc; i++)
174 if (m4_symbol_value_lookup (context, argv, i, true))
175 m4_symbol_delete (M4SYMTAB, M4ARG (i), M4ARGLEN (i));
178 M4BUILTIN_HANDLER (pushdef)
180 const m4_call_info *me = m4_arg_info (argv);
182 if (m4_is_arg_text (argv, 1))
184 m4_symbol_value *value = m4_symbol_value_create ();
186 if (m4_symbol_value_copy (context, value, m4_arg_symbol (argv, 2)))
187 m4_warn (context, 0, me, _("cannot concatenate builtins"));
188 m4_symbol_pushdef (M4SYMTAB, M4ARG (1), M4ARGLEN (1), value);
190 else
191 m4_warn (context, 0, me, _("invalid macro name ignored"));
194 M4BUILTIN_HANDLER (popdef)
196 size_t i;
197 for (i = 1; i < argc; i++)
198 if (m4_symbol_value_lookup (context, argv, i, true))
199 m4_symbol_popdef (M4SYMTAB, M4ARG (i), M4ARGLEN (i));
204 /* --- CONDITIONALS OF M4 --- */
207 M4BUILTIN_HANDLER (ifdef)
209 m4_push_arg (context, obs, argv,
210 m4_symbol_value_lookup (context, argv, 1, false) ? 2 : 3);
213 M4BUILTIN_HANDLER (ifelse)
215 const m4_call_info *me = m4_arg_info (argv);
216 size_t i;
218 /* The valid ranges of argc for ifelse is discontinuous, we cannot
219 rely on the regular mechanisms. */
220 if (argc == 2 || m4_bad_argc (context, argc, me, 3, -1, false))
221 return;
222 else if (argc % 3 == 0)
223 /* Diagnose excess arguments if 5, 8, 11, etc., actual arguments. */
224 m4_bad_argc (context, argc, me, 0, argc - 2, false);
226 i = 1;
227 argc--;
229 while (true)
231 if (m4_arg_equal (context, argv, i, i + 1))
233 m4_push_arg (context, obs, argv, i + 2);
234 return;
236 switch (argc)
238 case 3:
239 return;
241 case 4:
242 case 5:
243 m4_push_arg (context, obs, argv, i + 3);
244 return;
246 default:
247 argc -= 3;
248 i += 3;
254 /* qsort comparison routine, for sorting the table made in m4_dumpdef (). */
255 static int
256 dumpdef_cmp_CB (const void *s1, const void *s2)
258 const m4_string *a = (const m4_string *) s1;
259 const m4_string *b = (const m4_string *) s2;
260 int result = memcmp (a->str, b->str, a->len < b->len ? a->len : b->len);
261 if (!result)
262 result = a->len < b->len ? -1 : b->len < a->len;
263 return result;
266 /* The function m4_dump_symbols () is for use by "dumpdef". It builds up a
267 table of all defined symbol names. */
268 static void *
269 dump_symbol_CB (m4_symbol_table *ignored M4_GNUC_UNUSED, const char *name,
270 size_t len, m4_symbol *symbol, void *userdata)
272 m4_dump_symbol_data *symbol_data = (m4_dump_symbol_data *) userdata;
273 m4_string *key;
275 assert (name);
276 assert (symbol);
277 assert (!m4_is_symbol_value_void (m4_get_symbol_value (symbol)));
279 if (symbol_data->size == 0)
281 size_t offset = obstack_object_size (symbol_data->obs);
282 obstack_blank (symbol_data->obs, sizeof *symbol_data->base);
283 symbol_data->size = (obstack_room (symbol_data->obs)
284 / sizeof *symbol_data->base);
285 symbol_data->base = (m4_string *) (obstack_base (symbol_data->obs)
286 + offset);
288 else
290 obstack_blank_fast (symbol_data->obs, sizeof *symbol_data->base);
291 symbol_data->size--;
294 /* Safe to cast away const, since m4_dump_symbols adds it back. */
295 key = (m4_string *) symbol_data->base++;
296 key->str = (char *) name;
297 key->len = len;
298 return NULL;
301 /* If there are no arguments, build a sorted list of all defined
302 symbols, otherwise, only the specified symbols. */
303 void
304 m4_dump_symbols (m4 *context, m4_dump_symbol_data *data, size_t argc,
305 m4_macro_args *argv, bool complain)
307 assert (obstack_object_size (data->obs) == 0);
308 data->size = obstack_room (data->obs) / sizeof *data->base;
309 data->base = (m4_string *) obstack_base (data->obs);
311 if (argc == 1)
312 m4_symtab_apply (M4SYMTAB, false, dump_symbol_CB, data);
313 else
315 size_t i;
316 m4_symbol *symbol;
318 for (i = 1; i < argc; i++)
320 symbol = m4_symbol_value_lookup (context, argv, i, complain);
321 if (symbol)
322 dump_symbol_CB (NULL, M4ARG (i), M4ARGLEN (i), symbol, data);
326 data->size = obstack_object_size (data->obs) / sizeof *data->base;
327 data->base = (m4_string *) obstack_finish (data->obs);
328 /* Safe to cast away const, since we don't modify entries. */
329 qsort ((m4_string *) data->base, data->size, sizeof *data->base,
330 dumpdef_cmp_CB);
334 /* Implementation of "dumpdef" itself. It builds up a table of pointers to
335 symbols, sorts it and prints the sorted table. */
336 M4BUILTIN_HANDLER (dumpdef)
338 m4_dump_symbol_data data;
339 const m4_string_pair *quotes = NULL;
340 bool stack = m4_is_debug_bit (context, M4_DEBUG_TRACE_STACK);
341 size_t arg_length = m4_get_max_debug_arg_length_opt (context);
342 bool module = m4_is_debug_bit (context, M4_DEBUG_TRACE_MODULE);
344 if (m4_is_debug_bit (context, M4_DEBUG_TRACE_QUOTE))
345 quotes = m4_get_syntax_quotes (M4SYNTAX);
346 data.obs = m4_arg_scratch (context);
347 m4_dump_symbols (context, &data, argc, argv, true);
348 m4_sysval_flush (context, false);
350 for (; data.size > 0; --data.size, data.base++)
352 m4_symbol *symbol = m4_symbol_lookup (M4SYMTAB, data.base->str,
353 data.base->len);
354 char *value;
355 size_t len;
356 assert (symbol);
358 /* TODO - add debugmode(b) option to control quoting style. */
359 obstack_grow (obs, data.base->str, data.base->len);
360 obstack_1grow (obs, ':');
361 obstack_1grow (obs, '\t');
362 m4_symbol_print (context, symbol, obs, quotes, stack, arg_length,
363 module);
364 obstack_1grow (obs, '\n');
365 len = obstack_object_size (obs);
366 value = (char *) obstack_finish (obs);
367 fwrite (value, 1, len, stderr);
368 obstack_free (obs, value);
372 /* The macro "defn" returns the quoted definition of the macro named by
373 the first argument. If the macro is builtin, it will push a special
374 macro-definition token on the input stack. */
375 M4BUILTIN_HANDLER (defn)
377 const m4_call_info *me = m4_arg_info (argv);
378 size_t i;
380 for (i = 1; i < argc; i++)
382 m4_symbol *symbol = m4_symbol_value_lookup (context, argv, i, true);
384 if (!symbol)
386 else if (m4_is_symbol_text (symbol))
387 m4_shipout_string (context, obs, m4_get_symbol_text (symbol),
388 m4_get_symbol_len (symbol), true);
389 else if (m4_is_symbol_func (symbol))
390 m4_push_builtin (context, obs, m4_get_symbol_value (symbol));
391 else if (m4_is_symbol_placeholder (symbol))
392 m4_warn (context, 0, me,
393 _("%s: builtin `%s' requested by frozen file not found"),
394 M4ARG (i), m4_get_symbol_placeholder (symbol));
395 else
397 assert (!"Bad token data type in m4_defn");
398 abort ();
404 /* This section contains macros to handle the builtins "syscmd"
405 and "sysval". */
407 /* Exit code from last "syscmd" command. */
408 /* FIXME - we should preserve this value across freezing. See
409 http://lists.gnu.org/archive/html/bug-m4/2006-06/msg00059.html
410 for ideas on how do to that. */
411 static int m4_sysval = 0;
413 /* Helper macros for readability. */
414 #if UNIX || defined WEXITSTATUS
415 # define M4_SYSVAL_EXITBITS(status) \
416 (WIFEXITED (status) ? WEXITSTATUS (status) : 0)
417 # define M4_SYSVAL_TERMSIGBITS(status) \
418 (WIFSIGNALED (status) ? WTERMSIG (status) << 8 : 0)
420 #else /* !UNIX && !defined WEXITSTATUS */
421 /* Platforms such as mingw do not support the notion of reporting
422 which signal terminated a process. Furthermore if WEXITSTATUS was
423 not provided, then the exit value is in the low eight bits. */
424 # define M4_SYSVAL_EXITBITS(status) status
425 # define M4_SYSVAL_TERMSIGBITS(status) 0
426 #endif /* !UNIX && !defined WEXITSTATUS */
428 /* Fallback definitions if <stdlib.h> or <sys/wait.h> are inadequate. */
429 /* FIXME - this may fit better as a gnulib module. */
430 #ifndef WEXITSTATUS
431 # define WEXITSTATUS(status) (((status) >> 8) & 0xff)
432 #endif
433 #ifndef WTERMSIG
434 # define WTERMSIG(status) ((status) & 0x7f)
435 #endif
436 #ifndef WIFSIGNALED
437 # define WIFSIGNALED(status) (WTERMSIG (status) != 0)
438 #endif
439 #ifndef WIFEXITED
440 # define WIFEXITED(status) (WTERMSIG (status) == 0)
441 #endif
443 void
444 m4_set_sysval (int value)
446 m4_sysval = value;
449 /* Flush a given output STREAM. If REPORT, also print an error
450 message and clear the stream error bit. */
451 static void
452 sysval_flush_helper (m4 *context, FILE *stream, bool report)
454 if (fflush (stream) == EOF && report)
456 m4_error (context, 0, errno, NULL, _("write error"));
457 clearerr (stream);
461 /* Flush all user output streams, prior to doing something that can
462 could lose unflushed data or interleave debug and normal output
463 incorrectly. If REPORT, then print an error message on failure and
464 clear the stream error bit; otherwise a subsequent ferror can track
465 that an error occurred. */
466 void
467 m4_sysval_flush (m4 *context, bool report)
469 FILE *debug_file = m4_get_debug_file (context);
471 if (debug_file != stdout)
472 sysval_flush_helper (context, stdout, report);
473 if (debug_file != stderr)
474 /* If we have problems with stderr, we can't really report that
475 problem to stderr. The closeout module will ensure the exit
476 status reflects the problem, though. */
477 fflush (stderr);
478 if (debug_file != NULL)
479 sysval_flush_helper (context, debug_file, report);
480 /* POSIX requires that if m4 doesn't consume all input, but stdin is
481 opened on a seekable file, that the file pointer be left at the
482 next character on exit (but places no restrictions on the file
483 pointer location on a non-seekable file). It also requires that
484 fflush() followed by fseeko() on an input file set the underlying
485 file pointer, and gnulib guarantees these semantics. However,
486 fflush() on a non-seekable file can lose buffered data, which we
487 might otherwise want to process after syscmd. Hence, we must
488 check whether stdin is seekable. We must also be tolerant of
489 operating with stdin closed, so we don't report any failures in
490 this attempt. The stdio-safer module and friends are essential,
491 so that if stdin was closed, this lseek is not on some other file
492 that we have since opened. */
493 if (lseek (STDIN_FILENO, 0, SEEK_CUR) >= 0
494 && fflush (stdin) == 0)
496 fseeko (stdin, 0, SEEK_CUR);
500 M4BUILTIN_HANDLER (syscmd)
502 if (m4_get_safer_opt (context))
504 m4_error (context, 0, 0, m4_arg_info (argv), _("disabled by --safer"));
505 return;
508 /* Optimize the empty command. */
509 if (m4_arg_empty (argv, 1))
511 m4_set_sysval (0);
512 return;
514 m4_sysval_flush (context, false);
515 m4_sysval = system (M4ARG (1));
516 /* FIXME - determine if libtool works for OS/2, in which case the
517 FUNC_SYSTEM_BROKEN section on the branch must be ported to work
518 around the bug in their EMX libc system(). */
522 M4BUILTIN_HANDLER (sysval)
524 m4_shipout_int (obs, (m4_sysval == -1 ? 127
525 : (M4_SYSVAL_EXITBITS (m4_sysval)
526 | M4_SYSVAL_TERMSIGBITS (m4_sysval))));
530 M4BUILTIN_HANDLER (incr)
532 int value;
534 if (!m4_numeric_arg (context, m4_arg_info (argv), M4ARG (1), &value))
535 return;
537 m4_shipout_int (obs, value + 1);
540 M4BUILTIN_HANDLER (decr)
542 int value;
544 if (!m4_numeric_arg (context, m4_arg_info (argv), M4ARG (1), &value))
545 return;
547 m4_shipout_int (obs, value - 1);
551 /* This section contains the macros "divert", "undivert" and "divnum" for
552 handling diversion. The utility functions used lives in output.c. */
554 /* Divert further output to the diversion given by ARGV[1]. Out of range
555 means discard further output. */
556 M4BUILTIN_HANDLER (divert)
558 int i = 0;
560 if (argc >= 2 && !m4_numeric_arg (context, m4_arg_info (argv), M4ARG (1),
561 &i))
562 return;
563 m4_make_diversion (context, i);
564 m4_divert_text (context, NULL, M4ARG (2), M4ARGLEN (2),
565 m4_get_current_line (context));
568 /* Expand to the current diversion number. */
569 M4BUILTIN_HANDLER (divnum)
571 m4_shipout_int (obs, m4_get_current_diversion (context));
574 /* Bring back the diversion given by the argument list. If none is
575 specified, bring back all diversions. GNU specific is the option
576 of undiverting the named file, by passing a non-numeric argument to
577 undivert (). */
579 M4BUILTIN_HANDLER (undivert)
581 size_t i = 0;
582 const m4_call_info *me = m4_arg_info (argv);
584 if (argc == 1)
585 m4_undivert_all (context);
586 else
587 for (i = 1; i < argc; i++)
589 const char *str = M4ARG (i);
590 char *endp;
591 int diversion = strtol (str, &endp, 10);
592 if (*endp == '\0' && !isspace ((unsigned char) *str))
593 m4_insert_diversion (context, diversion);
594 else if (m4_get_posixly_correct_opt (context))
595 m4_numeric_arg (context, me, str, &diversion);
596 else
598 FILE *fp = m4_path_search (context, str, NULL);
599 if (fp != NULL)
601 m4_insert_file (context, fp);
602 if (fclose (fp) == EOF)
603 m4_error (context, 0, errno, me, _("error undiverting `%s'"),
604 str);
606 else
607 m4_error (context, 0, errno, me, _("cannot undivert `%s'"), str);
613 /* This section contains various macros, which does not fall into
614 any specific group. These are "dnl", "shift", "changequote",
615 "changecom" and "changesyntax" */
617 /* Delete all subsequent whitespace from input. The function skip_line ()
618 lives in input.c. */
619 M4BUILTIN_HANDLER (dnl)
621 m4_skip_line (context, m4_arg_info (argv));
624 /* Shift all arguments one to the left, discarding the first argument.
625 Each output argument is quoted with the current quotes. */
626 M4BUILTIN_HANDLER (shift)
628 m4_push_args (context, obs, argv, true, true);
631 /* Change the current quotes. The function set_quotes () lives in
632 syntax.c. */
633 M4BUILTIN_HANDLER (changequote)
635 m4_set_quotes (M4SYNTAX,
636 (argc >= 2) ? M4ARG (1) : NULL, M4ARGLEN (1),
637 (argc >= 3) ? M4ARG (2) : NULL, M4ARGLEN (2));
640 /* Change the current comment delimiters. The function set_comment ()
641 lives in syntax.c. */
642 M4BUILTIN_HANDLER (changecom)
644 m4_set_comment (M4SYNTAX,
645 (argc >= 2) ? M4ARG (1) : NULL, M4ARGLEN (1),
646 (argc >= 3) ? M4ARG (2) : NULL, M4ARGLEN (2));
650 /* This section contains macros for inclusion of other files -- "include"
651 and "sinclude". This differs from bringing back diversions, in that
652 the input is scanned before being copied to the output. */
654 /* Generic include function. Include the file given by the first
655 argument, if it exists. Complain about inaccessible files iff
656 SILENT is false. */
657 static void
658 include (m4 *context, int argc, m4_macro_args *argv, bool silent)
660 FILE *fp;
661 char *name = NULL;
663 fp = m4_path_search (context, M4ARG (1), &name);
664 if (fp == NULL)
666 if (!silent)
667 m4_error (context, 0, errno, m4_arg_info (argv), _("cannot open `%s'"),
668 M4ARG (1));
669 return;
672 m4_push_file (context, fp, name, true);
673 free (name);
676 /* Include a file, complaining in case of errors. */
677 M4BUILTIN_HANDLER (include)
679 include (context, argc, argv, false);
682 /* Include a file, ignoring errors. */
683 M4BUILTIN_HANDLER (sinclude)
685 include (context, argc, argv, true);
689 /* More miscellaneous builtins -- "maketemp", "errprint". */
691 /* Add trailing `X' to PATTERN of length LEN as necessary, then
692 securely create the temporary file system object. If DIR, create a
693 directory instead of a file. Report errors on behalf of CALLER. If
694 successful, output the quoted resulting name on OBS. */
695 void
696 m4_make_temp (m4 *context, m4_obstack *obs, const m4_call_info *caller,
697 const char *pattern, size_t len, bool dir)
699 int fd;
700 int i;
701 char *name;
702 const m4_string_pair *quotes = m4_get_syntax_quotes (M4SYNTAX);
704 if (m4_get_safer_opt (context))
706 m4_error (context, 0, 0, caller, _("disabled by --safer"));
707 return;
710 /* Guarantee that there are six trailing 'X' characters, even if the
711 user forgot to supply them. Output must be quoted if
712 successful. */
713 assert (obstack_object_size (obs) == 0);
714 obstack_grow (obs, quotes->str1, quotes->len1);
715 obstack_grow (obs, pattern, len);
716 for (i = 0; len > 0 && i < 6; i++)
717 if (pattern[--len] != 'X')
718 break;
719 obstack_grow0 (obs, "XXXXXX", 6 - i);
720 name = (char *) obstack_base (obs) + quotes->len1;
722 /* Make the temporary object. */
723 errno = 0;
724 fd = gen_tempname (name, dir ? GT_DIR : GT_FILE);
725 if (fd < 0)
727 /* This use of _() will need to change if xgettext ever changes
728 its undocumented behavior of parsing both string options. */
730 m4_error (context, 0, errno, caller,
731 _(dir ? "cannot create directory from template `%s'"
732 : "cannot create file from template `%s'"),
733 pattern);
734 obstack_free (obs, obstack_finish (obs));
736 else
738 if (!dir)
739 close (fd);
740 /* Remove NUL, then finish quote. */
741 obstack_blank (obs, -1);
742 obstack_grow (obs, quotes->str2, quotes->len2);
746 /* Use the first argument as at template for a temporary file name. */
747 M4BUILTIN_HANDLER (maketemp)
749 const m4_call_info *me = m4_arg_info (argv);
750 m4_warn (context, 0, me, _("recommend using mkstemp instead"));
751 if (m4_get_posixly_correct_opt (context))
753 /* POSIX states "any trailing 'X' characters [are] replaced with
754 the current process ID as a string", without referencing the
755 file system. Horribly insecure, but we have to do it.
757 For reference, Solaris m4 does:
758 maketemp() -> `'
759 maketemp(X) -> `X'
760 maketemp(XX) -> `Xn', where n is last digit of pid
761 maketemp(XXXXXXXX) -> `X00nnnnn', where nnnnn is 16-bit pid
763 const char *str = M4ARG (1);
764 size_t len = M4ARGLEN (1);
765 size_t i;
766 m4_obstack *scratch = m4_arg_scratch (context);
767 size_t pid_len = obstack_printf (scratch, "%lu",
768 (unsigned long) getpid ());
769 char *pid = (char *) obstack_copy0 (scratch, "", 0);
771 for (i = len; i > 1; i--)
772 if (str[i - 1] != 'X')
773 break;
774 obstack_grow (obs, str, i);
775 if (len - i < pid_len)
776 obstack_grow (obs, pid + pid_len - (len - i), len - i);
777 else
778 obstack_printf (obs, "%.*d%s", len - i - pid_len, 0, pid);
780 else
781 m4_make_temp (context, obs, me, M4ARG (1), M4ARGLEN (1), false);
784 /* Use the first argument as a template for a temporary file name. */
785 M4BUILTIN_HANDLER (mkstemp)
787 m4_make_temp (context, obs, m4_arg_info (argv), M4ARG (1), M4ARGLEN (1),
788 false);
791 /* Print all arguments on standard error. */
792 M4BUILTIN_HANDLER (errprint)
794 size_t i;
796 m4_sysval_flush (context, false);
797 /* The close_stdin module makes it safe to skip checking the return
798 values here. */
799 fwrite (M4ARG (1), 1, M4ARGLEN (1), stderr);
800 for (i = 2; i < m4_arg_argc (argv); i++)
802 fputc (' ', stderr);
803 fwrite (M4ARG (i), 1, M4ARGLEN (i), stderr);
805 fflush (stderr);
809 /* This section contains various macros for exiting, saving input until
810 EOF is seen, and tracing macro calls. That is: "m4exit", "m4wrap",
811 "traceon" and "traceoff". */
813 /* Exit immediately, with exitcode specified by the first argument, 0 if no
814 arguments are present. */
815 M4BUILTIN_HANDLER (m4exit)
817 const m4_call_info *me = m4_arg_info (argv);
818 int exit_code = EXIT_SUCCESS;
820 /* Warn on bad arguments, but still exit. */
821 if (argc >= 2 && !m4_numeric_arg (context, me, M4ARG (1), &exit_code))
822 exit_code = EXIT_FAILURE;
823 if (exit_code < 0 || exit_code > 255)
825 m4_warn (context, 0, me, _("exit status out of range: `%d'"), exit_code);
826 exit_code = EXIT_FAILURE;
829 /* Ensure that atexit handlers see correct nonzero status. */
830 if (exit_code != EXIT_SUCCESS)
831 m4_set_exit_failure (exit_code);
833 /* Ensure any module exit callbacks are executed. */
834 m4__module_exit (context);
836 /* Change debug stream back to stderr, to force flushing debug
837 stream and detect any errors. */
838 m4_debug_set_output (context, me, NULL);
839 m4_sysval_flush (context, true);
841 /* Check for saved error. */
842 if (exit_code == 0 && m4_get_exit_status (context) != 0)
843 exit_code = m4_get_exit_status (context);
844 exit (exit_code);
847 /* Save the argument text until EOF has been seen, allowing for user
848 specified cleanup action. GNU version saves all arguments, the standard
849 version only the first. */
850 M4BUILTIN_HANDLER (m4wrap)
852 m4_wrap_args (context, argv);
855 /* Enable tracing of all specified macros, or all, if none is specified.
856 Tracing is disabled by default, when a macro is defined. This can be
857 overridden by the "t" debug flag. */
859 M4BUILTIN_HANDLER (traceon)
861 const m4_call_info *me = m4_arg_info (argv);
862 size_t i;
864 if (argc == 1)
865 m4_set_debug_level_opt (context, (m4_get_debug_level_opt (context)
866 | M4_DEBUG_TRACE_ALL));
867 else
868 for (i = 1; i < argc; i++)
869 if (m4_is_arg_text (argv, i))
870 m4_set_symbol_name_traced (M4SYMTAB, M4ARG (i), M4ARGLEN (i), true);
871 else
872 m4_warn (context, 0, me, _("invalid macro name ignored"));
875 /* Disable tracing of all specified macros, or all, if none is specified. */
876 M4BUILTIN_HANDLER (traceoff)
878 const m4_call_info *me = m4_arg_info (argv);
879 size_t i;
881 if (argc == 1)
882 m4_set_debug_level_opt (context, (m4_get_debug_level_opt (context)
883 & ~M4_DEBUG_TRACE_ALL));
884 else
885 for (i = 1; i < argc; i++)
886 if (m4_is_arg_text (argv, i))
887 m4_set_symbol_name_traced (M4SYMTAB, M4ARG (i), M4ARGLEN (i), false);
888 else
889 m4_warn (context, 0, me, _("invalid macro name ignored"));
893 /* This section contains text processing macros: "len", "index",
894 "substr", "translit", "format", "regexp" and "patsubst". The last
895 three are GNU specific. */
897 /* Expand to the length of the first argument. */
898 M4BUILTIN_HANDLER (len)
900 m4_shipout_int (obs, M4ARGLEN (1));
903 /* The macro expands to the first index of the second argument in the first
904 argument. */
905 M4BUILTIN_HANDLER (index)
907 const char *haystack = M4ARG (1);
908 const char *needle = M4ARG (2);
909 const char *result = NULL;
910 int retval = -1;
912 /* Rely on the optimizations guaranteed by gnulib's memmem
913 module. */
914 result = (char *) memmem (haystack, M4ARGLEN (1), needle, M4ARGLEN (2));
915 if (result)
916 retval = result - haystack;
918 m4_shipout_int (obs, retval);
921 /* The macro "substr" extracts substrings from the first argument, starting
922 from the index given by the second argument, extending for a length
923 given by the third argument. If the third argument is missing, the
924 substring extends to the end of the first argument. */
925 M4BUILTIN_HANDLER (substr)
927 const m4_call_info *me = m4_arg_info (argv);
928 const char *str = M4ARG (1);
929 int start = 0;
930 int length;
931 int avail;
933 if (argc <= 2)
935 m4_push_arg (context, obs, argv, 1);
936 return;
939 length = avail = M4ARGLEN (1);
940 if (!m4_numeric_arg (context, me, M4ARG (2), &start))
941 return;
943 if (argc >= 4 && !m4_numeric_arg (context, me, M4ARG (3), &length))
944 return;
946 if (start < 0 || length <= 0 || start >= avail)
947 return;
949 if (start + length > avail)
950 length = avail - start;
951 obstack_grow (obs, str + start, length);
955 /* Any ranges in string S of length *LEN are expanded, using OBS for
956 scratch space, and the expansion returned. *LEN is set to the
957 expanded length. A single - (dash) can be included in the strings
958 by being the first or the last character in the string. If the
959 first character in a range is after the first in the character set,
960 the range is made backwards, thus 9-0 is the string 9876543210. */
961 const char *
962 m4_expand_ranges (const char *s, size_t *len, m4_obstack *obs)
964 unsigned char from;
965 unsigned char to;
966 const char *end = s + *len;
968 assert (obstack_object_size (obs) == 0);
969 assert (s != end);
970 from = *s++;
971 obstack_1grow (obs, from);
973 for ( ; s != end; from = *s++)
975 if (*s == '-')
977 if (++s == end)
979 /* trailing dash */
980 obstack_1grow (obs, '-');
981 break;
983 to = *s;
984 if (from <= to)
986 while (from++ < to)
987 obstack_1grow (obs, from);
989 else
991 while (--from >= to)
992 obstack_1grow (obs, from);
995 else
996 obstack_1grow (obs, *s);
998 *len = obstack_object_size (obs);
999 /* FIXME - use obstack_finish once translit is updated. */
1000 return (char *) obstack_copy0 (obs, "", 0);
1003 /* The macro "translit" translates all characters in the first
1004 argument, which are present in the second argument, into the
1005 corresponding character from the third argument. If the third
1006 argument is shorter than the second, the extra characters in the
1007 second argument are deleted from the first. */
1008 M4BUILTIN_HANDLER (translit)
1010 const char *data;
1011 const char *from;
1012 const char *to;
1013 size_t from_len;
1014 size_t to_len;
1015 char map[UCHAR_MAX + 1] = {0};
1016 char found[UCHAR_MAX + 1] = {0};
1017 unsigned char ch;
1019 if (argc <= 2)
1021 m4_push_arg (context, obs, argv, 1);
1022 return;
1025 from = M4ARG (2);
1026 from_len = M4ARGLEN (2);
1027 if (strchr (from, '-') != NULL)
1029 from = m4_expand_ranges (from, &from_len, m4_arg_scratch (context));
1030 assert (from);
1033 to = M4ARG (3);
1034 to_len = M4ARGLEN (3);
1035 if (strchr (to, '-') != NULL)
1037 to = m4_expand_ranges (to, &to_len, m4_arg_scratch (context));
1038 assert (to);
1041 /* Calling strchr(from) for each character in data is quadratic,
1042 since both strings can be arbitrarily long. Instead, create a
1043 from-to mapping in one pass of from, then use that map in one
1044 pass of data, for linear behavior. Traditional behavior is that
1045 only the first instance of a character in from is consulted,
1046 hence the found map. */
1047 for ( ; (ch = *from) != '\0'; from++)
1049 if (!found[ch])
1051 found[ch] = 1;
1052 map[ch] = *to;
1054 if (*to != '\0')
1055 to++;
1058 for (data = M4ARG (1); (ch = *data) != '\0'; data++)
1060 if (!found[ch])
1061 obstack_1grow (obs, ch);
1062 else if (map[ch])
1063 obstack_1grow (obs, map[ch]);
1069 /* The rest of this file contains the functions to evaluate integer
1070 * expressions for the "eval" macro. `number' should be at least 32 bits.
1072 #define numb_set(ans, x) ((ans) = (x))
1073 #define numb_set_si(ans, si) (*(ans) = (number) (si))
1075 #define numb_ZERO ((number) 0)
1076 #define numb_ONE ((number) 1)
1078 #define numb_init(x) ((x) = numb_ZERO)
1079 #define numb_fini(x)
1081 #define numb_incr(n) ((n) += numb_ONE)
1082 #define numb_decr(n) ((n) -= numb_ONE)
1084 #define numb_zerop(x) ((x) == numb_ZERO)
1085 #define numb_positivep(x) ((x) > numb_ZERO)
1086 #define numb_negativep(x) ((x) < numb_ZERO)
1088 #define numb_eq(x, y) ((x) = ((x) == (y)))
1089 #define numb_ne(x, y) ((x) = ((x) != (y)))
1090 #define numb_lt(x, y) ((x) = ((x) < (y)))
1091 #define numb_le(x, y) ((x) = ((x) <= (y)))
1092 #define numb_gt(x, y) ((x) = ((x) > (y)))
1093 #define numb_ge(x, y) ((x) = ((x) >= (y)))
1095 #define numb_lnot(x) ((x) = (!(x)))
1096 #define numb_lior(x, y) ((x) = ((x) || (y)))
1097 #define numb_land(x, y) ((x) = ((x) && (y)))
1099 #define numb_not(c, x) (*(x) = ~ *(x))
1100 #define numb_eor(c, x, y) (*(x) = *(x) ^ *(y))
1101 #define numb_ior(c, x, y) (*(x) = *(x) | *(y))
1102 #define numb_and(c, x, y) (*(x) = *(x) & *(y))
1104 #define numb_plus(x, y) ((x) = ((x) + (y)))
1105 #define numb_minus(x, y) ((x) = ((x) - (y)))
1106 #define numb_negate(x) ((x) = (- (x)))
1108 #define numb_times(x, y) ((x) = ((x) * (y)))
1109 /* Be careful of x86 SIGFPE. */
1110 #define numb_ratio(x, y) \
1111 (((y) == -1) ? (numb_negate (x)) : ((x) /= (y)))
1112 #define numb_divide(x, y) \
1113 ((*(y) == -1) ? (numb_negate (*(y))) : (*(x) /= *(y)))
1114 #define numb_modulo(c, x, y) \
1115 ((*(y) == -1) ? (*(x) = numb_ZERO) : (*(x) %= *(y)))
1116 /* numb_invert is only used in the context of x**-y, which integral math
1117 does not support. */
1118 #define numb_invert(x) return NEGATIVE_EXPONENT
1120 /* Minimize undefined C behavior (shifting by a negative number,
1121 shifting by the width or greater, left shift overflow, or right
1122 shift of a negative number). Implement Java wrap-around semantics,
1123 with implicit masking of shift amount. This code assumes that the
1124 implementation-defined overflow when casting unsigned to signed is
1125 a silent twos-complement wrap-around. */
1126 #define shift_mask (sizeof (number) * CHAR_BIT - 1)
1127 #define numb_lshift(c, x, y) \
1128 (*(x) = (number) ((unumber) *(x) << (*(y) & shift_mask)))
1129 #define numb_rshift(c, x, y) \
1130 (*(x) = (number) (*(x) < 0 \
1131 ? ~(~(unumber) *(x) >> (*(y) & shift_mask)) \
1132 : (unumber) *(x) >> (*(y) & shift_mask)))
1133 #define numb_urshift(c, x, y) \
1134 (*(x) = (number) ((unumber) *(x) >> (*(y) & shift_mask)))
1137 /* The function ntoa () converts VALUE to a signed ASCII representation in
1138 radix RADIX. Radix must be between 2 and 36, inclusive. */
1139 static const char *
1140 ntoa (number value, int radix)
1142 /* Digits for number to ASCII conversions. */
1143 static char const ntoa_digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
1145 bool negative;
1146 unumber uvalue;
1147 /* Sized for radix 2, plus sign and trailing NUL. */
1148 static char str[sizeof value * CHAR_BIT + 2];
1149 char *s = &str[sizeof str];
1151 *--s = '\0';
1153 if (value < 0)
1155 negative = true;
1156 uvalue = (unumber) -value;
1158 else
1160 negative = false;
1161 uvalue = (unumber) value;
1166 *--s = ntoa_digits[uvalue % radix];
1167 uvalue /= radix;
1169 while (uvalue > 0);
1171 if (negative)
1172 *--s = '-';
1173 return s;
1176 static void
1177 numb_obstack (m4_obstack *obs, number value, int radix, int min)
1179 const char *s;
1180 size_t len;
1181 unumber uvalue;
1183 if (radix == 1)
1185 if (value < 0)
1187 obstack_1grow (obs, '-');
1188 uvalue = -value;
1190 else
1191 uvalue = value;
1192 if (uvalue < min)
1194 obstack_blank (obs, min - uvalue);
1195 memset ((char *) obstack_next_free (obs) - (min - uvalue), '0',
1196 min - uvalue);
1198 obstack_blank (obs, uvalue);
1199 memset ((char *) obstack_next_free (obs) - uvalue, '1', uvalue);
1200 return;
1203 s = ntoa (value, radix);
1205 if (*s == '-')
1207 obstack_1grow (obs, '-');
1208 s++;
1210 len = strlen (s);
1211 if (len < min)
1213 min -= len;
1214 obstack_blank (obs, min);
1215 memset ((char *) obstack_next_free (obs) - min, '0', min);
1217 obstack_grow (obs, s, len);
1221 static void
1222 numb_initialise (void)
1227 /* This macro defines the top level code for the "eval" builtin. The
1228 actual work is done in the function m4_evaluate (), which lives in
1229 evalparse.c. */
1230 #define m4_evaluate builtin_eval
1231 #include "evalparse.c"