str.c revision 118415
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 118415 2003-08-04 05:22:06Z ache $");
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 *, int *);
55static int	bracket(STR *);
56static int	c_class(const void *, const void *);
57static void	genclass(STR *);
58static void	genequiv(STR *);
59static int      genrange(STR *, int);
60static void	genseq(STR *);
61
62int
63next(s)
64	STR *s;
65{
66	int ch, is_octal;
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, &is_octal);
80			break;
81		case '[':
82			if (bracket(s))
83				return (next(s));
84			/* FALLTHROUGH */
85		default:
86			is_octal = 0;
87			++s->str;
88			s->lastch = ch;
89			break;
90		}
91
92		/* We can start a range at any time. */
93		if (s->str[0] == '-' && genrange(s, is_octal))
94			return (next(s));
95		return (1);
96	case RANGE:
97		if (s->cnt-- == 0) {
98			s->state = NORMAL;
99			return (next(s));
100		}
101		++s->lastch;
102		return (1);
103	case SEQUENCE:
104		if (s->cnt-- == 0) {
105			s->state = NORMAL;
106			return (next(s));
107		}
108		return (1);
109	case SET:
110	case SET_UPPER:
111	case SET_LOWER:
112		if ((ch = s->set[s->cnt++]) == OOBCH) {
113			s->state = NORMAL;
114			return (next(s));
115		}
116		s->lastch = ch;
117		return (1);
118	default:
119		return (0);
120	}
121	/* NOTREACHED */
122}
123
124static int
125bracket(s)
126	STR *s;
127{
128	char *p;
129
130	switch (s->str[1]) {
131	case ':':				/* "[:class:]" */
132		if ((p = strchr(s->str + 2, ']')) == NULL)
133			return (0);
134		if (*(p - 1) != ':' || p - s->str < 4)
135			goto repeat;
136		*(p - 1) = '\0';
137		s->str += 2;
138		genclass(s);
139		s->str = p + 1;
140		return (1);
141	case '=':				/* "[=equiv=]" */
142		if ((p = strchr(s->str + 2, ']')) == NULL)
143			return (0);
144		if (*(p - 1) != '=' || p - s->str < 4)
145			goto repeat;
146		s->str += 2;
147		genequiv(s);
148		return (1);
149	default:				/* "[\###*n]" or "[#*n]" */
150	repeat:
151		if ((p = strpbrk(s->str + 2, "*]")) == NULL)
152			return (0);
153		if (p[0] != '*' || index(p, ']') == NULL)
154			return (0);
155		s->str += 1;
156		genseq(s);
157		return (1);
158	}
159	/* NOTREACHED */
160}
161
162typedef struct {
163	const char *name;
164	int (*func)(int);
165	int *set;
166} CLASS;
167
168static CLASS classes[] = {
169#undef isalnum
170	{ "alnum",  isalnum,  NULL },
171#undef isalpha
172	{ "alpha",  isalpha,  NULL },
173#undef isblank
174	{ "blank",  isblank,  NULL },
175#undef iscntrl
176	{ "cntrl",  iscntrl,  NULL },
177#undef isdigit
178	{ "digit",  isdigit,  NULL },
179#undef isgraph
180	{ "graph",  isgraph,  NULL },
181#undef islower
182	{ "lower",  islower,  NULL },
183#undef isprint
184	{ "print",  isprint,  NULL },
185#undef ispunct
186	{ "punct",  ispunct,  NULL },
187#undef isspace
188	{ "space",  isspace,  NULL },
189#undef isupper
190	{ "upper",  isupper,  NULL },
191#undef isxdigit
192	{ "xdigit", isxdigit, NULL },
193};
194
195static void
196genclass(s)
197	STR *s;
198{
199	int cnt, (*func)(int);
200	CLASS *cp, tmp;
201	int *p, n;
202
203	tmp.name = s->str;
204	if ((cp = (CLASS *)bsearch(&tmp, classes, sizeof(classes) /
205	    sizeof(CLASS), sizeof(CLASS), c_class)) == NULL)
206		errx(1, "unknown class %s", s->str);
207
208	if ((cp->set = p = malloc((NCHARS + 1) * sizeof(int))) == NULL)
209		err(1, "genclass() malloc");
210	for (cnt = 0, func = cp->func; cnt < NCHARS; ++cnt)
211		if ((func)(cnt))
212			*p++ = cnt;
213	*p = OOBCH;
214	n = p - cp->set;
215
216	s->cnt = 0;
217	s->set = cp->set;
218	if (strcmp(s->str, "upper") == 0)
219		s->state = SET_UPPER;
220	else if (strcmp(s->str, "lower") == 0) {
221		s->state = SET_LOWER;
222	} else
223		s->state = SET;
224	if ((s->state == SET_LOWER || s->state == SET_UPPER) && n > 1)
225		mergesort(s->set, n, sizeof(*(s->set)), charcoll);
226}
227
228static int
229c_class(a, b)
230	const void *a, *b;
231{
232	return (strcmp(((const CLASS *)a)->name, ((const CLASS *)b)->name));
233}
234
235static void
236genequiv(s)
237	STR *s;
238{
239	int i, p, pri;
240	char src[2], dst[3];
241
242	if (*s->str == '\\') {
243		s->equiv[0] = backslash(s, NULL);
244		if (*s->str != '=')
245			errx(1, "misplaced equivalence equals sign");
246		s->str += 2;
247	} else {
248		s->equiv[0] = s->str[0];
249		if (s->str[1] != '=')
250			errx(1, "misplaced equivalence equals sign");
251		s->str += 3;
252	}
253
254	/*
255	 * Calculate the set of all characters in the same equivalence class
256	 * as the specified character (they will have the same primary
257	 * collation weights).
258	 * XXX Knows too much about how strxfrm() is implemented. Assumes
259	 * it fills the string with primary collation weight bytes. Only one-
260	 * to-one mappings are supported.
261	 */
262	src[0] = s->equiv[0];
263	src[1] = '\0';
264	if (strxfrm(dst, src, sizeof(dst)) == 1) {
265		pri = (unsigned char)*dst;
266		for (p = 1, i = 1; i < NCHARS; i++) {
267			*src = i;
268			if (strxfrm(dst, src, sizeof(dst)) == 1 && pri &&
269			    pri == (unsigned char)*dst)
270				s->equiv[p++] = i;
271		}
272		s->equiv[p] = OOBCH;
273	}
274
275	s->cnt = 0;
276	s->state = SET;
277	s->set = s->equiv;
278}
279
280static int
281genrange(STR *s, int was_octal)
282{
283	int stopval, octal;
284	char *savestart;
285	int n, cnt, *p;
286
287	octal = 0;
288	savestart = s->str;
289	stopval = *++s->str == '\\' ? backslash(s, &octal) : (u_char)*s->str++;
290	if (!octal)
291		octal = was_octal;
292
293	if ((octal && stopval < s->lastch) ||
294	    (!octal &&
295	     charcoll((const void *)&stopval, (const void *)&(s->lastch)) < 0)) {
296		s->str = savestart;
297		return (0);
298	}
299	if (octal) {
300		s->cnt = stopval - s->lastch + 1;
301		s->state = RANGE;
302		--s->lastch;
303		return (1);
304	}
305	if ((s->set = p = malloc((NCHARS + 1) * sizeof(int))) == NULL)
306		err(1, "genrange() malloc");
307	for (cnt = 0; cnt < NCHARS; cnt++)
308		if (charcoll((const void *)&cnt, (const void *)&(s->lastch)) >= 0 &&
309		    charcoll((const void *)&cnt, (const void *)&stopval) <= 0)
310			*p++ = cnt;
311	*p = OOBCH;
312	n = p - s->set;
313
314	s->cnt = 0;
315	s->state = SET;
316	if (n > 1)
317		mergesort(s->set, n, sizeof(*(s->set)), charcoll);
318	return (1);
319}
320
321static void
322genseq(s)
323	STR *s;
324{
325	char *ep;
326
327	if (s->which == STRING1)
328		errx(1, "sequences only valid in string2");
329
330	if (*s->str == '\\')
331		s->lastch = backslash(s, NULL);
332	else
333		s->lastch = *s->str++;
334	if (*s->str != '*')
335		errx(1, "misplaced sequence asterisk");
336
337	switch (*++s->str) {
338	case '\\':
339		s->cnt = backslash(s, NULL);
340		break;
341	case ']':
342		s->cnt = 0;
343		++s->str;
344		break;
345	default:
346		if (isdigit((u_char)*s->str)) {
347			s->cnt = strtol(s->str, &ep, 0);
348			if (*ep == ']') {
349				s->str = ep + 1;
350				break;
351			}
352		}
353		errx(1, "illegal sequence count");
354		/* NOTREACHED */
355	}
356
357	s->state = s->cnt ? SEQUENCE : INFINITE;
358}
359
360/*
361 * Translate \??? into a character.  Up to 3 octal digits, if no digits either
362 * an escape code or a literal character.
363 */
364static int
365backslash(STR *s, int *is_octal)
366{
367	int ch, cnt, val;
368
369	if (is_octal != NULL)
370		*is_octal = 0;
371	for (cnt = val = 0;;) {
372		ch = (u_char)*++s->str;
373		if (!isdigit(ch))
374			break;
375		val = val * 8 + ch - '0';
376		if (++cnt == 3) {
377			++s->str;
378			break;
379		}
380	}
381	if (cnt) {
382		if (is_octal != NULL)
383			*is_octal = 1;
384		return (val);
385	}
386	if (ch != '\0')
387		++s->str;
388	switch (ch) {
389		case 'a':			/* escape characters */
390			return ('\7');
391		case 'b':
392			return ('\b');
393		case 'f':
394			return ('\f');
395		case 'n':
396			return ('\n');
397		case 'r':
398			return ('\r');
399		case 't':
400			return ('\t');
401		case 'v':
402			return ('\13');
403		case '\0':			/*  \" -> \ */
404			s->state = EOS;
405			return ('\\');
406		default:			/* \x" -> x */
407			return (ch);
408	}
409}
410