chiark / gitweb /
pcre.c, etc.: Support the PCRE2 library.
[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 {
39   pquis(fp, "Usage: $ [-f file] expression\n");
40 }
41
42 static void version(FILE *fp)
43 {
44   pquis(fp, "$, version " VERSION "\n");
45 }
46
47 static void help(FILE *fp)
48 {
49   version(fp);
50   fputc('\n', fp);
51   usage(fp);
52   fputs("\n\
53 Searches a wordlist, printing all of the words which match an expression.\n\
54 \n\
55 Options supported are:\n\
56 \n\
57 -h, --help              display this help text\n\
58 -v, --version           display the program's version number\n\
59 -u, --usage             display a very brief usage message\n\
60 -f, --file FILE         read wordlist from FILE, not `" DICTIONARY "'\n\
61 \n\
62 The basic tests in the expression are:\n\
63 \n\
64 -anagram WORD           matches a full-length anagram\n\
65 -subgram WORD           matches words which only use letters in WORD\n\
66 -wildcard PATTERN       matches with wildcards `*' and `?'\n\
67 -trackword WORD         matches words which can be found in a trackword\n\
68 -mono PATTERN           matches words isomorphic to the given PATTERN\n\
69 "
70 #ifdef HAVE_REGCOMP
71 "\
72 -regexp REGEXP          matches with an (extended) regular expression\n\
73 "
74 #endif
75 #if defined(HAVE_PCRE) || defined(HAVE_PCRE2)
76 "\
77 -pcre REGEXP            matches with a Perl-like regular expression\n\
78 "
79 #endif
80 "\
81 -length [+|-]N          matches if length is [at least|at most] N\n\
82 -longest                output longest matches found here\n\
83 -shortest               output shortest matches found here\n\
84 \n\
85 These simple tests can be combined using the operators `-a', `-o' and `-n'\n\
86 (for `and', `or' and `not'; they may also be written `&', `|' and `!' if\n\
87 you like), and grouped using parentheses `(' and `)'.\n\
88 ", fp); /*"*/
89 }
90
91 /*----- The options parser ------------------------------------------------*/
92
93 /* --- Options table structure --- */
94
95 struct opt {
96   const char *name;
97   unsigned nargs;
98   unsigned f;
99   unsigned tag;
100 };
101
102 enum {
103   O_HELP, O_VERSION, O_USAGE,
104   O_FILE,
105   O_AND, O_OR, O_NOT, O_LPAREN, O_RPAREN,
106   O_ANAG, O_SUBG, O_WILD, O_TRACK, O_REGEXP, O_PCRE, O_MONO, O_LENGTH,
107   O_LONGEST, O_SHORTEST,
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 operations -- 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   { "mono",             1,      0,              O_MONO },
138 #ifdef HAVE_REGCOMP
139   { "regexp",           1,      0,              O_REGEXP },
140 #endif
141 #if defined(HAVE_PCRE) || defined(HAVE_PCRE2)
142   { "pcre",             1,      0,              O_PCRE },
143 #endif
144   { "length",           1,      0,              O_LENGTH },
145   { "longest",          0,      0,              O_LONGEST },
146   { "shortest",         0,      0,              O_SHORTEST },
147
148   /* --- End marker --- */
149
150   { 0,                  0,      0,              0 }
151 };
152
153 static int ac;
154 static const char *const *av;
155 static int ai;
156
157 /* --- @nextopt@ --- *
158  *
159  * Arguments:   @const char ***arg@ = where to store the arg pointer
160  *
161  * Returns:     The tag of the next option.
162  *
163  * Use:         Scans the next option off the command line.  If the option
164  *              doesn't form part of the language, it's processed internally,
165  *              and you'll never see it from here.  On exit, the @arg@
166  *              pointer is set to contain the address of the option scanned,
167  *              followed by its arguments if any.  You're expected to know
168  *              how many arguments there are for your option.
169  */
170
171 static unsigned nextopt(const char *const **arg)
172 {
173   for (;;) {
174     const struct opt *o, *oo;
175     size_t sz;
176     const char *p;
177
178     /* --- Pick the next option off the front --- */
179
180     *arg = av + ai;
181     if (ai >= ac)
182       return (O_EOF);
183     p = av[ai++];
184
185     /* --- Cope with various forms of magic --- */
186
187     if (p[0] != '-') {
188       if (!p[1]) switch (*p) {
189         case '&': return (O_AND);
190         case '|': return (O_OR);
191         case '!': return (O_NOT);
192         case '(': return (O_LPAREN);
193         case ')': return (O_RPAREN);
194       }
195       goto bad;
196     }
197
198     /* --- Now cope with other sorts of weirdies --- *
199      *
200      * By the end of this, a leading `-' or `--' will have been stripped.
201      */
202
203     p++;
204     if (!*p)
205       goto bad;
206     if (*p == '-')
207       p++;
208     if (!*p) {
209       if (ai < ac)
210         die("syntax error near `--': rubbish at end of line");
211       return (O_EOF);
212     }
213
214     /* --- Now look the word up in my table --- */
215
216     sz = strlen(p);
217     oo = 0;
218     for (o = opttab; o->name; o++) {
219       if (strncmp(p, o->name, sz) == 0) {
220         if (strlen(o->name) == sz || ((o->f & OF_SHORT) && sz == 1)) {
221           oo = o;
222           break;
223         }
224         if (oo) {
225           die("ambiguous option name `-%s' (could match `-%s' or `-%s')",
226               p, oo->name, o->name);
227         }
228         oo = o;
229       }
230     }
231     if (!oo)
232       die("unrecognized option name `-%s'", p);
233
234     /* --- Sort out the arguments --- */
235
236     if (ai + oo->nargs > ac)
237       die("too few arguments for `-%s' (need %u)", oo->name, oo->nargs);
238     ai += oo->nargs;
239
240     /* --- Now process the option --- */
241
242     switch (oo->tag) {
243       case O_HELP:
244         help(stdout);
245         exit(0);
246       case O_VERSION:
247         version(stdout);
248         exit(0);
249       case O_USAGE:
250         usage(stdout);
251         exit(0);
252       case O_FILE:
253         file = (*arg)[1];
254         break;
255       default:
256         return (oo->tag);
257     }
258     continue;
259   bad:
260     die("syntax error near `%s': unknown token type", av[ai - 1]);
261   }
262 }
263
264 /*----- Node types for operators ------------------------------------------*/
265
266 /* --- Node structures --- */
267
268 typedef struct node_bin {
269   node n;
270   node *left;
271   node *right;
272 } node_bin;
273
274 typedef struct node_un {
275   node n;
276   node *arg;
277 } node_un;
278
279 /* --- Node functions --- */
280
281 static int n_or(node *nn, const char *p, size_t sz)
282 {
283   node_bin *n = (node_bin *)nn;
284   return (n->left->func(n->left, p, sz) || n->right->func(n->right, p, sz));
285 }
286
287 static int n_and(node *nn, const char *p, size_t sz)
288 {
289   node_bin *n = (node_bin *)nn;
290   return (n->left->func(n->left, p, sz) && n->right->func(n->right, p, sz));
291 }
292
293 static int n_not(node *nn, const char *p, size_t sz)
294 {
295   node_un *n = (node_un *)nn;
296   return (!n->arg->func(n->arg, p, sz));
297 }
298
299 /*----- Other simple node types -------------------------------------------*/
300
301 enum { LESS = -1, EQUAL = 0, GREATER = 1 };
302
303 typedef struct node_numeric {
304   node n;
305   int dir;
306   int i;
307 } node_numeric;
308
309 static void parse_numeric(const char *p, int *dir, int *i)
310 {
311   long l;
312   const char *pp = p;
313   char *q;
314
315   switch (*pp) {
316     case '-': *dir = LESS; pp++; break;
317     case '+': *dir = GREATER; pp++; break;
318     default: *dir = EQUAL; break;
319   }
320   errno = 0;
321   l = strtol(pp, &q, 0);
322   if (*q || errno || l < INT_MIN || l > INT_MAX)
323     die("bad numeric parameter `%s'", p);
324   *i = l;
325 }
326
327 static node *make_numeric(const char *const *av,
328                           int (*func)(struct node *, const char *, size_t))
329 {
330   node_numeric *n = xmalloc(sizeof(*n));
331   parse_numeric(av[0], &n->dir, &n->i);
332   n->n.func = func;
333   return (&n->n);
334 }
335
336 static int cmp_numeric(int x, int dir, int n)
337 {
338   switch (dir) {
339     case LESS: return (x <= n);
340     case EQUAL: return (x == n);
341     case GREATER: return (x >= n);
342   }
343   abort();
344 }
345
346 static int n_length(node *nn, const char *p, size_t sz)
347 {
348   node_numeric *n = (node_numeric *)nn;
349   return (cmp_numeric(sz, n->dir, n->i));
350 }
351
352 /*----- Parser for the expression syntax ----------------------------------*/
353
354 /* --- A parser context --- */
355
356 typedef struct p_ctx {
357   unsigned t;
358   const char *const *a;
359 } p_ctx;
360
361 /* --- Parser structure --- *
362  *
363  * This is a simple recursive descent parser.  The context retains
364  * information about the current token.  Each function is passed the address
365  * of a node pointer to fill in.  This simplifies the binary operator code
366  * somewhat, relative to returning pointers to node trees.
367  */
368
369 static void p_expr(p_ctx *p, node **/*nn*/);
370
371 static void p_next(p_ctx *p)
372 {
373   static const char *const eof[] = { "<end>", 0 };
374   p->t = nextopt(&p->a);
375   if (p->t == O_EOF)
376     p->a = eof;
377 }
378
379 static void p_factor(p_ctx *p, node **nn)
380 {
381   node_un *n;
382   if (p->t == O_LPAREN) {
383     p_next(p);
384     p_expr(p, nn);
385     if (p->t != O_RPAREN)
386       die("syntax error near `%s': missing `)'", *p->a);
387     p_next(p);
388   } else if (p->t == O_NOT) {
389     n = xmalloc(sizeof(node_un));
390     n->n.func = n_not;
391     *nn = &n->n;
392     p_next(p);
393     p_factor(p, &n->arg);
394   } else {
395     switch (p->t) {
396       case O_ANAG: *nn = anagram(p->a + 1); break;
397       case O_SUBG: *nn = subgram(p->a + 1); break;
398       case O_WILD: *nn = wildcard(p->a + 1); break;
399       case O_TRACK: *nn = trackword(p->a + 1); break;
400 #ifdef HAVE_REGCOMP
401       case O_REGEXP: *nn = regexp(p->a + 1); break;
402 #endif
403 #if defined(HAVE_PCRE) || defined(HAVE_PCRE2)
404       case O_PCRE: *nn = pcrenode(p->a + 1); break;
405 #endif
406       case O_MONO: *nn = mono(p->a + 1); break;
407       case O_LENGTH: *nn = make_numeric(p->a + 1, n_length); break;
408       case O_LONGEST: *nn = longest(p->a + 1); break;
409       case O_SHORTEST: *nn = shortest(p->a + 1); break;
410       default: die("syntax error near `%s': unexpected token", *p->a);
411     }
412     p_next(p);
413   }
414 }
415
416 static void p_term(p_ctx *p, node **nn)
417 {
418   node_bin *n;
419   for (;;) {
420     p_factor(p, nn);
421     switch (p->t) {
422       case O_AND:
423         p_next(p);
424       default:
425         break;
426       case O_RPAREN:
427       case O_OR:
428       case O_EOF:
429         return;
430     }
431     n = xmalloc(sizeof(node_bin));
432     n->left = *nn;
433     n->n.func = n_and;
434     *nn = &n->n;
435     nn = &n->right;
436   }
437 }
438
439 static void p_expr(p_ctx *p, node **nn)
440 {
441   node_bin *n;
442   for (;;) {
443     p_term(p, nn);
444     if (p->t != O_OR)
445       break;
446     p_next(p);
447     n = xmalloc(sizeof(node_bin));
448     n->left = *nn;
449     n->n.func = n_or;
450     *nn = &n->n;
451     nn = &n->right;
452   }
453 }
454
455 /* --- @p_argv@ --- *
456  *
457  * Arguments:   @int argc@ = number of command-line arguments
458  *              @const char *const argv[]@ = vectoor of arguments
459  *
460  * Returns:     A compiled node, parsed from the arguments.
461  *
462  * Use:         Does the donkey-work of parsing a command-line.
463  */
464
465 static node *p_argv(int argc, const char *const argv[])
466 {
467   p_ctx p;
468   node *n;
469
470   av = argv;
471   ac = argc;
472   ai = 1;
473   p_next(&p);
474   if (p.t == O_EOF) {
475     usage(stderr);
476     pquis(stderr, "(Run `$ --help' for more detail.)\n");
477     exit(EXIT_FAILURE);
478   }
479   p_expr(&p, &n);
480   if (p.t != O_EOF) {
481     die("syntax error near `%s': rubbish at end of line (too many `)'s?)",
482         *p.a);
483   }
484   return (n);
485 }
486
487 /*----- At-end stuff ------------------------------------------------------*/
488
489 /* --- @atend_register@ --- *
490  *
491  * Arguments:   @int (*func)(void *)@ = function to call
492  *              @void *p@ = handle to pass to it
493  *
494  * Returns:     ---
495  *
496  * Use:         Adds a function to the list of things to do at the end of the
497  *              program.  The function should return nonzero if it produced
498  *              any output.
499  */
500
501 typedef struct atend {
502   struct atend *next;
503   int (*func)(void */*p*/);
504   void *p;
505 } atend;
506
507 static atend *aa_head = 0, **aa_tail = &aa_head;
508
509 void atend_register(int (*func)(void */*p*/), void *p)
510 {
511   atend *a = xmalloc(sizeof(*a));
512   a->next = 0;
513   a->func = func;
514   a->p = p;
515   *aa_tail = a;
516   aa_tail = &a->next;
517 }
518
519 /*----- Main code ---------------------------------------------------------*/
520
521 /* --- @main@ --- *
522  *
523  * Arguments:   @int argc@ = number of command-line arguments
524  *              @char *argv[]@ = vector of argument words
525  *
526  * Returns:     Zero on success, nonzero on failure.
527  *
528  * Use:         Picks entries from a word list which match particular
529  *              expressions.  This might be of assistance to word-game types.
530  */
531
532 int main(int argc, char *argv[])
533 {
534   node *n;
535   FILE *fp;
536   dstr d = DSTR_INIT;
537   int ok = 0;
538   char *p, *q, *l;
539   atend *a;
540
541   ego(argv[0]);
542   n = p_argv(argc, (const char *const *)argv);
543
544   if ((fp = fopen(file, "r")) == 0)
545     die("error opening `%s': %s", file, strerror(errno));
546   for (;;) {
547     dstr_reset(&d);
548     if (dstr_putline(&d, fp) < 0)
549       break;
550     l = d.buf + d.len;
551     for (p = q = d.buf; p < l; p++) {
552       if (!isalnum((unsigned char)*p))
553         continue;
554       *q++ = tolower((unsigned char)*p);
555     }
556     *q = 0;
557     d.len = q - d.buf;
558     if (n->func(n, d.buf, d.len)) {
559       fwrite(d.buf, 1, d.len, stdout);
560       fputc('\n', stdout);
561       ok = 1;
562     }
563   }
564   if (ferror(fp) || fclose(fp))
565     die("error reading `%s': %s", file, strerror(errno));
566   for (a = aa_head; a; a = a->next) {
567     if (a->func(a->p))
568       ok = 1;
569   }
570   if (fflush(stdout) || ferror(stdout) || fclose(stdout))
571     die("error writing output: %s", strerror(errno));
572   if (!ok) pquis(stderr, "$: no matches found\n");
573   return (ok ? EX_OK : EX_NONE);
574 }
575
576 /*----- That's all, folks -------------------------------------------------*/