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