Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / usr.bin / sed / compile.c
1 /*-
2  * Copyright (c) 1992 Diomidis Spinellis.
3  * Copyright (c) 1992, 1993
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * This code is derived from software contributed to Berkeley by
7  * Diomidis Spinellis of Imperial College, University of London.
8  *
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  * 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.
24  *
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
35  * SUCH DAMAGE.
36  *
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.2 2003/06/17 04:29:31 dillon Exp $
40  */
41
42 #include <sys/types.h>
43 #include <sys/stat.h>
44
45 #include <ctype.h>
46 #include <err.h>
47 #include <fcntl.h>
48 #include <limits.h>
49 #include <regex.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53
54 #include "defs.h"
55 #include "extern.h"
56
57 #define LHSZ    128
58 #define LHMASK  (LHSZ - 1)
59 static struct labhash {
60         struct  labhash *lh_next;
61         u_int   lh_hash;
62         struct  s_command *lh_cmd;
63         int     lh_ref;
64 } *labels[LHSZ];
65
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
79                  *findlabel(char *);
80 static void       fixuplabel(struct s_command *, struct s_command *);
81 static void       uselabel(void);
82
83 /*
84  * Command specification.  This is used to drive the command parser.
85  */
86 struct s_format {
87         char code;                              /* Command code */
88         int naddr;                              /* Number of address args */
89         enum e_args args;                       /* Argument type */
90 };
91
92 static struct s_format cmd_fmts[] = {
93         {'{', 2, GROUP},
94         {'}', 0, ENDGROUP},
95         {'a', 1, TEXT},
96         {'b', 2, BRANCH},
97         {'c', 2, TEXT},
98         {'d', 2, EMPTY},
99         {'D', 2, EMPTY},
100         {'g', 2, EMPTY},
101         {'G', 2, EMPTY},
102         {'h', 2, EMPTY},
103         {'H', 2, EMPTY},
104         {'i', 1, TEXT},
105         {'l', 2, EMPTY},
106         {'n', 2, EMPTY},
107         {'N', 2, EMPTY},
108         {'p', 2, EMPTY},
109         {'P', 2, EMPTY},
110         {'q', 1, EMPTY},
111         {'r', 1, RFILE},
112         {'s', 2, SUBST},
113         {'t', 2, BRANCH},
114         {'w', 2, WFILE},
115         {'x', 2, EMPTY},
116         {'y', 2, TR},
117         {'!', 2, NONSEL},
118         {':', 0, LABEL},
119         {'#', 0, COMMENT},
120         {'=', 1, EMPTY},
121         {'\0', 0, COMMENT},
122 };
123
124 /* The compiled program. */
125 struct s_command *prog;
126
127 /*
128  * Compile the program into prog.
129  * Initialise appends.
130  */
131 void
132 compile()
133 {
134         *compile_stream(&prog) = NULL;
135         fixuplabel(prog, NULL);
136         uselabel();
137         if (appendnum == 0)
138                 appends = NULL;
139         else if ((appends = malloc(sizeof(struct s_appends) * appendnum)) ==
140             NULL)
141                 err(1, "malloc");
142         if ((match = malloc((maxnsub + 1) * sizeof(regmatch_t))) == NULL)
143                 err(1, "malloc");
144 }
145
146 #define EATSPACE() do {                                                 \
147         if (p)                                                          \
148                 while (*p && isspace((unsigned char)*p))                \
149                         p++;                                            \
150         } while (0)
151
152 static struct s_command **
153 compile_stream(link)
154         struct s_command **link;
155 {
156         char *p;
157         static char lbuf[_POSIX2_LINE_MAX + 1]; /* To save stack */
158         struct s_command *cmd, *cmd2, *stack;
159         struct s_format *fp;
160         int naddr;                              /* Number of addresses */
161
162         stack = 0;
163         for (;;) {
164                 if ((p = cu_fgets(lbuf, sizeof(lbuf), NULL)) == NULL) {
165                         if (stack != 0)
166                                 errx(1, "%lu: %s: unexpected EOF (pending }'s)",
167                                                         linenum, fname);
168                         return (link);
169                 }
170
171 semicolon:      EATSPACE();
172                 if (p) {
173                         if (*p == '#' || *p == '\0')
174                                 continue;
175                         else if (*p == ';') {
176                                 p++;
177                                 goto semicolon;
178                         }
179                 }
180                 if ((*link = cmd = malloc(sizeof(struct s_command))) == NULL)
181                         err(1, "malloc");
182                 link = &cmd->next;
183                 cmd->nonsel = cmd->inrange = 0;
184                 /* First parse the addresses */
185                 naddr = 0;
186
187 /* Valid characters to start an address */
188 #define addrchar(c)     (strchr("0123456789/\\$", (c)))
189                 if (addrchar(*p)) {
190                         naddr++;
191                         if ((cmd->a1 = malloc(sizeof(struct s_addr))) == NULL)
192                                 err(1, "malloc");
193                         p = compile_addr(p, cmd->a1);
194                         EATSPACE();                             /* EXTENSION */
195                         if (*p == ',') {
196                                 p++;
197                                 EATSPACE();                     /* EXTENSION */
198                                 naddr++;
199                                 if ((cmd->a2 = malloc(sizeof(struct s_addr)))
200                                     == NULL)
201                                         err(1, "malloc");
202                                 p = compile_addr(p, cmd->a2);
203                                 EATSPACE();
204                         } else
205                                 cmd->a2 = 0;
206                 } else
207                         cmd->a1 = cmd->a2 = 0;
208
209 nonsel:         /* Now parse the command */
210                 if (!*p)
211                         errx(1, "%lu: %s: command expected", linenum, fname);
212                 cmd->code = *p;
213                 for (fp = cmd_fmts; fp->code; fp++)
214                         if (fp->code == *p)
215                                 break;
216                 if (!fp->code)
217                         errx(1, "%lu: %s: invalid command code %c", linenum, fname, *p);
218                 if (naddr > fp->naddr)
219                         errx(1,
220                                 "%lu: %s: command %c expects up to %d address(es), found %d",
221                                 linenum, fname, *p, fp->naddr, naddr);
222                 switch (fp->args) {
223                 case NONSEL:                    /* ! */
224                         p++;
225                         EATSPACE();
226                         cmd->nonsel = ! cmd->nonsel;
227                         goto nonsel;
228                 case GROUP:                     /* { */
229                         p++;
230                         EATSPACE();
231                         cmd->next = stack;
232                         stack = cmd;
233                         link = &cmd->u.c;
234                         if (*p)
235                                 goto semicolon;
236                         break;
237                 case ENDGROUP:
238                         /*
239                          * Short-circuit command processing, since end of
240                          * group is really just a noop.
241                          */
242                         cmd->nonsel = 1;
243                         if (stack == 0)
244                                 errx(1, "%lu: %s: unexpected }", linenum, fname);
245                         cmd2 = stack;
246                         stack = cmd2->next;
247                         cmd2->next = cmd;
248                         /*FALLTHROUGH*/
249                 case EMPTY:             /* d D g G h H l n N p P q x = \0 */
250                         p++;
251                         EATSPACE();
252                         if (*p == ';') {
253                                 p++;
254                                 link = &cmd->next;
255                                 goto semicolon;
256                         }
257                         if (*p)
258                                 errx(1, "%lu: %s: extra characters at the end of %c command",
259                                                 linenum, fname, cmd->code);
260                         break;
261                 case TEXT:                      /* a c i */
262                         p++;
263                         EATSPACE();
264                         if (*p != '\\')
265                                 errx(1,
266 "%lu: %s: command %c expects \\ followed by text", linenum, fname, cmd->code);
267                         p++;
268                         EATSPACE();
269                         if (*p)
270                                 errx(1,
271                                 "%lu: %s: extra characters after \\ at the end of %c command",
272                                 linenum, fname, cmd->code);
273                         cmd->t = compile_text();
274                         break;
275                 case COMMENT:                   /* \0 # */
276                         break;
277                 case WFILE:                     /* w */
278                         p++;
279                         EATSPACE();
280                         if (*p == '\0')
281                                 errx(1, "%lu: %s: filename expected", linenum, fname);
282                         cmd->t = duptoeol(p, "w command");
283                         if (aflag)
284                                 cmd->u.fd = -1;
285                         else if ((cmd->u.fd = open(p, 
286                             O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
287                             DEFFILEMODE)) == -1)
288                                 err(1, "%s", p);
289                         break;
290                 case RFILE:                     /* r */
291                         p++;
292                         EATSPACE();
293                         if (*p == '\0')
294                                 errx(1, "%lu: %s: filename expected", linenum, fname);
295                         else
296                                 cmd->t = duptoeol(p, "read command");
297                         break;
298                 case BRANCH:                    /* b t */
299                         p++;
300                         EATSPACE();
301                         if (*p == '\0')
302                                 cmd->t = NULL;
303                         else
304                                 cmd->t = duptoeol(p, "branch");
305                         break;
306                 case LABEL:                     /* : */
307                         p++;
308                         EATSPACE();
309                         cmd->t = duptoeol(p, "label");
310                         if (strlen(p) == 0)
311                                 errx(1, "%lu: %s: empty label", linenum, fname);
312                         enterlabel(cmd);
313                         break;
314                 case SUBST:                     /* s */
315                         p++;
316                         if (*p == '\0' || *p == '\\')
317                                 errx(1,
318 "%lu: %s: substitute pattern can not be delimited by newline or backslash", 
319                                         linenum, fname);
320                         if ((cmd->u.s = malloc(sizeof(struct s_subst))) == NULL)
321                                 err(1, "malloc");
322                         p = compile_re(p, &cmd->u.s->re);
323                         if (p == NULL)
324                                 errx(1,
325                                 "%lu: %s: unterminated substitute pattern", linenum, fname);
326                         --p;
327                         p = compile_subst(p, cmd->u.s);
328                         p = compile_flags(p, cmd->u.s);
329                         EATSPACE();
330                         if (*p == ';') {
331                                 p++;
332                                 link = &cmd->next;
333                                 goto semicolon;
334                         }
335                         break;
336                 case TR:                        /* y */
337                         p++;
338                         p = compile_tr(p, (char **)&cmd->u.y);
339                         EATSPACE();
340                         if (*p == ';') {
341                                 p++;
342                                 link = &cmd->next;
343                                 goto semicolon;
344                         }
345                         if (*p)
346                                 errx(1,
347 "%lu: %s: extra text at the end of a transform command", linenum, fname);
348                         break;
349                 }
350         }
351 }
352
353 /*
354  * Get a delimited string.  P points to the delimeter of the string; d points
355  * to a buffer area.  Newline and delimiter escapes are processed; other
356  * escapes are ignored.
357  *
358  * Returns a pointer to the first character after the final delimiter or NULL
359  * in the case of a non-terminated string.  The character array d is filled
360  * with the processed string.
361  */
362 static char *
363 compile_delimited(p, d)
364         char *p, *d;
365 {
366         char c;
367
368         c = *p++;
369         if (c == '\0')
370                 return (NULL);
371         else if (c == '\\')
372                 errx(1, "%lu: %s: \\ can not be used as a string delimiter",
373                                 linenum, fname);
374         else if (c == '\n')
375                 errx(1, "%lu: %s: newline can not be used as a string delimiter",
376                                 linenum, fname);
377         while (*p) {
378                 if (*p == '[') {
379                         if ((d = compile_ccl(&p, d)) == NULL)
380                                 errx(1, "%lu: %s: unbalanced brackets ([])", linenum, fname);
381                         continue;
382                 } else if (*p == '\\' && p[1] == '[') {
383                         *d++ = *p++;
384                 } else if (*p == '\\' && p[1] == c)
385                         p++;
386                 else if (*p == '\\' && p[1] == 'n') {
387                         *d++ = '\n';
388                         p += 2;
389                         continue;
390                 } else if (*p == '\\' && p[1] == '\\')
391                         *d++ = *p++;
392                 else if (*p == c) {
393                         *d = '\0';
394                         return (p + 1);
395                 }
396                 *d++ = *p++;
397         }
398         return (NULL);
399 }
400
401
402 /* compile_ccl: expand a POSIX character class */
403 static char *
404 compile_ccl(sp, t)
405         char **sp;
406         char *t;
407 {
408         int c, d;
409         char *s = *sp;
410
411         *t++ = *s++;
412         if (*s == '^')
413                 *t++ = *s++;
414         if (*s == ']')
415                 *t++ = *s++;
416         for (; *s && (*t = *s) != ']'; s++, t++)
417                 if (*s == '[' && ((d = *(s+1)) == '.' || d == ':' || d == '=')) {
418                         *++t = *++s, t++, s++;
419                         for (c = *s; (*t = *s) != ']' || c != d; s++, t++)
420                                 if ((c = *s) == '\0')
421                                         return NULL;
422                 } else if (*s == '\\' && s[1] == 'n')
423                             *t = '\n', s++;
424         return (*s == ']') ? *sp = ++s, ++t : NULL;
425 }
426
427 /*
428  * Get a regular expression.  P points to the delimiter of the regular
429  * expression; repp points to the address of a regexp pointer.  Newline
430  * and delimiter escapes are processed; other escapes are ignored.
431  * Returns a pointer to the first character after the final delimiter
432  * or NULL in the case of a non terminated regular expression.  The regexp
433  * pointer is set to the compiled regular expression.
434  * Cflags are passed to regcomp.
435  */
436 static char *
437 compile_re(p, repp)
438         char *p;
439         regex_t **repp;
440 {
441         int eval;
442         char re[_POSIX2_LINE_MAX + 1];
443
444         p = compile_delimited(p, re);
445         if (p && strlen(re) == 0) {
446                 *repp = NULL;
447                 return (p);
448         }
449         if ((*repp = malloc(sizeof(regex_t))) == NULL)
450                 err(1, "malloc");
451         if (p && (eval = regcomp(*repp, re, rflags)) != 0)
452                 errx(1, "%lu: %s: RE error: %s",
453                                 linenum, fname, strregerror(eval, *repp));
454         if (maxnsub < (*repp)->re_nsub)
455                 maxnsub = (*repp)->re_nsub;
456         return (p);
457 }
458
459 /*
460  * Compile the substitution string of a regular expression and set res to
461  * point to a saved copy of it.  Nsub is the number of parenthesized regular
462  * expressions.
463  */
464 static char *
465 compile_subst(p, s)
466         char *p;
467         struct s_subst *s;
468 {
469         static char lbuf[_POSIX2_LINE_MAX + 1];
470         int asize, size;
471         u_char ref;
472         char c, *text, *op, *sp;
473         int more = 1, sawesc = 0;
474
475         c = *p++;                       /* Terminator character */
476         if (c == '\0')
477                 return (NULL);
478
479         s->maxbref = 0;
480         s->linenum = linenum;
481         asize = 2 * _POSIX2_LINE_MAX + 1;
482         if ((text = malloc(asize)) == NULL)
483                 err(1, "malloc");
484         size = 0;
485         do {
486                 op = sp = text + size;
487                 for (; *p; p++) {
488                         if (*p == '\\' || sawesc) {
489                                 /*
490                                  * If this is a continuation from the last
491                                  * buffer, we won't have a character to
492                                  * skip over.
493                                  */
494                                 if (sawesc)
495                                         sawesc = 0;
496                                 else
497                                         p++;
498
499                                 if (*p == '\0') {
500                                         /*
501                                          * This escaped character is continued
502                                          * in the next part of the line.  Note
503                                          * this fact, then cause the loop to
504                                          * exit w/ normal EOL case and reenter
505                                          * above with the new buffer.
506                                          */
507                                         sawesc = 1;
508                                         p--;
509                                         continue;
510                                 } else if (strchr("123456789", *p) != NULL) {
511                                         *sp++ = '\\';
512                                         ref = *p - '0';
513                                         if (s->re != NULL &&
514                                             ref > s->re->re_nsub)
515                                                 errx(1, "%lu: %s: \\%c not defined in the RE",
516                                                                 linenum, fname, *p);
517                                         if (s->maxbref < ref)
518                                                 s->maxbref = ref;
519                                 } else if (*p == '&' || *p == '\\')
520                                         *sp++ = '\\';
521                         } else if (*p == c) {
522                                 if (*++p == '\0' && more) {
523                                         if (cu_fgets(lbuf, sizeof(lbuf), &more))
524                                                 p = lbuf;
525                                 }
526                                 *sp++ = '\0';
527                                 size += sp - op;
528                                 if ((s->new = realloc(text, size)) == NULL)
529                                         err(1, "realloc");
530                                 return (p);
531                         } else if (*p == '\n') {
532                                 errx(1,
533 "%lu: %s: unescaped newline inside substitute pattern", linenum, fname);
534                                 /* NOTREACHED */
535                         }
536                         *sp++ = *p;
537                 }
538                 size += sp - op;
539                 if (asize - size < _POSIX2_LINE_MAX + 1) {
540                         asize *= 2;
541                         if ((text = realloc(text, asize)) == NULL)
542                                 err(1, "realloc");
543                 }
544         } while (cu_fgets(p = lbuf, sizeof(lbuf), &more));
545         errx(1, "%lu: %s: unterminated substitute in regular expression",
546                         linenum, fname);
547         /* NOTREACHED */
548 }
549
550 /*
551  * Compile the flags of the s command
552  */
553 static char *
554 compile_flags(p, s)
555         char *p;
556         struct s_subst *s;
557 {
558         int gn;                 /* True if we have seen g or n */
559         char wfile[_POSIX2_LINE_MAX + 1], *q;
560
561         s->n = 1;                               /* Default */
562         s->p = 0;
563         s->wfile = NULL;
564         s->wfd = -1;
565         for (gn = 0;;) {
566                 EATSPACE();                     /* EXTENSION */
567                 switch (*p) {
568                 case 'g':
569                         if (gn)
570                                 errx(1,
571 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
572                         gn = 1;
573                         s->n = 0;
574                         break;
575                 case '\0':
576                 case '\n':
577                 case ';':
578                         return (p);
579                 case 'p':
580                         s->p = 1;
581                         break;
582                 case '1': case '2': case '3':
583                 case '4': case '5': case '6':
584                 case '7': case '8': case '9':
585                         if (gn)
586                                 errx(1,
587 "%lu: %s: more than one number or 'g' in substitute flags", linenum, fname);
588                         gn = 1;
589                         /* XXX Check for overflow */
590                         s->n = (int)strtol(p, &p, 10);
591                         break;
592                 case 'w':
593                         p++;
594 #ifdef HISTORIC_PRACTICE
595                         if (*p != ' ') {
596                                 warnx("%lu: %s: space missing before w wfile", linenum, fname);
597                                 return (p);
598                         }
599 #endif
600                         EATSPACE();
601                         q = wfile;
602                         while (*p) {
603                                 if (*p == '\n')
604                                         break;
605                                 *q++ = *p++;
606                         }
607                         *q = '\0';
608                         if (q == wfile)
609                                 errx(1, "%lu: %s: no wfile specified", linenum, fname);
610                         s->wfile = strdup(wfile);
611                         if (!aflag && (s->wfd = open(wfile,
612                             O_WRONLY|O_APPEND|O_CREAT|O_TRUNC,
613                             DEFFILEMODE)) == -1)
614                                 err(1, "%s", wfile);
615                         return (p);
616                 default:
617                         errx(1, "%lu: %s: bad flag in substitute command: '%c'",
618                                         linenum, fname, *p);
619                         break;
620                 }
621                 p++;
622         }
623 }
624
625 /*
626  * Compile a translation set of strings into a lookup table.
627  */
628 static char *
629 compile_tr(p, transtab)
630         char *p;
631         char **transtab;
632 {
633         int i;
634         char *lt, *op, *np;
635         char old[_POSIX2_LINE_MAX + 1];
636         char new[_POSIX2_LINE_MAX + 1];
637
638         if (*p == '\0' || *p == '\\')
639                 errx(1,
640         "%lu: %s: transform pattern can not be delimited by newline or backslash",
641                         linenum, fname);
642         p = compile_delimited(p, old);
643         if (p == NULL)
644                 errx(1, "%lu: %s: unterminated transform source string",
645                                 linenum, fname);
646         p = compile_delimited(--p, new);
647         if (p == NULL)
648                 errx(1, "%lu: %s: unterminated transform target string",
649                                 linenum, fname);
650         EATSPACE();
651         if (strlen(new) != strlen(old))
652                 errx(1, "%lu: %s: transform strings are not the same length",
653                                 linenum, fname);
654         /* We assume characters are 8 bits */
655         if ((lt = malloc(UCHAR_MAX)) == NULL)
656                 err(1, "malloc");
657         for (i = 0; i <= UCHAR_MAX; i++)
658                 lt[i] = (char)i;
659         for (op = old, np = new; *op; op++, np++)
660                 lt[(u_char)*op] = *np;
661         *transtab = lt;
662         return (p);
663 }
664
665 /*
666  * Compile the text following an a or i command.
667  */
668 static char *
669 compile_text()
670 {
671         int asize, esc_nl, size;
672         char *text, *p, *op, *s;
673         char lbuf[_POSIX2_LINE_MAX + 1];
674
675         asize = 2 * _POSIX2_LINE_MAX + 1;
676         if ((text = malloc(asize)) == NULL)
677                 err(1, "malloc");
678         size = 0;
679         while (cu_fgets(lbuf, sizeof(lbuf), NULL)) {
680                 op = s = text + size;
681                 p = lbuf;
682                 EATSPACE();
683                 for (esc_nl = 0; *p != '\0'; p++) {
684                         if (*p == '\\' && p[1] != '\0' && *++p == '\n')
685                                 esc_nl = 1;
686                         *s++ = *p;
687                 }
688                 size += s - op;
689                 if (!esc_nl) {
690                         *s = '\0';
691                         break;
692                 }
693                 if (asize - size < _POSIX2_LINE_MAX + 1) {
694                         asize *= 2;
695                         if ((text = realloc(text, asize)) == NULL)
696                                 err(1, "realloc");
697                 }
698         }
699         text[size] = '\0';
700         if ((p = realloc(text, size + 1)) == NULL)
701                 err(1, "realloc");
702         return (p);
703 }
704
705 /*
706  * Get an address and return a pointer to the first character after
707  * it.  Fill the structure pointed to according to the address.
708  */
709 static char *
710 compile_addr(p, a)
711         char *p;
712         struct s_addr *a;
713 {
714         char *end;
715
716         switch (*p) {
717         case '\\':                              /* Context address */
718                 ++p;
719                 /* FALLTHROUGH */
720         case '/':                               /* Context address */
721                 p = compile_re(p, &a->u.r);
722                 if (p == NULL)
723                         errx(1, "%lu: %s: unterminated regular expression", linenum, fname);
724                 a->type = AT_RE;
725                 return (p);
726
727         case '$':                               /* Last line */
728                 a->type = AT_LAST;
729                 return (p + 1);
730                                                 /* Line number */
731         case '0': case '1': case '2': case '3': case '4':
732         case '5': case '6': case '7': case '8': case '9':
733                 a->type = AT_LINE;
734                 a->u.l = strtol(p, &end, 10);
735                 return (end);
736         default:
737                 errx(1, "%lu: %s: expected context address", linenum, fname);
738                 return (NULL);
739         }
740 }
741
742 /*
743  * duptoeol --
744  *      Return a copy of all the characters up to \n or \0.
745  */
746 static char *
747 duptoeol(s, ctype)
748         char *s;
749         const char *ctype;
750 {
751         size_t len;
752         int ws;
753         char *p, *start;
754
755         ws = 0;
756         for (start = s; *s != '\0' && *s != '\n'; ++s)
757                 ws = isspace((unsigned char)*s);
758         *s = '\0';
759         if (ws)
760                 warnx("%lu: %s: whitespace after %s", linenum, fname, ctype);
761         len = s - start + 1;
762         if ((p = malloc(len)) == NULL)
763                 err(1, "malloc");
764         return (memmove(p, start, len));
765 }
766
767 /*
768  * Convert goto label names to addresses, and count a and r commands, in
769  * the given subset of the script.  Free the memory used by labels in b
770  * and t commands (but not by :).
771  *
772  * TODO: Remove } nodes
773  */
774 static void
775 fixuplabel(cp, end)
776         struct s_command *cp, *end;
777 {
778
779         for (; cp != end; cp = cp->next)
780                 switch (cp->code) {
781                 case 'a':
782                 case 'r':
783                         appendnum++;
784                         break;
785                 case 'b':
786                 case 't':
787                         /* Resolve branch target. */
788                         if (cp->t == NULL) {
789                                 cp->u.c = NULL;
790                                 break;
791                         }
792                         if ((cp->u.c = findlabel(cp->t)) == NULL)
793                                 errx(1, "%lu: %s: undefined label '%s'", linenum, fname, cp->t);
794                         free(cp->t);
795                         break;
796                 case '{':
797                         /* Do interior commands. */
798                         fixuplabel(cp->u.c, cp->next);
799                         break;
800                 }
801 }
802
803 /*
804  * Associate the given command label for later lookup.
805  */
806 static void
807 enterlabel(cp)
808         struct s_command *cp;
809 {
810         struct labhash **lhp, *lh;
811         u_char *p;
812         u_int h, c;
813
814         for (h = 0, p = (u_char *)cp->t; (c = *p) != 0; p++)
815                 h = (h << 5) + h + c;
816         lhp = &labels[h & LHMASK];
817         for (lh = *lhp; lh != NULL; lh = lh->lh_next)
818                 if (lh->lh_hash == h && strcmp(cp->t, lh->lh_cmd->t) == 0)
819                         errx(1, "%lu: %s: duplicate label '%s'", linenum, fname, cp->t);
820         if ((lh = malloc(sizeof *lh)) == NULL)
821                 err(1, "malloc");
822         lh->lh_next = *lhp;
823         lh->lh_hash = h;
824         lh->lh_cmd = cp;
825         lh->lh_ref = 0;
826         *lhp = lh;
827 }
828
829 /*
830  * Find the label contained in the command l in the command linked
831  * list cp.  L is excluded from the search.  Return NULL if not found.
832  */
833 static struct s_command *
834 findlabel(name)
835         char *name;
836 {
837         struct labhash *lh;
838         u_char *p;
839         u_int h, c;
840
841         for (h = 0, p = (u_char *)name; (c = *p) != 0; p++)
842                 h = (h << 5) + h + c;
843         for (lh = labels[h & LHMASK]; lh != NULL; lh = lh->lh_next) {
844                 if (lh->lh_hash == h && strcmp(name, lh->lh_cmd->t) == 0) {
845                         lh->lh_ref = 1;
846                         return (lh->lh_cmd);
847                 }
848         }
849         return (NULL);
850 }
851
852 /*
853  * Warn about any unused labels.  As a side effect, release the label hash
854  * table space.
855  */
856 static void
857 uselabel()
858 {
859         struct labhash *lh, *next;
860         int i;
861
862         for (i = 0; i < LHSZ; i++) {
863                 for (lh = labels[i]; lh != NULL; lh = next) {
864                         next = lh->lh_next;
865                         if (!lh->lh_ref)
866                                 warnx("%lu: %s: unused label '%s'",
867                                     linenum, fname, lh->lh_cmd->t);
868                         free(lh);
869                 }
870         }
871 }