]> git.pond.sub.org Git - empserver/blobdiff - src/lib/common/xundump.c
Clean up redundant forward declarations
[empserver] / src / lib / common / xundump.c
index 6163827d653d5d4241591cb722bf801832b10029..14e88bfa8fc4c4207cab3939be38e78c2b1f2a29 100644 (file)
@@ -1,11 +1,11 @@
 /*
  *  Empire - A multi-player, client/server Internet based war game.
- *  Copyright (C) 1986-2006, Dave Pare, Jeff Bailey, Thomas Ruschak,
- *                           Ken Stevens, Steve McClure
+ *  Copyright (C) 1986-2013, Dave Pare, Jeff Bailey, Thomas Ruschak,
+ *                Ken Stevens, Steve McClure, Markus Armbruster
  *
- *  This program is free software; you can redistribute it and/or modify
+ *  Empire is free software: you can redistribute it and/or modify
  *  it under the terms of the GNU General Public License as published by
- *  the Free Software Foundation; either version 2 of the License, or
+ *  the Free Software Foundation, either version 3 of the License, or
  *  (at your option) any later version.
  *
  *  This program is distributed in the hope that it will be useful,
@@ -14,8 +14,7 @@
  *  GNU General Public License for more details.
  *
  *  You should have received a copy of the GNU General Public License
- *  along with this program; if not, write to the Free Software
- *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  *  ---
  *
  *  ---
  *
  *  xundump.c: Load back xdump output
- * 
+ *
  *  Known contributors to this file:
  *     Ron Koenderink, 2005
- *     Markus Armbruster, 2005
+ *     Markus Armbruster, 2005-2011
  */
 
 /*
+ * See doc/xdump!  And keep it up-to-date.
+ *
+ * Parsing of machine-readable xdump is not precise: it recognizes
+ * comments, accepts whitespace in place of single space, and accepts
+ * the full human-readable field syntax instead of its machine-
+ * readable subset.
+ *
  * FIXME:
  * - Normalize terminology: table/rows/columns or file/records/fields
  * - Loading tables with NSC_STRING elements more than once leaks memory
  * TODO:
- * - Check each partial table supplies the same rows
- * - Check EFF_CFG tables are dense
- * - Symbolic references to non-symbol tables
  * - Symbolic array indexes
+ * - Option to treat missing and unknown fields as warning, not error
  * TODO, but hardly worth the effort:
  * - Permit reordering of array elements
- * - Permit repetition of array elements in split tables
  */
 
 #include <config.h>
 
+#include <ctype.h>
+#include <stdarg.h>
 #include <stdio.h>
 #include <stdlib.h>
-
-#include <ctype.h>
 #include <string.h>
-#include <stdarg.h>
 #include <time.h>
-
 #include "file.h"
 #include "match.h"
 #include "nsc.h"
 #include "optlist.h"
-#include "prototypes.h"
-
-static unsigned char initialized[EF_MAX];
-static char *fname;
-static int lineno;
-static int human;
-static int ellipsis, is_partial;
-static int cur_type, cur_id;
-static void *cur_obj;
-static int nflds;
-static struct castr **fldca;
-static int *fldidx;
-static int *caflds;
-static unsigned char *caseen;
+#include "xdump.h"
+
+static char *fname;            /* Name of file being read */
+static int lineno;             /* Current line number */
+
+static int cur_type;           /* Current table's file type */
+static int partno;             /* Counts from 0..#parts-1 */
+static void *cur_obj;          /* The object being read into */
+static int cur_id;             /* and its index in the table */
+static int old_nelem;
+static unsigned char *idgap;   /* idgap && idgap[ID] iff part#0 lacks ID */
+static int idgap_len;          /* #elements in idgap[] */
+
+static int human;              /* Reading human-readable syntax? */
+static int ellipsis;           /* Header ended with ...? */
+static int nflds;              /* #fields in input records */
+static struct castr **fldca;   /* Map field number to selector */
+static int *fldidx;            /* Map field number to index */
+static int *caflds;            /* Map selector number to #fields seen */
+static int *cafldspp;          /* ditto, in previous parts */
+static int may_omit_id;                /* Okay to omit IDs? */
+static int may_trunc;          /* Okay to truncate? */
 
 static int gripe(char *, ...) ATTRIBUTE((format (printf, 1, 2)));
 static int deffld(int, char *, int);
-static int defellipsis(int fldno);
+static int defellipsis(void);
 static int chkflds(void);
 static int setnum(int, double);
 static int setstr(int, char *);
-static int xunsymbol(char *, struct castr *, int);
 static int setsym(int, char *);
 static int mtsymset(int, long *);
 static int add2symset(int, long *, char *);
-static int xundump1(FILE *, int, struct castr *);
-static int xundump2(FILE *, int, struct castr *);
+static int xubody(FILE *);
+static int xutail(FILE *, struct castr *);
 
