str.c revision 98210
1/*-
2 * Copyright (c) 1991, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#include <sys/cdefs.h>
35
36__FBSDID("$FreeBSD: head/usr.bin/tr/str.c 98210 2002-06-14 07:37:08Z tjr $");
37
38#ifndef lint
39static const char sccsid[] = "@(#)str.c	8.2 (Berkeley) 4/28/95";
40#endif
41
42#include <sys/cdefs.h>
43#include <sys/types.h>
44
45#include <ctype.h>
46#include <err.h>
47#include <stddef.h>
48#include <stdio.h>
49#include <stdlib.h>
50#include <string.h>
51
52#include "extern.h"
53
54static int	backslash(STR *);
55static int	bracket(STR *);
56static int	c_class(const void *, const void *);
57static void	genclass(STR *);
58static void	genequiv(STR *);
59static int	genrange(STR *);
60static void	genseq(STR *);
61
62int
63next(s)
64	STR *s;
65{
66	int ch;
67
68	switch (s->state) {
69	case EOS:
70		return (0);
71	case INFINITE:
72		return (1);
73	case NORMAL:
74		switch (ch = (u_char)*s->str) {
75		case '\0':
76			s->state = EOS;
77			return (0);
78		case '\\':
79			s->lastch = backslash(s);
80			break;
81		case '[':
82			if (bracket(s))
83				return (next(s));
84			/* FALLTHROUGH */
85		default:
86			++s->str;
87			s->lastch = ch;
88			break;
89		}
90
91		/* We can start a range at any time. */
92		if (s->str[0] == '-' && genrange(s))
93			return (next(s));
94		return (1);
95	case RANGE:
96		if (s->cnt-- == 0) {
97			s->state = NORMAL;
98			return (next(s));
99		}
100		++s->lastch;
101		return (1);
102	case SEQUENCE:
103		if (s->cnt-- == 0) {
104			s->state = NORMAL;
105			return (next(s));
106		}
107		return (1);
108	case SET:
109		if ((s->lastch = s->set[s->cnt++]) == OOBCH) {
110			s->state = NORMAL;
111			return (next(s));
112		}
113		return (1);
114	default:
115		return (0);
116	}
117	/* NOTREACHED */
118}
119
120static int
121bracket(s)
122	STR *s;
123{
124	char *p;
125
126	switch (s->str[1]) {
127	case ':':				/* "[:class:]" */
128		if ((p = strstr(s->str + 2, ":]")) == NULL)
129			return (0);
130		*p = '\0';
131		s->str += 2;
132		genclass(s);
133		s->str = p + 2;
134		return (1);
135	case '=':				/* "[=equiv=]" */
136		if ((p = strstr(s->str + 2, "=]")) == NULL)
137			return (0);
138		s->str += 2;
139		genequiv(s);
140		return (1);
141	default:				/* "[\###*n]" or "[#*n]" */
142		if ((p = strpbrk(s->str + 2, "*]")) == NULL)
143			return (0);
144		if (p[0] != '*' || index(p, ']') == NULL)
145			return (0);
146		s->str += 1;
147		genseq(s);
148		return (1);
149	}
150	/* NOTREACHED */
151}
152
153typedef struct {
154	const char *name;
155	int (*func)(int);
156	int *set;
157} CLASS;
158
159static CLASS classes[] = {
160#undef isalnum
161	{ "alnum",  isalnum,  NULL },
162#undef isalpha
163	{ "alpha",  isalpha,  NULL },
164#undef isblank
165	{ "blank",  isblank,  NULL },
166#undef iscntrl
167	{ "cntrl",  iscntrl,  NULL },
168#undef isdigit
169	{ "digit",  isdigit,  NULL },
170#undef isgraph
171	{ "graph",  isgraph,  NULL },
172#undef islower
173	{ "lower",  islower,  NULL },
174#undef isprint
175	{ "print",  isprint,  NULL },
176#undef ispunct
177	{ "punct",  ispunct,  NULL },
178#undef isspace
179	{ "space",  isspace,  NULL },
180#undef isupper
181	{ "upper",  isupper,  NULL },
182#undef isxdigit
183	{ "xdigit", isxdigit, NULL },
184};
185
186static void
187genclass(s)
188	STR *s;
189{
190	int cnt, (*func)(int);
191	CLASS *cp, tmp;
192	int *p;
193
194	tmp.name = s->str;
195	if ((cp = (CLASS *)bsearch(&tmp, classes, sizeof(classes) /
196	    sizeof(CLASS), sizeof(CLASS), c_class)) == NULL)
197		errx(1, "unknown class %s", s->str);
198
199	if ((cp->set = p = malloc((NCHARS + 1) * sizeof(int))) == NULL)
200		errx(1, "malloc");
201	bzero(p, (NCHARS + 1) * sizeof(int));
202	for (cnt = 0, func = cp->func; cnt < NCHARS; ++cnt)
203		if ((func)(cnt))
204			*p++ = cnt;
205	*p = OOBCH;
206
207	s->cnt = 0;
208	s->state = SET;
209	s->set = cp->set;
210}
211
212static int
213c_class(a, b)
214	const void *a, *b;
215{
216	return (strcmp(((const CLASS *)a)->name, ((const CLASS *)b)->name));
217}
218
219static void
220genequiv(s)
221	STR *s;
222{
223	int i, p, pri;
224	char src[2], dst[3];
225
226	if (*s->str == '\\') {
227		s->equiv[0] = backslash(s);
228		if (*s->str != '=')
229			errx(1, "misplaced equivalence equals sign");
230	} else {
231		s->equiv[0] = s->str[0];
232		if (s->str[1] != '=')
233			errx(1, "misplaced equivalence equals sign");
234	}
235
236	/*
237	 * Calculate the set of all characters in the same equivalence class
238	 * as the specified character (they will have the same primary
239	 * collation weights).
240	 * XXX Knows too much about how strxfrm() is implemented. Assumes
241	 * it fills the string with primary collation weight bytes. Only one-
242	 * to-one mappings are supported.
243	 */
244	src[0] = s->equiv[0];
245	src[1] = '\0';
246	if (strxfrm(dst, src, sizeof(dst)) == 1) {
247		pri = (unsigned char)*dst;
248		for (p = 1, i = 1; i < NCHARS; i++) {
249			*src = i;
250			if (strxfrm(dst, src, sizeof(dst)) == 1 && pri &&
251			    pri == (unsigned char)*dst)
252				s->equiv[p++] = i;
253		}
254		s->equiv[p] = OOBCH;
255	}
256
257	s->str += 2;
258	s->cnt = 0;
259	s->state = SET;
260	s->set = s->equiv;
261}
262
263static int
264genrange(s)
265	STR *s;
266{
267	int stopval;
268	char *savestart;
269
270	savestart = s->str;
271	stopval = *++s->str == '\\' ? backslash(s) : (u_char)*s->str++;
272	if (stopval < (u_char)s->lastch) {
273		s->str = savestart;
274		return (0);
275	}
276	s->cnt = stopval - s->lastch + 1;
277	s->state = RANGE;
278	--s->lastch;
279	return (1);
280}
281
282static void
283genseq(s)
284	STR *s;
285{
286	char *ep;
287
288	if (s->which == STRING1)
289		errx(1, "sequences only valid in string2");
290
291	if (*s->str == '\\')
292		s->lastch = backslash(s);
293	else
294		s->lastch = *s->str++;
295	if (*s->str != '*')
296		errx(1, "misplaced sequence asterisk");
297
298	switch (*++s->str) {
299	case '\\':
300		s->cnt = backslash(s);
301		break;
302	case ']':
303		s->cnt = 0;
304		++s->str;
305		break;
306	default:
307		if (isdigit((u_char)*s->str)) {
308			s->cnt = strtol(s->str, &ep, 0);
309			if (*ep == ']') {
310				s->str = ep + 1;
311				break;
312			}
313		}
314		errx(1, "illegal sequence count");
315		/* NOTREACHED */
316	}
317
318	s->state = s->cnt ? SEQUENCE : INFINITE;
319}
320
321/*
322 * Translate \??? into a character.  Up to 3 octal digits, if no digits either
323 * an escape code or a literal character.
324 */
325static int
326backslash(s)
327	STR *s;
328{
329	int ch, cnt, val;
330
331	for (cnt = val = 0;;) {
332		ch = (u_char)*++s->str;
333		if (!isascii(ch) || !isdigit(ch))
334			break;
335		val = val * 8 + ch - '0';
336		if (++cnt == 3) {
337			++s->str;
338			break;
339		}
340	}
341	if (cnt)
342		return (val);
343	if (ch != '\0')
344		++s->str;
345	switch (ch) {
346		case 'a':			/* escape characters */
347			return ('\7');
348		case 'b':
349			return ('\b');
350		case 'f':
351			return ('\f');
352		case 'n':
353			return ('\n');
354		case 'r':
355			return ('\r');
356		case 't':
357			return ('\t');
358		case 'v':
359			return ('\13');
360		case '\0':			/*  \" -> \ */
361			s->state = EOS;
362			return ('\\');
363		default:			/* \x" -> x */
364			return (ch);
365	}
366}
367