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