xref: /freebsd/usr.bin/tr/str.c (revision c4f6a2a9e1b1879b618c436ab4f56ff75c73a0f5)
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$");
37 
38 #ifndef lint
39 static 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 
54 static int	backslash(STR *);
55 static int	bracket(STR *);
56 static int	c_class(const void *, const void *);
57 static void	genclass(STR *);
58 static void	genequiv(STR *);
59 static int	genrange(STR *);
60 static void	genseq(STR *);
61 
62 int
63 next(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 
120 static int
121 bracket(s)
122 	STR *s;
123 {
124 	char *p;
125 
126 	switch (s->str[1]) {
127 	case ':':				/* "[:class:]" */
128 		if ((p = strchr(s->str + 2, ']')) == NULL)
129 			return (0);
130 		if (*(p - 1) != ':' || p - s->str < 4)
131 			goto repeat;
132 		*(p - 1) = '\0';
133 		s->str += 2;
134 		genclass(s);
135 		s->str = p + 1;
136 		return (1);
137 	case '=':				/* "[=equiv=]" */
138 		if ((p = strchr(s->str + 2, ']')) == NULL)
139 			return (0);
140 		if (*(p - 1) != '=' || p - s->str < 4)
141 			goto repeat;
142 		s->str += 2;
143 		genequiv(s);
144 		return (1);
145 	default:				/* "[\###*n]" or "[#*n]" */
146 	repeat:
147 		if ((p = strpbrk(s->str + 2, "*]")) == NULL)
148 			return (0);
149 		if (p[0] != '*' || index(p, ']') == NULL)
150 			return (0);
151 		s->str += 1;
152 		genseq(s);
153 		return (1);
154 	}
155 	/* NOTREACHED */
156 }
157 
158 typedef struct {
159 	const char *name;
160 	int (*func)(int);
161 	int *set;
162 } CLASS;
163 
164 static CLASS classes[] = {
165 #undef isalnum
166 	{ "alnum",  isalnum,  NULL },
167 #undef isalpha
168 	{ "alpha",  isalpha,  NULL },
169 #undef isblank
170 	{ "blank",  isblank,  NULL },
171 #undef iscntrl
172 	{ "cntrl",  iscntrl,  NULL },
173 #undef isdigit
174 	{ "digit",  isdigit,  NULL },
175 #undef isgraph
176 	{ "graph",  isgraph,  NULL },
177 #undef islower
178 	{ "lower",  islower,  NULL },
179 #undef isprint
180 	{ "print",  isprint,  NULL },
181 #undef ispunct
182 	{ "punct",  ispunct,  NULL },
183 #undef isspace
184 	{ "space",  isspace,  NULL },
185 #undef isupper
186 	{ "upper",  isupper,  NULL },
187 #undef isxdigit
188 	{ "xdigit", isxdigit, NULL },
189 };
190 
191 static void
192 genclass(s)
193 	STR *s;
194 {
195 	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 		err(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 
217 static int
218 c_class(a, b)
219 	const void *a, *b;
220 {
221 	return (strcmp(((const CLASS *)a)->name, ((const CLASS *)b)->name));
222 }
223 
224 static void
225 genequiv(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 
269 static int
270 genrange(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 
288 static void
289 genseq(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  */
331 static int
332 backslash(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