Debian Codegraph @

terps/scare/scexpr.c

raw symbols SCIP
1 /* vi: set ts=2 shiftwidth=2 expandtab:
2 *
3 * Copyright (C) 2003-2008 Simon Baldwin and Mark J. Tilford
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of version 2 of the GNU General Public License
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
17 * USA
18 */
19
20 /*
21 * Module notes:
22 *
23 * o The tokenizer doesn't differentiate between "&", "&&", and "and", but "&"
24 * is context sensitive -- either a logical and for numerics, or concaten-
25 * ation for strings. As a result, "&&" and "and" also work as string
26 * concatenators when used in string expressions. It may not be to spec,
27 * but we'll call this a "feature".
28 */
29
30 #include <assert.h>
31 #include <limits.h>
32 #include <setjmp.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <time.h>
36
37 #include "scare.h"
38 #include "scprotos.h"
39
40
41 /* Assorted definitions and constants. */
42 enum { MAX_NESTING_DEPTH = 32 };
43 static const sc_char NUL = '\0';
44 static const sc_char PERCENT = '%';
45 static const sc_char SINGLE_QUOTE = '\'';
46 static const sc_char DOUBLE_QUOTE = '"';
47
48
49 /*
50 * Tokens. Single character tokens are represented by their ascii value
51 * (0-255), others by values above 255. -1 represents a null token. Because
52 * '&' and '+' are context sensitive, the pseudo-token TOK_CONCATENATE
53 * serves to indicate string concatenation -- it's never returned by the
54 * tokenizer.
55 */
56 enum
57 { TOK_NONE = -1,
58 TOK_ADD = '+', TOK_SUBTRACT = '-', TOK_MULTIPLY = '*', TOK_DIVIDE = '/',
59 TOK_AND = '&', TOK_OR = '|',
60 TOK_LPAREN = '(', TOK_RPAREN = ')', TOK_COMMA = ',', TOK_POWER = '^',
61 TOK_EQUAL = '=', TOK_GREATER = '>', TOK_LESS = '<',
62
63 TOK_IDENT = 256,
64 TOK_INTEGER, TOK_STRING, TOK_VARIABLE, TOK_UMINUS, TOK_UPLUS,
65 TOK_MOD, TOK_NOT_EQUAL, TOK_GREATER_EQ, TOK_LESS_EQ, TOK_IF,
66 TOK_MIN, TOK_MAX, TOK_EITHER, TOK_RANDOM, TOK_INSTR, TOK_LEN, TOK_VAL,
67 TOK_ABS, TOK_UPPER, TOK_LOWER, TOK_PROPER, TOK_RIGHT, TOK_LEFT, TOK_MID,
68 TOK_STR, TOK_CONCATENATE,
69 TOK_EOS
70 };
71
72 /*
73 * Small tables tying multicharacter tokens strings to tokens. At present,
74 * the string lengths for names are not used.
75 */
76 typedef struct
77 {
78 const sc_char *const name;
79 const sc_int length;
80 const sc_int token;
81 } sc_expr_multichar_t;
82
83 static const sc_expr_multichar_t FUNCTION_TOKENS[] = {
84 {"either", 6, TOK_EITHER},
85 {"proper", 6, TOK_PROPER}, {"pcase", 5, TOK_PROPER}, {"instr", 5, TOK_INSTR},
86 {"upper", 5, TOK_UPPER}, {"ucase", 5, TOK_UPPER},
87 {"lower", 5, TOK_LOWER}, {"lcase", 5, TOK_LOWER},
88 {"right", 5, TOK_RIGHT}, {"left", 4, TOK_LEFT},
89 {"rand", 4, TOK_RANDOM}, {"max", 3, TOK_MAX}, {"min", 3, TOK_MIN},
90 {"mod", 3, TOK_MOD}, {"abs", 3, TOK_ABS}, {"len", 3, TOK_LEN},
91 {"val", 3, TOK_VAL}, {"and", 3, TOK_AND}, {"mid", 3, TOK_MID},
92 {"str", 3, TOK_STR}, {"or", 2, TOK_OR}, {"if", 2, TOK_IF},
93 {NULL, 0, TOK_NONE}
94 };
95 static const sc_expr_multichar_t OPERATOR_TOKENS[] = {
96 {"&&", 2, TOK_AND}, {"||", 2, TOK_OR},
97 {"==", 2, TOK_EQUAL}, {"!=", 2, TOK_NOT_EQUAL},
98 {"<>", 2, TOK_NOT_EQUAL}, {">=", 2, TOK_GREATER_EQ}, {"<=", 2, TOK_LESS_EQ},
99 {NULL, 0, TOK_NONE}
100 };
101
102
103 /*
104 * expr_multichar_search()
105 *
106 * Multicharacter token table search, returns the matching token, or
107 * TOK_NONE if no match.
108 */
109 static sc_int
110 expr_multichar_search (const sc_char *name, const sc_expr_multichar_t *table)
111 {
112 const sc_expr_multichar_t *entry;
113
114 /* Scan the table for a case-independent full string match. */
115 for (entry = table; entry->name; entry++)
116 {
117 if (sc_strcasecmp (name, entry->name) == 0)
118 break;
119 }
120
121 /* Return the token matched, or TOK_NONE. */
122 return entry->name ? entry->token : TOK_NONE;
123 }
124
125
126 /* Tokenizer variables. */
127 static const sc_char *expr_expression = NULL;
128 static sc_int expr_index = 0;
129 static sc_vartype_t expr_token_value;
130 static sc_char *expr_temporary = NULL;
131 static sc_int expr_current_token = TOK_NONE;
132
133 /*
134 * expr_tokenize_start()
135 * expr_tokenize_end()
136 *
137 * Start and wrap up expression string tokenization.
138 */
139 static void
140 expr_tokenize_start (const sc_char *expression)
141 {
142 static sc_bool initialized = FALSE;
143
144 /* On first call only, verify the string lengths in the tables. */
145 if (!initialized)
146 {
147 const sc_expr_multichar_t *entry;
148
149 /* Compare table lengths with string lengths. */
150 for (entry = FUNCTION_TOKENS; entry->name; entry++)
151 {
152 if (entry->length != (sc_int) strlen (entry->name))
153 {
154 sc_fatal ("expr_tokenize_start:"
155 " token string length is wrong for \"%s\"\n",
156 entry->name);
157 }
158 }
159
160 for (entry = OPERATOR_TOKENS; entry->name; entry++)
161 {
162 if (entry->length != (sc_int) strlen (entry->name))
163 {
164 sc_fatal ("expr_tokenize_start:"
165 " operator string length is wrong for \"%s\"\n",
166 entry->name);
167 }
168 }
169
170 initialized = TRUE;
171 }
172
173 /* Save expression, and restart index. */
174 expr_expression = expression;
175 expr_index = 0;
176
177 /* Allocate a temporary token value/literals string. */
178 assert (!expr_temporary);
179 expr_temporary = sc_malloc (strlen (expression) + 1);
180
181 /* Reset last token to none. */
182 expr_current_token = TOK_NONE;
183 }
184
185 static void
186 expr_tokenize_end (void)
187 {
188 /* Deallocate temporary strings, clear expression. */
189 sc_free (expr_temporary);
190 expr_temporary = NULL;
191 expr_expression = NULL;
192 expr_index = 0;
193 expr_current_token = TOK_NONE;
194 }
195
196
197 /*
198 * expr_next_token_unadjusted()
199 * expr_next_token()
200 *
201 * Return the next token from the current expression. The initial token may
202 * be adjusted into a unary +/- depending on the value of the previous token.
203 */
204 static sc_int
205 expr_next_token_unadjusted (sc_vartype_t *token_value)
206 {
207 sc_int c;
208 assert (expr_expression);
209
210 /* Skip any and all leading whitespace. */
211 do
212 {
213 c = expr_expression[expr_index++];
214 }
215 while (sc_isspace (c) && c != NUL);
216
217 /* Return EOS if at expression end. */
218 if (c == NUL)
219 {
220 expr_index--;
221 return TOK_EOS;
222 }
223
224 /*
225 * Identify and return numerics. We deal only with unsigned numbers here;
226 * the unary +/- tokens take care of any integer sign issues.
227 */
228 else if (sc_isdigit (c))
229 {
230 sc_int value;
231
232 sscanf (expr_expression + expr_index - 1, "%ld", &value);
233
234 while (sc_isdigit (c) && c != NUL)
235 c = expr_expression[expr_index++];
236 expr_index--;
237
238 token_value->integer = value;
239 return TOK_INTEGER;
240 }
241
242 /* Identify and return variable references. */
243 else if (c == PERCENT)
244 {
245 sc_int index_;
246
247 /* Copy variable name. */
248 c = expr_expression[expr_index++];
249 for (index_ = 0; c != PERCENT && c != NUL;)
250 {
251 expr_temporary[index_++] = c;
252 c = expr_expression[expr_index++];
253 }
254 expr_temporary[index_++] = NUL;
255
256 if (c == NUL)
257 {
258 sc_error ("expr_next_token_unadjusted:"
259 " warning: unterminated variable name\n");
260 expr_index--;
261 }
262
263 /* Return a variable name. */
264 token_value->string = expr_temporary;
265 return TOK_VARIABLE;
266 }
267
268 /* Identify and return string literals. */
269 else if (c == DOUBLE_QUOTE || c == SINGLE_QUOTE)
270 {
271 sc_int index_;
272 sc_char quote;
273
274 /* Copy maximal string literal. */
275 quote = c;
276 c = expr_expression[expr_index++];
277 for (index_ = 0; c != quote && c != NUL;)
278 {
279 expr_temporary[index_++] = c;
280 c = expr_expression[expr_index++];
281 }
282 expr_temporary[index_++] = NUL;
283
284 if (c == NUL)
285 {
286 sc_error ("expr_next_token_unadjusted:"
287 " warning: unterminated string literal\n");
288 expr_index--;
289 }
290
291 /* Return string literal. */
292 token_value->string = expr_temporary;
293 return TOK_STRING;
294 }
295
296 /* Identify ids and other multicharacter tokens. */
297 else if (sc_isalpha (c))
298 {
299 sc_int index_, token;
300
301 /*
302 * Copy maximal alphabetical string. While an ident would normally
303 * be alpha followed by zero or more alnum, for Adrift purposes we
304 * use only alpha -- all idents should really be "functions", and
305 * in particular we want to see "mod7" as "mod" and 7 separately.
306 */
307 for (index_ = 0; sc_isalpha (c) && c != NUL;)
308 {
309 expr_temporary[index_++] = c;
310 c = expr_expression[expr_index++];
311 }
312 expr_index--;
313 expr_temporary[index_++] = NUL;
314
315 /*
316 * Check for a function name, and if known, return that, otherwise
317 * return a bare id.
318 */
319 token = expr_multichar_search (expr_temporary, FUNCTION_TOKENS);
320 if (token == TOK_NONE)
321 {
322 token_value->string = expr_temporary;
323 return TOK_IDENT;
324 }
325 else
326 return token;
327 }
328
329 /*
330 * Last chance check for two-character (multichar) operators, and if none
331 * then return a single-character token.
332 */
333 else
334 {
335 sc_char operator_[3];
336 sc_int token;
337
338 /*
339 * Build a two-character string. If we happen to be at the last
340 * expression character, we'll pick up the expression NUL into
341 * operator_[1], so no need to special case end of expression here.
342 */
343 operator_[0] = c;
344 operator_[1] = expr_expression[expr_index];
345 operator_[2] = NUL;
346
347 /* Search for this two-character operator. */
348 if (operator_[0] != NUL && operator_[1] != NUL)
349 {
350 token = expr_multichar_search (operator_, OPERATOR_TOKENS);
351 if (token != TOK_NONE)
352 {
353 /* Matched, so advance expression index and return this token. */
354 expr_index++;
355 return token;
356 }
357 }
358
359 /*
360 * No match, or at last expression character; return a single character
361 * token.
362 */
363 return c;
364 }
365 }
366
367 static sc_int
368 expr_next_token (void)
369 {
370 sc_int token;
371 sc_vartype_t token_value;
372
373 /*
374 * Get the basic next token. We may adjust it later for unary minus/plus
375 * depending on what it is, and the prior token.
376 */
377 token_value.voidp = NULL;
378 token = expr_next_token_unadjusted (&token_value);
379
380 /* Special handling for unary minus/plus signs. */
381 if (token == TOK_SUBTRACT || token == TOK_ADD)
382 {
383 /*
384 * Unary minus/plus if prior token was an operator or a comparison, left
385 * parenthesis, or comma, or if there was no prior token.
386 */
387 switch (expr_current_token)
388 {
389 case TOK_MOD:
390 case TOK_POWER:
391 case TOK_ADD:
392 case TOK_SUBTRACT:
393 case TOK_MULTIPLY:
394 case TOK_DIVIDE:
395 case TOK_AND:
396 case TOK_OR:
397 case TOK_EQUAL:
398 case TOK_GREATER:
399 case TOK_LESS:
400 case TOK_NOT_EQUAL:
401 case TOK_GREATER_EQ:
402 case TOK_LESS_EQ:
403 case TOK_LPAREN:
404 case TOK_COMMA:
405 case TOK_NONE:
406 token = (token == TOK_SUBTRACT) ? TOK_UMINUS : TOK_UPLUS;
407 break;
408
409 default:
410 break;
411 }
412 }
413
414 /* Set current token to the one just found, and return it. */
415 expr_current_token = token;
416 expr_token_value = token_value;
417 return token;
418 }
419
420
421 /*
422 * expr_current_token_value()
423 *
424 * Return the token value of the current token. Undefined if the current
425 * token is not numeric, an id, or a variable.
426 */
427 static void
428 expr_current_token_value (sc_vartype_t *value)
429 {
430 /* Quick check that the value is a valid one. */
431 switch (expr_current_token)
432 {
433 case TOK_INTEGER:
434 case TOK_STRING:
435 case TOK_VARIABLE:
436 case TOK_IDENT:
437 break;
438
439 default:
440 sc_fatal ("expr_current_token_value:"
441 " taking undefined token value, %ld\n", expr_current_token);
442 }
443
444 /* Return value. */
445 *value = expr_token_value;
446 }
447
448
449 /*
450 * Evaluation values stack, uses a variable type so it can contain both
451 * integers and strings, and flags strings for possible garbage collection
452 * on parse errors.
453 */
454 typedef struct
455 {
456 sc_bool is_collectible;
457 sc_vartype_t value;
458 } sc_stack_t;
459 static sc_stack_t expr_eval_stack[MAX_NESTING_DEPTH];
460 static sc_int expr_eval_stack_index = 0;
461
462 /* Variables set to reference for %...% values. */
463 static sc_var_setref_t expr_varset = NULL;
464
465 /*
466 * expr_eval_start()
467 *
468 * Reset the evaluation stack to an empty state, and register the variables
469 * set to use when referencing %...% variables.
470 */
471 static void
472 expr_eval_start (sc_var_setref_t vars)
473 {
474 expr_eval_stack_index = 0;
475 expr_varset = vars;
476 }
477
478
479 /*
480 * expr_eval_garbage_collect()
481 *
482 * In case of parse error, empty out and free all collectible malloced
483 * strings left in the evaluation array.
484 */
485 static void
486 expr_eval_garbage_collect (void)
487 {
488 sc_int index_;
489
490 /*
491 * Find and free all collectible strings still in the stack. We have to
492 * free through mutable string rather than const string.
493 */
494 for (index_ = 0; index_ < expr_eval_stack_index; index_++)
495 {
496 if (expr_eval_stack[index_].is_collectible)
497 sc_free (expr_eval_stack[index_].value.mutable_string);
498 }
499
500 /* Reset the stack index, for clarity and neatness. */
501 expr_eval_stack_index = 0;
502 }
503
504
505 /*
506 * expr_eval_push_integer()
507 * expr_eval_push_string()
508 * expr_eval_push_alloced_string()
509 *
510 * Push a value onto the values stack. Strings are malloc'ed and copied,
511 * and the copy is placed onto the stack, unless _alloced_string() is used;
512 * for this case, the input string is assumed to be already malloc'ed, and
513 * the caller should not subsequently free the string.
514 */
515 static void
516 expr_eval_push_integer (sc_int value)
517 {
518 if (expr_eval_stack_index >= MAX_NESTING_DEPTH)
519 sc_fatal ("expr_eval_push_integer: stack overflow\n");
520
521 expr_eval_stack[expr_eval_stack_index].is_collectible = FALSE;
522 expr_eval_stack[expr_eval_stack_index++].value.integer = value;
523 }
524
525 static void
526 expr_eval_push_string (const sc_char *value)
527 {
528 sc_char *value_copy;
529
530 if (expr_eval_stack_index >= MAX_NESTING_DEPTH)
531 sc_fatal ("expr_eval_push_string: stack overflow\n");
532
533 /* Push a copy of value. */
534 value_copy = sc_malloc (strlen (value) + 1);
535 strcpy (value_copy, value);
536 expr_eval_stack[expr_eval_stack_index].is_collectible = TRUE;
537 expr_eval_stack[expr_eval_stack_index++].value.mutable_string = value_copy;
538 }
539
540 static void
541 expr_eval_push_alloced_string (sc_char *value)
542 {
543 if (expr_eval_stack_index >= MAX_NESTING_DEPTH)
544 sc_fatal ("expr_eval_push_alloced_string: stack overflow\n");
545
546 expr_eval_stack[expr_eval_stack_index].is_collectible = TRUE;
547 expr_eval_stack[expr_eval_stack_index++].value.mutable_string = value;
548 }
549
550
551 /*
552 * expr_eval_pop_integer()
553 * expr_eval_pop_string()
554 *
555 * Pop values off the values stack. Returned strings are malloc'ed copies,
556 * and the caller is responsible for freeing them.
557 */
558 static sc_int
559 expr_eval_pop_integer (void)
560 {
561 if (expr_eval_stack_index == 0)
562 sc_fatal ("expr_eval_pop_integer: stack underflow\n");
563
564 assert (!expr_eval_stack[expr_eval_stack_index - 1].is_collectible);
565 return expr_eval_stack[--expr_eval_stack_index].value.integer;
566 }
567
568 static sc_char *
569 expr_eval_pop_string (void)
570 {
571 if (expr_eval_stack_index == 0)
572 sc_fatal ("expr_eval_pop_string: stack underflow\n");
573
574 /* Returns mutable string rather than const string. */
575 assert (expr_eval_stack[expr_eval_stack_index - 1].is_collectible);
576 return expr_eval_stack[--expr_eval_stack_index].value.mutable_string;
577 }
578
579
580 /*
581 * expr_eval_result()
582 *
583 * Return the top of the values stack as the expression result.
584 */
585 static void
586 expr_eval_result (sc_vartype_t *vt_rvalue)
587 {
588 if (expr_eval_stack_index != 1)
589 sc_fatal ("expr_eval_result: values stack not completed\n");
590
591 /* Clear down stack and return the top value. */
592 expr_eval_stack_index = 0;
593 *vt_rvalue = expr_eval_stack[0].value;
594 }
595
596
597 /*
598 * expr_eval_abs()
599 *
600 * Return the absolute value of the given sc_int. Replacement for labs(),
601 * avoids tying sc_int to long types too closely.
602 */
603 static sc_int
604 expr_eval_abs (sc_int value)
605 {
606 return value < 0 ? -value : value;
607 }
608
609
610 /* Parse error jump buffer. */
611 static jmp_buf expr_parse_error;
612
613 /*
614 * expr_eval_action()
615 *
616 * Evaluate the effect of a token into the values stack.
617 */
618 static void
619 expr_eval_action (sc_int token)
620 {
621 sc_vartype_t token_value;
622
623 switch (token)
624 {
625 /* Handle tokens representing stack pushes. */
626 case TOK_INTEGER:
627 expr_current_token_value (&token_value);
628 expr_eval_push_integer (token_value.integer);
629 break;
630
631 case TOK_STRING:
632 expr_current_token_value (&token_value);
633 expr_eval_push_string (token_value.string);
634 break;
635
636 case TOK_VARIABLE:
637 {
638 sc_vartype_t vt_rvalue;
639 sc_int type;
640
641 expr_current_token_value (&token_value);
642 if (!var_get (expr_varset, token_value.string, &type, &vt_rvalue))
643 {
644 sc_error ("expr_eval_action:"
645 " undefined variable, %s\n", token_value.string);
646 longjmp (expr_parse_error, 1);
647 }
648 switch (type)
649 {
650 case VAR_INTEGER:
651 expr_eval_push_integer (vt_rvalue.integer);
652 break;
653
654 case VAR_STRING:
655 expr_eval_push_string (vt_rvalue.string);
656 break;
657
658 default:
659 sc_fatal ("expr_eval_action: bad variable type\n");
660 }
661 break;
662 }
663
664 /* Handle tokens representing functions returning numeric. */
665 case TOK_IF:
666 {
667 sc_int test, val1, val2;
668
669 /* Pop the test and alternatives, and push back result. */
670 val2 = expr_eval_pop_integer ();
671 val1 = expr_eval_pop_integer ();
672 test = expr_eval_pop_integer ();
673 expr_eval_push_integer (test ? val1 : val2);
674 break;
675 }
676
677 case TOK_MAX:
678 case TOK_MIN:
679 {
680 sc_int argument_count, index_, result;
681
682 /* Get argument count off the top of the stack. */
683 argument_count = expr_eval_pop_integer ();
684 assert (argument_count > 0);
685
686 /* Find the max or min of these stacked values. */
687 result = expr_eval_pop_integer ();
688 for (index_ = 1; index_ < argument_count; index_++)
689 {
690 sc_int next;
691
692 next = expr_eval_pop_integer ();
693 switch (token)
694 {
695 case TOK_MAX:
696 result = (next > result) ? next : result;
697 break;
698
699 case TOK_MIN:
700 result = (next < result) ? next : result;
701 break;
702
703 default:
704 sc_fatal ("expr_eval_action: bad token, %ld\n", token);
705 }
706 }
707
708 /* Push back the result. */
709 expr_eval_push_integer (result);
710 break;
711 }
712
713 case TOK_EITHER:
714 {
715 sc_int argument_count, pick, index_;
716 sc_int result = 0;
717
718 /* Get argument count off the top of the stack. */
719 argument_count = expr_eval_pop_integer ();
720 assert (argument_count > 0);
721
722 /*
723 * Pick one of the top N items at random, then unstack all N and
724 * push back the value of the one picked.
725 */
726 pick = sc_rand () % argument_count;
727 for (index_ = 0; index_ < argument_count; index_++)
728 {
729 sc_int val;
730
731 val = expr_eval_pop_integer ();
732 if (index_ == pick)
733 result = val;
734 }
735
736 /* Push back the result. */
737 expr_eval_push_integer (result);
738 break;
739 }
740
741 case TOK_INSTR:
742 {
743 sc_char *val1, *val2, *search;
744 sc_int result;
745
746 /* Extract the two values to work on. */
747 val2 = expr_eval_pop_string ();
748 val1 = expr_eval_pop_string ();
749
750 /*
751 * Search for the second in the first. The result is the character
752 * position, starting at 1, or 0 if not found. Then free the popped
753 * strings, and push back the result.
754 */
755 search = (val1[0] != NUL) ? strstr (val1, val2) : NULL;
756 result = (!search) ? 0 : search - val1 + 1;
757 sc_free (val1);
758 sc_free (val2);
759 expr_eval_push_integer (result);
760 break;
761 }
762
763 case TOK_LEN:
764 {
765 sc_char *val;
766 sc_int result;
767
768 /* Pop the top string, and push back its length. */
769 val = expr_eval_pop_string ();
770 result = strlen (val);
771 sc_free (val);
772 expr_eval_push_integer (result);
773 break;
774 }
775
776 case TOK_VAL:
777 {
778 sc_char *val;
779 sc_int result = 0;
780
781 /*
782 * Extract the string at stack top, and try to convert, returning
783 * zero if conversion fails. Free the popped string, and push back
784 * the result.
785 */
786 val = expr_eval_pop_string ();
787 sscanf (val, "%ld", &result);
788 sc_free (val);
789 expr_eval_push_integer (result);
790 break;
791 }
792
793 /* Handle tokens representing unary numeric operations. */
794 case TOK_UMINUS:
795 expr_eval_push_integer (-(expr_eval_pop_integer ()));
796 break;
797
798 case TOK_UPLUS:
799 break;
800
801 case TOK_ABS:
802 expr_eval_push_integer (expr_eval_abs (expr_eval_pop_integer ()));
803 break;
804
805 /* Handle tokens representing most binary numeric operations. */
806 case TOK_ADD:
807 case TOK_SUBTRACT:
808 case TOK_MULTIPLY:
809 case TOK_AND:
810 case TOK_OR:
811 case TOK_EQUAL:
812 case TOK_GREATER:
813 case TOK_LESS:
814 case TOK_NOT_EQUAL:
815 case TOK_GREATER_EQ:
816 case TOK_LESS_EQ:
817 case TOK_RANDOM:
818 {
819 sc_int val1, val2, result = 0;
820
821 /* Extract the two values to work on. */
822 val2 = expr_eval_pop_integer ();
823 val1 = expr_eval_pop_integer ();
824
825 /* Generate the result value. */
826 switch (token)
827 {
828 case TOK_ADD:
829 result = val1 + val2;
830 break;
831 case TOK_SUBTRACT:
832 result = val1 - val2;
833 break;
834 case TOK_MULTIPLY:
835 result = val1 * val2;
836 break;
837 case TOK_AND:
838 result = val1 && val2;
839 break;
840 case TOK_OR:
841 result = val1 || val2;
842 break;
843 case TOK_EQUAL:
844 result = val1 == val2;
845 break;
846 case TOK_GREATER:
847 result = val1 > val2;
848 break;
849 case TOK_LESS:
850 result = val1 < val2;
851 break;
852 case TOK_NOT_EQUAL:
853 result = val1 != val2;
854 break;
855 case TOK_GREATER_EQ:
856 result = val1 >= val2;
857 break;
858 case TOK_LESS_EQ:
859 result = val1 <= val2;
860 break;
861 case TOK_RANDOM:
862 result = sc_randomint (val1, val2);
863 break;
864 default:
865 sc_fatal ("expr_eval_action: bad token, %ld\n", token);
866 }
867
868 /* Put result back at top of stack. */
869 expr_eval_push_integer (result);
870 break;
871 }
872
873 /* Handle division and modulus separately; they're "eccentric". */
874 case TOK_DIVIDE:
875 case TOK_MOD:
876 {
877 sc_int val1, val2, x, y, result = 0;
878
879 /* Extract the two values to work on, complain about division by 0. */
880 val2 = expr_eval_pop_integer ();
881 val1 = expr_eval_pop_integer ();
882 if (val2 == 0)
883 {
884 sc_error ("expr_eval_action: attempt to divide by zero\n");
885 expr_eval_push_integer (result);
886 break;
887 }
888
889 /*
890 * ANSI/ISO C only defines integer division for positive values.
891 * Negative values usually work consistently across platforms, but are
892 * not guaranteed. For maximum portability, then, here we'll work
893 * carefully with positive integers only.
894 */
895 x = expr_eval_abs (val1);
896 y = expr_eval_abs (val2);
897
898 /* Generate the result value. */
899 switch (token)
900 {
901 case TOK_DIVIDE:
902 /*
903 * Adrift's division apparently works by dividing using floating
904 * point, then applying (asymmetrical) rounding, so we have to do
905 * the same here.
906 */
907 result = ((val1 < 0) == (val2 < 0))
908 ? ((x / y) + (((x % y) * 2 >= y) ? 1 : 0))
909 : -((x / y) + (((x % y) * 2 > y) ? 1 : 0));
910 break;
911
912 case TOK_MOD:
913 /*
914 * Adrift also breaks numerical consistency by defining mod in a
915 * conventional (non-rounded), way, so that A=(AdivB)*B+AmodB
916 * does not hold.
917 */
918 result = (val1 < 0) ? -(x % y) : (x % y);
919 break;
920
921 default:
922 sc_fatal ("expr_eval_action: bad token, %ld\n", token);
923 }
924
925 /* Put result back at top of stack. */
926 expr_eval_push_integer (result);
927 break;
928 }
929
930 /* Handle power individually, to avoid needing a maths library. */
931 case TOK_POWER:
932 {
933 sc_int val1, val2, result;
934
935 /* Extract the two values to work on. */
936 val2 = expr_eval_pop_integer ();
937 val1 = expr_eval_pop_integer ();
938
939 /* Handle negative and zero power values first, as special cases. */
940 if (val2 == 0)
941 result = 1;
942 else if (val2 < 0)
943 {
944 if (val1 == 0)
945 {
946 sc_error ("expr_eval_action: attempt to divide by zero\n");
947 result = 0;
948 }
949 else if (val1 == 1)
950 result = val1;
951 else if (val1 == -1)
952 result = (-val2 & 1) ? val1 : -val1;
953 else
954 result = 0;
955 }
956 else
957 {
958 /* Raise to positive powers using the Russian Peasant algorithm. */
959 while ((val2 & 1) == 0)
960 {
961 val1 = val1 * val1;
962 val2 >>= 1;
963 }
964
965 result = val1;
966 val2 >>= 1;
967 while (val2 > 0)
968 {
969 val1 = val1 * val1;
970 if (val2 & 1)
971 result = result * val1;
972 val2 >>= 1;
973 }
974 }
975
976 /* Put result back at top of stack. */
977 expr_eval_push_integer (result);
978 break;
979 }
980
981 /* Handle tokens representing functions returning string. */
982 case TOK_LEFT:
983 case TOK_RIGHT:
984 {
985 sc_char *text;
986 sc_int length;
987
988 /*
989 * Extract the text and length. If length is longer than text, or
990 * negative, do nothing.
991 */
992 length = expr_eval_pop_integer ();
993 text = expr_eval_pop_string ();
994 if (length < 0 || length >= (sc_int) strlen (text))
995 {
996 expr_eval_push_alloced_string (text);
997 break;
998 }
999
1000 /*
1001 * Take the left or right segment -- for left, the operation is a
1002 * simple truncation; for right, it's a memmove.
1003 */
1004 switch (token)
1005 {
1006 case TOK_LEFT:
1007 text[length] = NUL;
1008 break;
1009
1010 case TOK_RIGHT:
1011 memmove (text, text + strlen (text) - length, length + 1);
1012 break;
1013
1014 default:
1015 sc_fatal ("expr_eval_action: bad token, %ld\n", token);
1016 }
1017
1018 /* Put result back at top of stack. */
1019 expr_eval_push_alloced_string (text);
1020 break;
1021 }
1022
1023 case TOK_MID:
1024 {
1025 sc_char *text;
1026 sc_int length, start, limit;
1027
1028 /*
1029 * Extract the text, start, and length, re-basing start from 1 to 0,
1030 * and calculate the limit on characters available for the move.
1031 */
1032 length = expr_eval_pop_integer ();
1033 start = expr_eval_pop_integer () - 1;
1034 text = expr_eval_pop_string ();
1035 limit = strlen (text);
1036
1037 /*
1038 * Clamp ranges that roam outside the available text -- start less
1039 * than 0 to 0, and greater than len(text) to len(text), and length
1040 * less than 0 to 0, and off string end to string end.
1041 */
1042 if (start < 0)
1043 start = 0;
1044 else if (start > limit)
1045 start = limit;
1046 if (length < 0)
1047 length = 0;
1048 else if (length > limit - start)
1049 length = limit - start;
1050
1051 /* Move substring, terminate, and put back at top of stack. */
1052 memmove (text, text + start, length + 1);
1053 text[length] = NUL;
1054 expr_eval_push_alloced_string (text);
1055 break;
1056 }
1057
1058 case TOK_STR:
1059 {
1060 sc_int val;
1061 sc_char buffer[32];
1062
1063 /*
1064 * Extract the value, convert it, and push back the resulting string.
1065 * The leading space on positive values matches the Runner.
1066 */
1067 val = expr_eval_pop_integer ();
1068 sprintf (buffer, "% ld", val);
1069 expr_eval_push_string (buffer);
1070 break;
1071 }
1072
1073
1074 /* Handle tokens representing unary string operations. */
1075 case TOK_UPPER:
1076 case TOK_LOWER:
1077 case TOK_PROPER:
1078 {
1079 sc_char *text;
1080 sc_int index_;
1081
1082 /* Extract the value to work on. */
1083 text = expr_eval_pop_string ();
1084
1085 /* Convert the entire string in place -- it's malloc'ed. */
1086 for (index_ = 0; text[index_] != NUL; index_++)
1087 {
1088 switch (token)
1089 {
1090 case TOK_UPPER:
1091 text[index_] = sc_toupper (text[index_]);
1092 break;
1093
1094 case TOK_LOWER:
1095 text[index_] = sc_tolower (text[index_]);
1096 break;
1097
1098 case TOK_PROPER:
1099 if (index_ == 0 || sc_isspace (text[index_ - 1]))
1100 text[index_] = sc_toupper (text[index_]);
1101 else
1102 text[index_] = sc_tolower (text[index_]);
1103 break;
1104
1105 default:
1106 sc_fatal ("expr_eval_action: bad token, %ld\n", token);
1107 }
1108 }
1109
1110 /* Put result back at top of stack. */
1111 expr_eval_push_alloced_string (text);
1112 break;
1113 }
1114
1115 /* Handle token representing binary string operation. */
1116 case TOK_CONCATENATE:
1117 {
1118 sc_char *text1, *text2;
1119
1120 /* Extract the two texts to work on. */
1121 text2 = expr_eval_pop_string ();
1122 text1 = expr_eval_pop_string ();
1123
1124 /*
1125 * Resize text1 to be long enough for both, and concatenate, then
1126 * free text2, and push back the concatenation.
1127 */
1128 text1 = sc_realloc (text1, strlen (text1) + strlen (text2) + 1);
1129 strcat (text1, text2);
1130 sc_free (text2);
1131 expr_eval_push_alloced_string (text1);
1132 break;
1133 }
1134
1135 default:
1136 sc_fatal ("expr_eval_action: bad token, %ld\n", token);
1137 }
1138 }
1139
1140
1141 /* Predictive parser lookahead token. */
1142 static sc_int expr_parse_lookahead = TOK_NONE;
1143
1144 /* Forward declaration of factor parsers and string expression parser. */
1145 static void expr_parse_numeric_factor (void);
1146 static void expr_parse_string_factor (void);
1147 static void expr_parse_string_expr (void);
1148
1149 /*
1150 * expr_parse_match()
1151 *
1152 * Match a token to the lookahead, then advance lookahead.
1153 */
1154 static void
1155 expr_parse_match (sc_int token)
1156 {
1157 if (expr_parse_lookahead == token)
1158 expr_parse_lookahead = expr_next_token ();
1159 else
1160 {
1161 /* Syntax error. */
1162 sc_error ("expr_parse_match: syntax error,"
1163 " expected %ld, got %ld\n", expr_parse_lookahead, token);
1164 longjmp (expr_parse_error, 1);
1165 }
1166 }
1167
1168
1169 /*
1170 * Numeric operator precedence table. Operators are in order of precedence,
1171 * with the highest being a factor. Each precedence entry permits several
1172 * listed tokens. The end of the table (highest precedence) is marked by
1173 * a list with no operators (although in practice we need to put a TOK_NONE
1174 * in here since some C compilers won't accept { } as an empty initializer).
1175 */
1176 typedef struct
1177 {
1178 const sc_int token_count;
1179 const sc_int tokens[6];
1180 } sc_precedence_entry_t;
1181 #if 0
1182 /*
1183 * Conventional (BASIC, C) precedence table for the parser. Exponentiation
1184 * has the highest precedence, then multiplicative operations, additive,
1185 * comparisons, and boolean combiners.
1186 */
1187 static const sc_precedence_entry_t PRECEDENCE_TABLE[] = {
1188 {1, {TOK_OR}},
1189 {1, {TOK_AND}},
1190 {2, {TOK_EQUAL, TOK_NOT_EQUAL}},
1191 {4, {TOK_GREATER, TOK_LESS, TOK_GREATER_EQ, TOK_LESS_EQ}},
1192 {2, {TOK_ADD, TOK_SUBTRACT}},
1193 {3, {TOK_MULTIPLY, TOK_DIVIDE, TOK_MOD}},
1194 {1, {TOK_POWER}},
1195 {0, {TOK_NONE}}
1196 };
1197 #else
1198 /*
1199 * Adrift-like precedence table for the parser. Exponentiation and modulus
1200 * operations seem to be implemented at the same level as addition and
1201 * subtraction, and boolean 'and' and 'or' have equal precedence.
1202 */
1203 static const sc_precedence_entry_t PRECEDENCE_TABLE[] = {
1204 {2, {TOK_OR, TOK_AND}},
1205 {6, {TOK_EQUAL, TOK_NOT_EQUAL,
1206 TOK_GREATER, TOK_LESS, TOK_GREATER_EQ, TOK_LESS_EQ}},
1207 {4, {TOK_ADD, TOK_SUBTRACT, TOK_POWER, TOK_MOD}},
1208 {2, {TOK_MULTIPLY, TOK_DIVIDE}},
1209 {0, {TOK_NONE}}
1210 };
1211 #endif
1212
1213
1214 /*
1215 * expr_parse_contains_token()
1216 *
1217 * Helper for expr_parse_numeric_element(). Search the token list for the
1218 * entry passed in, and return TRUE if it contains the given token.
1219 */
1220 static int
1221 expr_parse_contains_token (const sc_precedence_entry_t *entry, sc_int token)
1222 {
1223 sc_bool is_matched;
1224 sc_int index_;
1225
1226 /* Search the entry's token list for the token passed in. */
1227 is_matched = FALSE;
1228 for (index_ = 0; index_ < entry->token_count; index_++)
1229 {
1230 if (entry->tokens[index_] == token)
1231 {
1232 is_matched = TRUE;
1233 break;
1234 }
1235 }
1236
1237 return is_matched;
1238 }
1239
1240
1241 /*
1242 * expr_parse_numeric_element()
1243 *
1244 * Parse numeric expression elements. This function uses the precedence table
1245 * to match tokens, then decide whether, and how, to recurse into itself, or
1246 * whether to parse a highest-precedence factor.
1247 */
1248 static void
1249 expr_parse_numeric_element (sc_int precedence)
1250 {
1251 const sc_precedence_entry_t *entry;
1252
1253 /* See if the level passed in has listed tokens. */
1254 entry = PRECEDENCE_TABLE + precedence;
1255 if (entry->token_count == 0)
1256 {
1257 /* Precedence levels that hit the table end are factors. */
1258 expr_parse_numeric_factor ();
1259 return;
1260 }
1261
1262 /*
1263 * Parse initial higher-precedence factor, then others that associate
1264 * with the given level.
1265 */
1266 expr_parse_numeric_element (precedence + 1);
1267 while (expr_parse_contains_token (entry, expr_parse_lookahead))
1268 {
1269 sc_int token;
1270
1271 /* Note token and match, parse next level, then action this token. */
1272 token = expr_parse_lookahead;
1273 expr_parse_match (token);
1274 expr_parse_numeric_element (precedence + 1);
1275 expr_eval_action (token);
1276 }
1277 }
1278
1279
1280 /*
1281 * expr_parse_numeric_expr()
1282 *
1283 * Parse a complete numeric (sub-)expression.
1284 */
1285 static void
1286 expr_parse_numeric_expr (void)
1287 {
1288 /* Call the parser of the lowest precedence operators. */
1289 expr_parse_numeric_element (0);
1290 }
1291
1292
1293 /*
1294 * expr_parse_numeric_factor()
1295 *
1296 * Parse a numeric expression factor.
1297 */
1298 static void
1299 expr_parse_numeric_factor (void)
1300 {
1301 /* Handle factors based on lookahead token. */
1302 switch (expr_parse_lookahead)
1303 {
1304 /* Handle straightforward factors first. */
1305 case TOK_LPAREN:
1306 expr_parse_match (TOK_LPAREN);
1307 expr_parse_numeric_expr ();
1308 expr_parse_match (TOK_RPAREN);
1309 break;
1310
1311 case TOK_UMINUS:
1312 expr_parse_match (TOK_UMINUS);
1313 expr_parse_numeric_factor ();
1314 expr_eval_action (TOK_UMINUS);
1315 break;
1316
1317 case TOK_UPLUS:
1318 expr_parse_match (TOK_UPLUS);
1319 expr_parse_numeric_factor ();
1320 break;
1321
1322 case TOK_INTEGER:
1323 expr_eval_action (TOK_INTEGER);
1324 expr_parse_match (TOK_INTEGER);
1325 break;
1326
1327 case TOK_VARIABLE:
1328 {
1329 sc_vartype_t token_value, vt_rvalue;
1330 sc_int type;
1331
1332 expr_current_token_value (&token_value);
1333 if (!var_get (expr_varset, token_value.string, &type, &vt_rvalue))
1334 {
1335 sc_error ("expr_parse_numeric_factor:"
1336 " undefined variable, %s\n", token_value.string);
1337 longjmp (expr_parse_error, 1);
1338 }
1339 if (type != VAR_INTEGER)
1340 {
1341 sc_error ("expr_parse_numeric_factor:"
1342 " string variable in numeric context, %s\n",
1343 token_value.string);
1344 longjmp (expr_parse_error, 1);
1345 }
1346 expr_eval_action (TOK_VARIABLE);
1347 expr_parse_match (TOK_VARIABLE);
1348 break;
1349 }
1350
1351 /* Handle functions as factors. */
1352 case TOK_ABS:
1353 /* Parse as "abs (val)". */
1354 expr_parse_match (TOK_ABS);
1355 expr_parse_match (TOK_LPAREN);
1356 expr_parse_numeric_expr ();
1357 expr_parse_match (TOK_RPAREN);
1358 expr_eval_action (TOK_ABS);
1359 break;
1360
1361 case TOK_IF:
1362 /* Parse as "if (boolean, val1, val2)". */
1363 expr_parse_match (TOK_IF);
1364 expr_parse_match (TOK_LPAREN);
1365 expr_parse_numeric_expr ();
1366 expr_parse_match (TOK_COMMA);
1367 expr_parse_numeric_expr ();
1368 expr_parse_match (TOK_COMMA);
1369 expr_parse_numeric_expr ();
1370 expr_parse_match (TOK_RPAREN);
1371 expr_eval_action (TOK_IF);
1372 break;
1373
1374 case TOK_RANDOM:
1375 /* Parse as "random (low, high)". */
1376 expr_parse_match (TOK_RANDOM);
1377 expr_parse_match (TOK_LPAREN);
1378 expr_parse_numeric_expr ();
1379 expr_parse_match (TOK_COMMA);
1380 expr_parse_numeric_expr ();
1381 expr_parse_match (TOK_RPAREN);
1382 expr_eval_action (TOK_RANDOM);
1383 break;
1384
1385 case TOK_MAX:
1386 case TOK_MIN:
1387 case TOK_EITHER:
1388 /* Parse as "<func> (val1[,val2[,val3...]]])". */
1389 {
1390 sc_int token, argument_count;
1391
1392 /* Match up the function name and opening parenthesis. */
1393 token = expr_parse_lookahead;
1394 expr_parse_match (token);
1395 expr_parse_match (TOK_LPAREN);
1396
1397 /* Count variable number of arguments as they are stacked. */
1398 expr_parse_numeric_expr ();
1399 argument_count = 1;
1400 while (expr_parse_lookahead == TOK_COMMA)
1401 {
1402 expr_parse_match (TOK_COMMA);
1403 expr_parse_numeric_expr ();
1404 argument_count++;
1405 }
1406 expr_parse_match (TOK_RPAREN);
1407
1408 /* Push additional value -- the count of arguments. */
1409 expr_eval_push_integer (argument_count);
1410 expr_eval_action (token);
1411 break;
1412 }
1413
1414 case TOK_INSTR:
1415 /* Parse as "instr (val1, val2)". */
1416 expr_parse_match (TOK_INSTR);
1417 expr_parse_match (TOK_LPAREN);
1418 expr_parse_string_expr ();
1419 expr_parse_match (TOK_COMMA);
1420 expr_parse_string_expr ();
1421 expr_parse_match (TOK_RPAREN);
1422 expr_eval_action (TOK_INSTR);
1423 break;
1424
1425 case TOK_LEN:
1426 /* Parse as "len (val)". */
1427 expr_parse_match (TOK_LEN);
1428 expr_parse_match (TOK_LPAREN);
1429 expr_parse_string_expr ();
1430 expr_parse_match (TOK_RPAREN);
1431 expr_eval_action (TOK_LEN);
1432 break;
1433
1434 case TOK_VAL:
1435 /* Parse as "val (val)". */
1436 expr_parse_match (TOK_VAL);
1437 expr_parse_match (TOK_LPAREN);
1438 expr_parse_string_expr ();
1439 expr_parse_match (TOK_RPAREN);
1440 expr_eval_action (TOK_VAL);
1441 break;
1442
1443 case TOK_IDENT:
1444 /* Unrecognized function-type token. */
1445 sc_error ("expr_parse_numeric_factor: syntax error, unknown ident\n");
1446 longjmp (expr_parse_error, 1);
1447
1448 default:
1449 /* Syntax error. */
1450 sc_error ("expr_parse_numeric_factor:"
1451 " syntax error, unexpected token, %ld\n", expr_parse_lookahead);
1452 longjmp (expr_parse_error, 1);
1453 }
1454 }
1455
1456
1457 /*
1458 * expr_parse_string_expr()
1459 *
1460 * Parse a complete string (sub-)expression.
1461 */
1462 static void
1463 expr_parse_string_expr (void)
1464 {
1465 /*
1466 * Parse a string factor, then all repeated concatenations. Because the '+'
1467 * and '&' are context sensitive, we have to invent/translate them into the
1468 * otherwise unused TOK_CONCATENATE for evaluation.
1469 */
1470 expr_parse_string_factor ();
1471 while (expr_parse_lookahead == TOK_AND || expr_parse_lookahead == TOK_ADD)
1472 {
1473 expr_parse_match (expr_parse_lookahead);
1474 expr_parse_string_factor ();
1475 expr_eval_action (TOK_CONCATENATE);
1476 }
1477 }
1478
1479
1480 /*
1481 * expr_parse_string_factor()
1482 *
1483 * Parse a string expression factor.
1484 */
1485 static void
1486 expr_parse_string_factor (void)
1487 {
1488 /* Handle factors based on lookahead token. */
1489 switch (expr_parse_lookahead)
1490 {
1491 /* Handle straightforward factors first. */
1492 case TOK_LPAREN:
1493 expr_parse_match (TOK_LPAREN);
1494 expr_parse_string_expr ();
1495 expr_parse_match (TOK_RPAREN);
1496 break;
1497
1498 case TOK_STRING:
1499 expr_eval_action (TOK_STRING);
1500 expr_parse_match (TOK_STRING);
1501 break;
1502
1503 case TOK_VARIABLE:
1504 {
1505 sc_vartype_t token_value, vt_rvalue;
1506 sc_int type;
1507
1508 expr_current_token_value (&token_value);
1509 if (!var_get (expr_varset, token_value.string, &type, &vt_rvalue))
1510 {
1511 sc_error ("expr_parse_string_factor:"
1512 " undefined variable, %s\n", token_value.string);
1513 longjmp (expr_parse_error, 1);
1514 }
1515 if (type != VAR_STRING)
1516 {
1517 sc_error ("expr_parse_string_factor:"
1518 " numeric variable in string context, %s\n",
1519 token_value.string);
1520 longjmp (expr_parse_error, 1);
1521 }
1522 expr_eval_action (TOK_VARIABLE);
1523 expr_parse_match (TOK_VARIABLE);
1524 break;
1525 }
1526
1527 /* Handle functions as factors. */
1528 case TOK_UPPER:
1529 case TOK_LOWER:
1530 case TOK_PROPER:
1531 /* Parse as "<func> (text)". */
1532 {
1533 sc_int token;
1534
1535 token = expr_parse_lookahead;
1536 expr_parse_match (token);
1537 expr_parse_match (TOK_LPAREN);
1538 expr_parse_string_expr ();
1539 expr_parse_match (TOK_RPAREN);
1540 expr_eval_action (token);
1541 break;
1542 }
1543
1544 case TOK_LEFT:
1545 case TOK_RIGHT:
1546 /* Parse as "<func> (text,length)". */
1547 {
1548 sc_int token;
1549
1550 token = expr_parse_lookahead;
1551 expr_parse_match (token);
1552 expr_parse_match (TOK_LPAREN);
1553 expr_parse_string_expr ();
1554 expr_parse_match (TOK_COMMA);
1555 expr_parse_numeric_expr ();
1556 expr_parse_match (TOK_RPAREN);
1557 expr_eval_action (token);
1558 break;
1559 }
1560
1561 case TOK_MID:
1562 /* Parse as "mid (text,start,length)". */
1563 expr_parse_match (TOK_MID);
1564 expr_parse_match (TOK_LPAREN);
1565 expr_parse_string_expr ();
1566 expr_parse_match (TOK_COMMA);
1567 expr_parse_numeric_expr ();
1568 expr_parse_match (TOK_COMMA);
1569 expr_parse_numeric_expr ();
1570 expr_parse_match (TOK_RPAREN);
1571 expr_eval_action (TOK_MID);
1572 break;
1573
1574 case TOK_STR:
1575 /* Parse as "str (val)". */
1576 expr_parse_match (TOK_STR);
1577 expr_parse_match (TOK_LPAREN);
1578 expr_parse_numeric_expr ();
1579 expr_parse_match (TOK_RPAREN);
1580 expr_eval_action (TOK_STR);
1581 break;
1582
1583 case TOK_IDENT:
1584 /* Unrecognized function-type token. */
1585 sc_error ("expr_parse_string_factor: syntax error, unknown ident\n");
1586 longjmp (expr_parse_error, 1);
1587
1588 default:
1589 /* Syntax error. */
1590 sc_error ("expr_parse_string_factor:"
1591 " syntax error, unexpected token, %ld\n", expr_parse_lookahead);
1592 longjmp (expr_parse_error, 1);
1593 }
1594 }
1595
1596
1597 /*
1598 * expr_evaluate_expression()
1599 *
1600 * Parse a string expression into a runtime values stack. Return the
1601 * value of the expression.
1602 */
1603 static sc_bool
1604 expr_evaluate_expression (const sc_char *expression, sc_var_setref_t vars,
1605 sc_int assign_type, sc_vartype_t *vt_rvalue)
1606 {
1607 assert (assign_type == VAR_INTEGER || assign_type == VAR_STRING);
1608
1609 /* Reset values stack and start tokenizer. */
1610 expr_eval_start (vars);
1611 expr_tokenize_start (expression);
1612
1613 /* Try parsing an expression, and catch errors. */
1614 if (setjmp (expr_parse_error) == 0)
1615 {
1616 /* Parse an expression, and ensure it ends at string end. */
1617 expr_parse_lookahead = expr_next_token ();
1618 if (assign_type == VAR_STRING)
1619 expr_parse_string_expr ();
1620 else
1621 expr_parse_numeric_expr ();
1622 expr_parse_match (TOK_EOS);
1623 }
1624 else
1625 {
1626 /* Parse error -- clean up tokenizer, collect garbage, and fail. */
1627 expr_tokenize_end ();
1628 expr_eval_garbage_collect ();
1629 return FALSE;
1630 }
1631
1632 /* Clean up tokenizer and return successfully with result. */
1633 expr_tokenize_end ();
1634 expr_eval_result (vt_rvalue);
1635 return TRUE;
1636 }
1637
1638
1639 /*
1640 * expr_eval_numeric_expression()
1641 * expr_eval_string_expression()
1642 *
1643 * Public interfaces to expression evaluation. Evaluate an expression, and
1644 * assign the result to either a numeric or a string. For string expressions,
1645 * the return value is malloc'ed, and the caller is responsible for freeing
1646 * it.
1647 */
1648 sc_bool
1649 expr_eval_numeric_expression (const sc_char *expression,
1650 sc_var_setref_t vars, sc_int *rvalue)
1651 {
1652 sc_vartype_t vt_rvalue;
1653 sc_bool status;
1654 assert (expression && vars && rvalue);
1655
1656 /* Evaluate numeric expression, and return value if valid. */
1657 status = expr_evaluate_expression (expression, vars, VAR_INTEGER, &vt_rvalue);
1658 if (status)
1659 *rvalue = vt_rvalue.integer;
1660 return status;
1661 }
1662
1663 sc_bool
1664 expr_eval_string_expression (const sc_char *expression,
1665 sc_var_setref_t vars, sc_char **rvalue)
1666 {
1667 sc_vartype_t vt_rvalue;
1668 sc_bool status;
1669 assert (expression && vars && rvalue);
1670
1671 /* Evaluate string expression, and return value if valid. */
1672 status = expr_evaluate_expression (expression, vars, VAR_STRING, &vt_rvalue);
1673 if (status)
1674 *rvalue = vt_rvalue.mutable_string;
1675 return status;
1676 }