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