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