chiark / gitweb /
Debianization.
[anag] / anag.c
1 /* -*-c-*-
2  *
3  * $Id: anag.c,v 1.7 2003/11/29 23:38:37 mdw Exp $
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 /*----- Revision history --------------------------------------------------* 
30  *
31  * $Log: anag.c,v $
32  * Revision 1.7  2003/11/29 23:38:37  mdw
33  * Debianization.
34  *
35  * Revision 1.6  2003/09/15 02:48:54  mdw
36  * Monoalphabetic match filter.
37  *
38  * Revision 1.5  2002/08/11 12:58:09  mdw
39  * Added support for regular expression matching, if supported by the C
40  * library.
41  *
42  * Revision 1.4  2001/02/19 19:18:50  mdw
43  * Minor big fixes to parser.
44  *
45  * Revision 1.3  2001/02/16 21:45:19  mdw
46  * Be more helpful.  Improve full help message.  Special-case error for
47  * empty command strings.
48  *
49  * Revision 1.2  2001/02/07 09:09:11  mdw
50  * Fix spurious error when `-file' is used.
51  *
52  * Revision 1.1  2001/02/04 17:14:42  mdw
53  * Initial checkin
54  *
55  */
56
57 /*----- Header files ------------------------------------------------------*/
58
59 #include "anag.h"
60
61 /*----- Static variables --------------------------------------------------*/
62
63 static const char *file = DICTIONARY;
64
65 /*----- Help text functions -----------------------------------------------*/
66
67 static void usage(FILE *fp)
68 {
69   pquis(fp, "Usage: $ [-f file] expression\n");
70 }
71
72 static void version(FILE *fp)
73 {
74   pquis(fp, "$, version " VERSION "\n");
75 }
76
77 static void help(FILE *fp)
78 {
79   version(fp);
80   fputc('\n', fp);
81   usage(fp);
82   fputs("\n\
83 Searches a wordlist, printing all of the words which match an expression.\n\
84 \n\
85 Options supported are:\n\
86 \n\
87 -h, --help              display this help text\n\
88 -v, --version           display the program's version number\n\
89 -u, --usage             display a very brief usage message\n\
90 -f, --file FILE         read wordlist from FILE, not `" DICTIONARY "'\n\
91 \n\
92 The basic tests in the expression are:\n\
93 \n\
94 -anagram WORD           matches a full-length anagram\n\
95 -subgram WORD           matches words which only use letters in WORD\n\
96 -wildcard PATTERN       matches with wildcards `*' and `?'\n\
97 -trackword WORD         matches words which can be found in a trackword\n\
98 -mono PATTERN           matches words isomorphic to the given PATTERN\n\
99 "
100 #ifdef HAVE_REGCOMP
101 "\
102 -regexp REGEXP          matches with an (extended) regular expression\n\
103 "
104 #endif
105 #ifdef HAVE_PCRE
106 "\
107 -pcre REGEXP            matches with a Perl-like regular expression\n\
108 "
109 #endif
110 "\
111 \n\
112 These simple tests can be combined using the operators `-a', `-o' and `-n'\n\
113 (for `and', `or' and `not'; they may also be written `&', `|' and `!' if\n\
114 you like), and grouped using parentheses `(' and `)'.\n\
115 ", fp); /*"*/
116 }
117
118 /*----- The options parser ------------------------------------------------*/
119
120 /* --- Options table structure --- */
121
122 struct opt {
123   const char *name;
124   unsigned nargs;
125   unsigned f;
126   unsigned tag;
127 };
128
129 enum {
130   O_HELP, O_VERSION, O_USAGE,
131   O_FILE,
132   O_AND, O_OR, O_NOT, O_LPAREN, O_RPAREN,
133   O_ANAG, O_SUBG, O_WILD, O_TRACK, O_REGEXP, O_PCRE, O_MONO,
134   O_EOF
135 };
136
137 #define OF_SHORT 1u
138
139 static const struct opt opttab[] = {
140
141   /* --- Options -- don't form part of the language --- */
142
143   { "help",             0,      OF_SHORT,       O_HELP },
144   { "version",          0,      OF_SHORT,       O_VERSION },
145   { "usage",            0,      OF_SHORT,       O_USAGE },
146   { "file",             1,      OF_SHORT,       O_FILE },
147
148   /* --- Operators -- provide the basic structure of the language --- *
149    *
150    * These are also given magical names by the parser.
151    */
152
153   { "and",              0,      OF_SHORT,       O_AND },
154   { "or",               0,      OF_SHORT,       O_OR },
155   { "not",              0,      OF_SHORT,       O_NOT },
156
157   /* --- Actual matching oeprations -- do something useful --- */
158
159   { "anagram",          1,      0,              O_ANAG },
160   { "subgram",          1,      0,              O_SUBG },
161   { "wildcard",         1,      0,              O_WILD },
162   { "trackword",        1,      0,              O_TRACK },
163   { "mono",             1,      0,              O_MONO },
164 #ifdef HAVE_REGCOMP
165   { "regexp",           1,      0,              O_REGEXP },
166 #endif
167 #ifdef HAVE_PCRE
168   { "pcre",             1,      0,              O_PCRE },
169 #endif
170
171   /* --- End marker --- */
172
173   { 0,                  0,      0,              0 }
174 };
175
176 static int ac;
177 static const char *const *av;
178 static int ai;
179
180 /* --- @nextopt@ --- *
181  *
182  * Arguments:   @const char ***arg@ = where to store the arg pointer
183  *
184  * Returns:     The tag of the next option.
185  *
186  * Use:         Scans the next option off the command line.  If the option
187  *              doesn't form part of the language, it's processed internally,
188  *              and you'll never see it from here.  On exit, the @arg@
189  *              pointer is set to contain the address of the option scanned,
190  *              followed by its arguments if any.  You're expected to know
191  *              how many arguments there are for your option.
192  */
193
194 static unsigned nextopt(const char *const **arg)
195 {
196   for (;;) {
197     const struct opt *o, *oo;
198     size_t sz;
199     const char *p;
200
201     /* --- Pick the next option off the front --- */
202
203     *arg = av + ai;
204     if (ai >= ac)
205       return (O_EOF);
206     p = av[ai++];
207
208     /* --- Cope with various forms of magic --- */
209
210     if (p[0] != '-') {
211       if (!p[1]) switch (*p) {
212         case '&': return (O_AND);
213         case '|': return (O_OR);
214         case '!': return (O_NOT);
215         case '(': return (O_LPAREN);
216         case ')': return (O_RPAREN);
217       }
218       goto bad;
219     }
220
221     /* --- Now cope with other sorts of weirdies --- *
222      *
223      * By the end of this, a leading `-' or `--' will have been stripped.
224      */
225
226     p++;
227     if (!*p)
228       goto bad;
229     if (*p == '-')
230       p++;
231     if (!*p) {
232       if (ai < ac)
233         die("syntax error near `--': rubbish at end of line");
234       return (O_EOF);
235     }
236
237     /* --- Now look the word up in my table --- */
238
239     sz = strlen(p);
240     oo = 0;
241     for (o = opttab; o->name; o++) {
242       if (strncmp(p, o->name, sz) == 0) {
243         if (strlen(o->name) == sz || ((o->f & OF_SHORT) && sz == 1)) {
244           oo = o;
245           break;
246         }
247         if (oo) {
248           die("ambiguous option name `-%s' (could match `-%s' or `-%s')",
249               p, oo->name, o->name);
250         }
251         oo = o;
252       }
253     }
254     if (!oo)
255       die("unrecognized option name `-%s'", p);
256
257     /* --- Sort out the arguments --- */
258
259     if (ai + oo->nargs > ac)
260       die("too few arguments for `-%s' (need %u)", oo->name, oo->nargs);
261     ai += oo->nargs;
262
263     /* --- Now process the option --- */
264
265     switch (oo->tag) {
266       case O_HELP:
267         help(stdout);
268         exit(0);
269       case O_VERSION:
270         version(stdout);
271         exit(0);
272       case O_USAGE:
273         usage(stdout);
274         exit(0);
275       case O_FILE:
276         file = (*arg)[1];
277         break;
278       default:
279         return (oo->tag);
280     }
281     continue;
282   bad:
283     die("syntax error near `%s': unknown token type", av[ai - 1]);
284   }
285 }
286
287 /*----- Node types for operators ------------------------------------------*/
288
289 /* --- Node structures --- */
290
291 typedef struct node_bin {
292   node n;
293   node *left;
294   node *right;
295 } node_bin;
296
297 typedef struct node_un {
298   node n;
299   node *arg;
300 } node_un;
301
302 /* --- Node functions --- */
303
304 static int n_or(node *nn, const char *p, size_t sz)
305 {
306   node_bin *n = (node_bin *)nn;
307   return (n->left->func(n->left, p, sz) || n->right->func(n->right, p, sz));
308 }
309
310 static int n_and(node *nn, const char *p, size_t sz)
311 {
312   node_bin *n = (node_bin *)nn;
313   return (n->left->func(n->left, p, sz) && n->right->func(n->right, p, sz));
314 }
315
316 static int n_not(node *nn, const char *p, size_t sz)
317 {
318   node_un *n = (node_un *)nn;
319   return (!n->arg->func(n->arg, p, sz));
320 }
321
322 /*----- Parser for the expression syntax ----------------------------------*/
323
324 /* --- A parser context --- */
325
326 typedef struct p_ctx {
327   unsigned t;
328   const char *const *a;
329 } p_ctx;
330
331 /* --- Parser structure --- *
332  *
333  * This is a simple recursive descent parser.  The context retains
334  * information about the current token.  Each function is passed the address
335  * of a node pointer to fill in.  This simplifies the binary operator code
336  * somewhat, relative to returning pointers to node trees.
337  */
338
339 static void p_expr(p_ctx *p, node **/*nn*/);
340
341 static void p_next(p_ctx *p)
342 {
343   static const char *const eof[] = { "<end>", 0 };
344   p->t = nextopt(&p->a);
345   if (p->t == O_EOF)
346     p->a = eof;
347 }
348
349 static void p_factor(p_ctx *p, node **nn)
350 {
351   node_un *n;
352   if (p->t == O_LPAREN) {
353     p_next(p);
354     p_expr(p, nn);
355     if (p->t != O_RPAREN)
356       die("syntax error near `%s': missing `)'", *p->a);
357     p_next(p);
358   } else if (p->t == O_NOT) {
359     n = xmalloc(sizeof(node_un));
360     n->n.func = n_not;
361     *nn = &n->n;
362     p_next(p);
363     p_factor(p, &n->arg);
364   } else {
365     switch (p->t) {
366       case O_ANAG: *nn = anagram(p->a + 1); break;
367       case O_SUBG: *nn = subgram(p->a + 1); break;
368       case O_WILD: *nn = wildcard(p->a + 1); break;
369       case O_TRACK: *nn = trackword(p->a + 1); break;
370 #ifdef HAVE_REGCOMP
371       case O_REGEXP: *nn = regexp(p->a + 1); break;
372 #endif
373 #ifdef HAVE_PCRE
374       case O_PCRE: *nn = pcrenode(p->a + 1); break;
375 #endif
376       case O_MONO: *nn = mono(p->a + 1); break;
377       default: die("syntax error near `%s': unexpected token", *p->a);
378     }
379     p_next(p);
380   }
381 }
382
383 static void p_term(p_ctx *p, node **nn)
384 {
385   node_bin *n;
386   for (;;) {
387     p_factor(p, nn);
388     switch (p->t) {
389       case O_AND:
390         p_next(p);
391       default:
392         break;
393       case O_RPAREN:
394       case O_OR:
395       case O_EOF:
396         return;
397     }
398     n = xmalloc(sizeof(node_bin));
399     n->left = *nn;
400     n->n.func = n_and;
401     *nn = &n->n;
402     nn = &n->right;
403   }
404 }
405
406 static void p_expr(p_ctx *p, node **nn)
407 {
408   node_bin *n;
409   for (;;) {
410     p_term(p, nn);
411     if (p->t != O_OR)
412       break;
413     p_next(p);
414     n = xmalloc(sizeof(node_bin));
415     n->left = *nn;
416     n->n.func = n_or;
417     *nn = &n->n;
418     nn = &n->right;
419   }
420 }
421
422 /* --- @p_argv@ --- *
423  *
424  * Arguments:   @int argc@ = number of command-line arguments
425  *              @const char *const argv[]@ = vectoor of arguments
426  *
427  * Returns:     A compiled node, parsed from the arguments.
428  *
429  * Use:         Does the donkey-work of parsing a command-line.
430  */
431
432 static node *p_argv(int argc, const char *const argv[])
433 {
434   p_ctx p;
435   node *n;
436
437   av = argv;
438   ac = argc;
439   ai = 1;
440   p_next(&p);
441   if (p.t == O_EOF) {
442     usage(stderr);
443     pquis(stderr, "(Run `$ --help' for more detail.)\n");
444     exit(EXIT_FAILURE);
445   }
446   p_expr(&p, &n);
447   if (p.t != O_EOF) {
448     die("syntax error near `%s': rubbish at end of line (too many `)'s?)",
449         *p.a);
450   }
451   return (n);
452 }
453
454 /*----- Main code ---------------------------------------------------------*/
455
456 /* --- @main@ --- *
457  *
458  * Arguments:   @int argc@ = number of command-line arguments
459  *              @char *argv[]@ = vector of argument words
460  *
461  * Returns:     Zero on success, nonzero on failure.
462  *
463  * Use:         Picks entries from a word list which match particular
464  *              expressions.  This might be of assistance to word-game types.
465  */
466
467 int main(int argc, char *argv[])
468 {
469   node *n;
470   FILE *fp;
471   dstr d = DSTR_INIT;
472   char *p, *q, *l;
473
474   ego(argv[0]);
475   n = p_argv(argc, (const char *const *)argv);
476
477   if ((fp = fopen(file, "r")) == 0)
478     die("error opening `%s': %s", file, strerror(errno));
479   for (;;) {
480     dstr_reset(&d);
481     if (dstr_putline(&d, fp) < 0)
482       break;
483     l = d.buf + d.len;
484     for (p = q = d.buf; p < l; p++) {
485       if (!isalnum((unsigned char)*p))
486         continue;
487       *q++ = tolower((unsigned char)*p);
488     }
489     *q = 0;
490     d.len = q - d.buf;
491     if (n->func(n, d.buf, d.len)) {
492       fwrite(d.buf, 1, d.len, stdout);
493       fputc('\n', stdout);
494     }
495   }
496   if (!feof(fp))
497     die("error reading `%s': %s", file, strerror(errno));
498   fclose(fp);
499   return (0);
500 }
501
502 /*----- That's all, folks -------------------------------------------------*/