Minor changes in Debug log messages
[idzebra-moved-to-github.git] / recctrl / regxread.c
1 /* $Id: regxread.c,v 1.47 2003-04-24 19:34:20 adam Exp $
2    Copyright (C) 1995,1996,1997,1998,1999,2000,2001,2002,2003
3    Index Data Aps
4
5 This file is part of the Zebra server.
6
7 Zebra is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 Zebra is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Zebra; see the file LICENSE.zebra.  If not, write to the
19 Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.
21 */
22
23
24 #include <stdio.h>
25 #include <assert.h>
26 #include <string.h>
27 #include <ctype.h>
28
29 #include <yaz/tpath.h>
30 #include <zebrautl.h>
31 #include <dfa.h>
32 #include "grsread.h"
33
34 #if HAVE_TCL_H
35 #include <tcl.h>
36
37 #if MAJOR_VERSION >= 8
38 #define HAVE_TCL_OBJECTS
39 #endif
40 #endif
41
42 #define REGX_DEBUG 0
43
44 #define F_WIN_EOF 2000000000
45 #define F_WIN_READ 1
46
47 #define REGX_EOF     0
48 #define REGX_PATTERN 1
49 #define REGX_BODY    2
50 #define REGX_BEGIN   3
51 #define REGX_END     4
52 #define REGX_CODE    5
53 #define REGX_CONTEXT 6
54 #define REGX_INIT    7
55
56 struct regxCode {
57     char *str;
58 #if HAVE_TCL_OBJECTS
59     Tcl_Obj *tcl_obj;
60 #endif
61 };
62
63 struct lexRuleAction {
64     int which; 
65     union {
66         struct {
67             struct DFA *dfa;    /* REGX_PATTERN */
68             int body;
69         } pattern;
70         struct regxCode *code;  /* REGX_CODE */
71     } u;
72     struct lexRuleAction *next;
73 };
74
75 struct lexRuleInfo {
76     int no;
77     struct lexRuleAction *actionList;
78 };
79
80 struct lexRule {
81     struct lexRuleInfo info;
82     struct lexRule *next;
83 };
84
85 struct lexContext {
86     char *name;
87     struct DFA *dfa;
88     struct lexRule *rules;
89     struct lexRuleInfo **fastRule;
90     int ruleNo;
91     int initFlag;
92
93     struct lexRuleAction *beginActionList;
94     struct lexRuleAction *endActionList;
95     struct lexRuleAction *initActionList;
96     struct lexContext *next;
97 };
98
99 struct lexConcatBuf {
100     int max;
101     char *buf;
102 };
103
104 struct lexSpec {
105     char *name;
106     struct lexContext *context;
107
108     struct lexContext **context_stack;
109     int context_stack_size;
110     int context_stack_top;
111
112     int lineNo;
113     NMEM m;
114     data1_handle dh;
115 #if HAVE_TCL_H
116     Tcl_Interp *tcl_interp;
117 #endif
118     void *f_win_fh;
119     void (*f_win_ef)(void *, off_t);
120
121     int f_win_start;      /* first byte of buffer is this file offset */
122     int f_win_end;        /* last byte of buffer is this offset - 1 */
123     int f_win_size;       /* size of buffer */
124     char *f_win_buf;      /* buffer itself */
125     int (*f_win_rf)(void *, char *, size_t);
126     off_t (*f_win_sf)(void *, off_t);
127
128     struct lexConcatBuf *concatBuf;
129     int maxLevel;
130     data1_node **d1_stack;
131     int d1_level;
132     int stop_flag;
133     
134     int *arg_start;
135     int *arg_end;
136     int arg_no;
137     int ptr;
138 };
139
140 struct lexSpecs {
141     struct lexSpec *spec;
142 };
143
144 static char *f_win_get (struct lexSpec *spec, off_t start_pos, off_t end_pos,
145                         int *size)
146 {
147     int i, r, off = start_pos - spec->f_win_start;
148
149     if (off >= 0 && end_pos <= spec->f_win_end)
150     {
151         *size = end_pos - start_pos;
152         return spec->f_win_buf + off;
153     }
154     if (off < 0 || start_pos >= spec->f_win_end)
155     {
156         (*spec->f_win_sf)(spec->f_win_fh, start_pos);
157         spec->f_win_start = start_pos;
158
159         if (!spec->f_win_buf)
160             spec->f_win_buf = (char *) xmalloc (spec->f_win_size);
161         *size = (*spec->f_win_rf)(spec->f_win_fh, spec->f_win_buf,
162                                   spec->f_win_size);
163         spec->f_win_end = spec->f_win_start + *size;
164
165         if (*size > end_pos - start_pos)
166             *size = end_pos - start_pos;
167         return spec->f_win_buf;
168     }
169     for (i = 0; i<spec->f_win_end - start_pos; i++)
170         spec->f_win_buf[i] = spec->f_win_buf[i + off];
171     r = (*spec->f_win_rf)(spec->f_win_fh,
172                           spec->f_win_buf + i,
173                           spec->f_win_size - i);
174     spec->f_win_start = start_pos;
175     spec->f_win_end += r;
176     *size = i + r;
177     if (*size > end_pos - start_pos)
178         *size = end_pos - start_pos;
179     return spec->f_win_buf;
180 }
181
182 static int f_win_advance (struct lexSpec *spec, int *pos)
183 {
184     int size;
185     char *buf;
186     
187     if (*pos >= spec->f_win_start && *pos < spec->f_win_end)
188         return spec->f_win_buf[(*pos)++ - spec->f_win_start];
189     if (*pos == F_WIN_EOF)
190         return 0;
191     buf = f_win_get (spec, *pos, *pos+1, &size);
192     if (size == 1)
193     {
194         (*pos)++;
195         return *buf;
196     }
197     *pos = F_WIN_EOF;
198     return 0;
199 }
200
201 static void regxCodeDel (struct regxCode **pp)
202 {
203     struct regxCode *p = *pp;
204     if (p)
205     {
206 #if HAVE_TCL_OBJECTS
207         if (p->tcl_obj)
208             Tcl_DecrRefCount (p->tcl_obj);
209 #endif
210         xfree (p->str); 
211         xfree (p);
212         *pp = NULL;
213     }
214 }
215
216 static void regxCodeMk (struct regxCode **pp, const char *buf, int len)
217 {
218     struct regxCode *p;
219
220     p = (struct regxCode *) xmalloc (sizeof(*p));
221     p->str = (char *) xmalloc (len+1);
222     memcpy (p->str, buf, len);
223     p->str[len] = '\0';
224 #if HAVE_TCL_OBJECTS
225     p->tcl_obj = Tcl_NewStringObj ((char *) buf, len);
226     if (p->tcl_obj)
227         Tcl_IncrRefCount (p->tcl_obj);
228 #endif
229     *pp = p;
230 }
231
232 static struct DFA *lexSpecDFA (void)
233 {
234     struct DFA *dfa;
235
236     dfa = dfa_init ();
237     dfa_parse_cmap_del (dfa, ' ');
238     dfa_parse_cmap_del (dfa, '\t');
239     dfa_parse_cmap_add (dfa, '/', 0);
240     return dfa;
241 }
242
243 static void actionListDel (struct lexRuleAction **rap)
244 {
245     struct lexRuleAction *ra1, *ra;
246
247     for (ra = *rap; ra; ra = ra1)
248     {
249         ra1 = ra->next;
250         switch (ra->which)
251         {
252         case REGX_PATTERN:
253             dfa_delete (&ra->u.pattern.dfa);
254             break;
255         case REGX_CODE:
256             regxCodeDel (&ra->u.code);
257             break;
258         }
259         xfree (ra);
260     }
261     *rap = NULL;
262 }
263
264 static struct lexContext *lexContextCreate (const char *name)
265 {
266     struct lexContext *p = (struct lexContext *) xmalloc (sizeof(*p));
267
268     p->name = xstrdup (name);
269     p->ruleNo = 1;
270     p->initFlag = 0;
271     p->dfa = lexSpecDFA ();
272     p->rules = NULL;
273     p->fastRule = NULL;
274     p->beginActionList = NULL;
275     p->endActionList = NULL;
276     p->initActionList = NULL;
277     p->next = NULL;
278     return p;
279 }
280
281 static void lexContextDestroy (struct lexContext *p)
282 {
283     struct lexRule *rp, *rp1;
284
285     dfa_delete (&p->dfa);
286     xfree (p->fastRule);
287     for (rp = p->rules; rp; rp = rp1)
288     {
289         rp1 = rp->next;
290         actionListDel (&rp->info.actionList);
291         xfree (rp);
292     }
293     actionListDel (&p->beginActionList);
294     actionListDel (&p->endActionList);
295     actionListDel (&p->initActionList);
296     xfree (p->name);
297     xfree (p);
298 }
299
300 static struct lexSpec *lexSpecCreate (const char *name, data1_handle dh)
301 {
302     struct lexSpec *p;
303     int i;
304     
305     p = (struct lexSpec *) xmalloc (sizeof(*p));
306     p->name = (char *) xmalloc (strlen(name)+1);
307     strcpy (p->name, name);
308
309 #if HAVE_TCL_H
310     p->tcl_interp = 0;
311 #endif
312     p->dh = dh;
313     p->context = NULL;
314     p->context_stack_size = 100;
315     p->context_stack = (struct lexContext **)
316         xmalloc (sizeof(*p->context_stack) * p->context_stack_size);
317     p->f_win_buf = NULL;
318
319     p->maxLevel = 128;
320     p->concatBuf = (struct lexConcatBuf *)
321         xmalloc (sizeof(*p->concatBuf) * p->maxLevel);
322     for (i = 0; i < p->maxLevel; i++)
323     {
324         p->concatBuf[i].max = 0;
325         p->concatBuf[i].buf = 0;
326     }
327     p->d1_stack = (data1_node **) xmalloc (sizeof(*p->d1_stack) * p->maxLevel);
328     p->d1_level = 0;
329     return p;
330 }
331
332 static void lexSpecDestroy (struct lexSpec **pp)
333 {
334     struct lexSpec *p;
335     struct lexContext *lt;
336     int i;
337
338     assert (pp);
339     p = *pp;
340     if (!p)
341         return ;
342
343     for (i = 0; i < p->maxLevel; i++)
344         xfree (p->concatBuf[i].buf);
345     xfree (p->concatBuf);
346
347     lt = p->context;
348     while (lt)
349     {
350         struct lexContext *lt_next = lt->next;
351         lexContextDestroy (lt);
352         lt = lt_next;
353     }
354 #if HAVE_TCL_OBJECTS
355     if (p->tcl_interp)
356         Tcl_DeleteInterp (p->tcl_interp);
357 #endif
358     xfree (p->name);
359     xfree (p->f_win_buf);
360     xfree (p->context_stack);
361     xfree (p->d1_stack);
362     xfree (p);
363     *pp = NULL;
364 }
365
366 static int readParseToken (const char **cpp, int *len)
367 {
368     const char *cp = *cpp;
369     char cmd[32];
370     int i, level;
371
372     while (*cp == ' ' || *cp == '\t' || *cp == '\n' || *cp == '\r')
373         cp++;
374     switch (*cp)
375     {
376     case '\0':
377         return 0;
378     case '/':
379         *cpp = cp+1;
380         return REGX_PATTERN;
381     case '{':
382         *cpp = cp+1;
383         level = 1;
384         while (*++cp)
385         {
386             if (*cp == '{')
387                 level++;
388             else if (*cp == '}')
389             {
390                 level--;
391                 if (level == 0)
392                     break;
393             }
394         }
395         *len = cp - *cpp;
396         return REGX_CODE;
397     default:
398         i = 0;
399         while (1)
400         {
401             if (*cp >= 'a' && *cp <= 'z')
402                 cmd[i] = *cp;
403             else if (*cp >= 'A' && *cp <= 'Z')
404                 cmd[i] = *cp + 'a' - 'A';
405             else
406                 break;
407             if (i < (int) sizeof(cmd)-2)
408                 i++;
409             cp++;
410         }
411         cmd[i] = '\0';
412         if (i == 0)
413         {
414             logf (LOG_WARN, "bad character %d %c", *cp, *cp);
415             cp++;
416             while (*cp && *cp != ' ' && *cp != '\t' &&
417                    *cp != '\n' && *cp != '\r')
418                 cp++;
419             *cpp = cp;
420             return 0;
421         }
422         *cpp = cp;
423         if (!strcmp (cmd, "begin"))
424             return REGX_BEGIN;
425         else if (!strcmp (cmd, "end"))
426             return REGX_END;
427         else if (!strcmp (cmd, "body"))
428             return REGX_BODY;
429         else if (!strcmp (cmd, "context"))
430             return REGX_CONTEXT;
431         else if (!strcmp (cmd, "init"))
432             return REGX_INIT;
433         else
434         {
435             logf (LOG_WARN, "bad command %s", cmd);
436             return 0;
437         }
438     }
439 }
440
441 static int actionListMk (struct lexSpec *spec, const char *s,
442                          struct lexRuleAction **ap)
443 {
444     int r, tok, len;
445     int bodyMark = 0;
446     const char *s0;
447
448     while ((tok = readParseToken (&s, &len)))
449     {
450         switch (tok)
451         {
452         case REGX_BODY:
453             bodyMark = 1;
454             continue;
455         case REGX_CODE:
456             *ap = (struct lexRuleAction *) xmalloc (sizeof(**ap));
457             (*ap)->which = tok;
458             regxCodeMk (&(*ap)->u.code, s, len);
459             s += len+1;
460             break;
461         case REGX_PATTERN:
462             *ap = (struct lexRuleAction *) xmalloc (sizeof(**ap));
463             (*ap)->which = tok;
464             (*ap)->u.pattern.body = bodyMark;
465             bodyMark = 0;
466             (*ap)->u.pattern.dfa = lexSpecDFA ();
467             s0 = s;
468             r = dfa_parse ((*ap)->u.pattern.dfa, &s);
469             if (r || *s != '/')
470             {
471                 xfree (*ap);
472                 *ap = NULL;
473                 logf (LOG_WARN, "regular expression error '%.*s'", s-s0, s0);
474                 return -1;
475             }
476             dfa_mkstate ((*ap)->u.pattern.dfa);
477             s++;
478             break;
479         case REGX_BEGIN:
480             logf (LOG_WARN, "cannot use BEGIN here");
481             continue;
482         case REGX_INIT:
483             logf (LOG_WARN, "cannot use INIT here");
484             continue;
485         case REGX_END:
486             *ap = (struct lexRuleAction *) xmalloc (sizeof(**ap));
487             (*ap)->which = tok;
488             break;
489         }
490         ap = &(*ap)->next;
491     }
492     *ap = NULL;
493     return 0;
494 }
495
496 int readOneSpec (struct lexSpec *spec, const char *s)
497 {
498     int len, r, tok;
499     struct lexRule *rp;
500     struct lexContext *lc;
501
502     tok = readParseToken (&s, &len);
503     if (tok == REGX_CONTEXT)
504     {
505         char context_name[32];
506         tok = readParseToken (&s, &len);
507         if (tok != REGX_CODE)
508         {
509             logf (LOG_WARN, "missing name after CONTEXT keyword");
510             return 0;
511         }
512         if (len > 31)
513             len = 31;
514         memcpy (context_name, s, len);
515         context_name[len] = '\0';
516         lc = lexContextCreate (context_name);
517         lc->next = spec->context;
518         spec->context = lc;
519         return 0;
520     }
521     if (!spec->context)
522         spec->context = lexContextCreate ("main");
523        
524     switch (tok)
525     {
526     case REGX_BEGIN:
527         actionListDel (&spec->context->beginActionList);
528         actionListMk (spec, s, &spec->context->beginActionList);
529         break;
530     case REGX_END:
531         actionListDel (&spec->context->endActionList);
532         actionListMk (spec, s, &spec->context->endActionList);
533         break;
534     case REGX_INIT:
535         actionListDel (&spec->context->initActionList);
536         actionListMk (spec, s, &spec->context->initActionList);
537         break;
538     case REGX_PATTERN:
539 #if REGX_DEBUG
540         logf (LOG_LOG, "rule %d %s", spec->context->ruleNo, s);
541 #endif
542         r = dfa_parse (spec->context->dfa, &s);
543         if (r)
544         {
545             logf (LOG_WARN, "regular expression error. r=%d", r);
546             return -1;
547         }
548         if (*s != '/')
549         {
550             logf (LOG_WARN, "expects / at end of pattern. got %c", *s);
551             return -1;
552         }
553         s++;
554         rp = (struct lexRule *) xmalloc (sizeof(*rp));
555         rp->info.no = spec->context->ruleNo++;
556         rp->next = spec->context->rules;
557         spec->context->rules = rp;
558         actionListMk (spec, s, &rp->info.actionList);
559     }
560     return 0;
561 }
562
563 int readFileSpec (struct lexSpec *spec)
564 {
565     struct lexContext *lc;
566     int c, i, errors = 0;
567     FILE *spec_inf = 0;
568     WRBUF lineBuf;
569     char fname[256];
570
571 #if HAVE_TCL_H
572     if (spec->tcl_interp)
573     {
574         sprintf (fname, "%s.tflt", spec->name);
575         spec_inf = data1_path_fopen (spec->dh, fname, "r");
576     }
577 #endif
578     if (!spec_inf)
579     {
580         sprintf (fname, "%s.flt", spec->name);
581         spec_inf = data1_path_fopen (spec->dh, fname, "r");
582     }
583     if (!spec_inf)
584     {
585         logf (LOG_ERRNO|LOG_WARN, "cannot read spec file %s", spec->name);
586         return -1;
587     }
588     logf (LOG_LOG, "reading regx filter %s", fname);
589 #if HAVE_TCL_H
590     if (spec->tcl_interp)
591         logf (LOG_LOG, "Tcl enabled");
592 #endif
593     lineBuf = wrbuf_alloc();
594     spec->lineNo = 0;
595     c = getc (spec_inf);
596     while (c != EOF)
597     {
598         wrbuf_rewind (lineBuf);
599         if (c == '#' || c == '\n' || c == ' ' || c == '\t' || c == '\r')
600         {
601             while (c != '\n' && c != EOF)
602                 c = getc (spec_inf);
603             spec->lineNo++;
604             if (c == '\n')
605                 c = getc (spec_inf);
606         }
607         else
608         {
609             int addLine = 0;
610             
611             while (1)
612             {
613                 int c1 = c;
614                 wrbuf_putc(lineBuf, c);
615                 c = getc (spec_inf);
616                 while (c == '\r')
617                     c = getc (spec_inf);
618                 if (c == EOF)
619                     break;
620                 if (c1 == '\n')
621                 {
622                     if (c != ' ' && c != '\t')
623                         break;
624                     addLine++;
625                 }
626             }
627             wrbuf_putc(lineBuf, '\0');
628             readOneSpec (spec, wrbuf_buf(lineBuf));
629             spec->lineNo += addLine;
630         }
631     }
632     fclose (spec_inf);
633     wrbuf_free(lineBuf, 1);
634
635 #if 0
636     debug_dfa_trav = 1;
637     debug_dfa_tran = 1;
638     debug_dfa_followpos = 1;
639     dfa_verbose = 1;
640 #endif
641     for (lc = spec->context; lc; lc = lc->next)
642     {
643         struct lexRule *rp;
644         lc->fastRule = (struct lexRuleInfo **)
645             xmalloc (sizeof(*lc->fastRule) * lc->ruleNo);
646         for (i = 0; i < lc->ruleNo; i++)
647             lc->fastRule[i] = NULL;
648         for (rp = lc->rules; rp; rp = rp->next)
649             lc->fastRule[rp->info.no] = &rp->info;
650         dfa_mkstate (lc->dfa);
651     }
652     if (errors)
653         return -1;
654     
655     return 0;
656 }
657
658 #if 0
659 static struct lexSpec *curLexSpec = NULL;
660 #endif
661
662 static void execData (struct lexSpec *spec,
663                       const char *ebuf, int elen, int formatted_text)
664 {
665     struct data1_node *res, *parent;
666     int org_len;
667
668     if (elen == 0) /* shouldn't happen, but it does! */
669         return ;
670 #if REGX_DEBUG
671     if (elen > 40)
672         logf (LOG_LOG, "data(%d bytes) %.15s ... %.*s", elen,
673               ebuf, 15, ebuf + elen-15);
674     else if (elen == 1 && ebuf[0] == '\n')
675     {
676         logf (LOG_LOG, "data(new line)");
677         assert(0);
678     }
679     else if (elen > 0)
680         logf (LOG_LOG, "data(%d bytes) %.*s", elen, elen, ebuf);
681     else 
682         logf (LOG_LOG, "data(%d bytes)", elen);
683 #endif
684         
685     if (spec->d1_level <= 1)
686         return;
687
688     parent = spec->d1_stack[spec->d1_level -1];
689     assert (parent);
690
691     if ((res = spec->d1_stack[spec->d1_level]) && res->which == DATA1N_data)
692         org_len = res->u.data.len;
693     else
694     {
695         org_len = 0;
696
697         res = data1_mk_node2 (spec->dh, spec->m, DATA1N_data, parent);
698         res->u.data.what = DATA1I_text;
699         res->u.data.len = 0;
700         res->u.data.formatted_text = formatted_text;
701         res->u.data.data = 0;
702         
703         if (spec->d1_stack[spec->d1_level])
704             spec->d1_stack[spec->d1_level]->next = res;
705         spec->d1_stack[spec->d1_level] = res;
706     }
707     if (org_len + elen >= spec->concatBuf[spec->d1_level].max)
708     {
709         char *old_buf, *new_buf;
710
711         spec->concatBuf[spec->d1_level].max = org_len + elen + 256;
712         new_buf = (char *) xmalloc (spec->concatBuf[spec->d1_level].max);
713         if ((old_buf = spec->concatBuf[spec->d1_level].buf))
714         {
715             memcpy (new_buf, old_buf, org_len);
716             xfree (old_buf);
717         }
718         spec->concatBuf[spec->d1_level].buf = new_buf;
719     }
720     memcpy (spec->concatBuf[spec->d1_level].buf + org_len, ebuf, elen);
721     res->u.data.len += elen;
722 }
723
724 static void execDataP (struct lexSpec *spec,
725                        const char *ebuf, int elen, int formatted_text)
726 {
727     execData (spec, ebuf, elen, formatted_text);
728 }
729
730 static void tagDataRelease (struct lexSpec *spec)
731 {
732     data1_node *res;
733     
734     if ((res = spec->d1_stack[spec->d1_level]) &&
735         res->which == DATA1N_data && 
736         res->u.data.what == DATA1I_text)
737     {
738         assert (!res->u.data.data);
739         assert (res->u.data.len > 0);
740         if (res->u.data.len > DATA1_LOCALDATA)
741             res->u.data.data = (char *) nmem_malloc (spec->m, res->u.data.len);
742         else
743             res->u.data.data = res->lbuf;
744         memcpy (res->u.data.data, spec->concatBuf[spec->d1_level].buf,
745                 res->u.data.len);
746     }
747 }
748
749 static void variantBegin (struct lexSpec *spec, 
750                           const char *class_str, int class_len,
751                           const char *type_str, int type_len,
752                           const char *value_str, int value_len)
753 {
754     struct data1_node *parent = spec->d1_stack[spec->d1_level -1];
755     char tclass[DATA1_MAX_SYMBOL], ttype[DATA1_MAX_SYMBOL];
756     data1_vartype *tp;
757     int i;
758     data1_node *res;
759
760     if (spec->d1_level == 0)
761     {
762         logf (LOG_WARN, "in variant begin. No record type defined");
763         return ;
764     }
765     if (class_len >= DATA1_MAX_SYMBOL)
766         class_len = DATA1_MAX_SYMBOL-1;
767     memcpy (tclass, class_str, class_len);
768     tclass[class_len] = '\0';
769
770     if (type_len >= DATA1_MAX_SYMBOL)
771         type_len = DATA1_MAX_SYMBOL-1;
772     memcpy (ttype, type_str, type_len);
773     ttype[type_len] = '\0';
774
775 #if REGX_DEBUG 
776     logf (LOG_LOG, "variant begin(%s,%s,%d)", tclass, ttype,
777           spec->d1_level);
778 #endif
779
780     if (!(tp =
781           data1_getvartypebyct(spec->dh, parent->root->u.root.absyn->varset,
782                                tclass, ttype)))
783         return;
784     
785     if (parent->which != DATA1N_variant)
786     {
787         res = data1_mk_node2 (spec->dh, spec->m, DATA1N_variant, parent);
788         if (spec->d1_stack[spec->d1_level])
789             tagDataRelease (spec);
790         spec->d1_stack[spec->d1_level] = res;
791         spec->d1_stack[++(spec->d1_level)] = NULL;
792     }
793     for (i = spec->d1_level-1; spec->d1_stack[i]->which == DATA1N_variant; i--)
794         if (spec->d1_stack[i]->u.variant.type == tp)
795         {
796             spec->d1_level = i;
797             break;
798         }
799
800 #if REGX_DEBUG 
801     logf (LOG_LOG, "variant node(%d)", spec->d1_level);
802 #endif
803     parent = spec->d1_stack[spec->d1_level-1];
804     res = data1_mk_node2 (spec->dh, spec->m, DATA1N_variant, parent);
805     res->u.variant.type = tp;
806
807     if (value_len >= DATA1_LOCALDATA)
808         value_len =DATA1_LOCALDATA-1;
809     memcpy (res->lbuf, value_str, value_len);
810     res->lbuf[value_len] = '\0';
811
812     res->u.variant.value = res->lbuf;
813     
814     if (spec->d1_stack[spec->d1_level])
815         tagDataRelease (spec);
816     spec->d1_stack[spec->d1_level] = res;
817     spec->d1_stack[++(spec->d1_level)] = NULL;
818 }
819
820 static void tagStrip (const char **tag, int *len)
821 {
822     int i;
823
824     for (i = *len; i > 0 && isspace((*tag)[i-1]); --i)
825         ;
826     *len = i;
827     for (i = 0; i < *len && isspace((*tag)[i]); i++)
828         ;
829     *tag += i;
830     *len -= i;
831 }
832
833 static void tagBegin (struct lexSpec *spec, 
834                       const char *tag, int len)
835 {
836     if (spec->d1_level == 0)
837     {
838         logf (LOG_WARN, "in element begin. No record type defined");
839         return ;
840     }
841     tagStrip (&tag, &len);
842     if (spec->d1_stack[spec->d1_level])
843         tagDataRelease (spec);
844
845 #if REGX_DEBUG 
846     logf (LOG_LOG, "begin tag(%.*s, %d)", len, tag, spec->d1_level);
847 #endif
848
849     spec->d1_stack[spec->d1_level] = data1_mk_tag_n (
850         spec->dh, spec->m, tag, len, 0, spec->d1_stack[spec->d1_level -1]);
851     spec->d1_stack[++(spec->d1_level)] = NULL;
852 }
853
854 static void tagEnd (struct lexSpec *spec, int min_level,
855                     const char *tag, int len)
856 {
857     tagStrip (&tag, &len);
858     while (spec->d1_level > min_level)
859     {
860         tagDataRelease (spec);
861         (spec->d1_level)--;
862         if (spec->d1_level == 0)
863             break;
864         if ((spec->d1_stack[spec->d1_level]->which == DATA1N_tag) &&
865             (!tag ||
866              (strlen(spec->d1_stack[spec->d1_level]->u.tag.tag) ==
867               (size_t) len &&
868               !memcmp (spec->d1_stack[spec->d1_level]->u.tag.tag, tag, len))))
869             break;
870     }
871 #if REGX_DEBUG
872     logf (LOG_LOG, "end tag(%d)", spec->d1_level);
873 #endif
874 }
875
876
877 static int tryMatch (struct lexSpec *spec, int *pptr, int *mptr,
878                      struct DFA *dfa)
879 {
880     struct DFA_state *state = dfa->states[0];
881     struct DFA_tran *t;
882     unsigned char c;
883     unsigned char c_prev = 0;
884     int ptr = *pptr;          /* current pointer */
885     int start_ptr = *pptr;    /* first char of match */
886     int last_ptr = 0;         /* last char of match */
887     int last_rule = 0;        /* rule number of current match */
888     int i;
889
890     while (1)
891     {
892         c = f_win_advance (spec, &ptr);
893         if (ptr == F_WIN_EOF)
894         {
895             if (last_rule)
896             {
897                 *mptr = start_ptr;
898                 *pptr = last_ptr;
899                 return 1;
900             }
901             break;
902         }
903         t = state->trans;
904         i = state->tran_no;
905         while (1)
906             if (--i < 0)
907             {
908                 if (last_rule)
909                 {
910                     *mptr = start_ptr;     /* match starts here */
911                     *pptr = last_ptr;      /* match end here (+1) */
912                     return 1;
913                 }
914                 state = dfa->states[0];
915                 start_ptr = ptr;
916                 c_prev = c;
917                 break;
918             }
919             else if (c >= t->ch[0] && c <= t->ch[1])
920             {
921                 state = dfa->states[t->to];
922                 if (state->rule_no)
923                 {
924                     if (c_prev == '\n')
925                     {
926                         last_rule = state->rule_no;
927                         last_ptr = ptr;
928                     }
929                     else
930                     {
931                         last_rule = state->rule_nno;
932                         last_ptr = ptr;
933                     }
934                 }
935                 break;
936             }
937             else
938                 t++;
939     }
940     return 0;
941 }
942
943 static int execTok (struct lexSpec *spec, const char **src,
944                     const char **tokBuf, int *tokLen)
945 {
946     const char *s = *src;
947
948     while (*s == ' ' || *s == '\t')
949         s++;
950     if (!*s)
951         return 0;
952     if (*s == '$' && s[1] >= '0' && s[1] <= '9')
953     {
954         int n = 0;
955         s++;
956         while (*s >= '0' && *s <= '9')
957             n = n*10 + (*s++ -'0');
958         if (spec->arg_no == 0)
959         {
960             *tokBuf = "";
961             *tokLen = 0;
962         }
963         else
964         {
965             if (n >= spec->arg_no)
966                 n = spec->arg_no-1;
967             *tokBuf = f_win_get (spec, spec->arg_start[n], spec->arg_end[n],
968                                  tokLen);
969         }
970     }
971     else if (*s == '\"')
972     {
973         *tokBuf = ++s;
974         while (*s && *s != '\"')
975             s++;
976         *tokLen = s - *tokBuf;
977         if (*s)
978             s++;
979         *src = s;
980     }
981     else if (*s == '\n' || *s == ';')
982     {
983         *src = s+1;
984         return 1;
985     }
986     else if (*s == '-')
987     {
988         *tokBuf = s++;
989         while (*s && *s != ' ' && *s != '\t' && *s != '\n' && *s != '\r' &&
990                *s != ';')
991             s++;
992         *tokLen = s - *tokBuf;
993         *src = s;
994         return 3;
995     }
996     else
997     {
998         *tokBuf = s++;
999         while (*s && *s != ' ' && *s != '\t' && *s != '\n' && *s != '\r' &&
1000                *s != ';')
1001             s++;
1002         *tokLen = s - *tokBuf;
1003     }
1004     *src = s;
1005     return 2;
1006 }
1007
1008 static char *regxStrz (const char *src, int len, char *str)
1009 {
1010     if (len > 63)
1011         len = 63;
1012     memcpy (str, src, len);
1013     str[len] = '\0';
1014     return str;
1015 }
1016
1017 #if HAVE_TCL_H
1018 static int cmd_tcl_begin (ClientData clientData, Tcl_Interp *interp,
1019                           int argc, char **argv)
1020 {
1021     struct lexSpec *spec = (struct lexSpec *) clientData;
1022     if (argc < 2)
1023         return TCL_ERROR;
1024     if (!strcmp(argv[1], "record") && argc == 3)
1025     {
1026         char *absynName = argv[2];
1027         data1_node *res;
1028
1029 #if REGX_DEBUG
1030         logf (LOG_LOG, "begin record %s", absynName);
1031 #endif
1032         res = data1_mk_root (spec->dh, spec->m, absynName);
1033         
1034         spec->d1_stack[spec->d1_level++] = res;
1035
1036         res = data1_mk_tag (spec->dh, spec->m, absynName, 0, res);
1037
1038         spec->d1_stack[spec->d1_level++] = res;
1039
1040         spec->d1_stack[spec->d1_level] = NULL;
1041     }
1042     else if (!strcmp(argv[1], "element") && argc == 3)
1043     {
1044         tagBegin (spec, argv[2], strlen(argv[2]));
1045     }
1046     else if (!strcmp (argv[1], "variant") && argc == 5)
1047     {
1048         variantBegin (spec, argv[2], strlen(argv[2]),
1049                       argv[3], strlen(argv[3]),
1050                       argv[4], strlen(argv[4]));
1051     }
1052     else if (!strcmp (argv[1], "context") && argc == 3)
1053     {
1054         struct lexContext *lc = spec->context;
1055 #if REGX_DEBUG
1056         logf (LOG_LOG, "begin context %s",argv[2]);
1057 #endif
1058         while (lc && strcmp (argv[2], lc->name))
1059             lc = lc->next;
1060         if (lc)
1061         {
1062             spec->context_stack[++(spec->context_stack_top)] = lc;
1063         }
1064         else
1065             logf (LOG_WARN, "unknown context %s", argv[2]);
1066     }
1067     else
1068         return TCL_ERROR;
1069     return TCL_OK;
1070 }
1071
1072 static int cmd_tcl_end (ClientData clientData, Tcl_Interp *interp,
1073                         int argc, char **argv)
1074 {
1075     struct lexSpec *spec = (struct lexSpec *) clientData;
1076     if (argc < 2)
1077         return TCL_ERROR;
1078     
1079     if (!strcmp (argv[1], "record"))
1080     {
1081         while (spec->d1_level)
1082         {
1083             tagDataRelease (spec);
1084             (spec->d1_level)--;
1085         }
1086 #if REGX_DEBUG
1087         logf (LOG_LOG, "end record");
1088 #endif
1089         spec->stop_flag = 1;
1090     }
1091     else if (!strcmp (argv[1], "element"))
1092     {
1093         int min_level = 1;
1094         char *element = 0;
1095         if (argc >= 3 && !strcmp(argv[2], "-record"))
1096         {
1097             min_level = 0;
1098             if (argc == 4)
1099                 element = argv[3];
1100         }
1101         else
1102             if (argc == 3)
1103                 element = argv[2];
1104         tagEnd (spec, min_level, element, (element ? strlen(element) : 0));
1105         if (spec->d1_level == 0)
1106         {
1107 #if REGX_DEBUG
1108             logf (LOG_LOG, "end element end records");
1109 #endif
1110             spec->stop_flag = 1;
1111         }
1112     }
1113     else if (!strcmp (argv[1], "context"))
1114     {
1115 #if REGX_DEBUG
1116         logf (LOG_LOG, "end context");
1117 #endif
1118         if (spec->context_stack_top)
1119             (spec->context_stack_top)--;
1120     }
1121     else
1122         return TCL_ERROR;
1123     return TCL_OK;
1124 }
1125
1126 static int cmd_tcl_data (ClientData clientData, Tcl_Interp *interp,
1127                          int argc, char **argv)
1128 {
1129     int argi = 1;
1130     int textFlag = 0;
1131     const char *element = 0;
1132     struct lexSpec *spec = (struct lexSpec *) clientData;
1133     
1134     while (argi < argc)
1135     {
1136         if (!strcmp("-text", argv[argi]))
1137         {
1138             textFlag = 1;
1139             argi++;
1140         }
1141         else if (!strcmp("-element", argv[argi]))
1142         {
1143             argi++;
1144             if (argi < argc)
1145                 element = argv[argi++];
1146         }
1147         else
1148             break;
1149     }
1150     if (element)
1151         tagBegin (spec, element, strlen(element));
1152
1153     while (argi < argc)
1154     {
1155 #if TCL_MAJOR_VERSION > 8 || (TCL_MAJOR_VERSION == 8 && TCL_MINOR_VERSION > 0)
1156         Tcl_DString ds;
1157         char *native = Tcl_UtfToExternalDString(0, argv[argi], -1, &ds);
1158         execData (spec, native, strlen(native), textFlag);
1159         Tcl_DStringFree (&ds);
1160 #else
1161         execData (spec, argv[argi], strlen(argv[argi]), textFlag);
1162 #endif
1163         argi++;
1164     }
1165     if (element)
1166         tagEnd (spec, 1, NULL, 0);
1167     return TCL_OK;
1168 }
1169
1170 static int cmd_tcl_unread (ClientData clientData, Tcl_Interp *interp,
1171                            int argc, char **argv)
1172 {
1173     struct lexSpec *spec = (struct lexSpec *) clientData;
1174     int argi = 1;
1175     int offset = 0;
1176     int no;
1177     
1178     while (argi < argc)
1179     {
1180         if (!strcmp("-offset", argv[argi]))
1181         {
1182             argi++;
1183             if (argi < argc)
1184             {
1185                 offset = atoi(argv[argi]);
1186                 argi++;
1187             }
1188         }
1189         else
1190             break;
1191     }
1192     if (argi != argc-1)
1193         return TCL_ERROR;
1194     no = atoi(argv[argi]);
1195     if (no >= spec->arg_no)
1196         no = spec->arg_no - 1;
1197     spec->ptr = spec->arg_start[no] + offset;
1198     return TCL_OK;
1199 }
1200
1201 static void execTcl (struct lexSpec *spec, struct regxCode *code)
1202 {   
1203     int i;
1204     int ret;
1205     for (i = 0; i < spec->arg_no; i++)
1206     {
1207         char var_name[10], *var_buf;
1208         int var_len, ch;
1209         
1210         sprintf (var_name, "%d", i);
1211         var_buf = f_win_get (spec, spec->arg_start[i], spec->arg_end[i],
1212                              &var_len); 
1213         if (var_buf)
1214         {
1215             ch = var_buf[var_len];
1216             var_buf[var_len] = '\0';
1217             Tcl_SetVar (spec->tcl_interp, var_name, var_buf, 0);
1218             var_buf[var_len] = ch;
1219         }
1220     }
1221 #if HAVE_TCL_OBJECTS
1222     ret = Tcl_GlobalEvalObj(spec->tcl_interp, code->tcl_obj);
1223 #else
1224     ret = Tcl_GlobalEval (spec->tcl_interp, code->str);
1225 #endif
1226     if (ret != TCL_OK)
1227     {
1228         const char *err = Tcl_GetVar(spec->tcl_interp, "errorInfo", 0);
1229         logf(LOG_FATAL, "Tcl error, line=%d, \"%s\"\n%s", 
1230             spec->tcl_interp->errorLine,
1231             spec->tcl_interp->result,
1232             err ? err : "[NO ERRORINFO]");
1233     }
1234 }
1235 /* HAVE_TCL_H */
1236 #endif
1237
1238 static void execCode (struct lexSpec *spec, struct regxCode *code)
1239 {
1240     const char *s = code->str;
1241     int cmd_len, r;
1242     const char *cmd_str;
1243     
1244     r = execTok (spec, &s, &cmd_str, &cmd_len);
1245     while (r)
1246     {
1247         char *p, ptmp[64];
1248         
1249         if (r == 1)
1250         {
1251             r = execTok (spec, &s, &cmd_str, &cmd_len);
1252             continue;
1253         }
1254         p = regxStrz (cmd_str, cmd_len, ptmp);
1255         if (!strcmp (p, "begin"))
1256         {
1257             r = execTok (spec, &s, &cmd_str, &cmd_len);
1258             if (r < 2)
1259             {
1260                 logf (LOG_WARN, "missing keyword after 'begin'");
1261                 continue;
1262             }
1263             p = regxStrz (cmd_str, cmd_len, ptmp);
1264             if (!strcmp (p, "record"))
1265             {
1266                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1267                 if (r < 2)
1268                     continue;
1269                 if (spec->d1_level == 0)
1270                 {
1271                     static char absynName[64];
1272                     data1_node *res;
1273
1274                     if (cmd_len > 63)
1275                         cmd_len = 63;
1276                     memcpy (absynName, cmd_str, cmd_len);
1277                     absynName[cmd_len] = '\0';
1278 #if REGX_DEBUG
1279                     logf (LOG_LOG, "begin record %s", absynName);
1280 #endif
1281                     res = data1_mk_root (spec->dh, spec->m, absynName);
1282                     
1283                     spec->d1_stack[spec->d1_level++] = res;
1284
1285                     res = data1_mk_tag (spec->dh, spec->m, absynName, 0, res);
1286
1287                     spec->d1_stack[spec->d1_level++] = res;
1288
1289                     spec->d1_stack[spec->d1_level] = NULL;
1290                 }
1291                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1292             }
1293             else if (!strcmp (p, "element"))
1294             {
1295                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1296                 if (r < 2)
1297                     continue;
1298                 tagBegin (spec, cmd_str, cmd_len);
1299                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1300             } 
1301             else if (!strcmp (p, "variant"))
1302             {
1303                 int class_len;
1304                 const char *class_str = NULL;
1305                 int type_len;
1306                 const char *type_str = NULL;
1307                 int value_len;
1308                 const char *value_str = NULL;
1309                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1310                 if (r < 2)
1311                     continue;
1312                 class_str = cmd_str;
1313                 class_len = cmd_len;
1314                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1315                 if (r < 2)
1316                     continue;
1317                 type_str = cmd_str;
1318                 type_len = cmd_len;
1319
1320                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1321                 if (r < 2)
1322                     continue;
1323                 value_str = cmd_str;
1324                 value_len = cmd_len;
1325
1326                 variantBegin (spec, class_str, class_len,
1327                               type_str, type_len, value_str, value_len);
1328                 
1329                 
1330                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1331             }
1332             else if (!strcmp (p, "context"))
1333             {
1334                 if (r > 1)
1335                 {
1336                     struct lexContext *lc = spec->context;
1337                     r = execTok (spec, &s, &cmd_str, &cmd_len);
1338                     p = regxStrz (cmd_str, cmd_len, ptmp);
1339 #if REGX_DEBUG
1340                     logf (LOG_LOG, "begin context %s", p);
1341 #endif
1342                     while (lc && strcmp (p, lc->name))
1343                         lc = lc->next;
1344                     if (lc)
1345                         spec->context_stack[++(spec->context_stack_top)] = lc;
1346                     else
1347                         logf (LOG_WARN, "unknown context %s", p);
1348                     
1349                 }
1350                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1351             }
1352             else
1353             {
1354                 logf (LOG_WARN, "bad keyword '%s' after begin", p);
1355             }
1356         }
1357         else if (!strcmp (p, "end"))
1358         {
1359             r = execTok (spec, &s, &cmd_str, &cmd_len);
1360             if (r < 2)
1361             {
1362                 logf (LOG_WARN, "missing keyword after 'end'");
1363                 continue;
1364             }
1365             p = regxStrz (cmd_str, cmd_len, ptmp);
1366             if (!strcmp (p, "record"))
1367             {
1368                 while (spec->d1_level)
1369                 {
1370                     tagDataRelease (spec);
1371                     (spec->d1_level)--;
1372                 }
1373                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1374 #if REGX_DEBUG
1375                 logf (LOG_LOG, "end record");
1376 #endif
1377                 spec->stop_flag = 1;
1378             }
1379             else if (!strcmp (p, "element"))
1380             {
1381                 int min_level = 1;
1382                 while ((r = execTok (spec, &s, &cmd_str, &cmd_len)) == 3)
1383                 {
1384                     if (cmd_len==7 && !memcmp ("-record", cmd_str, cmd_len))
1385                         min_level = 0;
1386                 }
1387                 if (r > 2)
1388                 {
1389                     tagEnd (spec, min_level, cmd_str, cmd_len);
1390                     r = execTok (spec, &s, &cmd_str, &cmd_len);
1391                 }
1392                 else
1393                     tagEnd (spec, min_level, NULL, 0);
1394                 if (spec->d1_level == 0)
1395                 {
1396 #if REGX_DEBUG
1397                     logf (LOG_LOG, "end element end records");
1398 #endif
1399                     spec->stop_flag = 1;
1400                 }
1401
1402             }
1403             else if (!strcmp (p, "context"))
1404             {
1405 #if REGX_DEBUG
1406                 logf (LOG_LOG, "end context");
1407 #endif
1408                 if (spec->context_stack_top)
1409                     (spec->context_stack_top)--;
1410                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1411             }       
1412             else
1413                 logf (LOG_WARN, "bad keyword '%s' after end", p);
1414         }
1415         else if (!strcmp (p, "data"))
1416         {
1417             int textFlag = 0;
1418             int element_len;
1419             const char *element_str = NULL;
1420             
1421             while ((r = execTok (spec, &s, &cmd_str, &cmd_len)) == 3)
1422             {
1423                 if (cmd_len==5 && !memcmp ("-text", cmd_str, cmd_len))
1424                     textFlag = 1;
1425                 else if (cmd_len==8 && !memcmp ("-element", cmd_str, cmd_len))
1426                 {
1427                     r = execTok (spec, &s, &element_str, &element_len);
1428                     if (r < 2)
1429                         break;
1430                 }
1431                 else 
1432                     logf (LOG_WARN, "bad data option: %.*s",
1433                           cmd_len, cmd_str);
1434             }
1435             if (r != 2)
1436             {
1437                 logf (LOG_WARN, "missing data item after data");
1438                 continue;
1439             }
1440             if (element_str)
1441                 tagBegin (spec, element_str, element_len);
1442             do
1443             {
1444                 execData (spec, cmd_str, cmd_len,textFlag);
1445                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1446             } while (r > 1);
1447             if (element_str)
1448                 tagEnd (spec, 1, NULL, 0);
1449         }
1450         else if (!strcmp (p, "unread"))
1451         {
1452             int no, offset;
1453             r = execTok (spec, &s, &cmd_str, &cmd_len);
1454             if (r==3 && cmd_len == 7 && !memcmp ("-offset", cmd_str, cmd_len))
1455             {
1456                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1457                 if (r < 2)
1458                 {
1459                     logf (LOG_WARN, "missing number after -offset");
1460                     continue;
1461                 }
1462                 p = regxStrz (cmd_str, cmd_len, ptmp);
1463                 offset = atoi (p);
1464                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1465             }
1466             else
1467                 offset = 0;
1468             if (r < 2)
1469             {
1470                 logf (LOG_WARN, "missing index after unread command");
1471                 continue;
1472             }
1473             if (cmd_len != 1 || *cmd_str < '0' || *cmd_str > '9')
1474             {
1475                 logf (LOG_WARN, "bad index after unread command");
1476                 continue;
1477             }
1478             else
1479             {
1480                 no = *cmd_str - '0';
1481                 if (no >= spec->arg_no)
1482                     no = spec->arg_no - 1;
1483                 spec->ptr = spec->arg_start[no] + offset;
1484             }
1485             r = execTok (spec, &s, &cmd_str, &cmd_len);
1486         }
1487         else if (!strcmp (p, "context"))
1488         {
1489             if (r > 1)
1490             {
1491                 struct lexContext *lc = spec->context;
1492                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1493                 p = regxStrz (cmd_str, cmd_len, ptmp);
1494                 
1495                 while (lc && strcmp (p, lc->name))
1496                     lc = lc->next;
1497                 if (lc)
1498                     spec->context_stack[spec->context_stack_top] = lc;
1499                 else
1500                     logf (LOG_WARN, "unknown context %s", p);
1501
1502             }
1503             r = execTok (spec, &s, &cmd_str, &cmd_len);
1504         }
1505         else
1506         {
1507             logf (LOG_WARN, "unknown code command '%.*s'", cmd_len, cmd_str);
1508             r = execTok (spec, &s, &cmd_str, &cmd_len);
1509             continue;
1510         }
1511         if (r > 1)
1512         {
1513             logf (LOG_WARN, "ignoring token %.*s", cmd_len, cmd_str);
1514             do {
1515                 r = execTok (spec, &s, &cmd_str, &cmd_len);
1516             } while (r > 1);
1517         }
1518     }
1519 }
1520
1521
1522 static int execAction (struct lexSpec *spec, struct lexRuleAction *ap,
1523                        int start_ptr, int *pptr)
1524 {
1525     int sptr;
1526     int arg_start[20];
1527     int arg_end[20];
1528     int arg_no = 1;
1529
1530     if (!ap)
1531         return 1;
1532     arg_start[0] = start_ptr;
1533     arg_end[0] = *pptr;
1534     spec->arg_start = arg_start;
1535     spec->arg_end = arg_end;
1536
1537     while (ap)
1538     {
1539         switch (ap->which)
1540         {
1541         case REGX_PATTERN:
1542             if (ap->u.pattern.body)
1543             {
1544                 arg_start[arg_no] = *pptr;
1545                 if (!tryMatch (spec, pptr, &sptr, ap->u.pattern.dfa))
1546                 {
1547                     arg_end[arg_no] = F_WIN_EOF;
1548                     arg_no++;
1549                     arg_start[arg_no] = F_WIN_EOF;
1550                     arg_end[arg_no] = F_WIN_EOF;
1551 /* return 1*/
1552                 }
1553                 else
1554                 {
1555                     arg_end[arg_no] = sptr;
1556                     arg_no++;
1557                     arg_start[arg_no] = sptr;
1558                     arg_end[arg_no] = *pptr;
1559                 }
1560             }
1561             else
1562             {
1563                 arg_start[arg_no] = *pptr;
1564                 if (!tryMatch (spec, pptr, &sptr, ap->u.pattern.dfa))
1565                     return 1;
1566                 if (sptr != arg_start[arg_no])
1567                     return 1;
1568                 arg_end[arg_no] = *pptr;
1569             }
1570             arg_no++;
1571             break;
1572         case REGX_CODE:
1573             spec->arg_no = arg_no;
1574             spec->ptr = *pptr;
1575 #if HAVE_TCL_H
1576             if (spec->tcl_interp)
1577                 execTcl(spec, ap->u.code);
1578             else
1579                 execCode (spec, ap->u.code);
1580 #else
1581             execCode (spec, ap->u.code);
1582 #endif
1583             *pptr = spec->ptr;
1584             if (spec->stop_flag)
1585                 return 0;
1586             break;
1587         case REGX_END:
1588             arg_start[arg_no] = *pptr;
1589             arg_end[arg_no] = F_WIN_EOF;
1590             arg_no++;
1591             *pptr = F_WIN_EOF;
1592         }
1593         ap = ap->next;
1594     }
1595     return 1;
1596 }
1597
1598 static int execRule (struct lexSpec *spec, struct lexContext *context,
1599                      int ruleNo, int start_ptr, int *pptr)
1600 {
1601 #if REGX_DEBUG
1602     logf (LOG_LOG, "exec rule %d", ruleNo);
1603 #endif
1604     return execAction (spec, context->fastRule[ruleNo]->actionList,
1605                        start_ptr, pptr);
1606 }
1607
1608 data1_node *lexNode (struct lexSpec *spec, int *ptr)
1609 {
1610     struct lexContext *context = spec->context_stack[spec->context_stack_top];
1611     struct DFA_state *state = context->dfa->states[0];
1612     struct DFA_tran *t;
1613     unsigned char c;
1614     unsigned char c_prev = '\n';
1615     int i;
1616     int last_rule = 0;        /* rule number of current match */
1617     int last_ptr = *ptr;      /* last char of match */
1618     int start_ptr = *ptr;     /* first char of match */
1619     int skip_ptr = *ptr;      /* first char of run */
1620
1621     while (1)
1622     {
1623         c = f_win_advance (spec, ptr);
1624         if (*ptr == F_WIN_EOF)
1625         {
1626             /* end of file met */
1627             if (last_rule)
1628             {
1629                 /* there was a match */
1630                 if (skip_ptr < start_ptr)
1631                 {
1632                     /* deal with chars that didn't match */
1633                     int size;
1634                     char *buf;
1635                     buf = f_win_get (spec, skip_ptr, start_ptr, &size);
1636                     execDataP (spec, buf, size, 0);
1637                 }
1638                 /* restore pointer */
1639                 *ptr = last_ptr;
1640                 /* execute rule */
1641                 if (!execRule (spec, context, last_rule, start_ptr, ptr))
1642                     break;
1643                 /* restore skip pointer */
1644                 skip_ptr = *ptr;
1645                 last_rule = 0;
1646             }
1647             else if (skip_ptr < *ptr)
1648             {
1649                 /* deal with chars that didn't match */
1650                 int size;
1651                 char *buf;
1652                 buf = f_win_get (spec, skip_ptr, *ptr, &size);
1653                 execDataP (spec, buf, size, 0);
1654             }
1655             if (*ptr == F_WIN_EOF)
1656                 break;
1657         }
1658         t = state->trans;
1659         i = state->tran_no;
1660         while (1)
1661             if (--i < 0)
1662             {   /* no transition for character c ... */
1663                 if (last_rule)
1664                 {
1665                     if (skip_ptr < start_ptr)
1666                     {
1667                         /* deal with chars that didn't match */
1668                         int size;
1669                         char *buf;
1670                         buf = f_win_get (spec, skip_ptr, start_ptr, &size);
1671                         execDataP (spec, buf, size, 0);
1672                     }
1673                     /* restore pointer */
1674                     *ptr = last_ptr;
1675                     if (!execRule (spec, context, last_rule, start_ptr, ptr))
1676                     {
1677                         if (spec->f_win_ef && *ptr != F_WIN_EOF)
1678                         {
1679 #if REGX_DEBUG
1680                             logf (LOG_LOG, "regx: endf ptr=%d", *ptr);
1681 #endif
1682                             (*spec->f_win_ef)(spec->f_win_fh, *ptr);
1683                         }
1684                         return NULL;
1685                     }
1686                     context = spec->context_stack[spec->context_stack_top];
1687                     skip_ptr = *ptr;
1688                     last_rule = 0;
1689                     last_ptr = start_ptr = *ptr;
1690                     if (start_ptr > 0)
1691                     {
1692                         --start_ptr;
1693                         c_prev = f_win_advance (spec, &start_ptr);
1694                     }
1695                 }
1696                 else
1697                 {
1698                     c_prev = f_win_advance (spec, &start_ptr);
1699                     *ptr = start_ptr;
1700                 }
1701                 state = context->dfa->states[0];
1702                 break;
1703             }
1704             else if (c >= t->ch[0] && c <= t->ch[1])
1705             {   /* transition ... */
1706                 state = context->dfa->states[t->to];
1707                 if (state->rule_no)
1708                 {
1709                     if (c_prev == '\n')
1710                     {
1711                         last_rule = state->rule_no;
1712                         last_ptr = *ptr;
1713                     } 
1714                     else if (state->rule_nno)
1715                     {
1716                         last_rule = state->rule_nno;
1717                         last_ptr = *ptr;
1718                     }
1719                 }
1720                 break;
1721             }
1722             else
1723                 t++;
1724     }
1725     return NULL;
1726 }
1727
1728 static data1_node *lexRoot (struct lexSpec *spec, off_t offset,
1729                             const char *context_name)
1730 {
1731     struct lexContext *lt = spec->context;
1732     int ptr = offset;
1733
1734     spec->stop_flag = 0;
1735     spec->d1_level = 0;
1736     spec->context_stack_top = 0;    
1737     while (lt)
1738     {
1739         if (!strcmp (lt->name, context_name))
1740             break;
1741         lt = lt->next;
1742     }
1743     if (!lt)
1744     {
1745         logf (LOG_WARN, "cannot find context %s", context_name);
1746         return NULL;
1747     }
1748     spec->context_stack[spec->context_stack_top] = lt;
1749     spec->d1_stack[spec->d1_level] = NULL;
1750 #if 1
1751     if (!lt->initFlag)
1752     {
1753         lt->initFlag = 1;
1754         execAction (spec, lt->initActionList, ptr, &ptr);
1755     }
1756 #endif
1757     execAction (spec, lt->beginActionList, ptr, &ptr);
1758     lexNode (spec, &ptr);
1759     while (spec->d1_level)
1760     {
1761         tagDataRelease (spec);
1762         (spec->d1_level)--;
1763     }
1764     execAction (spec, lt->endActionList, ptr, &ptr);
1765     return spec->d1_stack[0];
1766 }
1767
1768 void grs_destroy(void *clientData)
1769 {
1770     struct lexSpecs *specs = (struct lexSpecs *) clientData;
1771     if (specs->spec)
1772     {
1773         lexSpecDestroy(&specs->spec);
1774     }
1775     xfree (specs);
1776 }
1777
1778 void *grs_init(void)
1779 {
1780     struct lexSpecs *specs = (struct lexSpecs *) xmalloc (sizeof(*specs));
1781     specs->spec = 0;
1782     return specs;
1783 }
1784
1785 data1_node *grs_read_regx (struct grs_read_info *p)
1786 {
1787     int res;
1788     struct lexSpecs *specs = (struct lexSpecs *) p->clientData;
1789     struct lexSpec **curLexSpec = &specs->spec;
1790
1791 #if REGX_DEBUG
1792     logf (LOG_LOG, "grs_read_regx");
1793 #endif
1794     if (!*curLexSpec || strcmp ((*curLexSpec)->name, p->type))
1795     {
1796         if (*curLexSpec)
1797             lexSpecDestroy (curLexSpec);
1798         *curLexSpec = lexSpecCreate (p->type, p->dh);
1799         res = readFileSpec (*curLexSpec);
1800         if (res)
1801         {
1802             lexSpecDestroy (curLexSpec);
1803             return NULL;
1804         }
1805     }
1806     (*curLexSpec)->dh = p->dh;
1807     if (!p->offset)
1808     {
1809         (*curLexSpec)->f_win_start = 0;
1810         (*curLexSpec)->f_win_end = 0;
1811         (*curLexSpec)->f_win_rf = p->readf;
1812         (*curLexSpec)->f_win_sf = p->seekf;
1813         (*curLexSpec)->f_win_fh = p->fh;
1814         (*curLexSpec)->f_win_ef = p->endf;
1815         (*curLexSpec)->f_win_size = 500000;
1816     }
1817     (*curLexSpec)->m = p->mem;
1818     return lexRoot (*curLexSpec, p->offset, "main");
1819 }
1820
1821 static struct recTypeGrs regx_type = {
1822     "regx",
1823     grs_init,
1824     grs_destroy,
1825     grs_read_regx
1826 };
1827
1828 RecTypeGrs recTypeGrs_regx = &regx_type;
1829
1830 #if HAVE_TCL_H
1831 data1_node *grs_read_tcl (struct grs_read_info *p)
1832 {
1833     int res;
1834     struct lexSpecs *specs = (struct lexSpecs *) p->clientData;
1835     struct lexSpec **curLexSpec = &specs->spec;
1836
1837 #if REGX_DEBUG
1838     logf (LOG_LOG, "grs_read_tcl");
1839 #endif
1840     if (!*curLexSpec || strcmp ((*curLexSpec)->name, p->type))
1841     {
1842         Tcl_Interp *tcl_interp;
1843         if (*curLexSpec)
1844             lexSpecDestroy (curLexSpec);
1845         *curLexSpec = lexSpecCreate (p->type, p->dh);
1846         Tcl_FindExecutable("");
1847         tcl_interp = (*curLexSpec)->tcl_interp = Tcl_CreateInterp();
1848         Tcl_Init(tcl_interp);
1849         Tcl_CreateCommand (tcl_interp, "begin", cmd_tcl_begin, *curLexSpec, 0);
1850         Tcl_CreateCommand (tcl_interp, "end", cmd_tcl_end, *curLexSpec, 0);
1851         Tcl_CreateCommand (tcl_interp, "data", cmd_tcl_data, *curLexSpec, 0);
1852         Tcl_CreateCommand (tcl_interp, "unread", cmd_tcl_unread,
1853                            *curLexSpec, 0);
1854         res = readFileSpec (*curLexSpec);
1855         if (res)
1856         {
1857             lexSpecDestroy (curLexSpec);
1858             return NULL;
1859         }
1860     }
1861     (*curLexSpec)->dh = p->dh;
1862     if (!p->offset)
1863     {
1864         (*curLexSpec)->f_win_start = 0;
1865         (*curLexSpec)->f_win_end = 0;
1866         (*curLexSpec)->f_win_rf = p->readf;
1867         (*curLexSpec)->f_win_sf = p->seekf;
1868         (*curLexSpec)->f_win_fh = p->fh;
1869         (*curLexSpec)->f_win_ef = p->endf;
1870         (*curLexSpec)->f_win_size = 500000;
1871     }
1872     (*curLexSpec)->m = p->mem;
1873     return lexRoot (*curLexSpec, p->offset, "main");
1874 }
1875
1876 static struct recTypeGrs tcl_type = {
1877     "tcl",
1878     grs_init,
1879     grs_destroy,
1880     grs_read_tcl
1881 };
1882
1883 RecTypeGrs recTypeGrs_tcl = &tcl_type;
1884 #endif