+/*
+ * Gripe about the current line to stderr, return -1.
+ */
 static int
 gripe(char *fmt, ...)
 {
@@ -102,6 +113,186 @@ gripe(char *fmt, ...)
     return -1;
 }
 
+/* Make TYPE the current table.  */
+static void
+tbl_start(int type)
+{
+    cur_type = type;
+    partno = 0;
+    cur_id = -1;
+    cur_obj = NULL;
+    old_nelem = type == EF_BAD ? 0 : ef_nelem(type);
+    idgap = NULL;
+    idgap_len = 0;
+}
+
+/* End the current table.  */
+static void
+tbl_end(void)
+{
+    free(idgap);
+    tbl_start(EF_BAD);
+}
+
+/*
+ * Seek to current table's ID-th record.
+ * ID must be acceptable.
+ * Store it in cur_obj, and set cur_id accordingly.
+ * Return 0 on success, -1 on failure.
+ */
+static int
+tbl_seek(int id)
+{
+    struct empfile *ep = &empfile[cur_type];
+
+    if (id >= ef_nelem(cur_type)) {
+       if (!ef_ensure_space(cur_type, id, 1))
+           return gripe("Can't put ID %d into table %s", id, ep->name);
+    }
+
+    cur_obj = ef_ptr(cur_type, id);
+    if (CANT_HAPPEN(!cur_obj))
+       return -1;
+    cur_id = id;
+    return 0;
+}
+
+/*
+ * Get the next object.
+ * Must not have a record index.
+ * Store it in cur_obj, and set cur_id accordingly.
+ * Return 0 on success, -1 on failure.
+ */
+static int
+tbl_next_obj(void)
+{
+    int max_id = ef_id_limit(cur_type);
+
+    if (cur_id >= max_id)
+       return gripe("Too many rows");
+    return tbl_seek(cur_id + 1);
+}
+
+/*
+ * Omit ID1..ID2-1.
+ * Reset the omitted objects to default state.
+ */
+static void
+omit_ids(int id1, int id2)
+{
+    int i;
+
+    if (id1 >= id2)
+       return;
+
+    idgap = realloc(idgap, id2 * sizeof(*idgap));
+    for (i = idgap_len; i < id1; i++)
+       idgap[i] = 0;
+    for (i = id1; i < id2; i++) {
+       ef_blank(cur_type, i, ef_ptr(cur_type, i));
+       idgap[i] = 1;
+    }
+    idgap_len = id2;
+}
+
+/*
+ * Return the smallest non-omitted ID in ID1..ID2-1 if any, else -1.
+ */
+static int
+expected_id(int id1, int id2)
+{
+    int i;
+
+    for (i = id1; i < id2; i++) {
+       if (i >= idgap_len || !idgap[i])
+           return i;
+    }
+    return -1;
+}
+
+/*
+ * Get the next object, it has record index ID.
+ * Store it in cur_obj, and set cur_id accordingly.
+ * Ensure we're omitting the same objects as the previous parts.
+ * Reset any omitted objects to default state.
+ * Return 0 on success, -1 on failure.
+ */
+static int
+tbl_skip_to_obj(int id)
+{
+    struct empfile *ep = &empfile[cur_type];
+    int prev_id = cur_id;
+    int max_id, exp_id;
+
+    if (partno == 0) {
+       if (!may_omit_id && id != cur_id + 1)
+           return gripe("Expected %d in field %d", cur_id + 1, 1);
+       if (id <= cur_id)
+           return gripe("Field %d must be > %d", 1, cur_id);
+       max_id = ef_id_limit(cur_type);
+       if (id > max_id)
+           return gripe("Field %d must be <= %d", 1, max_id);
+    } else {
+       exp_id = expected_id(cur_id + 1, ep->fids);
+       if (exp_id < 0)
+           return gripe("Table's first part doesn't have this row");
+       else if (id != exp_id)
+           return gripe("Expected %d in field %d,"
+                        " like in table's first part",
+                        exp_id, 1);
+    }
+
+    if (tbl_seek(id) < 0)
+       return -1;
+
+    if (partno == 0)
+       omit_ids(prev_id + 1, id);
+    return 0;
+}
+
+/*
+ * Finish table part.
+ * If the table has variable length, truncate it.
+ * Else ensure we're omitting the same objects as the previous parts.
+ * Reset any omitted objects to default state.
+ * Return 0 on success, -1 on failure.
+ */
+static int
+tbl_part_done(void)
+{
+    struct empfile *ep = &empfile[cur_type];
+    int exp_id;
+
+    if (cur_id + 1 < ep->fids) {
+       if (partno == 0) {
+           if (may_trunc) {
+               if (!ef_truncate(cur_type, cur_id + 1))
+                   return -1;
+           } else {
+               if (!may_omit_id)
+                   return gripe("Expected %d more rows",
+                                ep->fids - (cur_id + 1));
+               omit_ids(cur_id + 1, ep->fids);
+           }
+       } else {
+           exp_id = expected_id(cur_id + 1, ep->fids);
+           if (exp_id >= 0)
+               return gripe("Expected row with %d in field %d,"
+                            " like in table's first part",
+                            exp_id, 1);
+       }
+    }
+
+    partno++;
+    cur_id = -1;
+    cur_obj = NULL;
+    return 0;
+}
+
+/*
+ * Read and ignore field separators from FP.
+ * Return first character that is not a field separator.
+ */
 static int
 skipfs(FILE *fp)
 {
@@ -120,16 +311,10 @@ skipfs(FILE *fp)
     return ch;
 }
 
