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