Debian Codegraph @

texk/web2c/cwebdir/examples/wordtest.w

raw
1 \datethis
2 @* Introduction. This program is a simple filter that sorts and outputs all
3 lines of input that do not appear in a given set of sorted files. It is called
4 {\tt wordtest} because each line of input is considered to be a `word' and
5 each of the sorted files is considered to be a 'dictionary'. Words are
6 output when they don't appear in any given dictionary.
7
8 The character set and alphabetic order are flexible. Every 8-bit
9 character is mapped into an integer called its {\it ord}. A character
10 is called a {\it null\/} if its ord is zero; such characters are
11 discarded from the input. A character is called a {\it break\/} if
12 its ord is negative; such characters break the input into so-called words.
13 Otherwise a character's ord is positive, and the character is called a
14 {\it letter}. One letter precedes another in alphabetic order if and only
15 if it has a smaller ord. Two letters are considered identical, for
16 purposes of sorting, if their ords are the same.
17
18 The null character |'\n'| must have ord~0; thus, it must remain null.
19 Otherwise the ord mapping is arbitrary. If the user doesn't specify
20 any special mapping, the default ord table simply maps every 8-bit
21 character code into itself, considering characters to be unsigned char
22 values in the range 0--255, except that ASCII codes {\tt a-z} are
23 mapped into the corresponding codes for {\tt A-Z}, and newline is a
24 break character. Optional command-line arguments, described below, can
25 change this default mapping to any other desired scheme.
26
27 A word is any nonempty sequence of letters that is immediately preceded
28 and followed by break characters, when nulls are ignored. Technically
29 speaking, we pretend that a break character is present at the beginning of a
30 file but not at the end; thus, all letters following the final break character
31 of a file are ignored, if any such letters are present. Two words are
32 {\it equivalent\/} to each other if their letters have the same sequence
33 of ord values. If two or more words of the input are equivalent, only
34 the first will be output, and it will be output only if it is not
35 equivalent to any word in the given dictionary files. Words in each
36 dictionary are assumed to be in lexicographic order and to contain no
37 nulls. Words in the output file will satisfy these conditions; therefore
38 {\tt wordtest} can be used to generate and update the dictionaries it needs.
39 Notice that if no dictionaries are given, {\tt wordtest} will act as a
40 sorting routine that simply discards nulls and duplicate lines.
41
42 @ The \UNIX/ command line `{\tt wordtest} {\tt [options]} {\tt [dictionaries]}'
43 is interpreted by executing option commands from left to right and then by
44 regarding any remaining arguments as the names of dictionary files.
45
46 Most of the option commands are designed to specify the |ord| table.
47 Initially |ord[c]=c| for each unsigned char code~|c|. The command
48 $$\line{\hskip5em\tt-b\it string\hfil}$$
49 makes every character in the string a break character. If the string is
50 empty, {\tt-b} makes every nonnull character a break (i.e., it sets
51 |ord[c]=-1| for |1<=c<=255|). The command
52 $$\line{\hskip5em\tt-n\it string\hfil}$$
53 makes every character in the string a null character. If the string is
54 empty, {\tt-n} makes every character null. The command
55 $$\line{\hskip5em\tt-a\it string\hfil}$$
56 sets the ord of the $k$th element of the string equal to $\delta+k$,
57 where $\delta$ is an offset value (normally zero). The command
58 $$\line{\hskip5em\tt-d\it offset\hfil}$$
59 sets the value of $\delta$; the offset should be a decimal integer between
60 0 and 255.
61
62 There is also an option that has no effect on the |ord| table:
63 $$\line{\hskip5em\tt-m\it length\hfil}$$
64 defines the length of the longest word. If any word of a file has
65 more than this many characters, a break is artificially inserted
66 so that a word of this maximum length is obtained. The default value is 50.
67 The maximum legal value is 1000.
68
69 If the given options do not specify at least one break character,
70 {\tt wordtest} applies the option commands
71 $$\vbox{\line{\hskip5em\.{-b"\\}\hfil}
72 \line{\.{" -d64 -a"abcdefghijklmnopqrstuvwxyz"}\hfil}}$$
73 which generate the default mapping mentioned above (unless other ords were
74 changed).
75
76 The program is designed to run fastest when there are at most two
77 dictionary files (usually one large system dictionary and another
78 personalized one), although it places no limit on the actual number of
79 dictionaries that can be mentioned on the command line. Users who want
80 to specify a multitude of dictionaries should ask themselves why they
81 wouldn't prefer to merge their dictionaries together first (using
82 {\tt wordtest}).
83
84 @d MAX_LENGTH_DEFAULT 50
85 @d MAX_LENGTH_LIMIT 1000
86
87 @ The general organization of {\tt wordtest} is typical of applications
88 written in \CEE/, and its approach is quite simple. If any errors are
89 detected, an indication of the error is sent to the |stderr| file and
90 a nonzero value is returned.
91
92 @p
93 #include <stdio.h>
94 #include <stdlib.h>
95 #include <stdbool.h>
96 @#
97 @<Typedefs@>@;
98 int main(
99 int argc, /* the number of command-line arguments */
100 char *argv[]) /* the arguments themselves */
101 {
102 @<Local variables@>;
103 @<Scan the command line arguments@>;
104 @<Sort the input into memory@>;
105 @<Output all input words that aren't in dictionaries@>;
106 return 0;
107 }
108
109 @ @<Typedefs@>=
110 typedef unsigned char byte; /* our bytes will range from 0 to 255 */
111
112 @ @<Local variables@>=
113 int targc; /* temporary modifications to |argc| */
114 byte **targv; /* pointer to the current argument of interest */
115 unsigned int delta; /* the offset used in the \.{-a} and \.{-d} options */
116 unsigned int max_length=MAX_LENGTH_DEFAULT; /* longest allowable word */
117 byte breakchar; /* break character to use in the output */
118 int ord[256]; /* table of ord values */
119 register int c; /* an all-purpose index */
120 register byte *u,*v; /* pointer to current string characters */
121
122 @ We try to use newline as the output break character, if possible.
123
124 @<Scan the command line arguments@>=
125 for (c=0;c<256;c++) ord[c]=c;
126 delta=0;
127 targc=argc-1;@+targv=(byte**)argv+1;
128 while (targc && **targv=='-') {
129 @<Execute the option command |targv|@>;
130 targc--;@+targv++;
131 }
132 if (ord['\n']<0) breakchar='\n';
133 else {
134 breakchar='\0';
135 for (c=255;c;c--) if (ord[c]<0) breakchar=c;
136 if (!breakchar) @<Set up the default ords@>;
137 }
138 @<Allocate data structures for a total of |targc| files@>;
139 for (;targc;targc--,targv++) @<Open the dictionary file named |*targv|@>;
140
141 @ @<Execute the option...@>=
142 switch((*targv)[1]) {
143 case 'a': for (c=delta,u=*targv+2;*u;u++) ord[*u]=++c;@+break;
144 case 'b': if ((*targv)[2]) for (u=*targv+2;*u;u++) ord[*u]=-1;
145 else for (c=1;c<256;c++) ord[c]=-1;
146 break;
147 case 'n': if ((*targv)[2]) for (u=*targv+2;*u;u++) ord[*u]=0;
148 else for (c=1;c<256;c++) ord[c]=0;
149 break;
150 case 'd': if (sscanf((char*)*targv+2,"%u",&delta)==1 && delta<256) break;
151 goto print_usage;
152 case 'm': if (sscanf((char*)*targv+2,"%u",&max_length)==1 &&
153 max_length<=MAX_LENGTH_LIMIT) break;
154 goto print_usage;
155 default: print_usage: fprintf(stderr,
156 "Usage: %s {-{{a|b|n}string|{d|m}number}}* dictionaryname*\n",*argv);
157 return-1;
158 }
159
160 @ @<Set up the default ords@>=
161 {
162 ord['\n']=-1; /* newline is break character */
163 breakchar='\n';
164 for (c=1;c<=26;c++) ord['a'-1+c]='A'-1+c;
165 }
166
167 @*Treaps. The most interesting part of this program is its sorting algorithm,
168 which is based on the ``treap'' data structure of Aragon and Seidel
169 [{\sl 30th IEEE Symposium on Foundations of Computer Science\/} (1989),
170 540--545].
171 @^Aragon, Cecilia Rodriguez@>@^Seidel, Raimund@>
172 A treap is a binary tree whose nodes have two key fields. The primary
173 key, which in our application is a word from the input, obeys
174 tree-search order: All descendants of the left child of node~$p$ have
175 a primary key that is less than the primary key of~$p$, and all descendants
176 of its right child have a primary key that is greater. The secondary key,
177 which in our application is a unique pseudorandom integer attached to
178 each input word, obeys heap order: The secondary key of~$p$'s children
179 is greater than $p$'s own secondary key.
180
181 A given set of nodes with distinct primary keys and distinct secondary
182 keys can be made into a treap in exactly one way. This unique treap
183 can be obtained, for example, by using ordinary tree insertion with
184 respect to primary keys while inserting nodes in order of their
185 secondary keys. It follows that, if the secondary keys are random,
186 the binary tree will almost always be quite well balanced.
187
188 We will compute secondary keys as unsigned long integers, assigning
189 the key $(cn)\bmod 2^{32}$ to the $n$th node, where $c$ is an odd
190 number. This will guarantee that the secondary keys are distinct.
191 By choosing $c$ close to $2^{32}/\phi$, where $\phi$ is the golden
192 ratio $(1+\sqrt5\,)/2$, we also spread the values out in a fashion that
193 is unlikely to match any existing order in the data.
194
195 @d PHICLONE 2654435769 /* $\approx 2^{32}/\phi$ */
196
197 @<Typedefs@>=
198 typedef struct node_struct {
199 struct node_struct *left,*right; /* children */
200 byte *keyword; /* primary key */
201 unsigned long rank; /* secondary key */
202 } node; /* node of a treap */
203
204 @ We want to be able to compare two strings rapidly with respect to
205 lexicographic order, as defined by the |ord| table. This can be done
206 if one string is delimited by |'\0'| as usual, while the other is
207 delimited by a break character. Then we are sure to have an unequal
208 comparison, and the inner loop is fast.
209
210 Here is a routine that checks to see if a word is already present in the
211 treap. The word is assumed to be in |buffer|, terminated by |breakchar|.
212 The words in the treap are terminated by nulls. The
213 treap is accessed by means of |root|, a pointer to its root node.
214
215 @<Search for |buffer| in the treap; |goto found| if it's there@>=
216 {@+register node *p=root;
217 while (p) {
218 for (u=buffer,v=p->keyword;ord[*u]==ord[*v];u++,v++) ;
219 if (*v=='\0' && *u==breakchar) goto found;
220 if (ord[*u]<ord[*v]) p=p->left;
221 else p=p->right;
222 }
223 }
224
225 @ We don't need to insert nodes into the treap as often as we need to
226 look words up, so we don't mind repeating the comparisons already made
227 when we discover that insertion is necessary. (Actually a more comprehensive
228 study of this tradeoff ought to be done. But not today; I am trying
229 here to keep the program short and sweet.)
230
231 The insertion algorithm proceeds just as the lookup algorithm until
232 we come to a node whose rank is larger than the rank of the node
233 to be inserted. We insert the new node in its place, then split the
234 old node and its descendants into two subtrees that will become the
235 left and right subtrees of the new node.
236
237 @<Insert the |buffer| word into the treap@>=
238 {@+register node *p,**q,**qq,*r;
239 current_rank += PHICLONE; /* unsigned addition mod $2^{32}$ */
240 p=root;@+q=&root;
241 while (p) {
242 if (p->rank>current_rank) break; /* end of the first phase */
243 for (u=buffer,v=p->keyword;ord[*u]==ord[*v];u++,v++) ;
244 if (ord[*u]<ord[*v]) q=&(p->left), p=*q;
245 else q=&(p->right), p=*q;
246 }
247 @<Set |r| to the address of a new node, and move |buffer| into it@>;
248 r->rank=current_rank;
249 *q=r; /* link the new node into the tree */
250 @<Split subtree |p| and attach it below node |r|@>;
251 }
252
253 @ @<Local...@>=
254 unsigned long current_rank=0; /* pseudorandom number */
255
256 @ At this point |p| may already be empty. If not, we can hook its
257 parts together easily. (A formal proof is a bit tricky, but the computer
258 doesn't slow down like people do when they get to a conceptually harder
259 part of an algorithm.)
260
261 @<Split subtree |p| and attach it below node |r|@>=
262 q=&(r->left);@+qq=&(r->right); /* slots to fill in as we split the subtree */
263 while (p) {
264 for (u=buffer,v=p->keyword;ord[*u]==ord[*v];u++,v++) ;
265 if (ord[*u]<ord[*v]) {
266 *qq=p;
267 qq=&(p->left);
268 p=*qq;
269 } else {
270 *q=p;
271 q=&(p->right);
272 p=*q;
273 }
274 }
275 *q=*qq=NULL;
276
277 @ We allocate node memory dynamically, in blocks of 100 nodes at a time.
278 We also allocate string memory dynamically, 1000 characters at once
279 (in addition to space for the current string).
280 The variable |l| will be set to the length of the word in |buffer|.
281
282 @d NODES_PER_BLOCK 100
283 @d CHARS_PER_BLOCK 1000
284 @d out_of_mem(x) {@+fprintf(stderr,"%s: Memory exhausted!\n",*argv);
285 return x;@+}
286
287 @<Set |r| to the address of a new node, and move |buffer| into it@>=
288 if (next_node==bad_node) {
289 next_node=(node*)calloc(NODES_PER_BLOCK,sizeof(node));
290 if (next_node==NULL) out_of_mem(-2);
291 bad_node=next_node+NODES_PER_BLOCK;
292 }
293 r=next_node++;
294 @<Move |buffer| to a new place in the string memory, and make
295 |r->keyword| point to it@>;
296
297 @ @<Move |buffer| to a new place...@>=
298 if (next_string+l+1>=bad_string) {@+int block_size=CHARS_PER_BLOCK+l+1;
299 next_string=(byte*)malloc(block_size);
300 if (next_string==NULL) out_of_mem(-3);
301 bad_string=next_string+block_size;
302 }
303 r->keyword=next_string;
304 for (u=buffer,v=next_string;ord[*u]>0;u++,v++) *v=*u;
305 *v='\0';
306 next_string=v+1;
307
308 @ We had better define the variables we've been assuming in these
309 storage allocation routines.
310
311 @<Local variables@>=
312 node *next_node=NULL, *bad_node=NULL;
313 byte *next_string=NULL, *bad_string=NULL;
314 node *root=NULL;
315 byte *buffer;
316 unsigned int l; /* length of current string in |buffer| */
317
318 @ The mechanisms for sorting the input words are now all in place.
319 We merely need to invoke them at the right times.
320
321 @<Sort the input into memory@>=
322 buffer=(byte*)malloc(max_length+1);
323 if (buffer==NULL) out_of_mem(-5);
324 while (true) {
325 @<Set |buffer| to the next word from |stdin|; |goto done| if file ends@>;
326 if (l) {
327 @<Search for |buffer| in the treap; |goto found| if it's there@>;
328 @<Insert the |buffer| word into the treap@>;
329 found:;
330 }
331 }
332 done:;
333
334 @ @<Set |buffer| to the next word from |stdin|...@>=
335 u=buffer;@+l=0;
336 while (l<max_length) {
337 c=getchar();
338 if (c==EOF) {
339 if (ferror(stdin)) {
340 fprintf(stderr,"%s: File read error on standard input!\n",*argv);
341 return -6;
342 }
343 goto done; /* end of file; the current word, if any, is discarded */
344 }
345 if (ord[c]<=0) {
346 if (ord[c]<0) break;
347 } else {
348 *u++=(byte)c;
349 l++;
350 }
351 }
352 *u=breakchar;
353
354 @ At the end we want to traverse the treap in symmetric order, so that
355 we see its words in alphabetic order. We might as well destroy the
356 treap structure as we do this. During this phase, |root| will point
357 to a stack of nodes that remain to be visited (followed by traversal
358 of their right subtrees).
359
360 @<Output all input words that aren't in dictionaries@>=
361 if (root!=NULL) {@+register node *p,*q;
362 p=root;
363 root=NULL;
364 while (true) {
365 while (p->left!=NULL) {
366 q=p->left;
367 p->left=root; /* |left| links are now used for the stack */
368 root=p;
369 p=q;
370 }
371 visit: @<Output |p->keyword|, if it's not in the dictionaries@>;
372 if (p->right==NULL) {
373 if (root==NULL) break; /* the stack is empty, we're done */
374 p=root;
375 root=root->left; /* pop the stack */
376 goto visit;
377 } else p=p->right;
378 }
379 }
380
381 @* The dictionaries. So now all we have to do is provide a mechanism
382 for reading the words in the dictionaries. The dictionaries are sorted,
383 and by now the input words have been sorted too.
384 So we need only scan through the
385 dictionaries once; we'll try to zoom through as quickly as possible.
386
387 First we need data structures. There will be an array of pointers to filenodes,
388 for all dictionary files currently open. Each filenode will contain
389 a buffer of size |BUFSIZ+1| for raw input bytes not yet scanned,
390 as well as a buffer of size |MAX_LENGTH_LIMIT+1| for the current word
391 being considered.
392
393 @<Typedefs@>=
394 typedef struct filenode_struct {
395 struct filenode_struct *link; /* pointer to next open file */
396 FILE *dfile; /* dictionary file */
397 byte buf[BUFSIZ+1], curword[MAX_LENGTH_LIMIT+1];
398 byte *pos; /* current position in |buf| */
399 byte *limit; /* end of input bytes in |buf| */
400 byte *endword; /* the first break character in |curword| */
401 } filenode;
402
403 @ @<Allocate data structures...@>=
404 if (targc) {
405 curfile=(filenode*)calloc(targc,sizeof(filenode));
406 if (curfile==NULL) out_of_mem(-7);
407 for (f=curfile;f<curfile+targc-1;f++) f->link=f+1;
408 f->link=curfile; /* circular linking */
409 } else curfile=NULL;
410
411 @ @<Local...@>=
412 filenode *curfile; /* current filenode of interest */
413 filenode *f; /* temporary register for filenode list processing */
414
415 @ @<Open the dictionary file named |*targv|@>=
416 {
417 curfile->dfile=fopen((char*)*targv,"r");
418 if (curfile->dfile==NULL) {
419 fprintf(stderr,"%s: Can't open dictionary file %s!\n",*argv,(char*)*targv);
420 return -8;
421 }
422 curfile->pos=curfile->limit=curfile->buf; /* |buf| is empty */
423 curfile->buf[0]='\0';
424 curfile->endword=curfile->curword; /* |curword| is empty too */
425 curfile->curword[0]=breakchar;
426 curfile=curfile->link; /* move to next filenode */
427 }
428
429 @ We will implicitly merge the dictionaries together by using a brute force
430 scheme that works fine when there are only a few of them. Namely,
431 |curfile| will point to a file having the currently smallest
432 current word. To get to the next word of the merge, we advance to the
433 next word in that file, comparing it with the current words of the
434 other files to see if |curfile| should switch to one of them.
435 When we get to the end of a file, its filenode simply leaves the circular
436 list. Eventually the list will be empty, and we will set |curfile| to
437 |NULL|; we will then have seen all the dictionary words in order.
438
439 @ @<Output |p->keyword|, if it's not in the dictionaries@>=
440 while (curfile!=NULL) {
441 for (u=p->keyword,v=curfile->curword;ord[*u]==ord[*v];u++,v++) ;
442 if (*u=='\0' && *v==breakchar) goto word_done;
443 /* we found it in the dictionary */
444 if (ord[*u]<ord[*v]) break; /* we didn't find it */
445 @<Advance to the next dictionary word@>;
446 }
447 @<Print |p->keyword| and |breakchar| on |stdout|@>@;
448 word_done:;
449
450 @ @<Print |p->keyword| and |breakchar| on |stdout|@>=
451 for (u=p->keyword;*u;u++) putchar(*u);
452 putchar(breakchar);
453
454 @ @<Advance...@>=
455 @<Read a new word into |curfile->curword|, as fast as you can@>;
456 @<Adjust |curfile|, if necessary, to point to a file with minimal
457 |curword|@>;
458
459 @ The dictionaries are supposed to be in order, and they shouldn't
460 contain nulls. But if they fail to meet these criteria, we don't want
461 {\tt wordtest} to crash; it should just run more slowly and/or more
462 peculiarly.
463
464 The logic of the code here removes null characters, at the cost of speed.
465 If the dictionary contains words out of order, say $\alpha>\beta$ where
466 $\alpha$ precedes $\beta$ in the file, the effect will be as if $\beta$
467 were not present. (In particular, if the dictionary would happen to have a null
468 word because of a break character inserted by our |max_length| logic,
469 that null word would cause no harm, because a null word is always less than
470 any nonnull word.)
471
472 A null character always appears in |curfile->limit|.
473
474 @<Read a new word into |curfile->curword|...@>=
475 v=curfile->curword;
476 l=max_length; /* here |l| represents max characters to put in |curword| */
477 while (true) {@+register byte *w=curfile->limit;
478 u=curfile->pos;
479 if (u+l>=w)
480 while (ord[*u]>0) *v++=*u++; /* this is the inner loop */
481 else {
482 w=u+l;
483 c=*w;
484 *w='\0'; /* temporarily store a null to avoid overlong string */
485 while (ord[*u]>0) *v++=*u++; /* this too is the inner loop */
486 *w=c; /* restore the damaged byte */
487 }
488 if (ord[*u]<0) {
489 curfile->pos=u+1; /* good, we found the next break character */
490 break;
491 }
492 l-=u-curfile->pos;
493 if (l==0) { /* |max_length| reached */
494 curfile->pos=u;
495 break;
496 }
497 if (u==w) { /* we're at |curfile->limit| */
498 @<Refill |curfile->buf|; or remove the current file from the
499 circular list and |goto update_done|, if it has ended@>;
500 } else curfile->pos=u+1; /* bypass a null character in the dictionary */
501 }
502 curfile->endword=v;
503 *v=breakchar;
504 update_done:;
505
506 @ @<Refill |curfile->buf|...@>=
507 if (ferror(curfile->dfile)) {
508 fprintf(stderr,"%s: File read error on dictionary file!\n",*argv);
509 return -9;
510 }
511 if (feof(curfile->dfile)) {
512 f=curfile->link;
513 if (f==curfile) curfile=NULL; /* the last dictionary file has ended */
514 else {
515 while (f->link!=curfile) f=f->link;
516 f->link=curfile->link; /* remove a filenode from the circular list */
517 curfile=f; /* and point to one of the remaining filenodes */
518 }
519 goto update_done;
520 }
521 curfile->limit=curfile->buf+fread(curfile->buf,1,BUFSIZ,curfile->dfile);
522 *curfile->limit='\0';
523 curfile->pos=curfile->buf;
524
525 @ @<Adjust |curfile|, if necessary...@>=
526 if (curfile!=NULL) {@+filenode *sentinel=curfile;
527 for (f=curfile->link;f!=sentinel;f=f->link)
528 @<Change |curfile| to |f| if |f->curword<curfile->curword|@>;
529 }
530
531 @ @<Change |curfile| to |f| if |f->curword<curfile->curword|@>=
532 {
533 *f->endword='\0';
534 for (u=f->curword,v=curfile->curword;ord[*u]==ord[*v];u++,v++) ;
535 if (ord[*u]<ord[*v]) curfile=f;
536 *f->endword=breakchar;
537 }
538
539 @* Index. Here is a list of the identifiers used by {\tt wordtest},
540 showing the sections in which they appear, underlined at points
541 of definition.