CCL: fix leak on syntax errors with split-list
[yaz-moved-to-github.git] / src / cclfind.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) Index Data
3  * See the file LICENSE for details.
4  */
5 /**
6  * \file cclfind.c
7  * \brief Implements parsing of a CCL FIND query.
8  *
9  * This source file implements parsing of a CCL Query (ISO8777).
10  * The parser uses predictive parsing, but it does several tokens
11  * of lookahead in the handling of relational operations.. So
12  * it's not really pure.
13  */
14 #if HAVE_CONFIG_H
15 #include <config.h>
16 #endif
17
18 #include <stdlib.h>
19 #include <string.h>
20 #include <assert.h>
21
22 #include "cclp.h"
23
24 /* returns type of current lookahead */
25 #define KIND (cclp->look_token->kind)
26
27 /* move one token forward */
28 #define ADVANCE cclp->look_token = cclp->look_token->next
29
30 /**
31  * qual_val_type: test for existance of attribute type/value pair.
32  * qa:     Attribute array
33  * type:   Type of attribute to search for
34  * value:  Value of attribute to seach for
35  * return: 1 if found; 0 otherwise.
36  */
37 static int qual_val_type(ccl_qualifier_t *qa, int type, int value,
38                          char **attset)
39 {
40     int i;
41
42     if (!qa)
43         return 0;
44     for (i = 0; qa[i]; i++)
45     {
46         struct ccl_rpn_attr *q = ccl_qual_get_attr(qa[i]);
47         while (q)
48         {
49             if (q->type == type && q->kind == CCL_RPN_ATTR_NUMERIC &&
50                 q->value.numeric == value)
51             {
52                 if (attset)
53                     *attset = q->set;
54                 return 1;
55             }
56             q = q->next;
57         }
58     }
59     return 0;
60 }
61
62 /**
63  * strxcat: concatenate strings.
64  * n:      Null-terminated Destination string
65  * src:    Source string to be appended (not null-terminated)
66  * len:    Length of source string.
67  */
68 static void strxcat(char *n, const char *src, int len)
69 {
70     while (*n)
71         n++;
72     while (--len >= 0)
73         *n++ = *src++;
74     *n = '\0';
75 }
76
77 /**
78  * copy_token_name: Return copy of CCL token name
79  * tp:      Pointer to token info.
80  * return:  malloc(3) allocated copy of token name.
81  */
82 static char *copy_token_name(struct ccl_token *tp)
83 {
84     char *str = (char *)xmalloc(tp->len + 1);
85     ccl_assert(str);
86     memcpy(str, tp->name, tp->len);
87     str[tp->len] = '\0';
88     return str;
89 }
90
91 /**
92  * mk_node: Create RPN node.
93  * kind:   Type of node.
94  * return: pointer to allocated node.
95  */
96 struct ccl_rpn_node *ccl_rpn_node_create(enum ccl_rpn_kind kind)
97 {
98     struct ccl_rpn_node *p;
99     p = (struct ccl_rpn_node *)xmalloc(sizeof(*p));
100     ccl_assert(p);
101     p->kind = kind;
102
103     switch (kind)
104     {
105     case CCL_RPN_TERM:
106         p->u.t.attr_list = 0;
107         p->u.t.term = 0;
108         p->u.t.qual = 0;
109         break;
110     default:
111         break;
112     }
113     return p;
114 }
115
116 static struct ccl_rpn_node *ccl_rpn_node_mkbool(struct ccl_rpn_node *l,
117                                                 struct ccl_rpn_node *r,
118                                                 enum ccl_rpn_kind op)
119 {
120     if (l && r)
121     {
122         struct ccl_rpn_node *tmp = ccl_rpn_node_create(op);
123         tmp->u.p[0] = l;
124         tmp->u.p[1] = r;
125         tmp->u.p[2] = 0;
126         return tmp;
127     }
128     else if (r)
129         return r;
130     return l;
131 }
132
133 static struct ccl_rpn_node *ccl_rpn_dup(struct ccl_rpn_node *rpn)
134 {
135     struct ccl_rpn_node *n;
136     struct ccl_rpn_attr *attr, **attrp;
137     if (!rpn)
138         return 0;
139     n = ccl_rpn_node_create(rpn->kind);
140     switch (rpn->kind)
141     {
142     case CCL_RPN_AND:
143     case CCL_RPN_OR:
144     case CCL_RPN_NOT:
145         n->u.p[0] = ccl_rpn_dup(rpn->u.p[0]);
146         n->u.p[1] = ccl_rpn_dup(rpn->u.p[1]);
147         break;
148     case CCL_RPN_TERM:
149         n->u.t.term = xstrdup(rpn->u.t.term);
150         n->u.t.qual = rpn->u.t.qual ? xstrdup(rpn->u.t.qual) : 0;
151         attrp = &n->u.t.attr_list;
152         for (attr = rpn->u.t.attr_list; attr; attr = attr->next)
153         {
154             *attrp = (struct ccl_rpn_attr *) xmalloc(sizeof(**attrp));
155             (*attrp)->kind = attr->kind;
156             (*attrp)->type = attr->type;
157             if (attr->kind == CCL_RPN_ATTR_STRING)
158                 (*attrp)->value.str = xstrdup(attr->value.str);
159             else
160                 (*attrp)->value.numeric = attr->value.numeric;
161             if (attr->set)
162                 (*attrp)->set = xstrdup(attr->set);
163             else
164                 (*attrp)->set = 0;
165             attrp = &(*attrp)->next;
166         }
167         *attrp = 0;
168         break;
169     case CCL_RPN_SET:
170         n->u.setname = xstrdup(rpn->u.setname);
171         break;
172     case CCL_RPN_PROX:
173         n->u.p[0] = ccl_rpn_dup(rpn->u.p[0]);
174         n->u.p[1] = ccl_rpn_dup(rpn->u.p[1]);
175         n->u.p[2] = ccl_rpn_dup(rpn->u.p[2]);
176         break;
177     }
178     return n;
179 }
180
181 /**
182  * ccl_rpn_delete: Delete RPN tree.
183  * rpn:   Pointer to tree.
184  */
185 void ccl_rpn_delete(struct ccl_rpn_node *rpn)
186 {
187     struct ccl_rpn_attr *attr, *attr1;
188     if (!rpn)
189         return;
190     switch (rpn->kind)
191     {
192     case CCL_RPN_AND:
193     case CCL_RPN_OR:
194     case CCL_RPN_NOT:
195         ccl_rpn_delete(rpn->u.p[0]);
196         ccl_rpn_delete(rpn->u.p[1]);
197         break;
198     case CCL_RPN_TERM:
199         xfree(rpn->u.t.term);
200         xfree(rpn->u.t.qual);
201         for (attr = rpn->u.t.attr_list; attr; attr = attr1)
202         {
203             attr1 = attr->next;
204             if (attr->kind == CCL_RPN_ATTR_STRING)
205                 xfree(attr->value.str);
206             if (attr->set)
207                 xfree(attr->set);
208             xfree(attr);
209         }
210         break;
211     case CCL_RPN_SET:
212         xfree(rpn->u.setname);
213         break;
214     case CCL_RPN_PROX:
215         ccl_rpn_delete(rpn->u.p[0]);
216         ccl_rpn_delete(rpn->u.p[1]);
217         ccl_rpn_delete(rpn->u.p[2]);
218         break;
219     }
220     xfree(rpn);
221 }
222
223 static struct ccl_rpn_node *find_spec(CCL_parser cclp, ccl_qualifier_t *qa);
224
225 static int is_term_ok(int look, int *list)
226 {
227     for (; *list >= 0; list++)
228         if (look == *list)
229             return 1;
230     return 0;
231 }
232
233 static struct ccl_rpn_node *search_terms(CCL_parser cclp, ccl_qualifier_t *qa);
234
235 static struct ccl_rpn_attr *add_attr_node(struct ccl_rpn_node *p,
236                                            const char *set, int type)
237 {
238     struct ccl_rpn_attr *n = (struct ccl_rpn_attr *) xmalloc(sizeof(*n));
239     ccl_assert(n);
240     if (set)
241         n->set = xstrdup(set);
242     else
243         n->set = 0;
244     n->type = type;
245     n->next = p->u.t.attr_list;
246     p->u.t.attr_list = n;
247     return n;
248 }
249
250 /**
251  * add_attr_numeric: Add attribute (type/value) to RPN term node.
252  * p:     RPN node of type term.
253  * type:  Type of attribute
254  * value: Value of attribute
255  * set: Attribute set name
256  */
257 void ccl_add_attr_numeric(struct ccl_rpn_node *p, const char *set,
258                           int type, int value)
259 {
260     struct ccl_rpn_attr *n = add_attr_node(p, set, type);
261     n->kind = CCL_RPN_ATTR_NUMERIC;
262     n->value.numeric = value;
263 }
264
265 void ccl_add_attr_string(struct ccl_rpn_node *p, const char *set,
266                          int type, char *value)
267 {
268     struct ccl_rpn_attr *n = add_attr_node(p, set, type);
269     n->kind = CCL_RPN_ATTR_STRING;
270     n->value.str = xstrdup(value);
271 }
272
273 static size_t cmp_operator(const char **aliases, const char *input)
274 {
275     for (; *aliases; aliases++)
276     {
277         const char *cp = *aliases;
278         size_t i;
279         for (i = 0; *cp && *cp == input[i]; i++, cp++)
280             ;
281         if (*cp == '\0')
282             return i;
283     }
284     return 0;
285 }
286
287
288 #define REGEX_CHARS "^[]{}()|.*+?!$"
289 #define CCL_CHARS "#?\\"
290
291 static int has_ccl_masking(const char *src_str,
292                            size_t src_len,
293                            const char **truncation_aliases,
294                            const char **mask_aliases)
295 {
296     size_t j;
297     int quote_mode = 0;
298
299     for (j = 0; j < src_len; j++)
300     {
301         size_t op_size;
302         if (j > 0 && src_str[j-1] == '\\')
303             ;
304         else if (src_str[j] == '"')
305             quote_mode = !quote_mode;
306         else if (!quote_mode &&
307                  (op_size = cmp_operator(truncation_aliases,
308                                          src_str + j)))
309             return 1;
310         else if (!quote_mode &&
311                  (op_size = cmp_operator(mask_aliases,
312                                           src_str + j)))
313             return 1;
314     }
315     return 0;
316 }
317
318 static int append_term(CCL_parser cclp, const char *src_str, size_t src_len,
319                        char *dst_term, int regex_trunc, int z3958_trunc,
320                        const char **truncation_aliases,
321                        const char **mask_aliases,
322                        int is_first, int is_last,
323                        int *left_trunc, int *right_trunc)
324 {
325     size_t j;
326     int quote_mode = 0;
327
328     for (j = 0; j < src_len; j++)
329     {
330         size_t op_size;
331         if (j > 0 && src_str[j-1] == '\\')
332         {
333             if (regex_trunc && strchr(REGEX_CHARS "\\", src_str[j]))
334                 strcat(dst_term, "\\");
335             else if (z3958_trunc && strchr(CCL_CHARS "\\", src_str[j]))
336                 strcat(dst_term, "\\");
337             strxcat(dst_term, src_str + j, 1);
338         }
339         else if (src_str[j] == '"')
340             quote_mode = !quote_mode;
341         else if (!quote_mode &&
342                  (op_size = cmp_operator(truncation_aliases,
343                                          src_str + j))
344             )
345         {
346             j += (op_size - 1);  /* j++ in for loop */
347             if (regex_trunc)
348                 strcat(dst_term, ".*");
349             else if (z3958_trunc)
350                 strcat(dst_term, "?");
351             else if (is_first && j == 0)
352                 *left_trunc = 1;
353             else if (is_last && j == src_len - 1)
354                 *right_trunc = 1;
355             else
356             {
357                 cclp->error_code = CCL_ERR_TRUNC_NOT_EMBED;
358                 return -1;
359             }
360         }
361         else if (!quote_mode &&
362                  (op_size = cmp_operator(mask_aliases, src_str + j)))
363         {
364             j += (op_size - 1);  /* j++ in for loop */
365             if (regex_trunc)
366                 strcat(dst_term, ".");
367             else if (z3958_trunc)
368                 strcat(dst_term, "#");
369             else
370             {
371                 cclp->error_code = CCL_ERR_TRUNC_NOT_SINGLE;
372                 return -1;
373             }
374         }
375         else if (src_str[j] != '\\')
376         {
377             if (regex_trunc && strchr(REGEX_CHARS, src_str[j]))
378                 strcat(dst_term, "\\");
379             else if (z3958_trunc && strchr(CCL_CHARS, src_str[j]))
380                 strcat(dst_term, "\\");
381             strxcat(dst_term, src_str + j, 1);
382         }
383     }
384     return 0;
385 }
386
387
388 static struct ccl_rpn_node *ccl_term_one_use(CCL_parser cclp,
389                                              struct ccl_token *lookahead0,
390                                              struct ccl_rpn_attr *attr_use,
391                                              ccl_qualifier_t *qa,
392                                              size_t no,
393                                              int is_phrase,
394                                              int auto_group)
395 {
396     struct ccl_rpn_node *p;
397     size_t i;
398     int relation_value = -1;
399     int position_value = -1;
400     int structure_value = -1;
401     int truncation_value = -1;
402     int completeness_value = -1;
403
404     int left_trunc = 0;
405     int right_trunc = 0;
406     int regex_trunc = 0;
407     int z3958_trunc = 0;
408     int is_ccl_masked = 0;
409     char *attset;
410     struct ccl_token *lookahead = lookahead0;
411     const char **truncation_aliases;
412     const char *t_default[2];
413     const char **mask_aliases;
414     const char *m_default[2];
415     int term_len = 0;
416
417     truncation_aliases =
418         ccl_qual_search_special(cclp->bibset, "truncation");
419     if (!truncation_aliases)
420     {
421         truncation_aliases = t_default;
422         t_default[0] = "?";
423         t_default[1] = 0;
424     }
425     mask_aliases =
426         ccl_qual_search_special(cclp->bibset, "mask");
427     if (!mask_aliases)
428     {
429         mask_aliases = m_default;
430         m_default[0] = "#";
431         m_default[1] = 0;
432     }
433     for (i = 0; i < no; i++)
434     {
435         if (has_ccl_masking(lookahead->name, lookahead->len,
436                             truncation_aliases,
437                             mask_aliases))
438             is_ccl_masked = 1;
439
440         term_len += 1 + lookahead->len + lookahead->ws_prefix_len;
441         lookahead = lookahead->next;
442     }
443     lookahead = lookahead0;
444
445     p = ccl_rpn_node_create(CCL_RPN_TERM);
446     p->u.t.attr_list = NULL;
447     p->u.t.term = NULL;
448     if (qa && qa[0])
449     {
450         const char *n = ccl_qual_get_name(qa[0]);
451         if (n)
452             p->u.t.qual = xstrdup(n);
453     }
454     /* go through all attributes and add them to the attribute list */
455     for (i = 0; qa && qa[i]; i++)
456     {
457         struct ccl_rpn_attr *attr;
458         for (attr = ccl_qual_get_attr(qa[i]); attr; attr = attr->next)
459             if (attr->type != 1 || !attr_use || attr == attr_use)
460             {
461                 switch (attr->kind)
462                 {
463                 case CCL_RPN_ATTR_STRING:
464                     ccl_add_attr_string(p, attr->set, attr->type,
465                                         attr->value.str);
466                     break;
467                 case CCL_RPN_ATTR_NUMERIC:
468                     if (attr->value.numeric > 0)
469                     {   /* deal only with REAL attributes (positive) */
470                         switch (attr->type)
471                         {
472                         case CCL_BIB1_REL:
473                             if (relation_value != -1)
474                                 continue;
475                             relation_value = attr->value.numeric;
476                             break;
477                         case CCL_BIB1_POS:
478                             if (position_value != -1)
479                                 continue;
480                             position_value = attr->value.numeric;
481                             break;
482                         case CCL_BIB1_STR:
483                             if (structure_value != -1)
484                                 continue;
485                             structure_value = attr->value.numeric;
486                             break;
487                         case CCL_BIB1_TRU:
488                             if (truncation_value != -1)
489                                 continue;
490                             truncation_value = attr->value.numeric;
491                             break;
492                         case CCL_BIB1_COM:
493                             if (completeness_value != -1)
494                                 continue;
495                             completeness_value = attr->value.numeric;
496                             break;
497                         }
498                         ccl_add_attr_numeric(p, attr->set, attr->type,
499                                              attr->value.numeric);
500                     }
501                 }
502             }
503     }
504     attset = 0;
505     if (structure_value == -1 && (
506             auto_group ||
507             qual_val_type(qa, CCL_BIB1_STR, CCL_BIB1_STR_WP, &attset))
508         )
509     {
510         if (!is_phrase)
511             ccl_add_attr_numeric(p, attset, CCL_BIB1_STR, 2);
512         else
513             ccl_add_attr_numeric(p, attset, CCL_BIB1_STR, 1);
514     }
515     if (qual_val_type(qa, CCL_BIB1_TRU, CCL_BIB1_TRU_CAN_REGEX,
516                       &attset))
517     {
518         if (is_ccl_masked)
519             regex_trunc = 1; /* regex trunc (102) allowed */
520     }
521     else if (qual_val_type(qa, CCL_BIB1_TRU, CCL_BIB1_TRU_CAN_Z3958,
522                            &attset))
523     {
524         if (is_ccl_masked)
525             z3958_trunc = 1; /* Z39.58 trunc (CCL) trunc allowed */
526     }
527     /* make the RPN token */
528     p->u.t.term = (char *)xmalloc(term_len * 2 + 2);
529     ccl_assert(p->u.t.term);
530     p->u.t.term[0] = '\0';
531
532     for (i = 0; i < no; i++)
533     {
534         const char *src_str = lookahead->name;
535         size_t src_len = lookahead->len;
536
537         if (p->u.t.term[0] && lookahead->ws_prefix_len)
538         {
539             strxcat(p->u.t.term, lookahead->ws_prefix_buf,
540                     lookahead->ws_prefix_len);
541         }
542         if (append_term(cclp, src_str, src_len, p->u.t.term, regex_trunc,
543                         z3958_trunc, truncation_aliases, mask_aliases,
544                         i == 0, i == no - 1,
545                         &left_trunc, &right_trunc))
546         {
547             ccl_rpn_delete(p);
548             return NULL;
549         }
550         lookahead = lookahead->next;
551     }
552     if (left_trunc && right_trunc)
553     {
554         if (!qual_val_type(qa, CCL_BIB1_TRU, CCL_BIB1_TRU_CAN_BOTH,
555                            &attset))
556         {
557             cclp->error_code = CCL_ERR_TRUNC_NOT_BOTH;
558             ccl_rpn_delete(p);
559             return NULL;
560         }
561         ccl_add_attr_numeric(p, attset, CCL_BIB1_TRU, 3);
562     }
563     else if (right_trunc)
564     {
565         if (!qual_val_type(qa, CCL_BIB1_TRU, CCL_BIB1_TRU_CAN_RIGHT,
566                            &attset))
567         {
568             cclp->error_code = CCL_ERR_TRUNC_NOT_RIGHT;
569             ccl_rpn_delete(p);
570             return NULL;
571         }
572         ccl_add_attr_numeric(p, attset, CCL_BIB1_TRU, 1);
573     }
574     else if (left_trunc)
575     {
576         if (!qual_val_type(qa, CCL_BIB1_TRU, CCL_BIB1_TRU_CAN_LEFT,
577                            &attset))
578         {
579             cclp->error_code = CCL_ERR_TRUNC_NOT_LEFT;
580             ccl_rpn_delete(p);
581             return NULL;
582         }
583         ccl_add_attr_numeric(p, attset, CCL_BIB1_TRU, 2);
584     }
585     else if (regex_trunc)
586     {
587         ccl_add_attr_numeric(p, attset, CCL_BIB1_TRU, 102);
588     }
589     else if (z3958_trunc)
590     {
591         ccl_add_attr_numeric(p, attset, CCL_BIB1_TRU, 104);
592     }
593     else
594     {
595         if (qual_val_type(qa, CCL_BIB1_TRU, CCL_BIB1_TRU_CAN_NONE,
596                           &attset))
597             ccl_add_attr_numeric(p, attset, CCL_BIB1_TRU, 100);
598     }
599     return p;
600 }
601
602 static struct ccl_rpn_node *ccl_term_multi_use(CCL_parser cclp,
603                                                struct ccl_token *lookahead0,
604                                                ccl_qualifier_t *qa,
605                                                size_t no,
606                                                int is_phrase,
607                                                int auto_group)
608 {
609     struct ccl_rpn_node *p = 0;
610     int i;
611     for (i = 0; qa && qa[i]; i++)
612     {
613         struct ccl_rpn_attr *attr;
614         for (attr = ccl_qual_get_attr(qa[i]); attr; attr = attr->next)
615             if (attr->type == 1 && i == 0)
616             {
617                 struct ccl_rpn_node *tmp2;
618                 tmp2 = ccl_term_one_use(cclp, lookahead0,
619                                         attr, qa, no,
620                                         is_phrase, auto_group);
621                 if (!tmp2)
622                 {
623                     ccl_rpn_delete(p);
624                     return 0;
625                 }
626                 p = ccl_rpn_node_mkbool(p, tmp2, CCL_RPN_OR);
627             }
628     }
629     if (!p)
630         p = ccl_term_one_use(cclp, lookahead0,
631                              0 /* attr: no use */, qa, no,
632                              is_phrase, auto_group);
633     return p;
634 }
635
636 static struct ccl_rpn_node *split_recur(CCL_parser cclp, ccl_qualifier_t *qa,
637                                         struct ccl_rpn_node *parent,
638                                         struct ccl_token **ar, size_t sz)
639 {
640     size_t l;
641     struct ccl_rpn_node *p_top = 0;
642     assert(sz > 0);
643     for (l = 1; l <= sz; l++)
644     {
645         struct ccl_rpn_node *p1;
646         struct ccl_rpn_node *p2 = ccl_term_multi_use(cclp, ar[0],
647                                                      qa, l,
648                                                      l > 1,
649                                                      /* auto_group */0);
650         if (!p2)
651         {
652             ccl_rpn_delete(p_top);
653             return 0;
654         }
655         if (parent)
656         {
657             struct ccl_rpn_node *tmp = ccl_rpn_node_create(CCL_RPN_AND);
658             tmp->u.p[0] = l > 1 ? ccl_rpn_dup(parent) : parent;
659             tmp->u.p[1] = p2;
660             p2 = tmp;
661         }
662         if (sz > l)
663             p1 = split_recur(cclp, qa, p2, ar + l, sz - l);
664         else
665             p1 = p2;
666         if (!p1)
667         {
668             ccl_rpn_delete(p2);
669             ccl_rpn_delete(p_top);
670             return 0;
671         }
672         p_top = ccl_rpn_node_mkbool(p_top, p1, CCL_RPN_OR);
673     }
674     assert(p_top);
675     return p_top;
676 }
677
678 static struct ccl_rpn_node *search_term_split_list(CCL_parser cclp,
679                                                    ccl_qualifier_t *qa,
680                                                    int *term_list, int multi)
681 {
682     struct ccl_rpn_node *p;
683     struct ccl_token **ar;
684     struct ccl_token *lookahead = cclp->look_token;
685     size_t i, sz;
686     for (sz = 0; is_term_ok(lookahead->kind, term_list); sz++)
687         lookahead = lookahead->next;
688     if (sz == 0)
689     {
690         cclp->error_code = CCL_ERR_TERM_EXPECTED;
691         return 0;
692     }
693     ar = (struct ccl_token **) xmalloc(sizeof(*lookahead) * sz);
694     lookahead = cclp->look_token;
695     for (i = 0; is_term_ok(lookahead->kind, term_list); i++)
696     {
697         ar[i] = lookahead;
698         lookahead = lookahead->next;
699     }
700     p = split_recur(cclp, qa, 0, ar, sz);
701     xfree(ar);
702     for (i = 0; i < sz; i++)
703         ADVANCE;
704     return p;
705 }
706
707 /**
708  * search_term: Parse CCL search term.
709  * cclp:   CCL Parser
710  * qa:     Qualifier attributes already applied.
711  * term_list: tokens we accept as terms in context
712  * multi:  whether we accept "multiple" tokens
713  * return: pointer to node(s); NULL on error.
714  */
715 static struct ccl_rpn_node *search_term_x(CCL_parser cclp,
716                                           ccl_qualifier_t *qa,
717                                           int *term_list, int multi)
718 {
719     struct ccl_rpn_node *p_top = 0;
720     struct ccl_token *lookahead = cclp->look_token;
721     int and_list = 0;
722     int auto_group = 0;
723     int or_list = 0;
724
725     if (qual_val_type(qa, CCL_BIB1_STR, CCL_BIB1_STR_AND_LIST, 0))
726         and_list = 1;
727     if (qual_val_type(qa, CCL_BIB1_STR, CCL_BIB1_STR_AUTO_GROUP, 0))
728         auto_group = 1;
729     if (qual_val_type(qa, CCL_BIB1_STR, CCL_BIB1_STR_OR_LIST, 0))
730         or_list = 1;
731     if (qual_val_type(qa, CCL_BIB1_STR, CCL_BIB1_STR_SPLIT_LIST, 0))
732     {
733         return search_term_split_list(cclp, qa, term_list, multi);
734     }
735     while (1)
736     {
737         struct ccl_rpn_node *p = 0;
738         size_t no, i;
739         int is_phrase = 0;
740         size_t max = 200;
741         if (and_list || or_list || !multi)
742             max = 1;
743
744         /* ignore commas when dealing with and-lists .. */
745         if (and_list && lookahead && lookahead->kind == CCL_TOK_COMMA)
746         {
747             lookahead = lookahead->next;
748             ADVANCE;
749             continue;
750         }
751         for (no = 0; no < max && is_term_ok(lookahead->kind, term_list); no++)
752         {
753             int this_is_phrase = 0;
754             for (i = 0; i<lookahead->len; i++)
755                 if (lookahead->name[i] == ' ')
756                     this_is_phrase = 1;
757             if (auto_group)
758             {
759                 if (no > 0 && (is_phrase || is_phrase != this_is_phrase))
760                     break;
761                 is_phrase = this_is_phrase;
762             }
763             else if (this_is_phrase || no > 0)
764                 is_phrase = 1;
765             lookahead = lookahead->next;
766         }
767
768         if (no == 0)
769             break;      /* no more terms . stop . */
770         p = ccl_term_multi_use(cclp, cclp->look_token, qa, no,
771                                is_phrase, auto_group);
772         for (i = 0; i < no; i++)
773             ADVANCE;
774         if (!p)
775             return 0;
776         p_top = ccl_rpn_node_mkbool(p_top, p, or_list ? CCL_RPN_OR : CCL_RPN_AND);
777         if (!multi)
778             break;
779     }
780     if (!p_top)
781         cclp->error_code = CCL_ERR_TERM_EXPECTED;
782     return p_top;
783 }
784
785 static struct ccl_rpn_node *search_term(CCL_parser cclp, ccl_qualifier_t *qa)
786 {
787     static int list[] = {CCL_TOK_TERM, CCL_TOK_COMMA, -1};
788     return search_term_x(cclp, qa, list, 0);
789 }
790
791
792 static struct ccl_rpn_node *search_terms2(CCL_parser cclp,
793                                           ccl_qualifier_t *qa)
794 {
795     if (KIND == CCL_TOK_LP)
796     {
797         struct ccl_rpn_node *p;
798         ADVANCE;
799         if (!(p = find_spec(cclp, qa)))
800             return NULL;
801         if (KIND != CCL_TOK_RP)
802         {
803             cclp->error_code = CCL_ERR_RP_EXPECTED;
804             ccl_rpn_delete(p);
805             return NULL;
806         }
807         ADVANCE;
808         return p;
809     }
810     else
811     {
812         static int list[] = {
813             CCL_TOK_TERM, CCL_TOK_COMMA,CCL_TOK_EQ,
814             CCL_TOK_REL, CCL_TOK_SET, -1};
815
816         return search_term_x(cclp, qa, list, 1);
817     }
818 }
819
820
821 static
822 struct ccl_rpn_node *qualifiers_order(CCL_parser cclp,
823                                       ccl_qualifier_t *ap, char *attset)
824 {
825     int rel = 0;
826     struct ccl_rpn_node *p;
827
828     if (cclp->look_token->len == 1)
829     {
830         if (cclp->look_token->name[0] == '<')
831             rel = 1;
832         else if (cclp->look_token->name[0] == '=')
833             rel = 3;
834         else if (cclp->look_token->name[0] == '>')
835             rel = 5;
836     }
837     else if (cclp->look_token->len == 2)
838     {
839         if (!memcmp(cclp->look_token->name, "<=", 2))
840             rel = 2;
841         else if (!memcmp(cclp->look_token->name, ">=", 2))
842             rel = 4;
843         else if (!memcmp(cclp->look_token->name, "<>", 2))
844             rel = 6;
845     }
846     if (!rel)
847     {
848         cclp->error_code = CCL_ERR_BAD_RELATION;
849         return NULL;
850     }
851     ADVANCE;  /* skip relation */
852     if (rel == 3 &&
853         qual_val_type(ap, CCL_BIB1_REL, CCL_BIB1_REL_PORDER, 0))
854     {
855         /* allow - inside term and treat it as range _always_ */
856         /* relation is =. Extract "embedded" - to separate terms */
857         if (KIND == CCL_TOK_TERM)
858         {
859             size_t i;
860             int quote_mode = 0;
861             for (i = 0; i<cclp->look_token->len; i++)
862             {
863                 if (i > 0 && cclp->look_token->name[i] == '\\')
864                     ;
865                 else if (cclp->look_token->name[i] == '"')
866                     quote_mode = !quote_mode;
867                 else if (cclp->look_token->name[i] == '-' && !quote_mode)
868                     break;
869             }
870
871             if (cclp->look_token->len > 1 && i == 0)
872             {   /*  -xx*/
873                 struct ccl_token *ntoken = ccl_token_add(cclp->look_token);
874
875                 ntoken->kind = CCL_TOK_TERM;
876                 ntoken->name = cclp->look_token->name + 1;
877                 ntoken->len = cclp->look_token->len - 1;
878
879                 cclp->look_token->len = 1;
880                 cclp->look_token->name = "-";
881             }
882             else if (cclp->look_token->len > 1 && i == cclp->look_token->len-1)
883             {   /* xx- */
884                 struct ccl_token *ntoken = ccl_token_add(cclp->look_token);
885
886                 ntoken->kind = CCL_TOK_TERM;
887                 ntoken->name = "-";
888                 ntoken->len = 1;
889
890                 (cclp->look_token->len)--;
891             }
892             else if (cclp->look_token->len > 2 && i < cclp->look_token->len)
893             {   /* xx-yy */
894                 struct ccl_token *ntoken1 = ccl_token_add(cclp->look_token);
895                 struct ccl_token *ntoken2 = ccl_token_add(ntoken1);
896
897                 ntoken1->kind = CCL_TOK_TERM;  /* generate - */
898                 ntoken1->name = "-";
899                 ntoken1->len = 1;
900
901                 ntoken2->kind = CCL_TOK_TERM;  /* generate yy */
902                 ntoken2->name = cclp->look_token->name + (i+1);
903                 ntoken2->len = cclp->look_token->len - (i+1);
904
905                 cclp->look_token->len = i;     /* adjust xx */
906             }
907             else if (i == cclp->look_token->len &&
908                      cclp->look_token->next &&
909                      cclp->look_token->next->kind == CCL_TOK_TERM &&
910                      cclp->look_token->next->len > 1 &&
911                      cclp->look_token->next->name[0] == '-')
912
913             {   /* xx -yy */
914                 /* we _know_ that xx does not have - in it */
915                 struct ccl_token *ntoken = ccl_token_add(cclp->look_token);
916
917                 ntoken->kind = CCL_TOK_TERM;    /* generate - */
918                 ntoken->name = "-";
919                 ntoken->len = 1;
920
921                 (ntoken->next->name)++;        /* adjust yy */
922                 (ntoken->next->len)--;
923             }
924         }
925     }
926
927     if (rel == 3 &&
928         KIND == CCL_TOK_TERM &&
929         cclp->look_token->next && cclp->look_token->next->len == 1 &&
930         cclp->look_token->next->name[0] == '-')
931     {
932         struct ccl_rpn_node *p1;
933         if (!(p1 = search_term(cclp, ap)))
934             return NULL;
935         ADVANCE;                   /* skip '-' */
936         if (KIND == CCL_TOK_TERM)  /* = term - term  ? */
937         {
938             struct ccl_rpn_node *p2;
939
940             if (!(p2 = search_term(cclp, ap)))
941             {
942                 ccl_rpn_delete(p1);
943                 return NULL;
944             }
945             p = ccl_rpn_node_create(CCL_RPN_AND);
946             p->u.p[0] = p1;
947             ccl_add_attr_numeric(p1, attset, CCL_BIB1_REL, 4);
948             p->u.p[1] = p2;
949             ccl_add_attr_numeric(p2, attset, CCL_BIB1_REL, 2);
950             return p;
951         }
952         else                       /* = term -    */
953         {
954             ccl_add_attr_numeric(p1, attset, CCL_BIB1_REL, 4);
955             return p1;
956         }
957     }
958     else if (rel == 3 &&
959              cclp->look_token->len == 1 &&
960              cclp->look_token->name[0] == '-')   /* = - term  ? */
961     {
962         ADVANCE;
963         if (!(p = search_term(cclp, ap)))
964             return NULL;
965         ccl_add_attr_numeric(p, attset, CCL_BIB1_REL, 2);
966         return p;
967     }
968     else
969     {
970         if (!(p = search_terms(cclp, ap)))
971             return NULL;
972         if (rel != 3 ||
973             !qual_val_type(ap, CCL_BIB1_REL, CCL_BIB1_REL_OMIT_EQUALS, 0))
974             ccl_add_attr_numeric(p, attset, CCL_BIB1_REL, rel);
975         return p;
976     }
977     return NULL;
978 }
979
980 static
981 struct ccl_rpn_node *qualifier_relation(CCL_parser cclp, ccl_qualifier_t *ap)
982 {
983     char *attset;
984
985     if (qual_val_type(ap, CCL_BIB1_REL, CCL_BIB1_REL_ORDER, &attset)
986         || qual_val_type(ap, CCL_BIB1_REL, CCL_BIB1_REL_PORDER, &attset))
987         return qualifiers_order(cclp, ap, attset);
988
989     /* unordered relation */
990     if (KIND != CCL_TOK_EQ)
991     {
992         cclp->error_code = CCL_ERR_EQ_EXPECTED;
993         return NULL;
994     }
995     ADVANCE;
996     return search_terms(cclp, ap);
997 }
998
999 /**
1000  * qualifier_list: Parse CCL qualifiers and search terms.
1001  * cclp:   CCL Parser
1002  * la:     Token pointer to RELATION token.
1003  * qa:     Qualifier attributes already applied.
1004  * return: pointer to node(s); NULL on error.
1005  */
1006 static struct ccl_rpn_node *qualifier_list(CCL_parser cclp,
1007                                            struct ccl_token *la,
1008                                            ccl_qualifier_t *qa)
1009 {
1010     struct ccl_token *lookahead = cclp->look_token;
1011     struct ccl_token *look_start = cclp->look_token;
1012     ccl_qualifier_t *ap;
1013     struct ccl_rpn_node *node = 0;
1014     const char **field_str;
1015     int no = 0;
1016     int seq = 0;
1017     int i;
1018     int mode_merge = 1;
1019 #if 0
1020     if (qa)
1021     {
1022         cclp->error_code = CCL_ERR_DOUBLE_QUAL;
1023         return NULL;
1024     }
1025 #endif
1026     for (lookahead = cclp->look_token; lookahead != la;
1027          lookahead=lookahead->next)
1028         no++;
1029     if (qa)
1030         for (i=0; qa[i]; i++)
1031             no++;
1032     ap = (ccl_qualifier_t *)xmalloc((no ? (no+1) : 2) * sizeof(*ap));
1033     ccl_assert(ap);
1034
1035     field_str = ccl_qual_search_special(cclp->bibset, "field");
1036     if (field_str)
1037     {
1038         if (!strcmp(field_str[0], "or"))
1039             mode_merge = 0;
1040         else if (!strcmp(field_str[0], "merge"))
1041             mode_merge = 1;
1042     }
1043     if (!mode_merge)
1044     {
1045         /* consider each field separately and OR */
1046         lookahead = look_start;
1047         while (lookahead != la)
1048         {
1049             ap[1] = 0;
1050             seq = 0;
1051             while ((ap[0] = ccl_qual_search(cclp, lookahead->name,
1052                                             lookahead->len, seq)) != 0)
1053             {
1054                 struct ccl_rpn_node *node_sub;
1055                 cclp->look_token = la;
1056
1057                 node_sub = qualifier_relation(cclp, ap);
1058                 if (!node_sub)
1059                 {
1060                     ccl_rpn_delete(node);
1061                     xfree(ap);
1062                     return 0;
1063                 }
1064                 node = ccl_rpn_node_mkbool(node, node_sub, CCL_RPN_OR);
1065                 seq++;
1066             }
1067             if (seq == 0)
1068             {
1069                 cclp->look_token = lookahead;
1070                 cclp->error_code = CCL_ERR_UNKNOWN_QUAL;
1071                 xfree(ap);
1072                 return NULL;
1073             }
1074             lookahead = lookahead->next;
1075             if (lookahead->kind == CCL_TOK_COMMA)
1076                 lookahead = lookahead->next;
1077         }
1078     }
1079     else
1080     {
1081         /* merge attributes from ALL fields - including inherited ones */
1082         while (1)
1083         {
1084             struct ccl_rpn_node *node_sub;
1085             int found = 0;
1086             lookahead = look_start;
1087             for (i = 0; lookahead != la; i++)
1088             {
1089                 ap[i] = ccl_qual_search(cclp, lookahead->name,
1090                                          lookahead->len, seq);
1091                 if (ap[i])
1092                     found++;
1093                 if (!ap[i] && seq > 0)
1094                     ap[i] = ccl_qual_search(cclp, lookahead->name,
1095                                              lookahead->len, 0);
1096                 if (!ap[i])
1097                 {
1098                     cclp->look_token = lookahead;
1099                     cclp->error_code = CCL_ERR_UNKNOWN_QUAL;
1100                     xfree(ap);
1101                     return NULL;
1102                 }
1103                 lookahead = lookahead->next;
1104                 if (lookahead->kind == CCL_TOK_COMMA)
1105                     lookahead = lookahead->next;
1106             }
1107             if (qa)
1108             {
1109                 ccl_qualifier_t *qa0 = qa;
1110
1111                 while (*qa0)
1112                     ap[i++] = *qa0++;
1113             }
1114             ap[i] = NULL;
1115
1116             if (!found)
1117                 break;
1118
1119             cclp->look_token = lookahead;
1120
1121             node_sub = qualifier_relation(cclp, ap);
1122             if (!node_sub)
1123             {
1124                 ccl_rpn_delete(node);
1125                 break;
1126             }
1127             node = ccl_rpn_node_mkbool(node, node_sub, CCL_RPN_OR);
1128             seq++;
1129         }
1130     }
1131     xfree(ap);
1132     return node;
1133 }
1134
1135
1136 /**
1137  * search_terms: Parse CCL search terms - including proximity.
1138  * cclp:   CCL Parser
1139  * qa:     Qualifier attributes already applied.
1140  * return: pointer to node(s); NULL on error.
1141  */
1142 static struct ccl_rpn_node *search_terms(CCL_parser cclp, ccl_qualifier_t *qa)
1143 {
1144     static int list[] = {
1145         CCL_TOK_TERM, CCL_TOK_COMMA,CCL_TOK_EQ,
1146         CCL_TOK_REL, CCL_TOK_SET, -1};
1147     struct ccl_rpn_node *p1, *p2, *pn;
1148     p1 = search_terms2(cclp, qa);
1149     if (!p1)
1150         return NULL;
1151     while (1)
1152     {
1153         if (KIND == CCL_TOK_PROX)
1154         {
1155             struct ccl_rpn_node *p_prox = 0;
1156             /* ! word order specified */
1157             /* % word order not specified */
1158             p_prox = ccl_rpn_node_create(CCL_RPN_TERM);
1159             p_prox->u.t.term = (char *) xmalloc(1 + cclp->look_token->len);
1160             memcpy(p_prox->u.t.term, cclp->look_token->name,
1161                    cclp->look_token->len);
1162             p_prox->u.t.term[cclp->look_token->len] = 0;
1163             p_prox->u.t.attr_list = 0;
1164
1165             ADVANCE;
1166             p2 = search_terms2(cclp, qa);
1167             if (!p2)
1168             {
1169                 ccl_rpn_delete(p1);
1170                 return NULL;
1171             }
1172             pn = ccl_rpn_node_create(CCL_RPN_PROX);
1173             pn->u.p[0] = p1;
1174             pn->u.p[1] = p2;
1175             pn->u.p[2] = p_prox;
1176             p1 = pn;
1177         }
1178         else if (is_term_ok(KIND, list))
1179         {
1180             p2 = search_terms2(cclp, qa);
1181             if (!p2)
1182             {
1183                 ccl_rpn_delete(p1);
1184                 return NULL;
1185             }
1186             pn = ccl_rpn_node_create(CCL_RPN_PROX);
1187             pn->u.p[0] = p1;
1188             pn->u.p[1] = p2;
1189             pn->u.p[2] = 0;
1190             p1 = pn;
1191         }
1192         else
1193             break;
1194     }
1195     return p1;
1196 }
1197
1198 /**
1199  * search_elements: Parse CCL search elements
1200  * cclp:   CCL Parser
1201  * qa:     Qualifier attributes already applied.
1202  * return: pointer to node(s); NULL on error.
1203  */
1204 static struct ccl_rpn_node *search_elements(CCL_parser cclp,
1205                                             ccl_qualifier_t *qa)
1206 {
1207     struct ccl_rpn_node *p1;
1208     struct ccl_token *lookahead;
1209     if (KIND == CCL_TOK_SET)
1210     {
1211         ADVANCE;
1212         if (KIND == CCL_TOK_EQ)
1213             ADVANCE;
1214         if (KIND != CCL_TOK_TERM)
1215         {
1216             cclp->error_code = CCL_ERR_SETNAME_EXPECTED;
1217             return NULL;
1218         }
1219         p1 = ccl_rpn_node_create(CCL_RPN_SET);
1220         p1->u.setname = copy_token_name(cclp->look_token);
1221         ADVANCE;
1222         return p1;
1223     }
1224     lookahead = cclp->look_token;
1225
1226     while (lookahead->kind==CCL_TOK_TERM)
1227     {
1228         lookahead = lookahead->next;
1229         if (lookahead->kind == CCL_TOK_REL || lookahead->kind == CCL_TOK_EQ)
1230             return qualifier_list(cclp, lookahead, qa);
1231         if (lookahead->kind != CCL_TOK_COMMA)
1232             break;
1233         lookahead = lookahead->next;
1234     }
1235     if (qa || lookahead->kind == CCL_TOK_LP)
1236         return search_terms(cclp, qa);
1237     else
1238     {
1239         ccl_qualifier_t qa[2];
1240         struct ccl_rpn_node *node = 0;
1241         int seq;
1242         lookahead = cclp->look_token;
1243
1244         qa[1] = 0;
1245         for(seq = 0; ;seq++)
1246         {
1247             struct ccl_rpn_node *node_sub;
1248             qa[0] = ccl_qual_search(cclp, "term", 4, seq);
1249             if (!qa[0])
1250                 break;
1251
1252             cclp->look_token = lookahead;
1253
1254             node_sub = search_terms(cclp, qa);
1255             if (!node_sub)
1256             {
1257                 ccl_rpn_delete(node);
1258                 return 0;
1259             }
1260             node = ccl_rpn_node_mkbool(node, node_sub, CCL_RPN_OR);
1261         }
1262         if (!node)
1263             node = search_terms(cclp, 0);
1264         return node;
1265     }
1266 }
1267
1268 /**
1269  * find_spec: Parse CCL find specification
1270  * cclp:   CCL Parser
1271  * qa:     Qualifier attributes already applied.
1272  * return: pointer to node(s); NULL on error.
1273  */
1274 static struct ccl_rpn_node *find_spec(CCL_parser cclp, ccl_qualifier_t *qa)
1275 {
1276     struct ccl_rpn_node *p1, *p2;
1277     if (!(p1 = search_elements(cclp, qa)))
1278         return NULL;
1279     while (1)
1280     {
1281         switch (KIND)
1282         {
1283         case CCL_TOK_AND:
1284             ADVANCE;
1285             p2 = search_elements(cclp, qa);
1286             if (!p2)
1287             {
1288                 ccl_rpn_delete(p1);
1289                 return NULL;
1290             }
1291             p1 = ccl_rpn_node_mkbool(p1, p2, CCL_RPN_AND);
1292             continue;
1293         case CCL_TOK_OR:
1294             ADVANCE;
1295             p2 = search_elements(cclp, qa);
1296             if (!p2)
1297             {
1298                 ccl_rpn_delete(p1);
1299                 return NULL;
1300             }
1301             p1 = ccl_rpn_node_mkbool(p1, p2, CCL_RPN_OR);
1302             continue;
1303         case CCL_TOK_NOT:
1304             ADVANCE;
1305             p2 = search_elements(cclp, qa);
1306             if (!p2)
1307             {
1308                 ccl_rpn_delete(p1);
1309                 return NULL;
1310             }
1311             p1 = ccl_rpn_node_mkbool(p1, p2, CCL_RPN_NOT);
1312             continue;
1313         }
1314         break;
1315     }
1316     return p1;
1317 }
1318
1319 struct ccl_rpn_node *ccl_parser_find_str(CCL_parser cclp, const char *str)
1320 {
1321     struct ccl_rpn_node *p;
1322     struct ccl_token *list = ccl_parser_tokenize(cclp, str);
1323     p = ccl_parser_find_token(cclp, list);
1324     ccl_token_del(list);
1325     return p;
1326 }
1327
1328 struct ccl_rpn_node *ccl_parser_find_token(CCL_parser cclp,
1329                                            struct ccl_token *list)
1330 {
1331     struct ccl_rpn_node *p;
1332
1333     cclp->look_token = list;
1334     p = find_spec(cclp, NULL);
1335     if (p && KIND != CCL_TOK_EOL)
1336     {
1337         if (KIND == CCL_TOK_RP)
1338             cclp->error_code = CCL_ERR_BAD_RP;
1339         else
1340             cclp->error_code = CCL_ERR_OP_EXPECTED;
1341         ccl_rpn_delete(p);
1342         p = NULL;
1343     }
1344     cclp->error_pos = cclp->look_token->name;
1345     if (p)
1346         cclp->error_code = CCL_ERR_OK;
1347     else
1348         cclp->error_code = cclp->error_code;
1349     return p;
1350 }
1351
1352 /**
1353  * ccl_find_str: Parse CCL find - string representation
1354  * bibset:  Bibset to be used for the parsing
1355  * str:     String to be parsed
1356  * error:   Pointer to integer. Holds error no. on completion.
1357  * pos:     Pointer to char position. Holds approximate error position.
1358  * return:  RPN tree on successful completion; NULL otherwise.
1359  */
1360 struct ccl_rpn_node *ccl_find_str(CCL_bibset bibset, const char *str,
1361                                   int *error, int *pos)
1362 {
1363     CCL_parser cclp = ccl_parser_create(bibset);
1364     struct ccl_token *list;
1365     struct ccl_rpn_node *p;
1366
1367     list = ccl_parser_tokenize(cclp, str);
1368     p = ccl_parser_find_token(cclp, list);
1369
1370     *error = cclp->error_code;
1371     if (*error)
1372         *pos = cclp->error_pos - str;
1373     ccl_parser_destroy(cclp);
1374     ccl_token_del(list);
1375     return p;
1376 }
1377
1378 /*
1379  * Local variables:
1380  * c-basic-offset: 4
1381  * c-file-style: "Stroustrup"
1382  * indent-tabs-mode: nil
1383  * End:
1384  * vim: shiftwidth=4 tabstop=8 expandtab
1385  */
1386