Sync with FreeBSD. Notable changes:
[dragonfly/port-amd64.git] / usr.bin / m4 / main.c
blob6689264380c59d284c4b3cafadaa4a4f7841a453
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 $ */
4 /*-
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
13 * are met:
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
37 * SUCH DAMAGE.
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.3 2006/12/27 21:29:02 pavalos Exp $
47 * main.c
48 * Facility: m4 macro processor
49 * by: oz
52 #include <sys/types.h>
53 #include <assert.h>
54 #include <signal.h>
55 #include <errno.h>
56 #include <unistd.h>
57 #include <stdio.h>
58 #include <ctype.h>
59 #include <string.h>
60 #include <stddef.h>
61 #include <stdlib.h>
62 #include <err.h>
63 #include <locale.h>
64 #include "mdef.h"
65 #include "stdd.h"
66 #include "extern.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)*/
79 int maxout;
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 char lquote[MAXCCHARS+1] = {LQUOTE}; /* left quote character (`) */
86 char rquote[MAXCCHARS+1] = {RQUOTE}; /* right quote character (') */
87 char scommt[MAXCCHARS+1] = {SCOMMT}; /* start character for comment */
88 char ecommt[MAXCCHARS+1] = {ECOMMT}; /* end character for comment */
89 int synccpp; /* Line synchronisation for C preprocessor */
91 struct keyblk keywrds[] = { /* m4 keywords to be installed */
92 { "include", INCLTYPE },
93 { "sinclude", SINCTYPE },
94 { "define", DEFITYPE },
95 { "defn", DEFNTYPE },
96 { "divert", DIVRTYPE | NOARGS },
97 { "expr", EXPRTYPE },
98 { "eval", EXPRTYPE },
99 { "substr", SUBSTYPE },
100 { "ifelse", IFELTYPE },
101 { "ifdef", IFDFTYPE },
102 { "len", LENGTYPE },
103 { "incr", INCRTYPE },
104 { "decr", DECRTYPE },
105 { "dnl", DNLNTYPE | NOARGS },
106 { "changequote", CHNQTYPE | NOARGS },
107 { "changecom", CHNCTYPE | NOARGS },
108 { "index", INDXTYPE },
109 #ifdef EXTENDED
110 { "paste", PASTTYPE },
111 { "spaste", SPASTYPE },
112 /* Newer extensions, needed to handle gnu-m4 scripts */
113 { "indir", INDIRTYPE},
114 { "builtin", BUILTINTYPE},
115 { "patsubst", PATSTYPE},
116 { "regexp", REGEXPTYPE},
117 { "esyscmd", ESYSCMDTYPE},
118 { "__file__", FILENAMETYPE | NOARGS},
119 { "__line__", LINETYPE | NOARGS},
120 #endif
121 { "popdef", POPDTYPE },
122 { "pushdef", PUSDTYPE },
123 { "dumpdef", DUMPTYPE | NOARGS },
124 { "shift", SHIFTYPE | NOARGS },
125 { "translit", TRNLTYPE },
126 { "undefine", UNDFTYPE },
127 { "undivert", UNDVTYPE | NOARGS },
128 { "divnum", DIVNTYPE | NOARGS },
129 { "maketemp", MKTMTYPE },
130 { "errprint", ERRPTYPE | NOARGS },
131 { "m4wrap", M4WRTYPE | NOARGS },
132 { "m4exit", EXITTYPE | NOARGS },
133 { "syscmd", SYSCTYPE },
134 { "sysval", SYSVTYPE | NOARGS },
135 { "traceon", TRACEONTYPE | NOARGS },
136 { "traceoff", TRACEOFFTYPE | NOARGS },
138 #if defined(unix) || defined(__unix__)
139 { "unix", SELFTYPE | NOARGS },
140 #else
141 #ifdef vms
142 { "vms", SELFTYPE | NOARGS },
143 #endif
144 #endif
147 #define MAXKEYS (sizeof(keywrds)/sizeof(struct keyblk))
149 #define MAXRECORD 50
150 static struct position {
151 char *name;
152 unsigned long line;
153 } quotes[MAXRECORD], paren[MAXRECORD];
155 static void record(struct position *, int);
156 static void dump_stack(struct position *, int);
158 static void macro(void);
159 static void initkwds(void);
160 static ndptr inspect(int, char *);
161 static int do_look_ahead(int, const char *);
163 static void enlarge_stack(void);
166 main(int argc, char *argv[])
168 int c;
169 int n;
170 int rval;
171 char *p;
173 setlocale(LC_ALL, "");
175 traceout = stderr;
177 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
178 signal(SIGINT, onintr);
180 initkwds();
181 initspaces();
182 STACKMAX = INITSTACKMAX;
184 mstack = (stae *)xalloc(sizeof(stae) * STACKMAX);
185 sstack = (char *)xalloc(STACKMAX);
187 maxout = 0;
188 outfile = NULL;
189 resizedivs(MAXOUT);
191 while ((c = getopt(argc, argv, "gst:d:D:U:o:I:")) != -1)
192 switch(c) {
193 case 'D': /* define something..*/
194 for (p = optarg; *p; p++)
195 if (*p == '=')
196 break;
197 if (p == optarg)
198 errx(1, "null variable cannot be defined");
199 if (*p)
200 *p++ = EOS;
201 dodefine(optarg, p);
202 break;
203 case 'I':
204 addtoincludepath(optarg);
205 break;
206 case 'U': /* undefine... */
207 remhash(optarg, TOP);
208 break;
209 case 'g':
210 mimic_gnu = 1;
211 break;
212 case 'd':
213 set_trace_flags(optarg);
214 break;
215 case 's':
216 synccpp = 1;
217 break;
218 case 't':
219 mark_traced(optarg, 1);
220 break;
221 case 'o':
222 trace_file(optarg);
223 break;
224 case '?':
225 default:
226 usage();
229 argc -= optind;
230 argv += optind;
232 rval = 0;
233 active = stdout; /* default active output */
234 bbase[0] = bufbase;
235 if (!argc) {
236 sp = -1; /* stack pointer initialized */
237 fp = 0; /* frame pointer initialized */
238 set_input(infile+0, stdin, "stdin");
239 /* default input (naturally) */
240 if ((inname[0] = strdup("-")) == NULL)
241 err(1, NULL);
242 inlineno[0] = 1;
243 emitline();
244 macro();
245 } else
246 for (; argc--; ++argv) {
247 p = *argv;
248 if (p[0] == '-' && p[1] == EOS)
249 set_input(infile, stdin, "stdin");
250 else if (fopen_trypath(infile, p) == NULL) {
251 warn("%s", p);
252 rval = 1;
253 continue;
255 sp = -1;
256 fp = 0;
257 if ((inname[0] = strdup(p)) == NULL)
258 err(1, NULL);
259 inlineno[0] = 1;
260 emitline();
261 macro();
262 release_input(infile);
265 if (*m4wraps) { /* anything for rundown ?? */
266 ilevel = 0; /* in case m4wrap includes.. */
267 bufbase = bp = buf; /* use the entire buffer */
268 pbstr(m4wraps); /* user-defined wrapup act */
269 macro(); /* last will and testament */
272 if (active != stdout)
273 active = stdout; /* reset output just in case */
274 for (n = 1; n < maxout; n++) /* default wrap-up: undivert */
275 if (outfile[n] != NULL)
276 getdiv(n);
277 /* remove bitbucket if used */
278 if (outfile[0] != NULL) {
279 (void) fclose(outfile[0]);
282 exit(rval);
286 * Look ahead for `token'.
287 * (on input `t == token[0]')
288 * Used for comment and quoting delimiters.
289 * Returns 1 if `token' present; copied to output.
290 * 0 if `token' not found; all characters pushed back
292 static int
293 do_look_ahead(int t, const char *token)
295 int i;
297 assert((unsigned char)t == (unsigned char)token[0]);
299 for (i = 1; *++token; i++) {
300 t = gpbc();
301 if (t == EOF || (unsigned char)t != (unsigned char)*token) {
302 putback(t);
303 while (--i)
304 putback(*--token);
305 return 0;
308 return 1;
311 #define LOOK_AHEAD(t, token) (t != EOF && \
312 (unsigned char)(t)==(unsigned char)(token)[0] && \
313 do_look_ahead(t,token))
316 * macro - the work horse..
318 static void
319 macro(void)
321 char token[MAXTOK+1];
322 int t, l;
323 ndptr p;
324 int nlpar;
326 cycle {
327 t = gpbc();
328 if (t == '_' || isalpha(t)) {
329 p = inspect(t, token);
330 if (p != nil)
331 putback(l = gpbc());
332 if (p == nil || (l != LPAREN &&
333 (p->type & NEEDARGS) != 0))
334 outputstr(token);
335 else {
337 * real thing.. First build a call frame:
339 pushf(fp); /* previous call frm */
340 pushf(p->type); /* type of the call */
341 pushf(0); /* parenthesis level */
342 fp = sp; /* new frame pointer */
344 * now push the string arguments:
346 pushs1(p->defn); /* defn string */
347 pushs1(p->name); /* macro name */
348 pushs(ep); /* start next..*/
350 if (l != LPAREN && PARLEV == 0) {
351 /* no bracks */
352 chrsave(EOS);
354 if ((uintptr_t)sp == STACKMAX)
355 errx(1, "internal stack overflow");
356 eval((const char **) mstack+fp+1, 2,
357 CALTYP);
359 ep = PREVEP; /* flush strspace */
360 sp = PREVSP; /* previous sp.. */
361 fp = PREVFP; /* rewind stack...*/
364 } else if (t == EOF) {
365 if (sp > -1) {
366 warnx( "unexpected end of input, unclosed parenthesis:");
367 dump_stack(paren, PARLEV);
368 exit(1);
370 if (ilevel <= 0)
371 break; /* all done thanks.. */
372 release_input(infile+ilevel--);
373 free(inname[ilevel+1]);
374 bufbase = bbase[ilevel];
375 emitline();
376 continue;
379 * non-alpha token possibly seen..
380 * [the order of else if .. stmts is important.]
382 else if (LOOK_AHEAD(t,lquote)) { /* strip quotes */
383 nlpar = 0;
384 record(quotes, nlpar++);
386 * Opening quote: scan forward until matching
387 * closing quote has been found.
389 do {
391 l = gpbc();
392 if (LOOK_AHEAD(l,rquote)) {
393 if (--nlpar > 0)
394 outputstr(rquote);
395 } else if (LOOK_AHEAD(l,lquote)) {
396 record(quotes, nlpar++);
397 outputstr(lquote);
398 } else if (l == EOF) {
399 if (nlpar == 1)
400 warnx("unclosed quote:");
401 else
402 warnx("%d unclosed quotes:", nlpar);
403 dump_stack(quotes, nlpar);
404 exit(1);
405 } else {
406 if (nlpar > 0) {
407 if (sp < 0)
408 putc(l, active);
409 else
410 CHRSAVE(l);
414 while (nlpar != 0);
417 else if (sp < 0 && LOOK_AHEAD(t, scommt)) {
418 fputs(scommt, active);
420 for(;;) {
421 t = gpbc();
422 if (LOOK_AHEAD(t, ecommt)) {
423 fputs(ecommt, active);
424 break;
426 if (t == EOF)
427 break;
428 putc(t, active);
432 else if (sp < 0) { /* not in a macro at all */
433 putc(t, active); /* output directly.. */
436 else switch(t) {
438 case LPAREN:
439 if (PARLEV > 0)
440 chrsave(t);
441 while (isspace(l = gpbc()))
442 ; /* skip blank, tab, nl.. */
443 putback(l);
444 record(paren, PARLEV++);
445 break;
447 case RPAREN:
448 if (--PARLEV > 0)
449 chrsave(t);
450 else { /* end of argument list */
451 chrsave(EOS);
453 if ((uintptr_t)sp == STACKMAX)
454 errx(1, "internal stack overflow");
456 eval((const char **) mstack+fp+1, sp-fp,
457 CALTYP);
459 ep = PREVEP; /* flush strspace */
460 sp = PREVSP; /* previous sp.. */
461 fp = PREVFP; /* rewind stack...*/
463 break;
465 case COMMA:
466 if (PARLEV == 1) {
467 chrsave(EOS); /* new argument */
468 while (isspace(l = gpbc()))
470 putback(l);
471 pushs(ep);
472 } else
473 chrsave(t);
474 break;
476 default:
477 if (LOOK_AHEAD(t, scommt)) {
478 char *pc;
479 for (pc = scommt; *pc; pc++)
480 chrsave(*pc);
481 for(;;) {
482 t = gpbc();
483 if (LOOK_AHEAD(t, ecommt)) {
484 for (pc = ecommt; *pc; pc++)
485 chrsave(*pc);
486 break;
488 if (t == EOF)
489 break;
490 CHRSAVE(t);
492 } else
493 CHRSAVE(t); /* stack the char */
494 break;
500 * output string directly, without pushing it for reparses.
502 void
503 outputstr(const char *s)
505 if (sp < 0)
506 while (*s)
507 putc(*s++, active);
508 else
509 while (*s)
510 CHRSAVE(*s++);
514 * build an input token..
515 * consider only those starting with _ or A-Za-z. This is a
516 * combo with lookup to speed things up.
518 static ndptr
519 inspect(int c, char *tp)
521 char *name = tp;
522 char *etp = tp+MAXTOK;
523 ndptr p;
524 unsigned int h;
526 h = *tp++ = c;
528 while ((isalnum(c = gpbc()) || c == '_') && tp < etp)
529 h = (h << 5) + h + (*tp++ = c);
530 if (c != EOF)
531 PUTBACK(c);
532 *tp = EOS;
533 /* token is too long, it won't match anything, but it can still
534 * be output. */
535 if (tp == ep) {
536 outputstr(name);
537 while (isalnum(c = gpbc()) || c == '_') {
538 if (sp < 0)
539 putc(c, active);
540 else
541 CHRSAVE(c);
543 *name = EOS;
544 return nil;
547 for (p = hashtab[h % HASHSIZE]; p != nil; p = p->nxtptr)
548 if (h == p->hv && STREQ(name, p->name))
549 break;
550 return p;
554 * initkwds - initialise m4 keywords as fast as possible.
555 * This very similar to install, but without certain overheads,
556 * such as calling lookup. Malloc is not used for storing the
557 * keyword strings, since we simply use the static pointers
558 * within keywrds block.
560 static void
561 initkwds(void)
563 size_t i;
564 unsigned int h;
565 ndptr p;
567 for (i = 0; i < MAXKEYS; i++) {
568 h = hash(keywrds[i].knam);
569 p = (ndptr) xalloc(sizeof(struct ndblock));
570 p->nxtptr = hashtab[h % HASHSIZE];
571 hashtab[h % HASHSIZE] = p;
572 p->name = xstrdup(keywrds[i].knam);
573 p->defn = null;
574 p->hv = h;
575 p->type = keywrds[i].ktyp & TYPEMASK;
576 if ((keywrds[i].ktyp & NOARGS) == 0)
577 p->type |= NEEDARGS;
581 /* Look up a builtin type, even if overridden by the user */
583 builtin_type(const char *key)
585 int i;
587 for (i = 0; i != MAXKEYS; i++)
588 if (STREQ(keywrds[i].knam, key))
589 return keywrds[i].ktyp;
590 return -1;
593 const char *
594 builtin_realname(int n)
596 int i;
598 for (i = 0; i != MAXKEYS; i++)
599 if (((keywrds[i].ktyp ^ n) & TYPEMASK) == 0)
600 return keywrds[i].knam;
601 return NULL;
604 static void
605 record(struct position *t, int lev)
607 if (lev < MAXRECORD) {
608 t[lev].name = CURRENT_NAME;
609 t[lev].line = CURRENT_LINE;
613 static void
614 dump_stack(struct position *t, int lev)
616 int i;
618 for (i = 0; i < lev; i++) {
619 if (i == MAXRECORD) {
620 fprintf(stderr, " ...\n");
621 break;
623 fprintf(stderr, " %s at line %lu\n",
624 t[i].name, t[i].line);
629 static void
630 enlarge_stack(void)
632 STACKMAX *= 2;
633 mstack = realloc(mstack, sizeof(stae) * STACKMAX);
634 sstack = realloc(sstack, STACKMAX);
635 if (mstack == NULL || sstack == NULL)
636 errx(1, "Evaluation stack overflow (%lu)",
637 (unsigned long)STACKMAX);
640 /* Emit preprocessor #line directive if -s option used. */
641 void
642 emitline(void)
645 if (synccpp)
646 fprintf(active, "#line %d \"%s\"\n", inlineno[ilevel],
647 inname[ilevel]);