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
41 static char copyright[] =
42 "@(#) Copyright (c) 1989, 1993\n\
43 The Regents of the University of California. All rights reserved.\n";
48 static char sccsid[] = "@(#)main.c 8.1 (Berkeley) 6/6/93";
51 static char rcsid[] = "$OpenBSD: main.c,v 1.53 2002/04/26 16:15:16 espie Exp $";
56 #include <sys/cdefs.h>
57 __FBSDID("$FreeBSD$");
61 * Facility: m4 macro processor
65 #include <sys/types.h>
80 #include "pathnames.h"
82 ndptr hashtab[HASHSIZE]; /* hash table for macros etc. */
83 stae *mstack; /* stack of m4 machine */
84 char *sstack; /* shadow stack, for string space extension */
85 static size_t STACKMAX; /* current maximum size of stack */
86 int sp; /* current m4 stack pointer */
87 int fp; /* m4 call frame pointer */
88 struct input_file infile[MAXINP];/* input file stack (0=stdin) */
89 char *inname[MAXINP]; /* names of these input files */
90 int inlineno[MAXINP]; /* current number in each input file */
91 FILE **outfile; /* diversion array(0=bitbucket)*/
93 FILE *active; /* active output file pointer */
94 int ilevel = 0; /* input file stack pointer */
95 int oindex = 0; /* diversion index.. */
96 char null[] = ""; /* as it says.. just a null.. */
97 const char *m4wraps = ""; /* m4wrap string default.. */
98 char lquote[MAXCCHARS+1] = {LQUOTE}; /* left quote character (`) */
99 char rquote[MAXCCHARS+1] = {RQUOTE}; /* right quote character (') */
100 char scommt[MAXCCHARS+1] = {SCOMMT}; /* start character for comment */
101 char ecommt[MAXCCHARS+1] = {ECOMMT}; /* end character for comment */
102 int synccpp; /* Line synchronisation for C preprocessor */
104 struct keyblk keywrds[] = { /* m4 keywords to be installed */
105 { "include", INCLTYPE },
106 { "sinclude", SINCTYPE },
107 { "define", DEFITYPE },
108 { "defn", DEFNTYPE },
109 { "divert", DIVRTYPE | NOARGS },
110 { "expr", EXPRTYPE },
111 { "eval", EXPRTYPE },
112 { "substr", SUBSTYPE },
113 { "ifelse", IFELTYPE },
114 { "ifdef", IFDFTYPE },
116 { "incr", INCRTYPE },
117 { "decr", DECRTYPE },
118 { "dnl", DNLNTYPE | NOARGS },
119 { "changequote", CHNQTYPE | NOARGS },
120 { "changecom", CHNCTYPE | NOARGS },
121 { "index", INDXTYPE },
123 { "paste", PASTTYPE },
124 { "spaste", SPASTYPE },
125 /* Newer extensions, needed to handle gnu-m4 scripts */
126 { "indir", INDIRTYPE},
127 { "builtin", BUILTINTYPE},
128 { "patsubst", PATSTYPE},
129 { "regexp", REGEXPTYPE},
130 { "esyscmd", ESYSCMDTYPE},
131 { "__file__", FILENAMETYPE | NOARGS},
132 { "__line__", LINETYPE | NOARGS},
134 { "popdef", POPDTYPE },
135 { "pushdef", PUSDTYPE },
136 { "dumpdef", DUMPTYPE | NOARGS },
137 { "shift", SHIFTYPE | NOARGS },
138 { "translit", TRNLTYPE },
139 { "undefine", UNDFTYPE },
140 { "undivert", UNDVTYPE | NOARGS },
141 { "divnum", DIVNTYPE | NOARGS },
142 { "maketemp", MKTMTYPE },
143 { "errprint", ERRPTYPE | NOARGS },
144 { "m4wrap", M4WRTYPE | NOARGS },
145 { "m4exit", EXITTYPE | NOARGS },
146 { "syscmd", SYSCTYPE },
147 { "sysval", SYSVTYPE | NOARGS },
148 { "traceon", TRACEONTYPE | NOARGS },
149 { "traceoff", TRACEOFFTYPE | NOARGS },
151 #if defined(unix) || defined(__unix__)
152 { "unix", SELFTYPE | NOARGS },
155 { "vms", SELFTYPE | NOARGS },
160 #define MAXKEYS (sizeof(keywrds)/sizeof(struct keyblk))
163 static struct position {
166 } quotes[MAXRECORD], paren[MAXRECORD];
168 static void record(struct position *, int);
169 static void dump_stack(struct position *, int);
171 static void macro(void);
172 static void initkwds(void);
173 static ndptr inspect(int, char *);
174 static int do_look_ahead(int, const char *);
176 static void enlarge_stack(void);
179 main(int argc, char *argv[])
186 setlocale(LC_ALL, "");
190 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
191 signal(SIGINT, onintr);
195 STACKMAX = INITSTACKMAX;
197 mstack = (stae *)xalloc(sizeof(stae) * STACKMAX);
198 sstack = (char *)xalloc(STACKMAX);
204 while ((c = getopt(argc, argv, "gst:d:D:U:o:I:")) != -1)
206 case 'D': /* define something..*/
207 for (p = optarg; *p; p++)
211 errx(1, "null variable cannot be defined");
217 addtoincludepath(optarg);
219 case 'U': /* undefine... */
220 remhash(optarg, TOP);
226 set_trace_flags(optarg);
232 mark_traced(optarg, 1);
246 active = stdout; /* default active output */
249 sp = -1; /* stack pointer initialized */
250 fp = 0; /* frame pointer initialized */
251 set_input(infile+0, stdin, "stdin");
252 /* default input (naturally) */
253 if ((inname[0] = strdup("-")) == NULL)
259 for (; argc--; ++argv) {
261 if (p[0] == '-' && p[1] == EOS)
262 set_input(infile, stdin, "stdin");
263 else if (fopen_trypath(infile, p) == NULL) {
270 if ((inname[0] = strdup(p)) == NULL)
275 release_input(infile);
278 if (*m4wraps) { /* anything for rundown ?? */
279 ilevel = 0; /* in case m4wrap includes.. */
280 bufbase = bp = buf; /* use the entire buffer */
281 pbstr(m4wraps); /* user-defined wrapup act */
282 macro(); /* last will and testament */
285 if (active != stdout)
286 active = stdout; /* reset output just in case */
287 for (n = 1; n < maxout; n++) /* default wrap-up: undivert */
288 if (outfile[n] != NULL)
290 /* remove bitbucket if used */
291 if (outfile[0] != NULL) {
292 (void) fclose(outfile[0]);
299 * Look ahead for `token'.
300 * (on input `t == token[0]')
301 * Used for comment and quoting delimiters.
302 * Returns 1 if `token' present; copied to output.
303 * 0 if `token' not found; all characters pushed back
306 do_look_ahead(int t, const char *token)
310 assert((unsigned char)t == (unsigned char)token[0]);
312 for (i = 1; *++token; i++) {
314 if (t == EOF || (unsigned char)t != (unsigned char)*token) {
324 #define LOOK_AHEAD(t, token) (t != EOF && \
325 (unsigned char)(t)==(unsigned char)(token)[0] && \
326 do_look_ahead(t,token))
329 * macro - the work horse..
334 char token[MAXTOK+1];
341 if (t == '_' || isalpha(t)) {
342 p = inspect(t, token);
345 if (p == nil || (l != LPAREN &&
346 (p->type & NEEDARGS) != 0))
350 * real thing.. First build a call frame:
352 pushf(fp); /* previous call frm */
353 pushf(p->type); /* type of the call */
354 pushf(0); /* parenthesis level */
355 fp = sp; /* new frame pointer */
357 * now push the string arguments:
359 pushs1(p->defn); /* defn string */
360 pushs1(p->name); /* macro name */
361 pushs(ep); /* start next..*/
363 if (l != LPAREN && PARLEV == 0) {
367 if ((uintptr_t)sp == STACKMAX)
368 errx(1, "internal stack overflow");
369 eval((const char **) mstack+fp+1, 2,
372 ep = PREVEP; /* flush strspace */
373 sp = PREVSP; /* previous sp.. */
374 fp = PREVFP; /* rewind stack...*/
377 } else if (t == EOF) {
379 warnx( "unexpected end of input, unclosed parenthesis:");
380 dump_stack(paren, PARLEV);
384 break; /* all done thanks.. */
385 release_input(infile+ilevel--);
386 free(inname[ilevel+1]);
387 bufbase = bbase[ilevel];
392 * non-alpha token possibly seen..
393 * [the order of else if .. stmts is important.]
395 else if (LOOK_AHEAD(t,lquote)) { /* strip quotes */
397 record(quotes, nlpar++);
399 * Opening quote: scan forward until matching
400 * closing quote has been found.
405 if (LOOK_AHEAD(l,rquote)) {
408 } else if (LOOK_AHEAD(l,lquote)) {
409 record(quotes, nlpar++);
411 } else if (l == EOF) {
413 warnx("unclosed quote:");
415 warnx("%d unclosed quotes:", nlpar);
416 dump_stack(quotes, nlpar);
430 else if (sp < 0 && LOOK_AHEAD(t, scommt)) {
431 fputs(scommt, active);
435 if (LOOK_AHEAD(t, ecommt)) {
436 fputs(ecommt, active);
445 else if (sp < 0) { /* not in a macro at all */
446 putc(t, active); /* output directly.. */
454 while (isspace(l = gpbc()))
455 ; /* skip blank, tab, nl.. */
457 record(paren, PARLEV++);
463 else { /* end of argument list */
466 if ((uintptr_t)sp == STACKMAX)
467 errx(1, "internal stack overflow");
469 eval((const char **) mstack+fp+1, sp-fp,
472 ep = PREVEP; /* flush strspace */
473 sp = PREVSP; /* previous sp.. */
474 fp = PREVFP; /* rewind stack...*/
480 chrsave(EOS); /* new argument */
481 while (isspace(l = gpbc()))
490 if (LOOK_AHEAD(t, scommt)) {
492 for (pc = scommt; *pc; pc++)
496 if (LOOK_AHEAD(t, ecommt)) {
497 for (pc = ecommt; *pc; pc++)
506 CHRSAVE(t); /* stack the char */
513 * output string directly, without pushing it for reparses.
516 outputstr(const char *s)
527 * build an input token..
528 * consider only those starting with _ or A-Za-z. This is a
529 * combo with lookup to speed things up.
532 inspect(int c, char *tp)
535 char *etp = tp+MAXTOK;
541 while ((isalnum(c = gpbc()) || c == '_') && tp < etp)
542 h = (h << 5) + h + (*tp++ = c);
546 /* token is too long, it won't match anything, but it can still
550 while (isalnum(c = gpbc()) || c == '_') {
560 for (p = hashtab[h % HASHSIZE]; p != nil; p = p->nxtptr)
561 if (h == p->hv && STREQ(name, p->name))
567 * initkwds - initialise m4 keywords as fast as possible.
568 * This very similar to install, but without certain overheads,
569 * such as calling lookup. Malloc is not used for storing the
570 * keyword strings, since we simply use the static pointers
571 * within keywrds block.
580 for (i = 0; i < MAXKEYS; i++) {
581 h = hash(keywrds[i].knam);
582 p = (ndptr) xalloc(sizeof(struct ndblock));
583 p->nxtptr = hashtab[h % HASHSIZE];
584 hashtab[h % HASHSIZE] = p;
585 p->name = xstrdup(keywrds[i].knam);
588 p->type = keywrds[i].ktyp & TYPEMASK;
589 if ((keywrds[i].ktyp & NOARGS) == 0)
594 /* Look up a builtin type, even if overridden by the user */
596 builtin_type(const char *key)
600 for (i = 0; i != MAXKEYS; i++)
601 if (STREQ(keywrds[i].knam, key))
602 return keywrds[i].ktyp;
607 builtin_realname(int n)
611 for (i = 0; i != MAXKEYS; i++)
612 if (((keywrds[i].ktyp ^ n) & TYPEMASK) == 0)
613 return keywrds[i].knam;
618 record(struct position *t, int lev)
620 if (lev < MAXRECORD) {
621 t[lev].name = CURRENT_NAME;
622 t[lev].line = CURRENT_LINE;
627 dump_stack(struct position *t, int lev)
631 for (i = 0; i < lev; i++) {
632 if (i == MAXRECORD) {
633 fprintf(stderr, " ...\n");
636 fprintf(stderr, " %s at line %lu\n",
637 t[i].name, t[i].line);
646 mstack = realloc(mstack, sizeof(stae) * STACKMAX);
647 sstack = realloc(sstack, STACKMAX);
648 if (mstack == NULL || sstack == NULL)
649 errx(1, "Evaluation stack overflow (%lu)",
650 (unsigned long)STACKMAX);
653 /* Emit preprocessor #line directive if -s option used. */
659 fprintf(active, "#line %d \"%s\"\n", inlineno[ilevel],