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. 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: head/usr.bin/sed/compile.c 289677 2015-10-21 05:37:09Z eadler $
37 #include <sys/types.h>
55 #define LHMASK (LHSZ - 1)
56 static struct labhash
{
57 struct labhash
*lh_next
;
59 struct s_command
*lh_cmd
;
63 static char *compile_addr(char *, struct s_addr
*);
64 static char *compile_ccl(char **, char *);
65 static char *compile_delimited(char *, char *, int);
66 static char *compile_flags(char *, struct s_subst
*);
67 static regex_t
*compile_re(char *, int);
68 static char *compile_subst(char *, struct s_subst
*);
69 static char *compile_text(void);
70 static char *compile_tr(char *, struct s_tr
**);
71 static struct s_command
72 **compile_stream(struct s_command
**);
73 static char *duptoeol(char *, const char *);
74 static void enterlabel(struct s_command
*);
75 static struct s_command
77 static void fixuplabel(struct s_command
*, struct s_command
*);
78 static void uselabel(void);
81 * Command specification. This is used to drive the command parser.
84 char code
; /* Command code */
85 int naddr
; /* Number of address args */
86 enum e_args args
; /* Argument type */
89 static struct s_format cmd_fmts
[] = {
121 /* The compiled program. */
122 struct s_command
*prog
;
125 * Compile the program into prog.
126 * Initialise appends.
131 *compile_stream(&prog
) = NULL
;
132 fixuplabel(prog
, NULL
);
136 else if ((appends
= malloc(sizeof(struct s_appends
) * appendnum
)) ==
139 if ((match
= malloc((maxnsub
+ 1) * sizeof(regmatch_t
))) == NULL
)
143 #define EATSPACE() do { \
145 while (*p && isspace((unsigned char)*p)) \
149 static struct s_command
**
150 compile_stream(struct s_command
**link
)
153 static char lbuf
[_POSIX2_LINE_MAX
+ 1]; /* To save stack */
154 struct s_command
*cmd
, *cmd2
, *stack
;
156 char re
[_POSIX2_LINE_MAX
+ 1];
157 int naddr
; /* Number of addresses */
161 if ((p
= cu_fgets(lbuf
, sizeof(lbuf
), NULL
)) == NULL
) {
163 errx(1, "%lu: %s: unexpected EOF (pending }'s)",
168 semicolon
: EATSPACE();
170 if (*p
== '#' || *p
== '\0')
172 else if (*p
== ';') {
177 if ((*link
= cmd
= malloc(sizeof(struct s_command
))) == NULL
)
180 cmd
->startline
= cmd
->nonsel
= 0;
181 /* First parse the addresses */
184 /* Valid characters to start an address */
185 #define addrchar(c) (strchr("0123456789/\\$", (c)))
188 if ((cmd
->a1
= malloc(sizeof(struct s_addr
))) == NULL
)
190 p
= compile_addr(p
, cmd
->a1
);
191 EATSPACE(); /* EXTENSION */
194 EATSPACE(); /* EXTENSION */
196 if ((cmd
->a2
= malloc(sizeof(struct s_addr
)))
199 p
= compile_addr(p
, cmd
->a2
);
204 cmd
->a1
= cmd
->a2
= 0;
206 nonsel
: /* Now parse the command */
208 errx(1, "%lu: %s: command expected", linenum
, fname
);
210 for (fp
= cmd_fmts
; fp
->code
; fp
++)
214 errx(1, "%lu: %s: invalid command code %c", linenum
, fname
, *p
);
215 if (naddr
> fp
->naddr
)
217 "%lu: %s: command %c expects up to %d address(es), found %d",
218 linenum
, fname
, *p
, fp
->naddr
, naddr
);
236 * Short-circuit command processing, since end of
237 * group is really just a noop.
241 errx(1, "%lu: %s: unexpected }", linenum
, fname
);
246 case EMPTY
: /* d D g G h H l n N p P q x = \0 */
255 errx(1, "%lu: %s: extra characters at the end of %c command",
256 linenum
, fname
, cmd
->code
);
258 case TEXT
: /* a c i */
263 "%lu: %s: command %c expects \\ followed by text", linenum
, fname
, cmd
->code
);
268 "%lu: %s: extra characters after \\ at the end of %c command",
269 linenum
, fname
, cmd
->code
);
270 cmd
->t
= compile_text();
272 case COMMENT
: /* \0 # */
278 errx(1, "%lu: %s: filename expected", linenum
, fname
);
279 cmd
->t
= duptoeol(p
, "w command");
282 else if ((cmd
->u
.fd
= open(p
,
283 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
291 errx(1, "%lu: %s: filename expected", linenum
, fname
);
293 cmd
->t
= duptoeol(p
, "read command");
295 case BRANCH
: /* b t */
301 cmd
->t
= duptoeol(p
, "branch");
306 cmd
->t
= duptoeol(p
, "label");
308 errx(1, "%lu: %s: empty label", linenum
, fname
);
313 if (*p
== '\0' || *p
== '\\')
315 "%lu: %s: substitute pattern can not be delimited by newline or backslash",
317 if ((cmd
->u
.s
= calloc(1, sizeof(struct s_subst
))) == NULL
)
319 p
= compile_delimited(p
, re
, 0);
322 "%lu: %s: unterminated substitute pattern", linenum
, fname
);
324 /* Compile RE with no case sensitivity temporarily */
328 cmd
->u
.s
->re
= compile_re(re
, 0);
330 p
= compile_subst(p
, cmd
->u
.s
);
331 p
= compile_flags(p
, cmd
->u
.s
);
333 /* Recompile RE with case sensitivity from "I" flag if any */
337 cmd
->u
.s
->re
= compile_re(re
, cmd
->u
.s
->icase
);
347 p
= compile_tr(p
, &cmd
->u
.y
);
356 "%lu: %s: extra text at the end of a transform command", linenum
, fname
);
363 * Get a delimited string. P points to the delimiter of the string; d points
364 * to a buffer area. Newline and delimiter escapes are processed; other
365 * escapes are ignored.
367 * Returns a pointer to the first character after the final delimiter or NULL
368 * in the case of a non-terminated string. The character array d is filled
369 * with the processed string.
372 compile_delimited(char *p
, char *d
, int is_tr
)
380 errx(1, "%lu: %s: \\ can not be used as a string delimiter",
383 errx(1, "%lu: %s: newline can not be used as a string delimiter",
386 if (*p
== '[' && *p
!= c
) {
387 if ((d
= compile_ccl(&p
, d
)) == NULL
)
388 errx(1, "%lu: %s: unbalanced brackets ([])", linenum
, fname
);
390 } else if (*p
== '\\' && p
[1] == '[') {
392 } else if (*p
== '\\' && p
[1] == c
)
394 else if (*p
== '\\' && p
[1] == 'n') {
398 } else if (*p
== '\\' && p
[1] == '\\') {
403 } else if (*p
== c
) {
413 /* compile_ccl: expand a POSIX character class */
415 compile_ccl(char **sp
, char *t
)
425 for (; *s
&& (*t
= *s
) != ']'; s
++, t
++)
426 if (*s
== '[' && ((d
= *(s
+1)) == '.' || d
== ':' || d
== '=')) {
427 *++t
= *++s
, t
++, s
++;
428 for (c
= *s
; (*t
= *s
) != ']' || c
!= d
; s
++, t
++)
429 if ((c
= *s
) == '\0')
432 return (*s
== ']') ? *sp
= ++s
, ++t
: NULL
;
436 * Compiles the regular expression in RE and returns a pointer to the compiled
437 * regular expression.
438 * Cflags are passed to regcomp.
441 compile_re(char *re
, int case_insensitive
)
448 if (case_insensitive
)
450 if ((rep
= malloc(sizeof(regex_t
))) == NULL
)
452 if ((eval
= regcomp(rep
, re
, flags
)) != 0)
453 errx(1, "%lu: %s: RE error: %s",
454 linenum
, fname
, strregerror(eval
, rep
));
455 if (maxnsub
< rep
->re_nsub
)
456 maxnsub
= rep
->re_nsub
;
461 * Compile the substitution string of a regular expression and set res to
462 * point to a saved copy of it. Nsub is the number of parenthesized regular
466 compile_subst(char *p
, struct s_subst
*s
)
468 static char lbuf
[_POSIX2_LINE_MAX
+ 1];
471 char c
, *text
, *op
, *sp
;
472 int more
= 1, sawesc
= 0;
474 c
= *p
++; /* Terminator character */
479 s
->linenum
= linenum
;
480 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
481 if ((text
= malloc(asize
)) == NULL
)
485 op
= sp
= text
+ size
;
487 if (*p
== '\\' || sawesc
) {
489 * If this is a continuation from the last
490 * buffer, we won't have a character to
500 * This escaped character is continued
501 * in the next part of the line. Note
502 * this fact, then cause the loop to
503 * exit w/ normal EOL case and reenter
504 * above with the new buffer.
509 } else if (strchr("123456789", *p
) != NULL
) {
513 ref
> s
->re
->re_nsub
)
514 errx(1, "%lu: %s: \\%c not defined in the RE",
516 if (s
->maxbref
< ref
)
518 } else if (*p
== '&' || *p
== '\\')
520 } else if (*p
== c
) {
521 if (*++p
== '\0' && more
) {
522 if (cu_fgets(lbuf
, sizeof(lbuf
), &more
))
527 if ((s
->new = realloc(text
, size
)) == NULL
)
530 } else if (*p
== '\n') {
532 "%lu: %s: unescaped newline inside substitute pattern", linenum
, fname
);
538 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
540 if ((text
= realloc(text
, asize
)) == NULL
)
543 } while (cu_fgets(p
= lbuf
, sizeof(lbuf
), &more
));
544 errx(1, "%lu: %s: unterminated substitute in regular expression",
550 * Compile the flags of the s command
553 compile_flags(char *p
, struct s_subst
*s
)
555 int gn
; /* True if we have seen g or n */
557 char wfile
[_POSIX2_LINE_MAX
+ 1], *q
, *eq
;
559 s
->n
= 1; /* Default */
565 EATSPACE(); /* EXTENSION */
570 "%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
);
593 nval
= strtol(p
, &p
, 10);
594 if (errno
== ERANGE
|| nval
> INT_MAX
)
596 "%lu: %s: overflow in the 'N' substitute flag", linenum
, fname
);
602 #ifdef HISTORIC_PRACTICE
604 warnx("%lu: %s: space missing before w wfile", linenum
, fname
);
610 eq
= wfile
+ sizeof(wfile
) - 1;
615 err(1, "wfile too long");
620 errx(1, "%lu: %s: no wfile specified", linenum
, fname
);
621 s
->wfile
= strdup(wfile
);
622 if (!aflag
&& (s
->wfd
= open(wfile
,
623 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
628 errx(1, "%lu: %s: bad flag in substitute command: '%c'",
637 * Compile a translation set of strings into a lookup table.
640 compile_tr(char *p
, struct s_tr
**py
)
645 char old
[_POSIX2_LINE_MAX
+ 1];
646 char new[_POSIX2_LINE_MAX
+ 1];
647 size_t oclen
, oldlen
, nclen
, newlen
;
648 mbstate_t mbs1
, mbs2
;
650 if ((*py
= y
= malloc(sizeof(*y
))) == NULL
)
655 if (*p
== '\0' || *p
== '\\')
657 "%lu: %s: transform pattern can not be delimited by newline or backslash",
659 p
= compile_delimited(p
, old
, 1);
661 errx(1, "%lu: %s: unterminated transform source string",
663 p
= compile_delimited(p
- 1, new, 1);
665 errx(1, "%lu: %s: unterminated transform target string",
669 oldlen
= mbsrtowcs(NULL
, &op
, 0, NULL
);
670 if (oldlen
== (size_t)-1)
673 newlen
= mbsrtowcs(NULL
, &np
, 0, NULL
);
674 if (newlen
== (size_t)-1)
676 if (newlen
!= oldlen
)
677 errx(1, "%lu: %s: transform strings are not the same length",
679 if (MB_CUR_MAX
== 1) {
681 * The single-byte encoding case is easy: generate a
684 for (i
= 0; i
<= UCHAR_MAX
; i
++)
685 y
->bytetab
[i
] = (char)i
;
686 for (; *op
; op
++, np
++)
687 y
->bytetab
[(u_char
)*op
] = *np
;
690 * Multi-byte encoding case: generate a lookup table as
691 * above, but only for single-byte characters. The first
692 * bytes of multi-byte characters have their lookup table
693 * entries set to 0, which causes do_tr() to search through
694 * an auxiliary vector of multi-byte mappings.
696 memset(&mbs1
, 0, sizeof(mbs1
));
697 memset(&mbs2
, 0, sizeof(mbs2
));
698 for (i
= 0; i
<= UCHAR_MAX
; i
++)
699 y
->bytetab
[i
] = (btowc(i
) != WEOF
) ? i
: 0;
700 while (*op
!= '\0') {
701 oclen
= mbrlen(op
, MB_LEN_MAX
, &mbs1
);
702 if (oclen
== (size_t)-1 || oclen
== (size_t)-2)
703 errc(1, EILSEQ
, NULL
);
704 nclen
= mbrlen(np
, MB_LEN_MAX
, &mbs2
);
705 if (nclen
== (size_t)-1 || nclen
== (size_t)-2)
706 errc(1, EILSEQ
, NULL
);
707 if (oclen
== 1 && nclen
== 1)
708 y
->bytetab
[(u_char
)*op
] = *np
;
710 y
->bytetab
[(u_char
)*op
] = 0;
711 y
->multis
= realloc(y
->multis
,
712 (y
->nmultis
+ 1) * sizeof(*y
->multis
));
713 if (y
->multis
== NULL
)
716 y
->multis
[i
].fromlen
= oclen
;
717 memcpy(y
->multis
[i
].from
, op
, oclen
);
718 y
->multis
[i
].tolen
= nclen
;
719 memcpy(y
->multis
[i
].to
, np
, nclen
);
729 * Compile the text following an a or i command.
734 int asize
, esc_nl
, size
;
735 char *text
, *p
, *op
, *s
;
736 char lbuf
[_POSIX2_LINE_MAX
+ 1];
738 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
739 if ((text
= malloc(asize
)) == NULL
)
742 while (cu_fgets(lbuf
, sizeof(lbuf
), NULL
)) {
743 op
= s
= text
+ size
;
746 for (esc_nl
= 0; *p
!= '\0'; p
++) {
747 if (*p
== '\\' && p
[1] != '\0' && *++p
== '\n')
756 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
758 if ((text
= realloc(text
, asize
)) == NULL
)
763 if ((p
= realloc(text
, size
+ 1)) == NULL
)
769 * Get an address and return a pointer to the first character after
770 * it. Fill the structure pointed to according to the address.
773 compile_addr(char *p
, struct s_addr
*a
)
775 char *end
, re
[_POSIX2_LINE_MAX
+ 1];
782 case '\\': /* Context address */
785 case '/': /* Context address */
786 p
= compile_delimited(p
, re
, 0);
788 errx(1, "%lu: %s: unterminated regular expression", linenum
, fname
);
789 /* Check for case insensitive regexp flag */
797 a
->u
.r
= compile_re(re
, icase
);
801 case '$': /* Last line */
805 case '+': /* Relative line number */
806 a
->type
= AT_RELLINE
;
810 case '0': case '1': case '2': case '3': case '4':
811 case '5': case '6': case '7': case '8': case '9':
814 a
->u
.l
= strtol(p
, &end
, 10);
817 errx(1, "%lu: %s: expected context address", linenum
, fname
);
824 * Return a copy of all the characters up to \n or \0.
827 duptoeol(char *s
, const char *ctype
)
834 for (start
= s
; *s
!= '\0' && *s
!= '\n'; ++s
)
835 ws
= isspace((unsigned char)*s
);
838 warnx("%lu: %s: whitespace after %s", linenum
, fname
, ctype
);
840 if ((p
= malloc(len
)) == NULL
)
842 return (memmove(p
, start
, len
));
846 * Convert goto label names to addresses, and count a and r commands, in
847 * the given subset of the script. Free the memory used by labels in b
848 * and t commands (but not by :).
850 * TODO: Remove } nodes
853 fixuplabel(struct s_command
*cp
, struct s_command
*end
)
856 for (; cp
!= end
; cp
= cp
->next
)
864 /* Resolve branch target. */
869 if ((cp
->u
.c
= findlabel(cp
->t
)) == NULL
)
870 errx(1, "%lu: %s: undefined label '%s'", linenum
, fname
, cp
->t
);
874 /* Do interior commands. */
875 fixuplabel(cp
->u
.c
, cp
->next
);
881 * Associate the given command label for later lookup.
884 enterlabel(struct s_command
*cp
)
886 struct labhash
**lhp
, *lh
;
890 for (h
= 0, p
= (u_char
*)cp
->t
; (c
= *p
) != 0; p
++)
891 h
= (h
<< 5) + h
+ c
;
892 lhp
= &labels
[h
& LHMASK
];
893 for (lh
= *lhp
; lh
!= NULL
; lh
= lh
->lh_next
)
894 if (lh
->lh_hash
== h
&& strcmp(cp
->t
, lh
->lh_cmd
->t
) == 0)
895 errx(1, "%lu: %s: duplicate label '%s'", linenum
, fname
, cp
->t
);
896 if ((lh
= malloc(sizeof *lh
)) == NULL
)
906 * Find the label contained in the command l in the command linked
907 * list cp. L is excluded from the search. Return NULL if not found.
909 static struct s_command
*
910 findlabel(char *name
)
916 for (h
= 0, p
= (u_char
*)name
; (c
= *p
) != 0; p
++)
917 h
= (h
<< 5) + h
+ c
;
918 for (lh
= labels
[h
& LHMASK
]; lh
!= NULL
; lh
= lh
->lh_next
) {
919 if (lh
->lh_hash
== h
&& strcmp(name
, lh
->lh_cmd
->t
) == 0) {
928 * Warn about any unused labels. As a side effect, release the label hash
934 struct labhash
*lh
, *next
;
937 for (i
= 0; i
< LHSZ
; i
++) {
938 for (lh
= labels
[i
]; lh
!= NULL
; lh
= next
) {
941 warnx("%lu: %s: unused label '%s'",
942 linenum
, fname
, lh
->lh_cmd
->t
);