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 * Read an identifier from FP into BUF.
137 * BUF must have space for 1024 characters.
138 * Return number of characters read on success, -1 on failure.
141 getid(FILE *fp, char *buf)
144 if (fscanf(fp, "%1023[^#()<>=#\" \t\n]%n", buf, &n) != 1
151 * Decode escape sequences in BUF.
152 * Return BUF on success, null pointer on failure.
164 if (sscanf(++src, "%3o%n", &octal_chr, &n) != 1 || n != 3)
166 *dst++ = (char)octal_chr;
176 * Try to read a field name from FP.
177 * I is the field number, counting from zero.
178 * If a name is read, set fldca[I] and fldidx[I] for it, and update
180 * Return 1 if a name or ... was read, 0 on end of line, -1 on error.
183 xufldname(FILE *fp, int i)
191 return gripe("Unexpected EOF");
198 if (getc(fp) != '.' || getc(fp) != '.')
199 return gripe("Junk in header field %d", i + 1);
200 if (defellipsis() < 0)
203 if (ch != EOF && ch != '\n')
204 return gripe("Junk after ...");
209 if (getid(fp, buf) < 0)
210 return gripe("Junk in header field %d", i + 1);
214 return deffld(i, buf, -1);
218 if (isdigit(ch) || ch == '-' || ch == '+') {
219 if (fscanf(fp, "%d", &idx) != 1)
220 return gripe("Malformed number in index of header field %d",
223 return gripe("Index must not be negative in header field %d",
226 if (getid(fp, buf) < 0)
227 return gripe("Malformed index in header field %d", i + 1);
228 return gripe("Symbolic index in header field %d not yet implemented",
233 return gripe("Malformed index in header field %d", i + 1);
234 return deffld(i, buf, idx);
239 * Try to read a field value from FP.
240 * I is the field number, counting from zero.
241 * Return 1 if a value was read, 0 on end of line, -1 on error.
244 xufld(FILE *fp, int i)
254 return gripe("Unexpected EOF");
256 CANT_HAPPEN(i > nflds);
258 if (fldca[i]->ca_type != NSC_STRINGY && fldca[i]->ca_len)
259 return gripe("Field %s(%d) missing",
260 fldca[i]->ca_name, fldidx[i]);
261 return gripe("Field %s missing", fldca[i]->ca_name);
265 case '+': case '-': case '.':
266 case '0': case '1': case '2': case '3': case '4':
267 case '5': case '6': case '7': case '8': case '9':
269 if (fscanf(fp, "%lg", &dbl) != 1)
270 return gripe("Malformed number in field %d", i + 1);
271 return setnum(i, dbl);
278 if (fscanf(fp, "%1023[^\"\n]", buf) != 1 || getc(fp) != '"')
279 return gripe("Malformed string in field %d", i + 1);
281 return gripe("Invalid escape sequence in field %d",
284 return setstr(i, buf);
286 if (mtsymset(i, &set) < 0)
290 if (ch == EOF || ch == '\n')
291 return gripe("Unmatched '(' in field %d", i + 1);
295 if (getid(fp, buf) < 0)
296 return gripe("Junk in field %d", i + 1);
297 if (add2symset(i, &set, buf) < 0)
300 return setnum(i, set);
303 if (getid(fp, buf) < 0)
304 return gripe("Junk in field %d", i + 1);
305 if (!strcmp(buf, "nil"))
306 return setstr(i, NULL);
308 return setsym(i, buf);
313 * Read fields from FP.
314 * Use PARSE() to read each field.
315 * Return number of fields read on success, -1 on error.
318 xuflds(FILE *fp, int (*parse)(FILE *, int))
331 else if (ch != ' ' && ch != '\t')
332 return gripe("Bad field separator after field %d", i + 1);
337 * Define the FLDNO-th field.
338 * If IDX is negative, define as selector NAME, else as NAME(IDX).
339 * Set fldca[FLDNO] and fldidx[FLDNO] accordingly.
341 * Return 1 on success, -1 on error.
344 deffld(int fldno, char *name, int idx)
346 struct castr *ca = ef_cadef(cur_type);
349 res = stmtch(name, ca, offsetof(struct castr, ca_name),
350 sizeof(struct castr));
352 return gripe("Header %s of field %d is %s", name, fldno + 1,
353 res == M_NOTUNIQUE ? "ambiguous" : "unknown");
354 if (ca[res].ca_type != NSC_STRINGY && ca[res].ca_len != 0) {
356 return gripe("Header %s requires an index in field %d",
357 ca[res].ca_name, fldno + 1);
358 if (idx >= ca[res].ca_len)
359 return gripe("Header %s(%d) index out of bounds in field %d",
360 ca[res].ca_name, idx, fldno + 1);
361 if (idx < caflds[res])
362 return gripe("Duplicate header %s(%d) in field %d",
363 ca[res].ca_name, idx, fldno + 1);
364 if (idx > caflds[res])
365 return gripe("Expected header %s(%d) in field %d",
366 ca[res].ca_name, caflds[res], fldno + 1);
369 return gripe("Header %s doesn't take an index in field %d",
370 ca[res].ca_name, fldno + 1);
373 return gripe("Duplicate header %s in field %d",
374 ca[res].ca_name, fldno + 1);
376 fldca[fldno] = &ca[res];
383 * Record that header ends with ...
384 * Set ellipsis and is_partial.
385 * Return 0 on success, -1 on error.
390 struct castr *ca = ef_cadef(cur_type);
392 if (ca[0].ca_table != cur_type)
393 return gripe("Table %s doesn't support ...", ef_nameof(cur_type));
394 ellipsis = is_partial = 1;
399 * Check fields in xdump are sane.
400 * Return 0 on success, -1 on error.
405 struct castr *ca = ef_cadef(cur_type);
406 int i, len, cafldsmax, res = 0;
409 /* Need a join field, use 0-th selector */
411 return gripe("Header field %s required with ...", ca[0].ca_name);
417 for (i = 0; ca[i].ca_name; i++) {
418 cafldsmax = MAX(caflds[i], cafldspp[i]);
419 if (ca[i].ca_flags & NSC_EXTRA)
421 len = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
422 if (!len && !cafldsmax)
423 res = gripe("Header field %s missing", ca[i].ca_name);
424 else if (len && cafldsmax == len - 1)
425 res = gripe("Header field %s(%d) missing",
426 ca[i].ca_name, len - 1);
427 else if (len && cafldsmax < len - 1)
428 res = gripe("Header fields %s(%d) ... %s(%d) missing",
429 ca[i].ca_name, cafldsmax, ca[i].ca_name, len - 1);
436 * Get selector for field FLDNO.
437 * Assign the field's selector index to *IDX, unless it is null.
438 * Return the selector on success, null pointer on error.
440 static struct castr *
441 getfld(int fldno, int *idx)
443 if (fldno >= nflds) {
444 gripe("Too many fields, expected only %d", nflds);
447 if (CANT_HAPPEN(fldno < 0))
450 *idx = fldidx[fldno];
455 * Is a new value for field FLDNO required to match the old one?
458 fldval_must_match(int fldno)
460 struct castr *ca = ef_cadef(cur_type);
461 int i = fldca[fldno] - ca;
464 * Value must match if:
465 * it's for a const selector, unless the object is still blank, or
466 * it was already given in a previous part of a split table.
468 return (!cur_obj_is_blank && (fldca[fldno]->ca_flags & NSC_CONST))
469 || fldidx[fldno] < cafldspp[i];
473 * Get the current object.
474 * Store it in cur_obj, and set cur_obj_is_blank accordingly.
475 * Return cur_obj, which is null on error.
480 struct empfile *ep = &empfile[cur_type];
481 int need_sentinel = !EF_IS_GAME_STATE(cur_type);
484 cur_obj_is_blank = cur_id >= ep->fids - !!need_sentinel;
485 if (cur_obj_is_blank) {
486 if (ef_ensure_space(cur_type, cur_id + !!need_sentinel, 1))
487 cur_obj = ef_ptr(cur_type, cur_id);
488 /* FIXME diagnose out of dynamic memory vs. static table full */
490 gripe("Can't put ID %d into table %s, it holds only 0..%d.",
491 cur_id, ep->name, ep->fids - !!need_sentinel - 1);
493 cur_obj = ef_ptr(cur_type, cur_id);
500 * Set value of field FLDNO in current object to DBL.
501 * Return 1 on success, -1 on error.
504 setnum(int fldno, double dbl)
511 ca = getfld(fldno, &idx);
516 * If this is the record index, put it into cur_id.
518 if (fldno == 0 && ca->ca_table == cur_type)
524 memb_ptr += ca->ca_off;
526 /* FIXME check assignment preserves value */
527 switch (ca->ca_type) {
529 old = ((signed char *)memb_ptr)[idx];
530 ((signed char *)memb_ptr)[idx] = (signed char)dbl;
534 old = ((unsigned char *)memb_ptr)[idx];
535 ((unsigned char *)memb_ptr)[idx] = (unsigned char)dbl;
538 old = ((short *)memb_ptr)[idx];
539 ((short *)memb_ptr)[idx] = (short)dbl;
542 old = ((unsigned short *)memb_ptr)[idx];
543 ((unsigned short *)memb_ptr)[idx] = (unsigned short)dbl;
546 old = ((int *)memb_ptr)[idx];
547 ((int *)memb_ptr)[idx] = (int)dbl;
550 old = ((long *)memb_ptr)[idx];
551 ((long *)memb_ptr)[idx] = (long)dbl;
554 old = ((coord *)memb_ptr)[idx];
555 /* FIXME use variant of xrel() that takes orig instead of nation */
556 if (old >= WORLD_X / 2)
558 ((coord *)memb_ptr)[idx] = XNORM((coord)dbl);
561 old = ((coord *)memb_ptr)[idx];
562 /* FIXME use variant of yrel() that takes orig instead of nation */
563 if (old >= WORLD_Y / 2)
565 ((coord *)memb_ptr)[idx] = YNORM((coord)dbl);
568 old = ((float *)memb_ptr)[idx];
569 ((float *)memb_ptr)[idx] = (float)dbl;
572 old = ((double *)memb_ptr)[idx];
573 ((double *)memb_ptr)[idx] = dbl;
576 old = ((time_t *)memb_ptr)[idx];
577 ((time_t *)memb_ptr)[idx] = (time_t)dbl;
580 return gripe("Field %d doesn't take numbers", fldno + 1);
583 if (fldval_must_match(fldno) && old != dbl)
584 return gripe("Value for field %d must be %g", fldno + 1, old);
590 * Set value of field FLDNO in current object to STR.
591 * Return 1 on success, -1 on error.
594 setstr(int fldno, char *str)
599 char *memb_ptr, *old;
601 ca = getfld(fldno, &idx);
608 memb_ptr += ca->ca_off;
609 must_match = fldval_must_match(fldno);
611 switch (ca->ca_type) {
613 old = ((char **)memb_ptr)[idx];
615 ((char **)memb_ptr)[idx] = str ? strdup(str) : NULL;
616 len = 65535; /* really SIZE_MAX, but that's C99 */
619 if (CANT_HAPPEN(idx))
622 return gripe("Field %d doesn't take nil", fldno + 1);
624 if (strlen(str) > len)
625 return gripe("Field %d takes at most %d characters",
626 fldno + 1, (int)len);
629 strncpy(memb_ptr, str, len);
632 return gripe("Field %d doesn't take strings", fldno + 1);
636 if (old && (!str || strncmp(old, str, len)))
637 return gripe("Value for field %d must be \"%.*s\"",
638 fldno + 1, (int)len, old);
640 return gripe("Value for field %d must be nil", fldno + 1);
647 * Resolve symbol name ID in table referred to by CA.
648 * Use field number N for error messages.
649 * Return index in referred table on success, -1 on failure.
652 xunsymbol(char *id, struct castr *ca, int n)
654 int i = ef_elt_byname(ca->ca_table, id);
656 return gripe("%s %s symbol `%s' in field %d",
657 i == M_NOTUNIQUE ? "Ambiguous" : "Unknown",
658 ca->ca_name, id, n + 1);
663 * Map symbol index to symbol value.
664 * CA is the table, and I is the index in it.
667 symval(struct castr *ca, int i)
669 int type = ca->ca_table;
671 if (ef_check(type) < 0)
673 if (ef_cadef(type) == symbol_ca)
674 /* symbol table, value is in the table */
675 return ((struct symbol *)ef_ptr(type, i))->value;
676 /* value is the table index */
681 * Set value of field FLDNO in current object to value of symbol SYM.
682 * Return 1 on success, -1 on error.
685 setsym(int fldno, char *sym)
690 ca = getfld(fldno, NULL);
694 if (ca->ca_table == EF_BAD || (ca->ca_flags & NSC_BITS))
695 return gripe("Field %d doesn't take symbols", fldno + 1);
697 i = xunsymbol(sym, ca, fldno);
700 return setnum(fldno, symval(ca, i));
704 * Create an empty symbol set for field FLDNO in *SET.
705 * Return 1 on success, -1 on error.
708 mtsymset(int fldno, long *set)
712 ca = getfld(fldno, NULL);
716 if (ca->ca_table == EF_BAD || ef_cadef(ca->ca_table) != symbol_ca
717 || !(ca->ca_flags & NSC_BITS))
718 return gripe("Field %d doesn't take symbol sets", fldno + 1);
724 * Add a symbol to a symbol set for field FLDNO in *SET.
725 * SYM is the name of the symbol to add.
726 * Return 1 on success, -1 on error.
729 add2symset(int fldno, long *set, char *sym)
734 ca = getfld(fldno, NULL);
738 i = xunsymbol(sym, ca, fldno);
741 *set |= symval(ca, i);
746 * Read an xdump table header line from FP.
747 * Expect header for EXPECTED_TABLE, unless it is EF_BAD.
748 * Recognize header for machine- and human-readable syntax, and set
750 * Return table type on success, -2 on EOF before header, -1 on failure.
753 xuheader(FILE *fp, int expected_table)
759 while ((ch = skipfs(fp)) == '\n')
761 if (ch == EOF && expected_table == EF_BAD)
768 ? fscanf(fp, "config%*[ \t]%63[^ \t#\n]%n", name, &res) != 1
769 : fscanf(fp, "XDUMP%*[ \t]%63[^ \t#\n]%*[ \t]%*[^ \t#\n]%n",
770 name, &res) != 1) || res < 0)
771 return gripe("Expected xdump header");
773 type = ef_byname(name);
775 return gripe("Unknown table `%s'", name);
776 if (expected_table != EF_BAD && expected_table != type)
777 return gripe("Expected table `%s', not `%s'",
778 ef_nameof(expected_table), name);
780 if (!ef_cadef(type) || !(ef_flags(type) & EFF_MEM)) {
781 CANT_HAPPEN(expected_table != EF_BAD);
782 return gripe("Table `%s' is not permitted here", name);
785 if (skipfs(fp) != '\n')
786 return gripe("Junk after xdump header");
793 * Find fields in this xdump.
794 * If reading human-readable syntax, read a field header line from FP.
795 * Else take fields from the table's selectors in CA[].
796 * Set ellipsis, nflds, fldca[], fldidx[] and caflds[] accordingly.
797 * Return 0 on success, -1 on failure.
800 xufldhdr(FILE *fp, struct castr ca[])
806 for (i = 0; ca[i].ca_name; i++)
811 while ((ch = skipfs(fp)) == '\n')
814 nflds = xuflds(fp, xufldname);
817 nflds -= ellipsis != 0;
822 for (i = 0; ca[i].ca_name; i++) {
823 if ((ca[i].ca_flags & NSC_EXTRA))
825 n = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
833 nflds = fidx - fldidx;
840 * Read xdump footer from FP.
841 * CA[] contains the table's selectors.
842 * The body had RECS records.
843 * Update cafldspp[] from caflds[].
844 * Return 0 on success, -1 on failure.
847 xufooter(FILE *fp, struct castr ca[], int recs)
853 if (fscanf(fp, "config%n", &res) != 0 || res < 0)
854 return gripe("Malformed table footer");
856 if (fscanf(fp, "%d", &n) != 1)
857 return gripe("Malformed table footer");
859 return gripe("Read %d rows, which doesn't match footer "
862 if (skipfs(fp) != '\n')
863 return gripe("Junk after table footer");
866 for (i = 0; ca[i].ca_name; i++) {
867 if (cafldspp[i] < caflds[i])
868 cafldspp[i] = caflds[i];
875 * Read an xdump table from FP.
876 * Both machine- and human-readable xdump syntax are recognized.
877 * Expect table EXPECTED_TABLE, unless it is EF_BAD.
878 * Report errors to stderr.
879 * Messages assume FP starts in the file FILE at line *PLNO.
880 * Update *PLNO to reflect lines read from FP.
881 * Return table type on success, -2 on EOF before header, -1 on failure.
884 xundump(FILE *fp, char *file, int *plno, int expected_table)
887 int type, nca, nf, i, ch;
892 if ((type = xuheader(fp, expected_table)) < 0)
896 if (CANT_HAPPEN(!ca))
900 for (i = 0; ca[i].ca_name; i++) {
902 if (!(ca[i].ca_flags & NSC_EXTRA))
903 nf += MAX(1, ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0);
905 fldca = malloc(nf * sizeof(*fldca));
906 fldidx = malloc(nf * sizeof(*fldidx));
907 caflds = malloc(nca * sizeof(*caflds));
908 cafldspp = calloc(nca, sizeof(*cafldspp));
911 if (xutail(fp, ca) < 0)
919 /* Skip empty lines so that callers can easily check for EOF */
920 while ((ch = skipfs(fp)) == '\n')
929 * Read the remainder of an xdump after the table header line from FP.
930 * CA[] contains the table's selectors.
931 * Return 0 on success, -1 on failure.
934 xutail(FILE *fp, struct castr *ca)
940 if (xufldhdr(fp, ca) < 0)
942 if ((recs = xubody(fp)) < 0)
944 if (xufooter(fp, ca, recs) < 0)
948 if (xuheader(fp, cur_type) < 0)
954 * Read the body of an xdump table from FP.
955 * Return number of rows read on success, -1 on failure.
960 struct empfile *ep = &empfile[cur_type];
961 int need_sentinel = !EF_IS_GAME_STATE(cur_type);
962 int old_maxid = ep->fids;
965 if (old_maxid == 0 && need_sentinel)
966 ef_ensure_space(cur_type, 0, 1);
970 while ((ch = skipfs(fp)) == '\n')
977 if (xuflds(fp, xufld) < 0)
979 maxid = MAX(maxid, cur_id + 1);
982 if (maxid >= old_maxid && need_sentinel) {
983 /* appended a sentinel, strip it off */
988 if (CANT_HAPPEN(maxid > ep->fids))
990 if (maxid < ep->fids) {
991 if (EF_IS_GAME_STATE(cur_type) && maxid != ep->csize)
992 /* TODO truncate file */
993 gripe("Warning: should resize table %s from %d to %d, not implemented",
994 ef_nameof(cur_type), ep->csize, maxid);
995 else if (cur_type >= EF_SHIP_CHR && cur_type <= EF_NUKE_CHR)
996 ep->cids = ep->fids = maxid;
998 return gripe("Table %s requires %d rows, got %d",
999 ef_nameof(cur_type), ep->fids, maxid);