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