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 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
37 static char copyright[] =
38 "@(#) Copyright (c) 1989, 1993\n\
39 The Regents of the University of California. All rights reserved.\n";
44 static char sccsid[] = "@(#)main.c 8.1 (Berkeley) 6/6/93";
47 static char rcsid[] = "$OpenBSD: main.c,v 1.53 2002/04/26 16:15:16 espie Exp $";
52 #include <sys/cdefs.h>
53 __FBSDID("$FreeBSD$");
57 * Facility: m4 macro processor
61 #include <sys/types.h>
76 #include "pathnames.h"
78 ndptr hashtab[HASHSIZE]; /* hash table for macros etc. */
79 stae *mstack; /* stack of m4 machine */
80 char *sstack; /* shadow stack, for string space extension */
81 static size_t STACKMAX; /* current maximum size of stack */
82 int sp; /* current m4 stack pointer */
83 int fp; /* m4 call frame pointer */
84 struct input_file infile[MAXINP];/* input file stack (0=stdin) */
85 char *inname[MAXINP]; /* names of these input files */
86 int inlineno[MAXINP]; /* current number in each input file */
87 FILE **outfile; /* diversion array(0=bitbucket)*/
89 FILE *active; /* active output file pointer */
90 int ilevel = 0; /* input file stack pointer */
91 int oindex = 0; /* diversion index.. */
92 char null[] = ""; /* as it says.. just a null.. */
93 const char *m4wraps = ""; /* m4wrap string default.. */
94 char lquote[MAXCCHARS+1] = {LQUOTE}; /* left quote character (`) */
95 char rquote[MAXCCHARS+1] = {RQUOTE}; /* right quote character (') */
96 char scommt[MAXCCHARS+1] = {SCOMMT}; /* start character for comment */
97 char ecommt[MAXCCHARS+1] = {ECOMMT}; /* end character for comment */
98 int synccpp; /* Line synchronisation for C preprocessor */
100 struct keyblk keywrds[] = { /* m4 keywords to be installed */
101 { "include", INCLTYPE },
102 { "sinclude", SINCTYPE },
103 { "define", DEFITYPE },
104 { "defn", DEFNTYPE },
105 { "divert", DIVRTYPE | NOARGS },
106 { "expr", EXPRTYPE },
107 { "eval", EXPRTYPE },
108 { "substr", SUBSTYPE },
109 { "ifelse", IFELTYPE },
110 { "ifdef", IFDFTYPE },
112 { "incr", INCRTYPE },
113 { "decr", DECRTYPE },
114 { "dnl", DNLNTYPE | NOARGS },
115 { "changequote", CHNQTYPE | NOARGS },
116 { "changecom", CHNCTYPE | NOARGS },
117 { "index", INDXTYPE },
119 { "paste", PASTTYPE },
120 { "spaste", SPASTYPE },
121 /* Newer extensions, needed to handle gnu-m4 scripts */
122 { "indir", INDIRTYPE},
123 { "builtin", BUILTINTYPE},
124 { "patsubst", PATSTYPE},
125 { "regexp", REGEXPTYPE},
126 { "esyscmd", ESYSCMDTYPE},
127 { "__file__", FILENAMETYPE | NOARGS},
128 { "__line__", LINETYPE | NOARGS},
130 { "popdef", POPDTYPE },
131 { "pushdef", PUSDTYPE },
132 { "dumpdef", DUMPTYPE | NOARGS },
133 { "shift", SHIFTYPE | NOARGS },
134 { "translit", TRNLTYPE },
135 { "undefine", UNDFTYPE },
136 { "undivert", UNDVTYPE | NOARGS },
137 { "divnum", DIVNTYPE | NOARGS },
138 { "maketemp", MKTMTYPE },
139 { "errprint", ERRPTYPE | NOARGS },
140 { "m4wrap", M4WRTYPE | NOARGS },
141 { "m4exit", EXITTYPE | NOARGS },
142 { "syscmd", SYSCTYPE },
143 { "sysval", SYSVTYPE | NOARGS },
144 { "traceon", TRACEONTYPE | NOARGS },
145 { "traceoff", TRACEOFFTYPE | NOARGS },
147 #if defined(unix) || defined(__unix__)
148 { "unix", SELFTYPE | NOARGS },
151 { "vms", SELFTYPE | NOARGS },
156 #define MAXKEYS (sizeof(keywrds)/sizeof(struct keyblk))
159 static struct position {
162 } quotes[MAXRECORD], paren[MAXRECORD];
164 static void record(struct position *, int);
165 static void dump_stack(struct position *, int);
167 static void macro(void);
168 static void initkwds(void);
169 static ndptr inspect(int, char *);
170 static int do_look_ahead(int, const char *);
172 static void enlarge_stack(void);
175 main(int argc, char *argv[])
182 setlocale(LC_ALL, "");
186 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
187 signal(SIGINT, onintr);
191 STACKMAX = INITSTACKMAX;
193 mstack = (stae *)xalloc(sizeof(stae) * STACKMAX);
194 sstack = (char *)xalloc(STACKMAX);
200 while ((c = getopt(argc, argv, "gst:d:D:U:o:I:")) != -1)
202 case 'D': /* define something..*/
203 for (p = optarg; *p; p++)
207 errx(1, "null variable cannot be defined");
213 addtoincludepath(optarg);
215 case 'U': /* undefine... */
216 remhash(optarg, TOP);
222 set_trace_flags(optarg);
228 mark_traced(optarg, 1);
242 active = stdout; /* default active output */
245 sp = -1; /* stack pointer initialized */
246 fp = 0; /* frame pointer initialized */
247 set_input(infile+0, stdin, "stdin");
248 /* default input (naturally) */
249 if ((inname[0] = strdup("-")) == NULL)
255 for (; argc--; ++argv) {
257 if (p[0] == '-' && p[1] == EOS)
258 set_input(infile, stdin, "stdin");
259 else if (fopen_trypath(infile, p) == NULL) {
266 if ((inname[0] = strdup(p)) == NULL)
271 release_input(infile);
274 if (*m4wraps) { /* anything for rundown ?? */
275 ilevel = 0; /* in case m4wrap includes.. */
276 bufbase = bp = buf; /* use the entire buffer */
277 pbstr(m4wraps); /* user-defined wrapup act */
278 macro(); /* last will and testament */
281 if (active != stdout)
282 active = stdout; /* reset output just in case */
283 for (n = 1; n < maxout; n++) /* default wrap-up: undivert */
284 if (outfile[n] != NULL)
286 /* remove bitbucket if used */
287 if (outfile[0] != NULL) {
288 (void) fclose(outfile[0]);
295 * Look ahead for `token'.
296 * (on input `t == token[0]')
297 * Used for comment and quoting delimiters.
298 * Returns 1 if `token' present; copied to output.
299 * 0 if `token' not found; all characters pushed back
302 do_look_ahead(int t, const char *token)
306 assert((unsigned char)t == (unsigned char)token[0]);
308 for (i = 1; *++token; i++) {
310 if (t == EOF || (unsigned char)t != (unsigned char)*token) {
320 #define LOOK_AHEAD(t, token) (t != EOF && \
321 (unsigned char)(t)==(unsigned char)(token)[0] && \
322 do_look_ahead(t,token))
325 * macro - the work horse..
330 char token[MAXTOK+1];
337 if (t == '_' || isalpha(t)) {
338 p = inspect(t, token);
341 if (p == nil || (l != LPAREN &&
342 (p->type & NEEDARGS) != 0))
346 * real thing.. First build a call frame:
348 pushf(fp); /* previous call frm */
349 pushf(p->type); /* type of the call */
350 pushf(0); /* parenthesis level */
351 fp = sp; /* new frame pointer */
353 * now push the string arguments:
355 pushs1(p->defn); /* defn string */
356 pushs1(p->name); /* macro name */
357 pushs(ep); /* start next..*/
359 if (l != LPAREN && PARLEV == 0) {
363 if ((uintptr_t)sp == STACKMAX)
364 errx(1, "internal stack overflow");
365 eval((const char **) mstack+fp+1, 2,
368 ep = PREVEP; /* flush strspace */
369 sp = PREVSP; /* previous sp.. */
370 fp = PREVFP; /* rewind stack...*/
373 } else if (t == EOF) {
375 warnx( "unexpected end of input, unclosed parenthesis:");
376 dump_stack(paren, PARLEV);
380 break; /* all done thanks.. */
381 release_input(infile+ilevel--);
382 free(inname[ilevel+1]);
383 bufbase = bbase[ilevel];
388 * non-alpha token possibly seen..
389 * [the order of else if .. stmts is important.]
391 else if (LOOK_AHEAD(t,lquote)) { /* strip quotes */
393 record(quotes, nlpar++);
395 * Opening quote: scan forward until matching
396 * closing quote has been found.
401 if (LOOK_AHEAD(l,rquote)) {
404 } else if (LOOK_AHEAD(l,lquote)) {
405 record(quotes, nlpar++);
407 } else if (l == EOF) {
409 warnx("unclosed quote:");
411 warnx("%d unclosed quotes:", nlpar);
412 dump_stack(quotes, nlpar);
426 else if (sp < 0 && LOOK_AHEAD(t, scommt)) {
427 fputs(scommt, active);
431 if (LOOK_AHEAD(t, ecommt)) {
432 fputs(ecommt, active);
441 else if (sp < 0) { /* not in a macro at all */
442 putc(t, active); /* output directly.. */
450 while (isspace(l = gpbc()))
451 ; /* skip blank, tab, nl.. */
453 record(paren, PARLEV++);
459 else { /* end of argument list */
462 if ((uintptr_t)sp == STACKMAX)
463 errx(1, "internal stack overflow");
465 eval((const char **) mstack+fp+1, sp-fp,
468 ep = PREVEP; /* flush strspace */
469 sp = PREVSP; /* previous sp.. */
470 fp = PREVFP; /* rewind stack...*/
476 chrsave(EOS); /* new argument */
477 while (isspace(l = gpbc()))
486 if (LOOK_AHEAD(t, scommt)) {
488 for (pc = scommt; *pc; pc++)
492 if (LOOK_AHEAD(t, ecommt)) {
493 for (pc = ecommt; *pc; pc++)
502 CHRSAVE(t); /* stack the char */
509 * output string directly, without pushing it for reparses.
512 outputstr(const char *s)
523 * build an input token..
524 * consider only those starting with _ or A-Za-z. This is a
525 * combo with lookup to speed things up.
528 inspect(int c, char *tp)
531 char *etp = tp+MAXTOK;
537 while ((isalnum(c = gpbc()) || c == '_') && tp < etp)
538 h = (h << 5) + h + (*tp++ = c);
542 /* token is too long, it won't match anything, but it can still
546 while (isalnum(c = gpbc()) || c == '_') {
556 for (p = hashtab[h % HASHSIZE]; p != nil; p = p->nxtptr)
557 if (h == p->hv && STREQ(name, p->name))
563 * initkwds - initialise m4 keywords as fast as possible.
564 * This very similar to install, but without certain overheads,
565 * such as calling lookup. Malloc is not used for storing the
566 * keyword strings, since we simply use the static pointers
567 * within keywrds block.
576 for (i = 0; i < MAXKEYS; i++) {
577 h = hash(keywrds[i].knam);
578 p = (ndptr) xalloc(sizeof(struct ndblock));
579 p->nxtptr = hashtab[h % HASHSIZE];
580 hashtab[h % HASHSIZE] = p;
581 p->name = xstrdup(keywrds[i].knam);
584 p->type = keywrds[i].ktyp & TYPEMASK;
585 if ((keywrds[i].ktyp & NOARGS) == 0)
590 /* Look up a builtin type, even if overridden by the user */
592 builtin_type(const char *key)
596 for (i = 0; i != MAXKEYS; i++)
597 if (STREQ(keywrds[i].knam, key))
598 return keywrds[i].ktyp;
603 builtin_realname(int n)
607 for (i = 0; i != MAXKEYS; i++)
608 if (((keywrds[i].ktyp ^ n) & TYPEMASK) == 0)
609 return keywrds[i].knam;
614 record(struct position *t, int lev)
616 if (lev < MAXRECORD) {
617 t[lev].name = CURRENT_NAME;
618 t[lev].line = CURRENT_LINE;
623 dump_stack(struct position *t, int lev)
627 for (i = 0; i < lev; i++) {
628 if (i == MAXRECORD) {
629 fprintf(stderr, " ...\n");
632 fprintf(stderr, " %s at line %lu\n",
633 t[i].name, t[i].line);
642 mstack = realloc(mstack, sizeof(stae) * STACKMAX);
643 sstack = realloc(sstack, STACKMAX);
644 if (mstack == NULL || sstack == NULL)
645 errx(1, "Evaluation stack overflow (%lu)",
646 (unsigned long)STACKMAX);
649 /* Emit preprocessor #line directive if -s option used. */
655 fprintf(active, "#line %d \"%s\"\n", inlineno[ilevel],