chiark / gitweb /
Add filtering by length, and retaining only longest/shortest matches.
[anag] / anag.c
1 /* -*-c-*-
2  *
3  * $Id$
4  *
5  * Main driver for anag
6  *
7  * (c) 2001 Mark Wooding
8  */
9
10 /*----- Licensing notice --------------------------------------------------* 
11  *
12  * This file is part of Anag: a simple wordgame helper.
13  *
14  * Anag is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2 of the License, or
17  * (at your option) any later version.
18  * 
19  * Anag is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU General Public License for more details.
23  * 
24  * You should have received a copy of the GNU General Public License
25  * along with Anag; if not, write to the Free Software Foundation,
26  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27  */
28
29 /*----- Header files ------------------------------------------------------*/
30
31 #include "anag.h"
32
33 /*----- Static variables --------------------------------------------------*/
34
35 static const char *file = DICTIONARY;
36
37 /*----- Help text functions -----------------------------------------------*/
38
39 static void usage(FILE *fp)
40 {
41   pquis(fp, "Usage: $ [-f file] expression\n");
42 }
43
44 static void version(FILE *fp)
45 {
46   pquis(fp, "$, version " VERSION "\n");
47 }
48
49 static void help(FILE *fp)
50 {
51   version(fp);
52   fputc('\n', fp);
53   usage(fp);
54   fputs("\n\
55 Searches a wordlist, printing all of the words which match an expression.\n\
56 \n\
57 Options supported are:\n\
58 \n\
59 -h, --help              display this help text\n\
60 -v, --version           display the program's version number\n\
61 -u, --usage             display a very brief usage message\n\
62 -f, --file FILE         read wordlist from FILE, not `" DICTIONARY "'\n\
63 \n\
64 The basic tests in the expression are:\n\
65 \n\
66 -anagram WORD           matches a full-length anagram\n\
67 -subgram WORD           matches words which only use letters in WORD\n\
68 -wildcard PATTERN       matches with wildcards `*' and `?'\n\
69 -trackword WORD         matches words which can be found in a trackword\n\
70 -mono PATTERN           matches words isomorphic to the given PATTERN\n\
71 "
72 #ifdef HAVE_REGCOMP
73 "\
74 -regexp REGEXP          matches with an (extended) regular expression\n\
75 "
76 #endif
77 #ifdef HAVE_PCRE
78 "\
79 -pcre REGEXP            matches with a Perl-like regular expression\n\
80 "
81 #endif
82 "\
83 -length [+|-]N          matches if length is [at least|at most] N\n\
84 -longest                output longest matches found here\n\
85 -shortest               output shortest matches found here\n\
86 \n\
87 These simple tests can be combined using the operators `-a', `-o' and `-n'\n\
88 (for `and', `or' and `not'; they may also be written `&', `|' and `!' if\n\
89 you like), and grouped using parentheses `(' and `)'.\n\
90 ", fp); /*"*/
91 }
92
93 /*----- The options parser ------------------------------------------------*/
94
95 /* --- Options table structure --- */
96
97 struct opt {
98   const char *name;
99   unsigned nargs;
100   unsigned f;
101   unsigned tag;
102 };
103
104 enum {
105   O_HELP, O_VERSION, O_USAGE,
106   O_FILE,
107   O_AND, O_OR, O_NOT, O_LPAREN, O_RPAREN,
108   O_ANAG, O_SUBG, O_WILD, O_TRACK, O_REGEXP, O_PCRE, O_MONO, O_LENGTH,
109   O_LONGEST, O_SHORTEST,
110   O_EOF
111 };
112
113 #define OF_SHORT 1u
114
115 static const struct opt opttab[] = {
116
117   /* --- Options -- don't form part of the language --- */
118
119   { "help",             0,      OF_SHORT,       O_HELP },
120   { "version",          0,      OF_SHORT,       O_VERSION },
121   { "usage",            0,      OF_SHORT,       O_USAGE },
122   { "file",             1,      OF_SHORT,       O_FILE },
123
124   /* --- Operators -- provide the basic structure of the language --- *
125    *
126    * These are also given magical names by the parser.
127    */
128
129   { "and",              0,      OF_SHORT,       O_AND },
130   { "or",               0,      OF_SHORT,       O_OR },
131   { "not",              0,      OF_SHORT,       O_NOT },
132
133   /* --- Actual matching operations -- do something useful --- */
134
135   { "anagram",          1,      0,              O_ANAG },
136   { "subgram",          1,      0,              O_SUBG },
137   { "wildcard",         1,      0,              O_WILD },
138   { "trackword",        1,      0,              O_TRACK },
139   { "mono",             1,      0,              O_MONO },
140 #ifdef HAVE_REGCOMP
141   { "regexp",           1,      0,              O_REGEXP },
142 #endif
143 #ifdef HAVE_PCRE
144   { "pcre",             1,      0,              O_PCRE },
145 #endif
146   { "length",           1,      0,              O_LENGTH },
147   { "longest",          0,      0,              O_LONGEST },
148   { "shortest",         0,      0,              O_SHORTEST },
149
150   /* --- End marker --- */
151
152   { 0,                  0,      0,              0 }
153 };
154
155 static int ac;
156 static const char *const *av;
157 static int ai;
158
159 /* --- @nextopt@ --- *
160  *
161  * Arguments:   @const char ***arg@ = where to store the arg pointer
162  *
163  * Returns:     The tag of the next option.
164  *
165  * Use:         Scans the next option off the command line.  If the option
166  *              doesn't form part of the language, it's processed internally,
167  *              and you'll never see it from here.  On exit, the @arg@
168  *              pointer is set to contain the address of the option scanned,
169  *              followed by its arguments if any.  You're expected to know
170  *              how many arguments there are for your option.
171  */
172
173 static unsigned nextopt(const char *const **arg)
174 {
175   for (;;) {
176     const struct opt *o, *oo;
177     size_t sz;
178     const char *p;
179
180     /* --- Pick the next option off the front --- */
181
182     *arg = av + ai;
183     if (ai >= ac)
184       return (O_EOF);
185     p = av[ai++];
186
187     /* --- Cope with various forms of magic --- */
188
189     if (p[0] != '-') {
190       if (!p[1]) switch (*p) {
191         case '&': return (O_AND);
192         case '|': return (O_OR);
193         case '!': return (O_NOT);
194         case '(': return (O_LPAREN);
195         case ')': return (O_RPAREN);
196       }
197       goto bad;
198     }
199
200     /* --- Now cope with other sorts of weirdies --- *
201      *
202      * By the end of this, a leading `-' or `--' will have been stripped.
203      */
204
205     p++;
206     if (!*p)
207       goto bad;
208     if (*p == '-')
209       p++;
210     if (!*p) {
211       if (ai < ac)
212         die("syntax error near `--': rubbish at end of line");
213       return (O_EOF);
214     }
215
216     /* --- Now look the word up in my table --- */
217
218     sz = strlen(p);
219     oo = 0;
220     for (o = opttab; o->name; o++) {
221       if (strncmp(p, o->name, sz) == 0) {
222         if (strlen(o->name) == sz || ((o->f & OF_SHORT) && sz == 1)) {
223           oo = o;
224           break;
225         }
226         if (oo) {
227           die("ambiguous option name `-%s' (could match `-%s' or `-%s')",
228               p, oo->name, o->name);
229         }
230         oo = o;
231       }
232     }
233     if (!oo)
234       die("unrecognized option name `-%s'", p);
235
236     /* --- Sort out the arguments --- */
237
238     if (ai + oo->nargs > ac)
239       die("too few arguments for `-%s' (need %u)", oo->name, oo->nargs);
240     ai += oo->nargs;
241
242     /* --- Now process the option --- */
243
244     switch (oo->tag) {
245       case O_HELP:
246         help(stdout);
247         exit(0);
248       case O_VERSION:
249         version(stdout);
250         exit(0);
251       case O_USAGE:
252         usage(stdout);
253         exit(0);
254       case O_FILE:
255         file = (*arg)[1];
256         break;
257       default:
258         return (oo->tag);
259     }
260     continue;
261   bad:
262     die("syntax error near `%s': unknown token type", av[ai - 1]);
263   }
264 }
265
266 /*----- Node types for operators ------------------------------------------*/
267
268 /* --- Node structures --- */
269
270 typedef struct node_bin {
271   node n;
272   node *left;
273   node *right;
274 } node_bin;
275
276 typedef struct node_un {
277   node n;
278   node *arg;
279 } node_un;
280
281 /* --- Node functions --- */
282
283 static int n_or(node *nn, const char *p, size_t sz)
284 {
285   node_bin *n = (node_bin *)nn;
286   return (n->left->func(n->left, p, sz) || n->right->func(n->right, p, sz));
287 }
288
289 static int n_and(node *nn, const char *p, size_t sz)
290 {
291   node_bin *n = (node_bin *)nn;
292   return (n->left->func(n->left, p, sz) && n->right->func(n->right, p, sz));
293 }
294
295 static int n_not(node *nn, const char *p, size_t sz)
296 {
297   node_un *n = (node_un *)nn;
298   return (!n->arg->func(n->arg, p, sz));
299 }
300
301 /*----- Other simple node types -------------------------------------------*/
302
303 enum { LESS = -1, EQUAL = 0, GREATER = 1 };
304
305 typedef struct node_numeric {
306   node n;
307   int dir;
308   int i;
309 } node_numeric;
310
311 static void parse_numeric(const char *p, int *dir, int *i)
312 {
313   long l;
314   const char *pp = p;
315   char *q;
316
317   switch (*pp) {
318     case '-': *dir = LESS; pp++; break;
319     case '+': *dir = GREATER; pp++; break;
320     default: *dir = EQUAL; break;
321   }
322   errno = 0;
323   l = strtol(pp, &q, 0);
324   if (*q || errno || l < INT_MIN || l > INT_MAX)
325     die("bad numeric parameter `%s'", p);
326   *i = l;
327 }
328
329 static node *make_numeric(const char *const *av,
330                           int (*func)(struct node *, const char *, size_t))
331 {
332   node_numeric *n = xmalloc(sizeof(*n));
333   parse_numeric(av[0], &n->dir, &n->i);
334   n->n.func = func;
335   return (&n->n);
336 }
337
338 static int cmp_numeric(int x, int dir, int n)
339 {
340   switch (dir) {
341     case LESS: return (x <= n);
342     case EQUAL: return (x == n);
343     case GREATER: return (x >= n);
344   }
345   abort();
346 }
347
348 static int n_length(node *nn, const char *p, size_t sz)
349 {
350   node_numeric *n = (node_numeric *)nn;
351   return (cmp_numeric(sz, n->dir, n->i));
352 }
353
354 /*----- Parser for the expression syntax ----------------------------------*/
355
356 /* --- A parser context --- */
357
358 typedef struct p_ctx {
359   unsigned t;
360   const char *const *a;
361 } p_ctx;
362
363 /* --- Parser structure --- *
364  *
365  * This is a simple recursive descent parser.  The context retains
366  * information about the current token.  Each function is passed the address
367  * of a node pointer to fill in.  This simplifies the binary operator code
368  * somewhat, relative to returning pointers to node trees.
369  */
370
371 static void p_expr(p_ctx *p, node **/*nn*/);
372
373 static void p_next(p_ctx *p)
374 {
375   static const char *const eof[] = { "<end>", 0 };
376   p->t = nextopt(&p->a);
377   if (p->t == O_EOF)
378     p->a = eof;
379 }
380
381 static void p_factor(p_ctx *p, node **nn)
382 {
383   node_un *n;
384   if (p->t == O_LPAREN) {
385     p_next(p);
386     p_expr(p, nn);
387     if (p->t != O_RPAREN)
388       die("syntax error near `%s': missing `)'", *p->a);
389     p_next(p);
390   } else if (p->t == O_NOT) {
391     n = xmalloc(sizeof(node_un));
392     n->n.func = n_not;
393     *nn = &n->n;
394     p_next(p);
395     p_factor(p, &n->arg);
396   } else {
397     switch (p->t) {
398       case O_ANAG: *nn = anagram(p->a + 1); break;
399       case O_SUBG: *nn = subgram(p->a + 1); break;
400       case O_WILD: *nn = wildcard(p->a + 1); break;
401       case O_TRACK: *nn = trackword(p->a + 1); break;
402 #ifdef HAVE_REGCOMP
403       case O_REGEXP: *nn = regexp(p->a + 1); break;
404 #endif
405 #ifdef HAVE_PCRE
406       case O_PCRE: *nn = pcrenode(p->a + 1); break;
407 #endif
408       case O_MONO: *nn = mono(p->a + 1); break;
409       case O_LENGTH: *nn = make_numeric(p->a + 1, n_length); break;
410       case O_LONGEST: *nn = longest(p->a + 1); break;
411       case O_SHORTEST: *nn = shortest(p->a + 1); break;
412       default: die("syntax error near `%s': unexpected token", *p->a);
413     }
414     p_next(p);
415   }
416 }
417
418 static void p_term(p_ctx *p, node **nn)
419 {
420   node_bin *n;
421   for (;;) {
422     p_factor(p, nn);
423     switch (p->t) {
424       case O_AND:
425         p_next(p);
426       default:
427         break;
428       case O_RPAREN:
429       case O_OR:
430       case O_EOF:
431         return;
432     }
433     n = xmalloc(sizeof(node_bin));
434     n->left = *nn;
435     n->n.func = n_and;
436     *nn = &n->n;
437     nn = &n->right;
438   }
439 }
440
441 static void p_expr(p_ctx *p, node **nn)
442 {
443   node_bin *n;
444   for (;;) {
445     p_term(p, nn);
446     if (p->t != O_OR)
447       break;
448     p_next(p);
449     n = xmalloc(sizeof(node_bin));
450     n->left = *nn;
451     n->n.func = n_or;
452     *nn = &n->n;
453     nn = &n->right;
454   }
455 }
456
457 /* --- @p_argv@ --- *
458  *
459  * Arguments:   @int argc@ = number of command-line arguments
460  *              @const char *const argv[]@ = vectoor of arguments
461  *
462  * Returns:     A compiled node, parsed from the arguments.
463  *
464  * Use:         Does the donkey-work of parsing a command-line.
465  */
466
467 static node *p_argv(int argc, const char *const argv[])
468 {
469   p_ctx p;
470   node *n;
471
472   av = argv;
473   ac = argc;
474   ai = 1;
475   p_next(&p);
476   if (p.t == O_EOF) {
477     usage(stderr);
478     pquis(stderr, "(Run `$ --help' for more detail.)\n");
479     exit(EXIT_FAILURE);
480   }
481   p_expr(&p, &n);
482   if (p.t != O_EOF) {
483     die("syntax error near `%s': rubbish at end of line (too many `)'s?)",
484         *p.a);
485   }
486   return (n);
487 }
488
489 /*----- At-end stuff ------------------------------------------------------*/
490
491 /* --- @atend_register@ --- *
492  *
493  * Arguments:   @int (*func)(void *)@ = function to call
494  *              @void *p@ = handle to pass to it
495  *
496  * Returns:     ---
497  *
498  * Use:         Adds a function to the list of things to do at the end of the
499  *              program.  The function should return nonzero if it produced
500  *              any output.
501  */
502
503 typedef struct atend {
504   struct atend *next;
505   int (*func)(void */*p*/);
506   void *p;
507 } atend;
508
509 static atend *aa_head = 0, **aa_tail = &aa_head;
510
511 void atend_register(int (*func)(void */*p*/), void *p)
512 {
513   atend *a = xmalloc(sizeof(*a));
514   a->next = 0;
515   a->func = func;
516   a->p = p;
517   *aa_tail = a;
518   aa_tail = &a->next;
519 }
520
521 /*----- Main code ---------------------------------------------------------*/
522
523 /* --- @main@ --- *
524  *
525  * Arguments:   @int argc@ = number of command-line arguments
526  *              @char *argv[]@ = vector of argument words
527  *
528  * Returns:     Zero on success, nonzero on failure.
529  *
530  * Use:         Picks entries from a word list which match particular
531  *              expressions.  This might be of assistance to word-game types.
532  */
533
534 int main(int argc, char *argv[])
535 {
536   node *n;
537   FILE *fp;
538   dstr d = DSTR_INIT;
539   int ok = 0;
540   char *p, *q, *l;
541   atend *a;
542
543   ego(argv[0]);
544   n = p_argv(argc, (const char *const *)argv);
545
546   if ((fp = fopen(file, "r")) == 0)
547     die("error opening `%s': %s", file, strerror(errno));
548   for (;;) {
549     dstr_reset(&d);
550     if (dstr_putline(&d, fp) < 0)
551       break;
552     l = d.buf + d.len;
553     for (p = q = d.buf; p < l; p++) {
554       if (!isalnum((unsigned char)*p))
555         continue;
556       *q++ = tolower((unsigned char)*p);
557     }
558     *q = 0;
559     d.len = q - d.buf;
560     if (n->func(n, d.buf, d.len)) {
561       fwrite(d.buf, 1, d.len, stdout);
562       fputc('\n', stdout);
563       ok = 1;
564     }
565   }
566   if (ferror(fp) || fclose(fp))
567     die("error reading `%s': %s", file, strerror(errno));
568   for (a = aa_head; a; a = a->next) {
569     if (a->func(a->p))
570       ok = 1;
571   }
572   if (fflush(stdout) || ferror(stdout) || fclose(stdout))
573     die("error writing output: %s", strerror(errno));
574   if (!ok) pquis(stderr, "$: no matches found\n");
575   return (ok ? EX_OK : EX_NONE);
576 }
577
578 /*----- That's all, folks -------------------------------------------------*/