]>
git.cameronkatri.com Git - apple_cmds.git/blob - text_cmds/sed/compile.c
2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1992 Diomidis Spinellis.
5 * Copyright (c) 1992, 1993
6 * The Regents of the University of California. All rights reserved.
8 * This code is derived from software contributed to Berkeley by
9 * Diomidis Spinellis of Imperial College, University of London.
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
40 static const char sccsid
[] = "@(#)compile.c 8.1 (Berkeley) 6/6/93";
43 #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 *, int);
72 static char *compile_flags(char *, struct s_subst
*);
73 static regex_t
*compile_re(char *, int);
74 static char *compile_subst(char *, struct s_subst
*);
75 static char *compile_text(void);
76 static char *compile_tr(char *, struct s_tr
**);
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
**
156 compile_stream(struct s_command
**link
)
159 static char lbuf
[_POSIX2_LINE_MAX
+ 1]; /* To save stack */
160 struct s_command
*cmd
, *cmd2
, *stack
;
162 char re
[_POSIX2_LINE_MAX
+ 1];
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
->startline
= cmd
->nonsel
= 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
= NULL
;
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
);
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
= calloc(1, sizeof(struct s_subst
))) == NULL
)
325 p
= compile_delimited(p
, re
, 0);
328 "%lu: %s: unterminated substitute pattern", linenum
, fname
);
330 /* Compile RE with no case sensitivity temporarily */
334 cmd
->u
.s
->re
= compile_re(re
, 0);
336 p
= compile_subst(p
, cmd
->u
.s
);
337 p
= compile_flags(p
, cmd
->u
.s
);
339 /* Recompile RE with case sensitivity from "I" flag if any */
343 cmd
->u
.s
->re
= compile_re(re
, cmd
->u
.s
->icase
);
353 p
= compile_tr(p
, &cmd
->u
.y
);
362 "%lu: %s: extra text at the end of a transform command", linenum
, fname
);
369 * Get a delimited string. P points to the delimiter of the string; d points
370 * to a buffer area. Newline and delimiter escapes are processed; other
371 * escapes are ignored.
373 * Returns a pointer to the first character after the final delimiter or NULL
374 * in the case of a non-terminated string. The character array d is filled
375 * with the processed string.
378 compile_delimited(char *p
, char *d
, int is_tr
)
386 errx(1, "%lu: %s: \\ can not be used as a string delimiter",
389 errx(1, "%lu: %s: newline can not be used as a string delimiter",
392 if (*p
== '[' && *p
!= c
) {
393 if ((d
= compile_ccl(&p
, d
)) == NULL
)
394 errx(1, "%lu: %s: unbalanced brackets ([])", linenum
, fname
);
396 } else if (*p
== '\\' && p
[1] == '[') {
398 } else if (*p
== '\\' && p
[1] == c
) {
400 } else if (*p
== '\\' &&
401 (p
[1] == 'n' || p
[1] == 'r' || p
[1] == 't')) {
415 } else if (*p
== '\\' && p
[1] == '\\') {
420 } else if (*p
== c
) {
430 /* compile_ccl: expand a POSIX character class */
432 compile_ccl(char **sp
, char *t
)
442 for (; *s
&& (*t
= *s
) != ']'; s
++, t
++) {
443 if (*s
== '[' && ((d
= *(s
+1)) == '.' || d
== ':' || d
== '=')) {
444 *++t
= *++s
, t
++, s
++;
445 for (c
= *s
; (*t
= *s
) != ']' || c
!= d
; s
++, t
++)
446 if ((c
= *s
) == '\0')
450 * Apple Note: FreeBSD treats the backslash character as the start of
451 * several possible escape sequences here, but this is not POSIX-
452 * compliant. See XBD 9.3.3: "The period, left-bracket, and backslash
453 * shall be special except when used in a bracket expression".
456 return (*s
== ']') ? *sp
= ++s
, ++t
: NULL
;
460 * Compiles the regular expression in RE and returns a pointer to the compiled
461 * regular expression.
462 * Cflags are passed to regcomp.
465 compile_re(char *re
, int case_insensitive
)
472 if (case_insensitive
)
474 if ((rep
= malloc(sizeof(regex_t
))) == NULL
)
476 if ((eval
= regcomp(rep
, re
, flags
)) != 0)
477 errx(1, "%lu: %s: RE error: %s",
478 linenum
, fname
, strregerror(eval
, rep
));
479 if (maxnsub
< rep
->re_nsub
)
480 maxnsub
= rep
->re_nsub
;
485 * Compile the substitution string of a regular expression and set res to
486 * point to a saved copy of it. Nsub is the number of parenthesized regular
490 compile_subst(char *p
, struct s_subst
*s
)
492 static char lbuf
[_POSIX2_LINE_MAX
+ 1];
495 char c
, *text
, *op
, *sp
;
496 int more
= 1, sawesc
= 0;
498 c
= *p
++; /* Terminator character */
503 s
->linenum
= linenum
;
504 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
505 if ((text
= malloc(asize
)) == NULL
)
509 op
= sp
= text
+ size
;
511 if (*p
== '\\' || sawesc
) {
513 * If this is a continuation from the last
514 * buffer, we won't have a character to
524 * This escaped character is continued
525 * in the next part of the line. Note
526 * this fact, then cause the loop to
527 * exit w/ normal EOL case and reenter
528 * above with the new buffer.
533 } else if (strchr("123456789", *p
) != NULL
) {
537 ref
> s
->re
->re_nsub
)
538 errx(1, "%lu: %s: \\%c not defined in the RE",
540 if (s
->maxbref
< ref
)
559 } else if (*p
== c
) {
560 if (*++p
== '\0' && more
) {
561 if (cu_fgets(lbuf
, sizeof(lbuf
), &more
))
566 if ((s
->new = realloc(text
, size
)) == NULL
)
569 } else if (*p
== '\n') {
571 "%lu: %s: unescaped newline inside substitute pattern", linenum
, fname
);
577 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
579 if ((text
= realloc(text
, asize
)) == NULL
)
582 } while (cu_fgets(p
= lbuf
, sizeof(lbuf
), &more
) != NULL
);
583 errx(1, "%lu: %s: unterminated substitute in regular expression",
589 * Compile the flags of the s command
592 compile_flags(char *p
, struct s_subst
*s
)
594 int gn
; /* True if we have seen g or n */
596 char wfile
[_POSIX2_LINE_MAX
+ 1], *q
, *eq
;
598 s
->n
= 1; /* Default */
604 EATSPACE(); /* EXTENSION */
609 "%lu: %s: more than one number or 'g' in substitute flags", linenum
, fname
);
624 case '1': case '2': case '3':
625 case '4': case '5': case '6':
626 case '7': case '8': case '9':
629 "%lu: %s: more than one number or 'g' in substitute flags", linenum
, fname
);
632 nval
= strtol(p
, &p
, 10);
633 if (errno
== ERANGE
|| nval
> INT_MAX
)
635 "%lu: %s: overflow in the 'N' substitute flag", linenum
, fname
);
641 #ifdef HISTORIC_PRACTICE
643 warnx("%lu: %s: space missing before w wfile", linenum
, fname
);
649 eq
= wfile
+ sizeof(wfile
) - 1;
654 err(1, "wfile too long");
659 errx(1, "%lu: %s: no wfile specified", linenum
, fname
);
660 s
->wfile
= strdup(wfile
);
661 if (!aflag
&& (s
->wfd
= open(wfile
,
662 O_WRONLY
|O_APPEND
|O_CREAT
|O_TRUNC
,
667 errx(1, "%lu: %s: bad flag in substitute command: '%c'",
676 * Compile a translation set of strings into a lookup table.
679 compile_tr(char *p
, struct s_tr
**py
)
684 char old
[_POSIX2_LINE_MAX
+ 1];
685 char new[_POSIX2_LINE_MAX
+ 1];
686 size_t oclen
, oldlen
, nclen
, newlen
;
687 mbstate_t mbs1
, mbs2
;
689 if ((*py
= y
= malloc(sizeof(*y
))) == NULL
)
694 if (*p
== '\0' || *p
== '\\')
696 "%lu: %s: transform pattern can not be delimited by newline or backslash",
698 p
= compile_delimited(p
, old
, 1);
700 errx(1, "%lu: %s: unterminated transform source string",
702 p
= compile_delimited(p
- 1, new, 1);
704 errx(1, "%lu: %s: unterminated transform target string",
708 oldlen
= mbsrtowcs(NULL
, &op
, 0, NULL
);
709 if (oldlen
== (size_t)-1)
712 newlen
= mbsrtowcs(NULL
, &np
, 0, NULL
);
713 if (newlen
== (size_t)-1)
715 if (newlen
!= oldlen
)
716 errx(1, "%lu: %s: transform strings are not the same length",
718 if (MB_CUR_MAX
== 1) {
720 * The single-byte encoding case is easy: generate a
723 for (i
= 0; i
<= UCHAR_MAX
; i
++)
724 y
->bytetab
[i
] = (char)i
;
725 for (; *op
; op
++, np
++)
726 y
->bytetab
[(u_char
)*op
] = *np
;
729 * Multi-byte encoding case: generate a lookup table as
730 * above, but only for single-byte characters. The first
731 * bytes of multi-byte characters have their lookup table
732 * entries set to 0, which causes do_tr() to search through
733 * an auxiliary vector of multi-byte mappings.
735 memset(&mbs1
, 0, sizeof(mbs1
));
736 memset(&mbs2
, 0, sizeof(mbs2
));
737 for (i
= 0; i
<= UCHAR_MAX
; i
++)
738 y
->bytetab
[i
] = (btowc(i
) != WEOF
) ? i
: 0;
739 while (*op
!= '\0') {
740 oclen
= mbrlen(op
, MB_LEN_MAX
, &mbs1
);
741 if (oclen
== (size_t)-1 || oclen
== (size_t)-2)
742 errc(1, EILSEQ
, NULL
);
743 nclen
= mbrlen(np
, MB_LEN_MAX
, &mbs2
);
744 if (nclen
== (size_t)-1 || nclen
== (size_t)-2)
745 errc(1, EILSEQ
, NULL
);
746 if (oclen
== 1 && nclen
== 1)
747 y
->bytetab
[(u_char
)*op
] = *np
;
749 y
->bytetab
[(u_char
)*op
] = 0;
750 y
->multis
= realloc(y
->multis
,
751 (y
->nmultis
+ 1) * sizeof(*y
->multis
));
752 if (y
->multis
== NULL
)
755 y
->multis
[i
].fromlen
= oclen
;
756 memcpy(y
->multis
[i
].from
, op
, oclen
);
757 y
->multis
[i
].tolen
= nclen
;
758 memcpy(y
->multis
[i
].to
, np
, nclen
);
768 * Compile the text following an a, c, or i command.
773 int asize
, esc_nl
, size
;
774 char *text
, *p
, *op
, *s
;
775 char lbuf
[_POSIX2_LINE_MAX
+ 1];
777 asize
= 2 * _POSIX2_LINE_MAX
+ 1;
778 if ((text
= malloc(asize
)) == NULL
)
781 while (cu_fgets(lbuf
, sizeof(lbuf
), NULL
) != NULL
) {
782 op
= s
= text
+ size
;
784 #ifdef LEGACY_BSDSED_COMPAT
787 for (esc_nl
= 0; *p
!= '\0'; p
++) {
788 if (*p
== '\\' && p
[1] != '\0' && *++p
== '\n')
797 if (asize
- size
< _POSIX2_LINE_MAX
+ 1) {
799 if ((text
= realloc(text
, asize
)) == NULL
)
804 if ((p
= realloc(text
, size
+ 1)) == NULL
)
810 * Get an address and return a pointer to the first character after
811 * it. Fill the structure pointed to according to the address.
814 compile_addr(char *p
, struct s_addr
*a
)
816 char *end
, re
[_POSIX2_LINE_MAX
+ 1];
823 case '\\': /* Context address */
826 case '/': /* Context address */
827 p
= compile_delimited(p
, re
, 0);
829 errx(1, "%lu: %s: unterminated regular expression", linenum
, fname
);
830 /* Check for case insensitive regexp flag */
838 a
->u
.r
= compile_re(re
, icase
);
842 case '$': /* Last line */
846 case '+': /* Relative line number */
847 a
->type
= AT_RELLINE
;
851 case '0': case '1': case '2': case '3': case '4':
852 case '5': case '6': case '7': case '8': case '9':
855 a
->u
.l
= strtol(p
, &end
, 10);
858 errx(1, "%lu: %s: expected context address", linenum
, fname
);
865 * Return a copy of all the characters up to \n or \0.
868 duptoeol(char *s
, const char *ctype
)
875 for (start
= s
; *s
!= '\0' && *s
!= '\n'; ++s
)
876 ws
= isspace((unsigned char)*s
);
879 warnx("%lu: %s: whitespace after %s", linenum
, fname
, ctype
);
881 if ((p
= malloc(len
)) == NULL
)
883 return (memmove(p
, start
, len
));
887 * Convert goto label names to addresses, and count a and r commands, in
888 * the given subset of the script. Free the memory used by labels in b
889 * and t commands (but not by :).
891 * TODO: Remove } nodes
894 fixuplabel(struct s_command
*cp
, struct s_command
*end
)
897 for (; cp
!= end
; cp
= cp
->next
)
905 /* Resolve branch target. */
910 if ((cp
->u
.c
= findlabel(cp
->t
)) == NULL
)
911 errx(1, "%lu: %s: undefined label '%s'", linenum
, fname
, cp
->t
);
915 /* Do interior commands. */
916 fixuplabel(cp
->u
.c
, cp
->next
);
922 * Associate the given command label for later lookup.
925 enterlabel(struct s_command
*cp
)
927 struct labhash
**lhp
, *lh
;
931 for (h
= 0, p
= (u_char
*)cp
->t
; (c
= *p
) != 0; p
++)
932 h
= (h
<< 5) + h
+ c
;
933 lhp
= &labels
[h
& LHMASK
];
934 for (lh
= *lhp
; lh
!= NULL
; lh
= lh
->lh_next
)
935 if (lh
->lh_hash
== h
&& strcmp(cp
->t
, lh
->lh_cmd
->t
) == 0)
936 errx(1, "%lu: %s: duplicate label '%s'", linenum
, fname
, cp
->t
);
937 if ((lh
= malloc(sizeof *lh
)) == NULL
)
947 * Find the label contained in the command l in the command linked
948 * list cp. L is excluded from the search. Return NULL if not found.
950 static struct s_command
*
951 findlabel(char *name
)
957 for (h
= 0, p
= (u_char
*)name
; (c
= *p
) != 0; p
++)
958 h
= (h
<< 5) + h
+ c
;
959 for (lh
= labels
[h
& LHMASK
]; lh
!= NULL
; lh
= lh
->lh_next
) {
960 if (lh
->lh_hash
== h
&& strcmp(name
, lh
->lh_cmd
->t
) == 0) {
969 * Warn about any unused labels. As a side effect, release the label hash
975 struct labhash
*lh
, *next
;
978 for (i
= 0; i
< LHSZ
; i
++) {
979 for (lh
= labels
[i
]; lh
!= NULL
; lh
= next
) {
982 warnx("%lu: %s: unused label '%s'",
983 linenum
, fname
, lh
->lh_cmd
->t
);