1 /* $OpenBSD: main.c,v 1.80 2011/09/27 07:24:02 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. 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
35 * $FreeBSD: src/usr.bin/m4/main.c,v 1.33 2012/11/17 01:54:24 svnexp Exp $
40 * Facility: m4 macro processor
59 #include "pathnames.h"
61 stae *mstack; /* stack of m4 machine */
62 char *sstack; /* shadow stack, for string space extension */
63 static size_t STACKMAX; /* current maximum size of stack */
64 int sp; /* current m4 stack pointer */
65 int fp; /* m4 call frame pointer */
66 struct input_file infile[MAXINP];/* input file stack (0=stdin) */
67 FILE **outfile; /* diversion array(0=bitbucket) */
69 FILE *active; /* active output file pointer */
70 int ilevel = 0; /* input file stack pointer */
71 int oindex = 0; /* diversion index.. */
72 const char *null = ""; /* as it says.. just a null.. */
73 char **m4wraps = NULL; /* m4wraps array. */
74 int maxwraps = 0; /* size of m4wraps array */
75 int wrapindex = 0; /* current offset in m4wraps */
76 char lquote[MAXCCHARS + 1] = {LQUOTE}; /* left quote character (`) */
77 char rquote[MAXCCHARS + 1] = {RQUOTE}; /* right quote character (') */
78 char scommt[MAXCCHARS + 1] = {SCOMMT}; /* start character for comment */
79 char ecommt[MAXCCHARS + 1] = {ECOMMT}; /* end character for comment */
80 int synch_lines = 0; /* line synchronisation for C preprocessor */
81 int prefix_builtins = 0; /* -P option to prefix builtin keywords */
84 const char *knam; /* keyword name */
85 int ktyp; /* keyword type */
88 static struct keyblk keywrds[] = { /* m4 keywords to be installed */
89 { "include", INCLTYPE },
90 { "sinclude", SINCTYPE },
91 { "define", DEFITYPE },
93 { "divert", DIVRTYPE | NOARGS },
96 { "substr", SUBSTYPE },
97 { "ifelse", IFELTYPE },
98 { "ifdef", IFDFTYPE },
100 { "incr", INCRTYPE },
101 { "decr", DECRTYPE },
102 { "dnl", DNLNTYPE | NOARGS },
103 { "changequote",CHNQTYPE | NOARGS },
104 { "changecom", CHNCTYPE | NOARGS },
105 { "index", INDXTYPE },
107 { "paste", PASTTYPE },
108 { "spaste", SPASTYPE },
109 /* Newer extensions, needed to handle gnu-m4 scripts */
110 { "indir", INDIRTYPE},
111 { "builtin", BUILTINTYPE},
112 { "patsubst", PATSTYPE},
113 { "regexp", REGEXPTYPE},
114 { "esyscmd", ESYSCMDTYPE},
115 { "__file__", FILENAMETYPE | NOARGS},
116 { "__line__", LINETYPE | NOARGS},
118 { "popdef", POPDTYPE },
119 { "pushdef", PUSDTYPE },
120 { "dumpdef", DUMPTYPE | NOARGS },
121 { "shift", SHIFTYPE | NOARGS },
122 { "translit", TRNLTYPE },
123 { "undefine", UNDFTYPE },
124 { "undivert", UNDVTYPE | NOARGS },
125 { "divnum", DIVNTYPE | NOARGS },
126 { "maketemp", MKTMTYPE },
127 { "mkstemp", MKTMTYPE },
128 { "errprint", ERRPTYPE | NOARGS },
129 { "m4wrap", M4WRTYPE | NOARGS },
130 { "m4exit", EXITTYPE | NOARGS },
131 { "syscmd", SYSCTYPE },
132 { "sysval", SYSVTYPE | NOARGS },
133 { "traceon", TRACEONTYPE | NOARGS },
134 { "traceoff", TRACEOFFTYPE | NOARGS },
135 { "unix", SELFTYPE | NOARGS },
138 #define MAXKEYS (sizeof(keywrds) / sizeof(struct keyblk))
141 static struct position {
144 } quotes[MAXRECORD], paren[MAXRECORD];
146 static void record(struct position *, int);
147 static void dump_stack(struct position *, int);
149 static void macro(void);
150 static void initkwds(void);
151 static ndptr inspect(int, char *);
152 static int do_look_ahead(int, const char *);
153 static void reallyoutputstr(const char *);
154 static void reallyputchar(int);
156 static void enlarge_stack(void);
161 main(int argc, char *argv[])
167 if (signal(SIGINT, SIG_IGN) != SIG_IGN)
168 signal(SIGINT, onintr);
172 STACKMAX = INITSTACKMAX;
174 mstack = (stae *)xalloc(sizeof(stae) * STACKMAX, NULL);
175 sstack = (char *)xalloc(STACKMAX, NULL);
181 while ((c = getopt(argc, argv, "gst:d:D:U:o:I:P")) != -1)
184 case 'D': /* define something.. */
185 for (p = optarg; *p; p++) {
194 addtoincludepath(optarg);
199 case 'U': /* undefine... */
200 macro_popdef(optarg);
206 set_trace_flags(optarg);
212 mark_traced(optarg, 1);
226 setup_builtin("format", FORMATTYPE);
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) */
237 for (; argc--; ++argv) {
239 if (p[0] == '-' && p[1] == EOS)
240 set_input(infile, stdin, "stdin");
241 else if (fopen_trypath(infile, p) == NULL)
246 release_input(infile);
253 ilevel = 0; /* in case m4wrap includes.. */
254 bufbase = bp = buf; /* use the entire buffer */
256 while (wrapindex != 0) {
257 for (i = 0; i < wrapindex; i++)
263 for (i = 0; i < wrapindex; i++) {
270 if (active != stdout)
271 active = stdout; /* reset output just in case */
272 for (n = 1; n < maxout; n++) { /* default wrap-up: undivert */
273 if (outfile[n] != NULL)
276 /* remove bitbucket if used */
277 if (outfile[0] != NULL)
284 * Look ahead for `token'.
285 * (on input `t == token[0]')
286 * Used for comment and quoting delimiters.
287 * Returns 1 if `token' present; copied to output.
288 * 0 if `token' not found; all characters pushed back
291 do_look_ahead(int t, const char *token)
295 assert((unsigned char)t == (unsigned char)token[0]);
297 for (i = 1; *++token; i++) {
299 if (t == EOF || (unsigned char)t != (unsigned char)*token) {
309 #define LOOK_AHEAD(t, token) (t != EOF && \
310 (unsigned char)(t) == (unsigned char)(token)[0] && \
311 do_look_ahead(t, token))
314 * macro - the work horse..
319 char token[MAXTOK + 1];
327 if (LOOK_AHEAD(t, lquote)) { /* strip quotes */
329 record(quotes, nlpar++);
331 * Opening quote: scan forward until matching
332 * closing quote has been found.
336 if (LOOK_AHEAD(l,rquote)) {
339 } else if (LOOK_AHEAD(l,lquote)) {
340 record(quotes, nlpar++);
342 } else if (l == EOF) {
344 warnx("unclosed quote:");
346 warnx("%d unclosed quotes:", nlpar);
347 dump_stack(quotes, nlpar);
359 } else if (sp < 0 && LOOK_AHEAD(t, scommt)) {
360 reallyoutputstr(scommt);
364 if (LOOK_AHEAD(t, ecommt)) {
365 reallyoutputstr(ecommt);
372 } else if (t == '_' || isalpha(t)) {
373 p = inspect(t, token);
375 pushback(l = gpbc());
376 if (p == NULL || (l != LPAREN &&
377 (macro_getdef(p)->type & NEEDARGS) != 0))
381 * real thing.. First build a call frame:
383 pushf(fp); /* previous call frm */
384 /* type of the call */
385 pushf(macro_getdef(p)->type);
387 pushf(0); /* parenthesis level */
388 fp = sp; /* new frame pointer */
390 * now push the string arguments:
392 pushs1(macro_getdef(p)->defn); /* defn string */
393 pushs1((char *)macro_name(p)); /* macro name */
394 pushs(ep); /* start next..*/
396 if (l != LPAREN && PARLEV == 0) {
400 if (sp == (int)STACKMAX) {
402 "internal stack overflow");
404 eval((const char **) mstack + fp + 1, 2,
405 CALTYP, TRACESTATUS);
407 ep = PREVEP; /* flush strspace */
408 sp = PREVSP; /* previous sp.. */
409 fp = PREVFP; /* rewind stack...*/
412 } else if (t == EOF) {
413 if (sp > -1 && ilevel <= 0) {
414 warnx( "unexpected end of input, unclosed parenthesis:");
415 dump_stack(paren, PARLEV);
419 break; /* all done thanks.. */
420 release_input(infile+ilevel--);
422 bufbase = bbase[ilevel];
424 } else if (sp < 0) { /* not in a macro at all */
425 reallyputchar(t); /* output directly.. */
433 while (isspace(l = gpbc())) /* skip blank, tab, nl.. */
437 record(paren, PARLEV++);
443 else { /* end of argument list */
446 if (sp == (int)STACKMAX)
447 errx(1, "internal stack overflow");
449 eval((const char **) mstack + fp + 1, sp-fp,
450 CALTYP, TRACESTATUS);
452 ep = PREVEP; /* flush strspace */
453 sp = PREVSP; /* previous sp.. */
454 fp = PREVFP; /* rewind stack...*/
460 chrsave(EOS); /* new argument */
461 while (isspace(l = gpbc()))
470 if (LOOK_AHEAD(t, scommt)) {
472 for (cp = scommt; *cp; cp++)
476 if (LOOK_AHEAD(t, ecommt)) {
477 for (cp = ecommt; *cp; cp++)
486 CHRSAVE(t); /* stack the char */
493 * output string directly, without pushing it for reparses.
496 outputstr(const char *s)
506 reallyoutputstr(const char *s)
512 infile[ilevel].synch_lineno++;
513 if (infile[ilevel].synch_lineno !=
514 infile[ilevel].lineno)
526 if (synch_lines && c == '\n') {
527 infile[ilevel].synch_lineno++;
528 if (infile[ilevel].synch_lineno != infile[ilevel].lineno)
534 * build an input token..
535 * consider only those starting with _ or A-Za-z.
538 inspect(int c, char *tp)
541 char *etp = tp + MAXTOK;
546 while ((isalnum(c = gpbc()) || c == '_') && tp < etp)
551 /* token is too long, it won't match anything, but it can still
555 while (isalnum(c = gpbc()) || c == '_') {
565 p = ohash_find(¯os, ohash_qlookupi(¯os, name, (const char **)(void *)&tp));
568 if (macro_getdef(p) == NULL)
574 * initkwds - initialize m4 keywords as fast as possible.
575 * This very similar to install, but without certain overheads,
576 * such as calling lookup. Malloc is not used for storing the
577 * keyword strings, since we simply use the static pointers
578 * within keywrds block.
586 for (i = 0; i < (int)MAXKEYS; i++) {
587 type = keywrds[i].ktyp & TYPEMASK;
588 if ((keywrds[i].ktyp & NOARGS) == 0)
590 setup_builtin(keywrds[i].knam, type);
595 record(struct position *t, int lev)
597 if (lev < MAXRECORD) {
598 t[lev].name = CURRENT_NAME;
599 t[lev].line = CURRENT_LINE;
604 dump_stack(struct position *t, int lev)
608 for (i = 0; i < lev; i++) {
609 if (i == MAXRECORD) {
610 fprintf(stderr, " ...\n");
613 fprintf(stderr, " %s at line %lu\n",
614 t[i].name, t[i].line);
622 STACKMAX += STACKMAX/2;
623 mstack = xrealloc(mstack, sizeof(stae) * STACKMAX,
624 "Evaluation stack overflow (%lu)",
625 (unsigned long)STACKMAX);
626 sstack = xrealloc(sstack, STACKMAX,
627 "Evaluation stack overflow (%lu)",
628 (unsigned long)STACKMAX);