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
37 * @(#)compile.c 8.1 (Berkeley) 6/6/93
38 * $FreeBSD: src/usr.bin/sed/compile.c,v 1.13.2.8 2002/08/17 05:47:06 tjr Exp $
39 * $DragonFly: src/usr.bin/sed/compile.c,v 1.3 2003/10/04 20:36:50 hmp Exp $
42 #include <sys/types.h>
58 #define LHMASK (LHSZ - 1)
59 static struct labhash
{
60 struct labhash
*lh_next
;
62 struct s_command
*lh_cmd
;
66 static char *compile_addr(char *, struct s_addr
*);
67 static char *compile_ccl(char **, char *);
68 static char *compile_delimited(char *, char *);
69 static char *compile_flags(char *, struct s_subst
*);
70 static char *compile_re(char *, regex_t
**);
71 static char *compile_subst(char *, struct s_subst
*);
72 static char *compile_text(void);
73 static char *compile_tr(char *, char **);
74 static struct s_command
75 **compile_stream(struct s_command
**);
76 static char *duptoeol(char *, const char *);
77 static void enterlabel(struct s_command
*);
78 static struct s_command
80 static void fixuplabel(struct s_command
*, struct s_command
*);
81 static void uselabel(void);
84 * Command specification. This is used to drive the command parser.
87 char code
; /* Command code */
88 int naddr
; /* Number of address args */
89 enum e_args args
; /* Argument type */
92 static struct s_format cmd_fmts
[] = {
124 /* The compiled program. */
125 struct s_command
*prog
;
128 * Compile the program into prog.
129 * Initialise appends.
134 *compile_stream(&prog
) = NULL
;
135 fixuplabel(prog
, NULL
);
139 else if ((appends
= malloc(sizeof(struct s_appends
) * appendnum
)) ==
142 if ((match
= malloc((maxnsub
+ 1) * sizeof(regmatch_t
))) == NULL
)
146 #define EATSPACE() do { \
148 while (*p && isspace((unsigned char)*p)) \
152 static struct s_command
**
153 compile_stream(struct s_command
**link
)
156 static char lbuf
[_POSIX2_LINE_MAX
+ 1]; /* To save stack */
157 struct s_command
*cmd
, *cmd2
, *stack
;
159 int naddr
; /* Number of addresses */
163 if ((p
= cu_fgets(lbuf
, sizeof(lbuf
), NULL
)) == NULL
) {
165 errx(1, "%lu: %s: unexpected EOF (pending }'s)",
170 semicolon
: EATSPACE();
172 if (*p
== '#' || *p
== '\0')
174 else if (*p
== ';') {
179 if ((*link
= cmd
= malloc(sizeof(struct s_command
))) == NULL
)
182 cmd
->nonsel
= cmd
->inrange
= 0;
183 /* First parse the addresses */
186 /* Valid characters to start an address */
187 #define addrchar(c) (strchr("0123456789/\\$", (c)))
190 if ((cmd
->a1
= malloc(sizeof(struct s_addr
))) == NULL
)
192 p
= compile_addr(p
, cmd
->a1
);
193 EATSPACE(); /* EXTENSION */
196 EATSPACE(); /* EXTENSION */
198 if ((cmd
->a2
= malloc(sizeof(struct s_addr
)))
201 p
= compile_addr(p
, cmd
->a2
);
206 cmd
->a1
= cmd
->a2
= 0;
208 nonsel
: /* Now parse the command */
210 errx(1, "%lu: %s: command expected", linenum
, fname
);
212 for (fp
= cmd_fmts
; fp
->code
; fp
++)
216 errx(1, "%lu: %s: invalid command code %c", linenum
, fname
, *p
);
217 if (naddr
> fp
->naddr
)
219 "%lu: %s: command %c expects up to %d address(es), found %d",
220 linenum
, fname
, *p
, fp
->naddr
, naddr
);
225 cmd
->nonsel
= ! cmd
->nonsel
;
238 * Short-circuit command processing, since end of
239 * group is really just a noop.
243 errx(1, "%lu: %s: unexpected }", linenum
, fname
);
248 case EMPTY
: /* d D g G h H l n N p P q x = \0 */
257 errx(1, "%lu: %s: extra characters at the end of %c command",
258 linenum
, fname
, cmd
->code
);
260 case TEXT
: /* a c i */
265 "%lu: %s: command %c expects \\ followed by text", linenum
, fname
, cmd
->code
);
270 "%lu: %s: extra characters after \\ at the end of %c command",
271 linenum
, fname
, cmd
->code
);
272 cmd
->t
= compile_text();
274 case COMMENT
: /* \0 # */
280 errx(1, "%lu: %s: filename expected", linenum
, fname
);
281 cmd
->t
= duptoeol(p
, "w command");
284 else if ((cmd
->u
.fd
= open(p
,
285 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
293 errx(1, "%lu: %s: filename expected", linenum
, fname
);
295 cmd
->t
= duptoeol(p
, "read command");
297 case BRANCH
: /* b t */
303 cmd
->t
= duptoeol(p
, "branch");
308 cmd
->t
= duptoeol(p
, "label");
310 errx(1, "%lu: %s: empty label", linenum
, fname
);
315 if (*p
== '\0' || *p
== '\\')
317 "%lu: %s: substitute pattern can not be delimited by newline or backslash",
319 if ((cmd
->u
.s
= malloc(sizeof(struct s_subst
))) == NULL
)
321 p
= compile_re(p
, &cmd
->u
.s
->re
);
324 "%lu: %s: unterminated substitute pattern", linenum
, fname
);
326 p
= compile_subst(p
, cmd
->u
.s
);
327 p
= compile_flags(p
, cmd
->u
.s
);
337 p
= compile_tr(p
, (char **)&cmd
->u
.y
);
346 "%lu: %s: extra text at the end of a transform command", linenum
, fname
);
353 * Get a delimited string. P points to the delimeter of the string; d points
354 * to a buffer area. Newline and delimiter escapes are processed; other
355 * escapes are ignored.
357 * Returns a pointer to the first character after the final delimiter or NULL
358 * in the case of a non-terminated string. The character array d is filled
359 * with the processed string.
362 compile_delimited(char *p
, char *d
)
370 errx(1, "%lu: %s: \\ can not be used as a string delimiter",
373 errx(1, "%lu: %s: newline can not be used as a string delimiter",
377 if ((d
= compile_ccl(&p
, d
)) == NULL
)
378 errx(1, "%lu: %s: unbalanced brackets ([])", linenum
, fname
);
380 } else if (*p
== '\\' && p
[1] == '[') {
382 } else if (*p
== '\\' && p
[1] == c
)
384 else if (*p
== '\\' && p
[1] == 'n') {
388 } else if (*p
== '\\' && p
[1] == '\\')
400 /* compile_ccl: expand a POSIX character class */
402 compile_ccl(char **sp
, char *t
)
412 for (; *s
&& (*t
= *s
) != ']'; s
++, t
++)
413 if (*s
== '[' && ((d
= *(s
+1)) == '.' || d
== ':' || d
== '=')) {
414 *++t
= *++s
, t
++, s
++;
415 for (c
= *s
; (*t
= *s
) != ']' || c
!= d
; s
++, t
++)
416 if ((c
= *s
) == '\0')
418 } else if (*s
== '\\' && s
[1] == 'n')
420 return (*s
== ']') ? *sp
= ++s
, ++t
: NULL
;
424 * Get a regular expression. P points to the delimiter of the regular
425 * expression; repp points to the address of a regexp pointer. Newline
426 * and delimiter escapes are processed; other escapes are ignored.
427 * Returns a pointer to the first character after the final delimiter
428 * or NULL in the case of a non terminated regular expression. The regexp
429 * pointer is set to the compiled regular expression.
430 * Cflags are passed to regcomp.
433 compile_re(char *p
, regex_t
**repp
)
436 char re
[_POSIX2_LINE_MAX
+ 1];
438 p
= compile_delimited(p
, re
);
439 if (p
&& strlen(re
) == 0) {
443 if ((*repp
= malloc(sizeof(regex_t
))) == NULL
)
445 if (p
&& (eval
= regcomp(*repp
, re
, rflags
)) != 0)
446 errx(1, "%lu: %s: RE error: %s",
447 linenum
, fname
, strregerror(eval
, *repp
));
448 if (maxnsub
< (*repp
)->re_nsub
)
449 maxnsub
= (*repp
)->re_nsub
;
454 * Compile the substitution string of a regular expression and set res to
455 * point to a saved copy of it. Nsub is the number of parenthesized regular
459 compile_subst(char *p
, struct s_subst
*s
)
461 static char lbuf
[_POSIX2_LINE_MAX
+ 1];
464 char c
, *text
, *op
, *sp
;
465 int more
= 1, sawesc
= 0;
467 c
= *p
++; /* Terminator character */
472 s
->linenum
= linenum
;
473 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
474 if ((text
= malloc(asize
)) == NULL
)
478 op
= sp
= text
+ size
;
480 if (*p
== '\\' || sawesc
) {
482 * If this is a continuation from the last
483 * buffer, we won't have a character to
493 * This escaped character is continued
494 * in the next part of the line. Note
495 * this fact, then cause the loop to
496 * exit w/ normal EOL case and reenter
497 * above with the new buffer.
502 } else if (strchr("123456789", *p
) != NULL
) {
506 ref
> s
->re
->re_nsub
)
507 errx(1, "%lu: %s: \\%c not defined in the RE",
509 if (s
->maxbref
< ref
)
511 } else if (*p
== '&' || *p
== '\\')
513 } else if (*p
== c
) {
514 if (*++p
== '\0' && more
) {
515 if (cu_fgets(lbuf
, sizeof(lbuf
), &more
))
520 if ((s
->new = realloc(text
, size
)) == NULL
)
523 } else if (*p
== '\n') {
525 "%lu: %s: unescaped newline inside substitute pattern", linenum
, fname
);
531 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
533 if ((text
= realloc(text
, asize
)) == NULL
)
536 } while (cu_fgets(p
= lbuf
, sizeof(lbuf
), &more
));
537 errx(1, "%lu: %s: unterminated substitute in regular expression",
543 * Compile the flags of the s command
546 compile_flags(char *p
, struct s_subst
*s
)
548 int gn
; /* True if we have seen g or n */
549 char wfile
[_POSIX2_LINE_MAX
+ 1], *q
;
551 s
->n
= 1; /* Default */
556 EATSPACE(); /* EXTENSION */
561 "%lu: %s: more than one number or 'g' in substitute flags", linenum
, fname
);
572 case '1': case '2': case '3':
573 case '4': case '5': case '6':
574 case '7': case '8': case '9':
577 "%lu: %s: more than one number or 'g' in substitute flags", linenum
, fname
);
579 /* XXX Check for overflow */
580 s
->n
= (int)strtol(p
, &p
, 10);
584 #ifdef HISTORIC_PRACTICE
586 warnx("%lu: %s: space missing before w wfile", linenum
, fname
);
599 errx(1, "%lu: %s: no wfile specified", linenum
, fname
);
600 s
->wfile
= strdup(wfile
);
601 if (!aflag
&& (s
->wfd
= open(wfile
,
602 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
607 errx(1, "%lu: %s: bad flag in substitute command: '%c'",
616 * Compile a translation set of strings into a lookup table.
619 compile_tr(char *p
, char **transtab
)
623 char old
[_POSIX2_LINE_MAX
+ 1];
624 char new[_POSIX2_LINE_MAX
+ 1];
626 if (*p
== '\0' || *p
== '\\')
628 "%lu: %s: transform pattern can not be delimited by newline or backslash",
630 p
= compile_delimited(p
, old
);
632 errx(1, "%lu: %s: unterminated transform source string",
634 p
= compile_delimited(--p
, new);
636 errx(1, "%lu: %s: unterminated transform target string",
639 if (strlen(new) != strlen(old
))
640 errx(1, "%lu: %s: transform strings are not the same length",
642 /* We assume characters are 8 bits */
643 if ((lt
= malloc(UCHAR_MAX
)) == NULL
)
645 for (i
= 0; i
<= UCHAR_MAX
; i
++)
647 for (op
= old
, np
= new; *op
; op
++, np
++)
648 lt
[(u_char
)*op
] = *np
;
654 * Compile the text following an a or i command.
659 int asize
, esc_nl
, size
;
660 char *text
, *p
, *op
, *s
;
661 char lbuf
[_POSIX2_LINE_MAX
+ 1];
663 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
664 if ((text
= malloc(asize
)) == NULL
)
667 while (cu_fgets(lbuf
, sizeof(lbuf
), NULL
)) {
668 op
= s
= text
+ size
;
671 for (esc_nl
= 0; *p
!= '\0'; p
++) {
672 if (*p
== '\\' && p
[1] != '\0' && *++p
== '\n')
681 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
683 if ((text
= realloc(text
, asize
)) == NULL
)
688 if ((p
= realloc(text
, size
+ 1)) == NULL
)
694 * Get an address and return a pointer to the first character after
695 * it. Fill the structure pointed to according to the address.
698 compile_addr(char *p
, struct s_addr
*a
)
703 case '\\': /* Context address */
706 case '/': /* Context address */
707 p
= compile_re(p
, &a
->u
.r
);
709 errx(1, "%lu: %s: unterminated regular expression", linenum
, fname
);
713 case '$': /* Last line */
717 case '0': case '1': case '2': case '3': case '4':
718 case '5': case '6': case '7': case '8': case '9':
720 a
->u
.l
= strtol(p
, &end
, 10);
723 errx(1, "%lu: %s: expected context address", linenum
, fname
);
730 * Return a copy of all the characters up to \n or \0.
733 duptoeol(char *s
, const char *ctype
)
740 for (start
= s
; *s
!= '\0' && *s
!= '\n'; ++s
)
741 ws
= isspace((unsigned char)*s
);
744 warnx("%lu: %s: whitespace after %s", linenum
, fname
, ctype
);
746 if ((p
= malloc(len
)) == NULL
)
748 return (memmove(p
, start
, len
));
752 * Convert goto label names to addresses, and count a and r commands, in
753 * the given subset of the script. Free the memory used by labels in b
754 * and t commands (but not by :).
756 * TODO: Remove } nodes
759 fixuplabel(struct s_command
*cp
, struct s_command
*end
)
762 for (; cp
!= end
; cp
= cp
->next
)
770 /* Resolve branch target. */
775 if ((cp
->u
.c
= findlabel(cp
->t
)) == NULL
)
776 errx(1, "%lu: %s: undefined label '%s'", linenum
, fname
, cp
->t
);
780 /* Do interior commands. */
781 fixuplabel(cp
->u
.c
, cp
->next
);
787 * Associate the given command label for later lookup.
790 enterlabel(struct s_command
*cp
)
792 struct labhash
**lhp
, *lh
;
796 for (h
= 0, p
= (u_char
*)cp
->t
; (c
= *p
) != 0; p
++)
797 h
= (h
<< 5) + h
+ c
;
798 lhp
= &labels
[h
& LHMASK
];
799 for (lh
= *lhp
; lh
!= NULL
; lh
= lh
->lh_next
)
800 if (lh
->lh_hash
== h
&& strcmp(cp
->t
, lh
->lh_cmd
->t
) == 0)
801 errx(1, "%lu: %s: duplicate label '%s'", linenum
, fname
, cp
->t
);
802 if ((lh
= malloc(sizeof *lh
)) == NULL
)
812 * Find the label contained in the command l in the command linked
813 * list cp. L is excluded from the search. Return NULL if not found.
815 static struct s_command
*
816 findlabel(char *name
)
822 for (h
= 0, p
= (u_char
*)name
; (c
= *p
) != 0; p
++)
823 h
= (h
<< 5) + h
+ c
;
824 for (lh
= labels
[h
& LHMASK
]; lh
!= NULL
; lh
= lh
->lh_next
) {
825 if (lh
->lh_hash
== h
&& strcmp(name
, lh
->lh_cmd
->t
) == 0) {
834 * Warn about any unused labels. As a side effect, release the label hash
840 struct labhash
*lh
, *next
;
843 for (i
= 0; i
< LHSZ
; i
++) {
844 for (lh
= labels
[i
]; lh
!= NULL
; lh
= next
) {
847 warnx("%lu: %s: unused label '%s'",
848 linenum
, fname
, lh
->lh_cmd
->t
);