xref: /netbsd/usr.bin/sort/init.c (revision de243242)
1 /*	$NetBSD: init.c,v 1.15 2004/02/18 20:44:36 jdolecek Exp $	*/
2 
3 /*-
4  * Copyright (c) 2000-2003 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Ben Harris and Jaromir Dolecek.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *        This product includes software developed by the NetBSD
21  *        Foundation, Inc. and its contributors.
22  * 4. Neither the name of The NetBSD Foundation nor the names of its
23  *    contributors may be used to endorse or promote products derived
24  *    from this software without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36  * POSSIBILITY OF SUCH DAMAGE.
37  */
38 
39 /*-
40  * Copyright (c) 1993
41  *	The Regents of the University of California.  All rights reserved.
42  *
43  * This code is derived from software contributed to Berkeley by
44  * Peter McIlroy.
45  *
46  * Redistribution and use in source and binary forms, with or without
47  * modification, are permitted provided that the following conditions
48  * are met:
49  * 1. Redistributions of source code must retain the above copyright
50  *    notice, this list of conditions and the following disclaimer.
51  * 2. Redistributions in binary form must reproduce the above copyright
52  *    notice, this list of conditions and the following disclaimer in the
53  *    documentation and/or other materials provided with the distribution.
54  * 3. Neither the name of the University nor the names of its contributors
55  *    may be used to endorse or promote products derived from this software
56  *    without specific prior written permission.
57  *
58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
68  * SUCH DAMAGE.
69  */
70 
71 #include "sort.h"
72 
73 #ifndef lint
74 __RCSID("$NetBSD: init.c,v 1.15 2004/02/18 20:44:36 jdolecek Exp $");
75 __SCCSID("@(#)init.c	8.1 (Berkeley) 6/6/93");
76 #endif /* not lint */
77 
78 #include <ctype.h>
79 #include <string.h>
80 
81 static void insertcol __P((struct field *));
82 static const char *setcolumn __P((const char *, struct field *, int));
83 
84 u_char gweights[NBINS];
85 
86 /*
87  * masks of ignored characters.  Alltable is 256 ones.
88  */
89 static u_char alltable[NBINS], dtable[NBINS], itable[NBINS];
90 
91 /*
92  * parsed key options
93  */
94 struct coldesc *clist = NULL;
95 int ncols = 0;
96 
97 /*
98  * clist (list of columns which correspond to one or more icol or tcol)
99  * is in increasing order of columns.
100  * Fields are kept in increasing order of fields.
101  */
102 
103 /*
104  * keep clist in order--inserts a column in a sorted array
105  */
106 static void
107 insertcol(field)
108 	struct field *field;
109 {
110 	int i;
111 	struct coldesc *p;
112 
113 	/* Make space for new item */
114 	p = realloc(clist, (ncols + 2) * sizeof(*clist));
115 	if (!p)
116 		err(1, "realloc");
117 	clist = p;
118 	memset(&clist[ncols], 0, sizeof(clist[ncols]));
119 
120 	for (i = 0; i < ncols; i++)
121 		if (field->icol.num <= clist[i].num)
122 			break;
123 	if (field->icol.num != clist[i].num) {
124 		memmove(clist+i+1, clist+i, sizeof(COLDESC)*(ncols-i));
125 		clist[i].num = field->icol.num;
126 		ncols++;
127 	}
128 	if (field->tcol.num && field->tcol.num != field->icol.num) {
129 		for (i = 0; i < ncols; i++)
130 			if (field->tcol.num <= clist[i].num)
131 				break;
132 		if (field->tcol.num != clist[i].num) {
133 			memmove(clist+i+1, clist+i,sizeof(COLDESC)*(ncols-i));
134 			clist[i].num = field->tcol.num;
135 			ncols++;
136 		}
137 	}
138 }
139 
140 /*
141  * matches fields with the appropriate columns--n^2 but who cares?
142  */
143 void
144 fldreset(fldtab)
145 	struct field *fldtab;
146 {
147 	int i;
148 
149 	fldtab[0].tcol.p = clist + ncols - 1;
150 	for (++fldtab; fldtab->icol.num; ++fldtab) {
151 		for (i = 0; fldtab->icol.num != clist[i].num; i++)
152 			;
153 		fldtab->icol.p = clist + i;
154 		if (!fldtab->tcol.num)
155 			continue;
156 		for (i = 0; fldtab->tcol.num != clist[i].num; i++)
157 			;
158 		fldtab->tcol.p = clist + i;
159 	}
160 }
161 
162 /*
163  * interprets a column in a -k field
164  */
165 static const char *
166 setcolumn(pos, cur_fld, gflag)
167 	const char *pos;
168 	struct field *cur_fld;
169 	int gflag;
170 {
171 	struct column *col;
172 	char *npos;
173 	int tmp;
174 	col = cur_fld->icol.num ? (&cur_fld->tcol) : (&cur_fld->icol);
175 	col->num = (int) strtol(pos, &npos, 10);
176 	pos = npos;
177 	if (col->num <= 0 && !(col->num == 0 && col == &(cur_fld->tcol)))
178 		errx(2, "field numbers must be positive");
179 	if (*pos == '.') {
180 		if (!col->num)
181 			errx(2, "cannot indent end of line");
182 		++pos;
183 		col->indent = (int) strtol(pos, &npos, 10);
184 		pos = npos;
185 		if (&cur_fld->icol == col)
186 			col->indent--;
187 		if (col->indent < 0)
188 			errx(2, "illegal offset");
189 	}
190 	for(; (tmp = optval(*pos, cur_fld->tcol.num)); pos++)
191 		cur_fld->flags |= tmp;
192 	if (cur_fld->icol.num == 0)
193 		cur_fld->icol.num = 1;
194 	return (pos);
195 }
196 
197 int
198 setfield(pos, cur_fld, gflag)
199 	const char *pos;
200 	struct field *cur_fld;
201 	int gflag;
202 {
203 	int tmp;
204 
205 	cur_fld->weights = ascii;
206 	cur_fld->mask = alltable;
207 
208 	pos = setcolumn(pos, cur_fld, gflag);
209 	if (*pos == '\0')			/* key extends to EOL. */
210 		cur_fld->tcol.num = 0;
211 	else {
212 		if (*pos != ',')
213 			errx(2, "illegal field descriptor");
214 		setcolumn((++pos), cur_fld, gflag);
215 	}
216 	if (!cur_fld->flags)
217 		cur_fld->flags = gflag;
218 	tmp = cur_fld->flags;
219 
220 	/*
221 	 * Assign appropriate mask table and weight table.
222 	 * If the global weights are reversed, the local field
223 	 * must be "re-reversed".
224 	 */
225 	if (((tmp & R) ^ (gflag & R)) && (tmp & F))
226 		cur_fld->weights = RFtable;
227 	else if (tmp & F)
228 		cur_fld->weights = Ftable;
229 	else if ((tmp & R) ^ (gflag & R))
230 		cur_fld->weights = Rascii;
231 
232 	if (tmp & I)
233 		cur_fld->mask = itable;
234 	else if (tmp & D)
235 		cur_fld->mask = dtable;
236 
237 	cur_fld->flags |= (gflag & (BI | BT));
238 	if (!cur_fld->tcol.indent)	/* BT has no meaning at end of field */
239 		cur_fld->flags &= ~BT;
240 
241 	if (cur_fld->tcol.num && !(!(cur_fld->flags & BI)
242 	    && cur_fld->flags & BT) && (cur_fld->tcol.num <= cur_fld->icol.num
243 	    && cur_fld->tcol.indent < cur_fld->icol.indent))
244 		errx(2, "fields out of order");
245 	insertcol(cur_fld);
246 	return (cur_fld->tcol.num);
247 }
248 
249 int
250 optval(desc, tcolflag)
251 	int desc, tcolflag;
252 {
253 	switch(desc) {
254 		case 'b':
255 			if (!tcolflag)
256 				return (BI);
257 			else
258 				return (BT);
259 		case 'd': return (D);
260 		case 'f': return (F);
261 		case 'i': return (I);
262 		case 'n': return (N);
263 		case 'r': return (R);
264 		default:  return (0);
265 	}
266 }
267 
268 /*
269  * Replace historic +SPEC arguments with appropriate -kSPEC.
270  */
271 void
272 fixit(argc, argv)
273 	int *argc;
274 	char **argv;
275 {
276 	int i, j, fplus=0;
277 	char *vpos, *tpos, spec[20];
278 	int col, indent;
279 	size_t sz;
280 
281 	for (i = 1; i < *argc; i++) {
282 		if (argv[i][0] != '+' && !fplus)
283 			continue;
284 
285 		if (fplus && (argv[i][0] != '-' || !isdigit(argv[i][1]))) {
286 			fplus = 0;
287 			if (argv[i][0] != '+') {
288 				/* not a -POS argument, skip */
289 				continue;
290 			}
291 		}
292 
293 		/* parse spec */
294 		tpos = argv[i]+1;
295 		col = (int)strtol(tpos, &tpos, 10);
296 		if (*tpos == '.') {
297 			++tpos;
298 			indent = (int) strtol(tpos, &tpos, 10);
299 		} else
300 			indent = 0;
301 		/* tpos points to optional flags now */
302 
303 		/*
304 		 * For x.y, the obsolescent variant assumed 0 == beginning
305 		 * of line, while the new form uses 0 == end of line.
306 		 * Convert accordingly.
307 		 */
308 		if (!fplus) {
309 			/* +POS */
310 			col += 1;
311 			indent += 1;
312 		} else {
313 			/* -POS */
314 			if (indent > 0)
315 				col += 1;
316 		}
317 
318 		/* new style spec */
319 		sz = snprintf(spec, sizeof(spec), "%d.%d%s", col, indent,
320 		    tpos);
321 
322 		if (!fplus) {
323 			/* Replace the +POS argument with new-style -kSPEC */
324 			asprintf(&vpos, "-k%s", spec);
325 			argv[i] = vpos;
326 			fplus = 1;
327 		} else {
328 			/*
329 			 * Append the spec to one previously generated from
330 			 * +POS argument, and remove the argv element.
331 			 */
332 			asprintf(&vpos, "%s,%s", argv[i-1], spec);
333 			free(argv[i-1]);
334 			argv[i-1] = vpos;
335 			for (j=i; j < *argc; j++)
336 				argv[j] = argv[j+1];
337 			*argc -= 1;
338 			i--;
339 		}
340 	}
341 }
342 
343 /*
344  * ascii, Rascii, Ftable, and RFtable map
345  * REC_D -> REC_D;  {not REC_D} -> {not REC_D}.
346  * gweights maps REC_D -> (0 or 255); {not REC_D} -> {not gweights[REC_D]}.
347  * Note: when sorting in forward order, to encode character zero in a key,
348  * use \001\001; character 1 becomes \001\002.  In this case, character 0
349  * is reserved for the field delimiter.  Analagously for -r (fld_d = 255).
350  * Note: this is only good for ASCII sorting.  For different LC 's,
351  * all bets are off.  See also num_init in number.c
352  */
353 void
354 settables(gflags)
355 	int gflags;
356 {
357 	u_char *wts;
358 	int i, incr;
359 	for (i=0; i < 256; i++) {
360 		ascii[i] = i;
361 		if (i > REC_D && i < 255 - REC_D+1)
362 			Rascii[i] = 255 - i + 1;
363 		else
364 			Rascii[i] = 255 - i;
365 		if (islower(i)) {
366 			Ftable[i] = Ftable[toupper(i)];
367 			RFtable[i] = RFtable[toupper(i)];
368 		} else if (REC_D>= 'A' && REC_D < 'Z' && i < 'a' && i > REC_D) {
369 			Ftable[i] = i + 1;
370 			RFtable[i] = Rascii[i] - 1;
371 		} else {
372 			Ftable[i] = i;
373 			RFtable[i] = Rascii[i];
374 		}
375 		alltable[i] = 1;
376 
377 		if (i == '\n' || isprint(i))
378 			itable[i] = 1;
379 		else
380 			itable[i] = 0;
381 
382 		if (i == '\n' || i == '\t' || i == ' ' || isalnum(i))
383 			dtable[i] = 1;
384 		else
385 			dtable[i] = 0;
386 	}
387 
388 	Rascii[REC_D] = RFtable[REC_D] = REC_D;
389 	if (isupper(REC_D))
390 		Ftable[tolower(REC_D)]++;
391 
392 	if ((gflags & R) && !((gflags & F) && SINGL_FLD))
393 		wts = Rascii;
394 	else if (!((gflags & F) && SINGL_FLD))
395 		wts = ascii;
396 	else if (gflags & R)
397 		wts = RFtable;
398 	else
399 		wts = Ftable;
400 
401 	memmove(gweights, wts, sizeof(gweights));
402 	incr = (gflags & R) ? -1 : 1;
403 	for (i = 0; i < REC_D; i++)
404 		gweights[i] += incr;
405 	gweights[REC_D] = ((gflags & R) ? 255 : 0);
406 	if (SINGL_FLD && (gflags & F)) {
407 		for (i = 0; i < REC_D; i++) {
408 			ascii[i] += incr;
409 			Rascii[i] += incr;
410 		}
411 		ascii[REC_D] = Rascii[REC_D] = gweights[REC_D];
412 	}
413 }
414