xref: /freebsd/usr.bin/tr/str.c (revision d4b3aefdf94fe401f6bfc93a33b69e21dd7a634a)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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 
33 #ifndef lint
34 static const char sccsid[] = "@(#)str.c	8.2 (Berkeley) 4/28/95";
35 #endif
36 
37 #include <sys/types.h>
38 
39 #include <ctype.h>
40 #include <err.h>
41 #include <errno.h>
42 #include <stddef.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <wchar.h>
47 #include <wctype.h>
48 
49 #include "extern.h"
50 
51 static int      backslash(STR *, int *);
52 static int	bracket(STR *);
53 static void	genclass(STR *);
54 static void	genequiv(STR *);
55 static int      genrange(STR *, int);
56 static void	genseq(STR *);
57 
58 wint_t
59 next(STR *s)
60 {
61 	int is_octal;
62 	wint_t ch;
63 	wchar_t wch;
64 	size_t clen;
65 
66 	switch (s->state) {
67 	case EOS:
68 		return (0);
69 	case INFINITE:
70 		return (1);
71 	case NORMAL:
72 		switch (*s->str) {
73 		case '\0':
74 			s->state = EOS;
75 			return (0);
76 		case '\\':
77 			s->lastch = backslash(s, &is_octal);
78 			break;
79 		case '[':
80 			if (bracket(s))
81 				return (next(s));
82 			/* FALLTHROUGH */
83 		default:
84 			clen = mbrtowc(&wch, s->str, MB_LEN_MAX, NULL);
85 			if (clen == (size_t)-1 || clen == (size_t)-2 ||
86 			    clen == 0)
87 				errc(1, EILSEQ, NULL);
88 			is_octal = 0;
89 			s->lastch = wch;
90 			s->str += clen;
91 			break;
92 		}
93 
94 		/* We can start a range at any time. */
95 		if (s->str[0] == '-' && genrange(s, is_octal))
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 CCLASS:
112 	case CCLASS_UPPER:
113 	case CCLASS_LOWER:
114 		s->cnt++;
115 		ch = nextwctype(s->lastch, s->cclass);
116 		if (ch == -1) {
117 			s->state = NORMAL;
118 			return (next(s));
119 		}
120 		s->lastch = ch;
121 		return (1);
122 	case SET:
123 		if ((ch = s->set[s->cnt++]) == OOBCH) {
124 			s->state = NORMAL;
125 			return (next(s));
126 		}
127 		s->lastch = ch;
128 		return (1);
129 	default:
130 		return (0);
131 	}
132 	/* NOTREACHED */
133 }
134 
135 static int
136 bracket(STR *s)
137 {
138 	char *p;
139 
140 	switch (s->str[1]) {
141 	case ':':				/* "[:class:]" */
142 		if ((p = strchr(s->str + 2, ']')) == NULL)
143 			return (0);
144 		if (*(p - 1) != ':' || p - s->str < 4)
145 			goto repeat;
146 		*(p - 1) = '\0';
147 		s->str += 2;
148 		genclass(s);
149 		s->str = p + 1;
150 		return (1);
151 	case '=':				/* "[=equiv=]" */
152 		if (s->str[2] == '\0' || (p = strchr(s->str + 3, ']')) == NULL)
153 			return (0);
154 		if (*(p - 1) != '=' || p - s->str < 4)
155 			goto repeat;
156 		s->str += 2;
157 		genequiv(s);
158 		return (1);
159 	default:				/* "[\###*n]" or "[#*n]" */
160 	repeat:
161 		if ((p = strpbrk(s->str + 2, "*]")) == NULL)
162 			return (0);
163 		if (p[0] != '*' || strchr(p, ']') == NULL)
164 			return (0);
165 		s->str += 1;
166 		genseq(s);
167 		return (1);
168 	}
169 	/* NOTREACHED */
170 }
171 
172 static void
173 genclass(STR *s)
174 {
175 
176 	if ((s->cclass = wctype(s->str)) == 0)
177 		errx(1, "unknown class %s", s->str);
178 	s->cnt = 0;
179 	s->lastch = -1;		/* incremented before check in next() */
180 	if (strcmp(s->str, "upper") == 0)
181 		s->state = CCLASS_UPPER;
182 	else if (strcmp(s->str, "lower") == 0)
183 		s->state = CCLASS_LOWER;
184 	else
185 		s->state = CCLASS;
186 }
187 
188 static void
189 genequiv(STR *s)
190 {
191 	int i, p, pri;
192 	char src[2], dst[3];
193 	size_t clen;
194 	wchar_t wc;
195 
196 	if (*s->str == '\\') {
197 		s->equiv[0] = backslash(s, NULL);
198 		if (*s->str != '=')
199 			errx(1, "misplaced equivalence equals sign");
200 		s->str += 2;
201 	} else {
202 		clen = mbrtowc(&wc, s->str, MB_LEN_MAX, NULL);
203 		if (clen == (size_t)-1 || clen == (size_t)-2 || clen == 0)
204 			errc(1, EILSEQ, NULL);
205 		s->equiv[0] = wc;
206 		if (s->str[clen] != '=')
207 			errx(1, "misplaced equivalence equals sign");
208 		s->str += clen + 2;
209 	}
210 
211 	/*
212 	 * Calculate the set of all characters in the same equivalence class
213 	 * as the specified character (they will have the same primary
214 	 * collation weights).
215 	 * XXX Knows too much about how strxfrm() is implemented. Assumes
216 	 * it fills the string with primary collation weight bytes. Only one-
217 	 * to-one mappings are supported.
218 	 * XXX Equivalence classes not supported in multibyte locales.
219 	 */
220 	src[0] = (char)s->equiv[0];
221 	src[1] = '\0';
222 	if (MB_CUR_MAX == 1 && strxfrm(dst, src, sizeof(dst)) == 1) {
223 		pri = (unsigned char)*dst;
224 		for (p = 1, i = 1; i < NCHARS_SB; i++) {
225 			*src = i;
226 			if (strxfrm(dst, src, sizeof(dst)) == 1 && pri &&
227 			    pri == (unsigned char)*dst)
228 				s->equiv[p++] = i;
229 		}
230 		s->equiv[p] = OOBCH;
231 	}
232 
233 	s->cnt = 0;
234 	s->state = SET;
235 	s->set = s->equiv;
236 }
237 
238 static int
239 genrange(STR *s, int was_octal)
240 {
241 	int stopval, octal;
242 	char *savestart;
243 	int n, cnt, *p;
244 	size_t clen;
245 	wchar_t wc;
246 
247 	octal = 0;
248 	savestart = s->str;
249 	if (*++s->str == '\\')
250 		stopval = backslash(s, &octal);
251 	else {
252 		clen = mbrtowc(&wc, s->str, MB_LEN_MAX, NULL);
253 		if (clen == (size_t)-1 || clen == (size_t)-2)
254 			errc(1, EILSEQ, NULL);
255 		stopval = wc;
256 		s->str += clen;
257 	}
258 	/*
259 	 * XXX Characters are not ordered according to collating sequence in
260 	 * multibyte locales.
261 	 */
262 	if (octal || was_octal || MB_CUR_MAX > 1) {
263 		if (stopval < s->lastch) {
264 			s->str = savestart;
265 			return (0);
266 		}
267 		s->cnt = stopval - s->lastch + 1;
268 		s->state = RANGE;
269 		--s->lastch;
270 		return (1);
271 	}
272 	if (charcoll((const void *)&stopval, (const void *)&(s->lastch)) < 0) {
273 		s->str = savestart;
274 		return (0);
275 	}
276 	if ((s->set = p = malloc((NCHARS_SB + 1) * sizeof(int))) == NULL)
277 		err(1, "genrange() malloc");
278 	for (cnt = 0; cnt < NCHARS_SB; cnt++)
279 		if (charcoll((const void *)&cnt, (const void *)&(s->lastch)) >= 0 &&
280 		    charcoll((const void *)&cnt, (const void *)&stopval) <= 0)
281 			*p++ = cnt;
282 	*p = OOBCH;
283 	n = p - s->set;
284 
285 	s->cnt = 0;
286 	s->state = SET;
287 	if (n > 1)
288 		mergesort(s->set, n, sizeof(*(s->set)), charcoll);
289 	return (1);
290 }
291 
292 static void
293 genseq(STR *s)
294 {
295 	char *ep;
296 	wchar_t wc;
297 	size_t clen;
298 
299 	if (s->which == STRING1)
300 		errx(1, "sequences only valid in string2");
301 
302 	if (*s->str == '\\')
303 		s->lastch = backslash(s, NULL);
304 	else {
305 		clen = mbrtowc(&wc, s->str, MB_LEN_MAX, NULL);
306 		if (clen == (size_t)-1 || clen == (size_t)-2)
307 			errc(1, EILSEQ, NULL);
308 		s->lastch = wc;
309 		s->str += clen;
310 	}
311 	if (*s->str != '*')
312 		errx(1, "misplaced sequence asterisk");
313 
314 	switch (*++s->str) {
315 	case '\\':
316 		s->cnt = backslash(s, NULL);
317 		break;
318 	case ']':
319 		s->cnt = 0;
320 		++s->str;
321 		break;
322 	default:
323 		if (isdigit((u_char)*s->str)) {
324 			s->cnt = strtol(s->str, &ep, 0);
325 			if (*ep == ']') {
326 				s->str = ep + 1;
327 				break;
328 			}
329 		}
330 		errx(1, "illegal sequence count");
331 		/* NOTREACHED */
332 	}
333 
334 	s->state = s->cnt ? SEQUENCE : INFINITE;
335 }
336 
337 /*
338  * Translate \??? into a character.  Up to 3 octal digits, if no digits either
339  * an escape code or a literal character.
340  */
341 static int
342 backslash(STR *s, int *is_octal)
343 {
344 	int ch, cnt, val;
345 
346 	if (is_octal != NULL)
347 		*is_octal = 0;
348 	for (cnt = val = 0;;) {
349 		ch = (u_char)*++s->str;
350 		if (!isdigit(ch) || ch > '7')
351 			break;
352 		val = val * 8 + ch - '0';
353 		if (++cnt == 3) {
354 			++s->str;
355 			break;
356 		}
357 	}
358 	if (cnt) {
359 		if (is_octal != NULL)
360 			*is_octal = 1;
361 		return (val);
362 	}
363 	if (ch != '\0')
364 		++s->str;
365 	switch (ch) {
366 		case 'a':			/* escape characters */
367 			return ('\7');
368 		case 'b':
369 			return ('\b');
370 		case 'f':
371 			return ('\f');
372 		case 'n':
373 			return ('\n');
374 		case 'r':
375 			return ('\r');
376 		case 't':
377 			return ('\t');
378 		case 'v':
379 			return ('\13');
380 		case '\0':			/*  \" -> \ */
381 			s->state = EOS;
382 			return ('\\');
383 		default:			/* \x" -> x */
384 			return (ch);
385 	}
386 }
387