-static int
-getid(FILE *fp, char *buf)
-{
-    int n;
-    if (fscanf(fp, "%1023[^#()<>=#\" \t\n]%n", buf, &n) != 1
-       || !isalpha(buf[0]))
-       return -1;
-    return n;
-}
-
+/*
+ * Decode escape sequences in BUF.
+ * Return BUF on success, null pointer on failure.
+ */
 static char *
 xuesc(char *buf)
 {
@@ -151,6 +336,29 @@ xuesc(char *buf)
     return buf;
 }
 
+/*
+ * Read an identifier from FP into BUF.
+ * BUF must have space for 1024 characters.
+ * Return number of characters read on success, -1 on failure.
+ */
+static int
+getid(FILE *fp, char *buf)
+{
+    int n;
+    if (fscanf(fp, "%1023[^\"#()<>= \t\n]%n", buf, &n) != 1
+       || !isalpha(buf[0]))
+       return -1;
+    xuesc(buf);
+    return n;
+}
+
+/*
+ * Try to read a field name from FP.
+ * I is the field number, counting from zero.
+ * If a name is read, set fldca[I] and fldidx[I] for it, and update
+ * caflds[].
+ * Return 1 if a name or ... was read, 0 on end of line, -1 on error.
+ */
 static int
 xufldname(FILE *fp, int i)
 {
@@ -169,9 +377,7 @@ xufldname(FILE *fp, int i)
     case '.':
        if (getc(fp) != '.' || getc(fp) != '.')
            return gripe("Junk in header field %d", i + 1);
-       if (i == 0)
-           return gripe("... not allowed in field 1");
-       if (defellipsis(i) < 0)
+       if (defellipsis() < 0)
            return -1;
        ch = skipfs(fp);
        if (ch != EOF && ch != '\n')
@@ -209,6 +415,11 @@ xufldname(FILE *fp, int i)
     }
 }
 
+/*
+ * Try to read a field value from FP.
+ * I is the field number, counting from zero.
+ * Return 1 if a value was read, 0 on end of line, -1 on error.
+ */
 static int
 xufld(FILE *fp, int i)
 {
@@ -222,7 +433,8 @@ xufld(FILE *fp, int i)
     case EOF:
        return gripe("Unexpected EOF");
     case '\n':
-       if (i != nflds) {
+       CANT_HAPPEN(i > nflds);
+       if (i < nflds) {
            if (fldca[i]->ca_type != NSC_STRINGY && fldca[i]->ca_len)
                return gripe("Field %s(%d) missing",
                             fldca[i]->ca_name, fldidx[i]);
@@ -277,6 +489,11 @@ xufld(FILE *fp, int i)
     }
 }
 
+/*
+ * Read fields from FP.
+ * Use PARSE() to read each field.
+ * Return number of fields read on success, -1 on error.
+ */
 static int
 xuflds(FILE *fp, int (*parse)(FILE *, int))
 {
@@ -296,6 +513,13 @@ xuflds(FILE *fp, int (*parse)(FILE *, int))
     }
 }
 
+/*
+ * Define the FLDNO-th field.
+ * If IDX is negative, define as selector NAME, else as NAME(IDX).
+ * Set fldca[FLDNO] and fldidx[FLDNO] accordingly.
+ * Update caflds[].
+ * Return 1 on success, -1 on error.
+ */
 static int
 deffld(int fldno, char *name, int idx)
 {
@@ -303,10 +527,12 @@ deffld(int fldno, char *name, int idx)
     int res;
 
     res = stmtch(name, ca, offsetof(struct castr, ca_name),
-                    sizeof(struct castr));
+                sizeof(struct castr));
     if (res < 0)
        return gripe("Header %s of field %d is %s", name, fldno + 1,
                     res == M_NOTUNIQUE ? "ambiguous" : "unknown");
