chiark / gitweb /
*.c: General spring-clean of the coding style.
[anag] / anag.c
CommitLineData
6e403221 1/* -*-c-*-
6e403221 2 *
3 * Main driver for anag
4 *
5 * (c) 2001 Mark Wooding
6 */
7
0279756e 8/*----- Licensing notice --------------------------------------------------*
6e403221 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.
0279756e 16 *
6e403221 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.
0279756e 21 *
6e403221 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
6e403221 27/*----- Header files ------------------------------------------------------*/
28
29#include "anag.h"
30
31/*----- Static variables --------------------------------------------------*/
32
33static const char *file = DICTIONARY;
34
35/*----- Help text functions -----------------------------------------------*/
36
37static void usage(FILE *fp)
904ac13a 38 { pquis(fp, "Usage: $ [-f file] expression\n"); }
6e403221 39
40static void version(FILE *fp)
904ac13a 41 { pquis(fp, "$, version " VERSION "\n"); }
6e403221 42
43static void help(FILE *fp)
44{
45 version(fp);
46 fputc('\n', fp);
47 usage(fp);
48 fputs("\n\
49Searches a wordlist, printing all of the words which match an expression.\n\
2668675c 50\n\
51Options 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\
6e403221 58The 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\
fe9969ff 64-mono PATTERN matches words isomorphic to the given PATTERN\n\
a10122de 65"
66#ifdef HAVE_REGCOMP
67"\
68-regexp REGEXP matches with an (extended) regular expression\n\
69"
70#endif
650bb9da 71#if defined(HAVE_PCRE) || defined(HAVE_PCRE2)
d9af4a2b 72"\
73-pcre REGEXP matches with a Perl-like regular expression\n\
74"
75#endif
a10122de 76"\
94ed9b30 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\
6e403221 80\n\
81These 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\
83you like), and grouped using parentheses `(' and `)'.\n\
d9af4a2b 84", fp); /*"*/
6e403221 85}
86
87/*----- The options parser ------------------------------------------------*/
88
89/* --- Options table structure --- */
90
91struct opt {
92 const char *name;
93 unsigned nargs;
94 unsigned f;
95 unsigned tag;
96};
97
98enum {
99 O_HELP, O_VERSION, O_USAGE,
100 O_FILE,
101 O_AND, O_OR, O_NOT, O_LPAREN, O_RPAREN,
94ed9b30 102 O_ANAG, O_SUBG, O_WILD, O_TRACK, O_REGEXP, O_PCRE, O_MONO, O_LENGTH,
103 O_LONGEST, O_SHORTEST,
6e403221 104 O_EOF
105};
106
107#define OF_SHORT 1u
108
109static 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
94ed9b30 127 /* --- Actual matching operations -- do something useful --- */
6e403221 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 },
fe9969ff 133 { "mono", 1, 0, O_MONO },
a10122de 134#ifdef HAVE_REGCOMP
135 { "regexp", 1, 0, O_REGEXP },
136#endif
650bb9da 137#if defined(HAVE_PCRE) || defined(HAVE_PCRE2)
d9af4a2b 138 { "pcre", 1, 0, O_PCRE },
139#endif
0279756e
MW
140 { "length", 1, 0, O_LENGTH },
141 { "longest", 0, 0, O_LONGEST },
142 { "shortest", 0, 0, O_SHORTEST },
6e403221 143
144 /* --- End marker --- */
145
146 { 0, 0, 0, 0 }
147};
148
149static int ac;
150static const char *const *av;
151static 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
167static unsigned nextopt(const char *const **arg)
168{
169 for (;;) {
170 const struct opt *o, *oo;
171 size_t sz;
172 const char *p;
173
904ac13a 174 /* Pick the next option off the front. */
6e403221 175 *arg = av + ai;
904ac13a 176 if (ai >= ac) return (O_EOF);
6e403221 177 p = av[ai++];
178
904ac13a 179 /* Cope with various forms of magic. */
6e403221 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
904ac13a
MW
191 /* Now cope with other sorts of weirdies. By the end of this, a leading
192 * `-' or `--' will have been stripped.
6e403221 193 */
6e403221 194 p++;
904ac13a
MW
195 if (!*p) goto bad;
196 if (*p == '-') p++;
6e403221 197 if (!*p) {
904ac13a 198 if (ai < ac) die("syntax error near `--': rubbish at end of line");
6e403221 199 return (O_EOF);
200 }
201
904ac13a 202 /*Now look the word up in my table. */
6e403221 203 sz = strlen(p);
204 oo = 0;
205 for (o = opttab; o->name; o++) {
206 if (strncmp(p, o->name, sz) == 0) {
904ac13a
MW
207 if (strlen(o->name) == sz || ((o->f & OF_SHORT) && sz == 1))
208 { oo = o; break; }
209 if (oo)
6e403221 210 die("ambiguous option name `-%s' (could match `-%s' or `-%s')",
211 p, oo->name, o->name);
6e403221 212 oo = o;
213 }
214 }
904ac13a 215 if (!oo) die("unrecognized option name `-%s'", p);
6e403221 216
904ac13a 217 /* Sort out the arguments. */
6e403221 218 if (ai + oo->nargs > ac)
219 die("too few arguments for `-%s' (need %u)", oo->name, oo->nargs);
220 ai += oo->nargs;
221
904ac13a 222 /* Now process the option. */
6e403221 223 switch (oo->tag) {
904ac13a
MW
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);
6e403221 229 }
60dffc01 230 continue;
6e403221 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
240typedef struct node_bin {
241 node n;
242 node *left;
243 node *right;
244} node_bin;
245
246typedef struct node_un {
247 node n;
248 node *arg;
249} node_un;
250
251/* --- Node functions --- */
252
253static 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
259static 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
265static 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
94ed9b30 271/*----- Other simple node types -------------------------------------------*/
272
273enum { LESS = -1, EQUAL = 0, GREATER = 1 };
274
275typedef struct node_numeric {
276 node n;
277 int dir;
278 int i;
279} node_numeric;
280
281static 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
299static 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
308static 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
318static 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
6e403221 324/*----- Parser for the expression syntax ----------------------------------*/
325
326/* --- A parser context --- */
327
328typedef 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
341static void p_expr(p_ctx *p, node **/*nn*/);
342
343static void p_next(p_ctx *p)
344{
345 static const char *const eof[] = { "<end>", 0 };
346 p->t = nextopt(&p->a);
904ac13a 347 if (p->t == O_EOF) p->a = eof;
6e403221 348}
349
350static 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);
904ac13a 356 if (p->t != O_RPAREN) die("syntax error near `%s': missing `)'", *p->a);
6e403221 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;
a10122de 370#ifdef HAVE_REGCOMP
371 case O_REGEXP: *nn = regexp(p->a + 1); break;
d9af4a2b 372#endif
650bb9da 373#if defined(HAVE_PCRE) || defined(HAVE_PCRE2)
d9af4a2b 374 case O_PCRE: *nn = pcrenode(p->a + 1); break;
a10122de 375#endif
fe9969ff 376 case O_MONO: *nn = mono(p->a + 1); break;
94ed9b30 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;
6e403221 380 default: die("syntax error near `%s': unexpected token", *p->a);
381 }
382 p_next(p);
383 }
384}
385
386static void p_term(p_ctx *p, node **nn)
387{
388 node_bin *n;
389 for (;;) {
390 p_factor(p, nn);
391 switch (p->t) {
904ac13a
MW
392 case O_AND: p_next(p); break;
393 default: break;
394 case O_RPAREN: case O_OR: case O_EOF: return;
6e403221 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
404static void p_expr(p_ctx *p, node **nn)
405{
406 node_bin *n;
407 for (;;) {
408 p_term(p, nn);
904ac13a 409 if (p->t != O_OR) break;
6e403221 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
429static 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);
2668675c 438 if (p.t == O_EOF) {
439 usage(stderr);
440 pquis(stderr, "(Run `$ --help' for more detail.)\n");
441 exit(EXIT_FAILURE);
442 }
6e403221 443 p_expr(&p, &n);
904ac13a 444 if (p.t != O_EOF)
6e403221 445 die("syntax error near `%s': rubbish at end of line (too many `)'s?)",
446 *p.a);
6e403221 447 return (n);
448}
449
94ed9b30 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
464typedef struct atend {
465 struct atend *next;
466 int (*func)(void */*p*/);
467 void *p;
468} atend;
469
470static atend *aa_head = 0, **aa_tail = &aa_head;
471
472void 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
6e403221 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
495int main(int argc, char *argv[])
496{
497 node *n;
498 FILE *fp;
499 dstr d = DSTR_INIT;
94ed9b30 500 int ok = 0;
6e403221 501 char *p, *q, *l;
94ed9b30 502 atend *a;
6e403221 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);
904ac13a 511 if (dstr_putline(&d, fp) < 0) break;
6e403221 512 l = d.buf + d.len;
513 for (p = q = d.buf; p < l; p++) {
904ac13a 514 if (!isalnum((unsigned char)*p)) continue;
6e403221 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);
94ed9b30 522 ok = 1;
6e403221 523 }
524 }
94ed9b30 525 if (ferror(fp) || fclose(fp))
6e403221 526 die("error reading `%s': %s", file, strerror(errno));
904ac13a
MW
527 for (a = aa_head; a; a = a->next)
528 if (a->func(a->p)) ok = 1;
94ed9b30 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);
6e403221 533}
534
535/*----- That's all, folks -------------------------------------------------*/