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