]> 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-2014, 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  *  nstr.c: compile and execute the item selections on sectors
28  *
29  *  Known contributors to this file:
30  *     Dave Pare, 1989
31  *     Steve McClure, 1997
32  *     Markus Armbruster, 2004-2013
33  */
34
35 #include <config.h>
36
37 #include <ctype.h>
38 #include <limits.h>
39 #include "file.h"
40 #include "match.h"
41 #include "nsc.h"
42 #include "player.h"
43 #include "prototypes.h"
44
45 static char *nstr_parse_val(char *, struct valstr *);
46 static int nstr_match_ca(struct valstr *, struct castr *);
47 static int nstr_is_name_of_ca(struct valstr *, struct castr *, int);
48 static int nstr_ca_comparable(struct castr *, int, int);
49 static int nstr_match_val(struct valstr *, struct castr *, int);
50 static struct valstr *nstr_resolve_id(struct valstr *, struct castr *, int);
51 static struct valstr *nstr_resolve_val(struct valstr *, int, struct castr *);
52 static int nstr_optype(enum nsc_type, enum nsc_type);
53
54 /*
55  * Compile conditions into array NP[LEN].
56  * Return number of conditions, or -1 on error.
57  * It is an error if there are more than LEN conditions.
58  * TYPE is the context type, a file type.
59  * STR is the condition string, in Empire syntax, without the leading
60  * '?'.
61  */
62 int
63 nstr_comp(struct nscstr *np, int len, int type, char *str)
64 {
65     struct castr *ca = ef_cadef(type);
66     char *cond;
67     char *tail;
68     int i;
69     struct nscstr dummy;
70     int lft_caidx, rgt_caidx;
71     int lft_val, rgt_val;
72     int two_sels;
73
74     cond = str;
75     for (i = 0; ; ++i, ++np) {
76         if (i >= len)
77             np = &dummy;
78
79         /* left operand */
80         if (!*cond) {
81             pr("%s -- %scondition expected\n", str, i ? "another " : "");
82             return -1;
83         }
84         tail = nstr_parse_val(cond, &np->lft);
85         lft_caidx = nstr_match_ca(&np->lft, ca);
86
87         /* operator */
88         if (*tail != '<' && *tail != '=' && *tail != '>' && *tail != '#') {
89             if (*tail)
90                 pr("%s -- expected condition operator\n", cond);
91             else
92                 pr("%s -- missing condition operator\n", cond);
93             return -1;
94         }
95         np->operator = *tail;
96         ++tail;
97
98         /* right operand */
99         if (!*tail) {
100             pr("%s -- operand expected\n", cond);
101             return -1;
102         }
103         tail = nstr_parse_val(tail, &np->rgt);
104         rgt_caidx = nstr_match_ca(&np->rgt, ca);
105
106         /*
107          * Resolve identifiers
108          *
109          * If just one operand is an identifier, it names a selector.
110          * If both operands are identifiers, things get complicated:
111          * either can then name a selector or a symbolic value for the
112          * selector named by the other operand.
113          */
114         if (np->lft.val_cat == NSC_ID && np->rgt.val_cat == NSC_ID) {
115             lft_val = nstr_match_val(&np->lft, ca, rgt_caidx);
116             rgt_val = nstr_match_val(&np->rgt, ca, lft_caidx);
117             two_sels = nstr_ca_comparable(ca, lft_caidx, rgt_caidx);
118             /*
119              * If lft_val >= 0 interpreting rgt as a selector and lft
120              * as one of its values works.  Likewise for rgt_val >= 0.
121              * If two_sels, interpreting both lft and rgt as selector
122              * works.
123              */
124             switch ((lft_val >= 0) + (rgt_val >= 0) + !!two_sels) {
125             case 0:             /* no interpretation */
126                 if (lft_caidx >= 0 && rgt_caidx >= 0) {
127                     /*
128                      * Both identifiers name selectors.  Since
129                      * !two_sels, they can't be comparable.
130                      * Example: type=civil.
131                      */
132                     pr("%.*s -- not comparable\n", (int)(tail-cond), cond);
133                     return -1;
134                 }
135                 /*
136                  * At least one identifier doesn't name a selector,
137                  * and nstr_resolve_id() will fail for it below
138                  */
139                 break;
140             case 1:             /* one unambigous interpretation */
141                 break;
142             default:            /* multiple interpretations */
143                 /*
144                  * Last-resort disambiguation: if the identifier is
145                  * the unabbreviated name of a selector, discard
146                  * value, else discard selector interpretation.
147                  * Example: resolve wing=g to wing='g', not wing=group
148                  * or 'wing'=group.
149                  */
150                 if (nstr_is_name_of_ca(&np->lft, ca, lft_caidx))
151                     lft_val = -1;
152                 else
153                     two_sels = 0;
154                 if (nstr_is_name_of_ca(&np->rgt, ca, rgt_caidx))
155                     rgt_val = -1;
156                 else
157                     two_sels = 0;
158                 if ((lft_val >= 0) + (rgt_val >= 0) + !!two_sels == 1)
159                     break;      /* last-resort disambiguation worked */
160                 /*
161                  * Example: n<n for sectors could mean newdes<n or
162                  * n<newdes.
163                  */
164                 pr("%.*s -- condition ambiguous\n", (int)(tail-cond), cond);
165                 return -1;
166             }
167             /* resolve identifiers naming values */
168             if (lft_val >= 0)
169                 nstr_resolve_val(&np->lft, lft_val, &ca[rgt_caidx]);
170             if (rgt_val >= 0)
171                 nstr_resolve_val(&np->rgt, rgt_val, &ca[lft_caidx]);
172         }
173         /* remaining identifiers name selectors */
174         if (!nstr_resolve_id(&np->lft, ca, lft_caidx))
175             return -1;
176         if (!nstr_resolve_id(&np->rgt, ca, rgt_caidx))
177             return -1;
178
179         /* find operator type */
180         np->optype = nstr_optype(np->lft.val_type, np->rgt.val_type);
181         if (np->optype == NSC_NOTYPE) {
182             pr("%.*s -- not comparable\n", (int)(tail-cond), cond);
183             return -1;
184         }
185
186         /* another condition? */
187         if (*tail == 0)
188             break;
189         if (*tail != '&') {
190             pr("%s -- expected `&'\n", cond);
191             return -1;
192         }
193         cond = tail + 1;
194     }
195
196     if (i >= len) {
197         /* could just return I and let caller gripe or enlarge buffer */
198         pr("%s -- too many conditions\n", str);
199         return -1;
200     }
201
202     return i + 1;
203 }
204
205 /* Like strcmp(S1, S2), but limit length of S1 to SZ1 and of S2 to SZ2.  */
206 static int
207 strnncmp(char *s1, size_t sz1, char *s2, size_t sz2)
208 {
209     int res;
210     if (sz1 == sz2)
211         return strncmp(s1, s2, sz2);
212     if (sz1 < sz2)
213         return -strnncmp(s2, sz2, s1, sz1);
214     res = strncmp(s1, s2, sz2);
215     return res ? res : s1[sz2];
216 }
217
218 #define EVAL(op, lft, rgt)                      \
219     ((op) == '<' ? (lft) < (rgt)                \
220      : (op) == '=' ? (lft) == (rgt)             \
221      : (op) == '>' ? (lft) > (rgt)              \
222      : (op) == '#' ? (lft) != (rgt)             \
223      : (CANT_REACH(), 0))
224
225 /*
226  * Evaluate compiled conditions in array NP[NCOND].
227  * Return non-zero iff they are all true.
228  * PTR points to a context object of the type that was used to compile
229  * the conditions.
230  */
231 int
232 nstr_exec(struct nscstr *np, int ncond, void *ptr)
233 {
234     int i, op, optype, cmp;
235     struct valstr lft, rgt;
236
237     for (i = 0; i < ncond; ++i) {
238         op = np[i].operator;
239         optype = np[i].optype;
240         if (np[i].lft.val_cat == NSC_NOCAT || np[i].rgt.val_cat == NSC_NOCAT)
241             return 0;
242         lft = np[i].lft;
243         nstr_exec_val(&lft, player->cnum, ptr, optype);
244         rgt = np[i].rgt;
245         nstr_exec_val(&rgt, player->cnum, ptr, optype);
246         switch (optype) {
247         case NSC_LONG:
248             if (!EVAL(op, lft.val_as.lng, rgt.val_as.lng))
249                 return 0;
250             break;
251         case NSC_DOUBLE:
252             if (!EVAL(op, lft.val_as.dbl, rgt.val_as.dbl))
253                 return 0;
254             break;
255         case NSC_STRING:
256             cmp = strnncmp(lft.val_as.str.base, lft.val_as.str.maxsz,
257                            rgt.val_as.str.base, rgt.val_as.str.maxsz);
258             if (!EVAL(op, cmp, 0))
259                 return 0;
260             break;
261         default:
262             CANT_REACH();
263             return 0;
264         }
265     }
266
267     return 1;
268 }
269
270 /*
271  * Parse a value in STR into VAL.
272  * Return a pointer to the first character after the value.
273  * Value is either evaluated into NSC_STRING, NSC_DOUBLE or NSC_LONG,
274  * or an identifier.
275  */
276 static char *
277 nstr_parse_val(char *str, struct valstr *val)
278 {
279     long l;
280     double d;
281     char *tail, *tail2;
282
283     /* string */
284     if (str[0] == '\'') {
285         for (tail = str + 1; *tail && *tail != '\''; ++tail) ;
286         /* FIXME implement \ quoting */
287         val->val_type = NSC_STRING;
288         val->val_cat = NSC_VAL;
289         val->val_as.str.base = str + 1;
290         val->val_as.str.maxsz = tail - (str + 1);
291         if (*tail)
292             ++tail;
293         /* FIXME else unclosed string */
294         return tail;
295     }
296
297     /* identifier */
298     if (isalpha(str[0])) {
299         for (tail = str+1; isalnum(*tail) || *tail == '_'; ++tail) ;
300         val->val_type = NSC_NOTYPE;
301         val->val_cat = NSC_ID;
302         val->val_as.str.base = str;
303         val->val_as.str.maxsz = tail - str;
304         return tail;
305     }
306
307     /* number */
308     l = strtol(str, &tail, 0);
309     d = strtod(str, &tail2);
310     if (tail2 > tail) {
311         val->val_type = NSC_DOUBLE;
312         val->val_cat = NSC_VAL;
313         val->val_as.dbl = d;
314         return tail2;
315     }
316     if (tail != str) {
317         val->val_type = NSC_LONG;
318         val->val_cat = NSC_VAL;
319         val->val_as.lng = l;
320         return tail;
321     }
322
323     /* funny character, interpret as identifier */
324     tail = CANT_HAPPEN(!*str) ? str : str + 1;
325     val->val_type = NSC_NOTYPE;
326     val->val_cat = NSC_ID;
327     val->val_as.str.base = str;
328     val->val_as.str.maxsz = tail - str;
329     return tail;
330 }
331
332 /*
333  * Match VAL in table of selector descriptors CA, return index.
334  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
335  * several.
336  * A VAL that is not an identifier doesn't match anything.  A null CA
337  * is considered empty.
338  */
339 static int
340 nstr_match_ca(struct valstr *val, struct castr *ca)
341 {
342     char id[32];
343
344     if (val->val_cat != NSC_ID || val->val_as.str.maxsz >= sizeof(id))
345         return M_NOTFOUND;
346
347     if (!ca)
348         return M_NOTFOUND;
349
350     memcpy(id, val->val_as.str.base, val->val_as.str.maxsz);
351     id[val->val_as.str.maxsz] = 0;
352
353     return stmtch(id, ca, offsetof(struct castr, ca_name),
354                   sizeof(struct castr));
355 }
356
357 /*
358  * Is identifier VAL the name of the selector given by CA and IDX?
359  * Return non-zero if and only if IDX is non-negative and VAL is the
360  * name of CA[IDX].
361  * IDX must have been obtained from nstr_match_ca(VAL, CA).
362  */
363 static int
364 nstr_is_name_of_ca(struct valstr *val, struct castr *ca, int idx)
365 {
366     if (CANT_HAPPEN(val->val_cat != NSC_ID && idx >= 0))
367         return 0;
368     return idx >= 0 && strlen(ca[idx].ca_name) == val->val_as.str.maxsz;
369 }
370
371 /*
372  * Do we have two comparable selectors?
373  * Check selector descriptors CA[LFT_IDX] (unless LFT_IDX is negative)
374  * and CA[RGT_IDX] (unless RGT_IDX is negative).  CA may be null when
375  * both are negative.
376  */
377 static int
378 nstr_ca_comparable(struct castr *ca, int lft_idx, int rgt_idx)
379 {
380     if (lft_idx < 0 || rgt_idx < 0)
381         return 0;
382     if (ca[lft_idx].ca_table != ca[rgt_idx].ca_table)
383         return 0;               /* Example: land type=spy */
384     return nstr_optype(ca[lft_idx].ca_type, ca[rgt_idx].ca_type)
385         != NSC_NOTYPE;          /* Example: ship name=effic */
386 }
387
388 /*
389  * Match VAL in a selector's values, return its (non-negative) value.
390  * Match values of selector descriptor CA[IDX], provided IDX is not
391  * negative.  CA may be null when IDX is negative.
392  * Return M_NOTFOUND if there are no matches, M_NOTUNIQUE if there are
393  * several.
394  */
395 static int
396 nstr_match_val(struct valstr *val, struct castr *ca, int idx)
397 {
398     char id[32];
399     enum nsc_type type;
400
401     if (val->val_cat != NSC_ID || idx < 0)
402         return M_NOTFOUND;
403
404     type = nstr_promote(ca[idx].ca_type);
405     if (type == NSC_STRING)
406         return 0;
407
408     if (ca[idx].ca_table == EF_BAD || CANT_HAPPEN(type != NSC_LONG))
409         return M_NOTFOUND;
410
411     if (val->val_as.str.maxsz >= sizeof(id))
412         return M_NOTFOUND;
413     memcpy(id, val->val_as.str.base, val->val_as.str.maxsz);
414     id[val->val_as.str.maxsz] = 0;
415     return ef_elt_byname(ca[idx].ca_table, id);
416 }
417
418 /*
419  * Change VAL to resolve identifier to selector.
420  * Return VAL on success, NULL on error.
421  * No change if VAL is not an identifier.
422  * Else change VAL into symbolic value for selector CA[IDX] if IDX >=
423  * 0, and error if not.
424  */
425 static struct valstr *
426 nstr_resolve_id(struct valstr *val, struct castr *ca, int idx)
427 {
428     if (val->val_cat != NSC_ID)
429         return val;
430
431     if (idx == M_NOTUNIQUE) {
432         pr("%.*s -- ambiguous name\n",
433            (int)val->val_as.str.maxsz, val->val_as.str.base);
434         val->val_cat = NSC_NOCAT;
435         return NULL;
436     }
437
438     if (idx == M_NOTFOUND) {
439         pr("%.*s -- unknown name\n",
440            (int)val->val_as.str.maxsz, val->val_as.str.base);
441         val->val_cat = NSC_NOCAT;
442         return NULL;
443     }
444
445     if ((ca[idx].ca_flags & NSC_DEITY) && !player->god) {
446         pr("%.*s -- not accessible to mortals\n",
447            (int)val->val_as.str.maxsz, val->val_as.str.base);
448         val->val_cat = NSC_NOCAT;
449         return NULL;
450     }
451
452     return nstr_mksymval(val, &ca[idx], 0);
453 }
454
455 /*
456  * Change VAL to resolve identifier to value SELVAL for selector CA.
457  * Return VAL.
458  * VAL must be an identifier, and SELVAL must have been obtained from
459  * nstr_match_val(VAL, CA0, IDX), where CA = &CA0[IDX].
460  */
461 static struct valstr *
462 nstr_resolve_val(struct valstr *val, int selval, struct castr *ca)
463 {
464     enum nsc_type type = nstr_promote(ca->ca_type);
465
466     if (CANT_HAPPEN(val->val_cat != NSC_ID)) {
467         val->val_cat = NSC_NOCAT;
468         return val;
469     }
470
471     if (type == NSC_STRING) {
472         val->val_type = NSC_STRING;
473         val->val_cat = NSC_VAL;
474         /* map identifier ~ to empty string, like some commands do */
475         if (val->val_as.str.maxsz == 1 && val->val_as.str.base[0] == '~')
476             val->val_as.str.maxsz = 0;
477         return val;
478     }
479
480     if (CANT_HAPPEN(type != NSC_LONG || ca->ca_table == EF_BAD)) {
481         val->val_type = NSC_NOTYPE;
482         val->val_cat = NSC_NOCAT;
483         return val;
484     }
485
486     val->val_type = type;
487     val->val_cat = NSC_VAL;
488     val->val_as.lng = selval;
489     return val;
490 }
491
492 /*
493  * Return operator type for operand types LFT, RGT.
494  */
495 static int
496 nstr_optype(enum nsc_type lft, enum nsc_type rgt)
497 {
498     lft = nstr_promote(lft);
499     rgt = nstr_promote(rgt);
500     if (lft == rgt)
501         return lft;
502     if (lft == NSC_DOUBLE && rgt == NSC_LONG)
503         return NSC_DOUBLE;
504     if (rgt == NSC_DOUBLE && lft == NSC_LONG)
505         return NSC_DOUBLE;
506     return NSC_NOTYPE;
507 }
508
509 /*
510  * Compile a value in STR into VAL.
511  * Return a pointer to the first character after the value on success,
512  * NULL on error.
513  * TYPE is the context type, a file type.
514  * If STR names an array, VAL simply refers to the element with index
515  * zero.
516  */
517 char *
518 nstr_comp_val(char *str, struct valstr *val, int type)
519 {
520     struct castr *ca = ef_cadef(type);
521     char *tail = nstr_parse_val(str, val);
522     if (!nstr_resolve_id(val, ca, nstr_match_ca(val, ca)))
523         return NULL;
524     return tail;
525 }