+    if ((ca[res].ca_flags & NSC_EXTRA) || CANT_HAPPEN(ca[res].ca_get))
+       return gripe("Extraneous header %s in field %d", name, fldno + 1);
     if (ca[res].ca_type != NSC_STRINGY && ca[res].ca_len != 0) {
        if (idx < 0)
            return gripe("Header %s requires an index in field %d",
@@ -325,62 +551,87 @@ deffld(int fldno, char *name, int idx)
            return gripe("Header %s doesn't take an index in field %d",
                         ca[res].ca_name, fldno + 1);
        idx = 0;
-       if (caflds[res] && !caseen[res])
-           /* FIXME doesn't catch dupes within table part when caseen[res] */
+       if (caflds[res])
            return gripe("Duplicate header %s in field %d",
                         ca[res].ca_name, fldno + 1);
     }
     fldca[fldno] = &ca[res];
     fldidx[fldno] = idx;
-    if (!caseen[res])
-       caflds[res]++;
+    caflds[res]++;
     return 1;
 }
 
+/*
+ * Record that header ends with ...
+ * Set ellipsis and is_partial.
+ * Return 0 on success, -1 on error.
+ */
 static int
-defellipsis(int fldno)
+defellipsis(void)
 {
     struct castr *ca = ef_cadef(cur_type);
 
-    if (ca[0].ca_table != cur_type)
+    if (ca[0].ca_table != cur_type || (ca[0].ca_flags & NSC_EXTRA))
        return gripe("Table %s doesn't support ...", ef_nameof(cur_type));
-    ellipsis = fldno;
-    is_partial = 1;
+    ellipsis = 1;
     return 0;
 }
 
+/* Is table split into parts? */
+static int
+is_partial(void)
+{
+    return ellipsis || partno;
+}
+
+/*
+ * Check fields in xdump are sane.
+ * Return 0 on success, -1 on error.
+ */
 static int
 chkflds(void)
 {
     struct castr *ca = ef_cadef(cur_type);
-    int i, len, res = 0;
+    int i, len, cafldsmax, res = 0;
+
+    /* Record index must come first, to make cur_id work, see setnum() */
+    if (ca[0].ca_table == cur_type && caflds[0] && fldca[0] != &ca[0])
+       res = gripe("Header field %s must come first", ca[0].ca_name);
 
-    if (is_partial) {
-       /* Require index field */
+    if (is_partial()) {
+       /* Need a join field, use 0-th selector */
        if (!caflds[0])
-           return gripe("Header field %s required with ...", ca[0].ca_name);
-       /* Want the index field again in continued table: */
-       caflds[0] = 0;
-       return 0;
+           res = gripe("Header field %s required in each table part",
+                       ca[0].ca_name);
     }
 
+    if (ellipsis)
+       return res;             /* table is split, another part expected */
+
+    /* Check for missing fields */
     for (i = 0; ca[i].ca_name; i++) {
+       cafldsmax = MAX(caflds[i], cafldspp[i]);
        if (ca[i].ca_flags & NSC_EXTRA)
            continue;
        len = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
-       if (!len && !caflds[i])
+       if (!len && !cafldsmax)
            res = gripe("Header field %s missing", ca[i].ca_name);
-       else if (len && caflds[i] == len - 1)
+       else if (len && cafldsmax == len - 1)
            res = gripe("Header field %s(%d) missing",
                        ca[i].ca_name, len - 1);
-       else if (len && caflds[i] < len - 1)
+       else if (len && cafldsmax < len - 1)
            res = gripe("Header fields %s(%d) ... %s(%d) missing",
-                       ca[i].ca_name, caflds[i], ca[i].ca_name, len - 1);
+                       ca[i].ca_name, cafldsmax, ca[i].ca_name, len - 1);
     }
 
     return res;
 }
 
+/*
+ * Get selector for field FLDNO.
+ * Assign the field's selector index to *IDX, unless it is null.
+ * Return the selector on success, null pointer on error.
+ */
 static struct castr *
 getfld(int fldno, int *idx)
 {
@@ -395,109 +646,113 @@ getfld(int fldno, int *idx)
     return fldca[fldno];
 }
 
