sed: sync with freebsd
[unleashed.git] / usr / src / cmd / sed / compile.c
blobe1aa9acadabcf7353511d70ad52642aa478a5452
1 /*-
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
11 * are met:
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
31 * SUCH DAMAGE.
34 #include <sys/types.h>
35 #include <sys/stat.h>
37 #include <ctype.h>
38 #include <err.h>
39 #include <errno.h>
40 #include <fcntl.h>
41 #include <limits.h>
42 #include <regex.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <wchar.h>
48 #include "defs.h"
49 #include "extern.h"
50 #include "freebsd-compat.h"
52 #define LHSZ 128
53 #define LHMASK (LHSZ - 1)
54 static struct labhash {
55 struct labhash *lh_next;
56 u_int lh_hash;
57 struct s_command *lh_cmd;
58 int lh_ref;
59 } *labels[LHSZ];
61 static char *compile_addr(char *, struct s_addr *);
62 static char *compile_ccl(char **, char *);
63 static char *compile_delimited(char *, char *, int);
64 static char *compile_flags(char *, struct s_subst *);
65 static regex_t *compile_re(char *, int);
66 static char *compile_subst(char *, struct s_subst *);
67 static char *compile_text(void);
68 static char *compile_tr(char *, struct s_tr **);
69 static struct s_command
70 **compile_stream(struct s_command **);
71 static char *duptoeol(char *, const char *);
72 static void enterlabel(struct s_command *);
73 static struct s_command
74 *findlabel(char *);
75 static void fixuplabel(struct s_command *, struct s_command *);
76 static void uselabel(void);
79 * Command specification. This is used to drive the command parser.
81 struct s_format {
82 char code; /* Command code */
83 int naddr; /* Number of address args */
84 enum e_args args; /* Argument type */
87 static struct s_format cmd_fmts[] = {
88 {'{', 2, GROUP},
89 {'}', 0, ENDGROUP},
90 {'a', 1, TEXT},
91 {'b', 2, BRANCH},
92 {'c', 2, TEXT},
93 {'d', 2, EMPTY},
94 {'D', 2, EMPTY},
95 {'g', 2, EMPTY},
96 {'G', 2, EMPTY},
97 {'h', 2, EMPTY},
98 {'H', 2, EMPTY},
99 {'i', 1, TEXT},
100 {'l', 2, EMPTY},
101 {'n', 2, EMPTY},
102 {'N', 2, EMPTY},
103 {'p', 2, EMPTY},
104 {'P', 2, EMPTY},
105 {'q', 1, EMPTY},
106 {'r', 1, RFILE},
107 {'s', 2, SUBST},
108 {'t', 2, BRANCH},
109 {'w', 2, WFILE},
110 {'x', 2, EMPTY},
111 {'y', 2, TR},
112 {'!', 2, NONSEL},
113 {':', 0, LABEL},
114 {'#', 0, COMMENT},
115 {'=', 1, EMPTY},
116 {'\0', 0, COMMENT},
119 /* The compiled program. */
120 struct s_command *prog;
123 * Compile the program into prog.
124 * Initialise appends.
126 void
127 compile(void)
129 *compile_stream(&prog) = NULL;
130 fixuplabel(prog, NULL);
131 uselabel();
132 if (appendnum == 0)
133 appends = NULL;
134 else if ((appends = malloc(sizeof(struct s_appends) * appendnum)) ==
135 NULL)
136 err(1, "malloc");
137 if ((match = malloc((maxnsub + 1) * sizeof(regmatch_t))) == NULL)
138 err(1, "malloc");
141 #define EATSPACE() do { \
142 if (p) \
143 while (*p && isspace((unsigned char)*p)) \
144 p++; \
145 } while (0)
147 static struct s_command **
148 compile_stream(struct s_command **link)
150 char *p;
151 static char lbuf[_POSIX2_LINE_MAX + 1]; /* To save stack */
152 struct s_command *cmd, *cmd2, *stack;
153 struct s_format *fp;
154 char re[_POSIX2_LINE_MAX + 1];
155 int naddr; /* Number of addresses */
157 stack = NULL;
158 for (;;) {
159 if ((p = cu_fgets(lbuf, sizeof(lbuf), NULL)) == NULL) {
160 if (stack != NULL)
161 errx(1, "%lu: %s: unexpected EOF (pending }'s)",
162 linenum, fname);
163 return (link);
166 semicolon: EATSPACE();
167 if (p) {
168 if (*p == '#' || *p == '\0')
169 continue;
170 else if (*p == ';') {
171 p++;
172 goto semicolon;
175 if ((*link = cmd = malloc(sizeof(struct s_command))) == NULL)
176 err(1, "malloc");
177 link = &cmd->next;
178 cmd->startline = cmd->nonsel = 0;
179 /* First parse the addresses */
180 naddr = 0;
182 /* Valid characters to start an address */
183 #define addrchar(c) (strchr("0123456789/\\$", (c)))
184 if (addrchar(*p)) {
185 naddr++;
186 if ((cmd->a1 = malloc(sizeof(struct s_addr))) == NULL)
187 err(1, "malloc");
188 p = compile_addr(p, cmd->a1);
189 EATSPACE(); /* EXTENSION */
190 if (*p == ',') {
191 p++;
192 EATSPACE(); /* EXTENSION */
193 naddr++;
194 if ((cmd->a2 = malloc(sizeof(struct s_addr)))
195 == NULL)
196 err(1, "malloc");
197 p = compile_addr(p, cmd->a2);
198 EATSPACE();
199 } else
200 cmd->a2 = NULL;
201 } else
202 cmd->a1 = cmd->a2 = NULL;
204 nonsel: /* Now parse the command */
205 if (!*p)
206 errx(1, "%lu: %s: command expected", linenum, fname);
207 cmd->code = *p;
208 for (fp = cmd_fmts; fp->code; fp++)
209 if (fp->code == *p)
210 break;
211 if (!fp->code)
212 errx(1, "%lu: %s: invalid command code %c", linenum, fname, *p);
213 if (naddr > fp->naddr)
214 errx(1,
215 "%lu: %s: command %c expects up to %d address(es), found %d",
216 linenum, fname, *p, fp->naddr, naddr);
217 switch (fp->args) {
218 case NONSEL: /* ! */
219 p++;
220 EATSPACE();
221 cmd->nonsel = 1;
222 goto nonsel;
223 case GROUP: /* { */
224 p++;
225 EATSPACE();
226 cmd->next = stack;
227 stack = cmd;
228 link = &cmd->u.c;
229 if (*p)
230 goto semicolon;
231 break;
232 case ENDGROUP:
234 * Short-circuit command processing, since end of
235 * group is really just a noop.
237 cmd->nonsel = 1;
238 if (stack == NULL)
239 errx(1, "%lu: %s: unexpected }", linenum, fname);
240 cmd2 = stack;
241 stack = cmd2->next;
242 cmd2->next = cmd;
243 /*FALLTHROUGH*/
244 case EMPTY: /* d D g G h H l n N p P q x = \0 */
245 p++;
246 EATSPACE();
247 if (*p == ';') {
248 p++;
249 link = &cmd->next;
250 goto semicolon;
252 if (*p)
253 errx(1, "%lu: %s: extra characters at the end of %c command",
254 linenum, fname, cmd->code);
255 break;
256 case TEXT: /* a c i */
257 p++;
258 EATSPACE();
259 if (*p != '\\')
260 errx(1,
261 "%lu: %s: command %c expects \\ followed by text", linenum, fname, cmd->code);
262 p++;
263 EATSPACE();
264 if (*p)
265 errx(1,
266 "%lu: %s: extra characters after \\ at the end of %c command",
267 linenum, fname, cmd->code);
268 cmd->t = compile_text();
269 break;
270 case COMMENT: /* \0 # */
271 break;
272 case WFILE: /* w */
273 p++;
274 EATSPACE();
275 if (*p == '\0')
276 errx(1, "%lu: %s: filename expected", linenum, fname);
277 cmd->t = duptoeol(p, "w command");
278 if (aflag)
279 cmd->u.fd = -1;
280 else if ((cmd->u.fd = open(p,
281 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
282 DEFFILEMODE)) == -1)
283 err(1, "%s", p);
284 break;
285 case RFILE: /* r */
286 p++;
287 EATSPACE();
288 if (*p == '\0')
289 errx(1, "%lu: %s: filename expected", linenum, fname);
290 else
291 cmd->t = duptoeol(p, "read command");
292 break;
293 case BRANCH: /* b t */
294 p++;
295 EATSPACE();
296 if (*p == '\0')
297 cmd->t = NULL;
298 else
299 cmd->t = duptoeol(p, "branch");
300 break;
301 case LABEL: /* : */
302 p++;
303 EATSPACE();
304 cmd->t = duptoeol(p, "label");
305 if (strlen(p) == 0)
306 errx(1, "%lu: %s: empty label", linenum, fname);
307 enterlabel(cmd);
308 break;
309 case SUBST: /* s */
310 p++;
311 if (*p == '\0' || *p == '\\')
312 errx(1,
313 "%lu: %s: substitute pattern can not be delimited by newline or backslash",
314 linenum, fname);
315 if ((cmd->u.s = calloc(1, sizeof(struct s_subst))) == NULL)
316 err(1, "malloc");
317 p = compile_delimited(p, re, 0);
318 if (p == NULL)
319 errx(1,
320 "%lu: %s: unterminated substitute pattern", linenum, fname);
322 /* Compile RE with no case sensitivity temporarily */
323 if (*re == '\0')
324 cmd->u.s->re = NULL;
325 else
326 cmd->u.s->re = compile_re(re, 0);
327 --p;
328 p = compile_subst(p, cmd->u.s);
329 p = compile_flags(p, cmd->u.s);
331 /* Recompile RE with case sensitivity from "I" flag if any */
332 if (*re == '\0')
333 cmd->u.s->re = NULL;
334 else
335 cmd->u.s->re = compile_re(re, cmd->u.s->icase);
336 EATSPACE();
337 if (*p == ';') {
338 p++;
339 link = &cmd->next;
340 goto semicolon;
342 break;
343 case TR: /* y */
344 p++;
345 p = compile_tr(p, &cmd->u.y);
346 EATSPACE();
347 if (*p == ';') {
348 p++;
349 link = &cmd->next;
350 goto semicolon;
352 if (*p)
353 errx(1,
354 "%lu: %s: extra text at the end of a transform command", linenum, fname);
355 break;
361 * Get a delimited string. P points to the delimiter of the string; d points
362 * to a buffer area. Newline and delimiter escapes are processed; other
363 * escapes are ignored.
365 * Returns a pointer to the first character after the final delimiter or NULL
366 * in the case of a non-terminated string. The character array d is filled
367 * with the processed string.
369 static char *
370 compile_delimited(char *p, char *d, int is_tr)
372 char c;
374 c = *p++;
375 if (c == '\0')
376 return (NULL);
377 else if (c == '\\')
378 errx(1, "%lu: %s: \\ can not be used as a string delimiter",
379 linenum, fname);
380 else if (c == '\n')
381 errx(1, "%lu: %s: newline can not be used as a string delimiter",
382 linenum, fname);
383 while (*p) {
384 if (*p == '[' && *p != c) {
385 if ((d = compile_ccl(&p, d)) == NULL)
386 errx(1, "%lu: %s: unbalanced brackets ([])", linenum, fname);
387 continue;
388 } else if (*p == '\\' && p[1] == '[') {
389 *d++ = *p++;
390 } else if (*p == '\\' && p[1] == c)
391 p++;
392 else if (*p == '\\' && p[1] == 'n') {
393 *d++ = '\n';
394 p += 2;
395 continue;
396 } else if (*p == '\\' && p[1] == '\\') {
397 if (is_tr)
398 p++;
399 else
400 *d++ = *p++;
401 } else if (*p == c) {
402 *d = '\0';
403 return (p + 1);
405 *d++ = *p++;
407 return (NULL);
411 /* compile_ccl: expand a POSIX character class */
412 static char *
413 compile_ccl(char **sp, char *t)
415 int c, d;
416 char *s = *sp;
418 *t++ = *s++;
419 if (*s == '^')
420 *t++ = *s++;
421 if (*s == ']')
422 *t++ = *s++;
423 for (; *s && (*t = *s) != ']'; s++, t++)
424 if (*s == '[' && ((d = *(s+1)) == '.' || d == ':' || d == '=')) {
425 *++t = *++s, t++, s++;
426 for (c = *s; (*t = *s) != ']' || c != d; s++, t++)
427 if ((c = *s) == '\0')
428 return NULL;
430 return (*s == ']') ? *sp = ++s, ++t : NULL;
434 * Compiles the regular expression in RE and returns a pointer to the compiled
435 * regular expression.
436 * Cflags are passed to regcomp.
438 static regex_t *
439 compile_re(char *re, int case_insensitive)
441 regex_t *rep;
442 int eval, flags;
445 flags = rflags;
446 if (case_insensitive)
447 flags |= REG_ICASE;
448 if ((rep = malloc(sizeof(regex_t))) == NULL)
449 err(1, "malloc");
450 if ((eval = regcomp(rep, re, flags)) != 0)
451 errx(1, "%lu: %s: RE error: %s",
452 linenum, fname, strregerror(eval, rep));
453 if (maxnsub < rep->re_nsub)
454 maxnsub = rep->re_nsub;
455 return (rep);
459 * Compile the substitution string of a regular expression and set res to
460 * point to a saved copy of it. Nsub is the number of parenthesized regular
461 * expressions.
463 static char *
464 compile_subst(char *p, struct s_subst *s)
466 static char lbuf[_POSIX2_LINE_MAX + 1];
467 int asize, size;
468 u_char ref;
469 char c, *text, *op, *sp;
470 int more = 1, sawesc = 0;
472 c = *p++; /* Terminator character */
473 if (c == '\0')
474 return (NULL);
476 s->maxbref = 0;
477 s->linenum = linenum;
478 asize = 2 * _POSIX2_LINE_MAX + 1;
479 if ((text = malloc(asize)) == NULL)
480 err(1, "malloc");
481 size = 0;
482 do {
483 op = sp = text + size;
484 for (; *p; p++) {
485 if (*p == '\\' || sawesc) {
487 * If this is a continuation from the last
488 * buffer, we won't have a character to
489 * skip over.
491 if (sawesc)
492 sawesc = 0;
493 else
494 p++;
496 if (*p == '\0') {
498 * This escaped character is continued
499 * in the next part of the line. Note
500 * this fact, then cause the loop to
501 * exit w/ normal EOL case and reenter
502 * above with the new buffer.
504 sawesc = 1;
505 p--;
506 continue;
507 } else if (strchr("123456789", *p) != NULL) {
508 *sp++ = '\\';
509 ref = *p - '0';
510 if (s->re != NULL &&
511 ref > s->re->re_nsub)
512 errx(1, "%lu: %s: \\%c not defined in the RE",
513 linenum, fname, *p);
514 if (s->maxbref < ref)
515 s->maxbref = ref;
516 } else if (*p == '&' || *p == '\\')
517 *sp++ = '\\';
518 } else if (*p == c) {
519 if (*++p == '\0' && more) {
520 if (cu_fgets(lbuf, sizeof(lbuf), &more))
521 p = lbuf;
523 *sp++ = '\0';
524 size += sp - op;
525 if ((s->new = realloc(text, size)) == NULL)
526 err(1, "realloc");
527 return (p);
528 } else if (*p == '\n') {
529 errx(1,
530 "%lu: %s: unescaped newline inside substitute pattern", linenum, fname);
531 /* NOTREACHED */
533 *sp++ = *p;
535 size += sp - op;
536 if (asize - size < _POSIX2_LINE_MAX + 1) {
537 asize *= 2;
538 if ((text = realloc(text, asize)) == NULL)
539 err(1, "realloc");
541 } while (cu_fgets(p = lbuf, sizeof(lbuf), &more) != NULL);
542 errx(1, "%lu: %s: unterminated substitute in regular expression",
543 linenum, fname);
544 /* NOTREACHED */
548 * Compile the flags of the s command
550 static char *
551 compile_flags(char *p, struct s_subst *s)
553 int gn; /* True if we have seen g or n */
554 unsigned long nval;
555 char wfile[_POSIX2_LINE_MAX + 1], *q, *eq;
557 s->n = 1; /* Default */
558 s->p = 0;
559 s->wfile = NULL;
560 s->wfd = -1;
561 s->icase = 0;
562 for (gn = 0;;) {
563 EATSPACE(); /* EXTENSION */
564 switch (*p) {
565 case 'g':
566 if (gn)
567 errx(1,
568 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
569 gn = 1;
570 s->n = 0;
571 break;
572 case '\0':
573 case '\n':
574 case ';':
575 return (p);
576 case 'p':
577 s->p = 1;
578 break;
579 case 'i':
580 case 'I':
581 s->icase = 1;
582 break;
583 case '1': case '2': case '3':
584 case '4': case '5': case '6':
585 case '7': case '8': case '9':
586 if (gn)
587 errx(1,
588 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
589 gn = 1;
590 errno = 0;
591 nval = strtol(p, &p, 10);
592 if (errno == ERANGE || nval > INT_MAX)
593 errx(1,
594 "%lu: %s: overflow in the 'N' substitute flag", linenum, fname);
595 s->n = nval;
596 p--;
597 break;
598 case 'w':
599 p++;
600 #ifdef HISTORIC_PRACTICE
601 if (*p != ' ') {
602 warnx("%lu: %s: space missing before w wfile", linenum, fname);
603 return (p);
605 #endif
606 EATSPACE();
607 q = wfile;
608 eq = wfile + sizeof(wfile) - 1;
609 while (*p) {
610 if (*p == '\n')
611 break;
612 if (q >= eq)
613 err(1, "wfile too long");
614 *q++ = *p++;
616 *q = '\0';
617 if (q == wfile)
618 errx(1, "%lu: %s: no wfile specified", linenum, fname);
619 s->wfile = strdup(wfile);
620 if (!aflag && (s->wfd = open(wfile,
621 O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
622 DEFFILEMODE)) == -1)
623 err(1, "%s", wfile);
624 return (p);
625 default:
626 errx(1, "%lu: %s: bad flag in substitute command: '%c'",
627 linenum, fname, *p);
628 break;
630 p++;
635 * Compile a translation set of strings into a lookup table.
637 static char *
638 compile_tr(char *p, struct s_tr **py)
640 struct s_tr *y;
641 int i;
642 const char *op, *np;
643 char old[_POSIX2_LINE_MAX + 1];
644 char new[_POSIX2_LINE_MAX + 1];
645 size_t oclen, oldlen, nclen, newlen;
646 mbstate_t mbs1, mbs2;
648 if ((*py = y = malloc(sizeof(*y))) == NULL)
649 err(1, NULL);
650 y->multis = NULL;
651 y->nmultis = 0;
653 if (*p == '\0' || *p == '\\')
654 errx(1,
655 "%lu: %s: transform pattern can not be delimited by newline or backslash",
656 linenum, fname);
657 p = compile_delimited(p, old, 1);
658 if (p == NULL)
659 errx(1, "%lu: %s: unterminated transform source string",
660 linenum, fname);
661 p = compile_delimited(p - 1, new, 1);
662 if (p == NULL)
663 errx(1, "%lu: %s: unterminated transform target string",
664 linenum, fname);
665 EATSPACE();
666 op = old;
667 oldlen = mbsrtowcs(NULL, &op, 0, NULL);
668 if (oldlen == (size_t)-1)
669 err(1, NULL);
670 np = new;
671 newlen = mbsrtowcs(NULL, &np, 0, NULL);
672 if (newlen == (size_t)-1)
673 err(1, NULL);
674 if (newlen != oldlen)
675 errx(1, "%lu: %s: transform strings are not the same length",
676 linenum, fname);
677 if (MB_CUR_MAX == 1) {
679 * The single-byte encoding case is easy: generate a
680 * lookup table.
682 for (i = 0; i <= UCHAR_MAX; i++)
683 y->bytetab[i] = (char)i;
684 for (; *op; op++, np++)
685 y->bytetab[(u_char)*op] = *np;
686 } else {
688 * Multi-byte encoding case: generate a lookup table as
689 * above, but only for single-byte characters. The first
690 * bytes of multi-byte characters have their lookup table
691 * entries set to 0, which causes do_tr() to search through
692 * an auxiliary vector of multi-byte mappings.
694 memset(&mbs1, 0, sizeof(mbs1));
695 memset(&mbs2, 0, sizeof(mbs2));
696 for (i = 0; i <= UCHAR_MAX; i++)
697 y->bytetab[i] = (btowc(i) != WEOF) ? i : 0;
698 while (*op != '\0') {
699 oclen = mbrlen(op, MB_LEN_MAX, &mbs1);
700 if (oclen == (size_t)-1 || oclen == (size_t)-2)
701 errc(1, EILSEQ, NULL);
702 nclen = mbrlen(np, MB_LEN_MAX, &mbs2);
703 if (nclen == (size_t)-1 || nclen == (size_t)-2)
704 errc(1, EILSEQ, NULL);
705 if (oclen == 1 && nclen == 1)
706 y->bytetab[(u_char)*op] = *np;
707 else {
708 y->bytetab[(u_char)*op] = 0;
709 y->multis = realloc(y->multis,
710 (y->nmultis + 1) * sizeof(*y->multis));
711 if (y->multis == NULL)
712 err(1, NULL);
713 i = y->nmultis++;
714 y->multis[i].fromlen = oclen;
715 memcpy(y->multis[i].from, op, oclen);
716 y->multis[i].tolen = nclen;
717 memcpy(y->multis[i].to, np, nclen);
719 op += oclen;
720 np += nclen;
723 return (p);
727 * Compile the text following an a, c, or i command.
729 static char *
730 compile_text(void)
732 int asize, esc_nl, size;
733 char *text, *p, *op, *s;
734 char lbuf[_POSIX2_LINE_MAX + 1];
736 asize = 2 * _POSIX2_LINE_MAX + 1;
737 if ((text = malloc(asize)) == NULL)
738 err(1, "malloc");
739 size = 0;
740 while (cu_fgets(lbuf, sizeof(lbuf), NULL) != NULL) {
741 op = s = text + size;
742 p = lbuf;
743 #ifdef LEGACY_BSDSED_COMPAT
744 EATSPACE();
745 #endif
746 for (esc_nl = 0; *p != '\0'; p++) {
747 if (*p == '\\' && p[1] != '\0' && *++p == '\n')
748 esc_nl = 1;
749 *s++ = *p;
751 size += s - op;
752 if (!esc_nl) {
753 *s = '\0';
754 break;
756 if (asize - size < _POSIX2_LINE_MAX + 1) {
757 asize *= 2;
758 if ((text = realloc(text, asize)) == NULL)
759 err(1, "realloc");
762 text[size] = '\0';
763 if ((p = realloc(text, size + 1)) == NULL)
764 err(1, "realloc");
765 return (p);
769 * Get an address and return a pointer to the first character after
770 * it. Fill the structure pointed to according to the address.
772 static char *
773 compile_addr(char *p, struct s_addr *a)
775 char *end, re[_POSIX2_LINE_MAX + 1];
776 int icase;
778 icase = 0;
780 a->type = 0;
781 switch (*p) {
782 case '\\': /* Context address */
783 ++p;
784 /* FALLTHROUGH */
785 case '/': /* Context address */
786 p = compile_delimited(p, re, 0);
787 if (p == NULL)
788 errx(1, "%lu: %s: unterminated regular expression", linenum, fname);
789 /* Check for case insensitive regexp flag */
790 if (*p == 'I') {
791 icase = 1;
792 p++;
794 if (*re == '\0')
795 a->u.r = NULL;
796 else
797 a->u.r = compile_re(re, icase);
798 a->type = AT_RE;
799 return (p);
801 case '$': /* Last line */
802 a->type = AT_LAST;
803 return (p + 1);
805 case '+': /* Relative line number */
806 a->type = AT_RELLINE;
807 p++;
808 /* FALLTHROUGH */
809 /* Line number */
810 case '0': case '1': case '2': case '3': case '4':
811 case '5': case '6': case '7': case '8': case '9':
812 if (a->type == 0)
813 a->type = AT_LINE;
814 a->u.l = strtol(p, &end, 10);
815 return (end);
816 default:
817 errx(1, "%lu: %s: expected context address", linenum, fname);
818 return (NULL);
823 * duptoeol --
824 * Return a copy of all the characters up to \n or \0.
826 static char *
827 duptoeol(char *s, const char *ctype)
829 size_t len;
830 int ws;
831 char *p, *start;
833 ws = 0;
834 for (start = s; *s != '\0' && *s != '\n'; ++s)
835 ws = isspace((unsigned char)*s);
836 *s = '\0';
837 if (ws)
838 warnx("%lu: %s: whitespace after %s", linenum, fname, ctype);
839 len = s - start + 1;
840 if ((p = malloc(len)) == NULL)
841 err(1, "malloc");
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
852 static void
853 fixuplabel(struct s_command *cp, struct s_command *end)
856 for (; cp != end; cp = cp->next)
857 switch (cp->code) {
858 case 'a':
859 case 'r':
860 appendnum++;
861 break;
862 case 'b':
863 case 't':
864 /* Resolve branch target. */
865 if (cp->t == NULL) {
866 cp->u.c = NULL;
867 break;
869 if ((cp->u.c = findlabel(cp->t)) == NULL)
870 errx(1, "%lu: %s: undefined label '%s'", linenum, fname, cp->t);
871 free(cp->t);
872 break;
873 case '{':
874 /* Do interior commands. */
875 fixuplabel(cp->u.c, cp->next);
876 break;
881 * Associate the given command label for later lookup.
883 static void
884 enterlabel(struct s_command *cp)
886 struct labhash **lhp, *lh;
887 u_char *p;
888 u_int h, c;
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)
897 err(1, "malloc");
898 lh->lh_next = *lhp;
899 lh->lh_hash = h;
900 lh->lh_cmd = cp;
901 lh->lh_ref = 0;
902 *lhp = lh;
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)
912 struct labhash *lh;
913 u_char *p;
914 u_int h, c;
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) {
920 lh->lh_ref = 1;
921 return (lh->lh_cmd);
924 return (NULL);
928 * Warn about any unused labels. As a side effect, release the label hash
929 * table space.
931 static void
932 uselabel(void)
934 struct labhash *lh, *next;
935 int i;
937 for (i = 0; i < LHSZ; i++) {
938 for (lh = labels[i]; lh != NULL; lh = next) {
939 next = lh->lh_next;
940 if (!lh->lh_ref)
941 warnx("%lu: %s: unused label '%s'",
942 linenum, fname, lh->lh_cmd->t);
943 free(lh);