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