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