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