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