xref: /netbsd-src/usr.bin/tr/str.c (revision b757af438b42b93f8c6571f026d8b8ef3eaf5fc9)
1 /*	$NetBSD: str.c,v 1.19 2011/09/08 12:00:26 christos 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. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #ifndef lint
34 #if 0
35 static char sccsid[] = "@(#)str.c	8.2 (Berkeley) 4/28/95";
36 #endif
37 __RCSID("$NetBSD: str.c,v 1.19 2011/09/08 12:00:26 christos Exp $");
38 #endif /* not lint */
39 
40 #include <sys/types.h>
41 
42 #include <err.h>
43 #include <errno.h>
44 #include <stddef.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <ctype.h>
49 
50 #include "extern.h"
51 
52 static int	backslash(STR *);
53 static int	bracket(STR *);
54 static int	c_class(const void *, const void *);
55 static void	genclass(STR *);
56 static void	genequiv(STR *);
57 static int	genrange(STR *);
58 static void	genseq(STR *);
59 
60 int
61 next(STR *s)
62 {
63 	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 	return 0;
114 }
115 
116 static int
117 bracket(STR *s)
118 {
119 	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] != '*' || strchr(p, ']') == NULL)
140 			return 0;
141 		s->str += 1;
142 		genseq(s);
143 		return 1;
144 	}
145 	/* NOTREACHED */
146 }
147 
148 typedef struct {
149 	const char *name;
150 	int (*func)(int);
151 } CLASS;
152 
153 static const CLASS classes[] = {
154 	{ "alnum",  isalnum  },
155 	{ "alpha",  isalpha  },
156 	{ "blank",  isblank  },
157 	{ "cntrl",  iscntrl  },
158 	{ "digit",  isdigit  },
159 	{ "graph",  isgraph  },
160 	{ "lower",  islower  },
161 	{ "print",  isprint  },
162 	{ "punct",  ispunct  },
163 	{ "space",  isspace  },
164 	{ "upper",  isupper  },
165 	{ "xdigit", isxdigit },
166 };
167 
168 static void
169 genclass(STR *s)
170 {
171 	int cnt;
172 	const CLASS *cp;
173 	CLASS tmp;
174 	int *p;
175 
176 	tmp.name = s->str;
177 	if ((cp = bsearch(&tmp, classes, sizeof(classes) /
178 	    sizeof(*cp), sizeof(*cp), c_class)) == NULL)
179 		errx(1, "unknown class %s", s->str);
180 
181 	if ((s->set = p = malloc((NCHARS + 1) * sizeof(*p))) == NULL)
182 		err(1, "malloc");
183 
184 	for (cnt = 0; cnt < NCHARS; ++cnt)
185 		if ((*cp->func)(cnt))
186 			*p++ = cnt;
187 	*p++ = OOBCH;
188 	memset(p, 0, NCHARS + 1 - (p - s->set));
189 
190 	s->cnt = 0;
191 	s->state = SET;
192 }
193 
194 static int
195 c_class(const void *a, const void *b)
196 {
197 	return strcmp(((const CLASS *)a)->name, ((const CLASS *)b)->name);
198 }
199 
200 /*
201  * English doesn't have any equivalence classes, so for now
202  * we just syntax check and grab the character.
203  */
204 static void
205 genequiv(STR *s)
206 {
207 	if (*s->str == '\\') {
208 		s->equiv[0] = backslash(s);
209 		if (*s->str != '=')
210 			errx(1, "misplaced equivalence equals sign");
211 	} else {
212 		s->equiv[0] = s->str[0];
213 		if (s->str[1] != '=')
214 			errx(1, "misplaced equivalence equals sign");
215 	}
216 	s->str += 2;
217 	s->cnt = 0;
218 	s->state = SET;
219 	s->set = s->equiv;
220 }
221 
222 static int
223 genrange(STR *s)
224 {
225 	int stopval;
226 	char *savestart;
227 
228 	savestart = s->str;
229 	stopval = *++s->str == '\\' ? backslash(s) : *s->str++;
230 	if (stopval < (u_char)s->lastch) {
231 		s->str = savestart;
232 		return 0;
233 	}
234 	s->cnt = stopval - s->lastch + 1;
235 	s->state = RANGE;
236 	--s->lastch;
237 	return 1;
238 }
239 
240 static void
241 genseq(STR *s)
242 {
243 	char *ep;
244 
245 	if (s->which == STRING1)
246 		errx(1, "sequences only valid in string2");
247 
248 	if (*s->str == '\\')
249 		s->lastch = backslash(s);
250 	else
251 		s->lastch = *s->str++;
252 	if (*s->str != '*')
253 		errx(1, "misplaced sequence asterisk");
254 
255 	switch (*++s->str) {
256 	case '\\':
257 		s->cnt = backslash(s);
258 		break;
259 	case ']':
260 		s->cnt = 0;
261 		++s->str;
262 		break;
263 	default:
264 		if (isdigit(*s->str)) {
265 			s->cnt = strtol(s->str, &ep, 0);
266 			if (*ep == ']') {
267 				s->str = ep + 1;
268 				break;
269 			}
270 		}
271 		errx(1, "illegal sequence count");
272 		/* NOTREACHED */
273 	}
274 
275 	s->state = s->cnt ? SEQUENCE : INFINITE;
276 }
277 
278 /*
279  * Translate \??? into a character.  Up to 3 octal digits, if no digits either
280  * an escape code or a literal character.
281  */
282 static int
283 backslash(STR *s)
284 {
285 	int ch, cnt, val;
286 
287 	for (cnt = val = 0;;) {
288 		ch = *++s->str;
289 		if (!isascii(ch) || !isdigit(ch))
290 			break;
291 		val = val * 8 + ch - '0';
292 		if (++cnt == 3) {
293 			++s->str;
294 			break;
295 		}
296 	}
297 	if (cnt)
298 		return val;
299 	if (ch != '\0')
300 		++s->str;
301 	switch (ch) {
302 	case 'a':			/* escape characters */
303 		return '\7';
304 	case 'b':
305 		return '\b';
306 	case 'e':
307 		return '\033';
308 	case 'f':
309 		return '\f';
310 	case 'n':
311 		return '\n';
312 	case 'r':
313 		return '\r';
314 	case 't':
315 		return '\t';
316 	case 'v':
317 		return '\13';
318 	case '\0':			/*  \" -> \ */
319 		s->state = EOS;
320 		return '\\';
321 	default:			/* \x" -> x */
322 		return ch;
323 	}
324 }
325