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