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