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