]> mj.ucw.cz Git - libucw.git/blob - ucw/regex.c
f74f33e1d4e78141557f5df7948937ed62d88d55
[libucw.git] / ucw / regex.c
1 /*
2  *      UCW Library -- Interface to Regular Expression Libraries
3  *
4  *      (c) 1997--2004 Martin Mares <mj@ucw.cz>
5  *      (c) 2001 Robert Spalek <robert@ucw.cz>
6  *
7  *      This software may be freely distributed and used according to the terms
8  *      of the GNU Lesser General Public License.
9  */
10
11 #include "ucw/lib.h"
12 #include "ucw/chartype.h"
13 #include "ucw/hashfunc.h"
14 #include "ucw/regex.h"
15
16 #include <stdio.h>
17 #include <string.h>
18
19 #if defined(CONFIG_OWN_REGEX) || defined(CONFIG_POSIX_REGEX)
20
21 /* POSIX regular expression library */
22
23 #ifdef CONFIG_OWN_REGEX
24 #include "lib/regex/regex-sh.h"
25 #else
26 #include <regex.h>
27 #endif
28
29 struct regex {
30   regex_t rx;
31   regmatch_t matches[10];
32 };
33
34 regex *
35 rx_compile(const char *p, int icase)
36 {
37   regex *r = xmalloc_zero(sizeof(regex));
38
39   int err = regcomp(&r->rx, p, REG_EXTENDED | (icase ? REG_ICASE : 0));
40   if (err)
41     {
42       char msg[256];
43       regerror(err, &r->rx, msg, sizeof(msg)-1);
44       /* regfree(&r->rx) not needed */
45       die("Error parsing regular expression `%s': %s", p, msg);
46     }
47   return r;
48 }
49
50 void
51 rx_free(regex *r)
52 {
53   regfree(&r->rx);
54   xfree(r);
55 }
56
57 int
58 rx_match(regex *r, const char *s)
59 {
60   int err = regexec(&r->rx, s, 10, r->matches, 0);
61   if (!err)
62     {
63       /* regexec doesn't support anchored expressions, so we have to check ourselves that the full string is matched */
64       return !(r->matches[0].rm_so || s[r->matches[0].rm_eo]);
65     }
66   else if (err == REG_NOMATCH)
67     return 0;
68   else if (err == REG_ESPACE)
69     die("Regex matching ran out of memory");
70   else
71     die("Regex matching failed with unknown error %d", err);
72 }
73
74 int
75 rx_subst(regex *r, const char *by, const char *src, char *dest, uns destlen)
76 {
77   char *end = dest + destlen - 1;
78
79   if (!rx_match(r, src))
80     return 0;
81
82   while (*by)
83     {
84       if (*by == '\\')
85         {
86           by++;
87           if (*by >= '0' && *by <= '9') /* \0 gets replaced by entire pattern */
88             {
89               uns j = *by++ - '0';
90               if (j <= r->rx.re_nsub && r->matches[j].rm_so >= 0)
91                 {
92                   const char *s = src + r->matches[j].rm_so;
93                   uns i = r->matches[j].rm_eo - r->matches[j].rm_so;
94                   if (dest + i >= end)
95                     return -1;
96                   memcpy(dest, s, i);
97                   dest += i;
98                   continue;
99                 }
100             }
101         }
102       if (dest < end)
103         *dest++ = *by++;
104       else
105         return -1;
106     }
107   *dest = 0;
108   return 1;
109 }
110
111 #elif defined(CONFIG_PCRE)
112
113 /* PCRE library */
114
115 #include <pcre.h>
116
117 struct regex {
118   pcre *rx;
119   pcre_extra *extra;
120   uns match_array_size;
121   uns real_matches;
122   int matches[0];                       /* (max_matches+1) pairs (pos,len) plus some workspace */
123 };
124
125 regex *
126 rx_compile(const char *p, int icase)
127 {
128   const char *err;
129   int errpos, match_array_size, eno;
130
131   pcre *rx = pcre_compile(p, PCRE_ANCHORED | PCRE_EXTRA | (icase ? PCRE_CASELESS : 0), &err, &errpos, NULL);
132   if (!rx)
133     die("Error parsing regular expression `%s': %s at position %d", p, err, errpos);
134   eno = pcre_fullinfo(rx, NULL, PCRE_INFO_CAPTURECOUNT, &match_array_size);
135   if (eno)
136     die("Internal error: pcre_fullinfo() failed with error %d", eno);
137   match_array_size = 3*(match_array_size+1);
138   regex *r = xmalloc_zero(sizeof(regex) + match_array_size * sizeof(int));
139   r->rx = rx;
140   r->match_array_size = match_array_size;
141   r->extra = pcre_study(r->rx, 0, &err);
142   if (err)
143     die("Error studying regular expression `%s': %s", p, err);
144   return r;
145 }
146
147 void
148 rx_free(regex *r)
149 {
150   xfree(r->rx);
151   xfree(r->extra);
152   xfree(r);
153 }
154
155 int
156 rx_match(regex *r, const char *s)
157 {
158   int len = str_len(s);
159   int err = pcre_exec(r->rx, r->extra, s, len, 0, 0, r->matches, r->match_array_size);
160   if (err >= 0)
161     {
162       r->real_matches = err;
163       /* need to check that the full string matches */
164       return !(r->matches[0] || s[r->matches[1]]);
165     }
166   else if (err == PCRE_ERROR_NOMATCH)
167     return 0;
168   else if (err == PCRE_ERROR_NOMEMORY)
169     die("Regex matching ran out of memory");
170   else
171     die("Regex matching failed with unknown error %d", err);
172 }
173
174 int
175 rx_subst(regex *r, const char *by, const char *src, char *dest, uns destlen)
176 {
177   char *end = dest + destlen - 1;
178
179   if (!rx_match(r, src))
180     return 0;
181
182   while (*by)
183     {
184       if (*by == '\\')
185         {
186           by++;
187           if (*by >= '0' && *by <= '9') /* \0 gets replaced by entire pattern */
188             {
189               uns j = *by++ - '0';
190               if (j < r->real_matches && r->matches[2*j] >= 0)
191                 {
192                   char *s = src + r->matches[2*j];
193                   uns i = r->matches[2*j+1] - r->matches[2*j];
194                   if (dest + i >= end)
195                     return -1;
196                   memcpy(dest, s, i);
197                   dest += i;
198                   continue;
199                 }
200             }
201         }
202       if (dest < end)
203         *dest++ = *by++;
204       else
205         return -1;
206     }
207   *dest = 0;
208   return 1;
209 }
210
211 #else
212
213 /* BSD regular expression library */
214
215 #include <regex.h>
216
217 #define INITIAL_MEM 1024                /* Initial space allocated for each pattern */
218 #define CHAR_SET_SIZE 256               /* How many characters in the character set.  */
219
220 struct regex {
221   struct re_pattern_buffer buf;
222   struct re_registers regs;             /* Must not change between re_match() calls */
223   int len_cache;
224 };
225
226 regex *
227 rx_compile(const char *p, int icase)
228 {
229   regex *r = xmalloc_zero(sizeof(regex));
230   const char *msg;
231
232   r->buf.buffer = xmalloc(INITIAL_MEM);
233   r->buf.allocated = INITIAL_MEM;
234   if (icase)
235     {
236       unsigned i;
237       r->buf.translate = xmalloc (CHAR_SET_SIZE);
238       /* Map uppercase characters to corresponding lowercase ones.  */
239       for (i = 0; i < CHAR_SET_SIZE; i++)
240         r->buf.translate[i] = Cupcase(i);
241     }
242   else
243     r->buf.translate = NULL;
244   re_set_syntax(RE_SYNTAX_POSIX_EXTENDED);
245   msg = re_compile_pattern(p, strlen(p), &r->buf);
246   if (!msg)
247     return r;
248   die("Error parsing pattern `%s': %s", p, msg);
249 }
250
251 void
252 rx_free(regex *r)
253 {
254   xfree(r->buf.buffer);
255   if (r->buf.translate)
256     xfree(r->buf.translate);
257   xfree(r);
258 }
259
260 int
261 rx_match(regex *r, const char *s)
262 {
263   int len = strlen(s);
264
265   r->len_cache = len;
266   if (re_match(&r->buf, s, len, 0, &r->regs) < 0)
267     return 0;
268   if (r->regs.start[0] || r->regs.end[0] != len) /* XXX: Why regex doesn't enforce implicit "^...$" ? */
269     return 0;
270   return 1;
271 }
272
273 int
274 rx_subst(regex *r, const char *by, const char *src, char *dest, uns destlen)
275 {
276   char *end = dest + destlen - 1;
277
278   if (!rx_match(r, src))
279     return 0;
280
281   while (*by)
282     {
283       if (*by == '\\')
284         {
285           by++;
286           if (*by >= '0' && *by <= '9') /* \0 gets replaced by entire pattern */
287             {
288               uns j = *by++ - '0';
289               if (j < r->regs.num_regs)
290                 {
291                   const char *s = src + r->regs.start[j];
292                   uns i = r->regs.end[j] - r->regs.start[j];
293                   if (r->regs.start[j] > r->len_cache || r->regs.end[j] > r->len_cache)
294                     return -1;
295                   if (dest + i >= end)
296                     return -1;
297                   memcpy(dest, s, i);
298                   dest += i;
299                   continue;
300                 }
301             }
302         }
303       if (dest < end)
304         *dest++ = *by++;
305       else
306         return -1;
307     }
308   *dest = 0;
309   return 1;
310 }
311
312 #endif
313
314 #ifdef TEST
315
316 int main(int argc, char **argv)
317 {
318   regex *r;
319   char buf1[4096], buf2[4096];
320   int opt_i = 0;
321
322   if (!strcmp(argv[1], "-i"))
323     {
324       opt_i = 1;
325       argv++;
326       argc--;
327     }
328   r = rx_compile(argv[1], opt_i);
329   while (fgets(buf1, sizeof(buf1), stdin))
330     {
331       char *p = strchr(buf1, '\n');
332       if (p)
333         *p = 0;
334       if (argc == 2)
335         {
336           if (rx_match(r, buf1))
337             puts("MATCH");
338           else
339             puts("NO MATCH");
340         }
341       else
342         {
343           int i = rx_subst(r, argv[2], buf1, buf2, sizeof(buf2));
344           if (i < 0)
345             puts("OVERFLOW");
346           else if (!i)
347             puts("NO MATCH");
348           else
349             puts(buf2);
350         }
351     }
352   rx_free(r);
353 }
354
355 #endif