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 */
85 static int gripe(char *, ...) ATTRIBUTE((format (printf, 1, 2)));
86 static int deffld(int, char *, int);
87 static int defellipsis(void);
88 static int chkflds(void);
89 static int setnum(int, double);
90 static int setstr(int, char *);
91 static int xunsymbol(char *, struct castr *, int);
92 static int setsym(int, char *);
93 static int mtsymset(int, long *);
94 static int add2symset(int, long *, char *);
95 static int xubody(FILE *);
96 static int xutail(FILE *, struct castr *);
99 * Gripe about the current line to stderr, return -1.
102 gripe(char *fmt, ...)
106 fprintf(stderr, "%s:%d: ", fname, lineno);
108 vfprintf(stderr, fmt, ap);
115 /* Make TYPE the current table. */
124 /* End the current table. */
132 * Seek to current table's ID-th record.
133 * ID must be acceptable.
134 * Store it in cur_obj, and set cur_id and cur_obj_is_blank accordingly.
135 * Return 0 on success, -1 on failure.
140 struct empfile *ep = &empfile[cur_type];
142 cur_obj_is_blank = id >= ep->fids;
144 if (id >= ef_nelem(cur_type)) {
145 if (!ef_ensure_space(cur_type, id, 1))
146 return gripe("Can't put ID %d into table %s", id, ep->name);
149 cur_obj = ef_ptr(cur_type, id);
150 if (CANT_HAPPEN(!cur_obj))
157 * Get the next object.
158 * Must not have a record index.
159 * Store it in cur_obj, and set cur_id and cur_obj_is_blank accordingly.
160 * Return 0 on success, -1 on failure.
165 int max_id = ef_id_limit(cur_type);
167 if (cur_id >= max_id)
168 return gripe("Too many rows");
169 return tbl_seek(cur_id + 1);
173 * Get the next object, it has record index ID.
174 * Store it in cur_obj, and set cur_id and cur_obj_is_blank accordingly.
175 * Return 0 on success, -1 on failure.
178 tbl_skip_to_obj(int id)
183 return gripe("Field %d must be >= 0", 1);
184 max_id = ef_id_limit(cur_type);
186 return gripe("Field %d must be <= %d", 1, max_id);
188 if (tbl_seek(id) < 0)
195 * If the table has variable length, truncate it.
205 * Read and ignore field separators from FP.
206 * Return first character that is not a field separator.
215 } while (ch == ' ' || ch == '\t');
220 } while (ch != EOF && ch != '\n');
227 * Decode escape sequences in BUF.
228 * Return BUF on success, null pointer on failure.
240 if (sscanf(++src, "%3o%n", &octal_chr, &n) != 1 || n != 3)
242 *dst++ = (char)octal_chr;
252 * Read an identifier from FP into BUF.
253 * BUF must have space for 1024 characters.
254 * Return number of characters read on success, -1 on failure.
257 getid(FILE *fp, char *buf)
260 if (fscanf(fp, "%1023[^\"#()<>= \t\n]%n", buf, &n) != 1
268 * Try to read a field name from FP.
269 * I is the field number, counting from zero.
270 * If a name is read, set fldca[I] and fldidx[I] for it, and update
272 * Return 1 if a name or ... was read, 0 on end of line, -1 on error.
275 xufldname(FILE *fp, int i)
283 return gripe("Unexpected EOF");
290 if (getc(fp) != '.' || getc(fp) != '.')
291 return gripe("Junk in header field %d", i + 1);
292 if (defellipsis() < 0)
295 if (ch != EOF && ch != '\n')
296 return gripe("Junk after ...");
301 if (getid(fp, buf) < 0)
302 return gripe("Junk in header field %d", i + 1);
306 return deffld(i, buf, -1);
310 if (isdigit(ch) || ch == '-' || ch == '+') {
311 if (fscanf(fp, "%d", &idx) != 1)
312 return gripe("Malformed number in index of header field %d",
315 return gripe("Index must not be negative in header field %d",
318 if (getid(fp, buf) < 0)
319 return gripe("Malformed index in header field %d", i + 1);
320 return gripe("Symbolic index in header field %d not yet implemented",
325 return gripe("Malformed index in header field %d", i + 1);
326 return deffld(i, buf, idx);
331 * Try to read a field value from FP.
332 * I is the field number, counting from zero.
333 * Return 1 if a value was read, 0 on end of line, -1 on error.
336 xufld(FILE *fp, int i)
346 return gripe("Unexpected EOF");
348 CANT_HAPPEN(i > nflds);
350 if (fldca[i]->ca_type != NSC_STRINGY && fldca[i]->ca_len)
351 return gripe("Field %s(%d) missing",
352 fldca[i]->ca_name, fldidx[i]);
353 return gripe("Field %s missing", fldca[i]->ca_name);
357 case '+': case '-': case '.':
358 case '0': case '1': case '2': case '3': case '4':
359 case '5': case '6': case '7': case '8': case '9':
361 if (fscanf(fp, "%lg", &dbl) != 1)
362 return gripe("Malformed number in field %d", i + 1);
363 return setnum(i, dbl);
370 if (fscanf(fp, "%1023[^\"\n]", buf) != 1 || getc(fp) != '"')
371 return gripe("Malformed string in field %d", i + 1);
373 return gripe("Invalid escape sequence in field %d",
376 return setstr(i, buf);
378 if (mtsymset(i, &set) < 0)
382 if (ch == EOF || ch == '\n')
383 return gripe("Unmatched '(' in field %d", i + 1);
387 if (getid(fp, buf) < 0)
388 return gripe("Junk in field %d", i + 1);
389 if (add2symset(i, &set, buf) < 0)
392 return setnum(i, set);
395 if (getid(fp, buf) < 0)
396 return gripe("Junk in field %d", i + 1);
397 if (!strcmp(buf, "nil"))
398 return setstr(i, NULL);
400 return setsym(i, buf);
405 * Read fields from FP.
406 * Use PARSE() to read each field.
407 * Return number of fields read on success, -1 on error.
410 xuflds(FILE *fp, int (*parse)(FILE *, int))
423 else if (ch != ' ' && ch != '\t')
424 return gripe("Bad field separator after field %d", i + 1);
429 * Define the FLDNO-th field.
430 * If IDX is negative, define as selector NAME, else as NAME(IDX).
431 * Set fldca[FLDNO] and fldidx[FLDNO] accordingly.
433 * Return 1 on success, -1 on error.
436 deffld(int fldno, char *name, int idx)
438 struct castr *ca = ef_cadef(cur_type);
441 res = stmtch(name, ca, offsetof(struct castr, ca_name),
442 sizeof(struct castr));
444 return gripe("Header %s of field %d is %s", name, fldno + 1,
445 res == M_NOTUNIQUE ? "ambiguous" : "unknown");
446 if ((ca[res].ca_flags & NSC_EXTRA) || CANT_HAPPEN(ca[res].ca_get))
447 return gripe("Extraneous header %s in field %d", name, fldno + 1);
448 if (ca[res].ca_type != NSC_STRINGY && ca[res].ca_len != 0) {
450 return gripe("Header %s requires an index in field %d",
451 ca[res].ca_name, fldno + 1);
452 if (idx >= ca[res].ca_len)
453 return gripe("Header %s(%d) index out of bounds in field %d",
454 ca[res].ca_name, idx, fldno + 1);
455 if (idx < caflds[res])
456 return gripe("Duplicate header %s(%d) in field %d",
457 ca[res].ca_name, idx, fldno + 1);
458 if (idx > caflds[res])
459 return gripe("Expected header %s(%d) in field %d",
460 ca[res].ca_name, caflds[res], fldno + 1);
463 return gripe("Header %s doesn't take an index in field %d",
464 ca[res].ca_name, fldno + 1);
467 return gripe("Duplicate header %s in field %d",
468 ca[res].ca_name, fldno + 1);
470 fldca[fldno] = &ca[res];
477 * Record that header ends with ...
478 * Set ellipsis and is_partial.
479 * Return 0 on success, -1 on error.
484 struct castr *ca = ef_cadef(cur_type);
486 if (ca[0].ca_table != cur_type || (ca[0].ca_flags & NSC_EXTRA))
487 return gripe("Table %s doesn't support ...", ef_nameof(cur_type));
488 ellipsis = is_partial = 1;
493 * Check fields in xdump are sane.
494 * Return 0 on success, -1 on error.
499 struct castr *ca = ef_cadef(cur_type);
500 int i, len, cafldsmax, res = 0;
502 /* Record index must come first, to make cur_id work, see setnum() */
503 if (ca[0].ca_table == cur_type && caflds[0] && fldca[0] != &ca[0])
504 res = gripe("Header field %s must come first", ca[0].ca_name);
507 /* Need a join field, use 0-th selector */
509 res = gripe("Header field %s required in each table part",
514 return res; /* table is split, another part expected */
516 /* Check for missing fields */
517 for (i = 0; ca[i].ca_name; i++) {
518 cafldsmax = MAX(caflds[i], cafldspp[i]);
519 if (ca[i].ca_flags & NSC_EXTRA)
521 len = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
522 if (!len && !cafldsmax)
523 res = gripe("Header field %s missing", ca[i].ca_name);
524 else if (len && cafldsmax == len - 1)
525 res = gripe("Header field %s(%d) missing",
526 ca[i].ca_name, len - 1);
527 else if (len && cafldsmax < len - 1)
528 res = gripe("Header fields %s(%d) ... %s(%d) missing",
529 ca[i].ca_name, cafldsmax, ca[i].ca_name, len - 1);
536 * Get selector for field FLDNO.
537 * Assign the field's selector index to *IDX, unless it is null.
538 * Return the selector on success, null pointer on error.
540 static struct castr *
541 getfld(int fldno, int *idx)
543 if (fldno >= nflds) {
544 gripe("Too many fields, expected only %d", nflds);
547 if (CANT_HAPPEN(fldno < 0))
550 *idx = fldidx[fldno];
555 * Is a new value for field FLDNO required to match the old one?
558 fldval_must_match(int fldno)
560 struct castr *ca = ef_cadef(cur_type);
561 int i = fldca[fldno] - ca;
564 * Value must match if:
565 * it's for a const selector, unless the object is still blank, or
566 * it was already given in a previous part of a split table.
568 return (!cur_obj_is_blank && (fldca[fldno]->ca_flags & NSC_CONST))
569 || fldidx[fldno] < cafldspp[i];
573 * Set value of field FLDNO in current object to DBL.
574 * Return 1 on success, -1 on error.
577 setnum(int fldno, double dbl)
584 ca = getfld(fldno, &idx);
589 if (ca->ca_table == cur_type) {
590 /* Got record index */
593 return gripe("Field %d can't hold this value", fldno + 1);
594 if (tbl_skip_to_obj(next_id) < 0)
597 if (tbl_next_obj() < 0)
602 memb_ptr += ca->ca_off;
604 switch (ca->ca_type) {
606 old = ((signed char *)memb_ptr)[idx];
607 new = ((signed char *)memb_ptr)[idx] = (signed char)dbl;
611 old = ((unsigned char *)memb_ptr)[idx];
612 new = ((unsigned char *)memb_ptr)[idx] = (unsigned char)dbl;
615 old = ((short *)memb_ptr)[idx];
616 new = ((short *)memb_ptr)[idx] = (short)dbl;
619 old = ((unsigned short *)memb_ptr)[idx];
620 new = ((unsigned short *)memb_ptr)[idx] = (unsigned short)dbl;
623 old = ((int *)memb_ptr)[idx];
624 new = ((int *)memb_ptr)[idx] = (int)dbl;
627 old = ((long *)memb_ptr)[idx];
628 new = ((long *)memb_ptr)[idx] = (long)dbl;
631 old = ((coord *)memb_ptr)[idx];
632 /* FIXME use variant of xrel() that takes orig instead of nation */
633 if (old >= WORLD_X / 2)
635 new = ((coord *)memb_ptr)[idx] = XNORM((coord)dbl);
636 if (new >= WORLD_X / 2)
640 old = ((coord *)memb_ptr)[idx];
641 /* FIXME use variant of yrel() that takes orig instead of nation */
642 if (old >= WORLD_Y / 2)
644 new = ((coord *)memb_ptr)[idx] = YNORM((coord)dbl);
645 if (new >= WORLD_Y / 2)
649 old = ((float *)memb_ptr)[idx];
650 ((float *)memb_ptr)[idx] = (float)dbl;
651 new = dbl; /* suppress new != dbl check */
654 old = ((double *)memb_ptr)[idx];
655 ((double *)memb_ptr)[idx] = dbl;
656 new = dbl; /* suppress new != dbl check */
659 old = ((time_t *)memb_ptr)[idx];
660 new = ((time_t *)memb_ptr)[idx] = (time_t)dbl;
663 return gripe("Field %d doesn't take numbers", fldno + 1);
666 if (fldval_must_match(fldno) && old != dbl)
667 return gripe("Value for field %d must be %g", fldno + 1, old);
669 return gripe("Field %d can't hold this value", fldno + 1);
675 * Set value of field FLDNO in current object to STR.
676 * Return 1 on success, -1 on error.
679 setstr(int fldno, char *str)
684 char *memb_ptr, *old;
686 ca = getfld(fldno, &idx);
691 if (tbl_next_obj() < 0)
695 memb_ptr += ca->ca_off;
696 must_match = fldval_must_match(fldno);
698 switch (ca->ca_type) {
700 old = ((char **)memb_ptr)[idx];
702 /* FIXME may leak old value */
703 ((char **)memb_ptr)[idx] = str ? strdup(str) : NULL;
704 len = 65535; /* really SIZE_MAX, but that's C99 */
707 if (CANT_HAPPEN(idx))
710 return gripe("Field %d doesn't take nil", fldno + 1);
712 if (strlen(str) > len)
713 return gripe("Field %d takes at most %d characters",
714 fldno + 1, (int)len);
717 strncpy(memb_ptr, str, len);
720 return gripe("Field %d doesn't take strings", fldno + 1);
724 if (old && (!str || strncmp(old, str, len)))
725 return gripe("Value for field %d must be \"%.*s\"",
726 fldno + 1, (int)len, old);
728 return gripe("Value for field %d must be nil", fldno + 1);
735 * Resolve symbol name ID in table referred to by CA.
736 * Use field number N for error messages.
737 * Return index in referred table on success, -1 on failure.
740 xunsymbol(char *id, struct castr *ca, int n)
742 int i = ef_elt_byname(ca->ca_table, id);
744 return gripe("%s %s symbol `%s' in field %d",
745 i == M_NOTUNIQUE ? "Ambiguous" : "Unknown",
746 ca->ca_name, id, n + 1);
751 * Map symbol index to symbol value.
752 * CA is the table, and I is the index in it.
755 symval(struct castr *ca, int i)
757 int type = ca->ca_table;
759 if (type != EF_BAD && ef_cadef(type) == symbol_ca)
760 /* symbol table, value is in the table */
761 return ((struct symbol *)ef_ptr(type, i))->value;
762 /* value is the table index */
767 * Set value of field FLDNO in current object to value of symbol SYM.
768 * Return 1 on success, -1 on error.
771 setsym(int fldno, char *sym)
776 ca = getfld(fldno, NULL);
780 if (ca->ca_table == EF_BAD || (ca->ca_flags & NSC_BITS))
781 return gripe("Field %d doesn't take symbols", fldno + 1);
783 i = xunsymbol(sym, ca, fldno);
786 return setnum(fldno, symval(ca, i));
790 * Create an empty symbol set for field FLDNO in *SET.
791 * Return 1 on success, -1 on error.
794 mtsymset(int fldno, long *set)
798 ca = getfld(fldno, NULL);
802 if (ca->ca_table == EF_BAD || ef_cadef(ca->ca_table) != symbol_ca
803 || !(ca->ca_flags & NSC_BITS))
804 return gripe("Field %d doesn't take symbol sets", fldno + 1);
810 * Add a symbol to a symbol set for field FLDNO in *SET.
811 * SYM is the name of the symbol to add.
812 * Return 1 on success, -1 on error.
815 add2symset(int fldno, long *set, char *sym)
820 ca = getfld(fldno, NULL);
824 i = xunsymbol(sym, ca, fldno);
827 *set |= symval(ca, i);
832 * Read an xdump table header line from FP.
833 * Expect header for EXPECTED_TABLE, unless it is EF_BAD.
834 * Recognize header for machine- and human-readable syntax, and set
836 * Return table type on success, -2 on EOF before header, -1 on failure.
839 xuheader(FILE *fp, int expected_table)
845 while ((ch = skipfs(fp)) == '\n')
847 if (ch == EOF && expected_table == EF_BAD)
854 ? fscanf(fp, "config%*[ \t]%63[^ \t#\n]%n", name, &res) != 1
855 : fscanf(fp, "XDUMP%*[ \t]%63[^ \t#\n]%*[ \t]%*[^ \t#\n]%n",
856 name, &res) != 1) || res < 0)
857 return gripe("Expected xdump header");
859 type = ef_byname(name);
861 return gripe("Unknown table `%s'", name);
862 if (expected_table != EF_BAD && expected_table != type)
863 return gripe("Expected table `%s', not `%s'",
864 ef_nameof(expected_table), name);
866 if (!empfile[type].file
867 || !ef_cadef(type) || !(ef_flags(type) & EFF_MEM)) {
868 CANT_HAPPEN(expected_table != EF_BAD);
869 return gripe("Table `%s' is not permitted here", name);
872 if (skipfs(fp) != '\n')
873 return gripe("Junk after xdump header");
880 * Find fields in this xdump.
881 * If reading human-readable syntax, read a field header line from FP.
882 * Else take fields from the table's selectors in CA[].
883 * Set ellipsis, nflds, fldca[], fldidx[] and caflds[] accordingly.
884 * Return 0 on success, -1 on failure.
887 xufldhdr(FILE *fp, struct castr ca[])
893 for (i = 0; ca[i].ca_name; i++)
898 while ((ch = skipfs(fp)) == '\n')
901 nflds = xuflds(fp, xufldname);
904 nflds -= ellipsis != 0;
909 for (i = 0; ca[i].ca_name; i++) {
910 if ((ca[i].ca_flags & NSC_EXTRA))
912 n = ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0;
920 nflds = fidx - fldidx;
927 * Read xdump footer from FP.
928 * CA[] contains the table's selectors.
929 * The body had RECS records.
930 * Update cafldspp[] from caflds[].
931 * Return 0 on success, -1 on failure.
934 xufooter(FILE *fp, struct castr ca[], int recs)
940 if (fscanf(fp, "config%n", &res) != 0 || res < 0)
941 return gripe("Malformed table footer");
943 if (fscanf(fp, "%d", &n) != 1)
944 return gripe("Malformed table footer");
946 return gripe("Read %d rows, which doesn't match footer "
949 if (skipfs(fp) != '\n')
950 return gripe("Junk after table footer");
954 for (i = 0; ca[i].ca_name; i++) {
955 if (cafldspp[i] < caflds[i])
956 cafldspp[i] = caflds[i];
963 * Read an xdump table from FP.
964 * Both machine- and human-readable xdump syntax are recognized.
965 * Expect table EXPECTED_TABLE, unless it is EF_BAD.
966 * Report errors to stderr.
967 * Messages assume FP starts in the file FILE at line *PLNO.
968 * Update *PLNO to reflect lines read from FP.
969 * Return table type on success, -2 on EOF before header, -1 on failure.
972 xundump(FILE *fp, char *file, int *plno, int expected_table)
975 int type, nca, nf, i, ch;
980 if ((type = xuheader(fp, expected_table)) < 0)
984 if (CANT_HAPPEN(!ca))
988 for (i = 0; ca[i].ca_name; i++) {
990 if (!(ca[i].ca_flags & NSC_EXTRA))
991 nf += MAX(1, ca[i].ca_type != NSC_STRINGY ? ca[i].ca_len : 0);
993 fldca = malloc(nf * sizeof(*fldca));
994 fldidx = malloc(nf * sizeof(*fldidx));
995 caflds = malloc(nca * sizeof(*caflds));
996 cafldspp = calloc(nca, sizeof(*cafldspp));
999 if (xutail(fp, ca) < 0)
1008 /* Skip empty lines so that callers can easily check for EOF */
1009 while ((ch = skipfs(fp)) == '\n')
1018 * Read the remainder of an xdump after the table header line from FP.
1019 * CA[] contains the table's selectors.
1020 * Return 0 on success, -1 on failure.
1023 xutail(FILE *fp, struct castr *ca)
1029 if (xufldhdr(fp, ca) < 0)
1031 if ((recs = xubody(fp)) < 0)
1033 if (xufooter(fp, ca, recs) < 0)
1037 if (xuheader(fp, cur_type) < 0)
1043 * Read the body of an xdump table from FP.
1044 * Return number of rows read on success, -1 on failure.
1049 struct empfile *ep = &empfile[cur_type];
1054 while ((ch = skipfs(fp)) == '\n')
1059 if (xuflds(fp, xufld) < 0)
1061 maxid = MAX(maxid, cur_id + 1);
1064 if (CANT_HAPPEN(maxid > ep->fids))
1066 if (maxid < ep->fids) {
1068 && (EF_IS_GAME_STATE(cur_type)
1069 || (cur_type >= EF_SHIP_CHR && cur_type <= EF_NUKE_CHR))) {
1070 if (!ef_truncate(cur_type, maxid))
1073 return gripe("Table %s requires %d rows, got %d",
1074 ef_nameof(cur_type), ep->fids, maxid);