]> git.pond.sub.org Git - empserver/blob - src/lib/common/xundump.c
387c721c0517598a9f3885d2163769d13abf0be9
[empserver] / src / lib / common / xundump.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2011, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                Ken Stevens, Steve McClure, Markus Armbruster
5  *
6  *  Empire is free software: you can redistribute it and/or modify
7  *  it under the terms of the GNU General Public License as published by
8  *  the Free Software Foundation, either version 3 of the License, or
9  *  (at your option) any later version.
10  *
11  *  This program is distributed in the hope that it will be useful,
12  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *  GNU General Public License for more details.
15  *
16  *  You should have received a copy of the GNU General Public License
17  *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  *
19  *  ---
20  *
21  *  See files README, COPYING and CREDITS in the root of the source
22  *  tree for related information and legal notices.  It is expected
23  *  that future projects/authors will amend these files as needed.
24  *
25  *  ---
26  *
27  *  xundump.c: Load back xdump output
28  *
29  *  Known contributors to this file:
30  *     Ron Koenderink, 2005
31  *     Markus Armbruster, 2005-2011
32  */
33
34 /*
35  * See doc/xdump!  And keep it up-to-date.
36  *
37  * Parsing of machine-readable xdump is not precise: it recognizes
38  * comments, accepts whitespace in place of single space, and accepts
39  * the full human-readable field syntax instead of its machine-
40  * readable subset.
41  *
42  * FIXME:
43  * - Normalize terminology: table/rows/columns or file/records/fields
44  * - Loading tables with NSC_STRING elements more than once leaks memory
45  * TODO:
46  * - Check EFF_CFG tables are dense
47  * - Symbolic array indexes
48  * - Option to treat missing and unknown fields as warning, not error
49  * TODO, but hardly worth the effort:
50  * - Permit reordering of array elements
51  */
52
53 #include <config.h>
54
55 #include <ctype.h>
56 #include <stdarg.h>
57 #include <stdio.h>
58 #include <stdlib.h>
59 #include <string.h>
60 #include <time.h>
61 #include "file.h"
62 #include "match.h"
63 #include "nsc.h"
64 #include "optlist.h"
65 #include "xdump.h"
66
67 static char *fname;             /* Name of file being read */
68 static int lineno;              /* Current line number */
69
70 static int cur_type;            /* Current table's file type */
71 static int partno;              /* Counts from 0..#parts-1 */
72 static void *cur_obj;           /* The object being read into */
73 static int cur_id;              /* and its index in the table */
74 static int cur_obj_is_blank;
75 static unsigned char *idgap;    /* idgap && idgap[ID] iff part#0 lacks ID */
76 static int idgap_max;           /* FIXME */
77
78 static int human;               /* Reading human-readable syntax? */
79 static int ellipsis;            /* Header ended with ...? */
80 static int nflds;               /* #fields in input records */
81 static struct castr **fldca;    /* Map field number to selector */
82 static int *fldidx;             /* Map field number to index */
83 static int *caflds;             /* Map selector number to #fields seen */
84 static int *cafldspp;           /* ditto, in previous parts */
85 static int may_omit_id;         /* Okay to omit IDs? */
86 static int may_trunc;           /* Okay to truncate? */
87
88 static int gripe(char *, ...) ATTRIBUTE((format (printf, 1, 2)));
89 static int deffld(int, char *, int);
90 static int defellipsis(void);
91 static int chkflds(void);
92 static int setnum(int, double);
93 static int setstr(int, char *);
94 static int xunsymbol(char *, struct castr *, int);
95 static int setsym(int, char *);
96 static int mtsymset(int, long *);
97 static int add2symset(int, long *, char *);
98 static int xubody(FILE *);
99 static int xutail(FILE *, struct castr *);
100
101 /*
102  * Gripe about the current line to stderr, return -1.
103  */
104 static int
105 gripe(char *fmt, ...)
106 {
107     va_list ap;
108
109     fprintf(stderr, "%s:%d: ", fname, lineno);
110     va_start(ap, fmt);
111     vfprintf(stderr, fmt, ap);
112     va_end(ap);
113     putc('\n', stderr);
114
115     return -1;
116 }
117
118 /* Make TYPE the current table.  */
119 static void
120 tbl_start(int type)
121 {
122     cur_type = type;
123     partno = 0;
124     cur_id = -1;
125     cur_obj = NULL;
126     idgap = NULL;
127     idgap_max = 0;
128 }
129
130 /* End the current table.  */
131 static void
132 tbl_end(void)
133 {
134     free(idgap);
135     tbl_start(EF_BAD);
136 }
137
138 /*
139  * Seek to current table's ID-th record.
140  * ID must be acceptable.
141  * Store it in cur_obj, and set cur_id and cur_obj_is_blank accordingly.
142  * Return 0 on success, -1 on failure.
143  */
144 static int
145 tbl_seek(int id)
146 {
147     struct empfile *ep = &empfile[cur_type];
148
149     cur_obj_is_blank = id >= ep->fids;
150
151     if (id >= ef_nelem(cur_type)) {
152         if (!ef_ensure_space(cur_type, id, 1))
153             return gripe("Can't put ID %d into table %s", id, ep->name);
154     }
155
156     cur_obj = ef_ptr(cur_type, id);
157     if (CANT_HAPPEN(!cur_obj))
158         return -1;
159     cur_id = id;
160     return 0;
161 }
162
163 /*
164  * Get the next object.
165  * Must not have a record index.
166  * Store it in cur_obj, and set cur_id and cur_obj_is_blank accordingly.
167  * Return 0 on success, -1 on failure.
168  */
169 static int
170 tbl_next_obj(void)
171 {
172     int max_id = ef_id_limit(cur_type);
173
174     if (cur_id >= max_id)
175         return gripe("Too many rows");
176     return tbl_seek(cur_id + 1);
177 }
178
179 /*
180  * Omit ID1..ID2-1.
181  */
182 static void
183 omit_ids(int id1, int id2)
184 {
185     int i;
186
187     if (id1 >= id2)
188         return;
189
190     idgap = realloc(idgap, (id2 + 1) * sizeof(*idgap));
191     for (i = idgap_max; i < id1; i++)
192         idgap[i] = 0;
193     for (i = id1; i < id2; i++)
194         idgap[i] = 1;
195     idgap[id2] = 0;
196     idgap_max = id2;
197 }
198
199 /*
200  * Return the smallest non-omitted ID in ID1..ID2-1 if any, else -1.
201  */
202 static int
203 expected_id(int id1, int id2)
204 {
205     int i;
206
207     for (i = id1; i < id2; i++) {
208         if (i >= idgap_max || !idgap[i])
209             return i;
210     }
211     return -1;
212 }
213
214 /*
215  * Get the next object, it has record index ID.
216  * Store it in cur_obj, and set cur_id and cur_obj_is_blank accordingly.
217  * Ensure we're omitting the same objects as the previous parts.
218  * Return 0 on success, -1 on failure.
219  */
220 static int
221 tbl_skip_to_obj(int id)
222 {
223     struct empfile *ep = &empfile[cur_type];
224     int prev_id = cur_id;
225     int max_id, exp_id;
226
227     if (partno == 0) {
228         if (!may_omit_id && id != cur_id + 1)
229             return gripe("Expected %d in field %d", cur_id + 1, 1);
230         if (id <= cur_id)
231             return gripe("Field %d must be > %d", 1, cur_id);
232         max_id = ef_id_limit(cur_type);
233         if (id > max_id)
234             return gripe("Field %d must be <= %d", 1, max_id);
235     } else {
236         exp_id = expected_id(cur_id + 1, ep->fids);
237         if (exp_id < 0)
238             return gripe("Table's first part doesn't have this row");
239         else if (id != exp_id)
240             return gripe("Expected %d in field %d,"
241                          " like in table's first part",
242                          exp_id, 1);
243     }
244
245     if (tbl_seek(id) < 0)
246         return -1;
247
248     if (partno == 0)
249         omit_ids(prev_id + 1, id);
250     return 0;
251 }
252
253 /*
254  * Finish table part.
255  * If the table has variable length, truncate it.
256  * Else ensure we're omitting the same objects as the previous parts.
257  * Return 0 on success, -1 on failure.
258  */
259 static int
260 tbl_part_done(void)
261 {
262     struct empfile *ep = &empfile[cur_type];
263     int exp_id;
264
265     if (cur_id + 1 < ep->fids) {
266         if (partno == 0) {
267             if (may_trunc) {
268                 if (!ef_truncate(cur_type, cur_id + 1))
269                     return -1;
270             } else {
271                 if (!may_omit_id)
272                     return gripe("Expected %d more rows",
273                                  ep->fids - (cur_id + 1));
274                 omit_ids(cur_id + 1, ep->fids);
275             }
276         } else {
277             exp_id = expected_id(cur_id + 1, ep->fids);
278             if (exp_id >= 0)
279                 return gripe("Expected row with %d in field %d,"
280                              " like in table's first part",
281                              exp_id, 1);
282         }
283     }
284
285     partno++;
286     cur_id = -1;
287     cur_obj = NULL;
288     return 0;
289 }
290
291 /*
292  * Read and ignore field separators from FP.
293  * Return first character that is not a field separator.
294  */
295 static int
296 skipfs(FILE *fp)
297 {
298     int ch;
299
300     do {
301         ch = getc(fp);
302     } while (ch == ' ' || ch == '\t');
303
304     if (ch == '#') {
305         do {
306             ch = getc(fp);
307         } while (ch != EOF && ch != '\n');
308     }
309
310     return ch;
311 }
312
313 /*
314  * Decode escape sequences in BUF.
315  * Return BUF on success, null pointer on failure.
316  */
317 static char *
318 xuesc(char *buf)
319 {
320     char *src, *dst;
321     int octal_chr, n;
322
323     dst = buf;
324     src = buf;
325     while (*src) {
326         if (*src == '\\') {
327             if (sscanf(++src, "%3o%n", &octal_chr, &n) != 1 || n != 3)
328                 return NULL;
329             *dst++ = (char)octal_chr;
330             src += 3;
331         } else
332             *dst++ = *src++;
333     }
334     *dst = '\0';
335     return buf;
336 }
337
338 /*
339  * Read an identifier from FP into BUF.
340  * BUF must have space for 1024 characters.
341  * Return number of characters read on success, -1 on failure.
342  */
343 static int
344 getid(FILE *fp, char *buf)
345 {
346     int n;
347     if (fscanf(fp, "%1023[^\"#()<>= \t\n]%n", buf, &n) != 1
348         || !isalpha(buf[0]))
349         return -1;
350     xuesc(buf);
351     return n;
352 }
353
354 /*
355  * Try to read a field name from FP.
356  * I is the field number, counting from zero.
357  * If a name is read, set fldca[I] and fldidx[I] for it, and update
358  * caflds[].
359  * Return 1 if a name or ... was read, 0 on end of line, -1 on error.
360  */
361 static int
362 xufldname(FILE *fp, int i)
363 {
364     int ch, idx;
365     char buf[1024];
366
367     ch = skipfs(fp);
368     switch (ch) {
369     case EOF:
370         return gripe("Unexpected EOF");
371     case '\n':
372         if (chkflds() < 0)
373             return -1;
374         lineno++;
375         return 0;
376     case '.':
377         if (getc(fp) != '.' || getc(fp) != '.')
378             return gripe("Junk in header field %d", i + 1);
379         if (defellipsis() < 0)
380             return -1;
381         ch = skipfs(fp);
382         if (ch != EOF && ch != '\n')
383             return gripe("Junk after ...");
384         ungetc(ch, fp);
385         return 1;
386     default:
387         ungetc(ch, fp);
388         if (getid(fp, buf) < 0)
389             return gripe("Junk in header field %d", i + 1);
390         ch = getc(fp);
391         if (ch != '(') {
392             ungetc(ch, fp);
393             return deffld(i, buf, -1);
394         }
395         ch = getc(fp);
396         ungetc(ch, fp);
397         if (isdigit(ch) || ch == '-' || ch == '+') {
398             if (fscanf(fp, "%d", &idx) != 1)
399                 return gripe("Malformed number in index of header field %d",
400                              i + 1);
401             if (idx < 0)
402                 return gripe("Index must not be negative in header field %d",
403                              i + 1);
404         } else {
405             if (getid(fp, buf) < 0)
406                 return gripe("Malformed index in header field %d", i + 1);
407             return gripe("Symbolic index in header field %d not yet implemented",
408                          i + 1);
409         }
410         ch = getc(fp);
411         if (ch != ')')
412             return gripe("Malformed index in header field %d", i + 1);
413         return deffld(i, buf, idx);
414     }
415 }
416
417 /*
418  * Try to read a field value from FP.
419  * I is the field number, counting from zero.
420  * Return 1 if a value was read, 0 on end of line, -1 on error.
421  */
422 static int
423 xufld(FILE *fp, int i)
424 {
425     int ch;
426     char buf[1024];
427     double dbl;
428     long set;
429
430     ch = skipfs(fp);
431     switch (ch) {
432     case EOF:
433         return gripe("Unexpected EOF");
434     case '\n':
435         CANT_HAPPEN(i > nflds);
436         if (i < nflds) {
437             if (fldca[i]->ca_type != NSC_STRINGY && fldca[i]->ca_len)
438                 return gripe("Field %s(%d) missing",
439                              fldca[i]->ca_name, fldidx[i]);
440             return gripe("Field %s missing", fldca[i]->ca_name);
441         }
442         lineno++;
443         return 0;
444     case '+': case '-': case '.':
445     case '0': case '1': case '2': case '3': case '4':
446     case '5': case '6': case '7': case '8': case '9':
447         ungetc(ch, fp);
448         if (fscanf(fp, "%lg", &dbl) != 1)
449             return gripe("Malformed number in field %d", i + 1);
450         return setnum(i, dbl);
451     case '"':
452         ch = getc(fp);
453         if (ch == '"')
454             buf[0] = 0;
455         else {
456             ungetc(ch, fp);
457             if (fscanf(fp, "%1023[^\"\n]", buf) != 1 || getc(fp) != '"')
458                 return gripe("Malformed string in field %d", i + 1);
459             if (!xuesc(buf))
460                 return gripe("Invalid escape sequence in field %d",
461                              i + 1);
462         }
463         return setstr(i, buf);
464     case '(':
465         if (mtsymset(i, &set) < 0)
466             return -1;
467         for (;;) {
468             ch = skipfs(fp);
469             if (ch == EOF || ch == '\n')
470                 return gripe("Unmatched '(' in field %d", i + 1);
471             if (ch == ')')
472                 break;
473             ungetc(ch, fp);
474             if (getid(fp, buf) < 0)
475                 return gripe("Junk in field %d", i + 1);
476             if (add2symset(i, &set, buf) < 0)
477                 return -1;
478         }
479         return setnum(i, set);
480     default:
481         ungetc(ch, fp);
482         if (getid(fp, buf) < 0)
483             return gripe("Junk in field %d", i + 1);
484         if (!strcmp(buf, "nil"))
485             return setstr(i, NULL);
486         else
487             return setsym(i, buf);
488     }
489 }
490
491 /*
492  * Read fields from FP.
493  * Use PARSE() to read each field.
494  * Return number of fields read on success, -1 on error.
495  */
496 static int
497 xuflds(FILE *fp, int (*parse)(FILE *, int))
498 {
499     int i, ch, res;
500
501     for (i = 0; ; i++) {
502         res = parse(fp, i);
503         if (res < 0)
504             return -1;
505         if (res == 0)
506             return i;
507         ch = getc(fp);
508         if (ch == '\n')
509             ungetc(ch, fp);
510         else if (ch != ' ' && ch != '\t')
511             return gripe("Bad field separator after field %d", i + 1);
512     }
513 }
514
515 /*
516  * Define the FLDNO-th field.
517  * If IDX is negative, define as selector NAME, else as NAME(IDX).
518  * Set fldca[FLDNO] and fldidx[FLDNO] accordingly.
519  * Update caflds[].
520  * Return 1 on success, -1 on error.
521  */
522 static int
523 deffld(int fldno, char *name, int idx)
524 {
525     struct castr *ca = ef_cadef(cur_type);
526     int res;
527
528     res = stmtch(name, ca, offsetof(struct castr, ca_name),
529                  sizeof(struct castr));
530     if (res < 0)
531         return gripe("Header %s of field %d is %s", name, fldno + 1,
532                      res == M_NOTUNIQUE ? "ambiguous" : "unknown");
533     if ((ca[res].ca_flags & NSC_EXTRA) || CANT_HAPPEN(ca[res].ca_get))
534         return gripe("Extraneous header %s in field %d", name, fldno + 1);
535     if (ca[res].ca_type != NSC_STRINGY && ca[res].ca_len != 0) {
536         if (idx < 0)
537             return gripe("Header %s requires an index in field %d",
538                          ca[res].ca_name, fldno + 1);
539         if (idx >= ca[res].ca_len)
540             return gripe("Header %s(%d) index out of bounds in field %d",
541                          ca[res].ca_name, idx, fldno + 1);
542         if (idx < caflds[res])
543             return gripe("Duplicate header %s(%d) in field %d",
544                          ca[res].ca_name, idx, fldno + 1);
545         if (idx > caflds[res])
546             return gripe("Expected header %s(%d) in field %d",
547                          ca[res].ca_name, caflds[res], fldno + 1);
548     } else {
549         if (idx >= 0)
550             return gripe("Header %s doesn't take an index in field %d",
551                          ca[res].ca_name, fldno + 1);
552         idx = 0;
553         if (caflds[res])
554             return gripe("Duplicate header %s in field %d",
555                          ca[res].ca_name, fldno + 1);
556     }
557     fldca[fldno] = &ca[res];
558     fldidx[fldno] = idx;
559     caflds[res]++;
560     return 1;
561 }
562
563 /*
564  * Record that header ends with ...
565  * Set ellipsis and is_partial.
566  * Return 0 on success, -1 on error.
567  */
568 static int
569 defellipsis(void)
570 {
571     struct castr *ca = ef_cadef(cur_type);
572
573     if (ca[0].ca_table != cur_type || (ca[0].ca_flags & NSC_EXTRA))
574         return gripe("Table %s doesn't support ...", ef_nameof(cur_type));
575     ellipsis = 1;
576     return 0;
577 }
578
579 /* Is table split into parts? */
580 static int
581 is_partial(void)
582 {
583     return ellipsis || partno;
584 }
585
586 /*
587  * Check fields in xdump are sane.
588  * Return 0 on success, -1 on error.
589  */
590 static int
591 chkflds(void)
592 {
593     struct castr *ca = ef_cadef(cur_type);
594     int i, len, cafldsmax, res = 0;
595
596     /* Record index must come first, to make cur_id work, see setnum() */
597     if (ca[0].ca_table == cur_type && caflds[0] && fldca[0] != &ca[0])
598         res = gripe("Header field %s must come first", ca[0].ca_name);
599
600     if (is_partial()) {
601         /* Need a join field, use 0-th selector */
602         if (!caflds[0])
603             res = gripe("Header field %s required in each table part",
604                         ca[0].ca_name);
605     }
606
607     if (ellipsis)
608         return res;             /* table is split, another part expected */
609
610     /* Check for missing fields */
611     for (i = 0; ca[i].ca_name; i++) {
612         cafldsmax = MAX(caflds[i], cafldspp[i]);
613         if (ca[i].ca_flags & NSC_EXTRA)
614             continue;
615         len = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
616         if (!len && !cafldsmax)
617             res = gripe("Header field %s missing", ca[i].ca_name);
618         else if (len && cafldsmax == len - 1)
619             res = gripe("Header field %s(%d) missing",
620                         ca[i].ca_name, len - 1);
621         else if (len && cafldsmax < len - 1)
622             res = gripe("Header fields %s(%d) ... %s(%d) missing",
623                         ca[i].ca_name, cafldsmax, ca[i].ca_name, len - 1);
624     }
625
626     return res;
627 }
628
629 /*
630  * Get selector for field FLDNO.
631  * Assign the field's selector index to *IDX, unless it is null.
632  * Return the selector on success, null pointer on error.
633  */
634 static struct castr *
635 getfld(int fldno, int *idx)
636 {
637     if (fldno >= nflds) {
638         gripe("Too many fields, expected only %d", nflds);
639         return NULL;
640     }
641     if (CANT_HAPPEN(fldno < 0))
642         return NULL;
643     if (idx)
644         *idx = fldidx[fldno];
645     return fldca[fldno];
646 }
647
648 /*
649  * Is a new value for field FLDNO required to match the old one?
650  */
651 static int
652 fldval_must_match(int fldno)
653 {
654     struct castr *ca = ef_cadef(cur_type);
655     int i = fldca[fldno] - ca;
656
657     /*
658      * Value must match if:
659      * it's for a const selector, unless the object is still blank, or
660      * it was already given in a previous part of a split table.
661      */
662     return (!cur_obj_is_blank && (fldca[fldno]->ca_flags & NSC_CONST))
663         || fldidx[fldno] < cafldspp[i];
664 }
665
666 /*
667  * Set value of field FLDNO in current object to DBL.
668  * Return 1 on success, -1 on error.
669  */
670 static int
671 setnum(int fldno, double dbl)
672 {
673     struct castr *ca;
674     int next_id, idx;
675     char *memb_ptr;
676     double old, new;
677
678     ca = getfld(fldno, &idx);
679     if (!ca)
680         return -1;
681
682     if (fldno == 0) {
683         if (ca->ca_table == cur_type) {
684             /* Got record index */
685             next_id = (int)dbl;
686             if (next_id != dbl)
687                 return gripe("Field %d can't hold this value", fldno + 1);
688             if (tbl_skip_to_obj(next_id) < 0)
689                 return -1;
690         } else {
691             if (tbl_next_obj() < 0)
692                 return -1;
693         }
694     }
695     memb_ptr = cur_obj;
696     memb_ptr += ca->ca_off;
697
698     switch (ca->ca_type) {
699     case NSC_CHAR:
700         old = ((signed char *)memb_ptr)[idx];
701         new = ((signed char *)memb_ptr)[idx] = (signed char)dbl;
702         break;
703     case NSC_UCHAR:
704     case NSC_HIDDEN:
705         old = ((unsigned char *)memb_ptr)[idx];
706         new = ((unsigned char *)memb_ptr)[idx] = (unsigned char)dbl;
707         break;
708     case NSC_SHORT:
709         old = ((short *)memb_ptr)[idx];
710         new = ((short *)memb_ptr)[idx] = (short)dbl;
711         break;
712     case NSC_USHORT:
713         old = ((unsigned short *)memb_ptr)[idx];
714         new = ((unsigned short *)memb_ptr)[idx] = (unsigned short)dbl;
715         break;
716     case NSC_INT:
717         old = ((int *)memb_ptr)[idx];
718         new = ((int *)memb_ptr)[idx] = (int)dbl;
719         break;
720     case NSC_LONG:
721         old = ((long *)memb_ptr)[idx];
722         new = ((long *)memb_ptr)[idx] = (long)dbl;
723         break;
724     case NSC_XCOORD:
725         old = ((coord *)memb_ptr)[idx];
726         /* FIXME use variant of xrel() that takes orig instead of nation */
727         if (old >= WORLD_X / 2)
728             old -= WORLD_X;
729         new = ((coord *)memb_ptr)[idx] = XNORM((coord)dbl);
730         if (new >= WORLD_X / 2)
731             new -= WORLD_X;
732         break;
733     case NSC_YCOORD:
734         old = ((coord *)memb_ptr)[idx];
735         /* FIXME use variant of yrel() that takes orig instead of nation */
736         if (old >= WORLD_Y / 2)
737             old -= WORLD_Y;
738         new = ((coord *)memb_ptr)[idx] = YNORM((coord)dbl);
739         if (new >= WORLD_Y / 2)
740             new -= WORLD_Y;
741         break;
742     case NSC_FLOAT:
743         old = ((float *)memb_ptr)[idx];
744         ((float *)memb_ptr)[idx] = (float)dbl;
745         new = dbl;              /* suppress new != dbl check */
746         break;
747     case NSC_DOUBLE:
748         old = ((double *)memb_ptr)[idx];
749         ((double *)memb_ptr)[idx] = dbl;
750         new = dbl;              /* suppress new != dbl check */
751         break;
752     case NSC_TIME:
753         old = ((time_t *)memb_ptr)[idx];
754         new = ((time_t *)memb_ptr)[idx] = (time_t)dbl;
755         break;
756     default:
757         return gripe("Field %d doesn't take numbers", fldno + 1);
758     }
759
760     if (fldval_must_match(fldno) && old != dbl)
761         return gripe("Value for field %d must be %g", fldno + 1, old);
762     if (new != dbl)
763         return gripe("Field %d can't hold this value", fldno + 1);
764
765     return 1;
766 }
767
768 /*
769  * Set value of field FLDNO in current object to STR.
770  * Return 1 on success, -1 on error.
771  */
772 static int
773 setstr(int fldno, char *str)
774 {
775     struct castr *ca;
776     int must_match, idx;
777     size_t len;
778     char *memb_ptr, *old;
779
780     ca = getfld(fldno, &idx);
781     if (!ca)
782         return -1;
783
784     if (fldno == 0) {
785         if (tbl_next_obj() < 0)
786             return -1;
787     }
788     memb_ptr = cur_obj;
789     memb_ptr += ca->ca_off;
790     must_match = fldval_must_match(fldno);
791
792     switch (ca->ca_type) {
793     case NSC_STRING:
794         old = ((char **)memb_ptr)[idx];
795         if (!must_match)
796             /* FIXME may leak old value */
797             ((char **)memb_ptr)[idx] = str ? strdup(str) : NULL;
798         len = 65535;            /* really SIZE_MAX, but that's C99 */
799         break;
800     case NSC_STRINGY:
801         if (CANT_HAPPEN(idx))
802             return -1;
803         if (!str)
804             return gripe("Field %d doesn't take nil", fldno + 1);
805         len = ca->ca_len;
806         if (strlen(str) > len)
807             return gripe("Field %d takes at most %d characters",
808                          fldno + 1, (int)len);
809         old = memb_ptr;
810         if (!must_match)
811             strncpy(memb_ptr, str, len);
812         break;
813     default:
814         return gripe("Field %d doesn't take strings", fldno + 1);
815     }
816
817     if (must_match) {
818         if (old && (!str || strncmp(old, str, len)))
819             return gripe("Value for field %d must be \"%.*s\"",
820                          fldno + 1, (int)len, old);
821         if (!old && str)
822             return gripe("Value for field %d must be nil", fldno + 1);
823     }
824
825     return 1;
826 }
827
828 /*
829  * Resolve symbol name ID in table referred to by CA.
830  * Use field number N for error messages.
831  * Return index in referred table on success, -1 on failure.
832  */
833 static int
834 xunsymbol(char *id, struct castr *ca, int n)
835 {
836     int i = ef_elt_byname(ca->ca_table, id);
837     if (i < 0)
838         return gripe("%s %s symbol `%s' in field %d",
839                      i == M_NOTUNIQUE ? "Ambiguous" : "Unknown",
840                      ca->ca_name, id, n + 1);
841     return i;
842 }
843
844 /*
845  * Map symbol index to symbol value.
846  * CA is the table, and I is the index in it.
847  */
848 static int
849 symval(struct castr *ca, int i)
850 {
851     int type = ca->ca_table;
852
853     if (type != EF_BAD && ef_cadef(type) == symbol_ca)
854         /* symbol table, value is in the table */
855         return ((struct symbol *)ef_ptr(type, i))->value;
856     /* value is the table index */
857     return i;
858 }
859
860 /*
861  * Set value of field FLDNO in current object to value of symbol SYM.
862  * Return 1 on success, -1 on error.
863  */
864 static int
865 setsym(int fldno, char *sym)
866 {
867     struct castr *ca;
868     int i;
869
870     ca = getfld(fldno, NULL);
871     if (!ca)
872         return -1;
873
874     if (ca->ca_table == EF_BAD || (ca->ca_flags & NSC_BITS))
875         return gripe("Field %d doesn't take symbols", fldno + 1);
876
877     i = xunsymbol(sym, ca, fldno);
878     if (i < 0)
879         return -1;
880     return setnum(fldno, symval(ca, i));
881 }
882
883 /*
884  * Create an empty symbol set for field FLDNO in *SET.
885  * Return 1 on success, -1 on error.
886  */
887 static int
888 mtsymset(int fldno, long *set)
889 {
890     struct castr *ca;
891
892     ca = getfld(fldno, NULL);
893     if (!ca)
894         return -1;
895
896     if (ca->ca_table == EF_BAD || ef_cadef(ca->ca_table) != symbol_ca
897         || !(ca->ca_flags & NSC_BITS))
898         return gripe("Field %d doesn't take symbol sets", fldno + 1);
899     *set = 0;
900     return 0;
901 }
902
903 /*
904  * Add a symbol to a symbol set for field FLDNO in *SET.
905  * SYM is the name of the symbol to add.
906  * Return 1 on success, -1 on error.
907  */
908 static int
909 add2symset(int fldno, long *set, char *sym)
910 {
911     struct castr *ca;
912     int i;
913
914     ca = getfld(fldno, NULL);
915     if (!ca)
916         return -1;
917
918     i = xunsymbol(sym, ca, fldno);
919     if (i < 0)
920         return -1;
921     *set |= symval(ca, i);
922     return 0;
923 }
924
925 /*
926  * Read an xdump table header line from FP.
927  * Expect header for EXPECTED_TABLE, unless it is EF_BAD.
928  * Recognize header for machine- and human-readable syntax, and set
929  * human accordingly.
930  * Return table type on success, -2 on EOF before header, -1 on failure.
931  */
932 static int
933 xuheader(FILE *fp, int expected_table)
934 {
935     char name[64];
936     int res, ch;
937     int type;
938
939     while ((ch = skipfs(fp)) == '\n')
940         lineno++;
941     if (ch == EOF && expected_table == EF_BAD)
942         return -2;
943     ungetc(ch, fp);
944
945     human = ch == 'c';
946     res = -1;
947     if ((human
948          ? fscanf(fp, "config%*[ \t]%63[^ \t#\n]%n", name, &res) != 1
949          : fscanf(fp, "XDUMP%*[ \t]%63[^ \t#\n]%*[ \t]%*[^ \t#\n]%n",
950                   name, &res) != 1) || res < 0)
951         return gripe("Expected xdump header");
952
953     type = ef_byname(name);
954     if (type < 0)
955         return gripe("Unknown table `%s'", name);
956     if (expected_table != EF_BAD && expected_table != type)
957         return gripe("Expected table `%s', not `%s'",
958                      ef_nameof(expected_table), name);
959
960     if (!empfile[type].file
961         || !ef_cadef(type) || !(ef_flags(type) & EFF_MEM)) {
962         CANT_HAPPEN(expected_table != EF_BAD);
963         return gripe("Table `%s' is not permitted here", name);
964     }
965
966     if (skipfs(fp) != '\n')
967         return gripe("Junk after xdump header");
968     lineno++;
969
970     return type;
971 }
972
973 /*
974  * Find fields in this xdump.
975  * If reading human-readable syntax, read a field header line from FP.
976  * Else take fields from the table's selectors in CA[].
977  * Set ellipsis, nflds, fldca[], fldidx[] and caflds[] accordingly.
978  * Return 0 on success, -1 on failure.
979  */
980 static int
981 xufldhdr(FILE *fp, struct castr ca[])
982 {
983     struct castr **fca;
984     int *fidx;
985     int ch, i, j, n;
986
987     for (i = 0; ca[i].ca_name; i++)
988         caflds[i] = 0;
989     ellipsis = 0;
990
991     if (human) {
992         while ((ch = skipfs(fp)) == '\n')
993             lineno++;
994         ungetc(ch, fp);
995         nflds = xuflds(fp, xufldname);
996         if (nflds < 0)
997             return -1;
998         nflds -= ellipsis != 0;
999     } else {
1000         fca = fldca;
1001         fidx = fldidx;
1002
1003         for (i = 0; ca[i].ca_name; i++) {
1004             if ((ca[i].ca_flags & NSC_EXTRA))
1005                 continue;
1006             n = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
1007             j = 0;
1008             do {
1009                 *fca++ = &ca[i];
1010                 *fidx++ = j;
1011             } while (++j < n);
1012         }
1013
1014         nflds = fidx - fldidx;
1015     }
1016
1017     return 0;
1018 }
1019
1020 /*
1021  * Read xdump footer from FP.
1022  * CA[] contains the table's selectors.
1023  * The body had RECS records.
1024  * Update cafldspp[] from caflds[].
1025  * Return 0 on success, -1 on failure.
1026  */
1027 static int
1028 xufooter(FILE *fp, struct castr ca[], int recs)
1029 {
1030     int res, n, i;
1031
1032     res = -1;
1033     if (human) {
1034         if (fscanf(fp, "config%n", &res) != 0 || res < 0)
1035             return gripe("Malformed table footer");
1036     } else {
1037         if (fscanf(fp, "%d", &n) != 1)
1038             return gripe("Malformed table footer");
1039         if (recs != n)
1040             return gripe("Read %d rows, which doesn't match footer "
1041                          "%d rows", recs, n);
1042     }
1043     if (skipfs(fp) != '\n')
1044         return gripe("Junk after table footer");
1045     if (tbl_part_done() < 0)
1046         return -1;
1047     lineno++;
1048
1049     for (i = 0; ca[i].ca_name; i++) {
1050         if (cafldspp[i] < caflds[i])
1051             cafldspp[i] = caflds[i];
1052     }
1053
1054     return 0;
1055 }
1056
1057 /*
1058  * Read an xdump table from FP.
1059  * Both machine- and human-readable xdump syntax are recognized.
1060  * Expect table EXPECTED_TABLE, unless it is EF_BAD.
1061  * Report errors to stderr.
1062  * Messages assume FP starts in the file FILE at line *PLNO.
1063  * Update *PLNO to reflect lines read from FP.
1064  * Return table type on success, -2 on EOF before header, -1 on failure.
1065  */
1066 int
1067 xundump(FILE *fp, char *file, int *plno, int expected_table)
1068 {
1069     struct castr *ca;
1070     int type, nca, nf, i, ch;
1071
1072     fname = file;
1073     lineno = *plno;
1074
1075     if ((type = xuheader(fp, expected_table)) < 0)
1076         return type;
1077
1078     ca = ef_cadef(type);
1079     if (CANT_HAPPEN(!ca))
1080         return -1;
1081
1082     nca = nf = 0;
1083     may_omit_id = 1;
1084     may_trunc = empfile[type].nent < 0;
1085     for (i = 0; ca[i].ca_name; i++) {
1086         nca++;
1087         if (!(ca[i].ca_flags & NSC_EXTRA)) {
1088             nf += MAX(1, ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0);
1089             if (ca[i].ca_flags & NSC_CONST)
1090                 may_omit_id = may_trunc = 0;
1091         }
1092     }
1093     fldca = malloc(nf * sizeof(*fldca));
1094     fldidx = malloc(nf * sizeof(*fldidx));
1095     caflds = malloc(nca * sizeof(*caflds));
1096     cafldspp = calloc(nca, sizeof(*cafldspp));
1097
1098     tbl_start(type);
1099     if (xutail(fp, ca) < 0)
1100         type = EF_BAD;
1101     tbl_end();
1102
1103     free(cafldspp);
1104     free(caflds);
1105     free(fldidx);
1106     free(fldca);
1107
1108     /* Skip empty lines so that callers can easily check for EOF */
1109     while ((ch = skipfs(fp)) == '\n')
1110         lineno++;
1111     ungetc(ch, fp);
1112
1113     *plno = lineno;
1114     return type;
1115 }
1116
1117 /*
1118  * Read the remainder of an xdump after the table header line from FP.
1119  * CA[] contains the table's selectors.
1120  * Return 0 on success, -1 on failure.
1121  */
1122 static int
1123 xutail(FILE *fp, struct castr *ca)
1124 {
1125     int recs;
1126
1127     for (;;) {
1128         if (xufldhdr(fp, ca) < 0)
1129             return -1;
1130         if ((recs = xubody(fp)) < 0)
1131             return -1;
1132         if (xufooter(fp, ca, recs) < 0)
1133             return -1;
1134         if (!ellipsis)
1135             return 0;
1136         if (xuheader(fp, cur_type) < 0)
1137             return -1;
1138     }
1139 }
1140
1141 /*
1142  * Read the body of an xdump table from FP.
1143  * Return number of rows read on success, -1 on failure.
1144  */
1145 static int
1146 xubody(FILE *fp)
1147 {
1148     int i, ch;
1149
1150     for (i = 0;; ++i) {
1151         while ((ch = skipfs(fp)) == '\n')
1152             lineno++;
1153         if (ch == '/')
1154             break;
1155         ungetc(ch, fp);
1156         if (xuflds(fp, xufld) < 0)
1157             return -1;
1158     }
1159     return i;
1160 }