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