Debian Codegraph @

terps/tads/tads3/vmgram.cpp

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header$";
4 #endif
5
6 /*
7 * Copyright (c) 2000, 2002 Michael J. Roberts. All Rights Reserved.
8 *
9 * Please see the accompanying license file, LICENSE.TXT, for information
10 * on using and copying this software.
11 */
12 /*
13 Name
14 vmgram.cpp - T3 Grammar Production metaclass
15 Function
16
17 Notes
18
19 Modified
20 02/15/00 MJRoberts - Creation
21 */
22
23 #include <stdlib.h>
24 #include <string.h>
25 #include <assert.h>
26
27 #include "t3std.h"
28 #include "tct3drv.h"
29 #include "tcprs.h"
30 #include "vmtype.h"
31 #include "vmstack.h"
32 #include "vmrun.h"
33 #include "vmlst.h"
34 #include "vmstr.h"
35 #include "vmgram.h"
36 #include "vmerr.h"
37 #include "vmerrnum.h"
38 #include "vmmeta.h"
39 #include "vmdict.h"
40 #include "vmtobj.h"
41 #include "vmpredef.h"
42 #include "vmfile.h"
43 #include "vmbif.h"
44 #include "vmdynfunc.h"
45 #include "vmpredef.h"
46
47
48 /* ------------------------------------------------------------------------ */
49 /*
50 * Grammar production object - undo record. This records a deleted or
51 * replaced alternative at a given index.
52 */
53 #define VMGRAM_UNDO_DELETED 1 /* alternative was deleted */
54 #define VMGRAM_UNDO_REPLACED 2 /* alternative was replaced */
55 #define VMGRAM_UNDO_ADDED 3 /* alternative was added */
56 struct vmgram_undo_rec
57 {
58 vmgram_undo_rec(int op, int idx, vmgram_alt_info *alt)
59 {
60 this->idx = idx;
61 this->op = op;
62 this->alt = alt;
63 }
64
65 ~vmgram_undo_rec()
66 {
67 /* delete our alternative */
68 if (alt != 0)
69 delete alt;
70 }
71
72 /* original index of 'alt' in the production's alternative list */
73 int idx;
74
75 /* operation that was performed */
76 int op;
77
78 /* the original alternative rule data */
79 vmgram_alt_info *alt;
80 };
81
82
83 /* ------------------------------------------------------------------------ */
84 /*
85 * Grammar production object - memory pool. This is a simple
86 * suballocator that obtains large blocks from the system allocator,
87 * then hands out pieces of those blocks. Allocating is very cheap
88 * (just a pointer increment in most cases), and we don't track
89 * individual allocations and deletions but just throw away all
90 * suballocated memory at once.
91 */
92
93 /* size of each memory block */
94 const size_t VMGRAMPROD_MEM_BLOCK_SIZE = 16*1024;
95
96 /*
97 * memory pool block
98 */
99 struct CVmGramProdMemBlock
100 {
101 /* next block in chain */
102 CVmGramProdMemBlock *nxt_;
103
104 /* bytes of the block */
105 char buf_[VMGRAMPROD_MEM_BLOCK_SIZE];
106 };
107
108 /*
109 * memory pool object
110 */
111 class CVmGramProdMem
112 {
113 public:
114 CVmGramProdMem()
115 {
116 /* no memory blocks yet */
117 block_head_ = 0;
118 block_cur_ = 0;
119
120 /* we don't yet have a block */
121 cur_rem_ = 0;
122 cur_free_ = 0;
123 }
124
125 ~CVmGramProdMem()
126 {
127 /* delete each of our blocks */
128 while (block_head_ != 0)
129 {
130 CVmGramProdMemBlock *nxt;
131
132 /* remember the next block */
133 nxt = block_head_->nxt_;
134
135 /* delete this block */
136 t3free(block_head_);
137
138 /* move on to the next */
139 block_head_ = nxt;
140 }
141 }
142
143 /* reset - delete all previously sub-allocated memory */
144 void reset()
145 {
146 /* start over with the first block */
147 block_cur_ = block_head_;
148
149 /* initialize the free pointer for the new block, if we have one */
150 if (block_cur_ != 0)
151 {
152 /* start at the beginning of the new block */
153 cur_free_ = block_cur_->buf_;
154
155 /* this entire block is available */
156 cur_rem_ = VMGRAMPROD_MEM_BLOCK_SIZE;
157 }
158 else
159 {
160 /* there are no blocks, so there's no memory available yet */
161 cur_rem_ = 0;
162 cur_free_ = 0;
163 }
164 }
165
166 /* allocate memory */
167 void *alloc(size_t siz)
168 {
169 void *ret;
170
171 /* round the size to the local hardware boundary */
172 siz = osrndsz(siz);
173
174 /* if it exceeds the block size, fail */
175 if (siz > VMGRAMPROD_MEM_BLOCK_SIZE)
176 return 0;
177
178 /* if we don't have enough space in this block, go to the next */
179 if (siz > cur_rem_)
180 {
181 /* allocate a new block if necessary */
182 if (block_cur_ == 0)
183 {
184 /* there's nothing in the list yet - set up the first block */
185 block_head_ = (CVmGramProdMemBlock *)
186 t3malloc(sizeof(CVmGramProdMemBlock));
187
188 /* activate the new block */
189 block_cur_ = block_head_;
190
191 /* there's nothing after this block */
192 block_cur_->nxt_ = 0;
193 }
194 else if (block_cur_->nxt_ == 0)
195 {
196 /* we're at the end of the list - add a block */
197 block_cur_->nxt_ = (CVmGramProdMemBlock *)
198 t3malloc(sizeof(CVmGramProdMemBlock));
199
200 /* advance to the new block */
201 block_cur_ = block_cur_->nxt_;
202
203 /* the new block is the last in the chain */
204 block_cur_->nxt_ = 0;
205 }
206 else
207 {
208 /* another block follows - advance to it */
209 block_cur_ = block_cur_->nxt_;
210 }
211
212 /* start at the beginning of the new block */
213 cur_free_ = block_cur_->buf_;
214
215 /* this entire block is available */
216 cur_rem_ = VMGRAMPROD_MEM_BLOCK_SIZE;
217 }
218
219 /* the return value will be the current free pointer */
220 ret = cur_free_;
221
222 /* consume the space */
223 cur_free_ += siz;
224 cur_rem_ -= siz;
225
226 /* return the block location */
227 return ret;
228 }
229
230 private:
231 /* head of block list */
232 CVmGramProdMemBlock *block_head_;
233
234 /* block we're currently suballocating out of */
235 CVmGramProdMemBlock *block_cur_;
236
237 /* current free pointer in current block */
238 char *cur_free_;
239
240 /* amount of space remaining in current block */
241 size_t cur_rem_;
242 };
243
244 /* ------------------------------------------------------------------------ */
245 /*
246 * Alternative object
247 */
248
249 vmgram_alt_info::vmgram_alt_info(size_t ntoks)
250 {
251 toks = new vmgram_tok_info[ntoks];
252 tok_cnt = ntoks;
253 score = 0;
254 badness = 0;
255 del = FALSE;
256 }
257
258 vmgram_alt_info::~vmgram_alt_info()
259 {
260 delete [] toks;
261 }
262
263 /* ------------------------------------------------------------------------ */
264 /*
265 * Input token array entry. We make a private copy of the input token list
266 * (i.e., the token list we're trying to match to our grammar rules) during
267 * parsing using one of these structures for each token.
268 */
269 struct vmgramprod_tok
270 {
271 /* original token value */
272 vm_val_t val_;
273
274 /* token type */
275 ulong typ_;
276
277 /* token text */
278 const char *txt_;
279
280 /* length of the token text */
281 size_t len_;
282
283 /* hash value of the token */
284 unsigned int hash_;
285
286 /* number of vocabulary matches associated with the word */
287 size_t match_cnt_;
288
289 /* pointer to list of matches for the word */
290 vmgram_match_info *matches_;
291 };
292
293
294 /* ------------------------------------------------------------------------ */
295 /*
296 * Parsing state match object. A match can be terminal, in which case
297 * it refers to a single token of input, or it can be a production, in
298 * which case it refers to a subtree of match objects.
299 */
300 struct CVmGramProdMatch
301 {
302 /* allocate */
303 static CVmGramProdMatch *alloc(CVmGramProdMem *mem, size_t tok_pos,
304 const vm_val_t *tok_match_result,
305 int matched_star,
306 vm_prop_id_t target_prop,
307 vm_obj_id_t proc_obj,
308 const CVmGramProdMatch **sub_match_list,
309 size_t sub_match_cnt)
310 {
311 CVmGramProdMatch *match;
312
313 /* allocate space */
314 match = (CVmGramProdMatch *)mem->alloc(sizeof(CVmGramProdMatch));
315
316 /* initialize */
317 match->tok_pos_ = tok_pos;
318 match->matched_star_ = matched_star;
319 match->target_prop_ = target_prop;
320 match->proc_obj_ = proc_obj;
321 match->sub_match_list_ = sub_match_list;
322 match->sub_match_cnt_ = sub_match_cnt;
323
324 /* save the token match value, if one was given */
325 if (tok_match_result != 0)
326 match->tok_match_result_ = *tok_match_result;
327 else
328 match->tok_match_result_.set_nil();
329
330 /* return the new match */
331 return match;
332 }
333
334 /* property ID with which this match is associated */
335 vm_prop_id_t target_prop_;
336
337 /*
338 * token position of the matching token; ignored if the production
339 * subtree information is valid
340 */
341 size_t tok_pos_;
342
343 /*
344 * The token match value. This is the result code from the Dictionary
345 * comparator's matchValues() function, which typically encodes
346 * information about how the value matched (truncation, case folding,
347 * accent approximation, etc) in bitwise flags.
348 */
349 vm_val_t tok_match_result_;
350
351 /*
352 * flag: this is a '*' token in the rule; these don't really match any
353 * tokens at all, since they merely serve to stop parsing regardless
354 * of whether or not more input tokens are present
355 */
356 int matched_star_;
357
358 /*
359 * object ID of match processor - if this is valid, this match
360 * refers to a production; otherwise, the match refers to a single
361 * token
362 */
363 vm_obj_id_t proc_obj_;
364
365 /* pointer to array of sub-matches */
366 const CVmGramProdMatch **sub_match_list_;
367
368 /* number of sub-match entries */
369 size_t sub_match_cnt_;
370 };
371
372 /*
373 * Top-level match list holder
374 */
375 struct CVmGramProdMatchEntry
376 {
377 /* the match tree */
378 CVmGramProdMatch *match_;
379
380 /* token position at the end of the match */
381 size_t tok_pos_;
382
383 /* next entry in the list */
384 CVmGramProdMatchEntry *nxt_;
385 };
386
387 /*
388 * Parsing state object. At any given time, we will have one or more of
389 * these state objects in our processing queue. A state object tracks a
390 * parsing position - the token position, the alternative position, the
391 * match list so far for the alternative (i.e., the match for each item
392 * in the alternative up to but not including the current position), and
393 * the enclosing parsing state object (i.e., the parsing state that
394 * "recursed" into this alternative).
395 */
396 struct CVmGramProdState
397 {
398 /* allocate */
399 static CVmGramProdState *alloc(CVmGramProdMem *mem,
400 int tok_pos, int alt_pos,
401 CVmGramProdState *enclosing,
402 const vmgram_alt_info *altp,
403 vm_obj_id_t prod_obj,
404 int circular_alt)
405 {
406 size_t match_cnt;
407 CVmGramProdState *state;
408
409 /* get the number of match list slots we'll need */
410 match_cnt = altp->tok_cnt;
411
412 /* allocate space, including space for the match list */
413 state = (CVmGramProdState *)
414 mem->alloc(sizeof(CVmGramProdState)
415 + (match_cnt - 1)*sizeof(CVmGramProdMatch *));
416
417 /* initialize */
418 state->init(tok_pos, alt_pos, enclosing, altp, prod_obj,
419 circular_alt);
420
421 /* return the new item */
422 return state;
423 }
424
425 /* initialize */
426 void init(int tok_pos, int alt_pos, CVmGramProdState *enclosing,
427 const vmgram_alt_info *altp, vm_obj_id_t prod_obj,
428 int circular_alt)
429 {
430 /* remember the position parameters */
431 tok_pos_ = tok_pos;
432 alt_pos_ = alt_pos;
433
434 /* we haven't matched a '*' token yet */
435 matched_star_ = FALSE;
436
437 /* remember our stack position */
438 enclosing_ = enclosing;
439
440 /* remember our alternative image data pointer */
441 altp_ = altp;
442
443 /* remember the production object */
444 prod_obj_ = prod_obj;
445
446 /* note if we had circular alternatives in the same production */
447 circular_alt_ = circular_alt;
448
449 /* no target property for sub-production yet */
450 sub_target_prop_ = VM_INVALID_PROP;
451
452 /* we're not in the queue yet */
453 nxt_ = 0;
454 }
455
456 /* clone the state */
457 CVmGramProdState *clone(CVmGramProdMem *mem)
458 {
459 CVmGramProdState *new_state;
460 CVmGramProdState *new_enclosing;
461
462 /* clone our enclosing state */
463 new_enclosing = (enclosing_ != 0 ? enclosing_->clone(mem) : 0);
464
465 /* create a new state object */
466 new_state = alloc(mem, tok_pos_, alt_pos_, new_enclosing,
467 altp_, prod_obj_, circular_alt_);
468
469 /* copy the target sub-production property */
470 new_state->sub_target_prop_ = sub_target_prop_;
471
472 /* copy the valid portion of my match list */
473 if (alt_pos_ != 0)
474 memcpy(new_state->match_list_, match_list_,
475 alt_pos_ * sizeof(match_list_[0]));
476
477 /* we're not yet in any queue */
478 new_state->nxt_ = 0;
479
480 /* set the '*' flag in the cloned state */
481 new_state->matched_star_ = matched_star_;
482
483 /* return the clone */
484 return new_state;
485 }
486
487 /* current token position, as an index into the token list */
488 size_t tok_pos_;
489
490 /*
491 * flag: we've matched a '*' token in a production or subproduction,
492 * so we should consider all remaining tokens to have been consumed
493 * (we don't advance tok_pos_ past all of the tokens, because we
494 * separately want to keep track of the number of tokens we matched
495 * for everything up to the '*')
496 */
497 int matched_star_;
498
499 /*
500 * current alternative position, as an index into the alternative's
501 * list of items
502 */
503 size_t alt_pos_;
504
505 /*
506 * the enclosing state object - this is the state object that
507 * "recursed" to our position
508 */
509 CVmGramProdState *enclosing_;
510
511 /* pointer to alternative definition */
512 const vmgram_alt_info *altp_;
513
514 /* object ID of the production object */
515 vm_obj_id_t prod_obj_;
516
517 /* the target property for the pending sub-production */
518 vm_prop_id_t sub_target_prop_;
519
520 /* next production state in the processing queue */
521 CVmGramProdState *nxt_;
522
523 /* the production contains circular alternatives */
524 int circular_alt_;
525
526 /*
527 * Match list. This list is allocated with enough space for one
528 * match for each of our items (the number of items is given by
529 * vmgram_alt_tokcnt(altp_)). At any given time, these will be
530 * valid up to but not including the current alt_pos_ index.
531 */
532 const struct CVmGramProdMatch *match_list_[1];
533 };
534
535 /*
536 * Queues. We maintain three queues: the primary work queue, which
537 * contains pending parsing states that we're still attempting to match;
538 * the success queue, which contains a list of match trees for
539 * successfully completed matches; and the badness queue, which contains
540 * a list of parsing states that we can try as fallbacks if we fail to
541 * find a match in any of the work queue items.
542 */
543 struct CVmGramProdQueue
544 {
545 /* clear the queues */
546 void clear()
547 {
548 work_queue_ = 0;
549 badness_queue_ = 0;
550 success_list_ = 0;
551 }
552
553 /* head of work queue */
554 CVmGramProdState *work_queue_;
555
556 /* head of badness queue */
557 CVmGramProdState *badness_queue_;
558
559 /* head of success list */
560 CVmGramProdMatchEntry *success_list_;
561 };
562
563 /* ------------------------------------------------------------------------ */
564 /*
565 * Grammar-Production object statics
566 */
567
568 /* metaclass registration object */
569 static CVmMetaclassGramProd metaclass_reg_obj;
570 CVmMetaclass *CVmObjGramProd::metaclass_reg_ = &metaclass_reg_obj;
571
572 /* function table */
573 int (CVmObjGramProd::
574 *CVmObjGramProd::func_table_[])(VMG_ vm_obj_id_t self,
575 vm_val_t *retval, uint *argc) =
576 {
577 &CVmObjGramProd::getp_undef, /* 0 */
578 &CVmObjGramProd::getp_parse, /* 1 */
579 &CVmObjGramProd::getp_get_gram_info, /* 2 */
580 &CVmObjGramProd::getp_addAlt, /* 3 */
581 &CVmObjGramProd::getp_deleteAlt, /* 4 */
582 &CVmObjGramProd::getp_clearAlts /* 5 */
583 };
584
585 /* property indices */
586 const int PROPIDX_deleteAlt = 4;
587
588
589 /* ------------------------------------------------------------------------ */
590 /*
591 * Grammar-Production metaclass implementation
592 */
593
594 /*
595 * create dynamically using stack arguments
596 */
597 vm_obj_id_t CVmObjGramProd::create_from_stack(VMG_ const uchar **pc_ptr,
598 uint argc)
599 {
600 /* create an empty new grammar production */
601 vm_obj_id_t id = vm_new_id(vmg_ FALSE, TRUE, TRUE);
602 new (vmg_ id) CVmObjGramProd(vmg0_);
603 CVmObjGramProd *prod = (CVmObjGramProd *)vm_objp(vmg_ id);
604
605 /*
606 * mark the object as modified-since-load, since it was never part of
607 * the image file
608 */
609 prod->get_ext()->modified_ = TRUE;
610
611 /* check arguments */
612 if (argc == 0)
613 {
614 /* no arguments - create a new production with no rules defined */
615 }
616 else
617 {
618 /* invalid argument list */
619 err_throw(VMERR_WRONG_NUM_OF_ARGS);
620 }
621
622 /* discard arguments */
623 G_stk->discard(argc);
624
625 /* return the new ID */
626 return id;
627 }
628
629 /*
630 * constructor
631 */
632 CVmObjGramProd::CVmObjGramProd(VMG0_)
633 {
634 /* allocate our extension structure from the variable heap */
635 ext_ = (char *)G_mem->get_var_heap()
636 ->alloc_mem(sizeof(vm_gram_ext), this);
637
638 /* we have no image data yet */
639 get_ext()->image_data_ = 0;
640 get_ext()->image_data_size_ = 0;
641
642 /* we haven't been modified yet */
643 get_ext()->modified_ = FALSE;
644
645 /* we haven't set up our alternatives yet */
646 get_ext()->alts_ = 0;
647 get_ext()->alt_cnt_ = 0;
648 get_ext()->alt_alo_ = 0;
649
650 /* we haven't cached any hash values yet */
651 get_ext()->hashes_cached_ = FALSE;
652 get_ext()->comparator_ = VM_INVALID_OBJ;
653
654 /* presume we have no circular rules */
655 get_ext()->has_circular_alt = FALSE;
656
657 /* create our memory pool */
658 get_ext()->mem_ = new CVmGramProdMem();
659
660 /*
661 * allocate initial property enumeration space (we'll expand this as
662 * needed, so the initial size is just a guess)
663 */
664 get_ext()->prop_enum_max_ = 64;
665 get_ext()->prop_enum_arr_ = (vmgram_match_info *)
666 t3malloc(get_ext()->prop_enum_max_
667 * sizeof(vmgram_match_info));
668 }
669
670 /*
671 * notify of deletion
672 */
673 void CVmObjGramProd::notify_delete(VMG_ int /*in_root_set*/)
674 {
675 /* free our additional data */
676 if (ext_ != 0)
677 {
678 /* if we've allocated alternatives, delete them */
679 vmgram_alt_info **alts = get_ext()->alts_;
680 if (alts != 0)
681 {
682 /* delete the alternative objects */
683 clear_alts();
684
685 /* free the alternative array itself */
686 t3free(alts);
687 }
688
689 /* delete our memory pool */
690 delete get_ext()->mem_;
691
692 /* delete our property enumeration space */
693 t3free(get_ext()->prop_enum_arr_);
694
695 /* free the extension */
696 G_mem->get_var_heap()->free_mem(ext_);
697 }
698 }
699
700 /* ------------------------------------------------------------------------ */
701 /*
702 * clear the alternative list
703 */
704 void CVmObjGramProd::clear_alts()
705 {
706 /* delete each alternative */
707 for (size_t i = 0 ; i < get_ext()->alt_cnt_ ; ++i)
708 delete get_ext()->alts_[i];
709
710 /* there are no more alternatives in the list */
711 get_ext()->alt_cnt_ = 0;
712 }
713
714 /*
715 * ensure there's room for the given number of alternatives
716 */
717 void CVmObjGramProd::ensure_alts(size_t cnt, size_t margin)
718 {
719 /* if there's not room, allocate a bigger array */
720 if (cnt > get_ext()->alt_alo_)
721 {
722 /* allocate or reallocate at the required size plus the margin */
723 cnt += margin;
724 size_t siz = cnt * sizeof(get_ext()->alts_[0]);
725 if (get_ext()->alts_ != 0)
726 {
727 get_ext()->alts_ = (vmgram_alt_info **)t3realloc(
728 get_ext()->alts_, siz);
729 }
730 else
731 {
732 get_ext()->alts_ = (vmgram_alt_info **)t3malloc(siz);
733 }
734
735 /* set the new allocated count */
736 get_ext()->alt_alo_ = cnt;
737 }
738 }
739
740 /*
741 * insert an alternative at the given index (no undo)
742 */
743 void CVmObjGramProd::insert_alt(
744 vm_obj_id_t self, size_t idx, vmgram_alt_info *alt)
745 {
746 /* make sure we have room for one more alternative */
747 ensure_alts(get_ext()->alt_cnt_ + 1, 8);
748
749 /* get the alt list */
750 vmgram_alt_info **alts = get_ext()->alts_;
751
752 /* open a hole in the array for the new alternative */
753 for (size_t i = get_ext()->alt_cnt_ ; i > idx ; --i)
754 alts[i] = alts[i-1];
755
756 /* adjust the count */
757 get_ext()->alt_cnt_ += 1;
758
759 /* plug in the new alternative */
760 alts[idx] = alt;
761
762 /* we've been modified since load time */
763 get_ext()->modified_ = TRUE;
764
765 /* note if this adds a circular rule */
766 if (alt->tok_cnt != 0
767 && alt->toks->typ == VMGRAM_MATCH_PROD
768 && alt->toks->typinfo.prod_obj == self)
769 get_ext()->has_circular_alt = TRUE;
770 }
771
772 /*
773 * delete the alternative at the given index (no undo)
774 */
775 void CVmObjGramProd::delete_alt(size_t idx)
776 {
777 /* remove it from the array and close the gap */
778 for ( ; idx + 1 < get_ext()->alt_cnt_ ; ++idx)
779 get_ext()->alts_[idx] = get_ext()->alts_[idx+1];
780
781 /* adjust the count */
782 get_ext()->alt_cnt_ -= 1;
783
784 /* we've been modified since load time */
785 get_ext()->modified_ = TRUE;
786 }
787
788
789 /* ------------------------------------------------------------------------ */
790 /*
791 * get a property
792 */
793 int CVmObjGramProd::get_prop(VMG_ vm_prop_id_t prop, vm_val_t *retval,
794 vm_obj_id_t self, vm_obj_id_t *source_obj,
795 uint *argc)
796 {
797 uint func_idx;
798
799 /* translate the property index to an index into our function table */
800 func_idx = G_meta_table
801 ->prop_to_vector_idx(metaclass_reg_->get_reg_idx(), prop);
802
803 /* call the appropriate function */
804 if ((this->*func_table_[func_idx])(vmg_ self, retval, argc))
805 {
806 *source_obj = metaclass_reg_->get_class_obj(vmg0_);
807 return TRUE;
808 }
809
810 /* inherit default handling */
811 return CVmObject::get_prop(vmg_ prop, retval, self, source_obj, argc);
812 }
813
814 /*
815 * set a property
816 */
817 void CVmObjGramProd::set_prop(VMG_ class CVmUndo *undo,
818 vm_obj_id_t self, vm_prop_id_t prop,
819 const vm_val_t *val)
820 {
821 /* no settable properties - throw an error */
822 err_throw(VMERR_INVALID_SETPROP);
823 }
824
825 /* ------------------------------------------------------------------------ */
826 /*
827 * load from an image file
828 */
829 void CVmObjGramProd::load_from_image(VMG_ vm_obj_id_t self,
830 const char *ptr, size_t siz)
831 {
832 /* remember where our image data comes from */
833 get_ext()->image_data_ = ptr;
834 get_ext()->image_data_size_ = siz;
835
836 /*
837 * Rebuild the list from the image file data. Note that an image file
838 * doesn't have a fixup table, since it defines the object numbering
839 * space in the first place.
840 */
841 CVmReadOnlyMemoryStream src(ptr, siz);
842 load_alts(vmg_ self, &src, 0);
843
844 /* we haven't been modified since being loaded from the image */
845 get_ext()->modified_ = FALSE;
846 }
847
848 /*
849 * reset to the image file
850 */
851 void CVmObjGramProd::reset_to_image(VMG_ vm_obj_id_t self)
852 {
853 /* if we we were modified and have image data, reload the image data */
854 if (get_ext()->modified_ && get_ext()->image_data_ != 0)
855 {
856 /* load from our original data stream */
857 CVmReadOnlyMemoryStream src(
858 get_ext()->image_data_, get_ext()->image_data_size_);
859 load_alts(vmg_ self, &src, 0);
860
861 /* we haven't been modified since being loaded from the image */
862 get_ext()->modified_ = FALSE;
863
864 /* reset the comparator caching information */
865 get_ext()->comparator_ = VM_INVALID_OBJ;
866 get_ext()->hashes_cached_ = FALSE;
867 }
868 }
869
870 /*
871 * save to a file
872 */
873 void CVmObjGramProd::save_to_file(VMG_ CVmFile *fp)
874 {
875 /* if we've been dynamically modified, save our contents */
876 if (get_ext()->modified_)
877 {
878 /* save to the file */
879 CVmFileStream dst(fp);
880 save_to_stream(vmg_ &dst);
881 }
882 }
883
884 /*
885 * Save to a data stream
886 */
887 void CVmObjGramProd::save_to_stream(VMG_ CVmStream *fp)
888 {
889 /* write the number of alternatives */
890 fp->write_uint2(get_ext()->alt_cnt_);
891
892 /* write the alternatives */
893 vmgram_alt_info **altp = get_ext()->alts_;
894 for (size_t i = 0 ; i < get_ext()->alt_cnt_ ; ++i, ++altp)
895 {
896 /* get the alternative pointer */
897 vmgram_alt_info *alt = *altp;
898
899 /* write the alternative header */
900 fp->write_int2(alt->score);
901 fp->write_int2(alt->badness);
902 fp->write_uint4((ulong)alt->proc_obj);
903 fp->write_uint2(alt->tok_cnt);
904
905 /* write the token list */
906 vmgram_tok_info *tok = alt->toks;
907 for (size_t j = 0 ; j < alt->tok_cnt ; ++j, ++tok)
908 {
909 /* write the fixed part of the token */
910 fp->write_uint2((uint)tok->prop);
911 fp->write_byte((uchar)tok->typ);
912
913 /* write the extra data according to the token type */
914 switch (tok->typ)
915 {
916 case VMGRAM_MATCH_PROD:
917 /* write the object ID */
918 fp->write_uint4((ulong)tok->typinfo.prod_obj);
919 break;
920
921 case VMGRAM_MATCH_SPEECH:
922 /* write the part-of-speech property */
923 fp->write_uint2((uint)tok->typinfo.speech_prop);
924 break;
925
926 case VMGRAM_MATCH_NSPEECH:
927 /* array of part-of-speech properties - write the count */
928 fp->write_uint2(tok->typinfo.nspeech.cnt);
929
930 /* write the array elements */
931 for (size_t k = 0 ; k < tok->typinfo.nspeech.cnt ; ++k)
932 fp->write_uint2((uint)tok->typinfo.nspeech.props[k]);
933
934 /* done */
935 break;
936
937 case VMGRAM_MATCH_LITERAL:
938 /* literal string - write the length, then the bytes */
939 fp->write_uint2(tok->typinfo.lit.len);
940 fp->write_bytes(tok->typinfo.lit.str, tok->typinfo.lit.len);
941 break;
942
943 case VMGRAM_MATCH_TOKTYPE:
944 /* token type */
945 fp->write_uint4((ulong)tok->typinfo.toktyp_enum);
946 break;
947
948 case VMGRAM_MATCH_STAR:
949 /* star - no additional data */
950 break;
951 }
952 }
953 }
954 }
955
956 /*
957 * restore from a file
958 */
959 void CVmObjGramProd::restore_from_file(VMG_ vm_obj_id_t self,
960 CVmFile *fp, CVmObjFixup *fixups)
961 {
962 /* load our alternative list from the file stream */
963 CVmFileStream src(fp);
964 load_alts(vmg_ self, &src, fixups);
965 }
966
967 /*
968 * Load alternative data from a data source. This is our common handler
969 * for loading from the image file and restoring from a saved game file.
970 */
971 void CVmObjGramProd::load_alts(VMG_ vm_obj_id_t self,
972 CVmStream *src, CVmObjFixup *fixups)
973 {
974 /* delete any existing alternative list */
975 clear_alts();
976
977 /* presume there will be no circular alternatives */
978 get_ext()->has_circular_alt = FALSE;
979
980 /* read the number of alternatives */
981 size_t alt_cnt = src->read_uint2();
982
983 /* ensure there's room for the new list */
984 ensure_alts(alt_cnt, 0);
985
986 /* load the alternatives */
987 for (size_t i = 0 ; i < alt_cnt ; ++i)
988 {
989 /* read the alternative header */
990 int score = src->read_int2();
991 int badness = src->read_int2();
992 vm_obj_id_t proc_obj = (vm_obj_id_t)src->read_uint4();
993 uint tokcnt = src->read_uint2();
994
995 /* fix up the processor object ID */
996 if (fixups != 0)
997 proc_obj = fixups->get_new_id(vmg_ proc_obj);
998
999 /* create this alternative */
1000 vmgram_alt_info *alt = new vmgram_alt_info(tokcnt);
1001 alt->score = score;
1002 alt->badness = badness;
1003 alt->proc_obj = proc_obj;
1004
1005 /* add it to the list in our extension */
1006 get_ext()->alt_cnt_ += 1;
1007 get_ext()->alts_[i] = alt;
1008
1009 /* get the first token */
1010 vmgram_tok_info *tok = alt->toks;
1011
1012 /* read the tokens */
1013 for (size_t j = 0 ; j < tokcnt ; ++j, ++tok)
1014 {
1015 /* read the fixed part of the token */
1016 tok->prop = (vm_prop_id_t)src->read_uint2();
1017 tok->typ = (vmgram_match_type)src->read_byte();
1018
1019 /* read the extra data according to the token type */
1020 switch (tok->typ)
1021 {
1022 case VMGRAM_MATCH_PROD:
1023 /* read the object ID */
1024 tok->typinfo.prod_obj = (vm_obj_id_t)src->read_uint4();
1025
1026 /* fix it up if necessary */
1027 if (fixups != 0)
1028 tok->typinfo.prod_obj = fixups->get_new_id(
1029 vmg_ tok->typinfo.prod_obj);
1030 break;
1031
1032 case VMGRAM_MATCH_SPEECH:
1033 /* read the part-of-speech property */
1034 tok->typinfo.speech_prop = (vm_prop_id_t)src->read_uint2();
1035 break;
1036
1037 case VMGRAM_MATCH_NSPEECH:
1038 /* array of part-of-speech properties */
1039 {
1040 /* read the count */
1041 size_t propcnt = src->read_uint2();
1042
1043 /* allocate the array */
1044 tok->set_nspeech(propcnt);
1045
1046 /* read the properties */
1047 for (size_t k = 0 ; k < propcnt ; ++k)
1048 {
1049 tok->typinfo.nspeech.props[k] =
1050 (vm_prop_id_t)src->read_uint2();
1051 }
1052 }
1053 break;
1054
1055 case VMGRAM_MATCH_LITERAL:
1056 /* literal string */
1057 {
1058 /* read the length */
1059 size_t len = src->read_uint2();
1060
1061 /* allocate the string */
1062 tok->set_literal(len);
1063
1064 /* read the string */
1065 src->read_bytes(tok->typinfo.lit.str, len);
1066 }
1067 break;
1068
1069 case VMGRAM_MATCH_TOKTYPE:
1070 /* token type */
1071 tok->typinfo.toktyp_enum = src->read_uint4();
1072 break;
1073
1074 case VMGRAM_MATCH_STAR:
1075 /* star - no additional data */
1076 break;
1077 }
1078 }
1079
1080 /*
1081 * If the first token of the alternative is a recursive reference
1082 * to this production itself, we have a circular reference. Note
1083 * this, since we have to handle it specially when parsing.
1084 */
1085 tok = alt->toks;
1086 if (tokcnt != 0
1087 && tok->typ == VMGRAM_MATCH_PROD
1088 && tok->typinfo.prod_obj == self)
1089 {
1090 /* note the existence of a circular reference */
1091 get_ext()->has_circular_alt = TRUE;
1092 }
1093 }
1094 }
1095
1096 /* ------------------------------------------------------------------------ */
1097 /*
1098 * apply undo
1099 */
1100 void CVmObjGramProd::apply_undo(VMG_ CVmUndoRecord *undo_rec)
1101 {
1102 /* we only store pointer records, so ignore other types */
1103 if (undo_rec->id.ptrval != 0)
1104 {
1105 /* get our private undo record, properly cast */
1106 vmgram_undo_rec *rec = (vmgram_undo_rec *)undo_rec->id.ptrval;
1107
1108 /* get the 'self' object from the undo record */
1109 vm_obj_id_t self = undo_rec->obj;
1110
1111 /* get the original alternative object and its original index */
1112 vmgram_alt_info *alt = rec->alt;
1113 int idx = rec->idx;
1114
1115 /* get our alternative list and count */
1116 vmgram_alt_info **alts = get_ext()->alts_;
1117
1118 /* apply undo based on the event type */
1119 switch (rec->op)
1120 {
1121 case VMGRAM_UNDO_DELETED:
1122 /* deleted a record - re-insert it at the original index */
1123 insert_alt(self, idx, alt);
1124
1125 /* the grammar prod object owns it now - clear it in the undo */
1126 rec->alt = 0;
1127 break;
1128
1129 case VMGRAM_UNDO_REPLACED:
1130 /* replaced a record - restore it at the original index */
1131 alts[idx] = alt;
1132 break;
1133
1134 case VMGRAM_UNDO_ADDED:
1135 /* added a new record - delete the record at this index */
1136 delete_alt(idx);
1137
1138 /* check for circular references */
1139 check_circular_refs(self);
1140 break;
1141 }
1142 }
1143 }
1144
1145 /*
1146 * discard extra undo record information
1147 */
1148 void CVmObjGramProd::discard_undo(VMG_ CVmUndoRecord *undo_rec)
1149 {
1150 /* check for our private record type */
1151 if (undo_rec->id.ptrval != 0)
1152 {
1153 /* get our private undo record, properly cast */
1154 vmgram_undo_rec *rec = (vmgram_undo_rec *)undo_rec->id.ptrval;
1155
1156 /* delete it */
1157 delete rec;
1158 }
1159 }
1160
1161 /* ------------------------------------------------------------------------ */
1162 /*
1163 * mark object references in an undo record
1164 */
1165 void CVmObjGramProd::mark_undo_ref(VMG_ CVmUndoRecord *undo_rec)
1166 {
1167 /* check for our private record type */
1168 if (undo_rec->id.ptrval != 0)
1169 {
1170 /* get our private undo record, properly cast */
1171 vmgram_undo_rec *rec = (vmgram_undo_rec *)undo_rec->id.ptrval;
1172
1173 /* if it record an alternative, mark its references */
1174 if (rec->alt != 0)
1175 mark_alt_refs(vmg_ rec->alt, VMOBJ_REACHABLE);
1176 }
1177 }
1178
1179 /*
1180 * mark references
1181 */
1182 void CVmObjGramProd::mark_refs(VMG_ uint state)
1183 {
1184 /* if we've been dynamically modified, we could have non-root refs */
1185 if (get_ext()->modified_)
1186 {
1187 /* run through our alternative list */
1188 vmgram_alt_info *const *altp = get_ext()->alts_;
1189 for (size_t i = 0 ; i < get_ext()->alt_cnt_ ; ++i, ++altp)
1190 mark_alt_refs(vmg_ *altp, state);
1191 }
1192 }
1193
1194 /*
1195 * mark references in an alternative
1196 */
1197 void CVmObjGramProd::mark_alt_refs(VMG_ const vmgram_alt_info *alt, uint state)
1198 {
1199 /* mark the match object */
1200 if (alt->proc_obj != VM_INVALID_OBJ)
1201 G_obj_table->mark_all_refs(alt->proc_obj, state);
1202
1203 /* run through the token list */
1204 vmgram_tok_info *tok = alt->toks;
1205 for (size_t j = 0 ; j < alt->tok_cnt ; ++j, ++tok)
1206 {
1207 /* only production matches have object references */
1208 if (tok->typ == VMGRAM_MATCH_PROD
1209 && tok->typinfo.prod_obj != VM_INVALID_OBJ)
1210 {
1211 /* mark the reference */
1212 G_obj_table->mark_all_refs(tok->typinfo.prod_obj, state);
1213 }
1214 }
1215 }
1216
1217 /*
1218 * Remove stale weak references.
1219 */
1220 void CVmObjGramProd::remove_stale_weak_refs(VMG0_)
1221 {
1222 /*
1223 * Our reference to the dictionary comparator object is weak (we're
1224 * only caching it - we don't want to prevent the object from being
1225 * collected if no one else wants it). So, forget it if the comparator
1226 * is being deleted.
1227 */
1228 if (get_ext()->comparator_ != VM_INVALID_OBJ
1229 && G_obj_table->is_obj_deletable(get_ext()->comparator_))
1230 {
1231 /* forget the comparator */
1232 get_ext()->comparator_ = VM_INVALID_OBJ;
1233
1234 /*
1235 * our cached hash values depend on the comparator, so they're now
1236 * invalid - forget about them
1237 */
1238 get_ext()->hashes_cached_ = FALSE;
1239 }
1240 }
1241
1242
1243 /* ------------------------------------------------------------------------ */
1244 /*
1245 * Context for enum_props_cb
1246 */
1247 struct enum_props_ctx
1248 {
1249 /* object extension */
1250 vm_gram_ext *ext;
1251
1252 /* number of properties in our list so far */
1253 size_t cnt;
1254 };
1255
1256 /*
1257 * Callback for enumerating word properties
1258 */
1259 void CVmObjGramProd::enum_props_cb(VMG_ void *ctx0, vm_prop_id_t prop,
1260 const vm_val_t * /*match_val*/)
1261 {
1262 enum_props_ctx *ctx = (enum_props_ctx *)ctx0;
1263 vmgram_match_info *ep;
1264 size_t i;
1265
1266 /* if this property is already in our list, don't add it again */
1267 for (i = 0, ep = ctx->ext->prop_enum_arr_ ; i < ctx->cnt ; ++i, ++ep)
1268 {
1269 /* if we already have this one, we can ignore it */
1270 if (ep->prop == prop)
1271 return;
1272 }
1273
1274 /* we need to add it - if the array is full, expand it */
1275 if (ctx->cnt == ctx->ext->prop_enum_max_)
1276 {
1277 /* reallocate the array with more space */
1278 ctx->ext->prop_enum_max_ += 64;
1279 ctx->ext->prop_enum_arr_ = (vmgram_match_info *)
1280 t3realloc(ctx->ext->prop_enum_arr_,
1281 ctx->ext->prop_enum_max_
1282 * sizeof(vmgram_match_info));
1283 }
1284
1285 /* add the property to the array */
1286 ep = &ctx->ext->prop_enum_arr_[ctx->cnt];
1287 ep->prop = prop;
1288
1289 /* count the new entry */
1290 ctx->cnt++;
1291 }
1292
1293 /* ------------------------------------------------------------------------ */
1294 /*
1295 * Execute the parseTokens method
1296 */
1297 int CVmObjGramProd::getp_parse(VMG_ vm_obj_id_t self,
1298 vm_val_t *retval, uint *argc)
1299 {
1300 vm_val_t *tokval;
1301 vm_val_t dictval;
1302 CVmObjDict *dict;
1303 int tok_cnt;
1304 int i;
1305 vmgramprod_tok *tok;
1306 int orig_argc = (argc != 0 ? *argc : 0);
1307 CVmGramProdQueue queues;
1308 CVmObjList *lst;
1309 int succ_cnt;
1310 CVmGramProdMatchEntry *match;
1311 static CVmNativeCodeDesc desc(2);
1312
1313 /* check arguments */
1314 if (get_prop_check_argc(retval, argc, &desc))
1315 return TRUE;
1316
1317 /* reset our memory pool */
1318 get_ext()->mem_->reset();
1319
1320 /* clear the work queues */
1321 queues.clear();
1322
1323 /*
1324 * get the tokenList argument and make sure it's a list; leave it on
1325 * the stack for now so it remains reachable for the garbage
1326 * collector
1327 */
1328 tokval = G_stk->get(0);
1329 if (!tokval->is_listlike(vmg0_)
1330 || (tok_cnt = tokval->ll_length(vmg0_)) < 0)
1331 err_throw(VMERR_LIST_VAL_REQD);
1332
1333 /* check for a dictionary argument */
1334 if (orig_argc >= 2)
1335 {
1336 /* get the dictionary argument */
1337 dictval = *G_stk->get(1);
1338
1339 /* make sure it's an object or nil */
1340 if (dictval.typ != VM_OBJ && dictval.typ != VM_NIL)
1341 err_throw(VMERR_OBJ_VAL_REQD);
1342 }
1343 else
1344 {
1345 /* use a nil dictionary by default */
1346 dictval.set_nil();
1347 }
1348
1349 /* get the dictionary object and check that it's really a dictionary */
1350 if (dictval.typ != VM_NIL)
1351 {
1352 /* if it's not a CVmObjDict object, it's the wrong type */
1353 if (!CVmObjDict::is_dictionary_obj(vmg_ dictval.val.obj))
1354 {
1355 /* wrong type - throw an error */
1356 err_throw(VMERR_INVAL_OBJ_TYPE);
1357 }
1358
1359 /* get the VM object pointer */
1360 dict = (CVmObjDict *)vm_objp(vmg_ dictval.val.obj);
1361 }
1362 else
1363 {
1364 /* there's no dictionary object */
1365 dict = 0;
1366 }
1367
1368 /*
1369 * For quick and easy access, make our own private copy of the token
1370 * and type lists. First, allocate an array of token structures.
1371 */
1372 tok = (vmgramprod_tok *)get_ext()->mem_
1373 ->alloc(tok_cnt * sizeof(vmgramprod_tok));
1374
1375 /* copy the token string references and types into our list */
1376 for (i = 0 ; i < tok_cnt ; ++i)
1377 {
1378 vm_val_t ele_val;
1379 vm_val_t tok_typ_val;
1380 vm_val_t tok_str_val;
1381 int subcnt;
1382 const char *tokstrp;
1383
1384 /* presume we won't have any vocabulary properties for the word */
1385 tok[i].match_cnt_ = 0;
1386 tok[i].matches_ = 0;
1387
1388 /* get this element from the list, and treat it as a list */
1389 tokval->ll_index(vmg_ &ele_val, i + 1);
1390
1391 /* make sure the sub-val is a list */
1392 if (!ele_val.is_listlike(vmg0_)
1393 || (subcnt = ele_val.ll_length(vmg0_)) < 0)
1394 err_throw(VMERR_BAD_TYPE_BIF);
1395
1396 /*
1397 * parse the token sublist: the first element is the token value,
1398 * and the second element is the token type
1399 */
1400 ele_val.ll_index(vmg_ &tok_str_val, 1);
1401 ele_val.ll_index(vmg_ &tok_typ_val, 2);
1402
1403 /* use the value if it's an enumerator; if not, use zero */
1404 if (tok_typ_val.typ == VM_ENUM)
1405 tok[i].typ_ = tok_typ_val.val.enumval;
1406 else
1407 tok[i].typ_ = 0;
1408
1409 /* get the token value as a string */
1410 tokstrp = tok_str_val.get_as_string(vmg0_);
1411
1412 /* if it's a string, copy it; otherwise, ignore the value */
1413 if (tokstrp != 0)
1414 {
1415 /* remember the string value */
1416 tok[i].val_ = tok_str_val;
1417
1418 /* point the token to the string */
1419 tok[i].txt_ = tokstrp + VMB_LEN;
1420 tok[i].len_ = vmb_get_len(tokstrp);
1421
1422 /* calculate and store the token's hash value */
1423 tok[i].hash_ = calc_str_hash(
1424 vmg_ dict, &tok_str_val,
1425 tokstrp + VMB_LEN, vmb_get_len(tokstrp));
1426
1427 /*
1428 * if we have a dictionary, enumerate the properties
1429 * associated with the word
1430 */
1431 if (dict != 0)
1432 {
1433 enum_props_ctx ctx;
1434
1435 /* set up our callback context */
1436 ctx.ext = get_ext();
1437 ctx.cnt = 0;
1438
1439 /* enumerate the properties */
1440 dict->enum_word_props(vmg_ &enum_props_cb, &ctx,
1441 &tok_str_val, tok[i].txt_, tok[i].len_);
1442
1443 /*
1444 * if we found any properties for the word, make a copy
1445 * for the token list
1446 */
1447 if (ctx.cnt != 0)
1448 {
1449 /* allocate space for the list */
1450 tok[i].match_cnt_ = ctx.cnt;
1451 tok[i].matches_ =
1452 (vmgram_match_info *)get_ext()->mem_
1453 ->alloc(ctx.cnt * sizeof(vmgram_match_info));
1454
1455 /* copy the list */
1456 memcpy(tok[i].matches_, get_ext()->prop_enum_arr_,
1457 ctx.cnt * sizeof(tok[i].matches_[0]));
1458 }
1459 }
1460 }
1461 else
1462 {
1463 /* it's not a string - use a null string value for this token */
1464 tok[i].txt_ = 0;
1465 tok[i].len_ = 0;
1466 }
1467 }
1468
1469 /* enqueue a match state item for each of our alternatives */
1470 enqueue_alts(vmg_ get_ext()->mem_, tok, tok_cnt, 0, 0,
1471 &queues, self, FALSE, 0, dict);
1472
1473 /* process the work queue */
1474 process_work_queue(vmg_ get_ext()->mem_, tok, tok_cnt,
1475 &queues, dict);
1476
1477 /* count the entries in the success list */
1478 for (succ_cnt = 0, match = queues.success_list_ ; match != 0 ;
1479 ++succ_cnt, match = match->nxt_) ;
1480
1481 /* allocate the return list */
1482 retval->set_obj(CVmObjList::create(vmg_ FALSE, succ_cnt));
1483 lst = (CVmObjList *)vm_objp(vmg_ retval->val.obj);
1484
1485 /* initially clear the elements of the return list to nil */
1486 lst->cons_clear();
1487
1488 /* push the list momentarily to protect it from garbage collection */
1489 G_stk->push(retval);
1490
1491 /* set the elements */
1492 for (succ_cnt = 0, match = queues.success_list_ ; match != 0 ;
1493 ++succ_cnt, match = match->nxt_)
1494 {
1495 vm_val_t tree_val;
1496 vm_val_t tok_match_val;
1497 size_t first_tok;
1498 size_t last_tok;
1499
1500 /*
1501 * Create a list to hold the token match list - this is a list of
1502 * the dictionary's comparator's matchValue() results for the
1503 * tokens that matched literals in the grammar rule. We need a
1504 * list with one element per token that we matched.
1505 *
1506 * We can't actually populate this list yet, but all we need for
1507 * the moment are references to it. So, create the list; we'll
1508 * fill it in as we traverse the match to build the result tree.
1509 */
1510 tok_match_val.set_obj(
1511 CVmObjList::create(vmg_ FALSE, match->tok_pos_));
1512
1513 /* push the token match value list for gc protection */
1514 G_stk->push(&tok_match_val);
1515
1516 /* clear it out */
1517 ((CVmObjList *)vm_objp(vmg_ tok_match_val.val.obj))->cons_clear();
1518
1519 /* build the object tree for this success object */
1520 build_match_tree(vmg_ match->match_, tokval, &tok_match_val,
1521 &tree_val, &first_tok, &last_tok);
1522
1523 /* discard our token match list's gc protection stack entry */
1524 G_stk->discard();
1525
1526 /*
1527 * add the match tree's root object to the main return list (note
1528 * that this protects it from garbage collection by virtue of the
1529 * main return list being protected from garbage collection)
1530 */
1531 lst->cons_set_element(succ_cnt, &tree_val);
1532 }
1533
1534 /* discard the gc protection */
1535 G_stk->discard();
1536
1537 /* discard arguments */
1538 G_stk->discard(orig_argc);
1539
1540 /* evaluation successful */
1541 return TRUE;
1542 }
1543
1544 /*
1545 * Build an object tree for a match
1546 */
1547 void CVmObjGramProd::build_match_tree(VMG_ const CVmGramProdMatch *match,
1548 const vm_val_t *toklist,
1549 const vm_val_t *tokmatchlist,
1550 vm_val_t *retval,
1551 size_t *first_tok, size_t *last_tok)
1552 {
1553 /* check to see what kind of match we have */
1554 if (match->proc_obj_ != VM_INVALID_OBJ)
1555 {
1556 vm_obj_id_t obj_id;
1557 CVmObjTads *objp;
1558 size_t i;
1559
1560 /*
1561 * Create the object to hold the current tree level. The only
1562 * constructor argument is the superclass, which is the match's
1563 * processor object.
1564 */
1565 G_stk->push()->set_obj(match->proc_obj_);
1566 obj_id = CVmObjTads::create_from_stack(vmg_ 0, 1);
1567
1568 /* get a pointer to the new object */
1569 objp = (CVmObjTads *)vm_objp(vmg_ obj_id);
1570
1571 /* push this object to protect it from gc for a moment */
1572 G_stk->push()->set_obj(obj_id);
1573
1574 /*
1575 * Initialize the caller's first/last token indices to an invalid
1576 * range, in case we have no subproductions. A production with no
1577 * tokens and no subproductions matches no tokens at all; we
1578 * indicate this by using an invalid range, with the first token
1579 * index higher than the last token index. Note that it's still
1580 * important that we accurately reflect the end of our range for a
1581 * zero-token match, since our enclosing nodes will need our
1582 * position to figure out where they go.
1583 */
1584 *first_tok = match->tok_pos_ + 1;
1585 *last_tok = match->tok_pos_;
1586
1587 /* build the sub-match entries */
1588 for (i = 0 ; i < match->sub_match_cnt_ ; ++i)
1589 {
1590 size_t first_sub_tok;
1591 size_t last_sub_tok;
1592 vm_val_t val;
1593
1594 /* build this subtree */
1595 build_match_tree(vmg_ match->sub_match_list_[i],
1596 toklist, tokmatchlist,
1597 &val, &first_sub_tok, &last_sub_tok);
1598
1599 /*
1600 * If this is the first subtree, use it as the tentative
1601 * limits for our overall match so far; otherwise, expand our
1602 * limits if they are outside our range so far.
1603 *
1604 * If the submatch doesn't include any tokens, it obviously
1605 * has no effect on our range. The submatch range will
1606 * indicate that the first token index is greater than the
1607 * last token index if the submatch includes no tokens.
1608 */
1609 if (i == 0)
1610 {
1611 /* it's the first subtree - it's all we know as yet */
1612 *first_tok = first_sub_tok;
1613 *last_tok = last_sub_tok;
1614 }
1615 else if (first_sub_tok <= last_sub_tok)
1616 {
1617 /* check to see if it expands our current range */
1618 if (first_sub_tok < *first_tok)
1619 *first_tok = first_sub_tok;
1620 if (last_sub_tok > *last_tok)
1621 *last_tok = last_sub_tok;
1622 }
1623
1624 /*
1625 * save the subtree with the current match object if there's a
1626 * property in which to save it
1627 */
1628 if (match->sub_match_list_[i]->target_prop_ != VM_INVALID_PROP)
1629 {
1630 /*
1631 * Set the processor object property for the value. Note
1632 * that we don't have to keep undo for this change, since
1633 * we just created the tree object ourselves, and we don't
1634 * create any undo savepoints - an object created after
1635 * the most recent undo savepoint doesn't need to keep
1636 * undo information, since the entire object will be
1637 * deleted if we undo to the savepoint.
1638 */
1639 objp->set_prop(vmg_ 0, obj_id,
1640 match->sub_match_list_[i]->target_prop_,
1641 &val);
1642 }
1643 }
1644
1645 /*
1646 * if we have exported properties for recording the token index
1647 * range, save them with the object
1648 */
1649 if (G_predef->gramprod_first_tok != VM_INVALID_PROP
1650 && G_predef->gramprod_last_tok != VM_INVALID_PROP)
1651 {
1652 vm_val_t val;
1653
1654 /* save the first token index */
1655 val.set_int((int)*first_tok + 1);
1656 objp->set_prop(vmg_ 0, obj_id,
1657 G_predef->gramprod_first_tok, &val);
1658
1659 /* save the last token index */
1660 val.set_int((int)*last_tok + 1);
1661 objp->set_prop(vmg_ 0, obj_id,
1662 G_predef->gramprod_last_tok, &val);
1663 }
1664
1665 /*
1666 * if we have the token list property exported, set it to the
1667 * original token list reference
1668 */
1669 if (G_predef->gramprod_token_list != VM_INVALID_PROP)
1670 {
1671 /* save the token list reference */
1672 objp->set_prop(vmg_ 0, obj_id,
1673 G_predef->gramprod_token_list, toklist);
1674 }
1675
1676 /* if we have the token match list property exported, set it */
1677 if (G_predef->gramprod_token_match_list != VM_INVALID_PROP)
1678 {
1679 /* save the token match list reference */
1680 objp->set_prop(vmg_ 0, obj_id,
1681 G_predef->gramprod_token_match_list, tokmatchlist);
1682 }
1683
1684 /* discard our gc protection */
1685 G_stk->discard();
1686
1687 /* the return value is the object */
1688 retval->set_obj(obj_id);
1689 }
1690 else
1691 {
1692 /* get the token list */
1693 int lstcnt = toklist->ll_length(vmg0_);
1694
1695 /* make sure the index is in range */
1696 if ((int)match->tok_pos_ < lstcnt)
1697 {
1698 vm_val_t ele_val;
1699 CVmObjList *match_lst;
1700
1701 /* get the token from the list */
1702 toklist->ll_index(vmg_ &ele_val, match->tok_pos_ + 1);
1703
1704 /*
1705 * the token is itself a list, whose first element is the
1706 * token's value - retrieve the value
1707 */
1708 ele_val.ll_index(vmg_ retval, 1);
1709
1710 /*
1711 * Store the token match result in the result list. If this is
1712 * a '*' match, it doesn't have a result list contribution,
1713 * because '*' doesn't actually match any tokens (it merely
1714 * stops parsing).
1715 */
1716 if (!match->matched_star_)
1717 {
1718 /* get the match list */
1719 match_lst = (CVmObjList *)vm_objp(vmg_ tokmatchlist->val.obj);
1720
1721 /*
1722 * set the element at this token position in the match list
1723 * to the token match result
1724 */
1725 match_lst->cons_set_element(
1726 match->tok_pos_, &match->tok_match_result_);
1727 }
1728 }
1729 else
1730 {
1731 /*
1732 * the index is past the end of the list - this must be a
1733 * '*' token that matched nothing (i.e., the token list was
1734 * fully consumed before we reached the '*'), so just return
1735 * nil for the match value
1736 */
1737 retval->set_nil();
1738 }
1739
1740 /*
1741 * We match one token, so it's the first and last index. Note
1742 * that if this is a '*' match, we don't match any tokens.
1743 */
1744 if (!match->matched_star_)
1745 *first_tok = *last_tok = match->tok_pos_;
1746 }
1747 }
1748
1749 /*
1750 * Process the work queue
1751 */
1752 void CVmObjGramProd::process_work_queue(VMG_ CVmGramProdMem *mem,
1753 const vmgramprod_tok *tok,
1754 size_t tok_cnt,
1755 CVmGramProdQueue *queues,
1756 CVmObjDict *dict)
1757 {
1758 /* keep going until the work queue and badness queue are empty */
1759 for (;;)
1760 {
1761 /*
1762 * If the work queue is empty, fall back on the badness queue.
1763 * Ignore the badness queue if we have any successful matches,
1764 * since non-badness matches always take precedence over badness
1765 * items.
1766 */
1767 if (queues->work_queue_ == 0 && queues->success_list_ == 0)
1768 {
1769 int first;
1770 int min_badness;
1771 CVmGramProdState *cur;
1772 CVmGramProdState *prv;
1773 CVmGramProdState *nxt;
1774
1775 /* find the lowest badness rating in the queue */
1776 for (first = TRUE, min_badness = 0, cur = queues->badness_queue_ ;
1777 cur != 0 ; cur = cur->nxt_, first = FALSE)
1778 {
1779 /*
1780 * if we're on the first item, note its badness as the
1781 * tentative minimum; otherwise, note the current item's
1782 * badness if it's lower than the lowest we've seen so
1783 * far
1784 */
1785 if (first || cur->altp_->badness < min_badness)
1786 min_badness = cur->altp_->badness;
1787 }
1788
1789 /*
1790 * move each of the items whose badness matches the minimum
1791 * badness out of the badness queue and into the work queue
1792 */
1793 for (cur = queues->badness_queue_, prv = 0 ; cur != 0 ;
1794 cur = nxt)
1795 {
1796 /* remember the next item, in case we remove this one */
1797 nxt = cur->nxt_;
1798
1799 /* if this item has minimum badness, move it */
1800 if (cur->altp_->badness == min_badness)
1801 {
1802 /* unlink it from the badness queue */
1803 if (prv == 0)
1804 queues->badness_queue_ = cur->nxt_;
1805 else
1806 prv->nxt_ = cur->nxt_;
1807
1808 /* link it into the work queue */
1809 cur->nxt_ = queues->work_queue_;
1810 queues->work_queue_ = cur;
1811 }
1812 else
1813 {
1814 /*
1815 * this item is staying in the list - note it as the
1816 * item preceding the next item
1817 */
1818 prv = cur;
1819 }
1820 }
1821 }
1822
1823 /* if the work queue is still empty, we're out of work to do */
1824 if (queues->work_queue_ == 0)
1825 break;
1826
1827 /* process the head of the work queue */
1828 process_work_queue_head(vmg_ mem, tok, tok_cnt, queues, dict);
1829 }
1830 }
1831
1832 /*
1833 * Process a work queue entry
1834 */
1835 void CVmObjGramProd::process_work_queue_head(VMG_ CVmGramProdMem *mem,
1836 const vmgramprod_tok *tok,
1837 size_t tok_cnt,
1838 CVmGramProdQueue *queues,
1839 CVmObjDict *dict)
1840 {
1841 CVmGramProdState *state;
1842 CVmGramProdMatch *match;
1843 const vmgram_tok_info *tokp;
1844 int tok_matched_star;
1845 vm_prop_id_t enclosing_target_prop;
1846
1847 /* get the first entry from the queue */
1848 state = queues->work_queue_;
1849
1850 /* unlink this entry from the queue */
1851 queues->work_queue_ = state->nxt_;
1852 state->nxt_ = 0;
1853
1854 /* get the token pointer for the next active entry in the alternative */
1855 tokp = state->altp_->toks + state->alt_pos_;
1856
1857 /* presume we won't match a '*' token */
1858 tok_matched_star = FALSE;
1859
1860 /* process the remaining items in the entry */
1861 while (state->alt_pos_ < state->altp_->tok_cnt)
1862 {
1863 int match;
1864 vm_val_t match_result;
1865
1866 /* presume we won't find a match */
1867 match_result.set_nil();
1868
1869 /* see what we have for this token */
1870 switch(tokp->typ)
1871 {
1872 case VMGRAM_MATCH_PROD:
1873 {
1874 vm_obj_id_t sub_obj_id;
1875 CVmObjGramProd *sub_objp;
1876
1877 /*
1878 * This is a sub-production node. Get the
1879 * sub-production object.
1880 */
1881 sub_obj_id = tokp->typinfo.prod_obj;
1882
1883 /* make sure it's of the correct metaclass */
1884 if (!CVmObjGramProd::is_gramprod_obj(vmg_ sub_obj_id))
1885 {
1886 /* wrong type - throw an error */
1887 err_throw(VMERR_INVAL_OBJ_TYPE);
1888 }
1889
1890 /* get the sub-production object */
1891 sub_objp = (CVmObjGramProd *)vm_objp(vmg_ sub_obj_id);
1892
1893 /*
1894 * set my subproduction target property, so that the
1895 * sub-production can set the target property correctly
1896 */
1897 state->sub_target_prop_ = tokp->prop;
1898
1899 /* enqueue the alternatives for the sub-production */
1900 sub_objp->enqueue_alts(vmg_ mem, tok, tok_cnt,
1901 state->tok_pos_, state, queues,
1902 sub_obj_id, FALSE, 0, dict);
1903 }
1904
1905 /*
1906 * Do not process the current state any further for now -
1907 * we'll get back to it when (and if) we finish processing
1908 * the sub-production. Note that we don't even put the
1909 * current state back in the queue - it's stacked behind the
1910 * sub-production, and will be re-enqueued when we
1911 * successfully finish with the sub-production.
1912 */
1913 return;
1914
1915 case VMGRAM_MATCH_SPEECH:
1916 /* part of speech - check to see if the current token matches */
1917 match = (state->tok_pos_ < tok_cnt
1918 && find_prop_in_tok(&tok[state->tok_pos_],
1919 tokp->typinfo.speech_prop));
1920 break;
1921
1922 case VMGRAM_MATCH_NSPEECH:
1923 /*
1924 * multiple parts of speech - check to see if the current token
1925 * matches any of the parts of the speech
1926 */
1927 if (state->tok_pos_ < tok_cnt)
1928 {
1929 size_t rem;
1930 const vm_prop_id_t *prop;
1931
1932 /* presume we won't find a match */
1933 match = FALSE;
1934
1935 /* check each item in the list */
1936 for (prop = tokp->typinfo.nspeech.props,
1937 rem = tokp->typinfo.nspeech.cnt ;
1938 rem != 0 ; --rem, ++prop)
1939 {
1940 /* if this one matches, we have a match */
1941 if (find_prop_in_tok(&tok[state->tok_pos_], *prop))
1942 {
1943 /* note the match */
1944 match = TRUE;
1945
1946 /* no need to look any further at this token */
1947 break;
1948 }
1949 }
1950 }
1951 else
1952 {
1953 /*
1954 * we're out of tokens, so we definitely don't have a
1955 * match, since we must match at least one of the possible
1956 * parts of speech of this item
1957 */
1958 match = FALSE;
1959 }
1960 break;
1961
1962 case VMGRAM_MATCH_LITERAL:
1963 /*
1964 * Literal - check for a match to the string. Test the hash
1965 * values first, as this is much faster than comparing the
1966 * strings, and at least tells us if the strings fail to match
1967 * (and failing to match being by far the most common case,
1968 * this saves us doing a full comparison most of the time).
1969 */
1970 match = (state->tok_pos_ < tok_cnt
1971 && tokp->typinfo.lit.hash == tok[state->tok_pos_].hash_
1972 && tok_equals_lit(vmg_ &tok[state->tok_pos_],
1973 tokp->typinfo.lit.str,
1974 tokp->typinfo.lit.len,
1975 dict, &match_result));
1976 break;
1977
1978 case VMGRAM_MATCH_TOKTYPE:
1979 /* token type */
1980 match = (state->tok_pos_ < tok_cnt
1981 && (tok[state->tok_pos_].typ_
1982 == tokp->typinfo.toktyp_enum));
1983 break;
1984
1985 case VMGRAM_MATCH_STAR:
1986 /*
1987 * this matches anything remaining (it also matches if
1988 * there's nothing remaining)
1989 */
1990 match = TRUE;
1991
1992 /* note that we matched a star in the state */
1993 state->matched_star_ = TRUE;
1994
1995 /* note that we matched a star for this particular token */
1996 tok_matched_star = TRUE;
1997 break;
1998 }
1999
2000 /* check for a match */
2001 if (match)
2002 {
2003 /*
2004 * we matched this token - add a token match to our state's
2005 * match list for the current position
2006 */
2007 state->match_list_[state->alt_pos_] =
2008 CVmGramProdMatch::alloc(mem, state->tok_pos_, &match_result,
2009 tok_matched_star, tokp->prop,
2010 VM_INVALID_OBJ, 0, 0);
2011
2012 /* we're done with this alternative item - move on */
2013 state->alt_pos_++;
2014
2015 /*
2016 * If we matched a real token, consume the matched input
2017 * token. For a '*', we don't want to consume anything, since
2018 * a '*' merely stops parsing and doesn't actually match
2019 * anything.
2020 */
2021 if (!state->matched_star_)
2022 state->tok_pos_++;
2023
2024 /* move on to the next alternative token item */
2025 ++tokp;
2026 }
2027 else
2028 {
2029 /*
2030 * This is not a match - reject this alternative. We do not
2031 * need to process this item further, so we can stop now,
2032 * without returning this state to the work queue. Simply
2033 * abandon this work queue item.
2034 */
2035 return;
2036 }
2037 }
2038
2039 /*
2040 * If we make it here, we've reached the end of this alternative and
2041 * have matched everything in it. This means that the alternative
2042 * was successful, so we can perform a 'reduce' operation to replace
2043 * the matched tokens with this production.
2044 */
2045
2046 /* if we have an enclosing state, get its target property */
2047 enclosing_target_prop = (state->enclosing_ != 0
2048 ? state->enclosing_->sub_target_prop_
2049 : VM_INVALID_PROP);
2050
2051 /* create a match for the entire alternative (i.e., the subproduction) */
2052 match = CVmGramProdMatch::alloc(
2053 mem, state->tok_pos_, 0, FALSE, enclosing_target_prop,
2054 state->altp_->proc_obj, &state->match_list_[0],
2055 state->altp_->tok_cnt);
2056
2057 /*
2058 * If the state we just matched was marked on creation as coming
2059 * from an alternative with circular alternatives, we've just come
2060 * up with a match for each circular alternative. To avoid infinite
2061 * recursion, we never enqueue the circular alternatives; however,
2062 * now that we know we have a match for the first element of each
2063 * circular alternative, we can check each of them to see if we can
2064 * enqueue them.
2065 */
2066 if (state->circular_alt_)
2067 {
2068 vm_obj_id_t prod_obj_id;
2069 CVmObjGramProd *prod_objp;
2070
2071 /*
2072 * Get the production from which this alternative came (there
2073 * should be no need to check the metaclass, since we could only
2074 * have created the state object from a valid production in the
2075 * first place).
2076 *
2077 * First, make sure it's of the correct class. (It almost
2078 * certainly is, since the compiler should have generated this
2079 * reference automatically, so there should be no possibility of a
2080 * user error. However, if it's not a production object, we'll
2081 * probably crash by blindly casting it to one; so we'll check
2082 * here, just to be sure that the compiler didn't do something
2083 * wrong and the image file didn't become corrupted.)
2084 */
2085 if (!CVmObjGramProd::is_gramprod_obj(vmg_ state->prod_obj_))
2086 {
2087 /* wrong type - throw an error */
2088 err_throw(VMERR_INVAL_OBJ_TYPE);
2089 }
2090
2091 /* get the object, properly cast */
2092 prod_obj_id = state->prod_obj_;
2093 prod_objp = (CVmObjGramProd *)vm_objp(vmg_ prod_obj_id);
2094
2095 /*
2096 * Enqueue the matching circular alternatives from the original
2097 * production. Our match becomes the first token match in the
2098 * circular alternative (i.e., it matches the leading circular
2099 * reference element).
2100 */
2101 prod_objp->enqueue_alts(vmg_ mem, tok, tok_cnt, state->tok_pos_,
2102 state->enclosing_, queues, prod_obj_id,
2103 TRUE, match, dict);
2104 }
2105
2106 /* check for an enclosing state to pop */
2107 if (state->enclosing_ != 0)
2108 {
2109 /* add the match to the enclosing state's match list */
2110 state->enclosing_->match_list_[state->enclosing_->alt_pos_] = match;
2111 state->enclosing_->alt_pos_++;
2112
2113 /*
2114 * Move the enclosing state's token position to our token position
2115 * - since it now encompasses our match, it has consumed all of
2116 * the tokens therein. Likewise, set the '*' flag in the parent
2117 * to our own setting.
2118 */
2119 state->enclosing_->tok_pos_ = state->tok_pos_;
2120 state->enclosing_->matched_star_ = state->matched_star_;
2121
2122 /* enqueue the enclosing state so we can continue parsing it */
2123 enqueue_state(state->enclosing_, queues);
2124 }
2125 else
2126 {
2127 CVmGramProdMatchEntry *entry;
2128
2129 /*
2130 * This is a top-level state, so we've completed parsing. If
2131 * we've consumed all input, or we matched a '*' token, we were
2132 * successful. If there's more input remaining, this is not a
2133 * match.
2134 */
2135 if (state->tok_pos_ < tok_cnt && !state->matched_star_)
2136 {
2137 /*
2138 * There's more input remaining, so this isn't a match.
2139 * Reject this alternative. We do not need to process this
2140 * item further, so stop now without returning this state
2141 * object to the work queue.
2142 */
2143
2144 /* abandon this work queue item */
2145 return;
2146 }
2147
2148 /* create a new entry for the match list */
2149 entry = (CVmGramProdMatchEntry *)mem->alloc(sizeof(*entry));
2150 entry->match_ = match;
2151 entry->tok_pos_ = state->tok_pos_;
2152
2153 /* link the entry into the list */
2154 entry->nxt_ = queues->success_list_;
2155 queues->success_list_ = entry;
2156 }
2157 }
2158
2159 /*
2160 * Visit my alternatives and enqueue each one that is a possible match
2161 * for a given token list.
2162 */
2163 void CVmObjGramProd::enqueue_alts(VMG_ CVmGramProdMem *mem,
2164 const vmgramprod_tok *tok,
2165 size_t tok_cnt, size_t start_tok_pos,
2166 CVmGramProdState *enclosing_state,
2167 CVmGramProdQueue *queues, vm_obj_id_t self,
2168 int circ_only,
2169 CVmGramProdMatch *circ_match,
2170 CVmObjDict *dict)
2171 {
2172 vmgram_alt_info *const *altp;
2173 size_t i;
2174 int need_to_clone;
2175 int has_circ;
2176 vm_obj_id_t comparator;
2177
2178 /*
2179 * We don't need to clone the enclosing state until we've set up one
2180 * new state referring back to it. However, if we're doing circular
2181 * alternatives, the enclosing state could also be enqueued
2182 * separately as its own state, so do clone all required copies in
2183 * this case.
2184 */
2185 need_to_clone = circ_only;
2186
2187 /* note whether or not we have any circular alternatives */
2188 has_circ = get_ext()->has_circular_alt;
2189
2190 /*
2191 * Cache hash values for all of our literals. We need to do this if we
2192 * haven't done it before, or if the comparator associated with the
2193 * dictionary is different than it was last time we cached the values.
2194 */
2195 comparator = (dict != 0 ? dict->get_comparator() : VM_INVALID_OBJ);
2196 if (!get_ext()->hashes_cached_ || get_ext()->comparator_ != comparator)
2197 cache_hashes(vmg_ dict);
2198
2199 /*
2200 * run through our alternatives and enqueue each one that looks
2201 * plausible
2202 */
2203 for (altp = get_ext()->alts_, i = get_ext()->alt_cnt_ ; i != 0 ;
2204 --i, ++altp)
2205 {
2206 /* start at the first token remaining in the string */
2207 size_t tok_idx = start_tok_pos;
2208
2209 /* get the first token for this alternative */
2210 vmgram_tok_info *first_tokp = (*altp)->toks;
2211
2212 /* start at the first token */
2213 vmgram_tok_info *tokp = first_tokp;
2214
2215 /* get the number of tokens in the alternative */
2216 size_t alt_tok_cnt = (*altp)->tok_cnt;
2217
2218 /* presume we will find no mismatches in this check */
2219 int found_mismatch = FALSE;
2220
2221 /*
2222 * note whether this alternative is a direct circular reference
2223 * or not (it is directly circular if the first token points
2224 * back to this same production)
2225 */
2226 int is_circ = (alt_tok_cnt != 0
2227 && tokp->typ == VMGRAM_MATCH_PROD
2228 && tokp->typinfo.prod_obj == self);
2229
2230 /*
2231 * we don't have a production before the current item (this is
2232 * important because it determines whether we must consider the
2233 * current token or any following token when trying to match a
2234 * literal, part of speech, or token type)
2235 */
2236 int prod_before = FALSE;
2237
2238 /* scan the tokens in the alternative */
2239 for (size_t cur_alt_tok = 0 ; cur_alt_tok < alt_tok_cnt ;
2240 ++cur_alt_tok, ++tokp)
2241 {
2242 int match;
2243 int match_star;
2244 int ignore_item;
2245 vm_val_t match_result;
2246
2247 /* presume we won't find a match */
2248 match = FALSE;
2249 match_star = FALSE;
2250
2251 /* presume we won't be able to ignore the item */
2252 ignore_item = FALSE;
2253
2254 /*
2255 * Try to find a match to the current alternative item. If
2256 * we've already found a mismatch, don't bother, since we need
2257 * no further evidence to skip this alternative; in this case
2258 * we're still looping over the alternative items simply to
2259 * find the beginning of the next alternative.
2260 */
2261 for ( ; !found_mismatch ; ++tok_idx)
2262 {
2263 /* see what kind of item we have */
2264 switch(tokp->typ)
2265 {
2266 case VMGRAM_MATCH_PROD:
2267 /*
2268 * We can't rule out a production without checking
2269 * it fully, which we're not doing on this pass;
2270 * however, note that we found a production, because
2271 * it means that we must from now on try skipping
2272 * any number of tokens before ruling out a match on
2273 * other grounds, since the production could
2274 * potentially match any number of tokens.
2275 *
2276 * If we're doing circular matches only, and this is
2277 * a circular production, and we're on the first
2278 * token in our list, we already know it matches, so
2279 * don't even count it as a production before the
2280 * item.
2281 */
2282 if (is_circ && circ_only && cur_alt_tok == 0)
2283 {
2284 /*
2285 * ignore the fact that it's a production, since
2286 * we already know it matches - we don't want to
2287 * be flexible about tokens following this item
2288 * since we know the exact number that match it
2289 */
2290 }
2291 else
2292 {
2293 /* note the production item */
2294 prod_before = TRUE;
2295 }
2296
2297 /*
2298 * we can ignore this item for the purposes of
2299 * detecting a mismatch, because we can't tell
2300 * during this superficial scan whether it matches
2301 */
2302 ignore_item = TRUE;
2303 break;
2304
2305 case VMGRAM_MATCH_SPEECH:
2306 /* we must match a part of speech */
2307 if (tok_idx < tok_cnt
2308 && find_prop_in_tok(&tok[tok_idx],
2309 tokp->typinfo.speech_prop))
2310 {
2311 /* it's a match */
2312 match = TRUE;
2313 }
2314 break;
2315
2316 case VMGRAM_MATCH_NSPEECH:
2317 /* multiple parts of speech */
2318 if (tok_idx < tok_cnt)
2319 {
2320 vm_prop_id_t *prop;
2321 size_t rem;
2322
2323 /* presume we won't find a match */
2324 match = FALSE;
2325
2326 /* check each item in the list */
2327 for (prop = tokp->typinfo.nspeech.props,
2328 rem = tokp->typinfo.nspeech.cnt ; rem != 0 ;
2329 --rem, ++prop)
2330 {
2331 /* if this one matches, we have a match */
2332 if (find_prop_in_tok(&tok[tok_idx], *prop))
2333 {
2334 /* note the match */
2335 match = TRUE;
2336
2337 /* no need to look any further */
2338 break;
2339 }
2340 }
2341 }
2342 else
2343 {
2344 /* we're out of tokens, so we have no match */
2345 match = FALSE;
2346 }
2347 break;
2348
2349 case VMGRAM_MATCH_LITERAL:
2350 /*
2351 * Match a literal. Compare the hash values first,
2352 * since a negative match on the hash values will tell
2353 * us for sure that the text won't match; since not
2354 * matching is by far the most common case, this saves
2355 * us the work of doing full string comparisons most of
2356 * the time.
2357 */
2358 if (tok_idx < tok_cnt
2359 && tok[tok_idx].txt_ != 0
2360 && tokp->typinfo.lit.hash == tok[tok_idx].hash_
2361 && tok_equals_lit(vmg_ &tok[tok_idx],
2362 tokp->typinfo.lit.str,
2363 tokp->typinfo.lit.len,
2364 dict, &match_result))
2365 {
2366 /* it's a match */
2367 match = TRUE;
2368 }
2369 break;
2370
2371 case VMGRAM_MATCH_TOKTYPE:
2372 /* we must match a token type */
2373 if (tok_idx < tok_cnt
2374 && tok[tok_idx].typ_ == tokp->typinfo.toktyp_enum)
2375 match = TRUE;
2376 break;
2377
2378 case VMGRAM_MATCH_STAR:
2379 /* consume everything remaining on the line */
2380 tok_idx = tok_cnt;
2381
2382 /* this is a match */
2383 match = TRUE;
2384 match_star = TRUE;
2385 break;
2386 }
2387
2388 /* if we found a match, we can stop scanning now */
2389 if (match)
2390 break;
2391
2392 /*
2393 * we didn't match this token - if we have a production
2394 * before this point, we must keep scanning token, since
2395 * the production could end up matching any number of
2396 * tokens; if we don't have a production item, though,
2397 * we don't need to look any further, and we can rule
2398 * out this alternative immediately
2399 */
2400 if (!prod_before)
2401 break;
2402
2403 /*
2404 * if we're ignoring this item (because we can't decide
2405 * now whether it's a match or not, and hence can't rule
2406 * it out), don't scan any tokens for the item
2407 */
2408 if (ignore_item)
2409 break;
2410
2411 /*
2412 * if we didn't find a match, and we're out of tokens,
2413 * stop looking - we have no more tokens to look at to
2414 * find a match
2415 */
2416 if (!match && tok_idx >= tok_cnt)
2417 break;
2418 }
2419
2420 /* check to see if we found a match */
2421 if (match)
2422 {
2423 /*
2424 * we found a match - skip the current token (unless we
2425 * matched a '*' item, in which case we've already
2426 * consumed all remaining tokens)
2427 */
2428 if (!match_star && tok_idx < tok_cnt)
2429 ++tok_idx;
2430 }
2431 else if (!ignore_item)
2432 {
2433 /*
2434 * we didn't match, and we can't ignore this item - note
2435 * that the alternative does not match
2436 */
2437 found_mismatch = TRUE;
2438
2439 /* finish up with this alternative and proceed to the next */
2440 break;
2441 }
2442 }
2443
2444 /*
2445 * If we didn't find a reason to rule out this alternative,
2446 * enqueue the alternative. Never enqueue circular references,
2447 * unless we're ONLY enqueuing circular references.
2448 */
2449 if (!found_mismatch
2450 && ((!circ_only && !is_circ)
2451 || (circ_only && is_circ)))
2452 {
2453 CVmGramProdState *state;
2454
2455 /* create and enqueue the new state */
2456 state = enqueue_new_state(mem, start_tok_pos, enclosing_state,
2457 *altp, self, &need_to_clone, queues,
2458 has_circ);
2459
2460 /*
2461 * if we are enqueuing circular references, we already have
2462 * a match for the first (circular) token, so fill it in
2463 */
2464 if (circ_only)
2465 {
2466 CVmGramProdMatch *match;
2467
2468 /* create a match for the alternative */
2469 match = CVmGramProdMatch::
2470 alloc(mem, 0, 0, FALSE, first_tokp->prop,
2471 circ_match->proc_obj_,
2472 circ_match->sub_match_list_,
2473 circ_match->sub_match_cnt_);
2474
2475 /* set the first match in the token */
2476 state->match_list_[0] = match;
2477
2478 /* set up at the second token */
2479 state->alt_pos_ = 1;
2480 }
2481 }
2482 }
2483 }
2484
2485 /*
2486 * Cache hash values for all of our literal tokens
2487 */
2488 void CVmObjGramProd::cache_hashes(VMG_ CVmObjDict *dict)
2489 {
2490 vm_obj_id_t comparator;
2491 vmgram_alt_info **alt;
2492 size_t i;
2493
2494 /* get the comparator */
2495 comparator = (dict != 0 ? dict->get_comparator() : VM_INVALID_OBJ);
2496
2497 /* run through our alternatives */
2498 for (i = get_ext()->alt_cnt_, alt = get_ext()->alts_ ;
2499 i != 0 ; --i, ++alt)
2500 {
2501 vmgram_tok_info *tok;
2502 size_t j;
2503
2504 /* run through our tokens */
2505 for (j = (*alt)->tok_cnt, tok = (*alt)->toks ; j != 0 ; --j, ++tok)
2506 {
2507 /* if this is a literal token, calculate its hash value */
2508 if (tok->typ == VMGRAM_MATCH_LITERAL)
2509 {
2510 /* calculate and store our hash value */
2511 tok->typinfo.lit.hash = calc_str_hash(
2512 vmg_ dict, 0, tok->typinfo.lit.str, tok->typinfo.lit.len);
2513 }
2514 }
2515 }
2516
2517 /* note that we've cached hash values, and note the comparator we used */
2518 get_ext()->hashes_cached_ = TRUE;
2519 get_ext()->comparator_ = comparator;
2520 }
2521
2522 /*
2523 * Create and enqueue a new state
2524 */
2525 CVmGramProdState *CVmObjGramProd::
2526 enqueue_new_state(CVmGramProdMem *mem,
2527 size_t start_tok_pos,
2528 CVmGramProdState *enclosing_state,
2529 const vmgram_alt_info *altp, vm_obj_id_t self,
2530 int *need_to_clone, CVmGramProdQueue *queues,
2531 int circular_alt)
2532 {
2533 CVmGramProdState *state;
2534
2535 /* create the new state */
2536 state = create_new_state(mem, start_tok_pos, enclosing_state,
2537 altp, self, need_to_clone, circular_alt);
2538
2539 /*
2540 * Add the item to the appropriate queue. If the item has an
2541 * associated badness, add it to the badness queue. Otherwise, add
2542 * it to the work queue.
2543 */
2544 if (altp->badness != 0)
2545 {
2546 /*
2547 * we have a badness rating - add it to the badness queue, since
2548 * we don't want to process it until we entirely exhaust better
2549 * possibilities
2550 */
2551 state->nxt_ = queues->badness_queue_;
2552 queues->badness_queue_ = state;
2553 }
2554 else
2555 {
2556 /* enqueue the state */
2557 enqueue_state(state, queues);
2558 }
2559
2560 /* return the new state */
2561 return state;
2562 }
2563
2564 /*
2565 * Create a new state
2566 */
2567 CVmGramProdState *CVmObjGramProd::
2568 create_new_state(CVmGramProdMem *mem, size_t start_tok_pos,
2569 CVmGramProdState *enclosing_state,
2570 const vmgram_alt_info *altp, vm_obj_id_t self,
2571 int *need_to_clone, int circular_alt)
2572 {
2573 /*
2574 * if necessary, clone the enclosing state; we need to do this if we
2575 * enqueue more than one nested alternative, since each nested
2576 * alternative could parse the rest of the token list differently
2577 * and thus provide a different result to the enclosing state
2578 */
2579 if (*need_to_clone && enclosing_state != 0)
2580 enclosing_state = enclosing_state->clone(mem);
2581
2582 /*
2583 * we will need to clone the enclosing state if we create another
2584 * alternative after this one
2585 */
2586 *need_to_clone = TRUE;
2587
2588 /* create a new state object for the alternative */
2589 return CVmGramProdState::alloc(mem, start_tok_pos, 0,
2590 enclosing_state, altp, self,
2591 circular_alt);
2592 }
2593
2594 /*
2595 * Enqueue a state in the work queue
2596 */
2597 void CVmObjGramProd::enqueue_state(CVmGramProdState *state,
2598 CVmGramProdQueue *queues)
2599 {
2600 /* add it to the work queue */
2601 state->nxt_ = queues->work_queue_;
2602 queues->work_queue_ = state;
2603 }
2604
2605 /*
2606 * Determine if a token from the input matches a literal token, allowing
2607 * the input token to be a truncated version of the literal token if the
2608 * given truncation length is non-zero.
2609 */
2610 int CVmObjGramProd::tok_equals_lit(VMG_ const struct vmgramprod_tok *tok,
2611 const char *lit, size_t lit_len,
2612 CVmObjDict *dict, vm_val_t *result_val)
2613 {
2614 /*
2615 * if there's a dictionary, ask it to do the comparison; otherwise,
2616 * use an exact literal match
2617 */
2618 if (dict != 0)
2619 {
2620 /* ask the dictionary for the comparison */
2621 return dict->match_strings(vmg_ &tok->val_, tok->txt_, tok->len_,
2622 lit, lit_len, result_val);
2623 }
2624 else
2625 {
2626 /* perform an exact comparison */
2627 result_val->set_int(tok->len_ == lit_len
2628 && memcmp(tok->txt_, lit, lit_len) == 0);
2629 return result_val->val.intval;
2630 }
2631 }
2632
2633 /*
2634 * Calculate the hash value for a literal token, using our dictionary's
2635 * comparator.
2636 */
2637 unsigned int CVmObjGramProd::calc_str_hash(VMG_ CVmObjDict *dict,
2638 const vm_val_t *strval,
2639 const char *str, size_t len)
2640 {
2641 /*
2642 * if we have a dictionary, ask it to ask it for the hash value, as the
2643 * dictionary will ask its comparator to do the work; otherwise,
2644 * calculate our own hash value
2645 */
2646 if (dict != 0)
2647 {
2648 /*
2649 * We're doing comparisons through the dictionary's comparator, so
2650 * we must calculate hash values using the comparator as well to
2651 * keep the hash and match operations consistent.
2652 */
2653 return dict->calc_str_hash(vmg_ strval, str, len);
2654 }
2655 else
2656 {
2657 uint hash;
2658
2659 /*
2660 * We don't have a dictionary, so we're doing our own string
2661 * comparisons, which we do as exact byte-for-byte matches. We can
2662 * thus calculate an arbitrary hash value of our own devising.
2663 */
2664 for (hash = 0 ; len != 0 ; ++str, --len)
2665 hash += (unsigned char)*str;
2666
2667 /* return the hash value we calculated */
2668 return hash;
2669 }
2670 }
2671
2672
2673 /*
2674 * Find a property in a token's list. Returns true if the property is
2675 * there, false if not.
2676 */
2677 int CVmObjGramProd::find_prop_in_tok(const vmgramprod_tok *tok,
2678 vm_prop_id_t prop)
2679 {
2680 size_t i;
2681 const vmgram_match_info *p;
2682
2683 /* search for the property */
2684 for (i = tok->match_cnt_, p = tok->matches_ ; i != 0 ; --i, ++p)
2685 {
2686 /* if this is the one we're looking for, return success */
2687 if (p->prop == prop)
2688 return TRUE;
2689 }
2690
2691 /* we didn't find it */
2692 return FALSE;
2693 }
2694
2695 /* ------------------------------------------------------------------------ */
2696 /*
2697 * Execute the getGrammarInfo() method - builds and returns an information
2698 * structure describing this grammar production object.
2699 */
2700 int CVmObjGramProd::getp_get_gram_info(VMG_ vm_obj_id_t self,
2701 vm_val_t *retval, uint *argc)
2702 {
2703 vm_obj_id_t alt_lst_id;
2704 CVmObjList *alt_lst;
2705 size_t i;
2706 vmgram_alt_info **altp;
2707 static CVmNativeCodeDesc desc(0);
2708
2709 /* check arguments */
2710 if (get_prop_check_argc(retval, argc, &desc))
2711 return TRUE;
2712
2713 /*
2714 * This routine uses considerable extra stack in the course of its
2715 * work, so check in advance that we have enough space to run.
2716 */
2717 if (!G_stk->check_space(8))
2718 err_throw(VMERR_STACK_OVERFLOW);
2719
2720 /* create a list to hold the rule alternatives */
2721 alt_lst_id = CVmObjList::create(vmg_ FALSE, get_ext()->alt_cnt_);
2722 alt_lst = (CVmObjList *)vm_objp(vmg_ alt_lst_id);
2723 alt_lst->cons_clear();
2724
2725 /* push it onto the stack for protection from garbage collection */
2726 G_stk->push()->set_obj(alt_lst_id);
2727
2728 /* create the rule-alternative descriptions */
2729 for (i = 0, altp = get_ext()->alts_ ; i < get_ext()->alt_cnt_ ;
2730 ++i, ++altp)
2731 {
2732 size_t j;
2733 vmgram_tok_info *tokp;
2734 vm_val_t alt_obj_val;
2735 vm_obj_id_t tok_lst_id;
2736 CVmObjList *tok_lst;
2737
2738 /*
2739 * if our imported GrammarAltInfo class isn't defined, we can't
2740 * provide rule-alternative information, so just fill in the list
2741 * with a nil
2742 */
2743 if (G_predef->gramprod_gram_alt_info == VM_INVALID_OBJ)
2744 {
2745 /* add a nil to the list */
2746 alt_obj_val.set_nil();
2747 alt_lst->cons_set_element(i, &alt_obj_val);
2748
2749 /* done with this slot */
2750 continue;
2751 }
2752
2753 /* create a list to hold the token descriptors */
2754 tok_lst_id = CVmObjList::create(vmg_ FALSE, (*altp)->tok_cnt);
2755 tok_lst = (CVmObjList *)vm_objp(vmg_ tok_lst_id);
2756 tok_lst->cons_clear();
2757
2758 /* push this momentarily for gc protection */
2759 G_stk->push()->set_obj(tok_lst_id);
2760
2761 /*
2762 * Run through the tokens in the rule alternative, and build a list
2763 * of token descriptor structures.
2764 */
2765 for (j = 0, tokp = (*altp)->toks ; j < (*altp)->tok_cnt ; ++j, ++tokp)
2766 {
2767 vm_val_t tok_obj_val;
2768
2769 /*
2770 * if our imported GrammarAltTokInfo class isn't defined, we
2771 * can't provide token information, so just fill in the list
2772 * with a nil
2773 */
2774 if (G_predef->gramprod_gram_alt_tok_info == VM_INVALID_OBJ)
2775 {
2776 /* add a nil to the list */
2777 tok_obj_val.set_nil();
2778 tok_lst->cons_set_element(j, &tok_obj_val);
2779
2780 /* done with this slot */
2781 continue;
2782 }
2783
2784 /*
2785 * The constructor arguments are the target property ID, the
2786 * token type code, and extra information that depends on the
2787 * type code. We have to push the arguments backwards per the
2788 * normal protocol, so start with the variant part.
2789 */
2790 switch (tokp->typ)
2791 {
2792 case VMGRAM_MATCH_PROD:
2793 /* the extra information is the sub-production object */
2794 G_stk->push()->set_obj(tokp->typinfo.prod_obj);
2795 break;
2796
2797 case VMGRAM_MATCH_SPEECH:
2798 /* the extra info is the part-of-speech property */
2799 G_stk->push()->set_propid(tokp->typinfo.speech_prop);
2800 break;
2801
2802 case VMGRAM_MATCH_NSPEECH:
2803 /* the extra info is a list of part-of-speech properties */
2804 {
2805 vm_obj_id_t pos_lst_id;
2806 CVmObjList *pos_lst;
2807 vm_prop_id_t *pp;
2808 size_t k;
2809
2810 /* create the property list */
2811 pos_lst_id = CVmObjList::create(
2812 vmg_ FALSE, tokp->typinfo.nspeech.cnt);
2813 pos_lst = (CVmObjList *)vm_objp(vmg_ pos_lst_id);
2814
2815 /* push it */
2816 G_stk->push()->set_obj(pos_lst_id);
2817
2818 /* populate it */
2819 for (k = 0, pp = tokp->typinfo.nspeech.props ;
2820 k < tokp->typinfo.nspeech.cnt ;
2821 ++k, ++pp)
2822 {
2823 vm_val_t val;
2824
2825 /* fill in this element */
2826 val.set_propid(*pp);
2827 pos_lst->cons_set_element(k, &val);
2828 }
2829 }
2830 break;
2831
2832 case VMGRAM_MATCH_LITERAL:
2833 /* the extra info is the literal string value */
2834 G_stk->push()->set_obj(CVmObjString::create(
2835 vmg_ FALSE, tokp->typinfo.lit.str,
2836 tokp->typinfo.lit.len));
2837 break;
2838
2839 case VMGRAM_MATCH_TOKTYPE:
2840 /* the extra information is the token class enum */
2841 G_stk->push()->set_enum(tokp->typinfo.toktyp_enum);
2842 break;
2843
2844 case VMGRAM_MATCH_STAR:
2845 /*
2846 * for a 'star' type, there is no extra information, but
2847 * push nil to keep the argument list uniform
2848 */
2849 G_stk->push()->set_nil();
2850 break;
2851
2852 default:
2853 assert(FALSE);
2854 break;
2855 }
2856
2857 /* now push the target property and type code */
2858 G_stk->push()->set_int(tokp->typ);
2859 if (tokp->prop != VM_INVALID_PROP)
2860 G_stk->push()->set_propid(tokp->prop);
2861 else
2862 G_stk->push()->set_nil();
2863
2864 /*
2865 * the first argument to the constructor is the base class,
2866 * which is the imported GrammarAltTokInfo class object
2867 */
2868 G_stk->push()->set_obj(G_predef->gramprod_gram_alt_tok_info);
2869
2870 /* create the object, at long last */
2871 tok_obj_val.set_obj(CVmObjTads::create_from_stack(vmg_ 0, 4));
2872
2873 /* add it to our token list */
2874 tok_lst->cons_set_element(j, &tok_obj_val);
2875 }
2876
2877 /*
2878 * Create the GrammarAltInfo object to desribe the alternative.
2879 * Pass in the score, badness, match object, and token list as
2880 * arguments to the constructor, which we'll count on to stash the
2881 * information away in the new object.
2882 *
2883 * Note that the first constructor argument is the superclass,
2884 * which is the imported GrammarAltInfo class object.
2885 */
2886 G_stk->push()->set_obj(tok_lst_id);
2887 G_stk->push()->set_obj((*altp)->proc_obj);
2888 G_stk->push()->set_int((*altp)->badness);
2889 G_stk->push()->set_int((*altp)->score);
2890 G_stk->push()->set_obj(G_predef->gramprod_gram_alt_info);
2891 alt_obj_val.set_obj(CVmObjTads::create_from_stack(vmg_ 0, 5));
2892
2893 /* add the new GrammarAltInfo to the main alternative list */
2894 alt_lst->cons_set_element(i, &alt_obj_val);
2895
2896 /*
2897 * It's safe to discard the gc protection for the token list now,
2898 * since a reference to is now stashed away in the GrammarAltInfo
2899 * object, which in turn is referenced from our main alternative
2900 * list, which we stashed on the stack earlier for gc protection.
2901 */
2902 G_stk->discard();
2903 }
2904
2905 /* it's safe to discard our gc protection for the main list now */
2906 G_stk->discard();
2907
2908 /* return the main list */
2909 retval->set_obj(alt_lst_id);
2910
2911 /* successful evaluation */
2912 return TRUE;
2913 }
2914
2915 /* ------------------------------------------------------------------------ */
2916 /*
2917 * deleteAlt() method - remove an alternative from our rule list
2918 */
2919 int CVmObjGramProd::getp_deleteAlt(VMG_ vm_obj_id_t self,
2920 vm_val_t *retval, uint *oargc)
2921 {
2922 const vm_val_t *v;
2923
2924 /* check arguments */
2925 uint argc = (oargc != 0 ? *oargc : 0);
2926 static CVmNativeCodeDesc desc(1, 1);
2927 if (get_prop_check_argc(retval, oargc, &desc))
2928 return TRUE;
2929
2930 /* get the ID argument */
2931 vm_val_t *id = G_stk->get(0);
2932
2933 /* get the dictionary, if present */
2934 vm_obj_id_t dict = VM_INVALID_OBJ;
2935 if (argc >= 2
2936 && (v = G_stk->get(1))->typ != VM_NIL
2937 && (v->typ != VM_OBJ
2938 || !CVmObjDict::is_dictionary_obj(vmg_ dict = v->val.obj)))
2939 err_throw(VMERR_BAD_TYPE_BIF);
2940
2941 /* push 'self' for gc protection */
2942 G_interpreter->push_obj(vmg_ self);
2943
2944 /* check the ID type */
2945 const char *idstr;
2946 if (id->typ == VM_INT)
2947 {
2948 /* get the index of the alternative to delete */
2949 int idx = id->val.intval;
2950
2951 /* make sure it's in range */
2952 if (idx < 1 || idx > (int)get_ext()->alt_cnt_)
2953 err_throw(VMERR_INDEX_OUT_OF_RANGE);
2954
2955 /* mark the item for deletion */
2956 get_ext()->alts_[idx-1]->del = TRUE;
2957 }
2958 else if ((idstr = id->get_as_string(vmg0_)) != 0)
2959 {
2960 /* get the length and buffer pointer for the tag */
2961 size_t idlen = vmb_get_len(idstr);
2962 idstr += VMB_LEN;
2963
2964 /* get the garmmarTag property import */
2965 vm_prop_id_t grammarTag = G_predef->gramprod_tag;
2966
2967 /* set up a recursive invoker for grammarTag */
2968 vm_rcdesc rc(vmg_ "GrammarProd.deleteAlt", self,
2969 PROPIDX_deleteAlt, id, argc);
2970
2971 /*
2972 * Delete by tag name. Run through the alternatives and delete
2973 * each one whose match object's grammarTag property matches the
2974 * given tag name. Work backwards through the array to avoid the
2975 * overhead of closing gaps when we delete items.
2976 */
2977 for (int idx = get_ext()->alt_cnt_ ; idx != 0 ; )
2978 {
2979 /* on to the next index */
2980 --idx;
2981
2982 /* get this item's match object */
2983 vm_obj_id_t m = get_ext()->alts_[idx]->proc_obj;
2984
2985 /*
2986 * if there's a match object, and the 'grammarTag' import is
2987 * defined, check the match object's grammarTag value
2988 */
2989 if (m != VM_INVALID_OBJ && grammarTag != VM_INVALID_PROP)
2990 {
2991 /* evaluate m.grammarProd */
2992 vm_val_t mval;
2993 mval.set_obj(m);
2994 G_interpreter->get_prop(
2995 vmg_ 0, &mval, grammarTag, &mval, 0, &rc);
2996
2997 /* if it's a string, compare it */
2998 const char *gt = G_interpreter->get_r0()->get_as_string(vmg0_);
2999 if (gt != 0
3000 && vmb_get_len(gt) == idlen
3001 && memcmp(gt + VMB_LEN, idstr, idlen) == 0)
3002 {
3003 /* it's a match - mark it for deletion */
3004 get_ext()->alts_[idx]->del = TRUE;
3005 }
3006 }
3007 }
3008 }
3009 else if (id->typ == VM_OBJ)
3010 {
3011 /*
3012 * Delete each alternative whose match object equals or is a
3013 * subclass of the given object. Work backwards from the end of
3014 * the list to avoid the overhead of closing the gap when we delete
3015 * an item earlier in the array.
3016 */
3017 for (int idx = get_ext()->alt_cnt_ ; idx != 0 ; )
3018 {
3019 /* on to the next index */
3020 --idx;
3021
3022 /* check for a match to the match object */
3023 vm_obj_id_t m = get_ext()->alts_[idx]->proc_obj;
3024 if (m != VM_INVALID_OBJ
3025 && (m == id->val.obj
3026 || vm_objp(vmg_ m)->is_instance_of(vmg_ id->val.obj)))
3027 {
3028 /* it's a match - mark it for deletion */
3029 get_ext()->alts_[idx]->del = TRUE;
3030 }
3031 }
3032 }
3033 else
3034 {
3035 /* invalid type */
3036 err_throw(VMERR_BAD_VAL_BIF);
3037 }
3038
3039 /* delete the marked batch */
3040 delete_marked_alts(vmg_ self, dict);
3041
3042 /* return self */
3043 retval->set_obj(self);
3044
3045 /* discard arguments and gc protection */
3046 G_stk->discard(argc + 1);
3047
3048 /* handled */
3049 return TRUE;
3050 }
3051
3052 /*
3053 * Delete the marked alternatives. This runs through the alternative list
3054 * and deletes each alternative marked with the 'del' flag. We save undo
3055 * for the deletions and update the dictionary (if provided) to remove
3056 * literals associated with this production that are no longer used in any
3057 * alternative after the deletions.
3058 */
3059 void CVmObjGramProd::delete_marked_alts(
3060 VMG_ vm_obj_id_t self, vm_obj_id_t dict)
3061 {
3062 /* get the alt list */
3063 vmgram_alt_info **alts = get_ext()->alts_;
3064
3065 /* if there's a dictionary, delete the words that are no longer in use */
3066 if (dict != VM_INVALID_OBJ
3067 && G_predef->misc_vocab != VM_INVALID_PROP)
3068 {
3069 /* get the dictionary object, properly cast */
3070 CVmObjDict *dictp = (CVmObjDict *)vm_objp(vmg_ dict);
3071
3072 /* run through the alternatives being deleted */
3073 for (size_t i = 0 ; i < get_ext()->alt_cnt_ ; ++i)
3074 {
3075 /* get this item */
3076 vmgram_alt_info *alt = alts[i];
3077
3078 /* if it's not being deleted, skip it */
3079 if (!alt->del)
3080 continue;
3081
3082 /* run through its token list looking for literals */
3083 vmgram_tok_info *tok = alt->toks;
3084 for (size_t j = 0 ; j < alt->tok_cnt ; ++j, ++tok)
3085 {
3086 /*
3087 * if it's a literal, and it's not defined in a surviving
3088 * alternative, delete it from the dictionary
3089 */
3090 if (tok->typ == VMGRAM_MATCH_LITERAL
3091 && !find_literal_in_alts(
3092 tok->typinfo.lit.str,tok->typinfo.lit.len))
3093 {
3094 /* it's no longer used - remove it from the dictionary */
3095 dictp->del_word(
3096 vmg_ dict, tok->typinfo.lit.str, tok->typinfo.lit.len,
3097 self, G_predef->misc_vocab);
3098 }
3099 }
3100 }
3101 }
3102
3103 /*
3104 * Perform the deletions. Work backwards from the end of the array to
3105 * avoid overhead closing gaps in the array.
3106 */
3107 for (size_t i = get_ext()->alt_cnt_ ; i > 0 ; )
3108 {
3109 /* get the next item */
3110 vmgram_alt_info *alt = alts[--i];
3111
3112 /* if it's marked for deletion, delete it */
3113 if (alt->del)
3114 {
3115 /* unmark it, in case we later restore it via undo */
3116 alt->del = FALSE;
3117
3118 /*
3119 * If this is the only remaining alternative with the same
3120 * match object that's being deleted, rebuild the match
3121 * object's grammarAltProps list. If there's another
3122 * alternative yet to be deleted that uses the same match
3123 * object, don't bother doing the rebuild now, since we'll do
3124 * it again when the loop reaches the earlier alternative, and
3125 * we only need to do it once for the whole batch.
3126 */
3127 int rebuild = TRUE;
3128 for (size_t j = 0 ; j < i ; ++j)
3129 {
3130 /*
3131 * if this one's being deleted, and it has the same match
3132 * object, skip the rebuild now since we'll do it when we
3133 * get to 'j' in the main loop
3134 */
3135 if (alts[j]->del && alts[j]->proc_obj == alt->proc_obj)
3136 {
3137 rebuild = FALSE;
3138 break;
3139 }
3140 }
3141
3142 /* do the rebuild if this is our last chance */
3143 if (rebuild)
3144 build_alt_props(vmg_ alt->proc_obj);
3145
3146 /* delete it */
3147 delete_alt_undo(vmg_ self, i);
3148 }
3149 }
3150
3151 /* check for circular references */
3152 check_circular_refs(self);
3153 }
3154
3155 /*
3156 * Scan surviving alternatives (not marked with 'del') for a given literal
3157 */
3158 int CVmObjGramProd::find_literal_in_alts(const char *str, size_t len)
3159 {
3160 /*
3161 * Scan the surviving alternatives to see if this same literal token
3162 * appears in any of them. If not, it's no longer in use in the
3163 * production, so delete it from the dictionary.
3164 */
3165 for (size_t i = 0 ; i < get_ext()->alt_cnt_ ; ++i)
3166 {
3167 /* get this item */
3168 vmgram_alt_info *alt = get_ext()->alts_[i];
3169
3170 /* if it's being deleted, skip it */
3171 if (alt->del)
3172 continue;
3173
3174 /* it's still alive - scan its tokens */
3175 vmgram_tok_info *tok = alt->toks;
3176 for (size_t j = 0 ; j < alt->tok_cnt ; ++j, ++tok)
3177 {
3178 /* if this is a matching literal, the word is still in use */
3179 if (tok->typ == VMGRAM_MATCH_LITERAL
3180 && tok->typinfo.lit.len == len
3181 && memcmp(tok->typinfo.lit.str, str, len) == 0)
3182 return TRUE;
3183 }
3184 }
3185
3186 /* didn't find it */
3187 return FALSE;
3188 }
3189
3190 /*
3191 * delete an alternative, keeping undo
3192 */
3193 void CVmObjGramProd::delete_alt_undo(VMG_ vm_obj_id_t self, int idx)
3194
3195 {
3196 /* create an undo record for deleting this item */
3197 vmgram_undo_rec *rec = new vmgram_undo_rec(
3198 VMGRAM_UNDO_DELETED, idx, get_ext()->alts_[idx]);
3199
3200 /* save the record */
3201 if (!G_undo->add_new_record_ptr_key(vmg_ self, rec))
3202 delete rec;
3203
3204 /* remove the alternative from the array */
3205 delete_alt(idx);
3206 }
3207
3208 /*
3209 * Check for circular references. After deleting one or more alternatives,
3210 * call this to see if we can clear the circular reference flag. This
3211 * scans the surviging alternatives, and clears the flag if none of them
3212 * are circular.
3213 */
3214 void CVmObjGramProd::check_circular_refs(vm_obj_id_t self)
3215 {
3216 /* presume no circular references */
3217 get_ext()->has_circular_alt = FALSE;
3218
3219 /* scan the alternative list */
3220 vmgram_alt_info **altp = get_ext()->alts_;
3221 for (size_t i = 0 ; i < get_ext()->alt_cnt_ ; ++i, ++altp)
3222 {
3223 /* get the alternative */
3224 vmgram_alt_info *alt = *altp;
3225
3226 /* check for a circular reference */
3227 if (alt->tok_cnt != 0
3228 && alt->toks->typ == VMGRAM_MATCH_PROD
3229 && alt->toks->typinfo.prod_obj == self)
3230 {
3231 /* it's circular - set the flag */
3232 get_ext()->has_circular_alt = TRUE;
3233
3234 /* no need to look any further */
3235 break;
3236 }
3237 }
3238 }
3239
3240 /*
3241 * Rebuild the grammarAltProps list for a given match object. This creates
3242 * a list of all of the properties used in "->" expressions in all of the
3243 * alternatives associated with the match object.
3244 */
3245 void CVmObjGramProd::build_alt_props(VMG_ vm_obj_id_t match_obj)
3246 {
3247 /* if there's no grammarAltProps property export, skip this */
3248 if (G_predef->gramprod_alt_props == VM_INVALID_PROP)
3249 return;
3250
3251 /* first do a scan without an output list to count the properties */
3252 size_t cnt = build_alt_props_list(vmg_ match_obj, 0);
3253
3254 /* create the list */
3255 vm_val_t lstval;
3256 lstval.set_obj(CVmObjList::create(vmg_ FALSE, cnt));
3257 CVmObjList *lst = (CVmObjList *)vm_objp(vmg_ lstval.val.obj);
3258
3259 /* build the list */
3260 build_alt_props_list(vmg_ match_obj, lst);
3261
3262 /* keep only unique properties in the list */
3263 lst->cons_uniquify(vmg0_);
3264
3265 /* store it in the match object under grammarAltProps */
3266 vm_objp(vmg_ match_obj)->set_prop(
3267 vmg_ G_undo, match_obj, G_predef->gramprod_alt_props, &lstval);
3268 }
3269
3270 /*
3271 * Build the grammarAltProps list for a given object, storing the results
3272 * in the given list. Returns the number of properties we found.
3273 */
3274 size_t CVmObjGramProd::build_alt_props_list(
3275 VMG_ vm_obj_id_t match_obj, CVmObjList *lst)
3276 {
3277 /* we haven't stored any properties yet */
3278 size_t n = 0;
3279
3280 /* run through the surviving alternatives */
3281 vmgram_alt_info **alts = get_ext()->alts_;
3282 for (size_t i = 0 ; i < get_ext()->alt_cnt_ ; ++i, ++alts)
3283 {
3284 /*
3285 * if this alternative isn't being deleted, and it's associated
3286 * with the given match object, add its properties to the list
3287 */
3288 vmgram_alt_info *alt = *alts;
3289 if (!alt->del && alt->proc_obj == match_obj)
3290 {
3291 /* scan its token list */
3292 vmgram_tok_info *tok = alt->toks;
3293 for (size_t j = 0 ; j < alt->tok_cnt ; ++j, ++tok)
3294 {
3295 /* if this token has a target property, add it to the list */
3296 if (tok->prop != VM_INVALID_PROP)
3297 {
3298 /* if we have a list, store it */
3299 if (lst != 0)
3300 {
3301 vm_val_t v;
3302 v.set_propid(tok->prop);
3303 lst->cons_set_element(n, &v);
3304 }
3305
3306 /* count it */
3307 ++n;
3308 }
3309 }
3310 }
3311 }
3312
3313 /* return the number of properties we stored */
3314 return n;
3315 }
3316
3317
3318 /* ------------------------------------------------------------------------ */
3319 /*
3320 * clearAlts() method - removes all alternatives
3321 */
3322 int CVmObjGramProd::getp_clearAlts(VMG_ vm_obj_id_t self,
3323 vm_val_t *retval, uint *oargc)
3324 {
3325 const vm_val_t *v;
3326
3327 /* check arguments */
3328 int argc = (oargc != 0 ? *oargc : 0);
3329 static CVmNativeCodeDesc desc(0, 1);
3330 if (get_prop_check_argc(retval, oargc, &desc))
3331 return TRUE;
3332
3333 /* get the dictionary object, if specified */
3334 vm_obj_id_t dict = VM_INVALID_OBJ;
3335 if (argc >= 1
3336 && (v = G_stk->get(0))->typ != VM_NIL
3337 && (v->typ != VM_OBJ
3338 || !CVmObjDict::is_dictionary_obj(vmg_ dict = v->val.obj)))
3339 err_throw(VMERR_BAD_TYPE_BIF);
3340
3341 /* mark every alternative for deletion */
3342 for (size_t i = 0 ; i < get_ext()->alt_cnt_ ; ++i)
3343 get_ext()->alts_[i]->del = TRUE;
3344
3345 /* save 'self' for gc protection */
3346 G_interpreter->push_obj(vmg_ self);
3347
3348 /* delete the batch */
3349 delete_marked_alts(vmg_ self, dict);
3350
3351 /* return self */
3352 retval->set_obj(self);
3353
3354 /* discard arguments and gc protection */
3355 G_stk->discard(argc + 1);
3356
3357 /* handled */
3358 return TRUE;
3359 }
3360
3361 /* ------------------------------------------------------------------------ */
3362 /*
3363 * addAlt() method - add a new alternative
3364 */
3365
3366 /* compiler results/callback object for grammar rule parsing */
3367 struct CVmGramCompResults: public CVmDynCompResults
3368 {
3369 CVmGramCompResults(vm_obj_id_t self, CVmObjGramProd *selfp,
3370 vm_obj_id_t dict, vm_obj_id_t match)
3371 {
3372 this->self = self;
3373 this->selfp = selfp;
3374 this->dict = dict;
3375 this->match = match;
3376 }
3377
3378 /* save the parsed grammar rule data in our object */
3379 virtual void save_grammar(
3380 VMG_ CTcGramProdAlt *alts, CTcGramPropArrows *arrows)
3381 {
3382 /* add each alternative */
3383 for ( ; alts != 0 ; alts = alts->get_next())
3384 selfp->add_alt(vmg_ self, alts, dict, match);
3385 }
3386
3387 /* self - the GrammarProd that we're adding rules to */
3388 vm_obj_id_t self;
3389 CVmObjGramProd *selfp;
3390
3391 /* the Dictionary object in scope for the grammar rules */
3392 vm_obj_id_t dict;
3393
3394 /* the match object for the alternatives */
3395 vm_obj_id_t match;
3396 };
3397
3398 /* add an alternative to the production */
3399 void CVmObjGramProd::add_alt(VMG_ vm_obj_id_t self, CTcGramProdAlt *alt,
3400 vm_obj_id_t dict, vm_obj_id_t match)
3401 {
3402 /* add it at the last position */
3403 int idx = get_ext()->alt_cnt_;
3404
3405 /* count the tokens in the rule */
3406 CTcGramProdTok *tok;
3407 int ntoks;
3408 for (ntoks = 0, tok = alt->get_tok_head() ; tok != 0 ;
3409 ++ntoks, tok = tok->get_next()) ;
3410
3411 /* create our internal alt object */
3412 vmgram_alt_info *ai = new vmgram_alt_info(ntoks);
3413
3414 /* set the attributes */
3415 ai->proc_obj = match;
3416 ai->score = alt->get_score();
3417 ai->badness = alt->get_badness();
3418
3419 /* translate from the parsed token list to our internal token list */
3420 vmgram_tok_info *ti = ai->toks;
3421 for (tok = alt->get_tok_head() ; tok != 0 ; ++ti, tok = tok->get_next())
3422 {
3423 /* set the property association */
3424 ti->prop = tok->get_prop_assoc();
3425
3426 /* set the type and type-specific data */
3427 switch (tok->get_type())
3428 {
3429 case TCGRAM_UNKNOWN:
3430 ti->typ = VMGRAM_MATCH_UNDEF;
3431 break;
3432
3433 case TCGRAM_PROD:
3434 ti->typ = VMGRAM_MATCH_PROD;
3435 ti->typinfo.prod_obj = tok->getval_prod()->get_obj_id();
3436 break;
3437
3438 case TCGRAM_PART_OF_SPEECH:
3439 ti->typ = VMGRAM_MATCH_SPEECH;
3440 ti->typinfo.speech_prop = tok->getval_part_of_speech();
3441 break;
3442
3443 case TCGRAM_LITERAL:
3444 /* set the literal in our token structure */
3445 ti->set_literal(
3446 tok->getval_literal_txt(), tok->getval_literal_len());
3447
3448 /* add the token to the dictionary */
3449 if (dict != VM_INVALID_OBJ
3450 && G_predef->misc_vocab != VM_INVALID_PROP)
3451 {
3452 ((CVmObjDict *)vm_objp(vmg_ dict))->add_word(
3453 vmg_ dict, ti->typinfo.lit.str, ti->typinfo.lit.len,
3454 self, G_predef->misc_vocab);
3455 }
3456 break;
3457
3458 case TCGRAM_TOKEN_TYPE:
3459 ti->typ = VMGRAM_MATCH_TOKTYPE;
3460 ti->typinfo.toktyp_enum = tok->getval_token_type();
3461 break;
3462
3463 case TCGRAM_STAR:
3464 ti->typ = VMGRAM_MATCH_STAR;
3465 break;
3466
3467 case TCGRAM_PART_OF_SPEECH_LIST:
3468 ti->set_nspeech(tok->getval_part_list_len());
3469 for (size_t i = 0 ; i < ti->typinfo.nspeech.cnt ; ++i)
3470 ti->typinfo.nspeech.props[i] = tok->getval_part_list_ele(i);
3471 break;
3472 }
3473 }
3474
3475 /* add it to the object */
3476 insert_alt(self, idx, ai);
3477
3478 /* create and add an undo record */
3479 vmgram_undo_rec *rec = new vmgram_undo_rec(VMGRAM_UNDO_ADDED, idx, 0);
3480 if (!G_undo->add_new_record_ptr_key(vmg_ self, rec))
3481 delete rec;
3482 }
3483
3484 /* addAlt() implementation */
3485 int CVmObjGramProd::getp_addAlt(VMG_ vm_obj_id_t self,
3486 vm_val_t *retval, uint *oargc)
3487 {
3488 const vm_val_t *v;
3489
3490 /* check arguments */
3491 uint argc = (oargc != 0 ? *oargc : 0);
3492 static CVmNativeCodeDesc desc(2, 2);
3493 if (get_prop_check_argc(retval, oargc, &desc))
3494 return TRUE;
3495
3496 /* the first argument is the rule list */
3497 const vm_val_t *alt = G_stk->get(0);
3498 const char *altp = alt->get_as_string(vmg0_);
3499 if (altp == 0)
3500 err_throw(VMERR_STRING_VAL_REQD);
3501
3502 /* get the source length and buffer pointer */
3503 size_t altlen = vmb_get_len(altp);
3504 altp += VMB_LEN;
3505
3506 /* the next argument is the match object class */
3507 vm_obj_id_t match = VM_INVALID_OBJ;
3508 v = G_stk->get(1);
3509 if (v->typ != VM_OBJ
3510 || !CVmObjTads::is_tadsobj_obj(vmg_ match = v->val.obj))
3511 err_throw(VMERR_BAD_TYPE_BIF);
3512
3513 /* next comes the optional dictionary argument */
3514 vm_obj_id_t dict = VM_INVALID_OBJ;
3515 if (argc >= 3
3516 && (v = G_stk->get(2))->typ != VM_NIL
3517 && (v->typ != VM_OBJ
3518 || !CVmObjDict::is_dictionary_obj(vmg_ (dict = v->val.obj))))
3519 err_throw(VMERR_INVAL_OBJ_TYPE);
3520
3521 /* next comes the optional symbol table */
3522 vm_obj_id_t symtab = VM_INVALID_OBJ;
3523 if (argc >= 4 && (v = G_stk->get(3))->typ != VM_NIL)
3524 {
3525 /* get the value, and make sure it's an object */
3526 symtab = v->val.obj;
3527 if (v->typ != VM_OBJ)
3528 err_throw(VMERR_OBJ_VAL_REQD);
3529 }
3530
3531 /* push self for gc protection */
3532 G_interpreter->push_obj(vmg_ self);
3533
3534 /* dynamically compile the alt list */
3535 CVmGramCompResults results(self, this, dict, match);
3536 CVmDynamicCompiler *comp = CVmDynamicCompiler::get(vmg0_);
3537 comp->compile(vmg_ FALSE, symtab, VM_INVALID_OBJ, VM_INVALID_OBJ,
3538 alt, altp, altlen, DCModeGramAlt, 0, &results);
3539
3540 /* check for errors */
3541 if (results.err != 0)
3542 results.throw_error(vmg0_);
3543
3544 /* rebuild the grammarAltProps property for the match object */
3545 build_alt_props(vmg_ match);
3546
3547 /* discard arguments and gc protection */
3548 G_stk->discard(argc + 1);
3549
3550 /* return self */
3551 retval->set_obj(self);
3552
3553 /* handled */
3554 return TRUE;
3555 }