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