- if (0 == (e.mask = types[i].mask))
- return(NULL);
-
- if (++pos > argc--)
- return(NULL);
-
- if ('-' != *argv[pos])
- e.match = cs ? MATCH_STRCASE : MATCH_STR;
- else if (0 == strcmp("-eq", argv[pos]))
- e.match = cs ? MATCH_STRCASE : MATCH_STR;
- else if (0 == strcmp("-ieq", argv[pos]))
- e.match = MATCH_STRCASE;
- else if (0 == strcmp("-re", argv[pos]))
- e.match = cs ? MATCH_REGEXCASE : MATCH_REGEX;
- else if (0 == strcmp("-ire", argv[pos]))
- e.match = MATCH_REGEXCASE;
- else
- return(NULL);
-
- if ('-' == *argv[pos])
- pos++;
-
- if (pos > argc--)
- return(NULL);
-
- e.v = mandoc_strdup(argv[pos]);
-
- if (MATCH_REGEX == e.match || MATCH_REGEXCASE == e.match) {
- ch = REG_EXTENDED | REG_NOSUB;
- if (MATCH_REGEXCASE == e.match)
- ch |= REG_ICASE;
- if (regcomp(&e.re, e.v, ch))
+ /*
+ * Small note: if we're just starting, don't let "-a"
+ * and "-o" be considered logical operators: they're
+ * just tokens unless pairwise joining, in which case we
+ * record their existence (or assume "OR").
+ */
+ log = 0;
+
+ if (NULL != e && 0 == strcmp("-a", argv[*pos]))
+ log = 1;
+ else if (NULL != e && 0 == strcmp("-o", argv[*pos]))
+ log = 2;
+
+ if (log > 0 && ++(*pos) >= argc)
+ goto err;
+
+ /*
+ * Now we parse the term part. This can begin with
+ * "-i", in which case the expression is case
+ * insensitive.
+ */
+
+ if (0 == strcmp("(", argv[*pos])) {
+ ++(*pos);
+ ++(*lvl);
+ next = mandoc_calloc(1, sizeof(struct expr));
+ next->subexpr = exprexpr(argc, argv, pos, lvl, tt);
+ if (NULL == next->subexpr) {
+ free(next);
+ next = NULL;
+ }
+ } else if (0 == strcmp("-i", argv[*pos])) {
+ if (++(*pos) >= argc)
+ goto err;
+ next = exprterm(argv[*pos], 0);
+ } else
+ next = exprterm(argv[*pos], 1);
+
+ if (NULL == next)
+ goto err;
+
+ next->and = log == 1;
+ next->index = (int)(*tt)++;
+
+ /* Append to our chain of expressions. */
+
+ if (NULL == first) {
+ assert(NULL == e);
+ first = next;
+ } else {
+ assert(NULL != e);
+ e->next = next;
+ }
+ }
+
+ return(first);
+err:
+ exprfree(first);
+ return(NULL);
+}
+
+/*
+ * Parse a terminal expression with the grammar as defined in
+ * apropos(1).
+ * Return NULL if we fail the parse.
+ */
+static struct expr *
+exprterm(char *buf, int cs)
+{
+ struct expr e;
+ struct expr *p;
+ char *key;
+ int i;
+
+ memset(&e, 0, sizeof(struct expr));
+
+ /* Choose regex or substring match. */
+
+ if (NULL == (e.v = strpbrk(buf, "=~"))) {
+ e.regex = 0;
+ e.v = buf;
+ } else {
+ e.regex = '~' == *e.v;
+ *e.v++ = '\0';
+ }
+
+ /* Determine the record types to search for. */
+
+ e.mask = 0;
+ if (buf < e.v) {
+ while (NULL != (key = strsep(&buf, ","))) {
+ i = 0;
+ while (types[i].mask &&
+ strcmp(types[i].name, key))
+ i++;
+ e.mask |= types[i].mask;
+ }
+ }
+ if (0 == e.mask)
+ e.mask = TYPE_Nm | TYPE_Nd;
+
+ if (e.regex) {
+ i = REG_EXTENDED | REG_NOSUB | (cs ? 0 : REG_ICASE);
+ if (regcomp(&e.re, e.v, i))