xref: /netbsd/usr.bin/sort/init.c (revision 909cd63c)
1 /*	$NetBSD: init.c,v 1.13 2004/02/17 02:31:33 itojun 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.13 2004/02/17 02:31:33 itojun 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 + 1) * 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 			/* not a -POS argument, skip */
287 			fplus = 0;
288 			continue;
289 		}
290 
291 		/* parse spec */
292 		tpos = argv[i]+1;
293 		col = (int)strtol(tpos, &tpos, 10);
294 		if (*tpos == '.') {
295 			++tpos;
296 			indent = (int) strtol(tpos, &tpos, 10);
297 		} else
298 			indent = 0;
299 		/* tpos points to optional flags now */
300 
301 		/*
302 		 * For x.y, the obsolescent variant assumed 0 == beginning
303 		 * of line, while the new form uses 0 == end of line.
304 		 * Convert accordingly.
305 		 */
306 		if (!fplus) {
307 			/* +POS */
308 			col += 1;
309 			indent += 1;
310 		} else {
311 			/* -POS */
312 			if (indent > 0)
313 				col += 1;
314 		}
315 
316 		/* new style spec */
317 		sz = snprintf(spec, sizeof(spec), "%d.%d%s", col, indent,
318 		    tpos);
319 
320 		if (!fplus) {
321 			/* Replace the +POS argument with new-style -kSPEC */
322 			asprintf(&vpos, "-k%s", spec);
323 			argv[i] = vpos;
324 			fplus = 1;
325 		} else {
326 			/*
327 			 * Append the spec to one previously generated from
328 			 * +POS argument, and remove the argv element.
329 			 */
330 			asprintf(&vpos, "%s,%s", argv[i-1], spec);
331 			free(argv[i-1]);
332 			argv[i-1] = vpos;
333 			for (j=i; j < *argc; j++)
334 				argv[j] = argv[j+1];
335 			*argc -= 1;
336 		}
337 	}
338 }
339 
340 /*
341  * ascii, Rascii, Ftable, and RFtable map
342  * REC_D -> REC_D;  {not REC_D} -> {not REC_D}.
343  * gweights maps REC_D -> (0 or 255); {not REC_D} -> {not gweights[REC_D]}.
344  * Note: when sorting in forward order, to encode character zero in a key,
345  * use \001\001; character 1 becomes \001\002.  In this case, character 0
346  * is reserved for the field delimiter.  Analagously for -r (fld_d = 255).
347  * Note: this is only good for ASCII sorting.  For different LC 's,
348  * all bets are off.  See also num_init in number.c
349  */
350 void
351 settables(gflags)
352 	int gflags;
353 {
354 	u_char *wts;
355 	int i, incr;
356 	for (i=0; i < 256; i++) {
357 		ascii[i] = i;
358 		if (i > REC_D && i < 255 - REC_D+1)
359 			Rascii[i] = 255 - i + 1;
360 		else
361 			Rascii[i] = 255 - i;
362 		if (islower(i)) {
363 			Ftable[i] = Ftable[toupper(i)];
364 			RFtable[i] = RFtable[toupper(i)];
365 		} else if (REC_D>= 'A' && REC_D < 'Z' && i < 'a' && i > REC_D) {
366 			Ftable[i] = i + 1;
367 			RFtable[i] = Rascii[i] - 1;
368 		} else {
369 			Ftable[i] = i;
370 			RFtable[i] = Rascii[i];
371 		}
372 		alltable[i] = 1;
373 
374 		if (i == '\n' || isprint(i))
375 			itable[i] = 1;
376 		else
377 			itable[i] = 0;
378 
379 		if (i == '\n' || i == '\t' || i == ' ' || isalnum(i))
380 			dtable[i] = 1;
381 		else
382 			dtable[i] = 0;
383 	}
384 
385 	Rascii[REC_D] = RFtable[REC_D] = REC_D;
386 	if (isupper(REC_D))
387 		Ftable[tolower(REC_D)]++;
388 
389 	if ((gflags & R) && !((gflags & F) && SINGL_FLD))
390 		wts = Rascii;
391 	else if (!((gflags & F) && SINGL_FLD))
392 		wts = ascii;
393 	else if (gflags & R)
394 		wts = RFtable;
395 	else
396 		wts = Ftable;
397 
398 	memmove(gweights, wts, sizeof(gweights));
399 	incr = (gflags & R) ? -1 : 1;
400 	for (i = 0; i < REC_D; i++)
401 		gweights[i] += incr;
402 	gweights[REC_D] = ((gflags & R) ? 255 : 0);
403 	if (SINGL_FLD && (gflags & F)) {
404 		for (i = 0; i < REC_D; i++) {
405 			ascii[i] += incr;
406 			Rascii[i] += incr;
407 		}
408 		ascii[REC_D] = Rascii[REC_D] = gweights[REC_D];
409 	}
410 }
411