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