str.c revision 98242
1117395Skan/*-
2117395Skan * Copyright (c) 1991, 1993
3132718Skan *	The Regents of the University of California.  All rights reserved.
4117395Skan *
5117395Skan * Redistribution and use in source and binary forms, with or without
6132718Skan * modification, are permitted provided that the following conditions
7117395Skan * are met:
8132718Skan * 1. Redistributions of source code must retain the above copyright
9132718Skan *    notice, this list of conditions and the following disclaimer.
10132718Skan * 2. Redistributions in binary form must reproduce the above copyright
11132718Skan *    notice, this list of conditions and the following disclaimer in the
12117395Skan *    documentation and/or other materials provided with the distribution.
13132718Skan * 3. All advertising materials mentioning features or use of this software
14132718Skan *    must display the following acknowledgement:
15132718Skan *	This product includes software developed by the University of
16132718Skan *	California, Berkeley and its contributors.
17117395Skan * 4. Neither the name of the University nor the names of its contributors
18132718Skan *    may be used to endorse or promote products derived from this software
19132718Skan *    without specific prior written permission.
20132718Skan *
21132718Skan * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22117395Skan * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23117395Skan * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24117395Skan * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25117395Skan * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26117395Skan * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27117395Skan * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28117395Skan * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29117395Skan * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30117395Skan * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31117395Skan * SUCH DAMAGE.
32117395Skan */
33117395Skan
34117395Skan#include <sys/cdefs.h>
35117395Skan
36117395Skan__FBSDID("$FreeBSD: head/usr.bin/tr/str.c 98242 2002-06-15 07:38:27Z tjr $");
37117395Skan
38117395Skan#ifndef lint
39117395Skanstatic const char sccsid[] = "@(#)str.c	8.2 (Berkeley) 4/28/95";
40117395Skan#endif
41117395Skan
42117395Skan#include <sys/cdefs.h>
43117395Skan#include <sys/types.h>
44117395Skan
45117395Skan#include <ctype.h>
46117395Skan#include <err.h>
47117395Skan#include <stddef.h>
48117395Skan#include <stdio.h>
49117395Skan#include <stdlib.h>
50117395Skan#include <string.h>
51117395Skan
52117395Skan#include "extern.h"
53117395Skan
54117395Skanstatic int	backslash(STR *);
55117395Skanstatic int	bracket(STR *);
56117395Skanstatic int	c_class(const void *, const void *);
57117395Skanstatic void	genclass(STR *);
58117395Skanstatic void	genequiv(STR *);
59117395Skanstatic int	genrange(STR *);
60117395Skanstatic void	genseq(STR *);
61117395Skan
62132718Skanint
63117395Skannext(s)
64132718Skan	STR *s;
65117395Skan{
66117395Skan	int ch;
67117395Skan
68117395Skan	switch (s->state) {
69117395Skan	case EOS:
70117395Skan		return (0);
71132718Skan	case INFINITE:
72132718Skan		return (1);
73117395Skan	case NORMAL:
74117395Skan		switch (ch = (u_char)*s->str) {
75117395Skan		case '\0':
76117395Skan			s->state = EOS;
77117395Skan			return (0);
78117395Skan		case '\\':
79132718Skan			s->lastch = backslash(s);
80132718Skan			break;
81117395Skan		case '[':
82117395Skan			if (bracket(s))
83117395Skan				return (next(s));
84117395Skan			/* FALLTHROUGH */
85117395Skan		default:
86117395Skan			++s->str;
87117395Skan			s->lastch = ch;
88117395Skan			break;
89117395Skan		}
90117395Skan
91117395Skan		/* We can start a range at any time. */
92117395Skan		if (s->str[0] == '-' && genrange(s))
93117395Skan			return (next(s));
94117395Skan		return (1);
95117395Skan	case RANGE:
96117395Skan		if (s->cnt-- == 0) {
97117395Skan			s->state = NORMAL;
98117395Skan			return (next(s));
99117395Skan		}
100117395Skan		++s->lastch;
101117395Skan		return (1);
102117395Skan	case SEQUENCE:
103117395Skan		if (s->cnt-- == 0) {
104117395Skan			s->state = NORMAL;
105117395Skan			return (next(s));
106117395Skan		}
107117395Skan		return (1);
108117395Skan	case SET:
109117395Skan		if ((s->lastch = s->set[s->cnt++]) == OOBCH) {
110117395Skan			s->state = NORMAL;
111117395Skan			return (next(s));
112117395Skan		}
113117395Skan		return (1);
114117395Skan	default:
115117395Skan		return (0);
116117395Skan	}
117117395Skan	/* NOTREACHED */
118117395Skan}
119117395Skan
120117395Skanstatic int
121117395Skanbracket(s)
122117395Skan	STR *s;
123117395Skan{
124117395Skan	char *p;
125117395Skan
126117395Skan	switch (s->str[1]) {
127117395Skan	case ':':				/* "[:class:]" */
128117395Skan		if ((p = strchr(s->str + 2, ']')) == NULL)
129117395Skan			return (0);
130117395Skan		if (*(p - 1) != ':' || p - s->str < 4)
131117395Skan			goto repeat;
132117395Skan		*(p - 1) = '\0';
133117395Skan		s->str += 2;
134117395Skan		genclass(s);
135117395Skan		s->str = p + 1;
136117395Skan		return (1);
137117395Skan	case '=':				/* "[=equiv=]" */
138117395Skan		if ((p = strchr(s->str + 2, ']')) == NULL)
139117395Skan			return (0);
140117395Skan		if (*(p - 1) != '=' || p - s->str < 4)
141117395Skan			goto repeat;
142117395Skan		s->str += 2;
143117395Skan		genequiv(s);
144117395Skan		return (1);
145117395Skan	default:				/* "[\###*n]" or "[#*n]" */
146117395Skan	repeat:
147117395Skan		if ((p = strpbrk(s->str + 2, "*]")) == NULL)
148117395Skan			return (0);
149117395Skan		if (p[0] != '*' || index(p, ']') == NULL)
150117395Skan			return (0);
151117395Skan		s->str += 1;
152117395Skan		genseq(s);
153117395Skan		return (1);
154117395Skan	}
155117395Skan	/* NOTREACHED */
156117395Skan}
157117395Skan
158117395Skantypedef struct {
159117395Skan	const char *name;
160117395Skan	int (*func)(int);
161117395Skan	int *set;
162117395Skan} CLASS;
163117395Skan
164117395Skanstatic CLASS classes[] = {
165117395Skan#undef isalnum
166117395Skan	{ "alnum",  isalnum,  NULL },
167117395Skan#undef isalpha
168117395Skan	{ "alpha",  isalpha,  NULL },
169117395Skan#undef isblank
170117395Skan	{ "blank",  isblank,  NULL },
171117395Skan#undef iscntrl
172117395Skan	{ "cntrl",  iscntrl,  NULL },
173117395Skan#undef isdigit
174117395Skan	{ "digit",  isdigit,  NULL },
175117395Skan#undef isgraph
176117395Skan	{ "graph",  isgraph,  NULL },
177117395Skan#undef islower
178117395Skan	{ "lower",  islower,  NULL },
179117395Skan#undef isprint
180117395Skan	{ "print",  isprint,  NULL },
181117395Skan#undef ispunct
182117395Skan	{ "punct",  ispunct,  NULL },
183117395Skan#undef isspace
184117395Skan	{ "space",  isspace,  NULL },
185117395Skan#undef isupper
186117395Skan	{ "upper",  isupper,  NULL },
187117395Skan#undef isxdigit
188117395Skan	{ "xdigit", isxdigit, NULL },
189117395Skan};
190117395Skan
191132718Skanstatic void
192132718Skangenclass(s)
193132718Skan	STR *s;
194132718Skan{
195132718Skan	int cnt, (*func)(int);
196	CLASS *cp, tmp;
197	int *p;
198
199	tmp.name = s->str;
200	if ((cp = (CLASS *)bsearch(&tmp, classes, sizeof(classes) /
201	    sizeof(CLASS), sizeof(CLASS), c_class)) == NULL)
202		errx(1, "unknown class %s", s->str);
203
204	if ((cp->set = p = malloc((NCHARS + 1) * sizeof(int))) == NULL)
205		errx(1, "malloc");
206	bzero(p, (NCHARS + 1) * sizeof(int));
207	for (cnt = 0, func = cp->func; cnt < NCHARS; ++cnt)
208		if ((func)(cnt))
209			*p++ = cnt;
210	*p = OOBCH;
211
212	s->cnt = 0;
213	s->state = SET;
214	s->set = cp->set;
215}
216
217static int
218c_class(a, b)
219	const void *a, *b;
220{
221	return (strcmp(((const CLASS *)a)->name, ((const CLASS *)b)->name));
222}
223
224static void
225genequiv(s)
226	STR *s;
227{
228	int i, p, pri;
229	char src[2], dst[3];
230
231	if (*s->str == '\\') {
232		s->equiv[0] = backslash(s);
233		if (*s->str != '=')
234			errx(1, "misplaced equivalence equals sign");
235		s->str += 2;
236	} else {
237		s->equiv[0] = s->str[0];
238		if (s->str[1] != '=')
239			errx(1, "misplaced equivalence equals sign");
240		s->str += 3;
241	}
242
243	/*
244	 * Calculate the set of all characters in the same equivalence class
245	 * as the specified character (they will have the same primary
246	 * collation weights).
247	 * XXX Knows too much about how strxfrm() is implemented. Assumes
248	 * it fills the string with primary collation weight bytes. Only one-
249	 * to-one mappings are supported.
250	 */
251	src[0] = s->equiv[0];
252	src[1] = '\0';
253	if (strxfrm(dst, src, sizeof(dst)) == 1) {
254		pri = (unsigned char)*dst;
255		for (p = 1, i = 1; i < NCHARS; i++) {
256			*src = i;
257			if (strxfrm(dst, src, sizeof(dst)) == 1 && pri &&
258			    pri == (unsigned char)*dst)
259				s->equiv[p++] = i;
260		}
261		s->equiv[p] = OOBCH;
262	}
263
264	s->cnt = 0;
265	s->state = SET;
266	s->set = s->equiv;
267}
268
269static int
270genrange(s)
271	STR *s;
272{
273	int stopval;
274	char *savestart;
275
276	savestart = s->str;
277	stopval = *++s->str == '\\' ? backslash(s) : (u_char)*s->str++;
278	if (stopval < (u_char)s->lastch) {
279		s->str = savestart;
280		return (0);
281	}
282	s->cnt = stopval - s->lastch + 1;
283	s->state = RANGE;
284	--s->lastch;
285	return (1);
286}
287
288static void
289genseq(s)
290	STR *s;
291{
292	char *ep;
293
294	if (s->which == STRING1)
295		errx(1, "sequences only valid in string2");
296
297	if (*s->str == '\\')
298		s->lastch = backslash(s);
299	else
300		s->lastch = *s->str++;
301	if (*s->str != '*')
302		errx(1, "misplaced sequence asterisk");
303
304	switch (*++s->str) {
305	case '\\':
306		s->cnt = backslash(s);
307		break;
308	case ']':
309		s->cnt = 0;
310		++s->str;
311		break;
312	default:
313		if (isdigit((u_char)*s->str)) {
314			s->cnt = strtol(s->str, &ep, 0);
315			if (*ep == ']') {
316				s->str = ep + 1;
317				break;
318			}
319		}
320		errx(1, "illegal sequence count");
321		/* NOTREACHED */
322	}
323
324	s->state = s->cnt ? SEQUENCE : INFINITE;
325}
326
327/*
328 * Translate \??? into a character.  Up to 3 octal digits, if no digits either
329 * an escape code or a literal character.
330 */
331static int
332backslash(s)
333	STR *s;
334{
335	int ch, cnt, val;
336
337	for (cnt = val = 0;;) {
338		ch = (u_char)*++s->str;
339		if (!isascii(ch) || !isdigit(ch))
340			break;
341		val = val * 8 + ch - '0';
342		if (++cnt == 3) {
343			++s->str;
344			break;
345		}
346	}
347	if (cnt)
348		return (val);
349	if (ch != '\0')
350		++s->str;
351	switch (ch) {
352		case 'a':			/* escape characters */
353			return ('\7');
354		case 'b':
355			return ('\b');
356		case 'f':
357			return ('\f');
358		case 'n':
359			return ('\n');
360		case 'r':
361			return ('\r');
362		case 't':
363			return ('\t');
364		case 'v':
365			return ('\13');
366		case '\0':			/*  \" -> \ */
367			s->state = EOS;
368			return ('\\');
369		default:			/* \x" -> x */
370			return (ch);
371	}
372}
373