2 * Copyright (c) 1992 Diomidis Spinellis.
3 * Copyright (c) 1992, 1993
4 * The Regents of the University of California. All rights reserved.
6 * This code is derived from software contributed to Berkeley by
7 * Diomidis Spinellis of Imperial College, University of London.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
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.
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
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD: src/usr.bin/sed/compile.c,v 1.13.2.8 2002/08/17 05:47:06 tjr Exp $");
42 static const char sccsid[] = "@(#)compile.c 8.1 (Berkeley) 6/6/93";
45 #include <sys/types.h>
61 #define LHMASK (LHSZ - 1)
62 static struct labhash {
63 struct labhash *lh_next;
65 struct s_command *lh_cmd;
69 static char *compile_addr(char *, struct s_addr *);
70 static char *compile_ccl(char **, char *);
71 static char *compile_delimited(char *, char *);
72 static char *compile_flags(char *, struct s_subst *);
73 static char *compile_re(char *, regex_t **);
74 static char *compile_subst(char *, struct s_subst *);
75 static char *compile_text(void);
76 static char *compile_tr(char *, char **);
77 static struct s_command
78 **compile_stream(struct s_command **);
79 static char *duptoeol(char *, const char *);
80 static void enterlabel(struct s_command *);
81 static struct s_command
83 static void fixuplabel(struct s_command *, struct s_command *);
84 static void uselabel(void);
87 * Command specification. This is used to drive the command parser.
90 char code; /* Command code */
91 int naddr; /* Number of address args */
92 enum e_args args; /* Argument type */
95 static struct s_format cmd_fmts[] = {
127 /* The compiled program. */
128 struct s_command *prog;
131 * Compile the program into prog.
132 * Initialise appends.
137 *compile_stream(&prog) = NULL;
138 fixuplabel(prog, NULL);
142 else if ((appends = malloc(sizeof(struct s_appends) * appendnum)) ==
145 if ((match = malloc((maxnsub + 1) * sizeof(regmatch_t))) == NULL)
149 #define EATSPACE() do { \
151 while (*p && isspace((unsigned char)*p)) \
155 static struct s_command **
157 struct s_command **link;
160 static char lbuf[_POSIX2_LINE_MAX + 1]; /* To save stack */
161 struct s_command *cmd, *cmd2, *stack;
163 int naddr; /* Number of addresses */
167 if ((p = cu_fgets(lbuf, sizeof(lbuf), NULL)) == NULL) {
169 errx(1, "%lu: %s: unexpected EOF (pending }'s)",
174 semicolon: EATSPACE();
176 if (*p == '#' || *p == '\0')
178 else if (*p == ';') {
183 if ((*link = cmd = malloc(sizeof(struct s_command))) == NULL)
186 cmd->nonsel = cmd->inrange = 0;
187 /* First parse the addresses */
190 /* Valid characters to start an address */
191 #define addrchar(c) (strchr("0123456789/\\$", (c)))
194 if ((cmd->a1 = malloc(sizeof(struct s_addr))) == NULL)
196 p = compile_addr(p, cmd->a1);
197 EATSPACE(); /* EXTENSION */
200 EATSPACE(); /* EXTENSION */
202 if ((cmd->a2 = malloc(sizeof(struct s_addr)))
205 p = compile_addr(p, cmd->a2);
210 cmd->a1 = cmd->a2 = 0;
212 nonsel: /* Now parse the command */
214 errx(1, "%lu: %s: command expected", linenum, fname);
216 for (fp = cmd_fmts; fp->code; fp++)
220 errx(1, "%lu: %s: invalid command code %c", linenum, fname, *p);
221 if (naddr > fp->naddr)
223 "%lu: %s: command %c expects up to %d address(es), found %d",
224 linenum, fname, *p, fp->naddr, naddr);
229 cmd->nonsel = ! cmd->nonsel;
242 * Short-circuit command processing, since end of
243 * group is really just a noop.
247 errx(1, "%lu: %s: unexpected }", linenum, fname);
252 case EMPTY: /* d D g G h H l n N p P q x = \0 */
261 errx(1, "%lu: %s: extra characters at the end of %c command",
262 linenum, fname, cmd->code);
264 case TEXT: /* a c i */
269 "%lu: %s: command %c expects \\ followed by text", linenum, fname, cmd->code);
274 "%lu: %s: extra characters after \\ at the end of %c command",
275 linenum, fname, cmd->code);
276 cmd->t = compile_text();
278 case COMMENT: /* \0 # */
284 errx(1, "%lu: %s: filename expected", linenum, fname);
285 cmd->t = duptoeol(p, "w command");
288 else if ((cmd->u.fd = open(p,
289 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
297 errx(1, "%lu: %s: filename expected", linenum, fname);
299 cmd->t = duptoeol(p, "read command");
301 case BRANCH: /* b t */
307 cmd->t = duptoeol(p, "branch");
312 cmd->t = duptoeol(p, "label");
314 errx(1, "%lu: %s: empty label", linenum, fname);
319 if (*p == '\0' || *p == '\\')
321 "%lu: %s: substitute pattern can not be delimited by newline or backslash",
323 if ((cmd->u.s = malloc(sizeof(struct s_subst))) == NULL)
325 p = compile_re(p, &cmd->u.s->re);
328 "%lu: %s: unterminated substitute pattern", linenum, fname);
330 p = compile_subst(p, cmd->u.s);
331 p = compile_flags(p, cmd->u.s);
341 p = compile_tr(p, (char **)&cmd->u.y);
350 "%lu: %s: extra text at the end of a transform command", linenum, fname);
357 * Get a delimited string. P points to the delimeter of the string; d points
358 * to a buffer area. Newline and delimiter escapes are processed; other
359 * escapes are ignored.
361 * Returns a pointer to the first character after the final delimiter or NULL
362 * in the case of a non-terminated string. The character array d is filled
363 * with the processed string.
366 compile_delimited(p, d)
375 errx(1, "%lu: %s: \\ can not be used as a string delimiter",
378 errx(1, "%lu: %s: newline can not be used as a string delimiter",
382 if ((d = compile_ccl(&p, d)) == NULL)
383 errx(1, "%lu: %s: unbalanced brackets ([])", linenum, fname);
385 } else if (*p == '\\' && p[1] == '[') {
387 } else if (*p == '\\' && p[1] == c)
389 else if (*p == '\\' && p[1] == 'n') {
393 } else if (*p == '\\' && p[1] == '\\')
405 /* compile_ccl: expand a POSIX character class */
419 for (; *s && (*t = *s) != ']'; s++, t++)
420 if (*s == '[' && ((d = *(s+1)) == '.' || d == ':' || d == '=')) {
421 *++t = *++s, t++, s++;
422 for (c = *s; (*t = *s) != ']' || c != d; s++, t++)
423 if ((c = *s) == '\0')
425 } else if (*s == '\\' && s[1] == 'n')
427 return (*s == ']') ? *sp = ++s, ++t : NULL;
431 * Get a regular expression. P points to the delimiter of the regular
432 * expression; repp points to the address of a regexp pointer. Newline
433 * and delimiter escapes are processed; other escapes are ignored.
434 * Returns a pointer to the first character after the final delimiter
435 * or NULL in the case of a non terminated regular expression. The regexp
436 * pointer is set to the compiled regular expression.
437 * Cflags are passed to regcomp.
445 char re[_POSIX2_LINE_MAX + 1];
447 p = compile_delimited(p, re);
448 if (p && strlen(re) == 0) {
452 if ((*repp = malloc(sizeof(regex_t))) == NULL)
454 if (p && (eval = regcomp(*repp, re, rflags)) != 0)
455 errx(1, "%lu: %s: RE error: %s",
456 linenum, fname, strregerror(eval, *repp));
457 if (maxnsub < (*repp)->re_nsub)
458 maxnsub = (*repp)->re_nsub;
463 * Compile the substitution string of a regular expression and set res to
464 * point to a saved copy of it. Nsub is the number of parenthesized regular
472 static char lbuf[_POSIX2_LINE_MAX + 1];
475 char c, *text, *op, *sp;
476 int more = 1, sawesc = 0;
478 c = *p++; /* Terminator character */
483 s->linenum = linenum;
484 asize = 2 * _POSIX2_LINE_MAX + 1;
485 if ((text = malloc(asize)) == NULL)
489 op = sp = text + size;
491 if (*p == '\\' || sawesc) {
493 * If this is a continuation from the last
494 * buffer, we won't have a character to
504 * This escaped character is continued
505 * in the next part of the line. Note
506 * this fact, then cause the loop to
507 * exit w/ normal EOL case and reenter
508 * above with the new buffer.
513 } else if (strchr("123456789", *p) != NULL) {
517 ref > s->re->re_nsub)
518 errx(1, "%lu: %s: \\%c not defined in the RE",
520 if (s->maxbref < ref)
522 } else if (*p == '&' || *p == '\\')
524 } else if (*p == c) {
525 if (*++p == '\0' && more) {
526 if (cu_fgets(lbuf, sizeof(lbuf), &more))
531 if ((s->new = realloc(text, size)) == NULL)
534 } else if (*p == '\n') {
536 "%lu: %s: unescaped newline inside substitute pattern", linenum, fname);
542 if (asize - size < _POSIX2_LINE_MAX + 1) {
544 if ((text = realloc(text, asize)) == NULL)
547 } while (cu_fgets(p = lbuf, sizeof(lbuf), &more));
548 errx(1, "%lu: %s: unterminated substitute in regular expression",
554 * Compile the flags of the s command
561 int gn; /* True if we have seen g or n */
562 char wfile[_POSIX2_LINE_MAX + 1], *q;
564 s->n = 1; /* Default */
569 EATSPACE(); /* EXTENSION */
574 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
585 case '1': case '2': case '3':
586 case '4': case '5': case '6':
587 case '7': case '8': case '9':
590 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
592 /* XXX Check for overflow */
593 s->n = (int)strtol(p, &p, 10);
597 #ifdef HISTORIC_PRACTICE
599 warnx("%lu: %s: space missing before w wfile", linenum, fname);
612 errx(1, "%lu: %s: no wfile specified", linenum, fname);
613 s->wfile = strdup(wfile);
614 if (!aflag && (s->wfd = open(wfile,
615 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
620 errx(1, "%lu: %s: bad flag in substitute command: '%c'",
629 * Compile a translation set of strings into a lookup table.
632 compile_tr(p, transtab)
638 char old[_POSIX2_LINE_MAX + 1];
639 char new[_POSIX2_LINE_MAX + 1];
641 if (*p == '\0' || *p == '\\')
643 "%lu: %s: transform pattern can not be delimited by newline or backslash",
645 p = compile_delimited(p, old);
647 errx(1, "%lu: %s: unterminated transform source string",
649 p = compile_delimited(--p, new);
651 errx(1, "%lu: %s: unterminated transform target string",
654 if (strlen(new) != strlen(old))
655 errx(1, "%lu: %s: transform strings are not the same length",
657 /* We assume characters are 8 bits */
658 if ((lt = malloc(UCHAR_MAX)) == NULL)
660 for (i = 0; i <= UCHAR_MAX; i++)
662 for (op = old, np = new; *op; op++, np++)
663 lt[(u_char)*op] = *np;
669 * Compile the text following an a or i command.
674 int asize, esc_nl, size;
675 char *text, *p, *op, *s;
676 char lbuf[_POSIX2_LINE_MAX + 1];
678 asize = 2 * _POSIX2_LINE_MAX + 1;
679 if ((text = malloc(asize)) == NULL)
682 while (cu_fgets(lbuf, sizeof(lbuf), NULL)) {
683 op = s = text + size;
686 for (esc_nl = 0; *p != '\0'; p++) {
687 if (*p == '\\' && p[1] != '\0' && *++p == '\n')
696 if (asize - size < _POSIX2_LINE_MAX + 1) {
698 if ((text = realloc(text, asize)) == NULL)
703 if ((p = realloc(text, size + 1)) == NULL)
709 * Get an address and return a pointer to the first character after
710 * it. Fill the structure pointed to according to the address.
720 case '\\': /* Context address */
723 case '/': /* Context address */
724 p = compile_re(p, &a->u.r);
726 errx(1, "%lu: %s: unterminated regular expression", linenum, fname);
730 case '$': /* Last line */
734 case '0': case '1': case '2': case '3': case '4':
735 case '5': case '6': case '7': case '8': case '9':
737 a->u.l = strtol(p, &end, 10);
740 errx(1, "%lu: %s: expected context address", linenum, fname);
747 * Return a copy of all the characters up to \n or \0.
759 for (start = s; *s != '\0' && *s != '\n'; ++s)
760 ws = isspace((unsigned char)*s);
763 warnx("%lu: %s: whitespace after %s", linenum, fname, ctype);
765 if ((p = malloc(len)) == NULL)
767 return (memmove(p, start, len));
771 * Convert goto label names to addresses, and count a and r commands, in
772 * the given subset of the script. Free the memory used by labels in b
773 * and t commands (but not by :).
775 * TODO: Remove } nodes
779 struct s_command *cp, *end;
782 for (; cp != end; cp = cp->next)
790 /* Resolve branch target. */
795 if ((cp->u.c = findlabel(cp->t)) == NULL)
796 errx(1, "%lu: %s: undefined label '%s'", linenum, fname, cp->t);
800 /* Do interior commands. */
801 fixuplabel(cp->u.c, cp->next);
807 * Associate the given command label for later lookup.
811 struct s_command *cp;
813 struct labhash **lhp, *lh;
817 for (h = 0, p = (u_char *)cp->t; (c = *p) != 0; p++)
818 h = (h << 5) + h + c;
819 lhp = &labels[h & LHMASK];
820 for (lh = *lhp; lh != NULL; lh = lh->lh_next)
821 if (lh->lh_hash == h && strcmp(cp->t, lh->lh_cmd->t) == 0)
822 errx(1, "%lu: %s: duplicate label '%s'", linenum, fname, cp->t);
823 if ((lh = malloc(sizeof *lh)) == NULL)
833 * Find the label contained in the command l in the command linked
834 * list cp. L is excluded from the search. Return NULL if not found.
836 static struct s_command *
844 for (h = 0, p = (u_char *)name; (c = *p) != 0; p++)
845 h = (h << 5) + h + c;
846 for (lh = labels[h & LHMASK]; lh != NULL; lh = lh->lh_next) {
847 if (lh->lh_hash == h && strcmp(name, lh->lh_cmd->t) == 0) {
856 * Warn about any unused labels. As a side effect, release the label hash
862 struct labhash *lh, *next;
865 for (i = 0; i < LHSZ; i++) {
866 for (lh = labels[i]; lh != NULL; lh = next) {
869 warnx("%lu: %s: unused label '%s'",
870 linenum, fname, lh->lh_cmd->t);