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
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.
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.
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
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.
28 * xundump.c: Load back xdump output
30 * Known contributors to this file:
31 * Ron Koenderink, 2005
32 * Markus Armbruster, 2005-2007
36 * See doc/xdump! And keep it up-to-date.
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-
44 * - Normalize terminology: table/rows/columns or file/records/fields
45 * - Loading tables with NSC_STRING elements more than once leaks memory
47 * - Check each partial table supplies the same rows
48 * - Check EFF_CFG tables are dense
49 * - Symbolic array indexes
50 * TODO, but hardly worth the effort:
51 * - Permit reordering of array elements
68 static char *fname; /* Name of file being read */
69 static int lineno; /* Current line number */
70 static int human; /* Reading human-readable syntax? */
71 static int ellipsis; /* Header ended with ...? */
72 static int is_partial; /* Is input split into parts? */
73 static int cur_type; /* Current table's file type */
74 static void *cur_obj; /* The object being read into */
75 static int cur_id; /* and its index in the table */
76 static int cur_obj_is_blank;
77 static int nflds; /* #fields in input records */
78 static struct castr **fldca; /* Map field number to selector */
79 static int *fldidx; /* Map field number to index */
80 static int *caflds; /* Map selector number to #fields seen */
81 static int *cafldspp; /* ditto, in previous parts */
83 static int gripe(char *, ...) ATTRIBUTE((format (printf, 1, 2)));
84 static int deffld(int, char *, int);
85 static int defellipsis(void);
86 static int chkflds(void);
87 static int setnum(int, double);
88 static int setstr(int, char *);
89 static int xunsymbol(char *, struct castr *, int);
90 static int setsym(int, char *);
91 static int mtsymset(int, long *);
92 static int add2symset(int, long *, char *);
93 static int xubody(FILE *);
94 static int xutail(FILE *, struct castr *);
97 * Gripe about the current line to stderr, return -1.
100 gripe(char *fmt, ...)
104 fprintf(stderr, "%s:%d: ", fname, lineno);
106 vfprintf(stderr, fmt, ap);
114 * Read and ignore field separators from FP.
115 * Return first character that is not a field separator.
124 } while (ch == ' ' || ch == '\t');
129 } while (ch != EOF && ch != '\n');
136 * Decode escape sequences in BUF.
137 * Return BUF on success, null pointer on failure.
149 if (sscanf(++src, "%3o%n", &octal_chr, &n) != 1 || n != 3)
151 *dst++ = (char)octal_chr;
161 * Read an identifier from FP into BUF.
162 * BUF must have space for 1024 characters.
163 * Return number of characters read on success, -1 on failure.
166 getid(FILE *fp, char *buf)
169 if (fscanf(fp, "%1023[^\"#()<>= \t\n]%n", buf, &n) != 1
177 * Try to read a field name from FP.
178 * I is the field number, counting from zero.
179 * If a name is read, set fldca[I] and fldidx[I] for it, and update
181 * Return 1 if a name or ... was read, 0 on end of line, -1 on error.
184 xufldname(FILE *fp, int i)
192 return gripe("Unexpected EOF");
199 if (getc(fp) != '.' || getc(fp) != '.')
200 return gripe("Junk in header field %d", i + 1);
201 if (defellipsis() < 0)
204 if (ch != EOF && ch != '\n')
205 return gripe("Junk after ...");
210 if (getid(fp, buf) < 0)
211 return gripe("Junk in header field %d", i + 1);
215 return deffld(i, buf, -1);
219 if (isdigit(ch) || ch == '-' || ch == '+') {
220 if (fscanf(fp, "%d", &idx) != 1)
221 return gripe("Malformed number in index of header field %d",
224 return gripe("Index must not be negative in header field %d",
227 if (getid(fp, buf) < 0)
228 return gripe("Malformed index in header field %d", i + 1);
229 return gripe("Symbolic index in header field %d not yet implemented",
234 return gripe("Malformed index in header field %d", i + 1);
235 return deffld(i, buf, idx);
240 * Try to read a field value from FP.
241 * I is the field number, counting from zero.
242 * Return 1 if a value was read, 0 on end of line, -1 on error.
245 xufld(FILE *fp, int i)
255 return gripe("Unexpected EOF");
257 CANT_HAPPEN(i > nflds);
259 if (fldca[i]->ca_type != NSC_STRINGY && fldca[i]->ca_len)
260 return gripe("Field %s(%d) missing",
261 fldca[i]->ca_name, fldidx[i]);
262 return gripe("Field %s missing", fldca[i]->ca_name);
266 case '+': case '-': case '.':
267 case '0': case '1': case '2': case '3': case '4':
268 case '5': case '6': case '7': case '8': case '9':
270 if (fscanf(fp, "%lg", &dbl) != 1)
271 return gripe("Malformed number in field %d", i + 1);
272 return setnum(i, dbl);
279 if (fscanf(fp, "%1023[^\"\n]", buf) != 1 || getc(fp) != '"')
280 return gripe("Malformed string in field %d", i + 1);
282 return gripe("Invalid escape sequence in field %d",
285 return setstr(i, buf);
287 if (mtsymset(i, &set) < 0)
291 if (ch == EOF || ch == '\n')
292 return gripe("Unmatched '(' in field %d", i + 1);
296 if (getid(fp, buf) < 0)
297 return gripe("Junk in field %d", i + 1);
298 if (add2symset(i, &set, buf) < 0)
301 return setnum(i, set);
304 if (getid(fp, buf) < 0)
305 return gripe("Junk in field %d", i + 1);
306 if (!strcmp(buf, "nil"))
307 return setstr(i, NULL);
309 return setsym(i, buf);
314 * Read fields from FP.
315 * Use PARSE() to read each field.
316 * Return number of fields read on success, -1 on error.
319 xuflds(FILE *fp, int (*parse)(FILE *, int))
332 else if (ch != ' ' && ch != '\t')
333 return gripe("Bad field separator after field %d", i + 1);
338 * Define the FLDNO-th field.
339 * If IDX is negative, define as selector NAME, else as NAME(IDX).
340 * Set fldca[FLDNO] and fldidx[FLDNO] accordingly.
342 * Return 1 on success, -1 on error.
345 deffld(int fldno, char *name, int idx)
347 struct castr *ca = ef_cadef(cur_type);
350 res = stmtch(name, ca, offsetof(struct castr, ca_name),
351 sizeof(struct castr));
353 return gripe("Header %s of field %d is %s", name, fldno + 1,
354 res == M_NOTUNIQUE ? "ambiguous" : "unknown");
355 if (ca[res].ca_type != NSC_STRINGY && ca[res].ca_len != 0) {
357 return gripe("Header %s requires an index in field %d",
358 ca[res].ca_name, fldno + 1);
359 if (idx >= ca[res].ca_len)
360 return gripe("Header %s(%d) index out of bounds in field %d",
361 ca[res].ca_name, idx, fldno + 1);
362 if (idx < caflds[res])
363 return gripe("Duplicate header %s(%d) in field %d",
364 ca[res].ca_name, idx, fldno + 1);
365 if (idx > caflds[res])
366 return gripe("Expected header %s(%d) in field %d",
367 ca[res].ca_name, caflds[res], fldno + 1);
370 return gripe("Header %s doesn't take an index in field %d",
371 ca[res].ca_name, fldno + 1);
374 return gripe("Duplicate header %s in field %d",
375 ca[res].ca_name, fldno + 1);
377 fldca[fldno] = &ca[res];
384 * Record that header ends with ...
385 * Set ellipsis and is_partial.
386 * Return 0 on success, -1 on error.
391 struct castr *ca = ef_cadef(cur_type);
393 if (ca[0].ca_table != cur_type)
394 return gripe("Table %s doesn't support ...", ef_nameof(cur_type));
395 ellipsis = is_partial = 1;
400 * Check fields in xdump are sane.
401 * Return 0 on success, -1 on error.
406 struct castr *ca = ef_cadef(cur_type);
407 int i, len, cafldsmax, res = 0;
410 /* Need a join field, use 0-th selector */
412 return gripe("Header field %s required with ...", ca[0].ca_name);
418 for (i = 0; ca[i].ca_name; i++) {
419 cafldsmax = MAX(caflds[i], cafldspp[i]);
420 if (ca[i].ca_flags & NSC_EXTRA)
422 len = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
423 if (!len && !cafldsmax)
424 res = gripe("Header field %s missing", ca[i].ca_name);
425 else if (len && cafldsmax == len - 1)
426 res = gripe("Header field %s(%d) missing",
427 ca[i].ca_name, len - 1);
428 else if (len && cafldsmax < len - 1)
429 res = gripe("Header fields %s(%d) ... %s(%d) missing",
430 ca[i].ca_name, cafldsmax, ca[i].ca_name, len - 1);
437 * Get selector for field FLDNO.
438 * Assign the field's selector index to *IDX, unless it is null.
439 * Return the selector on success, null pointer on error.
441 static struct castr *
442 getfld(int fldno, int *idx)
444 if (fldno >= nflds) {
445 gripe("Too many fields, expected only %d", nflds);
448 if (CANT_HAPPEN(fldno < 0))
451 *idx = fldidx[fldno];
456 * Is a new value for field FLDNO required to match the old one?
459 fldval_must_match(int fldno)
461 struct castr *ca = ef_cadef(cur_type);
462 int i = fldca[fldno] - ca;
465 * Value must match if:
466 * it's for a const selector, unless the object is still blank, or
467 * it was already given in a previous part of a split table.
469 return (!cur_obj_is_blank && (fldca[fldno]->ca_flags & NSC_CONST))
470 || fldidx[fldno] < cafldspp[i];
474 * Get the current object.
475 * Store it in cur_obj, and set cur_obj_is_blank accordingly.
476 * Return cur_obj, which is null on error.
481 struct empfile *ep = &empfile[cur_type];
482 int need_sentinel = !EF_IS_GAME_STATE(cur_type);
485 cur_obj_is_blank = cur_id >= ep->fids - !!need_sentinel;
486 if (cur_obj_is_blank) {
487 if (ef_ensure_space(cur_type, cur_id + !!need_sentinel, 1))
488 cur_obj = ef_ptr(cur_type, cur_id);
489 /* FIXME diagnose out of dynamic memory vs. static table full */
491 gripe("Can't put ID %d into table %s, it holds only 0..%d.",
492 cur_id, ep->name, ep->fids - !!need_sentinel - 1);
494 cur_obj = ef_ptr(cur_type, cur_id);
501 * Set value of field FLDNO in current object to DBL.
502 * Return 1 on success, -1 on error.
505 setnum(int fldno, double dbl)
512 ca = getfld(fldno, &idx);
517 * If this is the record index, put it into cur_id.
519 if (fldno == 0 && ca->ca_table == cur_type)
525 memb_ptr += ca->ca_off;
527 /* FIXME check assignment preserves value */
528 switch (ca->ca_type) {
530 old = ((signed char *)memb_ptr)[idx];
531 ((signed char *)memb_ptr)[idx] = (signed char)dbl;
535 old = ((unsigned char *)memb_ptr)[idx];
536 ((unsigned char *)memb_ptr)[idx] = (unsigned char)dbl;
539 old = ((short *)memb_ptr)[idx];
540 ((short *)memb_ptr)[idx] = (short)dbl;
543 old = ((unsigned short *)memb_ptr)[idx];
544 ((unsigned short *)memb_ptr)[idx] = (unsigned short)dbl;
547 old = ((int *)memb_ptr)[idx];
548 ((int *)memb_ptr)[idx] = (int)dbl;
551 old = ((long *)memb_ptr)[idx];
552 ((long *)memb_ptr)[idx] = (long)dbl;
555 old = ((coord *)memb_ptr)[idx];
556 /* FIXME use variant of xrel() that takes orig instead of nation */
557 if (old >= WORLD_X / 2)
559 ((coord *)memb_ptr)[idx] = XNORM((coord)dbl);
562 old = ((coord *)memb_ptr)[idx];
563 /* FIXME use variant of yrel() that takes orig instead of nation */
564 if (old >= WORLD_Y / 2)
566 ((coord *)memb_ptr)[idx] = YNORM((coord)dbl);
569 old = ((float *)memb_ptr)[idx];
570 ((float *)memb_ptr)[idx] = (float)dbl;
573 old = ((double *)memb_ptr)[idx];
574 ((double *)memb_ptr)[idx] = dbl;
577 old = ((time_t *)memb_ptr)[idx];
578 ((time_t *)memb_ptr)[idx] = (time_t)dbl;
581 return gripe("Field %d doesn't take numbers", fldno + 1);
584 if (fldval_must_match(fldno) && old != dbl)
585 return gripe("Value for field %d must be %g", fldno + 1, old);
591 * Set value of field FLDNO in current object to STR.
592 * Return 1 on success, -1 on error.
595 setstr(int fldno, char *str)
600 char *memb_ptr, *old;
602 ca = getfld(fldno, &idx);
609 memb_ptr += ca->ca_off;
610 must_match = fldval_must_match(fldno);
612 switch (ca->ca_type) {
614 old = ((char **)memb_ptr)[idx];
616 ((char **)memb_ptr)[idx] = str ? strdup(str) : NULL;
617 len = 65535; /* really SIZE_MAX, but that's C99 */
620 if (CANT_HAPPEN(idx))
623 return gripe("Field %d doesn't take nil", fldno + 1);
625 if (strlen(str) > len)
626 return gripe("Field %d takes at most %d characters",
627 fldno + 1, (int)len);
630 strncpy(memb_ptr, str, len);
633 return gripe("Field %d doesn't take strings", fldno + 1);
637 if (old && (!str || strncmp(old, str, len)))
638 return gripe("Value for field %d must be \"%.*s\"",
639 fldno + 1, (int)len, old);
641 return gripe("Value for field %d must be nil", fldno + 1);
648 * Resolve symbol name ID in table referred to by CA.
649 * Use field number N for error messages.
650 * Return index in referred table on success, -1 on failure.
653 xunsymbol(char *id, struct castr *ca, int n)
655 int i = ef_elt_byname(ca->ca_table, id);
657 return gripe("%s %s symbol `%s' in field %d",
658 i == M_NOTUNIQUE ? "Ambiguous" : "Unknown",
659 ca->ca_name, id, n + 1);
664 * Map symbol index to symbol value.
665 * CA is the table, and I is the index in it.
668 symval(struct castr *ca, int i)
670 int type = ca->ca_table;
672 if (ef_check(type) < 0)
674 if (ef_cadef(type) == symbol_ca)
675 /* symbol table, value is in the table */
676 return ((struct symbol *)ef_ptr(type, i))->value;
677 /* value is the table index */
682 * Set value of field FLDNO in current object to value of symbol SYM.
683 * Return 1 on success, -1 on error.
686 setsym(int fldno, char *sym)
691 ca = getfld(fldno, NULL);
695 if (ca->ca_table == EF_BAD || (ca->ca_flags & NSC_BITS))
696 return gripe("Field %d doesn't take symbols", fldno + 1);
698 i = xunsymbol(sym, ca, fldno);
701 return setnum(fldno, symval(ca, i));
705 * Create an empty symbol set for field FLDNO in *SET.
706 * Return 1 on success, -1 on error.
709 mtsymset(int fldno, long *set)
713 ca = getfld(fldno, NULL);
717 if (ca->ca_table == EF_BAD || ef_cadef(ca->ca_table) != symbol_ca
718 || !(ca->ca_flags & NSC_BITS))
719 return gripe("Field %d doesn't take symbol sets", fldno + 1);
725 * Add a symbol to a symbol set for field FLDNO in *SET.
726 * SYM is the name of the symbol to add.
727 * Return 1 on success, -1 on error.
730 add2symset(int fldno, long *set, char *sym)
735 ca = getfld(fldno, NULL);
739 i = xunsymbol(sym, ca, fldno);
742 *set |= symval(ca, i);
747 * Read an xdump table header line from FP.
748 * Expect header for EXPECTED_TABLE, unless it is EF_BAD.
749 * Recognize header for machine- and human-readable syntax, and set
751 * Return table type on success, -2 on EOF before header, -1 on failure.
754 xuheader(FILE *fp, int expected_table)
760 while ((ch = skipfs(fp)) == '\n')
762 if (ch == EOF && expected_table == EF_BAD)
769 ? fscanf(fp, "config%*[ \t]%63[^ \t#\n]%n", name, &res) != 1
770 : fscanf(fp, "XDUMP%*[ \t]%63[^ \t#\n]%*[ \t]%*[^ \t#\n]%n",
771 name, &res) != 1) || res < 0)
772 return gripe("Expected xdump header");
774 type = ef_byname(name);
776 return gripe("Unknown table `%s'", name);
777 if (expected_table != EF_BAD && expected_table != type)
778 return gripe("Expected table `%s', not `%s'",
779 ef_nameof(expected_table), name);
781 if (!ef_cadef(type) || !(ef_flags(type) & EFF_MEM)) {
782 CANT_HAPPEN(expected_table != EF_BAD);
783 return gripe("Table `%s' is not permitted here", name);
786 if (skipfs(fp) != '\n')
787 return gripe("Junk after xdump header");
794 * Find fields in this xdump.
795 * If reading human-readable syntax, read a field header line from FP.
796 * Else take fields from the table's selectors in CA[].
797 * Set ellipsis, nflds, fldca[], fldidx[] and caflds[] accordingly.
798 * Return 0 on success, -1 on failure.
801 xufldhdr(FILE *fp, struct castr ca[])
807 for (i = 0; ca[i].ca_name; i++)
812 while ((ch = skipfs(fp)) == '\n')
815 nflds = xuflds(fp, xufldname);
818 nflds -= ellipsis != 0;
823 for (i = 0; ca[i].ca_name; i++) {
824 if ((ca[i].ca_flags & NSC_EXTRA))
826 n = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
834 nflds = fidx - fldidx;
841 * Read xdump footer from FP.
842 * CA[] contains the table's selectors.
843 * The body had RECS records.
844 * Update cafldspp[] from caflds[].
845 * Return 0 on success, -1 on failure.
848 xufooter(FILE *fp, struct castr ca[], int recs)
854 if (fscanf(fp, "config%n", &res) != 0 || res < 0)
855 return gripe("Malformed table footer");
857 if (fscanf(fp, "%d", &n) != 1)
858 return gripe("Malformed table footer");
860 return gripe("Read %d rows, which doesn't match footer "
863 if (skipfs(fp) != '\n')
864 return gripe("Junk after table footer");
867 for (i = 0; ca[i].ca_name; i++) {
868 if (cafldspp[i] < caflds[i])
869 cafldspp[i] = caflds[i];
876 * Read an xdump table from FP.
877 * Both machine- and human-readable xdump syntax are recognized.
878 * Expect table EXPECTED_TABLE, unless it is EF_BAD.
879 * Report errors to stderr.
880 * Messages assume FP starts in the file FILE at line *PLNO.
881 * Update *PLNO to reflect lines read from FP.
882 * Return table type on success, -2 on EOF before header, -1 on failure.
885 xundump(FILE *fp, char *file, int *plno, int expected_table)
888 int type, nca, nf, i, ch;
893 if ((type = xuheader(fp, expected_table)) < 0)
897 if (CANT_HAPPEN(!ca))
901 for (i = 0; ca[i].ca_name; i++) {
903 if (!(ca[i].ca_flags & NSC_EXTRA))
904 nf += MAX(1, ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0);
906 fldca = malloc(nf * sizeof(*fldca));
907 fldidx = malloc(nf * sizeof(*fldidx));
908 caflds = malloc(nca * sizeof(*caflds));
909 cafldspp = calloc(nca, sizeof(*cafldspp));
912 if (xutail(fp, ca) < 0)
920 /* Skip empty lines so that callers can easily check for EOF */
921 while ((ch = skipfs(fp)) == '\n')
930 * Read the remainder of an xdump after the table header line from FP.
931 * CA[] contains the table's selectors.
932 * Return 0 on success, -1 on failure.
935 xutail(FILE *fp, struct castr *ca)
941 if (xufldhdr(fp, ca) < 0)
943 if ((recs = xubody(fp)) < 0)
945 if (xufooter(fp, ca, recs) < 0)
949 if (xuheader(fp, cur_type) < 0)
955 * Read the body of an xdump table from FP.
956 * Return number of rows read on success, -1 on failure.
961 struct empfile *ep = &empfile[cur_type];
962 int need_sentinel = !EF_IS_GAME_STATE(cur_type);
963 int old_maxid = ep->fids;
966 if (old_maxid == 0 && need_sentinel)
967 ef_ensure_space(cur_type, 0, 1);
971 while ((ch = skipfs(fp)) == '\n')
978 if (xuflds(fp, xufld) < 0)
980 maxid = MAX(maxid, cur_id + 1);
983 if (maxid >= old_maxid && need_sentinel) {
984 /* appended a sentinel, strip it off */
989 if (CANT_HAPPEN(maxid > ep->fids))
991 if (maxid < ep->fids) {
992 if (EF_IS_GAME_STATE(cur_type) && maxid != ep->csize)
993 /* TODO truncate file */
994 gripe("Warning: should resize table %s from %d to %d, not implemented",
995 ef_nameof(cur_type), ep->csize, maxid);
996 else if (cur_type >= EF_SHIP_CHR && cur_type <= EF_NUKE_CHR)
997 ep->cids = ep->fids = maxid;
999 return gripe("Table %s requires %d rows, got %d",
1000 ef_nameof(cur_type), ep->fids, maxid);