chiark / gitweb /
*.c: General spring-clean of the coding style.
[anag] / anag.c
1 /* -*-c-*-
2  *
3  * Main driver for anag
4  *
5  * (c) 2001 Mark Wooding
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of Anag: a simple wordgame helper.
11  *
12  * Anag is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * Anag is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with Anag; if not, write to the Free Software Foundation,
24  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  */
26
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "anag.h"
30
31 /*----- Static variables --------------------------------------------------*/
32
33 static const char *file = DICTIONARY;
34
35 /*----- Help text functions -----------------------------------------------*/
36
37 static void usage(FILE *fp)
38   { pquis(fp, "Usage: $ [-f file] expression\n"); }
39
40 static void version(FILE *fp)
41   { pquis(fp, "$, version " VERSION "\n"); }
42
43 static void help(FILE *fp)
44 {
45   version(fp);
46   fputc('\n', fp);
47   usage(fp);
48   fputs("\n\
49 Searches a wordlist, printing all of the words which match an expression.\n\
50 \n\
51 Options supported are:\n\
52 \n\
53 -h, --help              display this help text\n\
54 -v, --version           display the program's version number\n\
55 -u, --usage             display a very brief usage message\n\
56 -f, --file FILE         read wordlist from FILE, not `" DICTIONARY "'\n\
57 \n\
58 The basic tests in the expression are:\n\
59 \n\
60 -anagram WORD           matches a full-length anagram\n\
61 -subgram WORD           matches words which only use letters in WORD\n\
62 -wildcard PATTERN       matches with wildcards `*' and `?'\n\
63 -trackword WORD         matches words which can be found in a trackword\n\
64 -mono PATTERN           matches words isomorphic to the given PATTERN\n\
65 "
66 #ifdef HAVE_REGCOMP
67 "\
68 -regexp REGEXP          matches with an (extended) regular expression\n\
69 "
70 #endif
71 #if defined(HAVE_PCRE) || defined(HAVE_PCRE2)
72 "\
73 -pcre REGEXP            matches with a Perl-like regular expression\n\
74 "
75 #endif
76 "\
77 -length [+|-]N          matches if length is [at least|at most] N\n\
78 -longest                output longest matches found here\n\
79 -shortest               output shortest matches found here\n\
80 \n\
81 These simple tests can be combined using the operators `-a', `-o' and `-n'\n\
82 (for `and', `or' and `not'; they may also be written `&', `|' and `!' if\n\
83 you like), and grouped using parentheses `(' and `)'.\n\
84 ", fp); /*"*/
85 }
86
87 /*----- The options parser ------------------------------------------------*/
88
89 /* --- Options table structure --- */
90
91 struct opt {
92   const char *name;
93   unsigned nargs;
94   unsigned f;
95   unsigned tag;
96 };
97
98 enum {
99   O_HELP, O_VERSION, O_USAGE,
100   O_FILE,
101   O_AND, O_OR, O_NOT, O_LPAREN, O_RPAREN,
102   O_ANAG, O_SUBG, O_WILD, O_TRACK, O_REGEXP, O_PCRE, O_MONO, O_LENGTH,
103   O_LONGEST, O_SHORTEST,
104   O_EOF
105 };
106
107 #define OF_SHORT 1u
108
109 static const struct opt opttab[] = {
110
111   /* --- Options -- don't form part of the language --- */
112
113   { "help",             0,      OF_SHORT,       O_HELP },
114   { "version",          0,      OF_SHORT,       O_VERSION },
115   { "usage",            0,      OF_SHORT,       O_USAGE },
116   { "file",             1,      OF_SHORT,       O_FILE },
117
118   /* --- Operators -- provide the basic structure of the language --- *
119    *
120    * These are also given magical names by the parser.
121    */
122
123   { "and",              0,      OF_SHORT,       O_AND },
124   { "or",               0,      OF_SHORT,       O_OR },
125   { "not",              0,      OF_SHORT,       O_NOT },
126
127   /* --- Actual matching operations -- do something useful --- */
128
129   { "anagram",          1,      0,              O_ANAG },
130   { "subgram",          1,      0,              O_SUBG },
131   { "wildcard",         1,      0,              O_WILD },
132   { "trackword",        1,      0,              O_TRACK },
133   { "mono",             1,      0,              O_MONO },
134 #ifdef HAVE_REGCOMP
135   { "regexp",           1,      0,              O_REGEXP },
136 #endif
137 #if defined(HAVE_PCRE) || defined(HAVE_PCRE2)
138   { "pcre",             1,      0,              O_PCRE },
139 #endif
140   { "length",           1,      0,              O_LENGTH },
141   { "longest",          0,      0,              O_LONGEST },
142   { "shortest",         0,      0,              O_SHORTEST },
143
144   /* --- End marker --- */
145
146   { 0,                  0,      0,              0 }
147 };
148
149 static int ac;
150 static const char *const *av;
151 static int ai;
152
153 /* --- @nextopt@ --- *
154  *
155  * Arguments:   @const char ***arg@ = where to store the arg pointer
156  *
157  * Returns:     The tag of the next option.
158  *
159  * Use:         Scans the next option off the command line.  If the option
160  *              doesn't form part of the language, it's processed internally,
161  *              and you'll never see it from here.  On exit, the @arg@
162  *              pointer is set to contain the address of the option scanned,
163  *              followed by its arguments if any.  You're expected to know
164  *              how many arguments there are for your option.
165  */
166
167 static unsigned nextopt(const char *const **arg)
168 {
169   for (;;) {
170     const struct opt *o, *oo;
171     size_t sz;
172     const char *p;
173
174     /* Pick the next option off the front. */
175     *arg = av + ai;
176     if (ai >= ac) return (O_EOF);
177     p = av[ai++];
178
179     /* Cope with various forms of magic. */
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.  By the end of this, a leading
192      * `-' or `--' will have been stripped.
193      */
194     p++;
195     if (!*p) goto bad;
196     if (*p == '-') p++;
197     if (!*p) {
198       if (ai < ac) die("syntax error near `--': rubbish at end of line");
199       return (O_EOF);
200     }
201
202     /*Now look the word up in my table. */
203     sz = strlen(p);
204     oo = 0;
205     for (o = opttab; o->name; o++) {
206       if (strncmp(p, o->name, sz) == 0) {
207         if (strlen(o->name) == sz || ((o->f & OF_SHORT) && sz == 1))
208           { oo = o; break; }
209         if (oo)
210           die("ambiguous option name `-%s' (could match `-%s' or `-%s')",
211               p, oo->name, o->name);
212         oo = o;
213       }
214     }
215     if (!oo) die("unrecognized option name `-%s'", p);
216
217     /* Sort out the arguments. */
218     if (ai + oo->nargs > ac)
219       die("too few arguments for `-%s' (need %u)", oo->name, oo->nargs);
220     ai += oo->nargs;
221
222     /* Now process the option. */
223     switch (oo->tag) {
224       case O_HELP: help(stdout); exit(0);
225       case O_VERSION: version(stdout); exit(0);
226       case O_USAGE: usage(stdout); exit(0);
227       case O_FILE: file = (*arg)[1]; break;
228       default: return (oo->tag);
229     }
230     continue;
231   bad:
232     die("syntax error near `%s': unknown token type", av[ai - 1]);
233   }
234 }
235
236 /*----- Node types for operators ------------------------------------------*/
237
238 /* --- Node structures --- */
239
240 typedef struct node_bin {
241   node n;
242   node *left;
243   node *right;
244 } node_bin;
245
246 typedef struct node_un {
247   node n;
248   node *arg;
249 } node_un;
250
251 /* --- Node functions --- */
252
253 static int n_or(node *nn, const char *p, size_t sz)
254 {
255   node_bin *n = (node_bin *)nn;
256   return (n->left->func(n->left, p, sz) || n->right->func(n->right, p, sz));
257 }
258
259 static int n_and(node *nn, const char *p, size_t sz)
260 {
261   node_bin *n = (node_bin *)nn;
262   return (n->left->func(n->left, p, sz) && n->right->func(n->right, p, sz));
263 }
264
265 static int n_not(node *nn, const char *p, size_t sz)
266 {
267   node_un *n = (node_un *)nn;
268   return (!n->arg->func(n->arg, p, sz));
269 }
270
271 /*----- Other simple node types -------------------------------------------*/
272
273 enum { LESS = -1, EQUAL = 0, GREATER = 1 };
274
275 typedef struct node_numeric {
276   node n;
277   int dir;
278   int i;
279 } node_numeric;
280
281 static void parse_numeric(const char *p, int *dir, int *i)
282 {
283   long l;
284   const char *pp = p;
285   char *q;
286
287   switch (*pp) {
288     case '-': *dir = LESS; pp++; break;
289     case '+': *dir = GREATER; pp++; break;
290     default: *dir = EQUAL; break;
291   }
292   errno = 0;
293   l = strtol(pp, &q, 0);
294   if (*q || errno || l < INT_MIN || l > INT_MAX)
295     die("bad numeric parameter `%s'", p);
296   *i = l;
297 }
298
299 static node *make_numeric(const char *const *av,
300                           int (*func)(struct node *, const char *, size_t))
301 {
302   node_numeric *n = xmalloc(sizeof(*n));
303   parse_numeric(av[0], &n->dir, &n->i);
304   n->n.func = func;
305   return (&n->n);
306 }
307
308 static int cmp_numeric(int x, int dir, int n)
309 {
310   switch (dir) {
311     case LESS: return (x <= n);
312     case EQUAL: return (x == n);
313     case GREATER: return (x >= n);
314   }
315   abort();
316 }
317
318 static int n_length(node *nn, const char *p, size_t sz)
319 {
320   node_numeric *n = (node_numeric *)nn;
321   return (cmp_numeric(sz, n->dir, n->i));
322 }
323
324 /*----- Parser for the expression syntax ----------------------------------*/
325
326 /* --- A parser context --- */
327
328 typedef struct p_ctx {
329   unsigned t;
330   const char *const *a;
331 } p_ctx;
332
333 /* --- Parser structure --- *
334  *
335  * This is a simple recursive descent parser.  The context retains
336  * information about the current token.  Each function is passed the address
337  * of a node pointer to fill in.  This simplifies the binary operator code
338  * somewhat, relative to returning pointers to node trees.
339  */
340
341 static void p_expr(p_ctx *p, node **/*nn*/);
342
343 static void p_next(p_ctx *p)
344 {
345   static const char *const eof[] = { "<end>", 0 };
346   p->t = nextopt(&p->a);
347   if (p->t == O_EOF) p->a = eof;
348 }
349
350 static void p_factor(p_ctx *p, node **nn)
351 {
352   node_un *n;
353   if (p->t == O_LPAREN) {
354     p_next(p);
355     p_expr(p, nn);
356     if (p->t != O_RPAREN) 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 #if defined(HAVE_PCRE) || defined(HAVE_PCRE2)
374       case O_PCRE: *nn = pcrenode(p->a + 1); break;
375 #endif
376       case O_MONO: *nn = mono(p->a + 1); break;
377       case O_LENGTH: *nn = make_numeric(p->a + 1, n_length); break;
378       case O_LONGEST: *nn = longest(p->a + 1); break;
379       case O_SHORTEST: *nn = shortest(p->a + 1); break;
380       default: die("syntax error near `%s': unexpected token", *p->a);
381     }
382     p_next(p);
383   }
384 }
385
386 static void p_term(p_ctx *p, node **nn)
387 {
388   node_bin *n;
389   for (;;) {
390     p_factor(p, nn);
391     switch (p->t) {
392       case O_AND: p_next(p); break;
393       default: break;
394       case O_RPAREN: case O_OR: case O_EOF: return;
395     }
396     n = xmalloc(sizeof(node_bin));
397     n->left = *nn;
398     n->n.func = n_and;
399     *nn = &n->n;
400     nn = &n->right;
401   }
402 }
403
404 static void p_expr(p_ctx *p, node **nn)
405 {
406   node_bin *n;
407   for (;;) {
408     p_term(p, nn);
409     if (p->t != O_OR) break;
410     p_next(p);
411     n = xmalloc(sizeof(node_bin));
412     n->left = *nn;
413     n->n.func = n_or;
414     *nn = &n->n;
415     nn = &n->right;
416   }
417 }
418
419 /* --- @p_argv@ --- *
420  *
421  * Arguments:   @int argc@ = number of command-line arguments
422  *              @const char *const argv[]@ = vectoor of arguments
423  *
424  * Returns:     A compiled node, parsed from the arguments.
425  *
426  * Use:         Does the donkey-work of parsing a command-line.
427  */
428
429 static node *p_argv(int argc, const char *const argv[])
430 {
431   p_ctx p;
432   node *n;
433
434   av = argv;
435   ac = argc;
436   ai = 1;
437   p_next(&p);
438   if (p.t == O_EOF) {
439     usage(stderr);
440     pquis(stderr, "(Run `$ --help' for more detail.)\n");
441     exit(EXIT_FAILURE);
442   }
443   p_expr(&p, &n);
444   if (p.t != O_EOF)
445     die("syntax error near `%s': rubbish at end of line (too many `)'s?)",
446         *p.a);
447   return (n);
448 }
449
450 /*----- At-end stuff ------------------------------------------------------*/
451
452 /* --- @atend_register@ --- *
453  *
454  * Arguments:   @int (*func)(void *)@ = function to call
455  *              @void *p@ = handle to pass to it
456  *
457  * Returns:     ---
458  *
459  * Use:         Adds a function to the list of things to do at the end of the
460  *              program.  The function should return nonzero if it produced
461  *              any output.
462  */
463
464 typedef struct atend {
465   struct atend *next;
466   int (*func)(void */*p*/);
467   void *p;
468 } atend;
469
470 static atend *aa_head = 0, **aa_tail = &aa_head;
471
472 void atend_register(int (*func)(void */*p*/), void *p)
473 {
474   atend *a = xmalloc(sizeof(*a));
475   a->next = 0;
476   a->func = func;
477   a->p = p;
478   *aa_tail = a;
479   aa_tail = &a->next;
480 }
481
482 /*----- Main code ---------------------------------------------------------*/
483
484 /* --- @main@ --- *
485  *
486  * Arguments:   @int argc@ = number of command-line arguments
487  *              @char *argv[]@ = vector of argument words
488  *
489  * Returns:     Zero on success, nonzero on failure.
490  *
491  * Use:         Picks entries from a word list which match particular
492  *              expressions.  This might be of assistance to word-game types.
493  */
494
495 int main(int argc, char *argv[])
496 {
497   node *n;
498   FILE *fp;
499   dstr d = DSTR_INIT;
500   int ok = 0;
501   char *p, *q, *l;
502   atend *a;
503
504   ego(argv[0]);
505   n = p_argv(argc, (const char *const *)argv);
506
507   if ((fp = fopen(file, "r")) == 0)
508     die("error opening `%s': %s", file, strerror(errno));
509   for (;;) {
510     dstr_reset(&d);
511     if (dstr_putline(&d, fp) < 0) break;
512     l = d.buf + d.len;
513     for (p = q = d.buf; p < l; p++) {
514       if (!isalnum((unsigned char)*p)) continue;
515       *q++ = tolower((unsigned char)*p);
516     }
517     *q = 0;
518     d.len = q - d.buf;
519     if (n->func(n, d.buf, d.len)) {
520       fwrite(d.buf, 1, d.len, stdout);
521       fputc('\n', stdout);
522       ok = 1;
523     }
524   }
525   if (ferror(fp) || fclose(fp))
526     die("error reading `%s': %s", file, strerror(errno));
527   for (a = aa_head; a; a = a->next)
528     if (a->func(a->p)) ok = 1;
529   if (fflush(stdout) || ferror(stdout) || fclose(stdout))
530     die("error writing output: %s", strerror(errno));
531   if (!ok) pquis(stderr, "$: no matches found\n");
532   return (ok ? EX_OK : EX_NONE);
533 }
534
535 /*----- That's all, folks -------------------------------------------------*/