+/*
+ * Is a new value for field FLDNO required to match the old one?
+ */
 static int
 fldval_must_match(int fldno)
 {
     struct castr *ca = ef_cadef(cur_type);
     int i = fldca[fldno] - ca;
 
-    return (initialized[cur_type] && (fldca[fldno]->ca_flags & NSC_CONST))
-       || caseen[i];
-}
-
-static void *
-getobj(struct castr *ca, int altid)
-{
-    struct empfile *ep = &empfile[cur_type];
-    int need_sentinel = !EF_IS_GAME_STATE(cur_type);
-
-    if (!cur_obj) {
-       if (ca->ca_table == cur_type)
-           cur_id = altid;
-       if (cur_id >= ep->fids) {
-           /* TODO grow cache (and posssibly file) unless EFF_STATIC */
-           if (cur_id < ep->csize - !!need_sentinel)
-               ep->cids = ep->fids = cur_id + 1;
-           /* else: ef_ptr() will fail */
-       }
-       cur_obj = ef_ptr(cur_type, cur_id);
-       if (!cur_obj)
-           gripe("Can't put ID %d into table %s, it holds only 0..%d.",
-                 cur_id, ep->name, ep->fids - 1);
-    }
-
-    return cur_obj;
+    /*
+     * Value must match if:
+     * it's for a const selector, unless the object is still blank, or
+     * it was already given in a previous part of a split table.
+     */
+    return (cur_id < old_nelem && (fldca[fldno]->ca_flags & NSC_CONST))
+       || fldidx[fldno] < cafldspp[i];
 }
 
+/*
+ * Set value of field FLDNO in current object to DBL.
+ * Return 1 on success, -1 on error.
+ */
 static int
 setnum(int fldno, double dbl)
 {
     struct castr *ca;
-    int idx;
+    int next_id, idx;
     char *memb_ptr;
-    double old;
+    double old, new;
 
     ca = getfld(fldno, &idx);
     if (!ca)
        return -1;
 
-    memb_ptr = getobj(ca, (int)dbl);
-    if (!memb_ptr)
-       return -1;
+    if (fldno == 0) {
+       if (ca->ca_table == cur_type) {
+           /* Got record index */
+           next_id = (int)dbl;
+           if (next_id != dbl)
+               return gripe("Field %d can't hold this value", fldno + 1);
+           if (tbl_skip_to_obj(next_id) < 0)
+               return -1;
+       } else {
+           if (tbl_next_obj() < 0)
+               return -1;
+       }
+    }
+    memb_ptr = cur_obj;
     memb_ptr += ca->ca_off;
 
-    /* FIXME check assignment preserves value */
     switch (ca->ca_type) {
     case NSC_CHAR:
        old = ((signed char *)memb_ptr)[idx];
-       ((signed char *)memb_ptr)[idx] = (signed char)dbl;
+       new = ((signed char *)memb_ptr)[idx] = (signed char)dbl;
        break;
     case NSC_UCHAR:
     case NSC_HIDDEN:
        old = ((unsigned char *)memb_ptr)[idx];
-       ((unsigned char *)memb_ptr)[idx] = (unsigned char)dbl;
+       new = ((unsigned char *)memb_ptr)[idx] = (unsigned char)dbl;
        break;
     case NSC_SHORT:
        old = ((short *)memb_ptr)[idx];
-       ((short *)memb_ptr)[idx] = (short)dbl;
+       new = ((short *)memb_ptr)[idx] = (short)dbl;
        break;
     case NSC_USHORT:
        old = ((unsigned short *)memb_ptr)[idx];
-       ((unsigned short *)memb_ptr)[idx] = (unsigned short)dbl;
+       new = ((unsigned short *)memb_ptr)[idx] = (unsigned short)dbl;
        break;
     case NSC_INT:
        old = ((int *)memb_ptr)[idx];
-       ((int *)memb_ptr)[idx] = (int)dbl;
+       new = ((int *)memb_ptr)[idx] = (int)dbl;
        break;
     case NSC_LONG:
        old = ((long *)memb_ptr)[idx];
-       ((long *)memb_ptr)[idx] = (long)dbl;
+       new = ((long *)memb_ptr)[idx] = (long)dbl;
        break;
     case NSC_XCOORD:
        old = ((coord *)memb_ptr)[idx];
        /* FIXME use variant of xrel() that takes orig instead of nation */
        if (old >= WORLD_X / 2)
            old -= WORLD_X;
-       ((coord *)memb_ptr)[idx] = XNORM((coord)dbl);
+       new = ((coord *)memb_ptr)[idx] = XNORM((coord)dbl);
+       if (new >= WORLD_X / 2)
+           new -= WORLD_X;
        break;
     case NSC_YCOORD:
        old = ((coord *)memb_ptr)[idx];
        /* FIXME use variant of yrel() that takes orig instead of nation */
        if (old >= WORLD_Y / 2)
            old -= WORLD_Y;
-       ((coord *)memb_ptr)[idx] = YNORM((coord)dbl);
+       new = ((coord *)memb_ptr)[idx] = YNORM((coord)dbl);
+       if (new >= WORLD_Y / 2)
+           new -= WORLD_Y;
        break;
     case NSC_FLOAT:
        old = ((float *)memb_ptr)[idx];
        ((float *)memb_ptr)[idx] = (float)dbl;
+       new = dbl;              /* suppress new != dbl check */
        break;
     case NSC_DOUBLE:
        old = ((double *)memb_ptr)[idx];
        ((double *)memb_ptr)[idx] = dbl;
+       new = dbl;              /* suppress new != dbl check */
        break;
     case NSC_TIME:
        old = ((time_t *)memb_ptr)[idx];
-       ((time_t *)memb_ptr)[idx] = (time_t)dbl;
+       new = ((time_t *)memb_ptr)[idx] = (time_t)dbl;
        break;
     default:
        return gripe("Field %d doesn't take numbers", fldno + 1);
@@ -505,10 +760,16 @@ setnum(int fldno, double dbl)
 
     if (fldval_must_match(fldno) && old != dbl)
        return gripe("Value for field %d must be %g", fldno + 1, old);
+    if (new != dbl)
+       return gripe("Field %d can't hold this value", fldno + 1);
 
     return 1;
 }
 
+/*
+ * Set value of field FLDNO in current object to STR.
+ * Return 1 on success, -1 on error.
+ */
 static int
 setstr(int fldno, char *str)
 {
@@ -520,17 +781,20 @@ setstr(int fldno, char *str)
     ca = getfld(fldno, &idx);
     if (!ca)
        return -1;
-    must_match = fldval_must_match(fldno);
 
-    memb_ptr = getobj(ca, cur_id);
-    if (!memb_ptr)
-       return -1;
+    if (fldno == 0) {
+       if (tbl_next_obj() < 0)
+           return -1;
+    }
+    memb_ptr = cur_obj;
     memb_ptr += ca->ca_off;
+    must_match = fldval_must_match(fldno);
 
     switch (ca->ca_type) {
     case NSC_STRING:
        old = ((char **)memb_ptr)[idx];
        if (!must_match)
+           /* FIXME may leak old value */
            ((char **)memb_ptr)[idx] = str ? strdup(str) : NULL;
        len = 65535;            /* really SIZE_MAX, but that's C99 */
        break;
@@ -542,7 +806,7 @@ setstr(int fldno, char *str)
        len = ca->ca_len;
        if (strlen(str) > len)
            return gripe("Field %d takes at most %d characters",
-                        fldno + 1, len);
+                        fldno + 1, (int)len);
        old = memb_ptr;
        if (!must_match)
            strncpy(memb_ptr, str, len);
@@ -554,7 +818,7 @@ setstr(int fldno, char *str)
     if (must_match) {
        if (old && (!str || strncmp(old, str, len)))
            return gripe("Value for field %d must be \"%.*s\"",
-                        fldno + 1, len, old);
+                        fldno + 1, (int)len, old);
        if (!old && str)
            return gripe("Value for field %d must be nil", fldno + 1);
     }
@@ -562,6 +826,11 @@ setstr(int fldno, char *str)
     return 1;
 }
 
