Using yaz_fclose
[idzebra-moved-to-github.git] / util / charmap.c
1 /*
2  * Copyright (C) 1996-2002, Index Data
3  * All rights reserved.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Id: charmap.c,v 1.21 2002-04-05 12:54:29 adam Exp $
7  *
8  */
9
10 /*
11  * Support module to handle character-conversions into and out of the
12  * Zebra dictionary.
13  */
14
15 #include <ctype.h>
16 #include <string.h>
17 #include <assert.h>
18
19 #include <yaz/yaz-util.h>
20 #include <charmap.h>
21
22 #define CHR_MAXSTR 1024
23 #define CHR_MAXEQUIV 32
24
25 const char *CHR_UNKNOWN = "\001";
26 const char *CHR_SPACE   = "\002";
27 const char *CHR_BASE    = "\003";
28
29 struct chrmaptab_info
30 {
31     chr_t_entry *input;         /* mapping table for input data */
32     chr_t_entry *q_input;       /* mapping table for queries */
33     unsigned char *output[256]; /* return mapping - for display of registers */
34     int base_uppercase;         /* Start of upper-case ordinals */
35     NMEM nmem;
36 };
37
38 /*
39  * Character map trie node.
40  */
41 struct chr_t_entry
42 {
43     chr_t_entry **children;  /* array of children */
44     unsigned char **target;  /* target for this node, if any */
45 };
46
47 /*
48  * General argument structure for callback functions (internal use only)
49  */
50 typedef struct chrwork 
51 {
52     chrmaptab map;
53     char string[CHR_MAXSTR+1];
54 } chrwork;
55
56 /*
57  * Add an entry to the character map.
58  */
59 static chr_t_entry *set_map_string(chr_t_entry *root, NMEM nmem,
60                                    const char *from, int len, char *to,
61                                    const char *from_0)
62 {
63     if (!from_0)
64         from_0 = from;
65     if (!root)
66     {
67         root = (chr_t_entry *) nmem_malloc(nmem, sizeof(*root));
68         root->children = 0;
69         root->target = 0;
70     }
71     if (!len)
72     {
73         if (!root->target || !root->target[0] || strcmp(root->target[0], to))
74         {
75             if (from_0 && 
76                 root->target && root->target[0] && root->target[0][0] &&
77                 strcmp (root->target[0], CHR_UNKNOWN))
78             {
79                 yaz_log (LOG_WARN, "duplicate entry for charmap from '%s'",
80                          from_0);
81             }
82             root->target = (unsigned char **)
83                 nmem_malloc(nmem, sizeof(*root->target)*2);
84             root->target[0] = (unsigned char *) nmem_strdup(nmem, to);
85             root->target[1] = 0;
86         }
87     }
88     else
89     {
90         if (!root->children)
91         {
92             int i;
93
94             root->children = (chr_t_entry **)
95                 nmem_malloc(nmem, sizeof(chr_t_entry*) * 256);
96             for (i = 0; i < 256; i++)
97                 root->children[i] = 0;
98         }
99         if (!(root->children[(unsigned char) *from] =
100             set_map_string(root->children[(unsigned char) *from], nmem,
101                            from + 1, len - 1, to, from_0)))
102             return 0;
103     }
104     return root;
105 }
106
107 static chr_t_entry *find_entry(chr_t_entry *t, const char **from, int len)
108 {
109     chr_t_entry *res;
110
111     if (len && t->children && t->children[(unsigned char) **from])
112     {
113         const char *pos = *from;
114
115         (*from)++;
116         if ((res = find_entry(t->children[(unsigned char) *pos],
117             from, len - 1)))
118             return res;
119         /* no match */
120         *from = pos;
121     }
122     /* no children match. use ourselves, if we have a target */
123     return t->target ? t : 0;
124 }
125
126 static chr_t_entry *find_entry_x(chr_t_entry *t, const char **from, int *len)
127 {
128     chr_t_entry *res;
129
130     while (*len <= 0)
131     {   /* switch to next buffer */
132         if (*len < 0)
133             break;
134         from++;
135         len++;
136     }
137     if (*len > 0 && t->children && t->children[(unsigned char) **from])
138     {
139         const char *old_from = *from;
140         int old_len = *len;
141         
142         (*len)--;
143         (*from)++;
144         if ((res = find_entry_x(t->children[(unsigned char) *old_from],
145                                 from, len)))
146             return res;
147         /* no match */
148         *len = old_len;
149         *from = old_from;
150     }
151     /* no children match. use ourselves, if we have a target */
152     return t->target ? t : 0;
153 }
154
155 const char **chr_map_input_x(chrmaptab maptab, const char **from, int *len)
156 {
157     chr_t_entry *t = maptab->input;
158     chr_t_entry *res;
159
160     if (!(res = find_entry_x(t, from, len)))
161         abort();
162     return (const char **) (res->target);
163 }
164
165 const char **chr_map_input(chrmaptab maptab, const char **from, int len)
166 {
167     chr_t_entry *t = maptab->input;
168     chr_t_entry *res;
169     int len_tmp[2];
170
171     len_tmp[0] = len;
172     len_tmp[1] = -1;
173     if (!(res = find_entry_x(t, from, len_tmp)))
174         abort();
175     return (const char **) (res->target);
176 }
177
178 const char *chr_map_output(chrmaptab maptab, const char **from, int len)
179 {
180     unsigned char c = ** (unsigned char **) from;
181     (*from)++;
182     return (const char*) maptab->output[c];
183 }
184
185 unsigned char zebra_prim(char **s)
186 {
187     unsigned char c;
188     unsigned int i;
189
190     yaz_log (LOG_DEBUG, "prim %.3s", *s);
191     if (**s == '\\')
192     {
193         (*s)++;
194         c = **s;
195         switch (c)
196         {
197         case '\\': c = '\\'; (*s)++; break;
198         case 'r': c = '\r'; (*s)++; break;
199         case 'n': c = '\n'; (*s)++; break;
200         case 't': c = '\t'; (*s)++; break;
201         case 's': c = ' '; (*s)++; break;
202         case 'x': sscanf(*s, "x%2x", &i); c = i; *s += 3; break;
203         case '0':
204         case '1':
205         case '2':
206         case '3':
207         case '4':
208         case '5':
209         case '6':
210         case '7':
211         case '8':
212         case '9':
213             sscanf(*s, "%3o", &i);
214             c = i;
215             *s += 3;
216             break;
217         default:
218             (*s)++;
219         }
220     }
221     else
222     {
223         c = **s;
224         ++(*s);
225     }
226     yaz_log (LOG_DEBUG, "out %d", c);
227     return c;
228 }
229
230 /*
231  * Callback function.
232  * Add an entry to the value space.
233  */
234 static void fun_addentry(const char *s, void *data, int num)
235 {
236     chrmaptab tab = (chrmaptab) data;
237     char tmp[2];
238     
239     tmp[0] = num; tmp[1] = '\0';
240     tab->input = set_map_string(tab->input, tab->nmem, s, strlen(s), tmp, 0);
241     tab->output[num + tab->base_uppercase] =
242         (unsigned char *) nmem_strdup(tab->nmem, s);
243 }
244
245 /* 
246  * Callback function.
247  * Add a space-entry to the value space.
248  */
249 static void fun_addspace(const char *s, void *data, int num)
250 {
251     chrmaptab tab = (chrmaptab) data;
252     tab->input = set_map_string(tab->input, tab->nmem, s, strlen(s),
253                                 (char*) CHR_SPACE, 0);
254 }
255
256 /*
257  * Create a string containing the mapped characters provided.
258  */
259 static void fun_mkstring(const char *s, void *data, int num)
260 {
261     chrwork *arg = (chrwork *) data;
262     const char **res, *p = s;
263
264     res = chr_map_input(arg->map, &s, strlen(s));
265     if (*res == (char*) CHR_UNKNOWN)
266         logf(LOG_WARN, "Map: '%s' has no mapping", p);
267     strncat(arg->string, *res, CHR_MAXSTR - strlen(arg->string));
268     arg->string[CHR_MAXSTR] = '\0';
269 }
270
271 /*
272  * Add a map to the string contained in the argument.
273  */
274 static void fun_add_map(const char *s, void *data, int num)
275 {
276     chrwork *arg = (chrwork *) data;
277
278     assert(arg->map->input);
279     logf (LOG_DEBUG, "set map %.*s", (int) strlen(s), s);
280     set_map_string(arg->map->input, arg->map->nmem, s, strlen(s), arg->string,
281                    0);
282     for (s = arg->string; *s; s++)
283         logf (LOG_DEBUG, " %3d", (unsigned char) *s);
284 }
285
286 /*
287  * Add a query map to the string contained in the argument.
288  */
289 static void fun_add_qmap(const char *s, void *data, int num)
290 {
291     chrwork *arg = (chrwork *) data;
292
293     assert(arg->map->q_input);
294     logf (LOG_DEBUG, "set qmap %.*s", (int) strlen(s), s);
295     set_map_string(arg->map->q_input, arg->map->nmem, s,
296                    strlen(s), arg->string, 0);
297     for (s = arg->string; *s; s++)
298         logf (LOG_DEBUG, " %3d", (unsigned char) *s);
299 }
300
301
302 static int scan_string(char *s,
303                        void (*fun)(const char *c, void *data, int num),
304                        void *data, int *num)
305 {
306     unsigned char c, str[1024], begin, end, *p;
307     
308     while (*s)
309     {
310         switch (*s)
311         {
312         case '{':
313             s++;
314             begin = zebra_prim(&s);
315             if (*s != '-')
316             {
317                 logf(LOG_FATAL, "Bad range in char-map");
318                 return -1;
319             }
320             s++;
321             end = zebra_prim(&s);
322             if (end <= begin)
323             {
324                 logf(LOG_FATAL, "Bad range in char-map");
325                 return -1;
326             }
327             s++;
328             for (c = begin; c <= end; c++)
329             {
330                 str[0] = c; str[1] = '\0';
331                 (*fun)((char *) str, data, num ? (*num)++ : 0);
332             }
333             break;
334         case '[': s++; abort(); break;
335         case '(':
336             p = (unsigned char*) ++s;
337                 /* Find the end-marker, ignoring escapes */
338             do
339             {
340                 if (!(p = (unsigned char*) strchr((char*) p, ')')))
341                 {
342                     logf(LOG_FATAL, "Missing ')' in string");
343                     return -1;
344                 }
345             }
346             while (*(p -  1) == '\\');
347             *p = 0;
348             (*fun)(s, data, num ? (*num)++ : 0);
349             s = (char*) p + 1;
350             break;
351         default:
352             c = zebra_prim(&s);
353             str[0] = c; str[1] = '\0';
354             (*fun)((char *) str, data, num ? (*num)++ : 0);
355         }
356     }
357     return 0;
358 }
359
360 chrmaptab chrmaptab_create(const char *tabpath, const char *name, int map_only,
361                            const char *tabroot)
362 {
363     FILE *f;
364     char line[512], *argv[50];
365     chrmaptab res;
366     int lineno = 0;
367     int errors = 0;
368     int argc, num = (int) *CHR_BASE, i;
369     NMEM nmem;
370
371     logf (LOG_DEBUG, "maptab %s open", name);
372     if (!(f = yaz_fopen(tabpath, name, "r", tabroot)))
373     {
374         logf(LOG_WARN|LOG_ERRNO, "%s", name);
375         return 0;
376     }
377     nmem = nmem_create ();
378     res = (chrmaptab) nmem_malloc(nmem, sizeof(*res));
379     res->nmem = nmem;
380     res->input = (chr_t_entry *) nmem_malloc(res->nmem, sizeof(*res->input));
381     res->input->target = (unsigned char **)
382         nmem_malloc(res->nmem, sizeof(*res->input->target) * 2);
383     res->input->target[0] = (unsigned char*) CHR_UNKNOWN;
384     res->input->target[1] = 0;
385     res->input->children = (chr_t_entry **)
386         nmem_malloc(res->nmem, sizeof(res->input) * 256);
387     for (i = 0; i < 256; i++)
388     {
389         res->input->children[i] = (chr_t_entry *)
390             nmem_malloc(res->nmem, sizeof(*res->input));
391         res->input->children[i]->children = 0;
392         res->input->children[i]->target = (unsigned char **)
393             nmem_malloc (res->nmem, 2 * sizeof(unsigned char *));
394         res->input->children[i]->target[1] = 0;
395         if (map_only)
396         {
397             res->input->children[i]->target[0] = (unsigned char *)
398                 nmem_malloc (res->nmem, 2 * sizeof(unsigned char));
399             res->input->children[i]->target[0][0] = i;
400             res->input->children[i]->target[0][1] = 0;
401         }
402         else
403             res->input->children[i]->target[0] = (unsigned char*) CHR_UNKNOWN;
404     }
405     res->q_input = (chr_t_entry *)
406         nmem_malloc(res->nmem, sizeof(*res->q_input));
407     res->q_input->target = 0;
408     res->q_input->children = 0;
409
410     for (i = *CHR_BASE; i < 256; i++)
411         res->output[i] = 0;
412     res->output[(int) *CHR_SPACE] = (unsigned char *) " ";
413     res->output[(int) *CHR_UNKNOWN] = (unsigned char*) "@";
414     res->base_uppercase = 0;
415
416     while (!errors && (argc = readconf_line(f, &lineno, line, 512, argv, 50)))
417         if (!map_only && !yaz_matchstr(argv[0], "lowercase"))
418         {
419             if (argc != 2)
420             {
421                 logf(LOG_FATAL, "Syntax error in charmap");
422                 ++errors;
423             }
424             if (scan_string(argv[1], fun_addentry, res, &num) < 0)
425             {
426                 logf(LOG_FATAL, "Bad value-set specification");
427                 ++errors;
428             }
429             res->base_uppercase = num;
430             res->output[(int) *CHR_SPACE + num] = (unsigned char *) " ";
431             res->output[(int) *CHR_UNKNOWN + num] = (unsigned char*) "@";
432             num = (int) *CHR_BASE;
433         }
434         else if (!map_only && !yaz_matchstr(argv[0], "uppercase"))
435         {
436             if (!res->base_uppercase)
437             {
438                 logf(LOG_FATAL, "Uppercase directive with no lowercase set");
439                 ++errors;
440             }
441             if (argc != 2)
442             {
443                 logf(LOG_FATAL, "Missing arg for uppercase directive");
444                 ++errors;
445             }
446             if (scan_string(argv[1], fun_addentry, res, &num) < 0)
447             {
448                 logf(LOG_FATAL, "Bad value-set specification");
449                 ++errors;
450             }
451         }
452         else if (!map_only && !yaz_matchstr(argv[0], "space"))
453         {
454             if (argc != 2)
455             {
456                 logf(LOG_FATAL, "Syntax error in charmap");
457                 ++errors;
458             }
459             if (scan_string(argv[1], fun_addspace, res, 0) < 0)
460             {
461                 logf(LOG_FATAL, "Bad space specification");
462                 ++errors;
463             }
464         }
465         else if (!yaz_matchstr(argv[0], "map"))
466         {
467             chrwork buf;
468
469             if (argc != 3)
470             {
471                 logf(LOG_FATAL, "charmap directive map requires 2 args");
472                 ++errors;
473             }
474             buf.map = res;
475             buf.string[0] = '\0';
476             if (scan_string(argv[2], fun_mkstring, &buf, 0) < 0)
477             {
478                 logf(LOG_FATAL, "Bad map target");
479                 ++errors;
480             }
481             if (scan_string(argv[1], fun_add_map, &buf, 0) < 0)
482             {
483                 logf(LOG_FATAL, "Bad map source");
484                 ++errors;
485             }
486         }
487         else if (!yaz_matchstr(argv[0], "qmap"))
488         {
489             chrwork buf;
490
491             if (argc != 3)
492             {
493                 logf(LOG_FATAL, "charmap directive qmap requires 2 args");
494                 ++errors;
495             }
496             buf.map = res;
497             buf.string[0] = '\0';
498             if (scan_string(argv[2], fun_mkstring, &buf, 0) < 0)
499             {
500                 logf(LOG_FATAL, "Bad qmap target");
501                 ++errors;
502             }
503             if (scan_string(argv[1], fun_add_qmap, &buf, 0) < 0)
504             {
505                 logf(LOG_FATAL, "Bad qmap source");
506                 ++errors;
507             }
508         }
509         else
510         {
511             logf(LOG_WARN, "Syntax error at '%s' in %s", line, name);
512         }
513     
514     yaz_fclose(f);
515     if (errors)
516     {
517         chrmaptab_destroy(res);
518         res = 0;
519     }
520     logf (LOG_DEBUG, "maptab %s close %d errors", name, errors);
521     return res;
522 }
523
524 void chrmaptab_destroy(chrmaptab tab)
525 {
526     if (tab)
527         nmem_destroy (tab->nmem);
528 }
529
530