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