+/*
+ * Resolve symbol name ID in table referred to by CA.
+ * Use field number N for error messages.
+ * Return index in referred table on success, -1 on failure.
+ */
 static int
 xunsymbol(char *id, struct castr *ca, int n)
 {
@@ -573,20 +842,26 @@ xunsymbol(char *id, struct castr *ca, int n)
     return i;
 }
 
+/*
+ * Map symbol index to symbol value.
+ * CA is the table, and I is the index in it.
+ */
 static int
 symval(struct castr *ca, int i)
 {
     int type = ca->ca_table;
 
-    if (ef_check(type) < 0)
-       return -1;
-    if (ef_cadef(type) == symbol_ca)
+    if (type != EF_BAD && ef_cadef(type) == symbol_ca)
        /* symbol table, value is in the table */
        return ((struct symbol *)ef_ptr(type, i))->value;
     /* value is the table index */
     return i;
 }
 
+/*
+ * Set value of field FLDNO in current object to value of symbol SYM.
+ * Return 1 on success, -1 on error.
+ */
 static int
 setsym(int fldno, char *sym)
 {
@@ -606,6 +881,10 @@ setsym(int fldno, char *sym)
     return setnum(fldno, symval(ca, i));
 }
 
+/*
+ * Create an empty symbol set for field FLDNO in *SET.
+ * Return 1 on success, -1 on error.
+ */
 static int
 mtsymset(int fldno, long *set)
 {
@@ -622,6 +901,11 @@ mtsymset(int fldno, long *set)
     return 0;
 }
 
+/*
+ * Add a symbol to a symbol set for field FLDNO in *SET.
+ * SYM is the name of the symbol to add.
+ * Return 1 on success, -1 on error.
+ */
 static int
 add2symset(int fldno, long *set, char *sym)
 {
@@ -639,6 +923,13 @@ add2symset(int fldno, long *set, char *sym)
     return 0;
 }
 
