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.6.2.6 2002/07/15 02:06:15 jmallett Exp $
43 * $DragonFly: src/usr.bin/m4/main.c,v 1.2 2003/06/17 04:29:28 dillon Exp $
48 * Facility: m4 macro processor
52 #include <sys/types.h>
66 #include "pathnames.h"
68 ndptr hashtab[HASHSIZE]; /* hash table for macros etc. */
69 stae *mstack; /* stack of m4 machine */
70 char *sstack; /* shadow stack, for string space extension */
71 static size_t STACKMAX; /* current maximum size of stack */
72 int sp; /* current m4 stack pointer */
73 int fp; /* m4 call frame pointer */
74 struct input_file infile[MAXINP];/* input file stack (0=stdin) */
75 char *inname[MAXINP]; /* names of these input files */
76 int inlineno[MAXINP]; /* current number in each input file */
77 FILE **outfile; /* diversion array(0=bitbucket)*/
79 FILE *active; /* active output file pointer */
80 int ilevel = 0; /* input file stack pointer */
81 int oindex = 0; /* diversion index.. */
82 const char *null = ""; /* as it says.. just a null.. */
83 const char *m4wraps = ""; /* m4wrap string default.. */
84 char lquote[MAXCCHARS+1] = {LQUOTE}; /* left quote character (`) */
85 char rquote[MAXCCHARS+1] = {RQUOTE}; /* right quote character (') */
86 char scommt[MAXCCHARS+1] = {SCOMMT}; /* start character for comment */
87 char ecommt[MAXCCHARS+1] = {ECOMMT}; /* end character for comment */
88 int synccpp; /* Line synchronisation for C preprocessor */
90 struct keyblk keywrds[] = { /* m4 keywords to be installed */
91 { "include", INCLTYPE },
92 { "sinclude", SINCTYPE },
93 { "define", DEFITYPE },
95 { "divert", DIVRTYPE | NOARGS },
98 { "substr", SUBSTYPE },
99 { "ifelse", IFELTYPE },
100 { "ifdef", IFDFTYPE },
102 { "incr", INCRTYPE },
103 { "decr", DECRTYPE },
104 { "dnl", DNLNTYPE | NOARGS },
105 { "changequote", CHNQTYPE | NOARGS },
106 { "changecom", CHNCTYPE | NOARGS },
107 { "index", INDXTYPE },
109 { "paste", PASTTYPE },
110 { "spaste", SPASTYPE },
111 /* Newer extensions, needed to handle gnu-m4 scripts */
112 { "indir", INDIRTYPE},
113 { "builtin", BUILTINTYPE},
114 { "patsubst", PATSTYPE},
115 { "regexp", REGEXPTYPE},
116 { "esyscmd", ESYSCMDTYPE},
117 { "__file__", FILENAMETYPE | NOARGS},
118 { "__line__", LINETYPE | NOARGS},
120 { "popdef", POPDTYPE },
121 { "pushdef", PUSDTYPE },
122 { "dumpdef", DUMPTYPE | NOARGS },
123 { "shift", SHIFTYPE | NOARGS },
124 { "translit", TRNLTYPE },
125 { "undefine", UNDFTYPE },
126 { "undivert", UNDVTYPE | NOARGS },
127 { "divnum", DIVNTYPE | NOARGS },
128 { "maketemp", MKTMTYPE },
129 { "errprint", ERRPTYPE | NOARGS },
130 { "m4wrap", M4WRTYPE | NOARGS },
131 { "m4exit", EXITTYPE | NOARGS },
132 { "syscmd", SYSCTYPE },
133 { "sysval", SYSVTYPE | NOARGS },
134 { "traceon", TRACEONTYPE | NOARGS },
135 { "traceoff", TRACEOFFTYPE | NOARGS },
137 #if defined(unix) || defined(__unix__)
138 { "unix", SELFTYPE | NOARGS },
141 { "vms", SELFTYPE | NOARGS },
146 #define MAXKEYS (sizeof(keywrds)/sizeof(struct keyblk))
149 static struct position {
152 } quotes[MAXRECORD], paren[MAXRECORD];
154 static void record(struct position *, int);
155 static void dump_stack(struct position *, int);
157 static void macro(void);
158 static void initkwds(void);
159 static ndptr inspect(int, char *);
160 static int do_look_ahead(int, const char *);
162 static void enlarge_stack(void);
165 main(int argc, char *argv[])
174 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
175 signal(SIGINT, onintr);
179 STACKMAX = INITSTACKMAX;
181 mstack = (stae *)xalloc(sizeof(stae) * STACKMAX);
182 sstack = (char *)xalloc(STACKMAX);
188 while ((c = getopt(argc, argv, "gst:d:D:U:o:I:")) != -1)
190 case 'D': /* define something..*/
191 for (p = optarg; *p; p++)
199 addtoincludepath(optarg);
201 case 'U': /* undefine... */
202 remhash(optarg, TOP);
208 set_trace_flags(optarg);
214 mark_traced(optarg, 1);
228 active = stdout; /* default active output */
231 sp = -1; /* stack pointer initialized */
232 fp = 0; /* frame pointer initialized */
233 set_input(infile+0, stdin, "stdin");
234 /* default input (naturally) */
235 if ((inname[0] = strdup("-")) == NULL)
241 for (; argc--; ++argv) {
243 if (p[0] == '-' && p[1] == EOS)
244 set_input(infile, stdin, "stdin");
245 else if (fopen_trypath(infile, p) == NULL) {
252 if ((inname[0] = strdup(p)) == NULL)
257 release_input(infile);
260 if (*m4wraps) { /* anything for rundown ?? */
261 ilevel = 0; /* in case m4wrap includes.. */
262 bufbase = bp = buf; /* use the entire buffer */
263 pbstr(m4wraps); /* user-defined wrapup act */
264 macro(); /* last will and testament */
267 if (active != stdout)
268 active = stdout; /* reset output just in case */
269 for (n = 1; n < maxout; n++) /* default wrap-up: undivert */
270 if (outfile[n] != NULL)
272 /* remove bitbucket if used */
273 if (outfile[0] != NULL) {
274 (void) fclose(outfile[0]);
281 * Look ahead for `token'.
282 * (on input `t == token[0]')
283 * Used for comment and quoting delimiters.
284 * Returns 1 if `token' present; copied to output.
285 * 0 if `token' not found; all characters pushed back
288 do_look_ahead(int t, const char *token)
292 assert((unsigned char)t == (unsigned char)token[0]);
294 for (i = 1; *++token; i++) {
296 if (t == EOF || (unsigned char)t != (unsigned char)*token) {
306 #define LOOK_AHEAD(t, token) (t != EOF && \
307 (unsigned char)(t)==(unsigned char)(token)[0] && \
308 do_look_ahead(t,token))
311 * macro - the work horse..
316 char token[MAXTOK+1];
323 if (t == '_' || isalpha(t)) {
324 p = inspect(t, token);
327 if (p == nil || (l != LPAREN &&
328 (p->type & NEEDARGS) != 0))
332 * real thing.. First build a call frame:
334 pushf(fp); /* previous call frm */
335 pushf(p->type); /* type of the call */
336 pushf(0); /* parenthesis level */
337 fp = sp; /* new frame pointer */
339 * now push the string arguments:
341 pushs1(p->defn); /* defn string */
342 pushs1(p->name); /* macro name */
343 pushs(ep); /* start next..*/
345 if (l != LPAREN && PARLEV == 0) {
349 if ((uintptr_t)sp == STACKMAX)
350 errx(1, "internal stack overflow");
351 eval((const char **) mstack+fp+1, 2,
354 ep = PREVEP; /* flush strspace */
355 sp = PREVSP; /* previous sp.. */
356 fp = PREVFP; /* rewind stack...*/
359 } else if (t == EOF) {
361 warnx( "unexpected end of input, unclosed parenthesis:");
362 dump_stack(paren, PARLEV);
366 break; /* all done thanks.. */
367 release_input(infile+ilevel--);
368 free(inname[ilevel+1]);
369 bufbase = bbase[ilevel];
374 * non-alpha token possibly seen..
375 * [the order of else if .. stmts is important.]
377 else if (LOOK_AHEAD(t,lquote)) { /* strip quotes */
379 record(quotes, nlpar++);
381 * Opening quote: scan forward until matching
382 * closing quote has been found.
387 if (LOOK_AHEAD(l,rquote)) {
390 } else if (LOOK_AHEAD(l,lquote)) {
391 record(quotes, nlpar++);
393 } else if (l == EOF) {
395 warnx("unclosed quote:");
397 warnx("%d unclosed quotes:", nlpar);
398 dump_stack(quotes, nlpar);
412 else if (sp < 0 && LOOK_AHEAD(t, scommt)) {
413 fputs(scommt, active);
417 if (LOOK_AHEAD(t, ecommt)) {
418 fputs(ecommt, active);
427 else if (sp < 0) { /* not in a macro at all */
428 putc(t, active); /* output directly.. */
436 while (isspace(l = gpbc()))
437 ; /* skip blank, tab, nl.. */
439 record(paren, PARLEV++);
445 else { /* end of argument list */
448 if ((uintptr_t)sp == STACKMAX)
449 errx(1, "internal stack overflow");
451 eval((const char **) mstack+fp+1, sp-fp,
454 ep = PREVEP; /* flush strspace */
455 sp = PREVSP; /* previous sp.. */
456 fp = PREVFP; /* rewind stack...*/
462 chrsave(EOS); /* new argument */
463 while (isspace(l = gpbc()))
472 if (LOOK_AHEAD(t, scommt)) {
474 for (pc = scommt; *pc; pc++)
478 if (LOOK_AHEAD(t, ecommt)) {
479 for (pc = ecommt; *pc; pc++)
488 CHRSAVE(t); /* stack the char */
495 * output string directly, without pushing it for reparses.
498 outputstr(const char *s)
509 * build an input token..
510 * consider only those starting with _ or A-Za-z. This is a
511 * combo with lookup to speed things up.
514 inspect(int c, char *tp)
517 char *etp = tp+MAXTOK;
523 while ((isalnum(c = gpbc()) || c == '_') && tp < etp)
524 h = (h << 5) + h + (*tp++ = c);
528 /* token is too long, it won't match anything, but it can still
532 while (isalnum(c = gpbc()) || c == '_') {
542 for (p = hashtab[h % HASHSIZE]; p != nil; p = p->nxtptr)
543 if (h == p->hv && STREQ(name, p->name))
549 * initkwds - initialise m4 keywords as fast as possible.
550 * This very similar to install, but without certain overheads,
551 * such as calling lookup. Malloc is not used for storing the
552 * keyword strings, since we simply use the static pointers
553 * within keywrds block.
562 for (i = 0; i < MAXKEYS; i++) {
563 h = hash(keywrds[i].knam);
564 p = (ndptr) xalloc(sizeof(struct ndblock));
565 p->nxtptr = hashtab[h % HASHSIZE];
566 hashtab[h % HASHSIZE] = p;
567 p->name = xstrdup(keywrds[i].knam);
568 p->defn = xstrdup(null);
570 p->type = keywrds[i].ktyp & TYPEMASK;
571 if ((keywrds[i].ktyp & NOARGS) == 0)
576 /* Look up a builtin type, even if overridden by the user */
578 builtin_type(const char *key)
582 for (i = 0; i != MAXKEYS; i++)
583 if (STREQ(keywrds[i].knam, key))
584 return keywrds[i].ktyp;
589 builtin_realname(int n)
593 for (i = 0; i != MAXKEYS; i++)
594 if (((keywrds[i].ktyp ^ n) & TYPEMASK) == 0)
595 return keywrds[i].knam;
600 record(struct position *t, int lev)
602 if (lev < MAXRECORD) {
603 t[lev].name = CURRENT_NAME;
604 t[lev].line = CURRENT_LINE;
609 dump_stack(struct position *t, int lev)
613 for (i = 0; i < lev; i++) {
614 if (i == MAXRECORD) {
615 fprintf(stderr, " ...\n");
618 fprintf(stderr, " %s at line %lu\n",
619 t[i].name, t[i].line);
628 mstack = realloc(mstack, sizeof(stae) * STACKMAX);
629 sstack = realloc(sstack, STACKMAX);
630 if (mstack == NULL || sstack == NULL)
631 errx(1, "Evaluation stack overflow (%lu)",
632 (unsigned long)STACKMAX);
635 /* Emit preprocessor #line directive if -s option used. */
641 fprintf(active, "#line %d \"%s\"\n", inlineno[ilevel],