xref: /freebsd/usr.bin/tr/str.c (revision 48991a368427cadb9cdac39581d1676c29619c52)
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 #ifndef lint
35 static char sccsid[] = "@(#)str.c	8.2 (Berkeley) 4/28/95";
36 #endif /* not lint */
37 
38 #include <sys/cdefs.h>
39 #include <sys/types.h>
40 
41 #include <errno.h>
42 #include <stddef.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <ctype.h>
47 
48 #include "extern.h"
49 
50 static int	backslash __P((STR *));
51 static int	bracket __P((STR *));
52 static int	c_class __P((const void *, const void *));
53 static void	genclass __P((STR *));
54 static void	genequiv __P((STR *));
55 static int	genrange __P((STR *));
56 static void	genseq __P((STR *));
57 
58 int
59 next(s)
60 	register STR *s;
61 {
62 	register int ch;
63 
64 	switch (s->state) {
65 	case EOS:
66 		return (0);
67 	case INFINITE:
68 		return (1);
69 	case NORMAL:
70 		switch (ch = *s->str) {
71 		case '\0':
72 			s->state = EOS;
73 			return (0);
74 		case '\\':
75 			s->lastch = backslash(s);
76 			break;
77 		case '[':
78 			if (bracket(s))
79 				return (next(s));
80 			/* FALLTHROUGH */
81 		default:
82 			++s->str;
83 			s->lastch = ch;
84 			break;
85 		}
86 
87 		/* We can start a range at any time. */
88 		if (s->str[0] == '-' && genrange(s))
89 			return (next(s));
90 		return (1);
91 	case RANGE:
92 		if (s->cnt-- == 0) {
93 			s->state = NORMAL;
94 			return (next(s));
95 		}
96 		++s->lastch;
97 		return (1);
98 	case SEQUENCE:
99 		if (s->cnt-- == 0) {
100 			s->state = NORMAL;
101 			return (next(s));
102 		}
103 		return (1);
104 	case SET:
105 		if ((s->lastch = s->set[s->cnt++]) == OOBCH) {
106 			s->state = NORMAL;
107 			return (next(s));
108 		}
109 		return (1);
110 	}
111 	/* NOTREACHED */
112 }
113 
114 static int
115 bracket(s)
116 	register STR *s;
117 {
118 	register char *p;
119 
120 	switch (s->str[1]) {
121 	case ':':				/* "[:class:]" */
122 		if ((p = strstr(s->str + 2, ":]")) == NULL)
123 			return (0);
124 		*p = '\0';
125 		s->str += 2;
126 		genclass(s);
127 		s->str = p + 2;
128 		return (1);
129 	case '=':				/* "[=equiv=]" */
130 		if ((p = strstr(s->str + 2, "=]")) == NULL)
131 			return (0);
132 		s->str += 2;
133 		genequiv(s);
134 		return (1);
135 	default:				/* "[\###*n]" or "[#*n]" */
136 		if ((p = strpbrk(s->str + 2, "*]")) == NULL)
137 			return (0);
138 		if (p[0] != '*' || index(p, ']') == NULL)
139 			return (0);
140 		s->str += 1;
141 		genseq(s);
142 		return (1);
143 	}
144 	/* NOTREACHED */
145 }
146 
147 typedef struct {
148 	char *name;
149 	int (*func) __P((int));
150 	int *set;
151 } CLASS;
152 
153 static CLASS classes[] = {
154 #undef isalnum
155 	{ "alnum",  isalnum,  },
156 #undef isalpha
157 	{ "alpha",  isalpha,  },
158 #undef isblank
159 	{ "blank",  isblank,  },
160 #undef iscntrl
161 	{ "cntrl",  iscntrl,  },
162 #undef isdigit
163 	{ "digit",  isdigit,  },
164 #undef isgraph
165 	{ "graph",  isgraph,  },
166 #undef islower
167 	{ "lower",  islower,  },
168 #undef isprint
169 	{ "print",  isprint,  },
170 #undef ispunct
171 	{ "punct",  ispunct,  },
172 #undef isspace
173 	{ "space",  isspace,  },
174 #undef isupper
175 	{ "upper",  isupper,  },
176 #undef isxdigit
177 	{ "xdigit", isxdigit, },
178 };
179 
180 static void
181 genclass(s)
182 	STR *s;
183 {
184 	register int cnt, (*func) __P((int));
185 	CLASS *cp, tmp;
186 	int *p;
187 
188 	tmp.name = s->str;
189 	if ((cp = (CLASS *)bsearch(&tmp, classes, sizeof(classes) /
190 	    sizeof(CLASS), sizeof(CLASS), c_class)) == NULL)
191 		err("unknown class %s", s->str);
192 
193 	if ((cp->set = p = malloc((NCHARS + 1) * sizeof(int))) == NULL)
194 		err("%s", strerror(errno));
195 	bzero(p, (NCHARS + 1) * sizeof(int));
196 	for (cnt = 0, func = cp->func; cnt < NCHARS; ++cnt)
197 		if ((func)(cnt))
198 			*p++ = cnt;
199 	*p = OOBCH;
200 
201 	s->cnt = 0;
202 	s->state = SET;
203 	s->set = cp->set;
204 }
205 
206 static int
207 c_class(a, b)
208 	const void *a, *b;
209 {
210 	return (strcmp(((CLASS *)a)->name, ((CLASS *)b)->name));
211 }
212 
213 /*
214  * English doesn't have any equivalence classes, so for now
215  * we just syntax check and grab the character.
216  */
217 static void
218 genequiv(s)
219 	STR *s;
220 {
221 	if (*s->str == '\\') {
222 		s->equiv[0] = backslash(s);
223 		if (*s->str != '=')
224 			err("misplaced equivalence equals sign");
225 	} else {
226 		s->equiv[0] = s->str[0];
227 		if (s->str[1] != '=')
228 			err("misplaced equivalence equals sign");
229 	}
230 	s->str += 2;
231 	s->cnt = 0;
232 	s->state = SET;
233 	s->set = s->equiv;
234 }
235 
236 static int
237 genrange(s)
238 	STR *s;
239 {
240 	int stopval;
241 	char *savestart;
242 
243 	savestart = s->str;
244 	stopval = *++s->str == '\\' ? backslash(s) : *s->str++;
245 	if (stopval < (u_char)s->lastch) {
246 		s->str = savestart;
247 		return (0);
248 	}
249 	s->cnt = stopval - s->lastch + 1;
250 	s->state = RANGE;
251 	--s->lastch;
252 	return (1);
253 }
254 
255 static void
256 genseq(s)
257 	STR *s;
258 {
259 	char *ep;
260 
261 	if (s->which == STRING1)
262 		err("sequences only valid in string2");
263 
264 	if (*s->str == '\\')
265 		s->lastch = backslash(s);
266 	else
267 		s->lastch = *s->str++;
268 	if (*s->str != '*')
269 		err("misplaced sequence asterisk");
270 
271 	switch (*++s->str) {
272 	case '\\':
273 		s->cnt = backslash(s);
274 		break;
275 	case ']':
276 		s->cnt = 0;
277 		++s->str;
278 		break;
279 	default:
280 		if (isdigit(*s->str)) {
281 			s->cnt = strtol(s->str, &ep, 0);
282 			if (*ep == ']') {
283 				s->str = ep + 1;
284 				break;
285 			}
286 		}
287 		err("illegal sequence count");
288 		/* NOTREACHED */
289 	}
290 
291 	s->state = s->cnt ? SEQUENCE : INFINITE;
292 }
293 
294 /*
295  * Translate \??? into a character.  Up to 3 octal digits, if no digits either
296  * an escape code or a literal character.
297  */
298 static int
299 backslash(s)
300 	register STR *s;
301 {
302 	register int ch, cnt, val;
303 
304 	for (cnt = val = 0;;) {
305 		ch = *++s->str;
306 		if (!isascii(ch) || !isdigit(ch))
307 			break;
308 		val = val * 8 + ch - '0';
309 		if (++cnt == 3) {
310 			++s->str;
311 			break;
312 		}
313 	}
314 	if (cnt)
315 		return (val);
316 	if (ch != '\0')
317 		++s->str;
318 	switch (ch) {
319 		case 'a':			/* escape characters */
320 			return ('\7');
321 		case 'b':
322 			return ('\b');
323 		case 'f':
324 			return ('\f');
325 		case 'n':
326 			return ('\n');
327 		case 'r':
328 			return ('\r');
329 		case 't':
330 			return ('\t');
331 		case 'v':
332 			return ('\13');
333 		case '\0':			/*  \" -> \ */
334 			s->state = EOS;
335 			return ('\\');
336 		default:			/* \x" -> x */
337 			return (ch);
338 	}
339 }
340