+/*
+ * Read an xdump table header line from FP.
+ * Expect header for EXPECTED_TABLE, unless it is EF_BAD.
+ * Recognize header for machine- and human-readable syntax, and set
+ * human accordingly.
+ * Return table type on success, -2 on EOF before header, -1 on failure.
+ */
 static int
 xuheader(FILE *fp, int expected_table)
 {
@@ -655,9 +946,9 @@ xuheader(FILE *fp, int expected_table)
     human = ch == 'c';
     res = -1;
     if ((human
-         ? fscanf(fp, "config%*[ \t]%63[^ \t#\n]%n", name, &res) != 1
-         : fscanf(fp, "XDUMP%*[ \t]%63[^ \t#\n]%*[ \t]%*[^ \t#\n]%n",
-                  name, &res) != 1) || res < 0)
+        ? fscanf(fp, "config%*[ \t]%63[^ \t#\n]%n", name, &res) != 1
+        : fscanf(fp, "XDUMP%*[ \t]%63[^ \t#\n]%*[ \t]%*[^ \t#\n]%n",
+                 name, &res) != 1) || res < 0)
        return gripe("Expected xdump header");
 
     type = ef_byname(name);
@@ -667,7 +958,8 @@ xuheader(FILE *fp, int expected_table)
        return gripe("Expected table `%s', not `%s'",
                     ef_nameof(expected_table), name);
 
-    if (!ef_cadef(type) || !(ef_flags(type) & EFF_MEM)) {
+    if (!empfile[type].file
+       || !ef_cadef(type) || !(ef_flags(type) & EFF_MEM)) {
        CANT_HAPPEN(expected_table != EF_BAD);
        return gripe("Table `%s' is not permitted here", name);
     }
@@ -679,18 +971,28 @@ xuheader(FILE *fp, int expected_table)
     return type;
 }
 
+/*
+ * Find fields in this xdump.
+ * If reading human-readable syntax, read a field header line from FP.
+ * Else take fields from the table's selectors in CA[].
+ * Set ellipsis, nflds, fldca[], fldidx[] and caflds[] accordingly.
+ * Return 0 on success, -1 on failure.
+ */
 static int
-xuheader1(FILE *fp, int type, struct castr ca[])
+xufldhdr(FILE *fp, struct castr ca[])
 {
     struct castr **fca;
     int *fidx;
     int ch, i, j, n;
 
+    for (i = 0; ca[i].ca_name; i++)
+       caflds[i] = 0;
+    ellipsis = 0;
+
     if (human) {
        while ((ch = skipfs(fp)) == '\n')
            lineno++;
        ungetc(ch, fp);
-       ellipsis = 0;
        nflds = xuflds(fp, xufldname);
        if (nflds < 0)
            return -1;
@@ -716,39 +1018,60 @@ xuheader1(FILE *fp, int type, struct castr ca[])
     return 0;
 }
 
+/*
+ * Read xdump footer from FP.
+ * CA[] contains the table's selectors.
+ * The body had RECS records.
+ * Update cafldspp[] from caflds[].
+ * Return 0 on success, -1 on failure.
+ */
 static int
-xutrailer(FILE *fp, int type, int row)
+xufooter(FILE *fp, struct castr ca[], int recs)
 {
-    int rows, res;
+    int res, n, i;
 
     res = -1;
     if (human) {
-       if (fscanf(fp, "config%n",  &res) != 0 || res < 0)
+       if (fscanf(fp, "config%n", &res) != 0 || res < 0)
            return gripe("Malformed table footer");
     } else {
-       if (fscanf(fp, "%d", &rows) != 1)
+       if (fscanf(fp, "%d", &n) != 1)
            return gripe("Malformed table footer");
-       if (row != rows)
+       if (recs != n)
            return gripe("Read %d rows, which doesn't match footer "
-                        "%d rows", row, rows);
+                        "%d rows", recs, n);
     }
     if (skipfs(fp) != '\n')
        return gripe("Junk after table footer");
+    if (tbl_part_done() < 0)
+       return -1;
     lineno++;
 
+    for (i = 0; ca[i].ca_name; i++) {
+       if (cafldspp[i] < caflds[i])
+           cafldspp[i] = caflds[i];
+    }
+
     return 0;
 }
 
+/*
+ * Read an xdump table from FP.
+ * Both machine- and human-readable xdump syntax are recognized.
+ * Expect table EXPECTED_TABLE, unless it is EF_BAD.
+ * Report errors to stderr.
+ * Messages assume FP starts in the file FILE at line *PLNO.
+ * Update *PLNO to reflect lines read from FP.
+ * Return table type on success, -2 on EOF before header, -1 on failure.
+ */
 int
