2 * Empire - A multi-player, client/server Internet based war game.
3 * Copyright (C) 1986-2011, Dave Pare, Jeff Bailey, Thomas Ruschak,
4 * Ken Stevens, Steve McClure, Markus Armbruster
6 * Empire is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
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, see <http://www.gnu.org/licenses/>.
21 * See files README, COPYING and CREDITS in the root of the source
22 * tree for related information and legal notices. It is expected
23 * that future projects/authors will amend these files as needed.
27 * xundump.c: Load back xdump output
29 * Known contributors to this file:
30 * Ron Koenderink, 2005
31 * Markus Armbruster, 2005-2011
35 * See doc/xdump! And keep it up-to-date.
37 * Parsing of machine-readable xdump is not precise: it recognizes
38 * comments, accepts whitespace in place of single space, and accepts
39 * the full human-readable field syntax instead of its machine-
43 * - Normalize terminology: table/rows/columns or file/records/fields
44 * - Loading tables with NSC_STRING elements more than once leaks memory
46 * - Check each partial table supplies the same rows
47 * - Check EFF_CFG tables are dense
48 * - Symbolic array indexes
49 * - Option to treat missing and unknown fields as warning, not error
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 */
71 static int cur_type; /* Current table's file type */
72 static void *cur_obj; /* The object being read into */
73 static int cur_id; /* and its index in the table */
74 static int cur_obj_is_blank;
76 static int human; /* Reading human-readable syntax? */
77 static int ellipsis; /* Header ended with ...? */
78 static int is_partial; /* Is input split into parts? */
79 static int nflds; /* #fields in input records */
80 static struct castr **fldca; /* Map field number to selector */
81 static int *fldidx; /* Map field number to index */
82 static int *caflds; /* Map selector number to #fields seen */
83 static int *cafldspp; /* ditto, in previous parts */
84 static int may_trunc; /* Okay to truncate? */
86 static int gripe(char *, ...) ATTRIBUTE((format (printf, 1, 2)));
87 static int deffld(int, char *, int);
88 static int defellipsis(void);
89 static int chkflds(void);
90 static int setnum(int, double);
91 static int setstr(int, char *);
92 static int xunsymbol(char *, struct castr *, int);
93 static int setsym(int, char *);
94 static int mtsymset(int, long *);
95 static int add2symset(int, long *, char *);
96 static int xubody(FILE *);
97 static int xutail(FILE *, struct castr *);
100 * Gripe about the current line to stderr, return -1.
103 gripe(char *fmt, ...)
107 fprintf(stderr, "%s:%d: ", fname, lineno);
109 vfprintf(stderr, fmt, ap);
116 /* Make TYPE the current table. */
125 /* End the current table. */
133 * Seek to current table's ID-th record.
134 * ID must be acceptable.
135 * Store it in cur_obj, and set cur_id and cur_obj_is_blank accordingly.
136 * Return 0 on success, -1 on failure.
141 struct empfile *ep = &empfile[cur_type];
143 cur_obj_is_blank = id >= ep->fids;
145 if (id >= ef_nelem(cur_type)) {
146 if (!ef_ensure_space(cur_type, id, 1))
147 return gripe("Can't put ID %d into table %s", id, ep->name);
150 cur_obj = ef_ptr(cur_type, id);
151 if (CANT_HAPPEN(!cur_obj))
158 * Get the next object.
159 * Must not have a record index.
160 * Store it in cur_obj, and set cur_id and cur_obj_is_blank accordingly.
161 * Return 0 on success, -1 on failure.
166 int max_id = ef_id_limit(cur_type);
168 if (cur_id >= max_id)
169 return gripe("Too many rows");
170 return tbl_seek(cur_id + 1);
174 * Get the next object, it has record index ID.
175 * Store it in cur_obj, and set cur_id and cur_obj_is_blank accordingly.
176 * Return 0 on success, -1 on failure.
179 tbl_skip_to_obj(int id)
184 return gripe("Field %d must be >= 0", 1);
185 max_id = ef_id_limit(cur_type);
187 return gripe("Field %d must be <= %d", 1, max_id);
189 if (tbl_seek(id) < 0)
196 * If the table has variable length, truncate it.
206 * Read and ignore field separators from FP.
207 * Return first character that is not a field separator.
216 } while (ch == ' ' || ch == '\t');
221 } while (ch != EOF && ch != '\n');
228 * Decode escape sequences in BUF.
229 * Return BUF on success, null pointer on failure.
241 if (sscanf(++src, "%3o%n", &octal_chr, &n) != 1 || n != 3)
243 *dst++ = (char)octal_chr;
253 * Read an identifier from FP into BUF.
254 * BUF must have space for 1024 characters.
255 * Return number of characters read on success, -1 on failure.
258 getid(FILE *fp, char *buf)
261 if (fscanf(fp, "%1023[^\"#()<>= \t\n]%n", buf, &n) != 1
269 * Try to read a field name from FP.
270 * I is the field number, counting from zero.
271 * If a name is read, set fldca[I] and fldidx[I] for it, and update
273 * Return 1 if a name or ... was read, 0 on end of line, -1 on error.
276 xufldname(FILE *fp, int i)
284 return gripe("Unexpected EOF");
291 if (getc(fp) != '.' || getc(fp) != '.')
292 return gripe("Junk in header field %d", i + 1);
293 if (defellipsis() < 0)
296 if (ch != EOF && ch != '\n')
297 return gripe("Junk after ...");
302 if (getid(fp, buf) < 0)
303 return gripe("Junk in header field %d", i + 1);
307 return deffld(i, buf, -1);
311 if (isdigit(ch) || ch == '-' || ch == '+') {
312 if (fscanf(fp, "%d", &idx) != 1)
313 return gripe("Malformed number in index of header field %d",
316 return gripe("Index must not be negative in header field %d",
319 if (getid(fp, buf) < 0)
320 return gripe("Malformed index in header field %d", i + 1);
321 return gripe("Symbolic index in header field %d not yet implemented",
326 return gripe("Malformed index in header field %d", i + 1);
327 return deffld(i, buf, idx);
332 * Try to read a field value from FP.
333 * I is the field number, counting from zero.
334 * Return 1 if a value was read, 0 on end of line, -1 on error.
337 xufld(FILE *fp, int i)
347 return gripe("Unexpected EOF");
349 CANT_HAPPEN(i > nflds);
351 if (fldca[i]->ca_type != NSC_STRINGY && fldca[i]->ca_len)
352 return gripe("Field %s(%d) missing",
353 fldca[i]->ca_name, fldidx[i]);
354 return gripe("Field %s missing", fldca[i]->ca_name);
358 case '+': case '-': case '.':
359 case '0': case '1': case '2': case '3': case '4':
360 case '5': case '6': case '7': case '8': case '9':
362 if (fscanf(fp, "%lg", &dbl) != 1)
363 return gripe("Malformed number in field %d", i + 1);
364 return setnum(i, dbl);
371 if (fscanf(fp, "%1023[^\"\n]", buf) != 1 || getc(fp) != '"')
372 return gripe("Malformed string in field %d", i + 1);
374 return gripe("Invalid escape sequence in field %d",
377 return setstr(i, buf);
379 if (mtsymset(i, &set) < 0)
383 if (ch == EOF || ch == '\n')
384 return gripe("Unmatched '(' in field %d", i + 1);
388 if (getid(fp, buf) < 0)
389 return gripe("Junk in field %d", i + 1);
390 if (add2symset(i, &set, buf) < 0)
393 return setnum(i, set);
396 if (getid(fp, buf) < 0)
397 return gripe("Junk in field %d", i + 1);
398 if (!strcmp(buf, "nil"))
399 return setstr(i, NULL);
401 return setsym(i, buf);
406 * Read fields from FP.
407 * Use PARSE() to read each field.
408 * Return number of fields read on success, -1 on error.
411 xuflds(FILE *fp, int (*parse)(FILE *, int))
424 else if (ch != ' ' && ch != '\t')
425 return gripe("Bad field separator after field %d", i + 1);
430 * Define the FLDNO-th field.
431 * If IDX is negative, define as selector NAME, else as NAME(IDX).
432 * Set fldca[FLDNO] and fldidx[FLDNO] accordingly.
434 * Return 1 on success, -1 on error.
437 deffld(int fldno, char *name, int idx)
439 struct castr *ca = ef_cadef(cur_type);
442 res = stmtch(name, ca, offsetof(struct castr, ca_name),
443 sizeof(struct castr));
445 return gripe("Header %s of field %d is %s", name, fldno + 1,
446 res == M_NOTUNIQUE ? "ambiguous" : "unknown");
447 if ((ca[res].ca_flags & NSC_EXTRA) || CANT_HAPPEN(ca[res].ca_get))
448 return gripe("Extraneous header %s in field %d", name, fldno + 1);
449 if (ca[res].ca_type != NSC_STRINGY && ca[res].ca_len != 0) {
451 return gripe("Header %s requires an index in field %d",
452 ca[res].ca_name, fldno + 1);
453 if (idx >= ca[res].ca_len)
454 return gripe("Header %s(%d) index out of bounds in field %d",
455 ca[res].ca_name, idx, fldno + 1);
456 if (idx < caflds[res])
457 return gripe("Duplicate header %s(%d) in field %d",
458 ca[res].ca_name, idx, fldno + 1);
459 if (idx > caflds[res])
460 return gripe("Expected header %s(%d) in field %d",
461 ca[res].ca_name, caflds[res], fldno + 1);
464 return gripe("Header %s doesn't take an index in field %d",
465 ca[res].ca_name, fldno + 1);
468 return gripe("Duplicate header %s in field %d",
469 ca[res].ca_name, fldno + 1);
471 fldca[fldno] = &ca[res];
478 * Record that header ends with ...
479 * Set ellipsis and is_partial.
480 * Return 0 on success, -1 on error.
485 struct castr *ca = ef_cadef(cur_type);
487 if (ca[0].ca_table != cur_type || (ca[0].ca_flags & NSC_EXTRA))
488 return gripe("Table %s doesn't support ...", ef_nameof(cur_type));
489 ellipsis = is_partial = 1;
494 * Check fields in xdump are sane.
495 * Return 0 on success, -1 on error.
500 struct castr *ca = ef_cadef(cur_type);
501 int i, len, cafldsmax, res = 0;
503 /* Record index must come first, to make cur_id work, see setnum() */
504 if (ca[0].ca_table == cur_type && caflds[0] && fldca[0] != &ca[0])
505 res = gripe("Header field %s must come first", ca[0].ca_name);
508 /* Need a join field, use 0-th selector */
510 res = gripe("Header field %s required in each table part",
515 return res; /* table is split, another part expected */
517 /* Check for missing fields */
518 for (i = 0; ca[i].ca_name; i++) {
519 cafldsmax = MAX(caflds[i], cafldspp[i]);
520 if (ca[i].ca_flags & NSC_EXTRA)
522 len = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
523 if (!len && !cafldsmax)
524 res = gripe("Header field %s missing", ca[i].ca_name);
525 else if (len && cafldsmax == len - 1)
526 res = gripe("Header field %s(%d) missing",
527 ca[i].ca_name, len - 1);
528 else if (len && cafldsmax < len - 1)
529 res = gripe("Header fields %s(%d) ... %s(%d) missing",
530 ca[i].ca_name, cafldsmax, ca[i].ca_name, len - 1);
537 * Get selector for field FLDNO.
538 * Assign the field's selector index to *IDX, unless it is null.
539 * Return the selector on success, null pointer on error.
541 static struct castr *
542 getfld(int fldno, int *idx)
544 if (fldno >= nflds) {
545 gripe("Too many fields, expected only %d", nflds);
548 if (CANT_HAPPEN(fldno < 0))
551 *idx = fldidx[fldno];
556 * Is a new value for field FLDNO required to match the old one?
559 fldval_must_match(int fldno)
561 struct castr *ca = ef_cadef(cur_type);
562 int i = fldca[fldno] - ca;
565 * Value must match if:
566 * it's for a const selector, unless the object is still blank, or
567 * it was already given in a previous part of a split table.
569 return (!cur_obj_is_blank && (fldca[fldno]->ca_flags & NSC_CONST))
570 || fldidx[fldno] < cafldspp[i];
574 * Set value of field FLDNO in current object to DBL.
575 * Return 1 on success, -1 on error.
578 setnum(int fldno, double dbl)
585 ca = getfld(fldno, &idx);
590 if (ca->ca_table == cur_type) {
591 /* Got record index */
594 return gripe("Field %d can't hold this value", fldno + 1);
595 if (tbl_skip_to_obj(next_id) < 0)
598 if (tbl_next_obj() < 0)
603 memb_ptr += ca->ca_off;
605 switch (ca->ca_type) {
607 old = ((signed char *)memb_ptr)[idx];
608 new = ((signed char *)memb_ptr)[idx] = (signed char)dbl;
612 old = ((unsigned char *)memb_ptr)[idx];
613 new = ((unsigned char *)memb_ptr)[idx] = (unsigned char)dbl;
616 old = ((short *)memb_ptr)[idx];
617 new = ((short *)memb_ptr)[idx] = (short)dbl;
620 old = ((unsigned short *)memb_ptr)[idx];
621 new = ((unsigned short *)memb_ptr)[idx] = (unsigned short)dbl;
624 old = ((int *)memb_ptr)[idx];
625 new = ((int *)memb_ptr)[idx] = (int)dbl;
628 old = ((long *)memb_ptr)[idx];
629 new = ((long *)memb_ptr)[idx] = (long)dbl;
632 old = ((coord *)memb_ptr)[idx];
633 /* FIXME use variant of xrel() that takes orig instead of nation */
634 if (old >= WORLD_X / 2)
636 new = ((coord *)memb_ptr)[idx] = XNORM((coord)dbl);
637 if (new >= WORLD_X / 2)
641 old = ((coord *)memb_ptr)[idx];
642 /* FIXME use variant of yrel() that takes orig instead of nation */
643 if (old >= WORLD_Y / 2)
645 new = ((coord *)memb_ptr)[idx] = YNORM((coord)dbl);
646 if (new >= WORLD_Y / 2)
650 old = ((float *)memb_ptr)[idx];
651 ((float *)memb_ptr)[idx] = (float)dbl;
652 new = dbl; /* suppress new != dbl check */
655 old = ((double *)memb_ptr)[idx];
656 ((double *)memb_ptr)[idx] = dbl;
657 new = dbl; /* suppress new != dbl check */
660 old = ((time_t *)memb_ptr)[idx];
661 new = ((time_t *)memb_ptr)[idx] = (time_t)dbl;
664 return gripe("Field %d doesn't take numbers", fldno + 1);
667 if (fldval_must_match(fldno) && old != dbl)
668 return gripe("Value for field %d must be %g", fldno + 1, old);
670 return gripe("Field %d can't hold this value", fldno + 1);
676 * Set value of field FLDNO in current object to STR.
677 * Return 1 on success, -1 on error.
680 setstr(int fldno, char *str)
685 char *memb_ptr, *old;
687 ca = getfld(fldno, &idx);
692 if (tbl_next_obj() < 0)
696 memb_ptr += ca->ca_off;
697 must_match = fldval_must_match(fldno);
699 switch (ca->ca_type) {
701 old = ((char **)memb_ptr)[idx];
703 /* FIXME may leak old value */
704 ((char **)memb_ptr)[idx] = str ? strdup(str) : NULL;
705 len = 65535; /* really SIZE_MAX, but that's C99 */
708 if (CANT_HAPPEN(idx))
711 return gripe("Field %d doesn't take nil", fldno + 1);
713 if (strlen(str) > len)
714 return gripe("Field %d takes at most %d characters",
715 fldno + 1, (int)len);
718 strncpy(memb_ptr, str, len);
721 return gripe("Field %d doesn't take strings", fldno + 1);
725 if (old && (!str || strncmp(old, str, len)))
726 return gripe("Value for field %d must be \"%.*s\"",
727 fldno + 1, (int)len, old);
729 return gripe("Value for field %d must be nil", fldno + 1);
736 * Resolve symbol name ID in table referred to by CA.
737 * Use field number N for error messages.
738 * Return index in referred table on success, -1 on failure.
741 xunsymbol(char *id, struct castr *ca, int n)
743 int i = ef_elt_byname(ca->ca_table, id);
745 return gripe("%s %s symbol `%s' in field %d",
746 i == M_NOTUNIQUE ? "Ambiguous" : "Unknown",
747 ca->ca_name, id, n + 1);
752 * Map symbol index to symbol value.
753 * CA is the table, and I is the index in it.
756 symval(struct castr *ca, int i)
758 int type = ca->ca_table;
760 if (type != EF_BAD && ef_cadef(type) == symbol_ca)
761 /* symbol table, value is in the table */
762 return ((struct symbol *)ef_ptr(type, i))->value;
763 /* value is the table index */
768 * Set value of field FLDNO in current object to value of symbol SYM.
769 * Return 1 on success, -1 on error.
772 setsym(int fldno, char *sym)
777 ca = getfld(fldno, NULL);
781 if (ca->ca_table == EF_BAD || (ca->ca_flags & NSC_BITS))
782 return gripe("Field %d doesn't take symbols", fldno + 1);
784 i = xunsymbol(sym, ca, fldno);
787 return setnum(fldno, symval(ca, i));
791 * Create an empty symbol set for field FLDNO in *SET.
792 * Return 1 on success, -1 on error.
795 mtsymset(int fldno, long *set)
799 ca = getfld(fldno, NULL);
803 if (ca->ca_table == EF_BAD || ef_cadef(ca->ca_table) != symbol_ca
804 || !(ca->ca_flags & NSC_BITS))
805 return gripe("Field %d doesn't take symbol sets", fldno + 1);
811 * Add a symbol to a symbol set for field FLDNO in *SET.
812 * SYM is the name of the symbol to add.
813 * Return 1 on success, -1 on error.
816 add2symset(int fldno, long *set, char *sym)
821 ca = getfld(fldno, NULL);
825 i = xunsymbol(sym, ca, fldno);
828 *set |= symval(ca, i);
833 * Read an xdump table header line from FP.
834 * Expect header for EXPECTED_TABLE, unless it is EF_BAD.
835 * Recognize header for machine- and human-readable syntax, and set
837 * Return table type on success, -2 on EOF before header, -1 on failure.
840 xuheader(FILE *fp, int expected_table)
846 while ((ch = skipfs(fp)) == '\n')
848 if (ch == EOF && expected_table == EF_BAD)
855 ? fscanf(fp, "config%*[ \t]%63[^ \t#\n]%n", name, &res) != 1
856 : fscanf(fp, "XDUMP%*[ \t]%63[^ \t#\n]%*[ \t]%*[^ \t#\n]%n",
857 name, &res) != 1) || res < 0)
858 return gripe("Expected xdump header");
860 type = ef_byname(name);
862 return gripe("Unknown table `%s'", name);
863 if (expected_table != EF_BAD && expected_table != type)
864 return gripe("Expected table `%s', not `%s'",
865 ef_nameof(expected_table), name);
867 if (!empfile[type].file
868 || !ef_cadef(type) || !(ef_flags(type) & EFF_MEM)) {
869 CANT_HAPPEN(expected_table != EF_BAD);
870 return gripe("Table `%s' is not permitted here", name);
873 if (skipfs(fp) != '\n')
874 return gripe("Junk after xdump header");
881 * Find fields in this xdump.
882 * If reading human-readable syntax, read a field header line from FP.
883 * Else take fields from the table's selectors in CA[].
884 * Set ellipsis, nflds, fldca[], fldidx[] and caflds[] accordingly.
885 * Return 0 on success, -1 on failure.
888 xufldhdr(FILE *fp, struct castr ca[])
894 for (i = 0; ca[i].ca_name; i++)
899 while ((ch = skipfs(fp)) == '\n')
902 nflds = xuflds(fp, xufldname);
905 nflds -= ellipsis != 0;
910 for (i = 0; ca[i].ca_name; i++) {
911 if ((ca[i].ca_flags & NSC_EXTRA))
913 n = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
921 nflds = fidx - fldidx;
928 * Read xdump footer from FP.
929 * CA[] contains the table's selectors.
930 * The body had RECS records.
931 * Update cafldspp[] from caflds[].
932 * Return 0 on success, -1 on failure.
935 xufooter(FILE *fp, struct castr ca[], int recs)
941 if (fscanf(fp, "config%n", &res) != 0 || res < 0)
942 return gripe("Malformed table footer");
944 if (fscanf(fp, "%d", &n) != 1)
945 return gripe("Malformed table footer");
947 return gripe("Read %d rows, which doesn't match footer "
950 if (skipfs(fp) != '\n')
951 return gripe("Junk after table footer");
955 for (i = 0; ca[i].ca_name; i++) {
956 if (cafldspp[i] < caflds[i])
957 cafldspp[i] = caflds[i];
964 * Read an xdump table from FP.
965 * Both machine- and human-readable xdump syntax are recognized.
966 * Expect table EXPECTED_TABLE, unless it is EF_BAD.
967 * Report errors to stderr.
968 * Messages assume FP starts in the file FILE at line *PLNO.
969 * Update *PLNO to reflect lines read from FP.
970 * Return table type on success, -2 on EOF before header, -1 on failure.
973 xundump(FILE *fp, char *file, int *plno, int expected_table)
976 int type, nca, nf, i, ch;
981 if ((type = xuheader(fp, expected_table)) < 0)
985 if (CANT_HAPPEN(!ca))
989 may_trunc = empfile[type].nent < 0;
990 for (i = 0; ca[i].ca_name; i++) {
992 if (!(ca[i].ca_flags & NSC_EXTRA)) {
993 nf += MAX(1, ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0);
994 if (ca[i].ca_flags & NSC_CONST)
998 fldca = malloc(nf * sizeof(*fldca));
999 fldidx = malloc(nf * sizeof(*fldidx));
1000 caflds = malloc(nca * sizeof(*caflds));
1001 cafldspp = calloc(nca, sizeof(*cafldspp));
1004 if (xutail(fp, ca) < 0)
1013 /* Skip empty lines so that callers can easily check for EOF */
1014 while ((ch = skipfs(fp)) == '\n')
1023 * Read the remainder of an xdump after the table header line from FP.
1024 * CA[] contains the table's selectors.
1025 * Return 0 on success, -1 on failure.
1028 xutail(FILE *fp, struct castr *ca)
1034 if (xufldhdr(fp, ca) < 0)
1036 if ((recs = xubody(fp)) < 0)
1038 if (xufooter(fp, ca, recs) < 0)
1042 if (xuheader(fp, cur_type) < 0)
1048 * Read the body of an xdump table from FP.
1049 * Return number of rows read on success, -1 on failure.
1054 struct empfile *ep = &empfile[cur_type];
1059 while ((ch = skipfs(fp)) == '\n')
1064 if (xuflds(fp, xufld) < 0)
1066 maxid = MAX(maxid, cur_id + 1);
1069 if (CANT_HAPPEN(maxid > ep->fids))
1071 if (maxid < ep->fids) {
1073 if (!ef_truncate(cur_type, maxid))
1076 return gripe("Table %s requires %d rows, got %d",
1077 ef_nameof(cur_type), ep->fids, maxid);