Minor change that avoids compiler warning.
[idzebra-moved-to-github.git] / recctrl / regxread.c
1 /*
2  * Copyright (C) 1994-1996, Index Data I/S 
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: regxread.c,v $
7  * Revision 1.10  1997-10-31 12:36:12  adam
8  * Minor change that avoids compiler warning.
9  *
10  * Revision 1.9  1997/09/29 09:02:49  adam
11  * Fixed small bug (introduced by previous commit).
12  *
13  * Revision 1.8  1997/09/17 12:19:22  adam
14  * Zebra version corresponds to YAZ version 1.4.
15  * Changed Zebra server so that it doesn't depend on global common_resource.
16  *
17  * Revision 1.7  1997/07/15 16:33:07  adam
18  * Check for zero length in execData.
19  *
20  * Revision 1.6  1997/02/24 10:41:51  adam
21  * Cleanup of code and commented out the "end element-end-record" code.
22  *
23  * Revision 1.5  1997/02/19 16:22:33  adam
24  * Fixed "end element" to terminate record in outer-most level.
25  *
26  * Revision 1.4  1997/02/12 20:42:58  adam
27  * Changed some log messages.
28  *
29  * Revision 1.3  1996/11/08 14:05:33  adam
30  * Bug fix: data1 node member u.tag.get_bytes weren't initialized.
31  *
32  * Revision 1.2  1996/10/29  14:02:09  adam
33  * Doesn't use the global data1_tabpath (from YAZ). Instead the function
34  * data1_get_tabpath is used.
35  *
36  * Revision 1.1  1996/10/11 10:57:30  adam
37  * New module recctrl. Used to manage records (extract/retrieval).
38  *
39  * Revision 1.24  1996/06/17 14:25:31  adam
40  * Removed LOG_DEBUG logs; can still be enabled by setting REGX_DEBUG.
41  *
42  * Revision 1.23  1996/06/04 10:19:00  adam
43  * Minor changes - removed include of ctype.h.
44  *
45  * Revision 1.22  1996/06/03  15:23:13  adam
46  * Bug fix: /../ BODY /../ - pattern didn't match EOF.
47  *
48  * Revision 1.21  1996/05/14  16:58:38  adam
49  * Minor change.
50  *
51  * Revision 1.20  1996/05/01  13:46:36  adam
52  * First work on multiple records in one file.
53  * New option, -offset, to the "unread" command in the filter module.
54  *
55  * Revision 1.19  1996/02/12  16:18:20  adam
56  * Yet another bug fix in implementation of unread command.
57  *
58  * Revision 1.18  1996/02/12  16:07:54  adam
59  * Bug fix in new unread command.
60  *
61  * Revision 1.17  1996/02/12  15:56:11  adam
62  * New code command: unread.
63  *
64  * Revision 1.16  1996/01/17  14:57:51  adam
65  * Prototype changed for reader functions in extract/retrieve. File
66  *  is identified by 'void *' instead of 'int.
67  *
68  * Revision 1.15  1996/01/08  19:15:47  adam
69  * New input filter that works!
70  *
71  * Revision 1.14  1996/01/08  09:10:38  adam
72  * Yet another complete rework on this module.
73  *
74  * Revision 1.13  1995/12/15  17:21:50  adam
75  * This version is able to set data.formatted_text in data1-nodes.
76  *
77  * Revision 1.12  1995/12/15  16:20:10  adam
78  * The filter files (*.flt) are read from the path given by data1_tabpath.
79  *
80  * Revision 1.11  1995/12/15  12:35:16  adam
81  * Better logging.
82  *
83  * Revision 1.10  1995/12/15  10:35:36  adam
84  * Misc. bug fixes.
85  *
86  * Revision 1.9  1995/12/14  16:38:48  adam
87  * Completely new attempt to make regular expression parsing.
88  *
89  * Revision 1.8  1995/12/13  17:16:59  adam
90  * Small changes.
91  *
92  * Revision 1.7  1995/12/13  16:51:58  adam
93  * Modified to set last_child in data1_nodes.
94  * Uses destroy handler to free up data text nodes.
95  *
96  * Revision 1.6  1995/12/13  13:45:37  quinn
97  * Changed data1 to use nmem.
98  *
99  * Revision 1.5  1995/12/11  09:12:52  adam
100  * The rec_get function returns NULL if record doesn't exist - will
101  * happen in the server if the result set records have been deleted since
102  * the creation of the set (i.e. the search).
103  * The server saves a result temporarily if it is 'volatile', i.e. the
104  * set is register dependent.
105  *
106  * Revision 1.4  1995/12/05  16:57:40  adam
107  * More work on regular patterns.
108  *
109  * Revision 1.3  1995/12/05  09:37:09  adam
110  * One malloc was renamed to xmalloc.
111  *
112  * Revision 1.2  1995/12/04  17:59:24  adam
113  * More work on regular expression conversion.
114  *
115  * Revision 1.1  1995/12/04  14:25:30  adam
116  * Started work on regular expression parsed input to structured records.
117  *
118  */
119 #include <stdio.h>
120 #include <assert.h>
121 #include <string.h>
122
123 #include <tpath.h>
124 #include <zebrautl.h>
125 #include <dfa.h>
126 #include "grsread.h"
127
128 #define REGX_DEBUG 0
129
130 #define F_WIN_EOF 2000000000
131 #define F_WIN_READ 1
132
133 #define REGX_EOF     0
134 #define REGX_PATTERN 1
135 #define REGX_BODY    2
136 #define REGX_BEGIN   3
137 #define REGX_END     4
138 #define REGX_CODE    5
139
140 struct regxCode {
141     char *str;
142 };
143
144 struct lexRuleAction {
145     int which; 
146     union {
147         struct {
148             struct DFA *dfa;    /* REGX_PATTERN */
149             int body;
150         } pattern;
151         struct regxCode *code;  /* REGX_CODE */
152     } u;
153     struct lexRuleAction *next;
154 };
155
156 struct lexRuleInfo {
157     int no;
158     struct lexRuleAction *actionList;
159 };
160
161 struct lexRule {
162     struct lexRuleInfo info;
163     struct lexRule *next;
164 };
165
166 struct lexTrans {
167     struct DFA *dfa;
168     struct lexRule *rules;
169     struct lexRuleInfo **fastRule;
170     int ruleNo;
171 };
172
173 struct lexSpec {
174     char *name;
175     struct lexTrans trans;
176     int lineNo;
177     NMEM m;
178     data1_handle dh;
179     void *f_win_fh;
180     void (*f_win_ef)(void *, off_t);
181
182     int f_win_start;
183     int f_win_end;
184     int f_win_size;
185     char *f_win_buf;
186     int (*f_win_rf)(void *, char *, size_t);
187     off_t (*f_win_sf)(void *, off_t);
188
189     struct lexRuleAction *beginActionList;
190     struct lexRuleAction *endActionList;
191 };
192
193
194 static char *f_win_get (struct lexSpec *spec, off_t start_pos, off_t end_pos,
195                         int *size)
196 {
197     int i, r, off;
198
199     if (start_pos < spec->f_win_start || start_pos >= spec->f_win_end)
200     {
201         (*spec->f_win_sf)(spec->f_win_fh, start_pos);
202         spec->f_win_start = start_pos;
203
204         if (!spec->f_win_buf)
205             spec->f_win_buf = xmalloc (spec->f_win_size);
206         *size = (*spec->f_win_rf)(spec->f_win_fh, spec->f_win_buf,
207                                   spec->f_win_size);
208         spec->f_win_end = spec->f_win_start + *size;
209
210         if (*size > end_pos - start_pos)
211             *size = end_pos - start_pos;
212         return spec->f_win_buf;
213     }
214     if (end_pos <= spec->f_win_end)
215     {
216         *size = end_pos - start_pos;
217         return spec->f_win_buf + (start_pos - spec->f_win_start);
218     }
219     off = start_pos - spec->f_win_start;
220     for (i = 0; i<spec->f_win_end - start_pos; i++)
221         spec->f_win_buf[i] = spec->f_win_buf[i + off];
222     r = (*spec->f_win_rf)(spec->f_win_fh,
223                           spec->f_win_buf + i,
224                           spec->f_win_size - i);
225     spec->f_win_start = start_pos;
226     spec->f_win_end += r;
227     *size = i + r;
228     if (*size > end_pos - start_pos)
229         *size = end_pos - start_pos;
230     return spec->f_win_buf;
231 }
232
233 static int f_win_advance (struct lexSpec *spec, int *pos)
234 {
235     int size;
236     char *buf;
237     
238     if (*pos >= spec->f_win_start && *pos < spec->f_win_end)
239         return spec->f_win_buf[(*pos)++ - spec->f_win_start];
240     if (*pos == F_WIN_EOF)
241         return 0;
242     buf = f_win_get (spec, *pos, *pos+1, &size);
243     if (size == 1)
244     {
245         (*pos)++;
246         return *buf;
247     }
248     *pos = F_WIN_EOF;
249     return 0;
250 }
251
252 static void regxCodeDel (struct regxCode **pp)
253 {
254     struct regxCode *p = *pp;
255     if (p)
256     {
257         xfree (p->str); 
258         xfree (p);
259         *pp = NULL;
260     }
261 }
262
263 static void regxCodeMk (struct regxCode **pp, const char *buf, int len)
264 {
265     struct regxCode *p;
266
267     p = xmalloc (sizeof(*p));
268     p->str = xmalloc (len+1);
269     memcpy (p->str, buf, len);
270     p->str[len] = '\0';
271     *pp = p;
272 }
273
274 static struct DFA *lexSpecDFA (void)
275 {
276     struct DFA *dfa;
277
278     dfa = dfa_init ();
279     dfa_parse_cmap_del (dfa, ' ');
280     dfa_parse_cmap_del (dfa, '\t');
281     dfa_parse_cmap_add (dfa, '/', 0);
282     return dfa;
283 }
284
285 static struct lexSpec *lexSpecMk (const char *name)
286 {
287     struct lexSpec *p;
288
289     p = xmalloc (sizeof(*p));
290     p->name = xmalloc (strlen(name)+1);
291     strcpy (p->name, name);
292     p->trans.dfa = lexSpecDFA ();
293     p->trans.rules = NULL;
294     p->trans.fastRule = NULL;
295     p->beginActionList = NULL;
296     p->endActionList = NULL;
297     p->f_win_buf = NULL;
298     return p;
299 }
300
301 static void actionListDel (struct lexRuleAction **rap)
302 {
303     struct lexRuleAction *ra1, *ra;
304
305     for (ra = *rap; ra; ra = ra1)
306     {
307         ra1 = ra->next;
308         switch (ra->which)
309         {
310         case REGX_PATTERN:
311             dfa_delete (&ra->u.pattern.dfa);
312             break;
313         case REGX_CODE:
314             regxCodeDel (&ra->u.code);
315             break;
316         }
317         xfree (ra);
318     }
319     *rap = NULL;
320 }
321
322 static void lexSpecDel (struct lexSpec **pp)
323 {
324     struct lexSpec *p;
325     struct lexRule *rp, *rp1;
326
327     assert (pp);
328     p = *pp;
329     if (!p)
330         return ;
331     dfa_delete (&p->trans.dfa);
332     xfree (p->name);
333     xfree (p->trans.fastRule);
334     for (rp = p->trans.rules; rp; rp = rp1)
335     {
336         actionListDel (&rp->info.actionList);
337         xfree (rp);
338     }
339     actionListDel (&p->beginActionList);
340     actionListDel (&p->endActionList);
341     xfree (p->f_win_buf);
342     xfree (p);
343     *pp = NULL;
344 }
345
346 static int readParseToken (const char **cpp, int *len)
347 {
348     const char *cp = *cpp;
349     char cmd[32];
350     int i, level;
351
352     while (*cp == ' ' || *cp == '\t' || *cp == '\n')
353         cp++;
354     switch (*cp)
355     {
356     case '\0':
357         return 0;
358     case '/':
359         *cpp = cp+1;
360         return REGX_PATTERN;
361     case '{':
362         *cpp = cp+1;
363         level = 1;
364         while (*++cp)
365         {
366             if (*cp == '{')
367                 level++;
368             else if (*cp == '}')
369             {
370                 level--;
371                 if (level == 0)
372                     break;
373             }
374         }
375         *len = cp - *cpp;
376         return REGX_CODE;
377     default:
378         i = 0;
379         while (1)
380         {
381             if (*cp >= 'a' && *cp <= 'z')
382                 cmd[i] = *cp;
383             else if (*cp >= 'A' && *cp <= 'Z')
384                 cmd[i] = *cp + 'a' - 'A';
385             else
386                 break;
387             if (i > sizeof(cmd)-2)
388                 break;
389             i++;
390             cp++;
391         }
392         cmd[i] = '\0';
393         if (i == 0)
394         {
395             logf (LOG_WARN, "bad character %d %c", *cp, *cp);
396             cp++;
397             while (*cp && *cp != ' ' && *cp != '\t' && *cp != '\n')
398                 cp++;
399             *cpp = cp;
400             return 0;
401         }
402         *cpp = cp;
403         if (!strcmp (cmd, "begin"))
404             return REGX_BEGIN;
405         else if (!strcmp (cmd, "end"))
406             return REGX_END;
407         else if (!strcmp (cmd, "body"))
408             return REGX_BODY;
409         else
410         {
411             logf (LOG_WARN, "bad command %s", cmd);
412             return 0;
413         }
414     }
415 }
416
417 static int actionListMk (struct lexSpec *spec, const char *s,
418                          struct lexRuleAction **ap)
419 {
420     int r, tok, len;
421     int bodyMark = 0;
422
423     while ((tok = readParseToken (&s, &len)))
424     {
425         switch (tok)
426         {
427         case REGX_BODY:
428             bodyMark = 1;
429             continue;
430         case REGX_CODE:
431             *ap = xmalloc (sizeof(**ap));
432             (*ap)->which = tok;
433             regxCodeMk (&(*ap)->u.code, s, len);
434             s += len+1;
435             break;
436         case REGX_PATTERN:
437             *ap = xmalloc (sizeof(**ap));
438             (*ap)->which = tok;
439             (*ap)->u.pattern.body = bodyMark;
440             bodyMark = 0;
441             (*ap)->u.pattern.dfa = lexSpecDFA ();
442             r = dfa_parse ((*ap)->u.pattern.dfa, &s);
443             if (r || *s != '/')
444             {
445                 xfree (*ap);
446                 *ap = NULL;
447                 logf (LOG_WARN, "regular expression error. r=%d", r);
448                 return -1;
449             }
450             dfa_mkstate ((*ap)->u.pattern.dfa);
451             s++;
452             break;
453         case REGX_BEGIN:
454             logf (LOG_WARN, "cannot use begin here");
455             continue;
456         case REGX_END:
457             *ap = xmalloc (sizeof(**ap));
458             (*ap)->which = tok;
459             break;
460         }
461         ap = &(*ap)->next;
462     }
463     *ap = NULL;
464     return 0;
465 }
466
467 int readOneSpec (struct lexSpec *spec, const char *s)
468 {
469     int tok, len;
470
471     tok = readParseToken (&s, &len);
472     if (tok == REGX_BEGIN)
473     {
474         actionListDel (&spec->beginActionList);
475         actionListMk (spec, s, &spec->beginActionList);
476     }
477     else if (tok == REGX_END)
478     {
479         actionListDel (&spec->endActionList);
480         actionListMk (spec, s, &spec->endActionList);
481     }
482     else if (tok == REGX_PATTERN)
483     {
484         int r;
485         struct lexRule *rp;
486         r = dfa_parse (spec->trans.dfa, &s);
487         if (r)
488         {
489             logf (LOG_WARN, "regular expression error. r=%d", r);
490             return -1;
491         }
492         if (*s != '/')
493         {
494             logf (LOG_WARN, "expects / at end of pattern. got %c", *s);
495             return -1;
496         }
497         s++;
498         rp = xmalloc (sizeof(*rp));
499         rp->info.no = spec->trans.ruleNo++;
500         rp->next = spec->trans.rules;
501         spec->trans.rules = rp;
502         actionListMk (spec, s, &rp->info.actionList);
503     }
504     return 0;
505 }
506
507 int readFileSpec (struct lexSpec *spec)
508 {
509     char *lineBuf;
510     int lineSize = 512;
511     struct lexRule *rp;
512     int c, i, errors = 0;
513     FILE *spec_inf;
514
515     lineBuf = xmalloc (1+lineSize);
516     logf (LOG_LOG, "reading regx filter %s.flt", spec->name);
517     sprintf (lineBuf, "%s.flt", spec->name);
518     if (!(spec_inf = yaz_path_fopen (data1_get_tabpath(spec->dh),
519                                      lineBuf, "r")))
520     {
521         logf (LOG_ERRNO|LOG_WARN, "cannot read spec file %s", spec->name);
522         xfree (lineBuf);
523         return -1;
524     }
525     spec->lineNo = 0;
526     spec->trans.ruleNo = 1;
527     c = getc (spec_inf);
528     while (c != EOF)
529     {
530         int off = 0;
531         if (c == '#' || c == '\n' || c == ' ' || c == '\t')
532         {
533             while (c != '\n' && c != EOF)
534                 c = getc (spec_inf);
535             spec->lineNo++;
536             if (c == '\n')
537                 c = getc (spec_inf);
538         }
539         else
540         {
541             int addLine = 0;
542
543             lineBuf[off++] = c;
544             while (1)
545             {
546                 int c1 = c;
547                 c = getc (spec_inf);
548                 if (c == EOF)
549                     break;
550                 if (c1 == '\n')
551                 {
552                     if (c != ' ' && c != '\t')
553                         break;
554                     addLine++;
555                 }
556                 lineBuf[off] = c;
557                 if (off < lineSize)
558                     off++;
559             }
560             lineBuf[off] = '\0';
561             readOneSpec (spec, lineBuf);
562             spec->lineNo += addLine;
563         }
564     }
565     fclose (spec_inf);
566     xfree (lineBuf);
567     spec->trans.fastRule = xmalloc (sizeof(*spec->trans.fastRule) *
568                                    spec->trans.ruleNo);
569     for (i = 0; i<spec->trans.ruleNo; i++)
570         spec->trans.fastRule[i] = NULL;
571     for (rp = spec->trans.rules; rp; rp = rp->next)
572         spec->trans.fastRule[rp->info.no] = &rp->info;
573     if (errors)
574         return -1;
575 #if 0
576     debug_dfa_trav = 1;
577     debug_dfa_tran = 1;
578     debug_dfa_followpos = 1;
579     dfa_verbose = 1;
580 #endif
581     dfa_mkstate (spec->trans.dfa);
582     return 0;
583 }
584
585 static struct lexSpec *curLexSpec = NULL;
586
587 static void destroy_data (struct data1_node *n)
588 {
589     assert (n->which == DATA1N_data);
590     xfree (n->u.data.data);
591 }
592
593 static void execData (struct lexSpec *spec,
594                       data1_node **d1_stack, int *d1_level,
595                       const char *ebuf, int elen, int formatted_text)
596 {
597     struct data1_node *res, *parent;
598
599     if (elen == 0) /* shouldn't happen, but it does! */
600         return ;
601 #if REGX_DEBUG
602     if (elen > 40)
603         logf (LOG_DEBUG, "execData %.15s ... %.*s", ebuf, 15, ebuf + elen-15);
604     else if (elen > 0)
605         logf (LOG_DEBUG, "execData %.*s", elen, ebuf);
606     else 
607         logf (LOG_DEBUG, "execData len=%d", elen);
608 #endif
609         
610     if (*d1_level <= 1)
611         return;
612
613     parent = d1_stack[*d1_level -1];
614     assert (parent);
615     if ((res=d1_stack[*d1_level]) && res->which == DATA1N_data)
616     {
617         if (elen + res->u.data.len <= DATA1_LOCALDATA)
618             memcpy (res->u.data.data + res->u.data.len, ebuf, elen);
619         else
620         {
621             char *nb = xmalloc (elen + res->u.data.len);
622             memcpy (nb, res->u.data.data, res->u.data.len);
623             memcpy (nb + res->u.data.len, ebuf, elen);
624             if (res->u.data.len > DATA1_LOCALDATA)
625                 xfree (res->u.data.data);
626             res->u.data.data = nb;
627             res->destroy = destroy_data;
628         }
629         res->u.data.len += elen;
630     }
631     else
632     {
633         res = data1_mk_node (spec->dh, spec->m);
634         res->parent = parent;
635         res->which = DATA1N_data;
636         res->u.data.what = DATA1I_text;
637         res->u.data.len = elen;
638         res->u.data.formatted_text = formatted_text;
639         if (elen > DATA1_LOCALDATA)
640         {
641             res->u.data.data = xmalloc (elen);
642             res->destroy = destroy_data;
643         }
644         else
645             res->u.data.data = res->lbuf;
646         memcpy (res->u.data.data, ebuf, elen);
647         res->root = parent->root;
648         
649         parent->num_children++;
650         parent->last_child = res;
651         if (d1_stack[*d1_level])
652             d1_stack[*d1_level]->next = res;
653         else
654             parent->child = res;
655         d1_stack[*d1_level] = res;
656     }
657 }
658
659 static void execDataP (struct lexSpec *spec,
660                        data1_node **d1_stack, int *d1_level,
661                        const char *ebuf, int elen, int formatted_text)
662 {
663     execData (spec, d1_stack, d1_level, ebuf, elen, formatted_text);
664 }
665
666
667 static void tagBegin (struct lexSpec *spec, 
668                       data1_node **d1_stack, int *d1_level,
669                       const char *tag, int len)
670 {
671     struct data1_node *parent = d1_stack[*d1_level -1];
672     data1_element *elem = NULL;
673     data1_node *partag = get_parent_tag(spec->dh, parent);
674     data1_node *res;
675     data1_element *e = NULL;
676     int localtag = 0;
677
678     if (*d1_level == 0)
679     {
680         logf (LOG_WARN, "in element begin. No record type defined");
681         return ;
682     }
683     
684     res = data1_mk_node (spec->dh, spec->m);
685     res->parent = parent;
686     res->which = DATA1N_tag;
687     res->u.tag.tag = res->lbuf;
688     res->u.tag.get_bytes = -1;
689
690     if (len >= DATA1_LOCALDATA)
691         len = DATA1_LOCALDATA-1;
692
693     memcpy (res->u.tag.tag, tag, len);
694     res->u.tag.tag[len] = '\0';
695    
696 #if REGX_DEBUG 
697     logf (LOG_DEBUG, "tag begin %s (%d)", res->u.tag.tag, *d1_level);
698 #endif
699     if (parent->which == DATA1N_variant)
700         return ;
701     if (partag)
702         if (!(e = partag->u.tag.element))
703             localtag = 1;
704     
705     elem = data1_getelementbytagname (spec->dh, d1_stack[0]->u.root.absyn,
706                                       e, res->u.tag.tag);
707     
708     res->u.tag.element = elem;
709     res->u.tag.node_selected = 0;
710     res->u.tag.make_variantlist = 0;
711     res->u.tag.no_data_requested = 0;
712     res->root = parent->root;
713     parent->num_children++;
714     parent->last_child = res;
715     if (d1_stack[*d1_level])
716         d1_stack[*d1_level]->next = res;
717     else
718         parent->child = res;
719     d1_stack[*d1_level] = res;
720     d1_stack[++(*d1_level)] = NULL;
721 }
722
723 static void tagEnd (struct lexSpec *spec, 
724                     data1_node **d1_stack, int *d1_level,
725                     const char *tag, int len)
726 {
727     while (*d1_level > 1)
728     {
729         (*d1_level)--;
730         if (!tag ||
731             (strlen(d1_stack[*d1_level]->u.tag.tag) == (size_t) len &&
732              !memcmp (d1_stack[*d1_level]->u.tag.tag, tag, len)))
733             break;
734     }
735 #if REGX_DEBUG
736     logf (LOG_DEBUG, "tag end (%d)", *d1_level);
737 #endif
738 }
739
740
741 static int tryMatch (struct lexSpec *spec, int *pptr, int *mptr,
742                      struct DFA *dfa)
743 {
744     struct DFA_state *state = dfa->states[0];
745     struct DFA_tran *t;
746     unsigned char c;
747     unsigned char c_prev = 0;
748     int ptr = *pptr;
749     int start_ptr = *pptr;
750     int last_rule = 0;
751     int last_ptr = 0;
752     int i;
753
754     while (1)
755     {
756         c = f_win_advance (spec, &ptr);
757         if (ptr == F_WIN_EOF)
758         {
759             if (last_rule)
760             {
761                 *mptr = start_ptr;
762                 *pptr = last_ptr;
763                 return 1;
764             }
765             break;
766         }
767         t = state->trans;
768         i = state->tran_no;
769         while (1)
770             if (--i < 0)
771             {
772                 if (last_rule)
773                 {
774                     *mptr = start_ptr;     /* match starts here */
775                     *pptr = last_ptr;      /* match end here (+1) */
776                     return 1;
777                 }
778                 state = dfa->states[0];
779                 start_ptr = ptr;
780                 c_prev = c;
781                 break;
782             }
783             else if (c >= t->ch[0] && c <= t->ch[1])
784             {
785                 state = dfa->states[t->to];
786                 if (state->rule_no)
787                 {
788                     if (c_prev == '\n')
789                     {
790                         last_rule = state->rule_no;
791                         last_ptr = ptr;
792                     }
793                     else
794                     {
795                         last_rule = state->rule_nno;
796                         last_ptr = ptr;
797                     }
798                 }
799                 break;
800             }
801             else
802                 t++;
803     }
804     return 0;
805 }
806
807 static int execTok (struct lexSpec *spec, const char **src,
808                     int arg_no, int *arg_start, int *arg_end,
809                     const char **tokBuf, int *tokLen)
810 {
811     const char *s = *src;
812
813     while (*s == ' ' || *s == '\t')
814         s++;
815     if (!*s)
816         return 0;
817     if (*s == '$' && s[1] >= '0' && s[1] <= '9')
818     {
819         int n = 0;
820         s++;
821         while (*s >= '0' && *s <= '9')
822             n = n*10 + (*s++ -'0');
823         if (arg_no == 0)
824         {
825             *tokBuf = "";
826             *tokLen = 0;
827         }
828         else
829         {
830             if (n >= arg_no)
831                 n = arg_no-1;
832             *tokBuf = f_win_get (spec, arg_start[n], arg_end[n], tokLen);
833         }
834     }
835     else if (*s == '\"')
836     {
837         *tokBuf = ++s;
838         while (*s && *s != '\"')
839             s++;
840         *tokLen = s - *tokBuf;
841         if (*s)
842             s++;
843         *src = s;
844     }
845     else if (*s == '\n' || *s == ';')
846     {
847         *src = s+1;
848         return 1;
849     }
850     else if (*s == '-')
851     {
852         *tokBuf = s++;
853         while (*s && *s != ' ' && *s != '\t' && *s != '\n' && *s != ';')
854             s++;
855         *tokLen = s - *tokBuf;
856         *src = s;
857         return 3;
858     }
859     else
860     {
861         *tokBuf = s++;
862         while (*s && *s != ' ' && *s != '\t' && *s != '\n' && *s != ';')
863             s++;
864         *tokLen = s - *tokBuf;
865     }
866     *src = s;
867     return 2;
868 }
869
870 static char *regxStrz (const char *src, int len)
871 {
872     static char str[64];
873     
874     if (len > 63)
875         len = 63;
876     memcpy (str, src, len);
877     str[len] = '\0';
878     return str;
879 }
880
881 static int execCode (struct lexSpec *spec,
882                      int arg_no, int *arg_start, int *arg_end, int *pptr,
883                      struct regxCode *code,
884                      data1_node **d1_stack, int *d1_level)
885 {
886     const char *s = code->str;
887     int cmd_len, r;
888     int returnCode = 1;
889     const char *cmd_str;
890     
891     r = execTok (spec, &s, arg_no, arg_start, arg_end, &cmd_str, &cmd_len);
892     while (r)
893     {
894         char *p;
895         
896         if (r == 1)
897         {
898             r = execTok (spec, &s, arg_no, arg_start, arg_end,
899                          &cmd_str, &cmd_len);
900             continue;
901         }
902         p = regxStrz (cmd_str, cmd_len);
903         if (!strcmp (p, "begin"))
904         {
905             r = execTok (spec, &s, arg_no, arg_start, arg_end,
906                          &cmd_str, &cmd_len);
907             if (r < 2)
908                 continue;
909             p = regxStrz (cmd_str, cmd_len);
910             if (!strcmp (p, "record"))
911             {
912                 r = execTok (spec, &s, arg_no, arg_start, arg_end,
913                              &cmd_str, &cmd_len);
914                 if (r < 2)
915                     continue;
916                 if (*d1_level == 0)
917                 {
918                     static char absynName[64];
919                     data1_absyn *absyn;
920
921                     if (cmd_len > 63)
922                         cmd_len = 63;
923                     memcpy (absynName, cmd_str, cmd_len);
924                     absynName[cmd_len] = '\0';
925
926 #if REGX_DEBUG
927                     logf (LOG_DEBUG, "begin record %s", absynName);
928 #endif
929                     if (!(absyn = data1_get_absyn (spec->dh, absynName)))
930                         logf (LOG_WARN, "Unknown tagset: %s", absynName);
931                     else
932                     {
933                         data1_node *res;
934
935                         res = data1_mk_node (spec->dh, spec->m);
936                         res->which = DATA1N_root;
937                         res->u.root.type = absynName;
938                         res->u.root.absyn = absyn;
939                         res->root = res;
940                         
941                         d1_stack[*d1_level] = res;
942                         d1_stack[++(*d1_level)] = NULL;
943                     }
944                 }
945                 r = execTok (spec, &s, arg_no, arg_start, arg_end,
946                              &cmd_str, &cmd_len);
947             }
948             else if (!strcmp (p, "element"))
949             {
950                 r = execTok (spec, &s, arg_no, arg_start, arg_end,
951                              &cmd_str, &cmd_len);
952                 if (r < 2)
953                     continue;
954                 tagBegin (spec, d1_stack, d1_level, cmd_str, cmd_len);
955                 r = execTok (spec, &s, arg_no, arg_start, arg_end,
956                              &cmd_str, &cmd_len);
957             }
958         }
959         else if (!strcmp (p, "end"))
960         {
961             r = execTok (spec, &s, arg_no, arg_start, arg_end,
962                          &cmd_str, &cmd_len);
963             if (r > 1)
964             {
965                 p = regxStrz (cmd_str, cmd_len);
966                 if (!strcmp (p, "record"))
967                 {
968                     *d1_level = 0;
969                     r = execTok (spec, &s, arg_no, arg_start, arg_end,
970                                  &cmd_str, &cmd_len);
971 #if REGX_DEBUG
972                     logf (LOG_DEBUG, "end record");
973 #endif
974                     returnCode = 0;
975                 }
976                 else if (!strcmp (p, "element"))
977                 {
978                     r = execTok (spec, &s, arg_no, arg_start, arg_end,
979                                  &cmd_str, &cmd_len);
980 #if 0
981                     if (*d1_level == 1)
982                     {
983                         *d1_level = 0;
984                         returnCode = 0;
985                     }
986 #endif
987                     if (r > 2)
988                     {
989                         tagEnd (spec, d1_stack, d1_level, cmd_str, cmd_len);
990                         r = execTok (spec, &s, arg_no, arg_start, arg_end,
991                                      &cmd_str, &cmd_len);
992                     }
993                     else
994                         tagEnd (spec, d1_stack, d1_level, NULL, 0);
995                 }
996                 else
997                     logf (LOG_WARN, "missing record/element/variant");
998             }
999             else
1000                 logf (LOG_WARN, "missing record/element/variant");
1001         }
1002         else if (!strcmp (p, "data"))
1003         {
1004             int textFlag = 0;
1005             int element_len;
1006             const char *element_str = NULL;
1007             
1008             while ((r = execTok (spec, &s, arg_no, arg_start, arg_end,
1009                                  &cmd_str, &cmd_len)) == 3)
1010             {
1011                 if (cmd_len==5 && !memcmp ("-text", cmd_str, cmd_len))
1012                     textFlag = 1;
1013                 else if (cmd_len==8 && !memcmp ("-element", cmd_str, cmd_len))
1014                 {
1015                     r = execTok (spec, &s, arg_no, arg_start, arg_end,
1016                                  &element_str, &element_len);
1017                     if (r < 2)
1018                         break;
1019                 }
1020                 else 
1021                     logf (LOG_WARN, "bad data option: %.*s",
1022                           cmd_len, cmd_str);
1023             }
1024             if (r != 2)
1025             {
1026                 logf (LOG_WARN, "missing data item after data");
1027                 continue;
1028             }
1029             if (element_str)
1030                 tagBegin (spec, d1_stack, d1_level, element_str, element_len);
1031             do
1032             {
1033                 execData (spec, d1_stack, d1_level, cmd_str, cmd_len,
1034                           textFlag);
1035                 r = execTok (spec, &s, arg_no, arg_start, arg_end,
1036                          &cmd_str, &cmd_len);
1037             } while (r > 1);
1038             if (element_str)
1039                 tagEnd (spec, d1_stack, d1_level, NULL, 0);
1040         }
1041         else if (!strcmp (p, "unread"))
1042         {
1043             int no, offset;
1044             r = execTok (spec, &s, arg_no, arg_start, arg_end,
1045                          &cmd_str, &cmd_len);
1046             if (r==3 && cmd_len == 7 && !memcmp ("-offset", cmd_str, cmd_len))
1047             {
1048                 r = execTok (spec, &s, arg_no, arg_start, arg_end,
1049                              &cmd_str, &cmd_len);
1050                 if (r < 2)
1051                 {
1052                     logf (LOG_WARN, "missing number after -offset");
1053                     continue;
1054                 }
1055                 p = regxStrz (cmd_str, cmd_len);
1056                 offset = atoi (p);
1057                 r = execTok (spec, &s, arg_no, arg_start, arg_end,
1058                              &cmd_str, &cmd_len);
1059             }
1060             else
1061                 offset = 0;
1062             if (r < 2)
1063             {
1064                 logf (LOG_WARN, "missing index after unread command");
1065                 continue;
1066             }
1067             if (cmd_len != 1 || *cmd_str < '0' || *cmd_str > '9')
1068             {
1069                 logf (LOG_WARN, "bad index after unread command");
1070                 continue;
1071             }
1072             else
1073             {
1074                 no = *cmd_str - '0';
1075                 if (no >= arg_no)
1076                     no = arg_no - 1;
1077                 *pptr = arg_start[no] + offset;
1078             }
1079             r = execTok (spec, &s, arg_no, arg_start, arg_end,
1080                          &cmd_str, &cmd_len);
1081         }
1082         else
1083         {
1084             logf (LOG_WARN, "unknown code command: %.*s", cmd_len, cmd_str);
1085             r = execTok (spec, &s, arg_no, arg_start, arg_end,
1086                          &cmd_str, &cmd_len);
1087             continue;
1088         }
1089         if (r > 1)
1090         {
1091             logf (LOG_WARN, "ignoring token %.*s", cmd_len, cmd_str);
1092             do {
1093                 r = execTok (spec, &s, arg_no, arg_start, arg_end, &cmd_str,
1094                              &cmd_len);
1095             } while (r > 1);
1096         }
1097     }
1098     return returnCode;
1099 }
1100
1101
1102 static int execAction (struct lexSpec *spec, struct lexRuleAction *ap,
1103                        data1_node **d1_stack, int *d1_level,
1104                        int start_ptr, int *pptr)
1105 {
1106     int sptr;
1107     int arg_start[20];
1108     int arg_end[20];
1109     int arg_no = 1;
1110
1111     arg_start[0] = start_ptr;
1112     arg_end[0] = *pptr;
1113
1114     while (ap)
1115     {
1116         switch (ap->which)
1117         {
1118         case REGX_PATTERN:
1119             if (ap->u.pattern.body)
1120             {
1121                 arg_start[arg_no] = *pptr;
1122                 if (!tryMatch (spec, pptr, &sptr, ap->u.pattern.dfa))
1123                 {
1124                     arg_end[arg_no] = F_WIN_EOF;
1125                     arg_no++;
1126                     arg_start[arg_no] = F_WIN_EOF;
1127                     arg_end[arg_no] = F_WIN_EOF;
1128 /* return 1*/
1129                 }
1130                 else
1131                 {
1132                     arg_end[arg_no] = sptr;
1133                     arg_no++;
1134                     arg_start[arg_no] = sptr;
1135                     arg_end[arg_no] = *pptr;
1136                 }
1137             }
1138             else
1139             {
1140                 arg_start[arg_no] = *pptr;
1141                 if (!tryMatch (spec, pptr, &sptr, ap->u.pattern.dfa))
1142                     return 1;
1143                 if (sptr != arg_start[arg_no])
1144                     return 1;
1145                 arg_end[arg_no] = *pptr;
1146             }
1147             arg_no++;
1148             break;
1149         case REGX_CODE:
1150             if (!execCode (spec, arg_no, arg_start, arg_end, pptr,
1151                            ap->u.code, d1_stack, d1_level))
1152                 return 0;
1153             break;
1154         case REGX_END:
1155             arg_start[arg_no] = *pptr;
1156             arg_end[arg_no] = F_WIN_EOF;
1157             arg_no++;
1158             *pptr = F_WIN_EOF;
1159         }
1160         ap = ap->next;
1161     }
1162     return 1;
1163 }
1164
1165 static int execRule (struct lexSpec *spec, struct lexTrans *trans,
1166                      data1_node **d1_stack, int *d1_level,
1167                      int ruleNo, int start_ptr, int *pptr)
1168 {
1169 #if REGX_DEBUG
1170     logf (LOG_DEBUG, "execRule %d", ruleNo);
1171 #endif
1172     return execAction (spec, trans->fastRule[ruleNo]->actionList,
1173                        d1_stack, d1_level, start_ptr, pptr);
1174 }
1175
1176 data1_node *lexNode (struct lexSpec *spec, struct lexTrans *trans,
1177                      data1_node **d1_stack, int *d1_level,
1178                      int *ptr)
1179 {
1180     struct DFA_state *state = trans->dfa->states[0];
1181     struct DFA_tran *t;
1182     unsigned char c;
1183     unsigned char c_prev = '\n';
1184     int i;
1185     int last_rule = 0;
1186     int last_ptr = *ptr;
1187     int start_ptr = *ptr;
1188     int skip_ptr = *ptr;
1189
1190     while (1)
1191     {
1192         c = f_win_advance (spec, ptr);
1193         if (*ptr == F_WIN_EOF)
1194         {
1195             if (last_rule)
1196             {
1197                 if (skip_ptr < start_ptr)
1198                 {
1199                     int size;
1200                     char *buf;
1201                     buf = f_win_get (spec, skip_ptr, start_ptr, &size);
1202                     execDataP (spec, d1_stack, d1_level, buf, size, 0);
1203                 }
1204                 *ptr = last_ptr;
1205                 if (!execRule (spec, trans, d1_stack, d1_level, last_rule,
1206                                start_ptr, ptr))
1207                     break;
1208                 skip_ptr = *ptr;
1209                 last_rule = 0;
1210             }
1211             else if (skip_ptr < *ptr)
1212             {
1213                 int size;
1214                 char *buf;
1215                 buf = f_win_get (spec, skip_ptr, *ptr, &size);
1216                 execDataP (spec, d1_stack, d1_level, buf, size, 0);
1217             }
1218             if (*ptr == F_WIN_EOF)
1219                 break;
1220         }
1221         t = state->trans;
1222         i = state->tran_no;
1223         while (1)
1224             if (--i < 0)
1225             {   /* no transition for character c ... */
1226                 if (last_rule)
1227                 {
1228                     if (skip_ptr < start_ptr)
1229                     {
1230                         int size;
1231                         char *buf;
1232                         buf = f_win_get (spec, skip_ptr, start_ptr, &size);
1233                         execDataP (spec, d1_stack, d1_level, buf, size, 0);
1234                     }
1235                     *ptr = last_ptr;
1236                     if (!execRule (spec, trans, d1_stack, d1_level, last_rule,
1237                                    start_ptr, ptr))
1238                     {
1239                         if (spec->f_win_ef && *ptr != F_WIN_EOF)
1240                         {
1241 #if REGX_DEBUG
1242                             logf (LOG_DEBUG, "regx: endf ptr=%d", *ptr);
1243 #endif
1244                             (*spec->f_win_ef)(spec->f_win_fh, *ptr);
1245                         }
1246                         return NULL;
1247                     }
1248                     skip_ptr = *ptr;
1249                     last_rule = 0;
1250                     start_ptr = *ptr;
1251                     if (start_ptr > 0)
1252                     {
1253                         --start_ptr;
1254                         c_prev = f_win_advance (spec, &start_ptr);
1255                     }
1256                 }
1257                 else
1258                 {
1259                     c_prev = f_win_advance (spec, &start_ptr);
1260                     *ptr = start_ptr;
1261                 }
1262                 state = trans->dfa->states[0];
1263                 break;
1264             }
1265             else if (c >= t->ch[0] && c <= t->ch[1])
1266             {   /* transition ... */
1267                 state = trans->dfa->states[t->to];
1268                 if (state->rule_no)
1269                 {
1270                     if (c_prev == '\n')
1271                     {
1272                         last_rule = state->rule_no;
1273                         last_ptr = *ptr;
1274                     } 
1275                     else if (state->rule_nno)
1276                     {
1277                         last_rule = state->rule_nno;
1278                         last_ptr = *ptr;
1279                     }
1280                 }
1281                 break;
1282             }
1283             else
1284                 t++;
1285     }
1286     return NULL;
1287 }
1288
1289 static data1_node *lexRoot (struct lexSpec *spec, off_t offset)
1290 {
1291     data1_node *d1_stack[512];
1292     int d1_level = 0;
1293     int ptr = offset;
1294
1295     d1_stack[d1_level] = NULL;
1296     if (spec->beginActionList)
1297         execAction (spec, spec->beginActionList,
1298                     d1_stack, &d1_level, 0, &ptr);
1299     lexNode (spec, &spec->trans, d1_stack, &d1_level, &ptr);
1300     if (spec->endActionList)
1301         execAction (spec, spec->endActionList,
1302                     d1_stack, &d1_level, ptr, &ptr);
1303     return *d1_stack;
1304 }
1305
1306 data1_node *grs_read_regx (struct grs_read_info *p)
1307 {
1308     int res;
1309     data1_node *n;
1310
1311 #if REGX_DEBUG
1312     logf (LOG_DEBUG, "grs_read_regx");
1313 #endif
1314     if (!curLexSpec || strcmp (curLexSpec->name, p->type))
1315     {
1316         if (curLexSpec)
1317             lexSpecDel (&curLexSpec);
1318         curLexSpec = lexSpecMk (p->type);
1319         curLexSpec->dh = p->dh;
1320         res = readFileSpec (curLexSpec);
1321         if (res)
1322         {
1323             lexSpecDel (&curLexSpec);
1324             return NULL;
1325         }
1326     }
1327     if (!p->offset)
1328     {
1329         curLexSpec->f_win_start = 0;
1330         curLexSpec->f_win_end = 0;
1331         curLexSpec->f_win_rf = p->readf;
1332         curLexSpec->f_win_sf = p->seekf;
1333         curLexSpec->f_win_fh = p->fh;
1334         curLexSpec->f_win_ef = p->endf;
1335         curLexSpec->f_win_size = 500000;
1336     }
1337     curLexSpec->m = p->mem;
1338     n = lexRoot (curLexSpec, p->offset);
1339     return n;
1340 }