-xundump(FILE *fp, char *file, int expected_table)
+xundump(FILE *fp, char *file, int *plno, int expected_table)
 {
     struct castr *ca;
     int type, nca, nf, i, ch;
 
-    if (fname != file) {
-        fname = file;
-       lineno = 1;
-    }
+    fname = file;
+    lineno = *plno;
 
     if ((type = xuheader(fp, expected_table)) < 0)
        return type;
@@ -757,25 +1080,28 @@ xundump(FILE *fp, char *file, int expected_table)
     if (CANT_HAPPEN(!ca))
        return -1;
 
-    if (!EF_IS_GAME_STATE(type) && !empfile[type].file)
-       initialized[type] = 1;
-
     nca = nf = 0;
+    may_omit_id = 1;
+    may_trunc = empfile[type].nent < 0;
     for (i = 0; ca[i].ca_name; i++) {
        nca++;
-       if (!(ca[i].ca_flags & NSC_EXTRA))
+       if (!(ca[i].ca_flags & NSC_EXTRA)) {
            nf += MAX(1, ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0);
+           if (ca[i].ca_flags & NSC_CONST)
+               may_omit_id = may_trunc = 0;
+       }
     }
-    fldca = calloc(nf, sizeof(*fldca));
-    fldidx = calloc(nf, sizeof(*fldidx));
-    caflds = calloc(nca, sizeof(*caflds));
-    caseen = calloc(nca, sizeof(*caseen));
-    cur_type = type;
+    fldca = malloc(nf * sizeof(*fldca));
+    fldidx = malloc(nf * sizeof(*fldidx));
+    caflds = malloc(nca * sizeof(*caflds));
+    cafldspp = calloc(nca, sizeof(*cafldspp));
 
-    if (xundump2(fp, type, ca) < 0)
+    tbl_start(type);
+    if (xutail(fp, ca) < 0)
        type = EF_BAD;
+    tbl_end();
 
-    free(caseen);
+    free(cafldspp);
     free(caflds);
     free(fldidx);
     free(fldca);
@@ -785,73 +1111,51 @@ xundump(FILE *fp, char *file, int expected_table)
        lineno++;
     ungetc(ch, fp);
 
-    initialized[type] = 1;
+    *plno = lineno;
     return type;
 }
 
+/*
+ * Read the remainder of an xdump after the table header line from FP.
+ * CA[] contains the table's selectors.
+ * Return 0 on success, -1 on failure.
+ */
 static int
-xundump2(FILE *fp, int type, struct castr *ca)
+xutail(FILE *fp, struct castr *ca)
 {
-    int i;
+    int recs;
 
-    is_partial = 0;
     for (;;) {
-       if (xuheader1(fp, type, ca) < 0)
+       if (xufldhdr(fp, ca) < 0)
+           return -1;
+       if ((recs = xubody(fp)) < 0)
            return -1;
-       if (xundump1(fp, type, ca) < 0)
+       if (xufooter(fp, ca, recs) < 0)
            return -1;
        if (!ellipsis)
            return 0;
-       for (i = 0; ca[i].ca_name; i++)
-           caseen[i] = caflds[i] != 0;
-       if (xuheader(fp, type) < 0)
+       if (xuheader(fp, cur_type) < 0)
            return -1;
     }
 }
 
+/*
+ * Read the body of an xdump table from FP.
+ * Return number of rows read on success, -1 on failure.
+ */
 static int
-xundump1(FILE *fp, int type, struct castr *ca)
+xubody(FILE *fp)
 {
-    struct empfile *ep = &empfile[type];
-    int need_sentinel = !EF_IS_GAME_STATE(type);
-    int row, n, ch;
+    int i, ch;
 
-    n = 0;
-    for (row = 0;; ++row) {
+    for (i = 0;; ++i) {
        while ((ch = skipfs(fp)) == '\n')
            lineno++;
        if (ch == '/')
            break;
        ungetc(ch, fp);
-       cur_obj = NULL;
-       cur_id = row;
        if (xuflds(fp, xufld) < 0)
            return -1;
-       n = MAX(n, cur_id + 1);
-    }
-
-    if (CANT_HAPPEN(n > ep->fids))
-       n = ep->fids;
-    if (n < ep->fids) {
-       if (EF_IS_GAME_STATE(type) && n != ep->csize)
-           /* TODO truncate file */
-           gripe("Warning: should resize table %s from %d to %d, not implemented",
-                 ef_nameof(type), ep->csize, n);
-       else if (type >= EF_SHIP_CHR && type <= EF_NUKE_CHR)
-           ep->cids = ep->fids = n;
-       else
-           return gripe("Table %s requires %d rows, got %d",
-                        ef_nameof(type), ep->fids, n);
-    }
-
-    if (need_sentinel) {
-       if (CANT_HAPPEN(n >= ep->csize))
-           return gripe("No space for sentinel");
-       memset(ep->cache + ep->size * n, 0, ep->size);
     }
-
-    if (xutrailer(fp, type, row) < 0)
-       return -1;
-
-    return 0;
+    return i;
 }