1 /* $OpenBSD: main.c,v 1.53 2002/04/26 16:15:16 espie Exp $ */
2 /* $NetBSD: main.c,v 1.12 1997/02/08 23:54:49 cgd Exp $ */
5 * Copyright (c) 1989, 1993
6 * The Regents of the University of California. All rights reserved.
8 * This code is derived from software contributed to Berkeley by
9 * Ozan Yigit at York University.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
39 * @(#) Copyright (c) 1989, 1993 The Regents of the University of California. All rights reserved.
40 * @(#)main.c 8.1 (Berkeley) 6/6/93
41 * $OpenBSD: main.c,v 1.53 2002/04/26 16:15:16 espie Exp $
42 * $FreeBSD: src/usr.bin/m4/main.c,v 1.26 2004/08/16 14:18:22 tjr Exp $
43 * $DragonFly: src/usr.bin/m4/main.c,v 1.4 2007/01/01 00:41:58 pavalos Exp $
48 * Facility: m4 macro processor
52 #include <sys/types.h>
67 #include "pathnames.h"
69 ndptr hashtab[HASHSIZE]; /* hash table for macros etc. */
70 stae *mstack; /* stack of m4 machine */
71 char *sstack; /* shadow stack, for string space extension */
72 static size_t STACKMAX; /* current maximum size of stack */
73 int sp; /* current m4 stack pointer */
74 int fp; /* m4 call frame pointer */
75 struct input_file infile[MAXINP];/* input file stack (0=stdin) */
76 char *inname[MAXINP]; /* names of these input files */
77 int inlineno[MAXINP]; /* current number in each input file */
78 FILE **outfile; /* diversion array(0=bitbucket)*/
80 FILE *active; /* active output file pointer */
81 int ilevel = 0; /* input file stack pointer */
82 int oindex = 0; /* diversion index.. */
83 char null[] = ""; /* as it says.. just a null.. */
84 const char *m4wraps = ""; /* m4wrap string default.. */
85 int m4prefix = 0; /* prefix keywords with m4_ */
86 char lquote[MAXCCHARS+1] = {LQUOTE}; /* left quote character (`) */
87 char rquote[MAXCCHARS+1] = {RQUOTE}; /* right quote character (') */
88 char scommt[MAXCCHARS+1] = {SCOMMT}; /* start character for comment */
89 char ecommt[MAXCCHARS+1] = {ECOMMT}; /* end character for comment */
90 int synccpp; /* Line synchronisation for C preprocessor */
92 struct keyblk keywrds[] = { /* m4 keywords to be installed */
93 { "include", INCLTYPE },
94 { "sinclude", SINCTYPE },
95 { "define", DEFITYPE },
97 { "divert", DIVRTYPE | NOARGS },
100 { "substr", SUBSTYPE },
101 { "ifelse", IFELTYPE },
102 { "ifdef", IFDFTYPE },
104 { "incr", INCRTYPE },
105 { "decr", DECRTYPE },
106 { "dnl", DNLNTYPE | NOARGS },
107 { "changequote", CHNQTYPE | NOARGS },
108 { "changecom", CHNCTYPE | NOARGS },
109 { "index", INDXTYPE },
111 { "paste", PASTTYPE },
112 { "spaste", SPASTYPE },
113 /* Newer extensions, needed to handle gnu-m4 scripts */
114 { "indir", INDIRTYPE},
115 { "builtin", BUILTINTYPE},
116 { "patsubst", PATSTYPE},
117 { "regexp", REGEXPTYPE},
118 { "esyscmd", ESYSCMDTYPE},
119 { "__file__", FILENAMETYPE | NOARGS},
120 { "__line__", LINETYPE | NOARGS},
122 { "popdef", POPDTYPE },
123 { "pushdef", PUSDTYPE },
124 { "dumpdef", DUMPTYPE | NOARGS },
125 { "shift", SHIFTYPE | NOARGS },
126 { "translit", TRNLTYPE },
127 { "undefine", UNDFTYPE },
128 { "undivert", UNDVTYPE | NOARGS },
129 { "divnum", DIVNTYPE | NOARGS },
130 { "maketemp", MKTMTYPE },
131 { "errprint", ERRPTYPE | NOARGS },
132 { "m4wrap", M4WRTYPE | NOARGS },
133 { "m4exit", EXITTYPE | NOARGS },
134 { "syscmd", SYSCTYPE },
135 { "sysval", SYSVTYPE | NOARGS },
136 { "traceon", TRACEONTYPE | NOARGS },
137 { "traceoff", TRACEOFFTYPE | NOARGS },
139 #if defined(unix) || defined(__unix__)
140 { "unix", SELFTYPE | NOARGS },
143 { "vms", SELFTYPE | NOARGS },
148 #define MAXKEYS (sizeof(keywrds)/sizeof(struct keyblk))
151 static struct position {
154 } quotes[MAXRECORD], paren[MAXRECORD];
156 static void record(struct position *, int);
157 static void dump_stack(struct position *, int);
159 static void macro(void);
160 static void initkwds(void);
161 static ndptr inspect(int, char *);
162 static int do_look_ahead(int, const char *);
164 static void enlarge_stack(void);
167 main(int argc, char *argv[])
172 const char *optstr = "D:I:PU:gd:o:st:";
175 setlocale(LC_ALL, "");
179 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
180 signal(SIGINT, onintr);
183 * We need to know if -P is there before checking -D and -U.
185 while ((c = getopt(argc, argv, optstr)) != -1)
188 optind = optreset = 1;
192 STACKMAX = INITSTACKMAX;
194 mstack = (stae *)xalloc(sizeof(stae) * STACKMAX);
195 sstack = (char *)xalloc(STACKMAX);
201 while ((c = getopt(argc, argv, optstr)) != -1)
203 case 'D': /* define something..*/
204 for (p = optarg; *p; p++)
208 errx(1, "null variable cannot be defined");
214 addtoincludepath(optarg);
218 case 'U': /* undefine... */
219 remhash(optarg, TOP);
225 set_trace_flags(optarg);
231 mark_traced(optarg, 1);
245 active = stdout; /* default active output */
248 sp = -1; /* stack pointer initialized */
249 fp = 0; /* frame pointer initialized */
250 set_input(infile+0, stdin, "stdin");
251 /* default input (naturally) */
252 if ((inname[0] = strdup("-")) == NULL)
258 for (; argc--; ++argv) {
260 if (p[0] == '-' && p[1] == EOS)
261 set_input(infile, stdin, "stdin");
262 else if (fopen_trypath(infile, p) == NULL) {
269 if ((inname[0] = strdup(p)) == NULL)
274 release_input(infile);
277 if (*m4wraps) { /* anything for rundown ?? */
278 ilevel = 0; /* in case m4wrap includes.. */
279 bufbase = bp = buf; /* use the entire buffer */
280 pbstr(m4wraps); /* user-defined wrapup act */
281 macro(); /* last will and testament */
284 if (active != stdout)
285 active = stdout; /* reset output just in case */
286 for (n = 1; n < maxout; n++) /* default wrap-up: undivert */
287 if (outfile[n] != NULL)
289 /* remove bitbucket if used */
290 if (outfile[0] != NULL) {
291 (void) fclose(outfile[0]);
298 * Look ahead for `token'.
299 * (on input `t == token[0]')
300 * Used for comment and quoting delimiters.
301 * Returns 1 if `token' present; copied to output.
302 * 0 if `token' not found; all characters pushed back
305 do_look_ahead(int t, const char *token)
309 assert((unsigned char)t == (unsigned char)token[0]);
311 for (i = 1; *++token; i++) {
313 if (t == EOF || (unsigned char)t != (unsigned char)*token) {
323 #define LOOK_AHEAD(t, token) (t != EOF && \
324 (unsigned char)(t)==(unsigned char)(token)[0] && \
325 do_look_ahead(t,token))
328 * macro - the work horse..
333 char token[MAXTOK+1];
340 if (t == '_' || isalpha(t)) {
341 p = inspect(t, token);
344 if (p == nil || (l != LPAREN &&
345 (p->type & NEEDARGS) != 0))
349 * real thing.. First build a call frame:
351 pushf(fp); /* previous call frm */
352 pushf(p->type); /* type of the call */
353 pushf(0); /* parenthesis level */
354 fp = sp; /* new frame pointer */
356 * now push the string arguments:
358 pushs1(p->defn); /* defn string */
359 pushs1(p->name); /* macro name */
360 pushs(ep); /* start next..*/
362 if (l != LPAREN && PARLEV == 0) {
366 if ((uintptr_t)sp == STACKMAX)
367 errx(1, "internal stack overflow");
368 eval((const char **) mstack+fp+1, 2,
371 ep = PREVEP; /* flush strspace */
372 sp = PREVSP; /* previous sp.. */
373 fp = PREVFP; /* rewind stack...*/
376 } else if (t == EOF) {
378 warnx( "unexpected end of input, unclosed parenthesis:");
379 dump_stack(paren, PARLEV);
383 break; /* all done thanks.. */
384 release_input(infile+ilevel--);
385 free(inname[ilevel+1]);
386 bufbase = bbase[ilevel];
391 * non-alpha token possibly seen..
392 * [the order of else if .. stmts is important.]
394 else if (LOOK_AHEAD(t,lquote)) { /* strip quotes */
396 record(quotes, nlpar++);
398 * Opening quote: scan forward until matching
399 * closing quote has been found.
404 if (LOOK_AHEAD(l,rquote)) {
407 } else if (LOOK_AHEAD(l,lquote)) {
408 record(quotes, nlpar++);
410 } else if (l == EOF) {
412 warnx("unclosed quote:");
414 warnx("%d unclosed quotes:", nlpar);
415 dump_stack(quotes, nlpar);
429 else if (sp < 0 && LOOK_AHEAD(t, scommt)) {
430 fputs(scommt, active);
434 if (LOOK_AHEAD(t, ecommt)) {
435 fputs(ecommt, active);
444 else if (sp < 0) { /* not in a macro at all */
445 putc(t, active); /* output directly.. */
453 while (isspace(l = gpbc()))
454 ; /* skip blank, tab, nl.. */
456 record(paren, PARLEV++);
462 else { /* end of argument list */
465 if ((uintptr_t)sp == STACKMAX)
466 errx(1, "internal stack overflow");
468 eval((const char **) mstack+fp+1, sp-fp,
471 ep = PREVEP; /* flush strspace */
472 sp = PREVSP; /* previous sp.. */
473 fp = PREVFP; /* rewind stack...*/
479 chrsave(EOS); /* new argument */
480 while (isspace(l = gpbc()))
489 if (LOOK_AHEAD(t, scommt)) {
491 for (pc = scommt; *pc; pc++)
495 if (LOOK_AHEAD(t, ecommt)) {
496 for (pc = ecommt; *pc; pc++)
505 CHRSAVE(t); /* stack the char */
512 * output string directly, without pushing it for reparses.
515 outputstr(const char *s)
526 * build an input token..
527 * consider only those starting with _ or A-Za-z. This is a
528 * combo with lookup to speed things up.
531 inspect(int c, char *tp)
534 char *etp = tp+MAXTOK;
540 while ((isalnum(c = gpbc()) || c == '_') && tp < etp)
541 h = (h << 5) + h + (*tp++ = c);
545 /* token is too long, it won't match anything, but it can still
549 while (isalnum(c = gpbc()) || c == '_') {
559 for (p = hashtab[h % HASHSIZE]; p != nil; p = p->nxtptr)
560 if (h == p->hv && STREQ(name, p->name))
566 * initkwds - initialise m4 keywords as fast as possible.
567 * This very similar to install, but without certain overheads,
568 * such as calling lookup. Malloc is not used for storing the
569 * keyword strings, since we simply use the static pointers
570 * within keywrds block.
580 for (i = 0; i < MAXKEYS; i++) {
581 k = __DECONST(char *, keywrds[i].knam);
583 if (asprintf(&k, "m4_%s", k) == -1)
588 p = (ndptr) xalloc(sizeof(struct ndblock));
589 p->nxtptr = hashtab[h % HASHSIZE];
590 hashtab[h % HASHSIZE] = p;
591 p->name = xstrdup(keywrds[i].knam);
594 p->type = keywrds[i].ktyp & TYPEMASK;
595 if ((keywrds[i].ktyp & NOARGS) == 0)
600 /* Look up a builtin type, even if overridden by the user */
602 builtin_type(const char *key)
606 for (i = 0; i != MAXKEYS; i++)
607 if (STREQ(keywrds[i].knam, key))
608 return keywrds[i].ktyp;
613 builtin_realname(int n)
617 for (i = 0; i != MAXKEYS; i++)
618 if (((keywrds[i].ktyp ^ n) & TYPEMASK) == 0)
619 return keywrds[i].knam;
624 record(struct position *t, int lev)
626 if (lev < MAXRECORD) {
627 t[lev].name = CURRENT_NAME;
628 t[lev].line = CURRENT_LINE;
633 dump_stack(struct position *t, int lev)
637 for (i = 0; i < lev; i++) {
638 if (i == MAXRECORD) {
639 fprintf(stderr, " ...\n");
642 fprintf(stderr, " %s at line %lu\n",
643 t[i].name, t[i].line);
652 mstack = realloc(mstack, sizeof(stae) * STACKMAX);
653 sstack = realloc(sstack, STACKMAX);
654 if (mstack == NULL || sstack == NULL)
655 errx(1, "Evaluation stack overflow (%lu)",
656 (unsigned long)STACKMAX);
659 /* Emit preprocessor #line directive if -s option used. */
665 fprintf(active, "#line %d \"%s\"\n", inlineno[ilevel],