1 /* $OpenBSD: main.c,v 1.87 2017/06/15 13:48:42 bcallah Exp $ */
2 /* $NetBSD: main.c,v 1.12 1997/02/08 23:54:49 cgd Exp $ */
5 * SPDX-License-Identifier: BSD-3-Clause
7 * Copyright (c) 1989, 1993
8 * The Regents of the University of California. All rights reserved.
10 * This code is derived from software contributed to Berkeley by
11 * Ozan Yigit at York University.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
21 * 3. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 * Facility: m4 macro processor
43 #include <sys/cdefs.h>
60 #include "pathnames.h"
62 static const char *shortopts = "+D:d::EGgI:o:Pst:U:";
63 static const struct option longopts[] = {
64 { "define", required_argument, NULL, 'D' },
65 { "debug", optional_argument, NULL, 'd' },
66 { "fatal-warnings", no_argument, NULL, 'E' },
67 { "traditional", no_argument, NULL, 'G' },
68 { "gnu", no_argument, NULL, 'g' },
69 { "include", required_argument, NULL, 'I' },
70 { "error-output", required_argument, NULL, 'o' },
71 { "prefix-builtins", no_argument, NULL, 'P' },
72 { "synclines", no_argument, NULL, 's' },
73 { "trace", required_argument, NULL, 't' },
74 { "undefine", required_argument, NULL, 'U' },
78 stae *mstack; /* stack of m4 machine */
79 char *sstack; /* shadow stack, for string space extension */
80 static size_t STACKMAX; /* current maximum size of stack */
81 int sp; /* current m4 stack pointer */
82 int fp; /* m4 call frame pointer */
83 struct input_file infile[MAXINP];/* input file stack (0=stdin) */
84 FILE **outfile; /* diversion array(0=bitbucket)*/
86 FILE *active; /* active output file pointer */
87 int ilevel = 0; /* input file stack pointer */
88 int oindex = 0; /* diversion index.. */
89 const char *null = ""; /* as it says.. just a null.. */
90 char **m4wraps = NULL; /* m4wraps array. */
91 int maxwraps = 0; /* size of m4wraps array */
92 int wrapindex = 0; /* current offset in m4wraps */
93 char lquote[MAXCCHARS+1] = {LQUOTE}; /* left quote character (`) */
94 char rquote[MAXCCHARS+1] = {RQUOTE}; /* right quote character (') */
95 char scommt[MAXCCHARS+1] = {SCOMMT}; /* start character for comment */
96 char ecommt[MAXCCHARS+1] = {ECOMMT}; /* end character for comment */
97 int synch_lines = 0; /* line synchronisation for C preprocessor */
98 int prefix_builtins = 0; /* -P option to prefix builtin keywords */
99 int error_warns = 0; /* -E option to make warnings exit_code = 1 */
100 int fatal_warns = 0; /* -E -E option to make warnings fatal */
103 const char *knam; /* keyword name */
104 int ktyp; /* keyword type */
107 static struct keyblk keywrds[] = { /* m4 keywords to be installed */
108 { "include", INCLTYPE },
109 { "sinclude", SINCTYPE },
110 { "define", DEFITYPE },
111 { "defn", DEFNTYPE },
112 { "divert", DIVRTYPE | NOARGS },
113 { "expr", EXPRTYPE },
114 { "eval", EXPRTYPE },
115 { "substr", SUBSTYPE },
116 { "ifelse", IFELTYPE },
117 { "ifdef", IFDFTYPE },
119 { "incr", INCRTYPE },
120 { "decr", DECRTYPE },
121 { "dnl", DNLNTYPE | NOARGS },
122 { "changequote", CHNQTYPE | NOARGS },
123 { "changecom", CHNCTYPE | NOARGS },
124 { "index", INDXTYPE },
126 { "paste", PASTTYPE },
127 { "spaste", SPASTYPE },
128 /* Newer extensions, needed to handle gnu-m4 scripts */
129 { "indir", INDIRTYPE},
130 { "builtin", BUILTINTYPE},
131 { "patsubst", PATSTYPE},
132 { "regexp", REGEXPTYPE},
133 { "esyscmd", ESYSCMDTYPE},
134 { "__file__", FILENAMETYPE | NOARGS},
135 { "__line__", LINETYPE | NOARGS},
137 { "popdef", POPDTYPE },
138 { "pushdef", PUSDTYPE },
139 { "dumpdef", DUMPTYPE | NOARGS },
140 { "shift", SHIFTYPE | NOARGS },
141 { "translit", TRNLTYPE },
142 { "undefine", UNDFTYPE },
143 { "undivert", UNDVTYPE | NOARGS },
144 { "divnum", DIVNTYPE | NOARGS },
145 { "maketemp", MKTMTYPE },
146 { "mkstemp", MKTMTYPE },
147 { "errprint", ERRPTYPE | NOARGS },
148 { "m4wrap", M4WRTYPE | NOARGS },
149 { "m4exit", EXITTYPE | NOARGS },
150 { "syscmd", SYSCTYPE },
151 { "sysval", SYSVTYPE | NOARGS },
152 { "traceon", TRACEONTYPE | NOARGS },
153 { "traceoff", TRACEOFFTYPE | NOARGS },
155 { "unix", SELFTYPE | NOARGS },
158 #define MAXKEYS (sizeof(keywrds)/sizeof(struct keyblk))
164 static struct position {
167 } quotes[MAXRECORD], paren[MAXRECORD];
169 static void record(struct position *, int);
170 static void dump_stack(struct position *, int);
172 static void macro(void);
173 static void initkwds(void);
174 static ndptr inspect(int, char *);
175 static int do_look_ahead(int, const char *);
176 static void reallyoutputstr(const char *);
177 static void reallyputchar(int);
179 static void enlarge_stack(void);
181 int main(int, char *[]);
186 main(int argc, char *argv[])
192 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
193 signal(SIGINT, onintr);
197 STACKMAX = INITSTACKMAX;
199 mstack = xreallocarray(NULL, STACKMAX, sizeof(stae), NULL);
200 sstack = xalloc(STACKMAX, NULL);
206 while ((c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1)
209 case 'D': /* define something..*/
210 for (p = optarg; *p; p++)
217 case 'E': /* like GNU m4 1.4.9+ */
218 if (error_warns == 0)
224 addtoincludepath(optarg);
229 case 'U': /* undefine... */
230 macro_popdef(optarg);
239 set_trace_flags(optarg ? optarg : "aeq");
245 mark_traced(optarg, 1);
259 setup_builtin("format", FORMATTYPE);
261 active = stdout; /* default active output */
264 sp = -1; /* stack pointer initialized */
265 fp = 0; /* frame pointer initialized */
266 set_input(infile+0, stdin, "stdin");
267 /* default input (naturally) */
270 for (; argc--; ++argv) {
272 if (p[0] == '-' && p[1] == EOS)
273 set_input(infile, stdin, "stdin");
274 else if (fopen_trypath(infile, p) == NULL)
279 release_input(infile);
285 ilevel = 0; /* in case m4wrap includes.. */
286 bufbase = bp = buf; /* use the entire buffer */
288 while (wrapindex != 0) {
289 for (i = 0; i < wrapindex; i++)
295 for (i = 0; i < wrapindex; i++) {
302 if (active != stdout)
303 active = stdout; /* reset output just in case */
304 for (n = 1; n < maxout; n++) /* default wrap-up: undivert */
305 if (outfile[n] != NULL)
307 /* remove bitbucket if used */
308 if (outfile[0] != NULL) {
309 (void) fclose(outfile[0]);
316 * Look ahead for `token'.
317 * (on input `t == token[0]')
318 * Used for comment and quoting delimiters.
319 * Returns 1 if `token' present; copied to output.
320 * 0 if `token' not found; all characters pushed back
323 do_look_ahead(int t, const char *token)
327 assert((unsigned char)t == (unsigned char)token[0]);
329 for (i = 1; *++token; i++) {
331 if (t == EOF || (unsigned char)t != (unsigned char)*token) {
341 #define LOOK_AHEAD(t, token) (t != EOF && \
342 (unsigned char)(t)==(unsigned char)(token)[0] && \
343 do_look_ahead(t,token))
346 * macro - the work horse..
351 char token[MAXTOK+1];
359 if (LOOK_AHEAD(t,lquote)) { /* strip quotes */
361 record(quotes, nlpar++);
363 * Opening quote: scan forward until matching
364 * closing quote has been found.
369 if (LOOK_AHEAD(l,rquote)) {
372 } else if (LOOK_AHEAD(l,lquote)) {
373 record(quotes, nlpar++);
375 } else if (l == EOF) {
377 warnx("unclosed quote:");
379 warnx("%d unclosed quotes:", nlpar);
380 dump_stack(quotes, nlpar);
392 } else if (sp < 0 && LOOK_AHEAD(t, scommt)) {
393 reallyoutputstr(scommt);
397 if (LOOK_AHEAD(t, ecommt)) {
398 reallyoutputstr(ecommt);
405 } else if (t == '_' || isalpha(t)) {
406 p = inspect(t, token);
408 pushback(l = gpbc());
409 if (p == NULL || (l != LPAREN &&
410 (macro_getdef(p)->type & NEEDARGS) != 0))
414 * real thing.. First build a call frame:
416 pushf(fp); /* previous call frm */
417 pushf(macro_getdef(p)->type); /* type of the call */
419 pushf(0); /* parenthesis level */
420 fp = sp; /* new frame pointer */
422 * now push the string arguments:
424 pushdef(p); /* defn string */
425 pushs1((char *)macro_name(p)); /* macro name */
426 pushs(ep); /* start next..*/
428 if (l != LPAREN && PARLEV == 0) {
432 if (sp == (int)STACKMAX)
433 errx(1, "internal stack overflow");
434 eval((const char **) mstack+fp+1, 2,
435 CALTYP, TRACESTATUS);
437 ep = PREVEP; /* flush strspace */
438 sp = PREVSP; /* previous sp.. */
439 fp = PREVFP; /* rewind stack...*/
442 } else if (t == EOF) {
443 if (!mimic_gnu /* you can puke right there */
444 && sp > -1 && ilevel <= 0) {
445 warnx( "unexpected end of input, unclosed parenthesis:");
446 dump_stack(paren, PARLEV);
450 break; /* all done thanks.. */
451 release_input(infile+ilevel--);
453 bufbase = bbase[ilevel];
455 } else if (sp < 0) { /* not in a macro at all */
456 reallyputchar(t); /* output directly.. */
464 while (isspace(l = gpbc())) /* skip blank, tab, nl.. */
468 record(paren, PARLEV++);
474 else { /* end of argument list */
477 if (sp == (int)STACKMAX)
478 errx(1, "internal stack overflow");
480 eval((const char **) mstack+fp+1, sp-fp,
481 CALTYP, TRACESTATUS);
483 ep = PREVEP; /* flush strspace */
484 sp = PREVSP; /* previous sp.. */
485 fp = PREVFP; /* rewind stack...*/
491 chrsave(EOS); /* new argument */
492 while (isspace(l = gpbc()))
501 if (LOOK_AHEAD(t, scommt)) {
503 for (p = scommt; *p; p++)
507 if (LOOK_AHEAD(t, ecommt)) {
508 for (p = ecommt; *p; p++)
517 CHRSAVE(t); /* stack the char */
524 * output string directly, without pushing it for reparses.
527 outputstr(const char *s)
537 reallyoutputstr(const char *s)
543 infile[ilevel].synch_lineno++;
544 if (infile[ilevel].synch_lineno !=
545 infile[ilevel].lineno)
557 if (synch_lines && c == '\n') {
558 infile[ilevel].synch_lineno++;
559 if (infile[ilevel].synch_lineno != infile[ilevel].lineno)
565 * build an input token..
566 * consider only those starting with _ or A-Za-z.
569 inspect(int c, char *tp)
572 char *etp = tp+MAXTOK;
577 while ((isalnum(c = gpbc()) || c == '_') && tp < etp)
582 /* token is too long, it won't match anything, but it can still
586 while (isalnum(c = gpbc()) || c == '_') {
596 p = ohash_find(¯os, ohash_qlookupi(¯os, name, (const char **)&tp));
599 if (macro_getdef(p) == NULL)
605 * initkwds - initialise m4 keywords as fast as possible.
606 * This very similar to install, but without certain overheads,
607 * such as calling lookup. Malloc is not used for storing the
608 * keyword strings, since we simply use the static pointers
609 * within keywrds block.
617 for (i = 0; i < (int)MAXKEYS; i++) {
618 type = keywrds[i].ktyp & TYPEMASK;
619 if ((keywrds[i].ktyp & NOARGS) == 0)
621 setup_builtin(keywrds[i].knam, type);
626 record(struct position *t, int lev)
628 if (lev < MAXRECORD) {
629 t[lev].name = CURRENT_NAME;
630 t[lev].line = CURRENT_LINE;
635 dump_stack(struct position *t, int lev)
639 for (i = 0; i < lev; i++) {
640 if (i == MAXRECORD) {
641 fprintf(stderr, " ...\n");
644 fprintf(stderr, " %s at line %lu\n",
645 t[i].name, t[i].line);
653 STACKMAX += STACKMAX/2;
654 mstack = xreallocarray(mstack, STACKMAX, sizeof(stae),
655 "Evaluation stack overflow (%lu)",
656 (unsigned long)STACKMAX);
657 sstack = xrealloc(sstack, STACKMAX,
658 "Evaluation stack overflow (%lu)",
659 (unsigned long)STACKMAX);