Debian Codegraph @

terps/scare/scparser.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 Some of the "finer" points of pattern matching in relation to "*"
24 * wildcards, and %text%, are unknown.
25 *
26 * o The inclusion of part or all of prefixes in %character% and %object%
27 * matching may be right; then again, it may not be.
28 */
29
30 #include <assert.h>
31 #include <setjmp.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35
36 #include "scare.h"
37 #include "scprotos.h"
38 #include "scgamest.h"
39
40
41 /* Assorted definitions and constants. */
42 static const sc_char NUL = '\0';
43 static const sc_char MINUS = '-';
44 static const sc_char PLUS = '+';
45 static const sc_char PERCENT = '%';
46 static const sc_char *const WHITESPACE = "\t\n\v\f\r ";
47
48 /* Pattern matching trace flag. */
49 static sc_bool uip_trace = FALSE;
50
51 /* Enumeration of tokens. TOK_NONE represents a non-occurring token. */
52 typedef enum
53 {
54 TOK_NONE = 0,
55 TOK_CHOICE, TOK_CHOICE_END, TOK_OPTIONAL, TOK_OPTIONAL_END,
56 TOK_ALTERNATES_SEPARATOR,
57 TOK_WILDCARD, TOK_WHITESPACE, TOK_WORD, TOK_VARIABLE,
58 TOK_CHARACTER_REFERENCE, TOK_OBJECT_REFERENCE, TOK_NUMBER_REFERENCE,
59 TOK_TEXT_REFERENCE, TOK_EOS
60 } sc_uip_tok_t;
61
62 /*
63 * Small table tying token strings to tokens. Anything not whitespace and
64 * not caught by the table is a plain TOK_WORD.
65 */
66 typedef struct
67 {
68 const sc_char *const name;
69 const sc_int length;
70 const sc_uip_tok_t token;
71 } sc_uip_token_entry_t;
72
73 static const sc_uip_token_entry_t UIP_TOKENS[] = {
74 {"[", 1, TOK_CHOICE}, {"]", 1, TOK_CHOICE_END},
75 {"{", 1, TOK_OPTIONAL}, {"}", 1, TOK_OPTIONAL_END},
76 {"/", 1, TOK_ALTERNATES_SEPARATOR},
77 {"*", 1, TOK_WILDCARD},
78 {"%character%", 11, TOK_CHARACTER_REFERENCE},
79 {"%object%", 8, TOK_OBJECT_REFERENCE},
80 {"%number%", 8, TOK_NUMBER_REFERENCE},
81 {"%text%", 6, TOK_TEXT_REFERENCE},
82 {NULL, 0, TOK_NONE}
83 };
84
85
86 /*
87 * Tokenizer variables. The temporary is used for keeping word token values.
88 * For improved performance, we'll set it to indicate a static buffer if
89 * short enough, otherwise it's allocated.
90 */
91 static const sc_char *uip_pattern = NULL;
92 static sc_int uip_index = 0;
93 static const sc_char *uip_token_value;
94 enum { UIP_ALLOCATION_AVOIDANCE_SIZE = 128 };
95 static sc_char uip_static_temporary[UIP_ALLOCATION_AVOIDANCE_SIZE];
96 static sc_char *uip_temporary = NULL;
97
98 /*
99 * uip_tokenize_start()
100 * uip_tokenize_end()
101 *
102 * Start and wrap up pattern string tokenization.
103 */
104 static void
105 uip_tokenize_start (const sc_char *pattern)
106 {
107 static sc_bool initialized = FALSE;
108 sc_int required;
109
110 /* On first call only, verify the string lengths in the table. */
111 if (!initialized)
112 {
113 const sc_uip_token_entry_t *entry;
114
115 /* Compare table lengths with string lengths. */
116 for (entry = UIP_TOKENS; entry->name; entry++)
117 {
118 if (entry->length != (sc_int) strlen (entry->name))
119 {
120 sc_fatal ("uip_tokenize_start:"
121 " table string length is wrong for \"%s\"\n",
122 entry->name);
123 }
124 }
125
126 initialized = TRUE;
127 }
128
129 /* Save pattern, and restart index. */
130 uip_pattern = pattern;
131 uip_index = 0;
132
133 /* Set up temporary; static if long enough, otherwise allocated. */
134 required = strlen (pattern) + 1;
135 uip_temporary = (required > UIP_ALLOCATION_AVOIDANCE_SIZE)
136 ? sc_malloc (required) : uip_static_temporary;
137 }
138
139 static void
140 uip_tokenize_end (void)
141 {
142 /* Deallocate temporary if required, and clear pattern and index. */
143 if (uip_temporary != uip_static_temporary)
144 sc_free (uip_temporary);
145 uip_temporary = NULL;
146 uip_pattern = NULL;
147 uip_index = 0;
148 }
149
150
151 /*
152 * uip_next_token()
153 *
154 * Return the next token from the current pattern.
155 */
156 static sc_uip_tok_t
157 uip_next_token (void)
158 {
159 const sc_uip_token_entry_t *entry;
160 sc_char close;
161 assert (uip_pattern);
162
163 /* Get next character, return EOS if at pattern end. */
164 if (uip_pattern[uip_index] == NUL)
165 {
166 uip_token_value = NULL;
167 return TOK_EOS;
168 }
169
170 /* If whitespace, skip it, then return a whitespace token. */
171 if (sc_isspace (uip_pattern[uip_index]))
172 {
173 uip_index++;
174 while (sc_isspace (uip_pattern[uip_index])
175 && uip_pattern[uip_index] != NUL)
176 uip_index++;
177 uip_token_value = NULL;
178 return TOK_WHITESPACE;
179 }
180
181 /* Search the table for matching strings. */
182 for (entry = UIP_TOKENS; entry->name; entry++)
183 {
184 if (strncmp (uip_pattern + uip_index, entry->name, entry->length) == 0)
185 break;
186 }
187 if (entry->name)
188 {
189 /* Advance over string, and return token. */
190 uip_index += entry->length;
191 uip_token_value = NULL;
192 return entry->token;
193 }
194
195 /*
196 * Search for a non-special variable reference. This is apparently an
197 * Adrift extension to the standard pattern match, allowing %user_var% to
198 * be used in patterns. If found, return a variable with the name as the
199 * token value. We can't interpolate the value into the string either
200 * here or earlier, so we have to save the variable's name, and retrieve
201 * it when we come to try the match.
202 */
203 if (sscanf (uip_pattern + uip_index, "%%%[^%]%c", uip_temporary, &close) == 2
204 && close == PERCENT)
205 {
206 uip_index += strlen (uip_temporary) + 2;
207 uip_token_value = uip_temporary;
208 return TOK_VARIABLE;
209 }
210
211 /*
212 * Return a word. This is a contiguous run of non-pattern-special, non-
213 * whitespace, non-percent characters
214 */
215 sscanf (uip_pattern + uip_index, "%[^][/{}*% \f\n\r\t\v]", uip_temporary);
216 uip_token_value = uip_temporary;
217 uip_index += strlen (uip_temporary);
218 return TOK_WORD;
219 }
220
221
222 /*
223 * uip_current_token_value()
224 *
225 * Return the token value of the current token. It is an error to call
226 * here if the current token is not a TOK_WORD or TOK_VARIABLE.
227 */
228 static const sc_char *
229 uip_current_token_value (void)
230 {
231 /* If the token value is NULL, the current token isn't a word. */
232 if (!uip_token_value)
233 {
234 sc_fatal ("uip_current_token_value:"
235 " attempt to take undefined token value\n");
236 }
237
238 /* Return value. */
239 return uip_token_value;
240 }
241
242
243 /*
244 * Parsed pattern tree node definition. The tree is a left child, right
245 * sibling representation, with token type, and word at nodes of type TOK_WORD.
246 * NODE_UNUSED must be zero to ensure that the statically allocated array that
247 * forms the node pool appears initially as containing only unused nodes.
248 */
249 typedef enum
250 {
251 NODE_UNUSED = 0,
252 NODE_CHOICE, NODE_OPTIONAL, NODE_WILDCARD, NODE_WHITESPACE,
253 NODE_CHARACTER_REFERENCE, NODE_OBJECT_REFERENCE, NODE_TEXT_REFERENCE,
254 NODE_NUMBER_REFERENCE, NODE_WORD, NODE_VARIABLE, NODE_LIST, NODE_EOS
255 } sc_pttype_t;
256 typedef struct sc_ptnode_s
257 {
258 struct sc_ptnode_s *left_child;
259 struct sc_ptnode_s *right_sibling;
260
261 sc_pttype_t type;
262 sc_char *word;
263 sc_bool is_allocated;
264 } sc_ptnode_t;
265 typedef sc_ptnode_t *sc_ptnoderef_t;
266
267 /* Predictive parser lookahead token. */
268 static sc_uip_tok_t uip_parse_lookahead = TOK_NONE;
269
270 /* Parse error jump buffer. */
271 static jmp_buf uip_parse_error;
272
273 /* Parse tree for cleanup, and forward declaration of pattern list parser. */
274 static sc_ptnoderef_t uip_parse_tree = NULL;
275 static void uip_parse_list (sc_ptnoderef_t list);
276
277 /*
278 * Pool of statically allocated nodes, for faster allocations. Nodes are
279 * first allocated from here, then by straight malloc() if this pool is empty.
280 * An average game's peak node allocation seems to be around 40-50 nodes, so
281 * allowing 128 here should be plenty.
282 */
283 enum { UIP_NODE_POOL_SIZE = 128 };
284 static sc_ptnode_t uip_node_pool[UIP_NODE_POOL_SIZE];
285 static sc_int uip_node_pool_cursor = 0;
286 static sc_int uip_node_pool_available = UIP_NODE_POOL_SIZE;
287
288 /*
289 * Words held at nodes are usually short (15 chars covers 95% of English), so
290 * to avoid a lot of small allocations we use a pool of short strings, used
291 * first, then by straight malloc() should the pool empty.
292 */
293 enum { UIP_WORD_POOL_SIZE = 64, UIP_SHORT_WORD_SIZE = 16 };
294 typedef struct
295 {
296 sc_bool is_in_use;
297 sc_char word[UIP_SHORT_WORD_SIZE];
298 } sc_ptshortword_t;
299 typedef sc_ptshortword_t *sc_ptshortwordref_t;
300 static sc_ptshortword_t uip_word_pool[UIP_WORD_POOL_SIZE];
301 static sc_int uip_word_pool_cursor = 0;
302 static sc_int uip_word_pool_available = UIP_WORD_POOL_SIZE;
303
304 /*
305 * uip_parse_match()
306 *
307 * Match a token to the lookahead, then advance lookahead.
308 */
309 static void
310 uip_parse_match (sc_uip_tok_t token)
311 {
312 if (uip_parse_lookahead == token)
313 uip_parse_lookahead = uip_next_token ();
314 else
315 {
316 /* Syntax error. */
317 sc_error ("uip_parse_match: syntax error, expected %ld, got %ld\n",
318 (sc_int) uip_parse_lookahead, (sc_int) token);
319 longjmp (uip_parse_error, 1);
320 }
321 }
322
323
324 /*
325 * uip_new_word()
326 *
327 * Return a string containing a copy of the word. Uses a ring allocator to
328 * allocate initially from static storage, for performance. If this is
329 * exhausted, backs off to standard allocation.
330 */
331 static sc_char *
332 uip_new_word (const sc_char *word)
333 {
334 sc_int required;
335
336 /*
337 * Unless the pool is empty, search forwards from the next cursor position
338 * until an unused slot is found, or until the index wraps to the cursor.
339 */
340 required = strlen (word) + 1;
341 if (uip_word_pool_available > 0 && required <= UIP_SHORT_WORD_SIZE)
342 {
343 sc_int index_;
344 sc_ptshortwordref_t shortword;
345
346 index_ = (uip_word_pool_cursor + 1) % UIP_WORD_POOL_SIZE;
347 while (index_ != uip_word_pool_cursor)
348 {
349 if (!uip_word_pool[index_].is_in_use)
350 break;
351 index_ = (index_ + 1) % UIP_WORD_POOL_SIZE;
352 }
353
354 if (uip_word_pool[index_].is_in_use)
355 sc_fatal ("uip_new_word: no free slot found in the words pool\n");
356
357 /* Use the slot and update the pool cursor and free count. */
358 shortword = uip_word_pool + index_;
359 strcpy (shortword->word, word);
360 shortword->is_in_use = TRUE;
361
362 uip_word_pool_cursor = index_;
363 uip_word_pool_available--;
364
365 /* Return the address of the copied string. */
366 return shortword->word;
367 }
368 else
369 {
370 sc_char *word_copy;
371
372 /* Fall back to less efficient allocations. */
373 word_copy = sc_malloc (required);
374 strcpy (word_copy, word);
375 return word_copy;
376 }
377 }
378
379
380 /*
381 * uip_free_word()
382 *
383 * If the word was allocated, free its memory; if not, find its short word
384 * pool entry and return it to the pool.
385 */
386 static void
387 uip_free_word (sc_char *word)
388 {
389 const sc_char *first_in_pool, *last_in_pool;
390
391 /* Obtain the range of valid addresses for words from the word pool. */
392 first_in_pool = uip_word_pool[0].word;
393 last_in_pool = uip_word_pool[UIP_WORD_POOL_SIZE - 1].word;
394
395 /* If from the pool, mark the entry as no longer in use, otherwise free. */
396 if (word >= first_in_pool && word <= last_in_pool)
397 {
398 sc_int index_;
399 sc_ptshortwordref_t shortword;
400
401 /*
402 * Calculate the index to the word pool entry from which this short
403 * word was allocated.
404 */
405 index_ = (word - first_in_pool) / sizeof (uip_word_pool[0]);
406 shortword = uip_word_pool + index_;
407 assert (shortword->word == word);
408
409 shortword->is_in_use = FALSE;
410 uip_word_pool_available++;
411 }
412 else
413 sc_free (word);
414 }
415
416
417 /*
418 * uip_new_node()
419 *
420 * Create a new node, populated with an initial type. Uses a ring allocator
421 * to allocate initially from static storage, for performance. If this is
422 * exhausted, backs off to standard allocation.
423 */
424 static sc_ptnoderef_t
425 uip_new_node (sc_pttype_t type)
426 {
427 sc_ptnoderef_t node;
428
429 /*
430 * Unless the pool is empty, search forwards from the next cursor position
431 * until an unused slot is found, or until the index wraps to the cursor.
432 */
433 if (uip_node_pool_available > 0)
434 {
435 sc_int index_;
436
437 index_ = (uip_node_pool_cursor + 1) % UIP_NODE_POOL_SIZE;
438 while (index_ != uip_node_pool_cursor)
439 {
440 if (uip_node_pool[index_].type == NODE_UNUSED)
441 break;
442 index_ = (index_ + 1) % UIP_NODE_POOL_SIZE;
443 }
444
445 if (uip_node_pool[index_].type != NODE_UNUSED)
446 sc_fatal ("uip_new_node: no free slot found in the nodes pool\n");
447
448 /* Use the slot and update the pool cursor and free count. */
449 node = uip_node_pool + index_;
450 node->is_allocated = FALSE;
451
452 uip_node_pool_cursor = index_;
453 uip_node_pool_available--;
454 }
455 else
456 {
457 /* Fall back to less efficient allocations. */
458 node = sc_malloc (sizeof (*node));
459 node->is_allocated = TRUE;
460 }
461
462 /* Fill in the remaining fields and return the new node. */
463 node->left_child = NULL;
464 node->right_sibling = NULL;
465 node->type = type;
466 node->word = NULL;
467
468 return node;
469 }
470
471
472 /*
473 * uip_destroy_node()
474 *
475 * Destroy a node, and any allocated word memory. If the node was allocated,
476 * free its memory; if not, return it to the pool.
477 */
478 static void
479 uip_destroy_node (sc_ptnoderef_t node)
480 {
481 /* Free any word contained at this node. */
482 if (node->word)
483 uip_free_word (node->word);
484
485 /*
486 * If the node was allocated, poison memory and free it. If it came from
487 * the node pool, set it to unused and update the availability count for
488 * the pool.
489 */
490 if (node->is_allocated)
491 {
492 memset (node, 0xaa, sizeof (*node));
493 sc_free (node);
494 }
495 else
496 {
497 node->type = NODE_UNUSED;
498 uip_node_pool_available++;
499 }
500 }
501
502
503 /*
504 * uip_parse_new_list()
505 * uip_parse_alternatives()
506 *
507 * Parse a set of .../.../... alternatives for choices and optionals. The
508 * first function is a helper, returning a newly constructed parsed list.
509 */
510 static sc_ptnoderef_t
511 uip_parse_new_list (void)
512 {
513 sc_ptnoderef_t list;
514
515 /* Create a new list node, parse into it, and return it. */
516 list = uip_new_node (NODE_LIST);
517 uip_parse_list (list);
518 return list;
519 }
520
521 static void
522 uip_parse_alternatives (sc_ptnoderef_t node)
523 {
524 sc_ptnoderef_t child;
525
526 /* Parse initial alternative, then add other listed alternatives. */
527 node->left_child = uip_parse_new_list ();
528 child = node->left_child;
529 while (uip_parse_lookahead == TOK_ALTERNATES_SEPARATOR)
530 {
531 uip_parse_match (TOK_ALTERNATES_SEPARATOR);
532 child->right_sibling = uip_parse_new_list ();
533 child = child->right_sibling;
534 }
535 }
536
537
538 /*
539 * uip_parse_element()
540 *
541 * Parse a single pattern element.
542 */
543 static sc_ptnoderef_t
544 uip_parse_element (void)
545 {
546 sc_ptnoderef_t node = NULL;
547 sc_uip_tok_t token;
548
549 /* Handle pattern element based on lookahead token. */
550 switch (uip_parse_lookahead)
551 {
552 case TOK_WHITESPACE:
553 uip_parse_match (TOK_WHITESPACE);
554 node = uip_new_node (NODE_WHITESPACE);
555 break;
556
557 case TOK_CHOICE:
558 /* Parse a [...[/.../...]] choice. */
559 uip_parse_match (TOK_CHOICE);
560 node = uip_new_node (NODE_CHOICE);
561 uip_parse_alternatives (node);
562 uip_parse_match (TOK_CHOICE_END);
563 break;
564
565 case TOK_OPTIONAL:
566 /* Parse a {...[/.../...]} optional element. */
567 uip_parse_match (TOK_OPTIONAL);
568 node = uip_new_node (NODE_OPTIONAL);
569 uip_parse_alternatives (node);
570 uip_parse_match (TOK_OPTIONAL_END);
571 break;
572
573 case TOK_WILDCARD:
574 case TOK_CHARACTER_REFERENCE:
575 case TOK_OBJECT_REFERENCE:
576 case TOK_NUMBER_REFERENCE:
577 case TOK_TEXT_REFERENCE:
578 /* Parse %mumble% references and * wildcards. */
579 token = uip_parse_lookahead;
580 uip_parse_match (token);
581 switch (token)
582 {
583 case TOK_WILDCARD:
584 node = uip_new_node (NODE_WILDCARD);
585 break;
586 case TOK_CHARACTER_REFERENCE:
587 node = uip_new_node (NODE_CHARACTER_REFERENCE);
588 break;
589 case TOK_OBJECT_REFERENCE:
590 node = uip_new_node (NODE_OBJECT_REFERENCE);
591 break;
592 case TOK_NUMBER_REFERENCE:
593 node = uip_new_node (NODE_NUMBER_REFERENCE);
594 break;
595 case TOK_TEXT_REFERENCE:
596 node = uip_new_node (NODE_TEXT_REFERENCE);
597 break;
598 default:
599 sc_fatal ("uip_parse_element: invalid token, %ld\n", (sc_int) token);
600 }
601 break;
602
603 case TOK_WORD:
604 {
605 const sc_char *token_value;
606 sc_char *word;
607
608 /* Take a copy of the token's word value. */
609 token_value = uip_current_token_value ();
610 word = uip_new_word (token_value);
611
612 /* Store details in a word node. */
613 uip_parse_match (TOK_WORD);
614 node = uip_new_node (NODE_WORD);
615 node->word = word;
616 break;
617 }
618
619 case TOK_VARIABLE:
620 {
621 const sc_char *token_value;
622 sc_char *name;
623
624 /* Take a copy of the token's variable name value. */
625 token_value = uip_current_token_value ();
626 name = uip_new_word (token_value);
627
628 /* Store details in a variable node, overloading word. */
629 uip_parse_match (TOK_VARIABLE);
630 node = uip_new_node (NODE_VARIABLE);
631 node->word = name;
632 break;
633 }
634
635 default:
636 /* Syntax error. */
637 sc_error ("uip_parse_element: syntax error,"
638 " unexpected token, %ld\n", (sc_int) uip_parse_lookahead);
639 longjmp (uip_parse_error, 1);
640 }
641
642 /* Return the newly created node. */
643 assert (node);
644 return node;
645 }
646
647
648 /*
649 * uip_parse_list()
650 *
651 * Parse a list of pattern elements.
652 */
653 static void
654 uip_parse_list (sc_ptnoderef_t list)
655 {
656 sc_ptnoderef_t child, node;
657
658 /* Add elements until a list terminator token is encountered. */
659 child = list;
660 while (TRUE)
661 {
662 switch (uip_parse_lookahead)
663 {
664 case TOK_CHOICE_END:
665 case TOK_OPTIONAL_END:
666 case TOK_ALTERNATES_SEPARATOR:
667 /* Terminate list building and return. */
668 return;
669
670 case TOK_EOS:
671 /* Place EOS at the appropriate link and return. */
672 node = uip_new_node (NODE_EOS);
673 if (child == list)
674 child->left_child = node;
675 else
676 child->right_sibling = node;
677 return;
678
679 default:
680 /* Add the next node at the appropriate link. */
681 node = uip_parse_element ();
682 if (child == list)
683 {
684 child->left_child = node;
685 child = child->left_child;
686 }
687 else
688 {
689 /*
690 * Make a special case of a choice or option next to another
691 * choice or option. In this case, add an (invented) whitespace
692 * node, to ensure a match with suitable input.
693 */
694 if ((child->type == NODE_OPTIONAL || child->type == NODE_CHOICE)
695 && (node->type == NODE_OPTIONAL || node->type == NODE_CHOICE))
696 {
697 sc_ptnoderef_t whitespace;
698
699 /* Interpose invented whitespace. */
700 whitespace = uip_new_node (NODE_WHITESPACE);
701 child->right_sibling = whitespace;
702 child = child->right_sibling;
703 }
704
705 child->right_sibling = node;
706 child = child->right_sibling;
707 }
708 continue;
709 }
710 }
711 }
712
713
714 /*
715 * uip_destroy_tree()
716 *
717 * Free and destroy a parsed pattern tree.
718 */
719 static void
720 uip_destroy_tree (sc_ptnoderef_t node)
721 {
722 if (node)
723 {
724 /* Recursively destroy siblings, then left child. */
725 uip_destroy_tree (node->right_sibling);
726 uip_destroy_tree (node->left_child);
727
728 /* Destroy the node itself. */
729 uip_destroy_node (node);
730 }
731 }
732
733
734 /*
735 * uip_debug_dump_node()
736 * uip_debug_dump()
737 *
738 * Print out a pattern match tree.
739 */
740 static void
741 uip_debug_dump_node (sc_ptnoderef_t node, sc_int depth)
742 {
743 /* End recursion on null node. */
744 if (node)
745 {
746 sc_int index_;
747
748 sc_trace (" ");
749 for (index_ = 0; index_ < depth; index_++)
750 sc_trace (" ");
751
752 sc_trace ("%p", (void *) node);
753 switch (node->type)
754 {
755 case NODE_CHOICE:
756 sc_trace (", choice");
757 break;
758 case NODE_OPTIONAL:
759 sc_trace (", optional");
760 break;
761 case NODE_WILDCARD:
762 sc_trace (", wildcard");
763 break;
764 case NODE_WHITESPACE:
765 sc_trace (", whitespace");
766 break;
767 case NODE_CHARACTER_REFERENCE:
768 sc_trace (", character");
769 break;
770 case NODE_OBJECT_REFERENCE:
771 sc_trace (", object");
772 break;
773 case NODE_TEXT_REFERENCE:
774 sc_trace (", text");
775 break;
776 case NODE_NUMBER_REFERENCE:
777 sc_trace (", number");
778 break;
779 case NODE_WORD:
780 sc_trace (", word \"%s\"", node->word);
781 break;
782 case NODE_VARIABLE:
783 sc_trace (", variable \"%s\"", node->word);
784 break;
785 case NODE_LIST:
786 sc_trace (", list");
787 break;
788 case NODE_EOS:
789 sc_trace (", <eos>");
790 break;
791 default:
792 sc_trace (", unknown type %ld", (sc_int) node->type);
793 break;
794 }
795 if (node->left_child)
796 sc_trace (", left child %p", (void *) node->left_child);
797 if (node->right_sibling)
798 sc_trace (", right sibling %p", (void *) node->right_sibling);
799 sc_trace ("\n");
800
801 /* Recursively dump left child, then siblings. */
802 uip_debug_dump_node (node->left_child, depth + 1);
803 uip_debug_dump_node (node->right_sibling, depth);
804 }
805 }
806
807 static void
808 uip_debug_dump (void)
809 {
810 sc_trace ("UIParser: debug dump follows...\n");
811 if (uip_parse_tree)
812 {
813 sc_trace ("uip_parse_tree = {\n");
814 uip_debug_dump_node (uip_parse_tree, 0);
815 sc_trace ("}\n");
816 }
817 else
818 sc_trace ("uip_parse_tree = (nil)\n");
819 }
820
821
822 /* String matching variables. */
823 static const sc_char *uip_string = NULL;
824 static sc_int uip_posn = 0;
825 static sc_gameref_t uip_game = NULL;
826
827 /*
828 * uip_match_start()
829 * uip_match_end()
830 *
831 * Set up a string for matching to a pattern tree, and wrap up matching.
832 */
833 static void
834 uip_match_start (const sc_char *string, sc_gameref_t game)
835 {
836 /* Save string, and restart index. */
837 uip_string = string;
838 uip_posn = 0;
839
840 /* Save the game we're working on. */
841 uip_game = game;
842 }
843
844 static void
845 uip_match_end (void)
846 {
847 /* Clear match target string, and variable set. */
848 uip_string = NULL;
849 uip_posn = 0;
850 uip_game = NULL;
851 }
852
853
854 /*
855 * uip_get_game()
856 *
857 * Safety wrapper to ensure module code sees a valid game when it requires
858 * one.
859 */
860 static sc_gameref_t
861 uip_get_game (void)
862 {
863 assert (gs_is_game_valid (uip_game));
864 return uip_game;
865 }
866
867
868 /* Forward declaration of low level node matcher. */
869 static sc_bool uip_match_node (sc_ptnoderef_t node);
870
871 /*
872 * uip_match_eos()
873 * uip_match_word()
874 * uip_match_variable()
875 * uip_match_whitespace()
876 * uip_match_list()
877 * uip_match_alternatives()
878 * uip_match_choice()
879 * uip_match_optional()
880 * uip_match_wildcard()
881 *
882 * Text element and list/choice element match functions. Return TRUE, and
883 * advance position if necessary, on match, FALSE on no match, with position
884 * unchanged.
885 */
886 static sc_bool
887 uip_match_eos (void)
888 {
889 /* Check that we hit the string's end. */
890 return uip_string[uip_posn] == NUL;
891 }
892
893 static sc_bool
894 uip_match_word (sc_ptnoderef_t node)
895 {
896 sc_int length;
897 const sc_char *word;
898
899 /* Get the word to match. */
900 assert (node->word);
901 word = node->word;
902
903 /* Compare string text with this node's word, ignore case. */
904 length = strlen (word);
905 if (sc_strncasecmp (uip_string + uip_posn, word, length) == 0)
906 {
907 /* Word match, advance position and return. */
908 uip_posn += length;
909 return TRUE;
910 }
911
912 /* No match. */
913 return FALSE;
914 }
915
916 static sc_bool
917 uip_match_variable (sc_ptnoderef_t node)
918 {
919 const sc_gameref_t game = uip_get_game ();
920 const sc_var_setref_t vars = gs_get_vars (game);
921 sc_int type;
922 sc_vartype_t vt_rvalue;
923 const sc_char *name;
924
925 /* Get the variable name to match, from overloaded word. */
926 assert (node->word);
927 name = node->word;
928
929 /* Get the variable's value. */
930 if (var_get (vars, name, &type, &vt_rvalue))
931 {
932 sc_int length;
933
934 /* Compare the value against the current string position. */
935 switch (type)
936 {
937 case VAR_INTEGER:
938 {
939 sc_char value[32];
940
941 /* Compare numeric against the current string position. */
942 sprintf (value, "%ld", vt_rvalue.integer);
943 length = strlen (value);
944 if (strncmp (uip_string + uip_posn, value, length) == 0)
945 {
946 /* Integer match, advance position and return. */
947 uip_posn += length;
948 return TRUE;
949 }
950 break;
951 }
952
953 case VAR_STRING:
954 /* Compare string value against the current string position. */
955 length = strlen (vt_rvalue.string);
956 if (sc_strncasecmp (uip_string + uip_posn,
957 vt_rvalue.string, length) == 0)
958 {
959 /* String match, advance position and return. */
960 uip_posn += length;
961 return TRUE;
962 }
963 break;
964
965 default:
966 sc_fatal ("uip_match_variable: invalid variable type, %ld\n", type);
967 }
968 }
969
970 /* No match, or no such variable. */
971 return FALSE;
972 }
973
974 static sc_bool
975 uip_match_whitespace (void)
976 {
977 /* If next character is space, read whitespace and return. */
978 if (sc_isspace (uip_string[uip_posn]))
979 {
980 /* Space match, advance position and return. */
981 while (uip_string[uip_posn] != NUL && sc_isspace (uip_string[uip_posn]))
982 uip_posn++;
983 return TRUE;
984 }
985
986 /*
987 * No match. However, if we're trying to match space, this is a word
988 * boundary. So... even though we're not sitting on a space, if the string
989 * prior character is whitespace, "double-match" the space.
990 *
991 * Also, match if we haven't yet matched any text. In effect, this means
992 * leading spaces on patterns will be ignored.
993 *
994 * TODO Is this what we want to happen? It seems harmless, even useful.
995 */
996 if (uip_posn == 0 || sc_isspace (uip_string[uip_posn - 1]))
997 return TRUE;
998
999 /*
1000 * And that's not all. We also want to match whitespace if we're at the end
1001 * of a string (another word boundary). This will permit patterns that end
1002 * in optional elements to succeed since options and wildcards always match,
1003 * even if to no text.
1004 */
1005 if (uip_string[uip_posn] == NUL)
1006 return TRUE;
1007
1008 /* No match. Really. */
1009 return FALSE;
1010 }
1011
1012 static sc_bool
1013 uip_match_list (sc_ptnoderef_t node)
1014 {
1015 sc_ptnoderef_t child;
1016
1017 /*
1018 * If this list is empty, fail the match. This special-case handling is
1019 * what catches constructed temporary lists for wildcard-like items that
1020 * don't actually encompass anything.
1021 */
1022 if (!node->left_child)
1023 return FALSE;
1024
1025 /* Match everything listed sequentially. */
1026 for (child = node->left_child; child; child = child->right_sibling)
1027 {
1028 if (!uip_match_node (child))
1029 {
1030 /* No match. */
1031 return FALSE;
1032 }
1033 }
1034
1035 /* Matched. */
1036 return TRUE;
1037 }
1038
1039 static sc_bool
1040 uip_match_alternatives (sc_ptnoderef_t node)
1041 {
1042 sc_ptnoderef_t child;
1043 sc_int start_posn, extent;
1044 sc_bool matched;
1045
1046 /* Note the start position for rewind between tries. */
1047 start_posn = uip_posn;
1048
1049 /*
1050 * Try a match on each of the children, looking to see which one moves the
1051 * position on the furthest. Match on this one. This is a "maximal munch".
1052 */
1053 extent = uip_posn;
1054 matched = FALSE;
1055 for (child = node->left_child; child; child = child->right_sibling)
1056 {
1057 uip_posn = start_posn;
1058 if (uip_match_node (child))
1059 {
1060 /* Matched. */
1061 matched = TRUE;
1062 if (uip_posn > extent)
1063 extent = uip_posn;
1064 }
1065 }
1066
1067 /* If matched, set position to extent; if not, back to start. */
1068 uip_posn = matched ? extent : start_posn;
1069
1070 /* Return match status. */
1071 return matched;
1072 }
1073
1074 static sc_bool
1075 uip_match_choice (sc_ptnoderef_t node)
1076 {
1077 /*
1078 * Return the result of matching alternatives. The choice will therefore
1079 * fail if none of the alternatives match.
1080 */
1081 return uip_match_alternatives (node);
1082 }
1083
1084 static sc_bool
1085 uip_match_optional (sc_ptnoderef_t node)
1086 {
1087 sc_int start_posn;
1088 sc_ptnoderef_t list;
1089 sc_bool matched;
1090
1091 /* Note the start position for rewind on empty match. */
1092 start_posn = uip_posn;
1093
1094 /*
1095 * Look ahead to see if we can match to nothing, and still have the main
1096 * pattern match. If we can, we'll go with this. It's a "minimal munch"-ish
1097 * strategy, but seems to be what Adrift does in this situation.
1098 */
1099 list = uip_new_node (NODE_LIST);
1100 list->left_child = node->right_sibling;
1101
1102 /* Match on the temporary list. */
1103 matched = uip_match_node (list);
1104
1105 /* Free the temporary list node. */
1106 uip_destroy_node (list);
1107
1108 /*
1109 * If the temporary matched and consumed text, rewind position to match
1110 * nothing. If it didn't, match alternatives to consume anything that may
1111 * match our options.
1112 */
1113 if (matched && uip_posn > start_posn)
1114 uip_posn = start_posn;
1115 else
1116 uip_match_alternatives (node);
1117
1118 /* Return TRUE no matter what. */
1119 return TRUE;
1120 }
1121
1122 static sc_bool
1123 uip_match_wildcard (sc_ptnoderef_t node)
1124 {
1125 sc_int start_posn, limit, index_;
1126 sc_bool matched;
1127 sc_ptnoderef_t list;
1128
1129 /*
1130 * At least one game uses patterns like "thing******...". Why? Who knows.
1131 * But if we're in a list of wildcards, and not the first, ignore the call;
1132 * only the final one needs handling.
1133 */
1134 if (node->right_sibling && node->right_sibling->type == NODE_WILDCARD)
1135 return TRUE;
1136
1137 /* Note the start position for rewind on no match. */
1138 start_posn = uip_posn;
1139
1140 /*
1141 * To make life a little easier, we'll match on the tree to the right of
1142 * this node by constructing a temporary list node, containing stuff to the
1143 * right of the wildcard, and then matching on that.
1144 */
1145 list = uip_new_node (NODE_LIST);
1146 list->left_child = node->right_sibling;
1147
1148 /*
1149 * Repeatedly try to match the rest of the tree at successive character
1150 * positions, and stop if we succeed. This is a "minimal munch", which may
1151 * or may not be the right thing to be doing here.
1152 *
1153 * When scanning forward, take care to include the NUL, needed to match
1154 * TOK_EOS.
1155 */
1156 matched = FALSE;
1157 limit = strlen (uip_string) + 1;
1158 for (index_ = uip_posn + 1; index_ < limit; index_++)
1159 {
1160 uip_posn = index_;
1161 if (uip_match_node (list))
1162 {
1163 /* Wildcard match at this point. */
1164 uip_posn = index_;
1165 matched = TRUE;
1166 break;
1167 }
1168 }
1169
1170 /* Free the temporary list node. */
1171 uip_destroy_node (list);
1172
1173 /* If we didn't match in the loop, restore position. */
1174 if (!matched)
1175 uip_posn = start_posn;
1176
1177 /* Return TRUE whether we matched text or not. */
1178 return TRUE;
1179 }
1180
1181
1182 /*
1183 * uip_match_number()
1184 * uip_match_text()
1185 *
1186 * Attempt to match a number, or a word, from the string.
1187 */
1188 static sc_bool
1189 uip_match_number (void)
1190 {
1191 const sc_gameref_t game = uip_get_game ();
1192 const sc_var_setref_t vars = gs_get_vars (game);
1193 sc_int number;
1194
1195 /* Attempt to read a number from input. */
1196 if (sscanf (uip_string + uip_posn, "%ld", &number) == 1)
1197 {
1198 /* Advance position over the number. */
1199 while (uip_string[uip_posn] == MINUS || uip_string[uip_posn] == PLUS)
1200 uip_posn++;
1201 while (sc_isdigit (uip_string[uip_posn]))
1202 uip_posn++;
1203
1204 /* Set number reference in variables and return. */
1205 var_set_ref_number (vars, number);
1206 return TRUE;
1207 }
1208
1209 /* No match. */
1210 return FALSE;
1211 }
1212
1213 static sc_bool
1214 uip_match_text (sc_ptnoderef_t node)
1215 {
1216 const sc_gameref_t game = uip_get_game ();
1217 const sc_var_setref_t vars = gs_get_vars (game);
1218 sc_int start_posn, limit, index_;
1219 sc_bool matched;
1220 sc_ptnoderef_t list;
1221
1222 /* Note the start position for rewind on no match. */
1223 start_posn = uip_posn;
1224
1225 /*
1226 * As with wildcards, create a temporary list of the stuff to the right of
1227 * the reference node, and match on that.
1228 */
1229 list = uip_new_node (NODE_LIST);
1230 list->left_child = node->right_sibling;
1231
1232 /*
1233 * Again, as with wildcards, repeatedly try to match the rest of the tree at
1234 * successive character positions, stopping if we succeed.
1235 */
1236 matched = FALSE;
1237 limit = strlen (uip_string) + 1;
1238 for (index_ = uip_posn + 1; index_ < limit; index_++)
1239 {
1240 uip_posn = index_;
1241 if (uip_match_node (list))
1242 {
1243 /* Text reference match at this point. */
1244 uip_posn = index_;
1245 matched = TRUE;
1246 break;
1247 }
1248 }
1249
1250 /* Free the temporary list node. */
1251 uip_destroy_node (list);
1252
1253 /* See if we found a match in the loop. */
1254 if (matched)
1255 {
1256 sc_char *string;
1257
1258 /* Found a match; create a string and save the text. */
1259 string = sc_malloc (uip_posn - start_posn + 1);
1260 memcpy (string, uip_string + start_posn, uip_posn - start_posn);
1261 string[uip_posn - start_posn] = NUL;
1262
1263 /*
1264 * Adrift seems to save referenced text as all-lowercase; we need to do
1265 * the same.
1266 */
1267 for (index_ = 0; string[index_] != NUL; index_++)
1268 string[index_] = sc_tolower (string[index_]);
1269 var_set_ref_text (vars, string);
1270 sc_free (string);
1271
1272 /* Return TRUE since we matched text. */
1273 return TRUE;
1274 }
1275 else
1276 {
1277 /* We didn't match in the loop; restore position. */
1278 uip_posn = start_posn;
1279
1280 /* Return FALSE on no match. */
1281 return FALSE;
1282 }
1283 }
1284
1285
1286 /*
1287 * uip_skip_article()
1288 *
1289 * Skip over any "a"/"an"/"the"/"some" at the head of a string. Helper for
1290 * %character% and %object% matchers. Returns the revised string position.
1291 */
1292 static sc_int
1293 uip_skip_article (const sc_char *string, sc_int start)
1294 {
1295 sc_int posn;
1296
1297 /* Skip over articles. */
1298 posn = start;
1299 if (sc_compare_word (string + posn, "a", 1))
1300 posn += 1;
1301 else if (sc_compare_word (string + posn, "an", 2))
1302 posn += 2;
1303 else if (sc_compare_word (string + posn, "the", 3))
1304 posn += 3;
1305 else if (sc_compare_word (string + posn, "some", 4))
1306 posn += 4;
1307
1308 /* Skip any whitespace, and return. */
1309 while (sc_isspace (string[posn]) && string[posn] != NUL)
1310 posn++;
1311 return posn;
1312 }
1313
1314
1315 /*
1316 * uip_compare_reference()
1317 *
1318 * Helper for %character% and %object% matchers. Matches multiple words
1319 * if necessary, at the current position. Returns zero if the string
1320 * didn't match, otherwise the length of the current position that matched
1321 * the words passed in (the new value of uip_posn on match).
1322 */
1323 static sc_int
1324 uip_compare_reference (const sc_char *words)
1325 {
1326 sc_int wpos, posn;
1327
1328 /* Skip articles and lead in space on words and string. */
1329 wpos = uip_skip_article (words, 0);
1330 posn = uip_skip_article (uip_string, uip_posn);
1331
1332 /* Match characters from words with the string at position. */
1333 while (TRUE)
1334 {
1335 /* Any character mismatch means no words match. */
1336 if (sc_tolower (words[wpos]) != sc_tolower (uip_string[posn]))
1337 return 0;
1338
1339 /* Move to next character in each. */
1340 wpos++;
1341 posn++;
1342
1343 /*
1344 * If at space, advance over whitespace in words list. Stop when we
1345 * hit the end of the words list.
1346 */
1347 while (sc_isspace (words[wpos]) && words[wpos] != NUL)
1348 wpos++;
1349 if (words[wpos] == NUL)
1350 break;
1351
1352 /*
1353 * About to match another word, so advance over whitespace in the
1354 * current string too.
1355 */
1356 while (sc_isspace (uip_string[posn]) && uip_string[posn] != NUL)
1357 posn++;
1358 }
1359
1360 /*
1361 * We reached the end of words. If we're at the end of the match string, or
1362 * at spaces, we've matched.
1363 */
1364 if (sc_isspace (uip_string[posn]) || uip_string[posn] == NUL)
1365 return posn;
1366
1367 /* More text after the match, so it's not quite a match. */
1368 return 0;
1369 }
1370
1371
1372 /*
1373 * uip_compare_prefixed_name()
1374 *
1375 * Helper for %character% and %object% matchers. Attempts a reference
1376 * match against both the prefixed name, and if that fails, the plain name.
1377 * Returns the extent of the match, or zero if no match.
1378 */
1379 static sc_int
1380 uip_compare_prefixed_name (const sc_char *prefix, const sc_char *name)
1381 {
1382 sc_char buffer[UIP_SHORT_WORD_SIZE + UIP_SHORT_WORD_SIZE + 1];
1383 sc_char *string;
1384 sc_int required, extent;
1385
1386 /* Create a prefixed string, using the local buffer if possible. */
1387 required = strlen (prefix) + strlen (name) + 2;
1388 string = required > (sc_int) sizeof (buffer) ? sc_malloc (required) : buffer;
1389 sprintf (string, "%s %s", prefix, name);
1390
1391 /* Check against the prefixed name first, free string if required. */
1392 extent = uip_compare_reference (string);
1393 if (string != buffer)
1394 sc_free (string);
1395
1396 /* If no match there, retry with just the plain name. */
1397 if (extent == 0)
1398 extent = uip_compare_reference (name);
1399
1400 /* Return the count of characters consumed in matching. */
1401 return extent;
1402 }
1403
1404
1405 /*
1406 * uip_match_remainder()
1407 *
1408 * Helper for %character% and %object% matchers. Matches the remainder
1409 * of a pattern, to resolve the difference between, say, "table leg" and
1410 * "table".
1411 */
1412 static sc_bool
1413 uip_match_remainder (sc_ptnoderef_t node, sc_int extent)
1414 {
1415 sc_ptnoderef_t list;
1416 sc_int start_posn;
1417 sc_bool matched;
1418
1419 /* Note the start position, then advance to the given extent. */
1420 start_posn = uip_posn;
1421 uip_posn = extent;
1422
1423 /*
1424 * Try to match everything after the node passed in, at this position in the
1425 * string.
1426 */
1427 list = uip_new_node (NODE_LIST);
1428 list->left_child = node->right_sibling;
1429
1430 /* Match on the temporary list. */
1431 matched = uip_match_node (list);
1432
1433 /* Free the temporary list node, and restore position. */
1434 uip_destroy_node (list);
1435 uip_posn = start_posn;
1436
1437 /* Return TRUE if the pattern remainder matched. */
1438 return matched;
1439 }
1440
1441
1442 /*
1443 * uip_match_character()
1444 *
1445 * Match a %character% reference. This function searches all NPC names and
1446 * aliases for possible matches, and sets the game npc_references flag
1447 * for any that match. The final one to match is also stored in variables.
1448 */
1449 static sc_bool
1450 uip_match_character (sc_ptnoderef_t node)
1451 {
1452 const sc_gameref_t game = uip_get_game ();
1453 const sc_prop_setref_t bundle = gs_get_bundle (game);
1454 const sc_var_setref_t vars = gs_get_vars (game);
1455 sc_int npc_count, npc, max_extent;
1456
1457 if (uip_trace)
1458 sc_trace ("UIParser: attempting to match %%character%%\n");
1459
1460 /* Clear all current character references. */
1461 gs_clear_npc_references (game);
1462
1463 /* Iterate characters, looking for a name or alias match. */
1464 max_extent = 0;
1465 npc_count = gs_npc_count (game);
1466 for (npc = 0; npc < npc_count; npc++)
1467 {
1468 sc_vartype_t vt_key[4];
1469 const sc_char *prefix, *name;
1470 sc_int alias_count, alias, extent;
1471
1472 /* Get the NPC's prefix and name. */
1473 vt_key[0].string = "NPCs";
1474 vt_key[1].integer = npc;
1475 vt_key[2].string = "Prefix";
1476 prefix = prop_get_string (bundle, "S<-sis", vt_key);
1477 vt_key[2].string = "Name";
1478 name = prop_get_string (bundle, "S<-sis", vt_key);
1479
1480 if (uip_trace)
1481 sc_trace ("UIParser: trying %s\n", name);
1482
1483 /* Compare this name, both prefixed and not. */
1484 extent = uip_compare_prefixed_name (prefix, name);
1485 if (extent > 0 && uip_match_remainder (node, extent))
1486 {
1487 if (uip_trace)
1488 sc_trace ("UIParser: matched\n");
1489
1490 /* Increase the maximum match extent if required. */
1491 max_extent = (extent > max_extent) ? extent : max_extent;
1492
1493 /* Save match in variables and game. */
1494 var_set_ref_character (vars, npc);
1495 game->npc_references[npc] = TRUE;
1496 }
1497
1498 /* Now compare against all NPC aliases. */
1499 vt_key[2].string = "Alias";
1500 alias_count = prop_get_child_count (bundle, "I<-sis", vt_key);
1501
1502 for (alias = 0; alias < alias_count; alias++)
1503 {
1504 const sc_char *alias_name;
1505
1506 /*
1507 * Get the NPC alias. Version 3.9 games introduce empty aliases,
1508 * so check here.
1509 */
1510 vt_key[3].integer = alias;
1511 alias_name = prop_get_string (bundle, "S<-sisi", vt_key);
1512 if (sc_strempty (alias_name))
1513 continue;
1514
1515 if (uip_trace)
1516 sc_trace ("UIParser: trying alias %s\n", alias_name);
1517
1518 /* Compare this alias name, both prefixed and not. */
1519 extent = uip_compare_prefixed_name (prefix, alias_name);
1520 if (extent > 0 && uip_match_remainder (node, extent))
1521 {
1522 if (uip_trace)
1523 sc_trace ("UIParser: matched\n");
1524
1525 /* Increase the maximum match extent if required. */
1526 max_extent = (extent > max_extent) ? extent : max_extent;
1527
1528 /* Save match in variables and game. */
1529 var_set_ref_character (vars, npc);
1530 game->npc_references[npc] = TRUE;
1531 }
1532 }
1533 }
1534
1535 /* On match, advance position and return successfully. */
1536 if (max_extent > 0)
1537 {
1538 uip_posn = max_extent;
1539 return TRUE;
1540 }
1541
1542 /* No match. */
1543 return FALSE;
1544 }
1545
1546
1547 /*
1548 * uip_match_object()
1549 *
1550 * Match an %object% reference. This function searches all object names and
1551 * aliases for possible matches, and sets the game object_references flag
1552 * for any that match. The final one to match is also stored in variables.
1553 */
1554 static sc_bool
1555 uip_match_object (sc_ptnoderef_t node)
1556 {
1557 const sc_gameref_t game = uip_get_game ();
1558 const sc_prop_setref_t bundle = gs_get_bundle (game);
1559 const sc_var_setref_t vars = gs_get_vars (game);
1560 sc_int object_count, object, max_extent;
1561
1562 if (uip_trace)
1563 sc_trace ("UIParser: attempting to match %%object%%\n");
1564
1565 /* Clear all current object references. */
1566 gs_clear_object_references (game);
1567
1568 /* Iterate objects, looking for a name or alias match. */
1569 max_extent = 0;
1570 object_count = gs_object_count (game);
1571 for (object = 0; object < object_count; object++)
1572 {
1573 sc_vartype_t vt_key[4];
1574 const sc_char *prefix, *name;
1575 sc_int alias_count, alias, extent;
1576
1577 /* Get the object's prefix and name. */
1578 vt_key[0].string = "Objects";
1579 vt_key[1].integer = object;
1580 vt_key[2].string = "Prefix";
1581 prefix = prop_get_string (bundle, "S<-sis", vt_key);
1582 vt_key[2].string = "Short";
1583 name = prop_get_string (bundle, "S<-sis", vt_key);
1584
1585 if (uip_trace)
1586 sc_trace ("UIParser: trying %s\n", name);
1587
1588 /* Compare this name, both prefixed and not. */
1589 extent = uip_compare_prefixed_name (prefix, name);
1590 if (extent > 0 && uip_match_remainder (node, extent))
1591 {
1592 if (uip_trace)
1593 sc_trace ("UIParser: matched\n");
1594
1595 /* Increase the maximum match extent if required. */
1596 max_extent = (extent > max_extent) ? extent : max_extent;
1597
1598 /* Save match in variables and game. */
1599 var_set_ref_object (vars, object);
1600 game->object_references[object] = TRUE;
1601 }
1602
1603 /* Now compare against all object aliases. */
1604 vt_key[2].string = "Alias";
1605 alias_count = prop_get_child_count (bundle, "I<-sis", vt_key);
1606
1607 for (alias = 0; alias < alias_count; alias++)
1608 {
1609 const sc_char *alias_name;
1610
1611 /*
1612 * Get the object alias. Version 3.9 games introduce empty aliases,
1613 * so check here.
1614 */
1615 vt_key[3].integer = alias;
1616 alias_name = prop_get_string (bundle, "S<-sisi", vt_key);
1617 if (sc_strempty (alias_name))
1618 continue;
1619
1620 if (uip_trace)
1621 sc_trace ("UIParser: trying alias %s\n", alias_name);
1622
1623 /* Compare this alias name, both prefixed and not. */
1624 extent = uip_compare_prefixed_name (prefix, alias_name);
1625 if (extent > 0 && uip_match_remainder (node, extent))
1626 {
1627 if (uip_trace)
1628 sc_trace ("UIParser: matched\n");
1629
1630 /* Increase the maximum match extent if required. */
1631 max_extent = (extent > max_extent) ? extent : max_extent;
1632
1633 /* Save match in variables and game. */
1634 var_set_ref_object (vars, object);
1635 game->object_references[object] = TRUE;
1636 }
1637 }
1638 }
1639
1640 /* On match, advance position and return successfully. */
1641 if (max_extent > 0)
1642 {
1643 uip_posn = max_extent;
1644 return TRUE;
1645 }
1646
1647 /* No match. */
1648 return FALSE;
1649 }
1650
1651
1652 /*
1653 * uip_match_node()
1654 *
1655 * Attempt to match the given node to the current match string/position.
1656 * Return TRUE, with position advanced, on match, FALSE on fail with the
1657 * position unchanged.
1658 */
1659 static sc_bool
1660 uip_match_node (sc_ptnoderef_t node)
1661 {
1662 sc_bool match = FALSE;
1663
1664 /* Match depending on node type. */
1665 switch (node->type)
1666 {
1667 case NODE_EOS:
1668 match = uip_match_eos ();
1669 break;
1670 case NODE_WORD:
1671 match = uip_match_word (node);
1672 break;
1673 case NODE_VARIABLE:
1674 match = uip_match_variable (node);
1675 break;
1676 case NODE_WHITESPACE:
1677 match = uip_match_whitespace ();
1678 break;
1679 case NODE_LIST:
1680 match = uip_match_list (node);
1681 break;
1682 case NODE_CHOICE:
1683 match = uip_match_choice (node);
1684 break;
1685 case NODE_OPTIONAL:
1686 match = uip_match_optional (node);
1687 break;
1688 case NODE_WILDCARD:
1689 match = uip_match_wildcard (node);
1690 break;
1691 case NODE_CHARACTER_REFERENCE:
1692 match = uip_match_character (node);
1693 break;
1694 case NODE_OBJECT_REFERENCE:
1695 match = uip_match_object (node);
1696 break;
1697 case NODE_NUMBER_REFERENCE:
1698 match = uip_match_number ();
1699 break;
1700 case NODE_TEXT_REFERENCE:
1701 match = uip_match_text (node);
1702 break;
1703 default:
1704 sc_fatal ("uip_match_node: invalid type, %ld\n", (sc_int) node->type);
1705 }
1706
1707 return match;
1708 }
1709
1710
1711 /*
1712 * uip_cleanse_string()
1713 * uip_free_cleansed_string()
1714 *
1715 * Given a string, copy it to the given buffer, and trim leading and trailing
1716 * spaces from it. If the string does not fit the buffer, malloc enough for
1717 * a string copy and use that instead. The caller needs to free this
1718 * allocation if it happens (detectable by comparing the return value to the
1719 * buffer passed in), or call uip_free_cleansed_string.
1720 */
1721 static sc_char *
1722 uip_cleanse_string (const sc_char *original, sc_char *buffer, sc_int length)
1723 {
1724 sc_int required;
1725 sc_char *string;
1726
1727 /*
1728 * Use the supplied buffer if it is long enough, otherwise allocate, and
1729 * copy the string.
1730 */
1731 required = strlen (original) + 1;
1732 string = (required < length) ? buffer : sc_malloc (required);
1733 strcpy (string, original);
1734
1735 /* Trim, and return the string. */
1736 sc_trim_string (string);
1737 return string;
1738 }
1739
1740 static sc_char *
1741 uip_free_cleansed_string (sc_char *string, const sc_char *buffer)
1742 {
1743 /* Free if the string was allocated by the function above. */
1744 if (string != buffer)
1745 sc_free (string);
1746
1747 /* Always returns NULL, for the syntactic convenience of the caller. */
1748 return NULL;
1749 }
1750
1751
1752 /*
1753 * uip_debug_trace()
1754 *
1755 * Set pattern match tracing on/off.
1756 */
1757 void
1758 uip_debug_trace (sc_bool flag)
1759 {
1760 uip_trace = flag;
1761 }
1762
1763
1764 /*
1765 * uip_match()
1766 *
1767 * Match a string to a pattern, and return TRUE on match, FALSE otherwise.
1768 * For performance, this function uses a local buffer to try to avoid the
1769 * need to copy each of the pattern and match strings passed in.
1770 */
1771 sc_bool
1772 uip_match (const sc_char *pattern, const sc_char *string, sc_gameref_t game)
1773 {
1774 static sc_char *cleansed; /* For setjmp safety. */
1775 sc_char buffer[UIP_ALLOCATION_AVOIDANCE_SIZE];
1776 sc_bool match;
1777 assert (pattern && string && game);
1778
1779 /* Start tokenizer. */
1780 cleansed = uip_cleanse_string (pattern, buffer, sizeof (buffer));
1781 if (uip_trace)
1782 sc_trace ("UIParser: pattern \"%s\"\n", cleansed);
1783 uip_tokenize_start (cleansed);
1784
1785 /* Try parsing the pattern, and catch errors. */
1786 if (setjmp (uip_parse_error) == 0)
1787 {
1788 /* Parse the pattern into a match tree. */
1789 uip_parse_lookahead = uip_next_token ();
1790 uip_parse_tree = uip_new_node (NODE_LIST);
1791 uip_parse_list (uip_parse_tree);
1792 uip_tokenize_end ();
1793 cleansed = uip_free_cleansed_string (cleansed, buffer);
1794 }
1795 else
1796 {
1797 /* Parse error -- clean up and fail. */
1798 uip_tokenize_end ();
1799 uip_destroy_tree (uip_parse_tree);
1800 uip_parse_tree = NULL;
1801 cleansed = uip_free_cleansed_string (cleansed, buffer);
1802 return FALSE;
1803 }
1804
1805 /* Dump out the pattern tree if requested. */
1806 if (if_get_trace_flag (SC_DUMP_PARSER_TREES))
1807 uip_debug_dump ();
1808
1809 /* Match the string to the pattern tree. */
1810 cleansed = uip_cleanse_string (string, buffer, sizeof (buffer));
1811 if (uip_trace)
1812 sc_trace ("UIParser: string \"%s\"\n", cleansed);
1813 uip_match_start (cleansed, game);
1814 match = uip_match_node (uip_parse_tree);
1815
1816 /* Clean up matching and free the parsed pattern tree. */
1817 uip_match_end ();
1818 cleansed = uip_free_cleansed_string (cleansed, buffer);
1819 uip_destroy_tree (uip_parse_tree);
1820 uip_parse_tree = NULL;
1821
1822 /* Return result of matching. */
1823 if (uip_trace)
1824 sc_trace ("UIParser: %s\n", match ? "MATCHED!" : "No match");
1825 return match;
1826 }
1827
1828
1829 /*
1830 * uip_replace_pronouns()
1831 *
1832 * Replaces pronouns by their respective object or NPC names, and returns the
1833 * resulting string to the caller, or NULL if no pronouns were replaced. The
1834 * return string is malloc'ed, so the caller needs to remember to free it.
1835 */
1836 sc_char *
1837 uip_replace_pronouns (sc_gameref_t game, const sc_char *string)
1838 {
1839 const sc_prop_setref_t bundle = gs_get_bundle (game);
1840 sc_int buffer_allocation;
1841 sc_char *buffer;
1842 const sc_char *current;
1843 assert (string);
1844
1845 if (uip_trace)
1846 sc_trace ("UIParser: pronoun search \"%s\"\n", string);
1847
1848 /* Begin with a NULL buffer for lazy allocation. */
1849 buffer_allocation = 0;
1850 buffer = NULL;
1851
1852 /* Search for pronouns until no more string remains. */
1853 current = string + strspn (string, WHITESPACE);
1854 while (current[0] != NUL)
1855 {
1856 sc_vartype_t vt_key[3];
1857 sc_int object, npc, extent;
1858 const sc_char *prefix, *name;
1859
1860 /* Initially, no object or NPC, no names, and a zero extent. */
1861 object = npc = -1;
1862 prefix = name = NULL;
1863 extent = 0;
1864
1865 /*
1866 * Search for pronouns where we have an assigned object or NPC. We
1867 * can't be sure of getting plurality right, and it's not always
1868 * intuitive even in English -- is "a pair of scissors" an "it", or
1869 * a "them"? Because of this, we just treat "it" and "them" equally
1870 * for now.
1871 */
1872 if (game->it_object != -1 && sc_compare_word (current, "it", 2))
1873 {
1874 object = game->it_object;
1875 extent = 2;
1876 }
1877 else if (game->it_object != -1 && sc_compare_word (current, "them", 4))
1878 {
1879 object = game->it_object;
1880 extent = 4;
1881 }
1882 else if (game->him_npc != -1 && sc_compare_word (current, "him", 3))
1883 {
1884 npc = game->him_npc;
1885 extent = 3;
1886 }
1887 else if (game->her_npc != -1 && sc_compare_word (current, "her", 3))
1888 {
1889 npc = game->her_npc;
1890 extent = 3;
1891 }
1892 else if (game->it_npc != -1 && sc_compare_word (current, "it", 2))
1893 {
1894 npc = game->it_npc;
1895 extent = 2;
1896 }
1897
1898 /* Assign prefix and name to the full object or NPC name, if any. */
1899 if (object > -1)
1900 {
1901 vt_key[0].string = "Objects";
1902 vt_key[1].integer = object;
1903 vt_key[2].string = "Prefix";
1904 prefix = prop_get_string (bundle, "S<-sis", vt_key);
1905 vt_key[2].string = "Short";
1906 name = prop_get_string (bundle, "S<-sis", vt_key);
1907 }
1908 else if (npc > -1)
1909 {
1910 vt_key[0].string = "NPCs";
1911 vt_key[1].integer = npc;
1912 vt_key[2].string = "Prefix";
1913 prefix = prop_get_string (bundle, "S<-sis", vt_key);
1914 vt_key[2].string = "Name";
1915 name = prop_get_string (bundle, "S<-sis", vt_key);
1916 }
1917
1918 /*
1919 * If a pronoun was found, prefix and name indicate what to insert, and
1920 * extent shows how much of the buffer to replace with them.
1921 */
1922 if (prefix && name && extent > 0)
1923 {
1924 sc_char *position;
1925 sc_int prefix_length, name_length, length, final;
1926
1927 /*
1928 * If not yet allocated, allocate a buffer now, and copy the input
1929 * string into it. Then switch current to the equivalent location
1930 * in the allocated buffer; basic copy-on-write.
1931 */
1932 if (!buffer)
1933 {
1934 buffer_allocation = strlen (string) + 1;
1935 buffer = sc_malloc (buffer_allocation);
1936 strcpy (buffer, string);
1937 current = buffer + (current - string);
1938 }
1939
1940 /*
1941 * If necessary, grow the output buffer for the replacement,
1942 * remembering to adjust current for the new buffer allocated.
1943 * At the same time, note the last character index for the move.
1944 */
1945 prefix_length = strlen (prefix);
1946 name_length = strlen (name);
1947 length = prefix_length + name_length + 1;
1948 if (length > extent)
1949 {
1950 sc_int offset;
1951
1952 offset = current - buffer;
1953 buffer_allocation += length - extent;
1954 buffer = sc_realloc (buffer, buffer_allocation);
1955 current = buffer + offset;
1956 final = length;
1957 }
1958 else
1959 final = extent;
1960
1961 /* Insert the replacement strings into the buffer. */
1962 position = buffer + (current - buffer);
1963 memmove (position + length,
1964 position + extent,
1965 buffer_allocation - (current - buffer) - final);
1966 memcpy (position, prefix, prefix_length);
1967 position[prefix_length] = ' ';
1968 memcpy (position + prefix_length + 1, name, name_length);
1969
1970 /* Adjust current to skip over the replacement. */
1971 current += length;
1972
1973 if (uip_trace)
1974 sc_trace ("Parser: pronoun \"%s\"\n", buffer);
1975 }
1976 else
1977 {
1978 /* If no match, advance current over the unmatched word. */
1979 current += strcspn (current, WHITESPACE);
1980 }
1981
1982 /* Set current to the next word start. */
1983 current += strspn (current, WHITESPACE);
1984 }
1985
1986 /* Return the final string, or NULL if no pronoun replacements. */
1987 return buffer;
1988 }
1989
1990
1991 /*
1992 * uip_assign_pronouns()
1993 *
1994 * Search a player command for object and NPC names, and assign any found to
1995 * game pronouns. The string is searched from front to back, assigning
1996 * pronouns for objects or NPC names as found. Later ones will overwrite
1997 * earlier ones if there is more than one in the string.
1998 */
1999 void
2000 uip_assign_pronouns (sc_gameref_t game, const sc_char *string)
2001 {
2002 const sc_prop_setref_t bundle = gs_get_bundle (game);
2003 const sc_var_setref_t vars = gs_get_vars (game);
2004 const sc_char *current;
2005 sc_int saved_ref_object, saved_ref_character;
2006 assert (string);
2007
2008 if (uip_trace)
2009 sc_trace ("UIParser: pronoun assignment \"%s\"\n", string);
2010
2011 /* Save var references so we can restore them later. */
2012 saved_ref_object = var_get_ref_object (vars);
2013 saved_ref_character = var_get_ref_character (vars);
2014
2015 /* Search for object and NPC names until no more string remains. */
2016 current = string + strspn (string, WHITESPACE);
2017 while (current[0] != NUL)
2018 {
2019 if (uip_match ("%object% *", current, game))
2020 {
2021 sc_int count, index_, object;
2022
2023 /*
2024 * "Disambiguate" by rejecting objects that the player hasn't seen
2025 * or can't see. If the reference is unique, assign to the 'it'
2026 * object pronoun.
2027 */
2028 count = 0;
2029 object = -1;
2030 for (index_ = 0; index_ < gs_object_count (game); index_++)
2031 {
2032 if (game->object_references[index_]
2033 && gs_object_seen (game, index_)
2034 && obj_indirectly_in_room (game,
2035 index_, gs_playerroom (game)))
2036 {
2037 count++;
2038 object = index_;
2039 }
2040 }
2041
2042 if (count == 1)
2043 {
2044 game->it_object = object;
2045 game->it_npc = -1;
2046
2047 if (uip_trace)
2048 sc_trace ("UIParser: object 'it/them' assigned %ld\n", object);
2049 }
2050 }
2051
2052 if (uip_match ("%character% *", current, game))
2053 {
2054 sc_int count, index_, npc;
2055
2056 /* Do the same "disambiguation" as for objects above. */
2057 count = 0;
2058 npc = -1;
2059 for (index_ = 0; index_ < gs_npc_count (game); index_++)
2060 {
2061 if (game->npc_references[index_]
2062 && gs_npc_seen (game, index_)
2063 && npc_in_room (game, index_, gs_playerroom (game)))
2064 {
2065 count++;
2066 npc = index_;
2067 }
2068 }
2069
2070 if (count == 1)
2071 {
2072 sc_vartype_t vt_key[3];
2073 sc_int version, gender;
2074
2075 /*
2076 * Version 3.8 games lack NPC gender information, so for this
2077 * case set "him"/"her" on each match, and never set "it"; this
2078 * matches the version 3.8 runner.
2079 */
2080 vt_key[0].string = "Version";
2081 version = prop_get_integer (bundle, "I<-s", vt_key);
2082 if (version == TAF_VERSION_380)
2083 {
2084 game->him_npc = npc;
2085 game->her_npc = npc;
2086 game->it_npc = -1;
2087
2088 if (uip_trace)
2089 {
2090 sc_trace ("UIParser: 3.8 pronouns"
2091 " 'him' and 'her' assigned %ld\n", npc);
2092 }
2093 }
2094 else
2095 {
2096 /* Find the NPC gender, so we know the pronoun to assign. */
2097 vt_key[0].string = "NPCs";
2098 vt_key[1].integer = npc;
2099 vt_key[2].string = "Gender";
2100 gender = prop_get_integer (bundle, "I<-sis", vt_key);
2101
2102 switch (gender)
2103 {
2104 case NPC_MALE:
2105 game->him_npc = npc;
2106 break;
2107 case NPC_FEMALE:
2108 game->her_npc = npc;
2109 break;
2110 case NPC_NEUTER:
2111 game->it_npc = npc;
2112 game->it_object = -1;
2113 break;
2114 default:
2115 sc_error ("uip_assign_pronouns:"
2116 " unknown gender, %ld\n", gender);
2117 }
2118
2119 if (uip_trace)
2120 sc_trace ("UIParser: NPC 'him/her/it' assigned %ld\n", npc);
2121 }
2122 }
2123 }
2124
2125 /*
2126 * Advance the string position by a complete word. This saves a lot
2127 * of time -- there's no point looking for an object or NPC name in
2128 * mid-word, and anyway it's not the right thing to do.
2129 */
2130 current += strcspn (current, WHITESPACE);
2131 current += strspn (current, WHITESPACE);
2132 }
2133
2134 /* Restore variables references. */
2135 var_set_ref_object (vars, saved_ref_object);
2136 var_set_ref_character (vars, saved_ref_character);
2137 }