]> git.pond.sub.org Git - empserver/blob - src/lib/common/xundump.c
Forbid omitting rows in config item and sect-chr
[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                 return gripe("Expected %d more rows",
272                              ep->fids - (cur_id + 1));
273             }
274         } else {
275             exp_id = expected_id(cur_id + 1, ep->fids);
276             if (exp_id >= 0)
277                 return gripe("Expected row with %d in field %d,"
278                              " like in table's first part",
279                              exp_id, 1);
280         }
281     }
282
283     partno++;
284     cur_id = -1;
285     cur_obj = NULL;
286     return 0;
287 }
288
289 /*
290  * Read and ignore field separators from FP.
291  * Return first character that is not a field separator.
292  */
293 static int
294 skipfs(FILE *fp)
295 {
296     int ch;
297
298     do {
299         ch = getc(fp);
300     } while (ch == ' ' || ch == '\t');
301
302     if (ch == '#') {
303         do {
304             ch = getc(fp);
305         } while (ch != EOF && ch != '\n');
306     }
307
308     return ch;
309 }
310
311 /*
312  * Decode escape sequences in BUF.
313  * Return BUF on success, null pointer on failure.
314  */
315 static char *
316 xuesc(char *buf)
317 {
318     char *src, *dst;
319     int octal_chr, n;
320
321     dst = buf;
322     src = buf;
323     while (*src) {
324         if (*src == '\\') {
325             if (sscanf(++src, "%3o%n", &octal_chr, &n) != 1 || n != 3)
326                 return NULL;
327             *dst++ = (char)octal_chr;
328             src += 3;
329         } else
330             *dst++ = *src++;
331     }
332     *dst = '\0';
333     return buf;
334 }
335
336 /*
337  * Read an identifier from FP into BUF.
338  * BUF must have space for 1024 characters.
339  * Return number of characters read on success, -1 on failure.
340  */
341 static int
342 getid(FILE *fp, char *buf)
343 {
344     int n;
345     if (fscanf(fp, "%1023[^\"#()<>= \t\n]%n", buf, &n) != 1
346         || !isalpha(buf[0]))
347         return -1;
348     xuesc(buf);
349     return n;
350 }
351
352 /*
353  * Try to read a field name from FP.
354  * I is the field number, counting from zero.
355  * If a name is read, set fldca[I] and fldidx[I] for it, and update
356  * caflds[].
357  * Return 1 if a name or ... was read, 0 on end of line, -1 on error.
358  */
359 static int
360 xufldname(FILE *fp, int i)
361 {
362     int ch, idx;
363     char buf[1024];
364
365     ch = skipfs(fp);
366     switch (ch) {
367     case EOF:
368         return gripe("Unexpected EOF");
369     case '\n':
370         if (chkflds() < 0)
371             return -1;
372         lineno++;
373         return 0;
374     case '.':
375         if (getc(fp) != '.' || getc(fp) != '.')
376             return gripe("Junk in header field %d", i + 1);
377         if (defellipsis() < 0)
378             return -1;
379         ch = skipfs(fp);
380         if (ch != EOF && ch != '\n')
381             return gripe("Junk after ...");
382         ungetc(ch, fp);
383         return 1;
384     default:
385         ungetc(ch, fp);
386         if (getid(fp, buf) < 0)
387             return gripe("Junk in header field %d", i + 1);
388         ch = getc(fp);
389         if (ch != '(') {
390             ungetc(ch, fp);
391             return deffld(i, buf, -1);
392         }
393         ch = getc(fp);
394         ungetc(ch, fp);
395         if (isdigit(ch) || ch == '-' || ch == '+') {
396             if (fscanf(fp, "%d", &idx) != 1)
397                 return gripe("Malformed number in index of header field %d",
398                              i + 1);
399             if (idx < 0)
400                 return gripe("Index must not be negative in header field %d",
401                              i + 1);
402         } else {
403             if (getid(fp, buf) < 0)
404                 return gripe("Malformed index in header field %d", i + 1);
405             return gripe("Symbolic index in header field %d not yet implemented",
406                          i + 1);
407         }
408         ch = getc(fp);
409         if (ch != ')')
410             return gripe("Malformed index in header field %d", i + 1);
411         return deffld(i, buf, idx);
412     }
413 }
414
415 /*
416  * Try to read a field value from FP.
417  * I is the field number, counting from zero.
418  * Return 1 if a value was read, 0 on end of line, -1 on error.
419  */
420 static int
421 xufld(FILE *fp, int i)
422 {
423     int ch;
424     char buf[1024];
425     double dbl;
426     long set;
427
428     ch = skipfs(fp);
429     switch (ch) {
430     case EOF:
431         return gripe("Unexpected EOF");
432     case '\n':
433         CANT_HAPPEN(i > nflds);
434         if (i < nflds) {
435             if (fldca[i]->ca_type != NSC_STRINGY && fldca[i]->ca_len)
436                 return gripe("Field %s(%d) missing",
437                              fldca[i]->ca_name, fldidx[i]);
438             return gripe("Field %s missing", fldca[i]->ca_name);
439         }
440         lineno++;
441         return 0;
442     case '+': case '-': case '.':
443     case '0': case '1': case '2': case '3': case '4':
444     case '5': case '6': case '7': case '8': case '9':
445         ungetc(ch, fp);
446         if (fscanf(fp, "%lg", &dbl) != 1)
447             return gripe("Malformed number in field %d", i + 1);
448         return setnum(i, dbl);
449     case '"':
450         ch = getc(fp);
451         if (ch == '"')
452             buf[0] = 0;
453         else {
454             ungetc(ch, fp);
455             if (fscanf(fp, "%1023[^\"\n]", buf) != 1 || getc(fp) != '"')
456                 return gripe("Malformed string in field %d", i + 1);
457             if (!xuesc(buf))
458                 return gripe("Invalid escape sequence in field %d",
459                              i + 1);
460         }
461         return setstr(i, buf);
462     case '(':
463         if (mtsymset(i, &set) < 0)
464             return -1;
465         for (;;) {
466             ch = skipfs(fp);
467             if (ch == EOF || ch == '\n')
468                 return gripe("Unmatched '(' in field %d", i + 1);
469             if (ch == ')')
470                 break;
471             ungetc(ch, fp);
472             if (getid(fp, buf) < 0)
473                 return gripe("Junk in field %d", i + 1);
474             if (add2symset(i, &set, buf) < 0)
475                 return -1;
476         }
477         return setnum(i, set);
478     default:
479         ungetc(ch, fp);
480         if (getid(fp, buf) < 0)
481             return gripe("Junk in field %d", i + 1);
482         if (!strcmp(buf, "nil"))
483             return setstr(i, NULL);
484         else
485             return setsym(i, buf);
486     }
487 }
488
489 /*
490  * Read fields from FP.
491  * Use PARSE() to read each field.
492  * Return number of fields read on success, -1 on error.
493  */
494 static int
495 xuflds(FILE *fp, int (*parse)(FILE *, int))
496 {
497     int i, ch, res;
498
499     for (i = 0; ; i++) {
500         res = parse(fp, i);
501         if (res < 0)
502             return -1;
503         if (res == 0)
504             return i;
505         ch = getc(fp);
506         if (ch == '\n')
507             ungetc(ch, fp);
508         else if (ch != ' ' && ch != '\t')
509             return gripe("Bad field separator after field %d", i + 1);
510     }
511 }
512
513 /*
514  * Define the FLDNO-th field.
515  * If IDX is negative, define as selector NAME, else as NAME(IDX).
516  * Set fldca[FLDNO] and fldidx[FLDNO] accordingly.
517  * Update caflds[].
518  * Return 1 on success, -1 on error.
519  */
520 static int
521 deffld(int fldno, char *name, int idx)
522 {
523     struct castr *ca = ef_cadef(cur_type);
524     int res;
525
526     res = stmtch(name, ca, offsetof(struct castr, ca_name),
527                  sizeof(struct castr));
528     if (res < 0)
529         return gripe("Header %s of field %d is %s", name, fldno + 1,
530                      res == M_NOTUNIQUE ? "ambiguous" : "unknown");
531     if ((ca[res].ca_flags & NSC_EXTRA) || CANT_HAPPEN(ca[res].ca_get))
532         return gripe("Extraneous header %s in field %d", name, fldno + 1);
533     if (ca[res].ca_type != NSC_STRINGY && ca[res].ca_len != 0) {
534         if (idx < 0)
535             return gripe("Header %s requires an index in field %d",
536                          ca[res].ca_name, fldno + 1);
537         if (idx >= ca[res].ca_len)
538             return gripe("Header %s(%d) index out of bounds in field %d",
539                          ca[res].ca_name, idx, fldno + 1);
540         if (idx < caflds[res])
541             return gripe("Duplicate header %s(%d) in field %d",
542                          ca[res].ca_name, idx, fldno + 1);
543         if (idx > caflds[res])
544             return gripe("Expected header %s(%d) in field %d",
545                          ca[res].ca_name, caflds[res], fldno + 1);
546     } else {
547         if (idx >= 0)
548             return gripe("Header %s doesn't take an index in field %d",
549                          ca[res].ca_name, fldno + 1);
550         idx = 0;
551         if (caflds[res])
552             return gripe("Duplicate header %s in field %d",
553                          ca[res].ca_name, fldno + 1);
554     }
555     fldca[fldno] = &ca[res];
556     fldidx[fldno] = idx;
557     caflds[res]++;
558     return 1;
559 }
560
561 /*
562  * Record that header ends with ...
563  * Set ellipsis and is_partial.
564  * Return 0 on success, -1 on error.
565  */
566 static int
567 defellipsis(void)
568 {
569     struct castr *ca = ef_cadef(cur_type);
570
571     if (ca[0].ca_table != cur_type || (ca[0].ca_flags & NSC_EXTRA))
572         return gripe("Table %s doesn't support ...", ef_nameof(cur_type));
573     ellipsis = 1;
574     return 0;
575 }
576
577 /* Is table split into parts? */
578 static int
579 is_partial(void)
580 {
581     return ellipsis || partno;
582 }
583
584 /*
585  * Check fields in xdump are sane.
586  * Return 0 on success, -1 on error.
587  */
588 static int
589 chkflds(void)
590 {
591     struct castr *ca = ef_cadef(cur_type);
592     int i, len, cafldsmax, res = 0;
593
594     /* Record index must come first, to make cur_id work, see setnum() */
595     if (ca[0].ca_table == cur_type && caflds[0] && fldca[0] != &ca[0])
596         res = gripe("Header field %s must come first", ca[0].ca_name);
597
598     if (is_partial()) {
599         /* Need a join field, use 0-th selector */
600         if (!caflds[0])
601             res = gripe("Header field %s required in each table part",
602                         ca[0].ca_name);
603     }
604
605     if (ellipsis)
606         return res;             /* table is split, another part expected */
607
608     /* Check for missing fields */
609     for (i = 0; ca[i].ca_name; i++) {
610         cafldsmax = MAX(caflds[i], cafldspp[i]);
611         if (ca[i].ca_flags & NSC_EXTRA)
612             continue;
613         len = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
614         if (!len && !cafldsmax)
615             res = gripe("Header field %s missing", ca[i].ca_name);
616         else if (len && cafldsmax == len - 1)
617             res = gripe("Header field %s(%d) missing",
618                         ca[i].ca_name, len - 1);
619         else if (len && cafldsmax < len - 1)
620             res = gripe("Header fields %s(%d) ... %s(%d) missing",
621                         ca[i].ca_name, cafldsmax, ca[i].ca_name, len - 1);
622     }
623
624     return res;
625 }
626
627 /*
628  * Get selector for field FLDNO.
629  * Assign the field's selector index to *IDX, unless it is null.
630  * Return the selector on success, null pointer on error.
631  */
632 static struct castr *
633 getfld(int fldno, int *idx)
634 {
635     if (fldno >= nflds) {
636         gripe("Too many fields, expected only %d", nflds);
637         return NULL;
638     }
639     if (CANT_HAPPEN(fldno < 0))
640         return NULL;
641     if (idx)
642         *idx = fldidx[fldno];
643     return fldca[fldno];
644 }
645
646 /*
647  * Is a new value for field FLDNO required to match the old one?
648  */
649 static int
650 fldval_must_match(int fldno)
651 {
652     struct castr *ca = ef_cadef(cur_type);
653     int i = fldca[fldno] - ca;
654
655     /*
656      * Value must match if:
657      * it's for a const selector, unless the object is still blank, or
658      * it was already given in a previous part of a split table.
659      */
660     return (!cur_obj_is_blank && (fldca[fldno]->ca_flags & NSC_CONST))
661         || fldidx[fldno] < cafldspp[i];
662 }
663
664 /*
665  * Set value of field FLDNO in current object to DBL.
666  * Return 1 on success, -1 on error.
667  */
668 static int
669 setnum(int fldno, double dbl)
670 {
671     struct castr *ca;
672     int next_id, idx;
673     char *memb_ptr;
674     double old, new;
675
676     ca = getfld(fldno, &idx);
677     if (!ca)
678         return -1;
679
680     if (fldno == 0) {
681         if (ca->ca_table == cur_type) {
682             /* Got record index */
683             next_id = (int)dbl;
684             if (next_id != dbl)
685                 return gripe("Field %d can't hold this value", fldno + 1);
686             if (tbl_skip_to_obj(next_id) < 0)
687                 return -1;
688         } else {
689             if (tbl_next_obj() < 0)
690                 return -1;
691         }
692     }
693     memb_ptr = cur_obj;
694     memb_ptr += ca->ca_off;
695
696     switch (ca->ca_type) {
697     case NSC_CHAR:
698         old = ((signed char *)memb_ptr)[idx];
699         new = ((signed char *)memb_ptr)[idx] = (signed char)dbl;
700         break;
701     case NSC_UCHAR:
702     case NSC_HIDDEN:
703         old = ((unsigned char *)memb_ptr)[idx];
704         new = ((unsigned char *)memb_ptr)[idx] = (unsigned char)dbl;
705         break;
706     case NSC_SHORT:
707         old = ((short *)memb_ptr)[idx];
708         new = ((short *)memb_ptr)[idx] = (short)dbl;
709         break;
710     case NSC_USHORT:
711         old = ((unsigned short *)memb_ptr)[idx];
712         new = ((unsigned short *)memb_ptr)[idx] = (unsigned short)dbl;
713         break;
714     case NSC_INT:
715         old = ((int *)memb_ptr)[idx];
716         new = ((int *)memb_ptr)[idx] = (int)dbl;
717         break;
718     case NSC_LONG:
719         old = ((long *)memb_ptr)[idx];
720         new = ((long *)memb_ptr)[idx] = (long)dbl;
721         break;
722     case NSC_XCOORD:
723         old = ((coord *)memb_ptr)[idx];
724         /* FIXME use variant of xrel() that takes orig instead of nation */
725         if (old >= WORLD_X / 2)
726             old -= WORLD_X;
727         new = ((coord *)memb_ptr)[idx] = XNORM((coord)dbl);
728         if (new >= WORLD_X / 2)
729             new -= WORLD_X;
730         break;
731     case NSC_YCOORD:
732         old = ((coord *)memb_ptr)[idx];
733         /* FIXME use variant of yrel() that takes orig instead of nation */
734         if (old >= WORLD_Y / 2)
735             old -= WORLD_Y;
736         new = ((coord *)memb_ptr)[idx] = YNORM((coord)dbl);
737         if (new >= WORLD_Y / 2)
738             new -= WORLD_Y;
739         break;
740     case NSC_FLOAT:
741         old = ((float *)memb_ptr)[idx];
742         ((float *)memb_ptr)[idx] = (float)dbl;
743         new = dbl;              /* suppress new != dbl check */
744         break;
745     case NSC_DOUBLE:
746         old = ((double *)memb_ptr)[idx];
747         ((double *)memb_ptr)[idx] = dbl;
748         new = dbl;              /* suppress new != dbl check */
749         break;
750     case NSC_TIME:
751         old = ((time_t *)memb_ptr)[idx];
752         new = ((time_t *)memb_ptr)[idx] = (time_t)dbl;
753         break;
754     default:
755         return gripe("Field %d doesn't take numbers", fldno + 1);
756     }
757
758     if (fldval_must_match(fldno) && old != dbl)
759         return gripe("Value for field %d must be %g", fldno + 1, old);
760     if (new != dbl)
761         return gripe("Field %d can't hold this value", fldno + 1);
762
763     return 1;
764 }
765
766 /*
767  * Set value of field FLDNO in current object to STR.
768  * Return 1 on success, -1 on error.
769  */
770 static int
771 setstr(int fldno, char *str)
772 {
773     struct castr *ca;
774     int must_match, idx;
775     size_t len;
776     char *memb_ptr, *old;
777
778     ca = getfld(fldno, &idx);
779     if (!ca)
780         return -1;
781
782     if (fldno == 0) {
783         if (tbl_next_obj() < 0)
784             return -1;
785     }
786     memb_ptr = cur_obj;
787     memb_ptr += ca->ca_off;
788     must_match = fldval_must_match(fldno);
789
790     switch (ca->ca_type) {
791     case NSC_STRING:
792         old = ((char **)memb_ptr)[idx];
793         if (!must_match)
794             /* FIXME may leak old value */
795             ((char **)memb_ptr)[idx] = str ? strdup(str) : NULL;
796         len = 65535;            /* really SIZE_MAX, but that's C99 */
797         break;
798     case NSC_STRINGY:
799         if (CANT_HAPPEN(idx))
800             return -1;
801         if (!str)
802             return gripe("Field %d doesn't take nil", fldno + 1);
803         len = ca->ca_len;
804         if (strlen(str) > len)
805             return gripe("Field %d takes at most %d characters",
806                          fldno + 1, (int)len);
807         old = memb_ptr;
808         if (!must_match)
809             strncpy(memb_ptr, str, len);
810         break;
811     default:
812         return gripe("Field %d doesn't take strings", fldno + 1);
813     }
814
815     if (must_match) {
816         if (old && (!str || strncmp(old, str, len)))
817             return gripe("Value for field %d must be \"%.*s\"",
818                          fldno + 1, (int)len, old);
819         if (!old && str)
820             return gripe("Value for field %d must be nil", fldno + 1);
821     }
822
823     return 1;
824 }
825
826 /*
827  * Resolve symbol name ID in table referred to by CA.
828  * Use field number N for error messages.
829  * Return index in referred table on success, -1 on failure.
830  */
831 static int
832 xunsymbol(char *id, struct castr *ca, int n)
833 {
834     int i = ef_elt_byname(ca->ca_table, id);
835     if (i < 0)
836         return gripe("%s %s symbol `%s' in field %d",
837                      i == M_NOTUNIQUE ? "Ambiguous" : "Unknown",
838                      ca->ca_name, id, n + 1);
839     return i;
840 }
841
842 /*
843  * Map symbol index to symbol value.
844  * CA is the table, and I is the index in it.
845  */
846 static int
847 symval(struct castr *ca, int i)
848 {
849     int type = ca->ca_table;
850
851     if (type != EF_BAD && ef_cadef(type) == symbol_ca)
852         /* symbol table, value is in the table */
853         return ((struct symbol *)ef_ptr(type, i))->value;
854     /* value is the table index */
855     return i;
856 }
857
858 /*
859  * Set value of field FLDNO in current object to value of symbol SYM.
860  * Return 1 on success, -1 on error.
861  */
862 static int
863 setsym(int fldno, char *sym)
864 {
865     struct castr *ca;
866     int i;
867
868     ca = getfld(fldno, NULL);
869     if (!ca)
870         return -1;
871
872     if (ca->ca_table == EF_BAD || (ca->ca_flags & NSC_BITS))
873         return gripe("Field %d doesn't take symbols", fldno + 1);
874
875     i = xunsymbol(sym, ca, fldno);
876     if (i < 0)
877         return -1;
878     return setnum(fldno, symval(ca, i));
879 }
880
881 /*
882  * Create an empty symbol set for field FLDNO in *SET.
883  * Return 1 on success, -1 on error.
884  */
885 static int
886 mtsymset(int fldno, long *set)
887 {
888     struct castr *ca;
889
890     ca = getfld(fldno, NULL);
891     if (!ca)
892         return -1;
893
894     if (ca->ca_table == EF_BAD || ef_cadef(ca->ca_table) != symbol_ca
895         || !(ca->ca_flags & NSC_BITS))
896         return gripe("Field %d doesn't take symbol sets", fldno + 1);
897     *set = 0;
898     return 0;
899 }
900
901 /*
902  * Add a symbol to a symbol set for field FLDNO in *SET.
903  * SYM is the name of the symbol to add.
904  * Return 1 on success, -1 on error.
905  */
906 static int
907 add2symset(int fldno, long *set, char *sym)
908 {
909     struct castr *ca;
910     int i;
911
912     ca = getfld(fldno, NULL);
913     if (!ca)
914         return -1;
915
916     i = xunsymbol(sym, ca, fldno);
917     if (i < 0)
918         return -1;
919     *set |= symval(ca, i);
920     return 0;
921 }
922
923 /*
924  * Read an xdump table header line from FP.
925  * Expect header for EXPECTED_TABLE, unless it is EF_BAD.
926  * Recognize header for machine- and human-readable syntax, and set
927  * human accordingly.
928  * Return table type on success, -2 on EOF before header, -1 on failure.
929  */
930 static int
931 xuheader(FILE *fp, int expected_table)
932 {
933     char name[64];
934     int res, ch;
935     int type;
936
937     while ((ch = skipfs(fp)) == '\n')
938         lineno++;
939     if (ch == EOF && expected_table == EF_BAD)
940         return -2;
941     ungetc(ch, fp);
942
943     human = ch == 'c';
944     res = -1;
945     if ((human
946          ? fscanf(fp, "config%*[ \t]%63[^ \t#\n]%n", name, &res) != 1
947          : fscanf(fp, "XDUMP%*[ \t]%63[^ \t#\n]%*[ \t]%*[^ \t#\n]%n",
948                   name, &res) != 1) || res < 0)
949         return gripe("Expected xdump header");
950
951     type = ef_byname(name);
952     if (type < 0)
953         return gripe("Unknown table `%s'", name);
954     if (expected_table != EF_BAD && expected_table != type)
955         return gripe("Expected table `%s', not `%s'",
956                      ef_nameof(expected_table), name);
957
958     if (!empfile[type].file
959         || !ef_cadef(type) || !(ef_flags(type) & EFF_MEM)) {
960         CANT_HAPPEN(expected_table != EF_BAD);
961         return gripe("Table `%s' is not permitted here", name);
962     }
963
964     if (skipfs(fp) != '\n')
965         return gripe("Junk after xdump header");
966     lineno++;
967
968     return type;
969 }
970
971 /*
972  * Find fields in this xdump.
973  * If reading human-readable syntax, read a field header line from FP.
974  * Else take fields from the table's selectors in CA[].
975  * Set ellipsis, nflds, fldca[], fldidx[] and caflds[] accordingly.
976  * Return 0 on success, -1 on failure.
977  */
978 static int
979 xufldhdr(FILE *fp, struct castr ca[])
980 {
981     struct castr **fca;
982     int *fidx;
983     int ch, i, j, n;
984
985     for (i = 0; ca[i].ca_name; i++)
986         caflds[i] = 0;
987     ellipsis = 0;
988
989     if (human) {
990         while ((ch = skipfs(fp)) == '\n')
991             lineno++;
992         ungetc(ch, fp);
993         nflds = xuflds(fp, xufldname);
994         if (nflds < 0)
995             return -1;
996         nflds -= ellipsis != 0;
997     } else {
998         fca = fldca;
999         fidx = fldidx;
1000
1001         for (i = 0; ca[i].ca_name; i++) {
1002             if ((ca[i].ca_flags & NSC_EXTRA))
1003                 continue;
1004             n = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
1005             j = 0;
1006             do {
1007                 *fca++ = &ca[i];
1008                 *fidx++ = j;
1009             } while (++j < n);
1010         }
1011
1012         nflds = fidx - fldidx;
1013     }
1014
1015     return 0;
1016 }
1017
1018 /*
1019  * Read xdump footer from FP.
1020  * CA[] contains the table's selectors.
1021  * The body had RECS records.
1022  * Update cafldspp[] from caflds[].
1023  * Return 0 on success, -1 on failure.
1024  */
1025 static int
1026 xufooter(FILE *fp, struct castr ca[], int recs)
1027 {
1028     int res, n, i;
1029
1030     res = -1;
1031     if (human) {
1032         if (fscanf(fp, "config%n", &res) != 0 || res < 0)
1033             return gripe("Malformed table footer");
1034     } else {
1035         if (fscanf(fp, "%d", &n) != 1)
1036             return gripe("Malformed table footer");
1037         if (recs != n)
1038             return gripe("Read %d rows, which doesn't match footer "
1039                          "%d rows", recs, n);
1040     }
1041     if (skipfs(fp) != '\n')
1042         return gripe("Junk after table footer");
1043     if (tbl_part_done() < 0)
1044         return -1;
1045     lineno++;
1046
1047     for (i = 0; ca[i].ca_name; i++) {
1048         if (cafldspp[i] < caflds[i])
1049             cafldspp[i] = caflds[i];
1050     }
1051
1052     return 0;
1053 }
1054
1055 /*
1056  * Read an xdump table from FP.
1057  * Both machine- and human-readable xdump syntax are recognized.
1058  * Expect table EXPECTED_TABLE, unless it is EF_BAD.
1059  * Report errors to stderr.
1060  * Messages assume FP starts in the file FILE at line *PLNO.
1061  * Update *PLNO to reflect lines read from FP.
1062  * Return table type on success, -2 on EOF before header, -1 on failure.
1063  */
1064 int
1065 xundump(FILE *fp, char *file, int *plno, int expected_table)
1066 {
1067     struct castr *ca;
1068     int type, nca, nf, i, ch;
1069
1070     fname = file;
1071     lineno = *plno;
1072
1073     if ((type = xuheader(fp, expected_table)) < 0)
1074         return type;
1075
1076     ca = ef_cadef(type);
1077     if (CANT_HAPPEN(!ca))
1078         return -1;
1079
1080     nca = nf = 0;
1081     may_omit_id = 1;
1082     may_trunc = empfile[type].nent < 0;
1083     for (i = 0; ca[i].ca_name; i++) {
1084         nca++;
1085         if (!(ca[i].ca_flags & NSC_EXTRA)) {
1086             nf += MAX(1, ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0);
1087             if (ca[i].ca_flags & NSC_CONST)
1088                 may_omit_id = may_trunc = 0;
1089         }
1090     }
1091     fldca = malloc(nf * sizeof(*fldca));
1092     fldidx = malloc(nf * sizeof(*fldidx));
1093     caflds = malloc(nca * sizeof(*caflds));
1094     cafldspp = calloc(nca, sizeof(*cafldspp));
1095
1096     tbl_start(type);
1097     if (xutail(fp, ca) < 0)
1098         type = EF_BAD;
1099     tbl_end();
1100
1101     free(cafldspp);
1102     free(caflds);
1103     free(fldidx);
1104     free(fldca);
1105
1106     /* Skip empty lines so that callers can easily check for EOF */
1107     while ((ch = skipfs(fp)) == '\n')
1108         lineno++;
1109     ungetc(ch, fp);
1110
1111     *plno = lineno;
1112     return type;
1113 }
1114
1115 /*
1116  * Read the remainder of an xdump after the table header line from FP.
1117  * CA[] contains the table's selectors.
1118  * Return 0 on success, -1 on failure.
1119  */
1120 static int
1121 xutail(FILE *fp, struct castr *ca)
1122 {
1123     int recs;
1124
1125     for (;;) {
1126         if (xufldhdr(fp, ca) < 0)
1127             return -1;
1128         if ((recs = xubody(fp)) < 0)
1129             return -1;
1130         if (xufooter(fp, ca, recs) < 0)
1131             return -1;
1132         if (!ellipsis)
1133             return 0;
1134         if (xuheader(fp, cur_type) < 0)
1135             return -1;
1136     }
1137 }
1138
1139 /*
1140  * Read the body of an xdump table from FP.
1141  * Return number of rows read on success, -1 on failure.
1142  */
1143 static int
1144 xubody(FILE *fp)
1145 {
1146     int i, ch;
1147
1148     for (i = 0;; ++i) {
1149         while ((ch = skipfs(fp)) == '\n')
1150             lineno++;
1151         if (ch == '/')
1152             break;
1153         ungetc(ch, fp);
1154         if (xuflds(fp, xufld) < 0)
1155             return -1;
1156     }
1157     return i;
1158 }