]> git.pond.sub.org Git - empserver/blob - src/lib/subs/nstr.c
Symbolic names for table entries in conditionals, closes #928376:
[empserver] / src / lib / subs / nstr.c
1 /*
2  *  Empire - A multi-player, client/server Internet based war game.
3  *  Copyright (C) 1986-2006, Dave Pare, Jeff Bailey, Thomas Ruschak,
4  *                           Ken Stevens, Steve McClure
5  *
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.
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, write to the Free Software
18  *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  *
20  *  ---
21  *
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.
25  *
26  *  ---
27  *
28  *  nstr.c: compile and execute the item selections on sectors
29  * 
30  *  Known contributors to this file:
31  *     Dave Pare, 1989
32  *     Steve McClure, 1997
33  *     Markus Armbruster, 2004-2005
34  */
35
36 #include <config.h>
37
38 #include <limits.h>
39 #include "misc.h"
40 #include "file.h"
41 #include "match.h"
42 #include "nsc.h"
43 #include "optlist.h"
44 #include "prototypes.h"
45
46 static char *nstr_parse_val(char *, struct valstr *);
47 static int nstr_match_ca(struct valstr *, struct castr *);
48 static int nstr_match_val(struct valstr *, struct castr *, int);
49 static int nstr_string_ok(struct castr *ca, int idx);
50 static struct valstr *nstr_resolve_sel(struct valstr *, struct castr *);
51 static struct valstr *nstr_mkselval(struct valstr *, int, struct castr *);
52 static struct valstr *nstr_resolve_id(struct valstr *, struct castr *, int, int);
53 static int nstr_promote(int);
54
55
56 /*
57  * Compile conditions into array NP[LEN].
58  * Return number of conditions, or -1 on error.
59  * It is an error if there are more than LEN conditions.
60  * TYPE is the context type, a file type.
61  * STR is the condition string, in Empire syntax, without the leading
62  * '?'.
63  */
64 int
65 nstr_comp(struct nscstr *np, int len, int type, char *str)
66 {
67     struct castr *ca = ef_cadef(type);
68     char *cond;
69     char *tail;
70     int i;
71     struct nscstr dummy;
72     int lft_caidx, rgt_caidx;
73     int lft_val, rgt_val;
74     int lft_type, rgt_type;
75
76     cond = str;
77     for (i = 0; ; ++i, ++np) {
78         if (i >= len)
79             np = &dummy;
80
81         /* left operand */
82         tail = nstr_parse_val(cond, &np->lft);
83         lft_caidx = nstr_match_ca(&np->lft, ca);
84
85         /* operator */
86         if (*tail != '<' && *tail != '=' && *tail != '>' && *tail != '#') {
87             if (*tail)
88                 pr("%s -- expected condition operator\n", cond);
89             else
90                 pr("%s -- missing condition operator\n", cond);
91             return -1;
92         }
93         np->operator = *tail;
94         ++tail;
95
96         /* right operand */
97         tail = nstr_parse_val(tail, &np->rgt);
98         rgt_caidx = nstr_match_ca(&np->rgt, ca);
99
100         /*
101          * Resolve identifiers
102          *
103          * An identifier can name a selector or, if the other operand
104          * is a selector, a value for that.  The condition is
105          * ambiguous if both selector x value and value x selector are
106          * possible.  Example: n<n for sectors could mean newdes<n or
107          * n<newdes.
108          */
109         lft_val = nstr_match_val(&np->lft, ca, rgt_caidx);
110         rgt_val = nstr_match_val(&np->rgt, ca, lft_caidx);
111         /*
112          * if lft_val >= 0, then rhs names a selector and lhs names
113          * one of its values.  Likewise for rgt_val.
114          */
115         if (lft_val >= 0 && rgt_val >= 0) {
116             pr("%.*s -- condition ambiguous\n", (int)(tail-cond), cond);
117             return -1;
118         } else if (rgt_val >= 0) {
119             /* selector x value */
120             if (!nstr_resolve_sel(&np->lft, &ca[lft_caidx]))
121                 return -1;
122             nstr_mkselval(&np->rgt, rgt_val, &ca[lft_caidx]);
123         } else if (lft_val >= 0) {
124             /* value x selector */
125             nstr_mkselval(&np->lft, lft_val, &ca[rgt_caidx]);
126             if (!nstr_resolve_sel(&np->rgt, &ca[rgt_caidx]))
127                 return -1;
128         } else {
129             /*
130              * Neither side works as selector value; any identifiers
131              * must name selectors.
132              */
133             if (!nstr_resolve_id(&np->lft, ca, lft_caidx,
134                                  nstr_string_ok(ca, rgt_caidx)))
135                 return -1;
136             if (!nstr_resolve_id(&np->rgt, ca, rgt_caidx,
137                                  nstr_string_ok(ca, lft_caidx)))
138                 return -1;
139         }
140
141         /* find operator type, coerce operands */
142         lft_type = nstr_promote(np->lft.val_type);
143         rgt_type = nstr_promote(np->rgt.val_type);
144         np->optype = NSC_NOTYPE;
145         if (lft_type == NSC_STRING) {
146             if (!nstr_coerce_val(&np->rgt, NSC_STRING, str))
147                 np->optype = NSC_STRING;
148         } else if (rgt_type == NSC_STRING) {
149             if (!nstr_coerce_val(&np->lft, NSC_STRING, str))
150                 np->optype = NSC_STRING;
151         } else if (lft_type == NSC_DOUBLE) {
152             if (!nstr_coerce_val(&np->rgt, NSC_DOUBLE, str))
153                 np->optype = NSC_DOUBLE;
154         } else if (rgt_type == NSC_DOUBLE) {
155             if (!nstr_coerce_val(&np->lft, NSC_DOUBLE, str))
156                 np->optype = NSC_DOUBLE;
157         } else {
158             if (!nstr_coerce_val(&np->lft, NSC_LONG, str)
159                 && !nstr_coerce_val(&np->rgt, NSC_LONG, str))
160                 np->optype = NSC_LONG;
161         }
162         if (np->optype == NSC_NOTYPE)
163             return -1;
164
165         /* another condition? */
166         if (*tail == 0)
167             break;
168         if (*tail != '&') {
169             pr("%s -- expected `&'\n", cond);
170             return -1;
171         }
172         cond = tail + 1;
173     }
174
175     if (i >= len) {
176         /* could just return I and let caller gripe or enlarge buffer */
177         pr("%s -- too many conditions\n", str);
178         return -1;
179     }
180
181     return i + 1;
182 }
183
184 /* Like strcmp(S1, S2), but limit length of S1 to SZ1 and of S2 to SZ2.  */
185 static int
186 strnncmp(char *s1, size_t sz1, char *s2, size_t sz2)
187 {
188     int res;
189     if (sz1 == sz2) return strncmp(s1, s2, sz2);
190     if (sz1 < sz2) return -strnncmp(s2, sz2, s1, sz1);
191     res = strncmp(s1, s2, sz2);
192     return res ? res : s1[sz2];
193 }
194
195 #define EVAL(op, lft, rgt)                      \
196     ((op) == '<' ? (lft) < (rgt)                \
197      : (op) == '=' ? (lft) == (rgt)             \
198      : (op) == '>' ? (lft) > (rgt)              \
199      : (op) == '#' ? (lft) != (rgt)             \
200      : 0)
201
202 /*
203  * Evaluate compiled conditions in array NP[NCOND].
204  * Return non-zero iff they are all true.
205  * PTR points to a context object of the type that was used to compile
206  * the conditions.
207  */
208 int
209 nstr_exec(struct nscstr *np, int ncond, void *ptr)
210 {
211     int i, op, optype, cmp;
212     struct valstr lft, rgt;
213
214     for (i = 0; i < ncond; ++i) {
215         op = np[i].operator;
216         optype = np[i].optype;
217         if (np[i].lft.val_cat == NSC_NOCAT || np[i].rgt.val_cat == NSC_NOCAT)
218             return 0;
219         lft = np[i].lft;
220         nstr_exec_val(&lft, player->cnum, ptr, optype);
221         rgt = np[i].rgt;
222         nstr_exec_val(&rgt, player->cnum, ptr, optype);
223         switch (optype) {
224         case NSC_LONG:
225             if (!EVAL(op, lft.val_as.lng, rgt.val_as.lng))
226                 return 0;
227             break;
228         case NSC_DOUBLE:
229             if (!EVAL(op, lft.val_as.dbl, rgt.val_as.dbl))
230                 return 0;
231             break;
232         case NSC_STRING:
233             cmp = strnncmp(lft.val_as.str.base, lft.val_as.str.maxsz,
234                            rgt.val_as.str.base, rgt.val_as.str.maxsz);
235             if (!EVAL(op, cmp, 0))
236                 return 0;
237             break;
238         default:
239             CANT_REACH();
240             return 0;
241         }
242     }
243
244     return 1;
245 }
246
247 /*
248  * Parse a value in STR into VAL.
249  * Return a pointer to the first character after the value.
250  * Value is either evaluated into NSC_STRING, NSC_DOUBLE or NSC_LONG,
251  * or an identifier.
252  */
253 static char *
254 nstr_parse_val(char *str, struct valstr *val)
255 {
256     long l;
257     double d;
258     char *tail, *tail2;
259
260     /* string */
261     if (str[0] == '\'') {
262         for (tail = str + 1; *tail && *tail != '\''; ++tail) ;
263         /* FIXME implement \ quoting */
264         val->val_type = NSC_STRING;
265         val->val_cat = NSC_VAL;
266         val->val_as.str.base = str + 1;
267         val->val_as.str.maxsz = tail - (str + 1);
268         if (*tail) ++tail;
269         /* FIXME else unclosed string */
270         return tail;
271     }
272
273     /* identifier */
274     if (isalpha(str[0])) {
275         for (tail = str+1; isalnum(*tail) || *tail == '_'; ++tail) ;
276         val->val_type = NSC_NOTYPE;
277         val->val_cat = NSC_ID;
278         val->val_as.str.base = str;
279         val->val_as.str.maxsz = tail - str;
280         return tail;
281     }
282
283     /* number */
284     l = strtol(str, &tail, 0);
285     d = strtod(str, &tail2);
286     if (tail2 > tail) {
287         val->val_type = NSC_DOUBLE;
288         val->val_cat = NSC_VAL;
289         val->val_as.dbl = d;
290         return tail2;
291     }
292     if (tail != str) {
293         val->val_type = NSC_LONG;
294         val->val_cat = NSC_VAL;
295         val->val_as.lng = l;
296         return tail;
297     }
298
299     /* funny character, interpret as identifier */
300     tail = str+1;
301     val->val_type = NSC_NOTYPE;
302     val->val_cat = NSC_ID;
303     val->val_as.str.base = str;
304     val->val_as.str.maxsz = tail - str;
305     return tail;
306 }
307
308 /*
309  * Match VAL in table of selector descriptors CA, return index.
310  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
311  * several.
312  * A VAL that is not an identifier doesn't match anything.  A null CA
313  * is considered empty.
314  */
315 static int
316 nstr_match_ca(struct valstr *val, struct castr *ca)
317 {
318     char id[32];
319
320     if (val->val_cat != NSC_ID || val->val_as.str.maxsz >= sizeof(id))
321         return M_NOTFOUND;
322
323     if (!ca)
324         return M_NOTFOUND;
325
326     memcpy(id, val->val_as.str.base, val->val_as.str.maxsz);
327     id[val->val_as.str.maxsz] = 0;
328
329     return stmtch(id, ca, offsetof(struct castr, ca_name),
330                   sizeof(struct castr));
331 }
332
333 /*
334  * Match VAL in a selector's values, return its (non-negative) value.
335  * Match values of selector descriptor CA[IDX], provided IDX is not
336  * negative.  CA may be null when IDX is negative.
337  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
338  * several.
339  */
340 static int
341 nstr_match_val(struct valstr *val, struct castr *ca, int idx)
342 {
343     char id[32];
344
345     if (val->val_cat != NSC_ID || val->val_as.str.maxsz >= sizeof(id))
346         return M_NOTFOUND;
347
348     if (idx < 0 || ca[idx].ca_table == EF_BAD)
349         return M_NOTFOUND;
350     if (CANT_HAPPEN(nstr_promote(ca[idx].ca_type) != NSC_LONG))
351         return M_NOTFOUND;
352
353     memcpy(id, val->val_as.str.base, val->val_as.str.maxsz);
354     id[val->val_as.str.maxsz] = 0;
355
356     return ef_elt_byname(ca[idx].ca_table, id);
357 }
358
359 /*
360  * Can CA[IDX] be compared to a string?
361  * Return 0 for negative IDX.
362  */
363 static int
364 nstr_string_ok(struct castr *ca, int idx)
365 {
366     return idx >= 0 && nstr_promote(ca[idx].ca_type) == NSC_STRING;
367 }
368
369 /*
370  * Change VAL to resolve identifier to selector or string.
371  * Return VAL on success, NULL on error.
372  * No change if VAL is not an identifier.  Otherwise, change it as
373  * follows.
374  * Error if IDX == M_NOTUNIQUE or IDX == M_NOTFOUND and !STRING_OK.
375  * Change into string if IDX == M_NOTFOUND and STRING_OK.
376  * Change into selector CA[IDX] if IDX >= 0.
377  */
378 static struct valstr *
379 nstr_resolve_id(struct valstr *val, struct castr *ca, int idx, int string_ok)
380 {
381     if (val->val_cat != NSC_ID)
382         return val;
383
384     if (idx == M_NOTUNIQUE && !string_ok) {
385         pr("%.*s -- ambiguous name\n",
386            (int)val->val_as.str.maxsz, val->val_as.str.base);
387         val->val_cat = NSC_NOCAT;
388         return NULL;
389     }
390
391     if (idx == M_NOTFOUND && !string_ok) {
392         pr("%.*s -- unknown name\n",
393            (int)val->val_as.str.maxsz, val->val_as.str.base);
394         val->val_cat = NSC_NOCAT;
395         return NULL;
396     }
397
398     if (idx < 0) {
399         CANT_HAPPEN(!string_ok);
400         /* interpret unresolvable identifier as string */
401         val->val_type = NSC_STRING;
402         val->val_cat = NSC_VAL;
403         /* map identifier ~ to empty string, like some commands do */
404         if (val->val_as.str.maxsz == 1 && val->val_as.str.base[0] == '~')
405             val->val_as.str.maxsz = 0;
406         return val;
407     }
408
409     return nstr_resolve_sel(val, &ca[idx]);
410 }
411
412 /*
413  * Change VAL to resolve identifier to selector CA.
414  * Return VAL on success, NULL if the player is denied access to the
415  * selector.
416  * VAL must be an identifier.
417  */
418 static struct valstr *
419 nstr_resolve_sel(struct valstr *val, struct castr *ca)
420 {
421     if (CANT_HAPPEN(val->val_cat != NSC_ID)) {
422         val->val_cat = NSC_NOCAT;
423         return val;
424     }
425
426     if ((ca->ca_flags & NSC_DEITY) && !player->god) {
427         pr("%.*s -- not accessible to mortals\n",
428            (int)val->val_as.str.maxsz, val->val_as.str.base);
429         val->val_cat = NSC_NOCAT;
430         return NULL;
431     }
432
433     val->val_type = ca->ca_type;
434     val->val_cat = NSC_OFF;
435     val->val_as.sym.off = ca->ca_off;
436     val->val_as.sym.len = ca->ca_len;
437     val->val_as.sym.idx = 0;
438     return val;
439 }
440
441 /*
442  * Initialize VAL to value SELVAL for selector CA, return VAL.
443  */
444 static struct valstr *
445 nstr_mkselval(struct valstr *val, int selval, struct castr *ca)
446 {
447     if (CANT_HAPPEN(nstr_promote(ca->ca_type) != NSC_LONG
448                     || ca->ca_table == EF_BAD)) {
449         val->val_type = NSC_NOTYPE;
450         val->val_cat = NSC_NOCAT;
451         return val;
452     }
453
454     val->val_type = ca->ca_type;
455     val->val_cat = NSC_VAL;
456     val->val_as.lng = selval;
457     return val;
458 }
459
460 /*
461  * Compile a value in STR into VAL.
462  * Return a pointer to the first character after the value on success,
463  * NULL on error.
464  * TYPE is the context type, a file type.
465  * If STR names an array, VAL simply refers to the element with index
466  * zero.
467  */
468 char *
469 nstr_comp_val(char *str, struct valstr *val, int type)
470 {
471     struct castr *ca = ef_cadef(type);
472     char *tail = nstr_parse_val(str, val);
473     if (!nstr_resolve_id(val, ca, nstr_match_ca(val, ca), 0))
474         return NULL;
475     return tail;
476 }
477
478
479 /*
480  * Promote VALTYPE.
481  * If VALTYPE is an integer type, return NSC_LONG.
482  * If VALTYPE is a floating-point type, return NSC_DOUBLE.
483  * If VALTYPE is a string type, return NSC_STRING.
484  */
485 static int
486 nstr_promote(int valtype)
487 {
488     switch (valtype) {
489     case NSC_LONG:
490     case NSC_DOUBLE:
491     case NSC_STRING:
492         break;
493     case NSC_CHAR:
494     case NSC_UCHAR:
495     case NSC_SHORT:
496     case NSC_USHORT:
497     case NSC_INT:
498     case NSC_XCOORD:
499     case NSC_YCOORD:
500     case NSC_HIDDEN:
501     case NSC_TIME:
502         valtype = NSC_LONG;
503         break;
504     case NSC_FLOAT:
505         valtype = NSC_DOUBLE;
506         break;
507     case NSC_STRINGY:
508         valtype = NSC_STRING;
509         break;
510     default:
511         CANT_REACH();
512         valtype = NSC_NOTYPE;
513     }
514     return valtype;
515 }
516
517 static int
518 cond_type_mismatch(char *str)
519 {
520     if (str)
521         pr("%s -- condition operand type mismatch\n", str);
522     return -1;
523 }
524
525 /*
526  * Coerce VAL to promoted value type TO.
527  * Return 0 on success, -1 on error.
528  * If VAL is evaluated, convert it, else only check.
529  * STR is the condition text to be used for error messages.  Suppress
530  * messages if it is a null pointer.
531  */
532 int
533 nstr_coerce_val(struct valstr *val, nsc_type to, char *str)
534 {
535     /* FIXME get rid of promotion?  */
536     nsc_type from = nstr_promote(val->val_type);
537
538     if (from == NSC_NOTYPE)
539         return 0;
540
541     if (from != to) {
542         switch (to) {
543         case NSC_STRING:
544             return cond_type_mismatch(str); /* FIXME implement */
545         case NSC_DOUBLE:
546             if (from == NSC_LONG) {
547                 if (val->val_cat == NSC_VAL)
548                     val->val_as.dbl = val->val_as.lng;
549             } else
550                 return cond_type_mismatch(str);
551             break;
552         case NSC_LONG:
553             return cond_type_mismatch(str);
554         default:
555             CANT_REACH();
556             to = from;
557         }
558     }
559
560     if (val->val_cat == NSC_VAL) {
561         /* unimplemented conversions; don't currently occur here */
562         CANT_HAPPEN(val->val_type == NSC_XCOORD
563                     || val->val_type == NSC_YCOORD
564                     || val->val_type == NSC_HIDDEN);
565         val->val_type = to;
566     }
567
568     return 0;
569 }
570
571 /*
572  * Evaluate VAL.
573  * If VAL is symbolic, evaluate it into a promoted value type.
574  * Use coordinate system of country CNUM.
575  * PTR points to a context object of the type that was used to compile
576  * the value.
577  * Unless WANT is NSC_NOTYPE, coerce the value to promoted value type
578  * WANT.  VAL must be coercible.  That's the case if a previous
579  * nstr_coerce_val(VAL, WANT, STR) succeeded.
580  */
581 void
582 nstr_exec_val(struct valstr *val, natid cnum, void *ptr, nsc_type want)
583 {
584     char *memb_ptr;
585     nsc_type valtype;
586     int idx;
587     struct natstr *natp;
588
589     switch (val->val_cat) {
590     default:
591         CANT_REACH();
592         /* fall through */
593     case NSC_VAL:
594         valtype = val->val_type;
595         break;
596     case NSC_OFF:
597         valtype = NSC_LONG;
598         memb_ptr = ptr;
599         memb_ptr += val->val_as.sym.off;
600         idx = val->val_as.sym.idx;
601         switch (val->val_type) {
602         case NSC_CHAR:
603             val->val_as.lng = ((signed char *)memb_ptr)[idx];
604             break;
605         case NSC_UCHAR:
606             val->val_as.lng = ((unsigned char *)memb_ptr)[idx];
607             break;
608         case NSC_SHORT:
609             val->val_as.lng = ((short *)memb_ptr)[idx];
610             break;
611         case NSC_USHORT:
612             val->val_as.lng = ((unsigned short *)memb_ptr)[idx];
613             break;
614         case NSC_INT:
615             val->val_as.lng = ((int *)memb_ptr)[idx];
616             break;
617         case NSC_LONG:
618             val->val_as.lng = ((long *)memb_ptr)[idx];
619             break;
620         case NSC_XCOORD:
621             val->val_as.lng = xrel(getnatp(cnum), ((short *)memb_ptr)[idx]);
622             break;
623         case NSC_YCOORD:
624             val->val_as.lng = yrel(getnatp(cnum), ((short *)memb_ptr)[idx]);
625             break;
626         case NSC_HIDDEN:
627             val->val_as.lng = -1;
628             if (CANT_HAPPEN(((struct natstr *)ptr)->ef_type != EF_NATION))
629                 break;
630             natp = getnatp(cnum);
631             if (!opt_HIDDEN
632                 || natp->nat_stat == STAT_GOD
633                 || (getcontact(natp, idx) && getcontact(ptr, idx)))
634                 val->val_as.lng = ((unsigned char *)memb_ptr)[idx];
635             break;
636         case NSC_FLOAT:
637             val->val_as.dbl = ((float *)memb_ptr)[idx];
638             valtype = NSC_DOUBLE;
639             break;
640         case NSC_DOUBLE:
641             val->val_as.dbl = ((double *)memb_ptr)[idx];
642             valtype = NSC_DOUBLE;
643             break;
644         case NSC_STRINGY:
645             CANT_HAPPEN(idx);
646             val->val_as.str.maxsz = val->val_as.sym.len;
647             val->val_as.str.base = (char *)memb_ptr;
648             valtype = NSC_STRING;
649             break;
650         case NSC_STRING:
651             val->val_as.str.base = ((char **)memb_ptr)[idx];
652             val->val_as.str.maxsz = INT_MAX;
653             valtype = NSC_STRING;
654             break;
655         case NSC_TIME:
656             val->val_as.lng = ((time_t *)memb_ptr)[idx];
657             break;
658         default:
659             CANT_REACH();
660             val->val_as.lng = 0;
661         }
662         val->val_cat = NSC_VAL;
663     }
664
665     if (valtype == want)
666         ;
667     else if (want == NSC_DOUBLE) {
668         if (valtype == NSC_LONG) {
669             valtype = want;
670             val->val_as.dbl = val->val_as.lng;
671         }
672     } else if (want == NSC_STRING)
673         CANT_REACH();           /* FIXME implement */
674
675     if (CANT_HAPPEN(valtype != want && want != NSC_NOTYPE)) {
676         valtype = want;
677         switch (want) {
678         case NSC_LONG: val->val_as.lng = 0; break;
679         case NSC_DOUBLE: val->val_as.dbl = 0.0; break;
680         case NSC_STRING: val->val_as.str.base = NULL; break;
681         default:
682             CANT_REACH();
683         }
684     }
685
686     val->val_type = valtype;
687 }
688
689 char *
690 symbol_by_value(int key, struct symbol *table)
691 {
692     int i;
693
694     for (i = 0; table[i].name; i++)
695         if (key == table[i].value)
696             return table[i].name;
697
698     return NULL;
699 }