7 * (c) 2001 Mark Wooding
10 /*----- Licensing notice --------------------------------------------------*
12 * This file is part of Anag: a simple wordgame helper.
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.
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.
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.
29 /*----- Header files ------------------------------------------------------*/
33 /*----- Static variables --------------------------------------------------*/
35 static const char *file = DICTIONARY;
37 /*----- Help text functions -----------------------------------------------*/
39 static void usage(FILE *fp)
41 pquis(fp, "Usage: $ [-f file] expression\n");
44 static void version(FILE *fp)
46 pquis(fp, "$, version " VERSION "\n");
49 static void help(FILE *fp)
55 Searches a wordlist, printing all of the words which match an expression.\n\
57 Options supported are:\n\
59 -h, --help display this help text\n\
60 -v, --version display the program's version number\n\
61 -u, --usage display a very brief usage message\n\
62 -f, --file FILE read wordlist from FILE, not `" DICTIONARY "'\n\
64 The basic tests in the expression are:\n\
66 -anagram WORD matches a full-length anagram\n\
67 -subgram WORD matches words which only use letters in WORD\n\
68 -wildcard PATTERN matches with wildcards `*' and `?'\n\
69 -trackword WORD matches words which can be found in a trackword\n\
70 -mono PATTERN matches words isomorphic to the given PATTERN\n\
74 -regexp REGEXP matches with an (extended) regular expression\n\
79 -pcre REGEXP matches with a Perl-like regular expression\n\
83 -length [+|-]N matches if length is [at least|at most] N\n\
84 -longest output longest matches found here\n\
85 -shortest output shortest matches found here\n\
87 These simple tests can be combined using the operators `-a', `-o' and `-n'\n\
88 (for `and', `or' and `not'; they may also be written `&', `|' and `!' if\n\
89 you like), and grouped using parentheses `(' and `)'.\n\
93 /*----- The options parser ------------------------------------------------*/
95 /* --- Options table structure --- */
105 O_HELP, O_VERSION, O_USAGE,
107 O_AND, O_OR, O_NOT, O_LPAREN, O_RPAREN,
108 O_ANAG, O_SUBG, O_WILD, O_TRACK, O_REGEXP, O_PCRE, O_MONO, O_LENGTH,
109 O_LONGEST, O_SHORTEST,
115 static const struct opt opttab[] = {
117 /* --- Options -- don't form part of the language --- */
119 { "help", 0, OF_SHORT, O_HELP },
120 { "version", 0, OF_SHORT, O_VERSION },
121 { "usage", 0, OF_SHORT, O_USAGE },
122 { "file", 1, OF_SHORT, O_FILE },
124 /* --- Operators -- provide the basic structure of the language --- *
126 * These are also given magical names by the parser.
129 { "and", 0, OF_SHORT, O_AND },
130 { "or", 0, OF_SHORT, O_OR },
131 { "not", 0, OF_SHORT, O_NOT },
133 /* --- Actual matching operations -- do something useful --- */
135 { "anagram", 1, 0, O_ANAG },
136 { "subgram", 1, 0, O_SUBG },
137 { "wildcard", 1, 0, O_WILD },
138 { "trackword", 1, 0, O_TRACK },
139 { "mono", 1, 0, O_MONO },
141 { "regexp", 1, 0, O_REGEXP },
144 { "pcre", 1, 0, O_PCRE },
146 { "length", 1, 0, O_LENGTH },
147 { "longest", 0, 0, O_LONGEST },
148 { "shortest", 0, 0, O_SHORTEST },
150 /* --- End marker --- */
156 static const char *const *av;
159 /* --- @nextopt@ --- *
161 * Arguments: @const char ***arg@ = where to store the arg pointer
163 * Returns: The tag of the next option.
165 * Use: Scans the next option off the command line. If the option
166 * doesn't form part of the language, it's processed internally,
167 * and you'll never see it from here. On exit, the @arg@
168 * pointer is set to contain the address of the option scanned,
169 * followed by its arguments if any. You're expected to know
170 * how many arguments there are for your option.
173 static unsigned nextopt(const char *const **arg)
176 const struct opt *o, *oo;
180 /* --- Pick the next option off the front --- */
187 /* --- Cope with various forms of magic --- */
190 if (!p[1]) switch (*p) {
191 case '&': return (O_AND);
192 case '|': return (O_OR);
193 case '!': return (O_NOT);
194 case '(': return (O_LPAREN);
195 case ')': return (O_RPAREN);
200 /* --- Now cope with other sorts of weirdies --- *
202 * By the end of this, a leading `-' or `--' will have been stripped.
212 die("syntax error near `--': rubbish at end of line");
216 /* --- Now look the word up in my table --- */
220 for (o = opttab; o->name; o++) {
221 if (strncmp(p, o->name, sz) == 0) {
222 if (strlen(o->name) == sz || ((o->f & OF_SHORT) && sz == 1)) {
227 die("ambiguous option name `-%s' (could match `-%s' or `-%s')",
228 p, oo->name, o->name);
234 die("unrecognized option name `-%s'", p);
236 /* --- Sort out the arguments --- */
238 if (ai + oo->nargs > ac)
239 die("too few arguments for `-%s' (need %u)", oo->name, oo->nargs);
242 /* --- Now process the option --- */
262 die("syntax error near `%s': unknown token type", av[ai - 1]);
266 /*----- Node types for operators ------------------------------------------*/
268 /* --- Node structures --- */
270 typedef struct node_bin {
276 typedef struct node_un {
281 /* --- Node functions --- */
283 static int n_or(node *nn, const char *p, size_t sz)
285 node_bin *n = (node_bin *)nn;
286 return (n->left->func(n->left, p, sz) || n->right->func(n->right, p, sz));
289 static int n_and(node *nn, const char *p, size_t sz)
291 node_bin *n = (node_bin *)nn;
292 return (n->left->func(n->left, p, sz) && n->right->func(n->right, p, sz));
295 static int n_not(node *nn, const char *p, size_t sz)
297 node_un *n = (node_un *)nn;
298 return (!n->arg->func(n->arg, p, sz));
301 /*----- Other simple node types -------------------------------------------*/
303 enum { LESS = -1, EQUAL = 0, GREATER = 1 };
305 typedef struct node_numeric {
311 static void parse_numeric(const char *p, int *dir, int *i)
318 case '-': *dir = LESS; pp++; break;
319 case '+': *dir = GREATER; pp++; break;
320 default: *dir = EQUAL; break;
323 l = strtol(pp, &q, 0);
324 if (*q || errno || l < INT_MIN || l > INT_MAX)
325 die("bad numeric parameter `%s'", p);
329 static node *make_numeric(const char *const *av,
330 int (*func)(struct node *, const char *, size_t))
332 node_numeric *n = xmalloc(sizeof(*n));
333 parse_numeric(av[0], &n->dir, &n->i);
338 static int cmp_numeric(int x, int dir, int n)
341 case LESS: return (x <= n);
342 case EQUAL: return (x == n);
343 case GREATER: return (x >= n);
348 static int n_length(node *nn, const char *p, size_t sz)
350 node_numeric *n = (node_numeric *)nn;
351 return (cmp_numeric(sz, n->dir, n->i));
354 /*----- Parser for the expression syntax ----------------------------------*/
356 /* --- A parser context --- */
358 typedef struct p_ctx {
360 const char *const *a;
363 /* --- Parser structure --- *
365 * This is a simple recursive descent parser. The context retains
366 * information about the current token. Each function is passed the address
367 * of a node pointer to fill in. This simplifies the binary operator code
368 * somewhat, relative to returning pointers to node trees.
371 static void p_expr(p_ctx *p, node **/*nn*/);
373 static void p_next(p_ctx *p)
375 static const char *const eof[] = { "<end>", 0 };
376 p->t = nextopt(&p->a);
381 static void p_factor(p_ctx *p, node **nn)
384 if (p->t == O_LPAREN) {
387 if (p->t != O_RPAREN)
388 die("syntax error near `%s': missing `)'", *p->a);
390 } else if (p->t == O_NOT) {
391 n = xmalloc(sizeof(node_un));
395 p_factor(p, &n->arg);
398 case O_ANAG: *nn = anagram(p->a + 1); break;
399 case O_SUBG: *nn = subgram(p->a + 1); break;
400 case O_WILD: *nn = wildcard(p->a + 1); break;
401 case O_TRACK: *nn = trackword(p->a + 1); break;
403 case O_REGEXP: *nn = regexp(p->a + 1); break;
406 case O_PCRE: *nn = pcrenode(p->a + 1); break;
408 case O_MONO: *nn = mono(p->a + 1); break;
409 case O_LENGTH: *nn = make_numeric(p->a + 1, n_length); break;
410 case O_LONGEST: *nn = longest(p->a + 1); break;
411 case O_SHORTEST: *nn = shortest(p->a + 1); break;
412 default: die("syntax error near `%s': unexpected token", *p->a);
418 static void p_term(p_ctx *p, node **nn)
433 n = xmalloc(sizeof(node_bin));
441 static void p_expr(p_ctx *p, node **nn)
449 n = xmalloc(sizeof(node_bin));
457 /* --- @p_argv@ --- *
459 * Arguments: @int argc@ = number of command-line arguments
460 * @const char *const argv[]@ = vectoor of arguments
462 * Returns: A compiled node, parsed from the arguments.
464 * Use: Does the donkey-work of parsing a command-line.
467 static node *p_argv(int argc, const char *const argv[])
478 pquis(stderr, "(Run `$ --help' for more detail.)\n");
483 die("syntax error near `%s': rubbish at end of line (too many `)'s?)",
489 /*----- At-end stuff ------------------------------------------------------*/
491 /* --- @atend_register@ --- *
493 * Arguments: @int (*func)(void *)@ = function to call
494 * @void *p@ = handle to pass to it
498 * Use: Adds a function to the list of things to do at the end of the
499 * program. The function should return nonzero if it produced
503 typedef struct atend {
505 int (*func)(void */*p*/);
509 static atend *aa_head = 0, **aa_tail = &aa_head;
511 void atend_register(int (*func)(void */*p*/), void *p)
513 atend *a = xmalloc(sizeof(*a));
521 /*----- Main code ---------------------------------------------------------*/
525 * Arguments: @int argc@ = number of command-line arguments
526 * @char *argv[]@ = vector of argument words
528 * Returns: Zero on success, nonzero on failure.
530 * Use: Picks entries from a word list which match particular
531 * expressions. This might be of assistance to word-game types.
534 int main(int argc, char *argv[])
544 n = p_argv(argc, (const char *const *)argv);
546 if ((fp = fopen(file, "r")) == 0)
547 die("error opening `%s': %s", file, strerror(errno));
550 if (dstr_putline(&d, fp) < 0)
553 for (p = q = d.buf; p < l; p++) {
554 if (!isalnum((unsigned char)*p))
556 *q++ = tolower((unsigned char)*p);
560 if (n->func(n, d.buf, d.len)) {
561 fwrite(d.buf, 1, d.len, stdout);
566 if (ferror(fp) || fclose(fp))
567 die("error reading `%s': %s", file, strerror(errno));
568 for (a = aa_head; a; a = a->next) {
572 if (fflush(stdout) || ferror(stdout) || fclose(stdout))
573 die("error writing output: %s", strerror(errno));
574 if (!ok) pquis(stderr, "$: no matches found\n");
575 return (ok ? EX_OK : EX_NONE);
578 /*----- That's all, folks -------------------------------------------------*/