compile.c revision 1.6 1 /*-
2 * Copyright (c) 1992 Diomidis Spinellis.
3 * Copyright (c) 1992 The Regents of the University of California.
4 * All rights reserved.
5 *
6 * This code is derived from software contributed to Berkeley by
7 * Diomidis Spinellis of Imperial College, University of London.
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. All advertising materials mentioning features or use of this software
18 * must display the following acknowledgement:
19 * This product includes software developed by the University of
20 * California, Berkeley and its contributors.
21 * 4. Neither the name of the University nor the names of its contributors
22 * may be used to endorse or promote products derived from this software
23 * without specific prior written permission.
24 *
25 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * SUCH DAMAGE.
36 */
37
38 #ifndef lint
39 /*static char sccsid[] = "from: @(#)compile.c 5.6 (Berkeley) 11/2/92";*/
40 static char rcsid[] = "$Id: compile.c,v 1.6 1993/11/04 01:36:29 andrew Exp $";
41 #endif /* not lint */
42
43 #include <sys/types.h>
44 #include <sys/stat.h>
45
46 #include <ctype.h>
47 #include <errno.h>
48 #include <fcntl.h>
49 #include <limits.h>
50 #include <regex.h>
51 #include <stdio.h>
52 #include <stdlib.h>
53 #include <string.h>
54
55 #include "defs.h"
56 #include "extern.h"
57
58 static char *compile_addr __P((char *, struct s_addr *));
59 static char *compile_ccl __P((char **, char *));
60 static char *compile_delimited __P((char *, char *));
61 static char *compile_flags __P((char *, struct s_subst *));
62 static char *compile_re __P((char *, regex_t **));
63 static char *compile_subst __P((char *, struct s_subst *));
64 static char *compile_text __P((void));
65 static char *compile_tr __P((char *, char **));
66 static struct s_command
67 **compile_stream __P((char *, struct s_command **, char *));
68 static char *duptoeol __P((char *));
69 static struct s_command
70 *findlabel __P((struct s_command *, struct s_command *));
71 static void fixuplabel __P((struct s_command *, struct s_command *,
72 struct s_command *));
73
74 /*
75 * Command specification. This is used to drive the command parser.
76 */
77 struct s_format {
78 char code; /* Command code */
79 int naddr; /* Number of address args */
80 enum e_args args; /* Argument type */
81 };
82
83 static struct s_format cmd_fmts[] = {
84 {'{', 2, GROUP},
85 {'a', 1, TEXT},
86 {'b', 2, BRANCH},
87 {'c', 2, TEXT},
88 {'d', 2, EMPTY},
89 {'D', 2, EMPTY},
90 {'g', 2, EMPTY},
91 {'G', 2, EMPTY},
92 {'h', 2, EMPTY},
93 {'H', 2, EMPTY},
94 {'i', 1, TEXT},
95 {'l', 2, EMPTY},
96 {'n', 2, EMPTY},
97 {'N', 2, EMPTY},
98 {'p', 2, EMPTY},
99 {'P', 2, EMPTY},
100 {'q', 1, EMPTY},
101 {'r', 1, RFILE},
102 {'s', 2, SUBST},
103 {'t', 2, BRANCH},
104 {'w', 2, WFILE},
105 {'x', 2, EMPTY},
106 {'y', 2, TR},
107 {'!', 2, NONSEL},
108 {':', 0, LABEL},
109 {'#', 0, COMMENT},
110 {'=', 1, EMPTY},
111 {'\0', 0, COMMENT},
112 };
113
114 /* The compiled program. */
115 struct s_command *prog;
116
117 /*
118 * Compile the program into prog.
119 * Initialise appends.
120 */
121 void
122 compile()
123 {
124 *compile_stream(NULL, &prog, NULL) = NULL;
125 fixuplabel(prog, prog, NULL);
126 appends = xmalloc(sizeof(struct s_appends) * appendnum);
127 match = xmalloc((maxnsub + 1) * sizeof(regmatch_t));
128 }
129
130 #define EATSPACE() do { \
131 if (p) \
132 while (*p && isascii(*p) && isspace(*p)) \
133 p++; \
134 } while (0)
135
136 static struct s_command **
137 compile_stream(terminator, link, p)
138 char *terminator;
139 struct s_command **link;
140 register char *p;
141 {
142 static char lbuf[_POSIX2_LINE_MAX + 1]; /* To save stack */
143 struct s_command *cmd, *cmd2;
144 struct s_format *fp;
145 int naddr; /* Number of addresses */
146
147 if (p != NULL)
148 goto semicolon;
149 for (;;) {
150 if ((p = cu_fgets(lbuf, sizeof(lbuf))) == NULL) {
151 if (terminator != NULL)
152 err(COMPILE, "unexpected EOF (pending }'s)");
153 return (link);
154 }
155
156 semicolon: EATSPACE();
157 if (p && (*p == '#' || *p == '\0'))
158 continue;
159 if (*p == '}') {
160 if (terminator == NULL)
161 err(COMPILE, "unexpected }");
162 return (link);
163 }
164 *link = cmd = xmalloc(sizeof(struct s_command));
165 link = &cmd->next;
166 cmd->nonsel = cmd->inrange = 0;
167 /* First parse the addresses */
168 naddr = 0;
169 cmd->a1 = cmd->a2 = NULL;
170
171 /* Valid characters to start an address */
172 #define addrchar(c) (strchr("0123456789/\\$", (c)))
173 if (addrchar(*p)) {
174 naddr++;
175 cmd->a1 = xmalloc(sizeof(struct s_addr));
176 p = compile_addr(p, cmd->a1);
177 EATSPACE(); /* EXTENSION */
178 if (*p == ',') {
179 naddr++;
180 p++;
181 EATSPACE(); /* EXTENSION */
182 cmd->a2 = xmalloc(sizeof(struct s_addr));
183 p = compile_addr(p, cmd->a2);
184 }
185 }
186
187 nonsel: /* Now parse the command */
188 EATSPACE();
189 if (!*p)
190 err(COMPILE, "command expected");
191 cmd->code = *p;
192 for (fp = cmd_fmts; fp->code; fp++)
193 if (fp->code == *p)
194 break;
195 if (!fp->code)
196 err(COMPILE, "invalid command code %c", *p);
197 if (naddr > fp->naddr)
198 err(COMPILE,
199 "command %c expects up to %d address(es), found %d", *p, fp->naddr, naddr);
200 switch (fp->args) {
201 case NONSEL: /* ! */
202 cmd->nonsel = ! cmd->nonsel;
203 p++;
204 goto nonsel;
205 case GROUP: /* { */
206 p++;
207 EATSPACE();
208 if (!*p)
209 p = NULL;
210 cmd2 = xmalloc(sizeof(struct s_command));
211 cmd2->code = '}';
212 *compile_stream("}", &cmd->u.c, p) = cmd2;
213 cmd->next = cmd2;
214 link = &cmd2->next;
215 break;
216 case EMPTY: /* d D g G h H l n N p P q x = \0 */
217 p++;
218 EATSPACE();
219 if (*p == ';') {
220 p++;
221 link = &cmd->next;
222 goto semicolon;
223 }
224 if (*p)
225 err(COMPILE,
226 "extra characters at the end of %c command", cmd->code);
227 break;
228 case TEXT: /* a c i */
229 p++;
230 EATSPACE();
231 if (*p != '\\')
232 err(COMPILE,
233 "command %c expects \\ followed by text", cmd->code);
234 p++;
235 EATSPACE();
236 if (*p)
237 err(COMPILE,
238 "extra characters after \\ at the end of %c command", cmd->code);
239 cmd->t = compile_text();
240 break;
241 case COMMENT: /* \0 # */
242 break;
243 case WFILE: /* w */
244 p++;
245 EATSPACE();
246 if (*p == '\0')
247 err(COMPILE, "filename expected");
248 cmd->t = duptoeol(p);
249 if (aflag)
250 cmd->u.fd = -1;
251 else if ((cmd->u.fd = open(p,
252 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
253 DEFFILEMODE)) == -1)
254 err(FATAL, "%s: %s\n", p, strerror(errno));
255 break;
256 case RFILE: /* r */
257 p++;
258 EATSPACE();
259 if (*p == '\0')
260 err(COMPILE, "filename expected");
261 else
262 cmd->t = duptoeol(p);
263 break;
264 case BRANCH: /* b t */
265 p++;
266 EATSPACE();
267 if (*p == '\0')
268 cmd->t = NULL;
269 else
270 cmd->t = duptoeol(p);
271 break;
272 case LABEL: /* : */
273 p++;
274 EATSPACE();
275 cmd->t = duptoeol(p);
276 if (strlen(p) == 0)
277 err(COMPILE, "empty label");
278 break;
279 case SUBST: /* s */
280 p++;
281 if (*p == '\0' || *p == '\\')
282 err(COMPILE,
283 "substitute pattern can not be delimited by newline or backslash");
284 cmd->u.s = xmalloc(sizeof(struct s_subst));
285 p = compile_re(p, &cmd->u.s->re);
286 if (p == NULL)
287 err(COMPILE, "unterminated substitute pattern");
288 --p;
289 p = compile_subst(p, cmd->u.s);
290 p = compile_flags(p, cmd->u.s);
291 EATSPACE();
292 if (*p == ';') {
293 p++;
294 link = &cmd->next;
295 goto semicolon;
296 }
297 break;
298 case TR: /* y */
299 p++;
300 p = compile_tr(p, (char **)&cmd->u.y);
301 EATSPACE();
302 if (*p == ';') {
303 p++;
304 link = &cmd->next;
305 goto semicolon;
306 }
307 if (*p)
308 err(COMPILE,
309 "extra text at the end of a transform command");
310 break;
311 }
312 }
313 }
314
315 /*
316 * Get a delimited string. P points to the delimeter of the string; d points
317 * to a buffer area. Newline and delimiter escapes are processed; other
318 * escapes are ignored.
319 *
320 * Returns a pointer to the first character after the final delimiter or NULL
321 * in the case of a non-terminated string. The character array d is filled
322 * with the processed string.
323 */
324 static char *
325 compile_delimited(p, d)
326 char *p, *d;
327 {
328 char c;
329
330 c = *p++;
331 if (c == '\0')
332 return (NULL);
333 else if (c == '\\')
334 err(COMPILE, "\\ can not be used as a string delimiter");
335 else if (c == '\n')
336 err(COMPILE, "newline can not be used as a string delimiter");
337 while (*p) {
338 if (*p == '[') {
339 if ((d = compile_ccl(&p, d)) == NULL)
340 err(COMPILE, "unbalanced brackets ([])");
341 continue;
342 } else if (*p == '\\' && p[1] == c)
343 p++;
344 else if (*p == '\\' && p[1] == 'n') {
345 *d++ = '\n';
346 p += 2;
347 continue;
348 } else if (*p == '\\' && p[1] == '\\')
349 *d++ = *p++;
350 else if (*p == c) {
351 *d = '\0';
352 return (p + 1);
353 }
354 *d++ = *p++;
355 }
356 return (NULL);
357 }
358
359
360 /* compile_ccl: expand a POSIX character class */
361 static char *
362 compile_ccl(sp, t)
363 char **sp;
364 char *t;
365 {
366 int c, d;
367 char *s = *sp;
368
369 *t++ = *s++;
370 if (*s == '^')
371 *t++ = *s++;
372 if (*s == ']')
373 *t++ = *s++;
374 for (; *s && (*t = *s) != ']'; s++, t++)
375 if (*s == '[' && ((d = *(s+1)) == '.' || d == ':' || d == '=')) {
376 *++t = *++s, t++, s++;
377 for (c = *s; (*t = *s) != ']' || c != d; s++, t++)
378 if ((c = *s) == '\0')
379 return NULL;
380 } else if (*s == '\\' && s[1] == 'n')
381 *t = '\n', s++;
382 return (*s == ']') ? *sp = ++s, ++t : NULL;
383 }
384
385 /*
386 * Get a regular expression. P points to the delimiter of the regular
387 * expression; repp points to the address of a regexp pointer. Newline
388 * and delimiter escapes are processed; other escapes are ignored.
389 * Returns a pointer to the first character after the final delimiter
390 * or NULL in the case of a non terminated regular expression. The regexp
391 * pointer is set to the compiled regular expression.
392 * Cflags are passed to regcomp.
393 */
394 static char *
395 compile_re(p, repp)
396 char *p;
397 regex_t **repp;
398 {
399 int eval;
400 char re[_POSIX2_LINE_MAX + 1];
401
402 p = compile_delimited(p, re);
403 if (p && strlen(re) == 0) {
404 *repp = NULL;
405 return (p);
406 }
407 *repp = xmalloc(sizeof(regex_t));
408 if (p && (eval = regcomp(*repp, re, 0)) != 0)
409 err(COMPILE, "RE error: %s", strregerror(eval, *repp));
410 if (maxnsub < (*repp)->re_nsub)
411 maxnsub = (*repp)->re_nsub;
412 return (p);
413 }
414
415 /*
416 * Compile the substitution string of a regular expression and set res to
417 * point to a saved copy of it. Nsub is the number of parenthesized regular
418 * expressions.
419 */
420 static char *
421 compile_subst(p, s)
422 char *p;
423 struct s_subst *s;
424 {
425 static char lbuf[_POSIX2_LINE_MAX + 1];
426 int asize, ref, size;
427 char c, *text, *op, *sp;
428
429 c = *p++; /* Terminator character */
430 if (c == '\0')
431 return (NULL);
432
433 s->maxbref = 0;
434 s->linenum = linenum;
435 asize = 2 * _POSIX2_LINE_MAX + 1;
436 text = xmalloc(asize);
437 size = 0;
438 do {
439 op = sp = text + size;
440 for (; *p; p++) {
441 if (*p == '\\') {
442 p++;
443 if (strchr("123456789", *p) != NULL) {
444 *sp++ = '\\';
445 ref = *p - '0';
446 if (s->re != NULL &&
447 ref > s->re->re_nsub)
448 err(COMPILE,
449 "\\%c not defined in the RE", *p);
450 if (s->maxbref < ref)
451 s->maxbref = ref;
452 } else if (*p == '&' || *p == '\\')
453 *sp++ = '\\';
454 } else if (*p == c) {
455 p++;
456 *sp++ = '\0';
457 size += sp - op;
458 s->new = xrealloc(text, size);
459 return (p);
460 } else if (*p == '\n') {
461 err(COMPILE,
462 "unescaped newline inside substitute pattern");
463 /* NOTREACHED */
464 }
465 *sp++ = *p;
466 }
467 size += sp - op;
468 if (asize - size < _POSIX2_LINE_MAX + 1) {
469 asize *= 2;
470 text = xmalloc(asize);
471 }
472 } while (cu_fgets(p = lbuf, sizeof(lbuf)));
473 err(COMPILE, "unterminated substitute in regular expression");
474 /* NOTREACHED */
475 }
476
477 /*
478 * Compile the flags of the s command
479 */
480 static char *
481 compile_flags(p, s)
482 char *p;
483 struct s_subst *s;
484 {
485 int gn; /* True if we have seen g or n */
486 char wfile[_POSIX2_LINE_MAX + 1], *q;
487
488 s->n = 1; /* Default */
489 s->p = 0;
490 s->wfile = NULL;
491 s->wfd = -1;
492 for (gn = 0;;) {
493 EATSPACE(); /* EXTENSION */
494 switch (*p) {
495 case 'g':
496 if (gn)
497 err(COMPILE,
498 "more than one number or 'g' in substitute flags");
499 gn = 1;
500 s->n = 0;
501 break;
502 case '\0':
503 case '\n':
504 case ';':
505 return (p);
506 case 'p':
507 s->p = 1;
508 break;
509 case '1': case '2': case '3':
510 case '4': case '5': case '6':
511 case '7': case '8': case '9':
512 if (gn)
513 err(COMPILE,
514 "more than one number or 'g' in substitute flags");
515 gn = 1;
516 /* XXX Check for overflow */
517 s->n = (int)strtol(p, &p, 10);
518 break;
519 case 'w':
520 p++;
521 #ifdef FUSSY_HISTORIC_PRACTICE
522 if (*p != ' ') {
523 err(WARNING, "space missing before w wfile");
524 return (p);
525 }
526 #endif
527 EATSPACE();
528 q = wfile;
529 while (*p) {
530 if (*p == '\n')
531 break;
532 *q++ = *p++;
533 }
534 *q = '\0';
535 if (q == wfile)
536 err(COMPILE, "no wfile specified");
537 s->wfile = strdup(wfile);
538 if (!aflag && (s->wfd = open(wfile,
539 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
540 DEFFILEMODE)) == -1)
541 err(FATAL, "%s: %s\n", wfile, strerror(errno));
542 return (p);
543 default:
544 err(COMPILE,
545 "bad flag in substitute command: '%c'", *p);
546 break;
547 }
548 p++;
549 }
550 }
551
552 /*
553 * Compile a translation set of strings into a lookup table.
554 */
555 static char *
556 compile_tr(p, transtab)
557 char *p;
558 char **transtab;
559 {
560 int i;
561 char *lt, *op, *np;
562 char old[_POSIX2_LINE_MAX + 1];
563 char new[_POSIX2_LINE_MAX + 1];
564
565 if (*p == '\0' || *p == '\\')
566 err(COMPILE,
567 "transform pattern can not be delimited by newline or backslash");
568 p = compile_delimited(p, old);
569 if (p == NULL) {
570 err(COMPILE, "unterminated transform source string");
571 return (NULL);
572 }
573 p = compile_delimited(--p, new);
574 if (p == NULL) {
575 err(COMPILE, "unterminated transform target string");
576 return (NULL);
577 }
578 EATSPACE();
579 if (strlen(new) != strlen(old)) {
580 err(COMPILE, "transform strings are not the same length");
581 return (NULL);
582 }
583 /* We assume characters are 8 bits */
584 lt = xmalloc(UCHAR_MAX);
585 for (i = 0; i <= UCHAR_MAX; i++)
586 lt[i] = (char)i;
587 for (op = old, np = new; *op; op++, np++)
588 lt[(u_char)*op] = *np;
589 *transtab = lt;
590 return (p);
591 }
592
593 /*
594 * Compile the text following an a or i command.
595 */
596 static char *
597 compile_text()
598 {
599 int asize, size;
600 char *text, *p, *op, *s;
601 char lbuf[_POSIX2_LINE_MAX + 1];
602
603 asize = 2 * _POSIX2_LINE_MAX + 1;
604 text = xmalloc(asize);
605 size = 0;
606 while (cu_fgets(lbuf, sizeof(lbuf))) {
607 op = s = text + size;
608 p = lbuf;
609 EATSPACE();
610 for (; *p; p++) {
611 if (*p == '\\')
612 p++;
613 *s++ = *p;
614 }
615 size += s - op;
616 if (p[-2] != '\\') {
617 *s = '\0';
618 break;
619 }
620 if (asize - size < _POSIX2_LINE_MAX + 1) {
621 asize *= 2;
622 text = xmalloc(asize);
623 }
624 }
625 return (xrealloc(text, size + 1));
626 }
627
628 /*
629 * Get an address and return a pointer to the first character after
630 * it. Fill the structure pointed to according to the address.
631 */
632 static char *
633 compile_addr(p, a)
634 char *p;
635 struct s_addr *a;
636 {
637 char *end;
638
639 switch (*p) {
640 case '\\': /* Context address */
641 ++p;
642 /* FALLTHROUGH */
643 case '/': /* Context address */
644 p = compile_re(p, &a->u.r);
645 if (p == NULL)
646 err(COMPILE, "unterminated regular expression");
647 a->type = AT_RE;
648 return (p);
649
650 case '$': /* Last line */
651 a->type = AT_LAST;
652 return (p + 1);
653 /* Line number */
654 case '0': case '1': case '2': case '3': case '4':
655 case '5': case '6': case '7': case '8': case '9':
656 a->type = AT_LINE;
657 a->u.l = strtol(p, &end, 10);
658 return (end);
659 default:
660 err(COMPILE, "expected context address");
661 return (NULL);
662 }
663 }
664
665 /*
666 * Return a copy of all the characters up to \n or \0
667 */
668 static char *
669 duptoeol(s)
670 register char *s;
671 {
672 size_t len;
673 char *start;
674
675 for (start = s; *s != '\0' && *s != '\n'; ++s);
676 *s = '\0';
677 len = s - start + 1;
678 return (memmove(xmalloc(len), start, len));
679 }
680
681 /*
682 * Find the label contained in the command l in the command linked list cp.
683 * L is excluded from the search. Return NULL if not found.
684 */
685 static struct s_command *
686 findlabel(l, cp)
687 struct s_command *l, *cp;
688 {
689 struct s_command *r;
690
691 for (; cp; cp = cp->next)
692 if (cp->code == ':' && cp != l && strcmp(l->t, cp->t) == 0)
693 return (cp);
694 else if (cp->code == '{' && (r = findlabel(l, cp->u.c)))
695 return (r);
696 return (NULL);
697 }
698
699 /*
700 * Convert goto label names to addresses.
701 * Detect duplicate labels.
702 * Set appendnum to the number of a and r commands in the script.
703 * Free the memory used by labels in b and t commands (but not by :)
704 * Root is a pointer to the script linked list; cp points to the
705 * search start.
706 * TODO: Remove } nodes
707 */
708 static void
709 fixuplabel(root, cp, end)
710 struct s_command *root, *cp, *end;
711 {
712 struct s_command *cp2;
713
714 for (; cp != end; cp = cp->next)
715 switch (cp->code) {
716 case ':':
717 if (findlabel(cp, root))
718 err(COMPILE2, "duplicate label %s", cp->t);
719 break;
720 case 'a':
721 case 'r':
722 appendnum++;
723 break;
724 case 'b':
725 case 't':
726 if (cp->t == NULL) {
727 cp->u.c = NULL;
728 break;
729 }
730 if ((cp2 = findlabel(cp, root)) == NULL)
731 err(COMPILE2, "undefined label '%s'", cp->t);
732 free(cp->t);
733 cp->u.c = cp2;
734 break;
735 case '{':
736 fixuplabel(root, cp->u.c, cp->next);
737 break;
738 }
739 }
740