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