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.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 $
48 * Facility: m4 macro processor
52 #include <sys/types.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)*/
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
},
96 { "divert", DIVRTYPE
| NOARGS
},
99 { "substr", SUBSTYPE
},
100 { "ifelse", IFELTYPE
},
101 { "ifdef", IFDFTYPE
},
103 { "incr", INCRTYPE
},
104 { "decr", DECRTYPE
},
105 { "dnl", DNLNTYPE
| NOARGS
},
106 { "changequote", CHNQTYPE
| NOARGS
},
107 { "changecom", CHNCTYPE
| NOARGS
},
108 { "index", INDXTYPE
},
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
},
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
},
142 { "vms", SELFTYPE
| NOARGS
},
147 #define MAXKEYS (sizeof(keywrds)/sizeof(struct keyblk))
150 static struct position
{
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
[])
173 setlocale(LC_ALL
, "");
177 if (signal(SIGINT
, SIG_IGN
) != SIG_IGN
)
178 signal(SIGINT
, onintr
);
182 STACKMAX
= INITSTACKMAX
;
184 mstack
= (stae
*)xalloc(sizeof(stae
) * STACKMAX
);
185 sstack
= (char *)xalloc(STACKMAX
);
191 while ((c
= getopt(argc
, argv
, "gst:d:D:U:o:I:")) != -1)
193 case 'D': /* define something..*/
194 for (p
= optarg
; *p
; p
++)
198 errx(1, "null variable cannot be defined");
204 addtoincludepath(optarg
);
206 case 'U': /* undefine... */
207 remhash(optarg
, TOP
);
213 set_trace_flags(optarg
);
219 mark_traced(optarg
, 1);
233 active
= stdout
; /* default active output */
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
)
246 for (; argc
--; ++argv
) {
248 if (p
[0] == '-' && p
[1] == EOS
)
249 set_input(infile
, stdin
, "stdin");
250 else if (fopen_trypath(infile
, p
) == NULL
) {
257 if ((inname
[0] = strdup(p
)) == NULL
)
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
)
277 /* remove bitbucket if used */
278 if (outfile
[0] != NULL
) {
279 (void) fclose(outfile
[0]);
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
293 do_look_ahead(int t
, const char *token
)
297 assert((unsigned char)t
== (unsigned char)token
[0]);
299 for (i
= 1; *++token
; i
++) {
301 if (t
== EOF
|| (unsigned char)t
!= (unsigned char)*token
) {
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..
321 char token
[MAXTOK
+1];
328 if (t
== '_' || isalpha(t
)) {
329 p
= inspect(t
, token
);
332 if (p
== nil
|| (l
!= LPAREN
&&
333 (p
->type
& NEEDARGS
) != 0))
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) {
354 if ((uintptr_t)sp
== STACKMAX
)
355 errx(1, "internal stack overflow");
356 eval((const char **) mstack
+fp
+1, 2,
359 ep
= PREVEP
; /* flush strspace */
360 sp
= PREVSP
; /* previous sp.. */
361 fp
= PREVFP
; /* rewind stack...*/
364 } else if (t
== EOF
) {
366 warnx( "unexpected end of input, unclosed parenthesis:");
367 dump_stack(paren
, PARLEV
);
371 break; /* all done thanks.. */
372 release_input(infile
+ilevel
--);
373 free(inname
[ilevel
+1]);
374 bufbase
= bbase
[ilevel
];
379 * non-alpha token possibly seen..
380 * [the order of else if .. stmts is important.]
382 else if (LOOK_AHEAD(t
,lquote
)) { /* strip quotes */
384 record(quotes
, nlpar
++);
386 * Opening quote: scan forward until matching
387 * closing quote has been found.
392 if (LOOK_AHEAD(l
,rquote
)) {
395 } else if (LOOK_AHEAD(l
,lquote
)) {
396 record(quotes
, nlpar
++);
398 } else if (l
== EOF
) {
400 warnx("unclosed quote:");
402 warnx("%d unclosed quotes:", nlpar
);
403 dump_stack(quotes
, nlpar
);
417 else if (sp
< 0 && LOOK_AHEAD(t
, scommt
)) {
418 fputs(scommt
, active
);
422 if (LOOK_AHEAD(t
, ecommt
)) {
423 fputs(ecommt
, active
);
432 else if (sp
< 0) { /* not in a macro at all */
433 putc(t
, active
); /* output directly.. */
441 while (isspace(l
= gpbc()))
442 ; /* skip blank, tab, nl.. */
444 record(paren
, PARLEV
++);
450 else { /* end of argument list */
453 if ((uintptr_t)sp
== STACKMAX
)
454 errx(1, "internal stack overflow");
456 eval((const char **) mstack
+fp
+1, sp
-fp
,
459 ep
= PREVEP
; /* flush strspace */
460 sp
= PREVSP
; /* previous sp.. */
461 fp
= PREVFP
; /* rewind stack...*/
467 chrsave(EOS
); /* new argument */
468 while (isspace(l
= gpbc()))
477 if (LOOK_AHEAD(t
, scommt
)) {
479 for (pc
= scommt
; *pc
; pc
++)
483 if (LOOK_AHEAD(t
, ecommt
)) {
484 for (pc
= ecommt
; *pc
; pc
++)
493 CHRSAVE(t
); /* stack the char */
500 * output string directly, without pushing it for reparses.
503 outputstr(const char *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.
519 inspect(int c
, char *tp
)
522 char *etp
= tp
+MAXTOK
;
528 while ((isalnum(c
= gpbc()) || c
== '_') && tp
< etp
)
529 h
= (h
<< 5) + h
+ (*tp
++ = c
);
533 /* token is too long, it won't match anything, but it can still
537 while (isalnum(c
= gpbc()) || c
== '_') {
547 for (p
= hashtab
[h
% HASHSIZE
]; p
!= nil
; p
= p
->nxtptr
)
548 if (h
== p
->hv
&& STREQ(name
, p
->name
))
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.
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
);
575 p
->type
= keywrds
[i
].ktyp
& TYPEMASK
;
576 if ((keywrds
[i
].ktyp
& NOARGS
) == 0)
581 /* Look up a builtin type, even if overridden by the user */
583 builtin_type(const char *key
)
587 for (i
= 0; i
!= MAXKEYS
; i
++)
588 if (STREQ(keywrds
[i
].knam
, key
))
589 return keywrds
[i
].ktyp
;
594 builtin_realname(int n
)
598 for (i
= 0; i
!= MAXKEYS
; i
++)
599 if (((keywrds
[i
].ktyp
^ n
) & TYPEMASK
) == 0)
600 return keywrds
[i
].knam
;
605 record(struct position
*t
, int lev
)
607 if (lev
< MAXRECORD
) {
608 t
[lev
].name
= CURRENT_NAME
;
609 t
[lev
].line
= CURRENT_LINE
;
614 dump_stack(struct position
*t
, int lev
)
618 for (i
= 0; i
< lev
; i
++) {
619 if (i
== MAXRECORD
) {
620 fprintf(stderr
, " ...\n");
623 fprintf(stderr
, " %s at line %lu\n",
624 t
[i
].name
, t
[i
].line
);
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. */
646 fprintf(active
, "#line %d \"%s\"\n", inlineno
[ilevel
],