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 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#)compile.c 8.1 (Berkeley) 6/6/93
34 * $FreeBSD: src/usr.bin/sed/compile.c,v 1.31 2008/02/09 09:12:02 dwmalone Exp $
35 * $DragonFly: src/usr.bin/sed/compile.c,v 1.4 2008/04/08 13:23:38 swildner Exp $
38 #include <sys/types.h>
56 #define LHMASK (LHSZ - 1)
57 static struct labhash
{
58 struct labhash
*lh_next
;
60 struct s_command
*lh_cmd
;
64 static char *compile_addr(char *, struct s_addr
*);
65 static char *compile_ccl(char **, char *);
66 static char *compile_delimited(char *, char *);
67 static char *compile_flags(char *, struct s_subst
*);
68 static regex_t
*compile_re(char *, int);
69 static char *compile_subst(char *, struct s_subst
*);
70 static char *compile_text(void);
71 static char *compile_tr(char *, struct s_tr
**);
72 static struct s_command
73 **compile_stream(struct s_command
**);
74 static char *duptoeol(char *, const char *);
75 static void enterlabel(struct s_command
*);
76 static struct s_command
78 static void fixuplabel(struct s_command
*, struct s_command
*);
79 static void uselabel(void);
82 * Command specification. This is used to drive the command parser.
85 char code
; /* Command code */
86 int naddr
; /* Number of address args */
87 enum e_args args
; /* Argument type */
90 static struct s_format cmd_fmts
[] = {
122 /* The compiled program. */
123 struct s_command
*prog
;
126 * Compile the program into prog.
127 * Initialise appends.
132 *compile_stream(&prog
) = NULL
;
133 fixuplabel(prog
, NULL
);
137 else if ((appends
= malloc(sizeof(struct s_appends
) * appendnum
)) ==
140 if ((match
= malloc((maxnsub
+ 1) * sizeof(regmatch_t
))) == NULL
)
144 #define EATSPACE() do { \
146 while (*p && isspace((unsigned char)*p)) \
150 static struct s_command
**
151 compile_stream(struct s_command
**link
)
154 static char lbuf
[_POSIX2_LINE_MAX
+ 1]; /* To save stack */
155 struct s_command
*cmd
, *cmd2
, *stack
;
157 char re
[_POSIX2_LINE_MAX
+ 1];
158 int naddr
; /* Number of addresses */
162 if ((p
= cu_fgets(lbuf
, sizeof(lbuf
), NULL
)) == NULL
) {
164 errx(1, "%lu: %s: unexpected EOF (pending }'s)",
169 semicolon
: EATSPACE();
171 if (*p
== '#' || *p
== '\0')
173 else if (*p
== ';') {
178 if ((*link
= cmd
= malloc(sizeof(struct s_command
))) == NULL
)
181 cmd
->nonsel
= cmd
->inrange
= 0;
182 /* First parse the addresses */
185 /* Valid characters to start an address */
186 #define addrchar(c) (strchr("0123456789/\\$", (c)))
189 if ((cmd
->a1
= malloc(sizeof(struct s_addr
))) == NULL
)
191 p
= compile_addr(p
, cmd
->a1
);
192 EATSPACE(); /* EXTENSION */
195 EATSPACE(); /* EXTENSION */
197 if ((cmd
->a2
= malloc(sizeof(struct s_addr
)))
200 p
= compile_addr(p
, cmd
->a2
);
205 cmd
->a1
= cmd
->a2
= 0;
207 nonsel
: /* Now parse the command */
209 errx(1, "%lu: %s: command expected", linenum
, fname
);
211 for (fp
= cmd_fmts
; fp
->code
; fp
++)
215 errx(1, "%lu: %s: invalid command code %c", linenum
, fname
, *p
);
216 if (naddr
> fp
->naddr
)
218 "%lu: %s: command %c expects up to %d address(es), found %d",
219 linenum
, fname
, *p
, fp
->naddr
, naddr
);
224 cmd
->nonsel
= ! cmd
->nonsel
;
237 * Short-circuit command processing, since end of
238 * group is really just a noop.
242 errx(1, "%lu: %s: unexpected }", linenum
, fname
);
247 case EMPTY
: /* d D g G h H l n N p P q x = \0 */
256 errx(1, "%lu: %s: extra characters at the end of %c command",
257 linenum
, fname
, cmd
->code
);
259 case TEXT
: /* a c i */
264 "%lu: %s: command %c expects \\ followed by text", linenum
, fname
, cmd
->code
);
269 "%lu: %s: extra characters after \\ at the end of %c command",
270 linenum
, fname
, cmd
->code
);
271 cmd
->t
= compile_text();
273 case COMMENT
: /* \0 # */
279 errx(1, "%lu: %s: filename expected", linenum
, fname
);
280 cmd
->t
= duptoeol(p
, "w command");
283 else if ((cmd
->u
.fd
= open(p
,
284 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
292 errx(1, "%lu: %s: filename expected", linenum
, fname
);
294 cmd
->t
= duptoeol(p
, "read command");
296 case BRANCH
: /* b t */
302 cmd
->t
= duptoeol(p
, "branch");
307 cmd
->t
= duptoeol(p
, "label");
309 errx(1, "%lu: %s: empty label", linenum
, fname
);
314 if (*p
== '\0' || *p
== '\\')
316 "%lu: %s: substitute pattern can not be delimited by newline or backslash",
318 if ((cmd
->u
.s
= calloc(1, sizeof(struct s_subst
))) == NULL
)
320 p
= compile_delimited(p
, re
);
323 "%lu: %s: unterminated substitute pattern", linenum
, fname
);
325 p
= compile_subst(p
, cmd
->u
.s
);
326 p
= compile_flags(p
, cmd
->u
.s
);
330 cmd
->u
.s
->re
= compile_re(re
, cmd
->u
.s
->icase
);
340 p
= compile_tr(p
, &cmd
->u
.y
);
349 "%lu: %s: extra text at the end of a transform command", linenum
, fname
);
356 * Get a delimited string. P points to the delimeter of the string; d points
357 * to a buffer area. Newline and delimiter escapes are processed; other
358 * escapes are ignored.
360 * Returns a pointer to the first character after the final delimiter or NULL
361 * in the case of a non-terminated string. The character array d is filled
362 * with the processed string.
365 compile_delimited(char *p
, char *d
)
373 errx(1, "%lu: %s: \\ can not be used as a string delimiter",
376 errx(1, "%lu: %s: newline can not be used as a string delimiter",
380 if ((d
= compile_ccl(&p
, d
)) == NULL
)
381 errx(1, "%lu: %s: unbalanced brackets ([])", linenum
, fname
);
383 } else if (*p
== '\\' && p
[1] == '[') {
385 } else if (*p
== '\\' && p
[1] == c
)
387 else if (*p
== '\\' && p
[1] == 'n') {
391 } else if (*p
== '\\' && p
[1] == '\\')
403 /* compile_ccl: expand a POSIX character class */
405 compile_ccl(char **sp
, char *t
)
415 for (; *s
&& (*t
= *s
) != ']'; s
++, t
++)
416 if (*s
== '[' && ((d
= *(s
+1)) == '.' || d
== ':' || d
== '=')) {
417 *++t
= *++s
, t
++, s
++;
418 for (c
= *s
; (*t
= *s
) != ']' || c
!= d
; s
++, t
++)
419 if ((c
= *s
) == '\0')
421 } else if (*s
== '\\' && s
[1] == 'n')
423 return (*s
== ']') ? *sp
= ++s
, ++t
: NULL
;
427 * Compiles the regular expression in RE and returns a pointer to the compiled
428 * regular expression.
429 * Cflags are passed to regcomp.
432 compile_re(char *re
, int case_insensitive
)
439 if (case_insensitive
)
441 if ((rep
= malloc(sizeof(regex_t
))) == NULL
)
443 if ((eval
= regcomp(rep
, re
, flags
)) != 0)
444 errx(1, "%lu: %s: RE error: %s",
445 linenum
, fname
, strregerror(eval
, rep
));
446 if (maxnsub
< rep
->re_nsub
)
447 maxnsub
= rep
->re_nsub
;
452 * Compile the substitution string of a regular expression and set res to
453 * point to a saved copy of it. Nsub is the number of parenthesized regular
457 compile_subst(char *p
, struct s_subst
*s
)
459 static char lbuf
[_POSIX2_LINE_MAX
+ 1];
462 char c
, *text
, *op
, *sp
;
463 int more
= 1, sawesc
= 0;
465 c
= *p
++; /* Terminator character */
470 s
->linenum
= linenum
;
471 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
472 if ((text
= malloc(asize
)) == NULL
)
476 op
= sp
= text
+ size
;
478 if (*p
== '\\' || sawesc
) {
480 * If this is a continuation from the last
481 * buffer, we won't have a character to
491 * This escaped character is continued
492 * in the next part of the line. Note
493 * this fact, then cause the loop to
494 * exit w/ normal EOL case and reenter
495 * above with the new buffer.
500 } else if (strchr("123456789", *p
) != NULL
) {
504 ref
> s
->re
->re_nsub
)
505 errx(1, "%lu: %s: \\%c not defined in the RE",
507 if (s
->maxbref
< ref
)
509 } else if (*p
== '&' || *p
== '\\')
511 } else if (*p
== c
) {
512 if (*++p
== '\0' && more
) {
513 if (cu_fgets(lbuf
, sizeof(lbuf
), &more
))
518 if ((s
->new = realloc(text
, size
)) == NULL
)
521 } else if (*p
== '\n') {
523 "%lu: %s: unescaped newline inside substitute pattern", linenum
, fname
);
529 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
531 if ((text
= realloc(text
, asize
)) == NULL
)
534 } while (cu_fgets(p
= lbuf
, sizeof(lbuf
), &more
));
535 errx(1, "%lu: %s: unterminated substitute in regular expression",
541 * Compile the flags of the s command
544 compile_flags(char *p
, struct s_subst
*s
)
546 int gn
; /* True if we have seen g or n */
548 char wfile
[_POSIX2_LINE_MAX
+ 1], *q
;
550 s
->n
= 1; /* Default */
556 EATSPACE(); /* EXTENSION */
561 "%lu: %s: more than one number or 'g' in substitute flags", linenum
, fname
);
575 case '1': case '2': case '3':
576 case '4': case '5': case '6':
577 case '7': case '8': case '9':
580 "%lu: %s: more than one number or 'g' in substitute flags", linenum
, fname
);
583 nval
= strtol(p
, &p
, 10);
584 if (errno
== ERANGE
|| nval
> INT_MAX
)
586 "%lu: %s: overflow in the 'N' substitute flag", linenum
, fname
);
592 #ifdef HISTORIC_PRACTICE
594 warnx("%lu: %s: space missing before w wfile", linenum
, fname
);
607 errx(1, "%lu: %s: no wfile specified", linenum
, fname
);
608 s
->wfile
= strdup(wfile
);
609 if (!aflag
&& (s
->wfd
= open(wfile
,
610 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
615 errx(1, "%lu: %s: bad flag in substitute command: '%c'",
624 * Compile a translation set of strings into a lookup table.
627 compile_tr(char *p
, struct s_tr
**py
)
632 char old
[_POSIX2_LINE_MAX
+ 1];
633 char new[_POSIX2_LINE_MAX
+ 1];
634 size_t oclen
, oldlen
, nclen
, newlen
;
635 mbstate_t mbs1
, mbs2
;
637 if ((*py
= y
= malloc(sizeof(*y
))) == NULL
)
642 if (*p
== '\0' || *p
== '\\')
644 "%lu: %s: transform pattern can not be delimited by newline or backslash",
646 p
= compile_delimited(p
, old
);
648 errx(1, "%lu: %s: unterminated transform source string",
650 p
= compile_delimited(p
- 1, new);
652 errx(1, "%lu: %s: unterminated transform target string",
656 oldlen
= mbsrtowcs(NULL
, &op
, 0, NULL
);
657 if (oldlen
== (size_t)-1)
660 newlen
= mbsrtowcs(NULL
, &np
, 0, NULL
);
661 if (newlen
== (size_t)-1)
663 if (newlen
!= oldlen
)
664 errx(1, "%lu: %s: transform strings are not the same length",
666 if (MB_CUR_MAX
== 1) {
668 * The single-byte encoding case is easy: generate a
671 for (i
= 0; i
<= UCHAR_MAX
; i
++)
672 y
->bytetab
[i
] = (char)i
;
673 for (; *op
; op
++, np
++)
674 y
->bytetab
[(u_char
)*op
] = *np
;
677 * Multi-byte encoding case: generate a lookup table as
678 * above, but only for single-byte characters. The first
679 * bytes of multi-byte characters have their lookup table
680 * entries set to 0, which causes do_tr() to search through
681 * an auxiliary vector of multi-byte mappings.
683 memset(&mbs1
, 0, sizeof(mbs1
));
684 memset(&mbs2
, 0, sizeof(mbs2
));
685 for (i
= 0; i
<= UCHAR_MAX
; i
++)
686 y
->bytetab
[i
] = (btowc(i
) != WEOF
) ? i
: 0;
687 while (*op
!= '\0') {
688 oclen
= mbrlen(op
, MB_LEN_MAX
, &mbs1
);
689 if (oclen
== (size_t)-1 || oclen
== (size_t)-2)
690 errc(1, EILSEQ
, NULL
);
691 nclen
= mbrlen(np
, MB_LEN_MAX
, &mbs2
);
692 if (nclen
== (size_t)-1 || nclen
== (size_t)-2)
693 errc(1, EILSEQ
, NULL
);
694 if (oclen
== 1 && nclen
== 1)
695 y
->bytetab
[(u_char
)*op
] = *np
;
697 y
->bytetab
[(u_char
)*op
] = 0;
698 y
->multis
= realloc(y
->multis
,
699 (y
->nmultis
+ 1) * sizeof(*y
->multis
));
700 if (y
->multis
== NULL
)
703 y
->multis
[i
].fromlen
= oclen
;
704 memcpy(y
->multis
[i
].from
, op
, oclen
);
705 y
->multis
[i
].tolen
= nclen
;
706 memcpy(y
->multis
[i
].to
, np
, nclen
);
716 * Compile the text following an a or i command.
721 int asize
, esc_nl
, size
;
722 char *text
, *p
, *op
, *s
;
723 char lbuf
[_POSIX2_LINE_MAX
+ 1];
725 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
726 if ((text
= malloc(asize
)) == NULL
)
729 while (cu_fgets(lbuf
, sizeof(lbuf
), NULL
)) {
730 op
= s
= text
+ size
;
733 for (esc_nl
= 0; *p
!= '\0'; p
++) {
734 if (*p
== '\\' && p
[1] != '\0' && *++p
== '\n')
743 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
745 if ((text
= realloc(text
, asize
)) == NULL
)
750 if ((p
= realloc(text
, size
+ 1)) == NULL
)
756 * Get an address and return a pointer to the first character after
757 * it. Fill the structure pointed to according to the address.
760 compile_addr(char *p
, struct s_addr
*a
)
762 char *end
, re
[_POSIX2_LINE_MAX
+ 1];
768 case '\\': /* Context address */
771 case '/': /* Context address */
772 p
= compile_delimited(p
, re
);
774 errx(1, "%lu: %s: unterminated regular expression", linenum
, fname
);
775 /* Check for case insensitive regexp flag */
783 a
->u
.r
= compile_re(re
, icase
);
787 case '$': /* Last line */
791 case '0': case '1': case '2': case '3': case '4':
792 case '5': case '6': case '7': case '8': case '9':
794 a
->u
.l
= strtol(p
, &end
, 10);
797 errx(1, "%lu: %s: expected context address", linenum
, fname
);
804 * Return a copy of all the characters up to \n or \0.
807 duptoeol(char *s
, const char *ctype
)
814 for (start
= s
; *s
!= '\0' && *s
!= '\n'; ++s
)
815 ws
= isspace((unsigned char)*s
);
818 warnx("%lu: %s: whitespace after %s", linenum
, fname
, ctype
);
820 if ((p
= malloc(len
)) == NULL
)
822 return (memmove(p
, start
, len
));
826 * Convert goto label names to addresses, and count a and r commands, in
827 * the given subset of the script. Free the memory used by labels in b
828 * and t commands (but not by :).
830 * TODO: Remove } nodes
833 fixuplabel(struct s_command
*cp
, struct s_command
*end
)
836 for (; cp
!= end
; cp
= cp
->next
)
844 /* Resolve branch target. */
849 if ((cp
->u
.c
= findlabel(cp
->t
)) == NULL
)
850 errx(1, "%lu: %s: undefined label '%s'", linenum
, fname
, cp
->t
);
854 /* Do interior commands. */
855 fixuplabel(cp
->u
.c
, cp
->next
);
861 * Associate the given command label for later lookup.
864 enterlabel(struct s_command
*cp
)
866 struct labhash
**lhp
, *lh
;
870 for (h
= 0, p
= (u_char
*)cp
->t
; (c
= *p
) != 0; p
++)
871 h
= (h
<< 5) + h
+ c
;
872 lhp
= &labels
[h
& LHMASK
];
873 for (lh
= *lhp
; lh
!= NULL
; lh
= lh
->lh_next
)
874 if (lh
->lh_hash
== h
&& strcmp(cp
->t
, lh
->lh_cmd
->t
) == 0)
875 errx(1, "%lu: %s: duplicate label '%s'", linenum
, fname
, cp
->t
);
876 if ((lh
= malloc(sizeof *lh
)) == NULL
)
886 * Find the label contained in the command l in the command linked
887 * list cp. L is excluded from the search. Return NULL if not found.
889 static struct s_command
*
890 findlabel(char *name
)
896 for (h
= 0, p
= (u_char
*)name
; (c
= *p
) != 0; p
++)
897 h
= (h
<< 5) + h
+ c
;
898 for (lh
= labels
[h
& LHMASK
]; lh
!= NULL
; lh
= lh
->lh_next
) {
899 if (lh
->lh_hash
== h
&& strcmp(name
, lh
->lh_cmd
->t
) == 0) {
908 * Warn about any unused labels. As a side effect, release the label hash
914 struct labhash
*lh
, *next
;
917 for (i
= 0; i
< LHSZ
; i
++) {
918 for (lh
= labels
[i
]; lh
!= NULL
; lh
= next
) {
921 warnx("%lu: %s: unused label '%s'",
922 linenum
, fname
, lh
->lh_cmd
->t
);