Debian Codegraph @

terps/tads/tads3/lib/adv3/action.t

raw
1 #charset "us-ascii"
2
3 /*
4 * Copyright (c) 2000, 2006 Michael J. Roberts. All Rights Reserved.
5 *
6 * TADS 3 Library: Actions.
7 *
8 * This module defines the Action classes. An Action is an abstract
9 * object representing a command to be performed.
10 */
11
12 #include "adv3.h"
13 #include "tok.h"
14
15 /* ------------------------------------------------------------------------ */
16 /*
17 * Object associations lists. We use this object to store some lookup
18 * tables that we build during preinitialization to relate object usages
19 * (DirectObject, IndirectObject) to certain properties.
20 */
21 objectRelations: PreinitObject
22 /* preinitialization - build the lookup tables */
23 execute()
24 {
25 /* build the default pre-condition properties table */
26 preCondDefaultProps[DirectObject] = &preCondDobjDefault;
27 preCondDefaultProps[IndirectObject] = &preCondIobjDefault;
28
29 /* build the catch-all pre-conditions properties table */
30 preCondAllProps[DirectObject] = &preCondDobjAll;
31 preCondAllProps[IndirectObject] = &preCondIobjAll;
32
33 /* build the default verification properties table */
34 verifyDefaultProps[DirectObject] = &verifyDobjDefault;
35 verifyDefaultProps[IndirectObject] = &verifyIobjDefault;
36
37 /* build the catch-all verification properties table */
38 verifyAllProps[DirectObject] = &verifyDobjAll;
39 verifyAllProps[IndirectObject] = &verifyIobjAll;
40
41 /* build the default check properties table */
42 checkDefaultProps[DirectObject] = &checkDobjDefault;
43 checkDefaultProps[IndirectObject] = &checkIobjDefault;
44
45 /* build the catch-all check properties table */
46 checkAllProps[DirectObject] = &checkDobjAll;
47 checkAllProps[IndirectObject] = &checkIobjAll;
48
49 /* build the default action properties table */
50 actionDefaultProps[DirectObject] = &actionDobjDefault;
51 actionDefaultProps[IndirectObject] = &actionIobjDefault;
52
53 /* build the catch-all check properties table */
54 actionAllProps[DirectObject] = &actionDobjAll;
55 actionAllProps[IndirectObject] = &actionIobjAll;
56 }
57
58 /* lookup table for default precondition properties */
59 preCondDefaultProps = static new LookupTable()
60
61 /* lookup table for catch-all precondition properties */
62 preCondAllProps = static new LookupTable()
63
64 /* lookup table for default verification properties */
65 verifyDefaultProps = static new LookupTable()
66
67 /* lookup table for catch-all verification properties */
68 verifyAllProps = static new LookupTable()
69
70 /* lookup table for default check properties */
71 checkDefaultProps = static new LookupTable()
72
73 /* lookup table for catch-all check properties */
74 checkAllProps = static new LookupTable()
75
76 /* lookup table for default action properties */
77 actionDefaultProps = static new LookupTable()
78
79 /* lookup table for catch-all action properties */
80 actionAllProps = static new LookupTable()
81 ;
82
83
84 /* ------------------------------------------------------------------------ */
85 /*
86 * Invoke the given function with the given values for the parser global
87 * variables gActor and gAction.
88 */
89 withParserGlobals(issuer, actor, action, func)
90 {
91 local oldIssuer;
92 local oldActor;
93 local oldAction;
94
95 /* remember the old action and actor, so we can restore them later */
96 oldIssuer = gIssuingActor;
97 oldActor = gActor;
98 oldAction = gAction;
99
100 /* establish our actor and action as the global settings */
101 gIssuingActor = issuer;
102 gActor = actor;
103 gAction = action;
104
105 /* make sure we restore globals on the way out */
106 try
107 {
108 /* invoke the callback and return the result */
109 return (func)();
110 }
111 finally
112 {
113 /* restore the globals we changed */
114 gActor = oldActor;
115 gIssuingActor = oldIssuer;
116 gAction = oldAction;
117 }
118 }
119
120
121 /* ------------------------------------------------------------------------ */
122 /*
123 * Pre-condition Descriptor. This object encapsulates a precondition
124 * object and the argument we want to pass to its condition check method.
125 */
126 class PreCondDesc: object
127 construct(cond, arg)
128 {
129 /* remember the condition and the check argument */
130 cond_ = cond;
131 arg_ = arg;
132 }
133
134 /* check the precondition */
135 checkPreCondition(allowImplicit)
136 {
137 /* call the precondition's check method with the argument we stored */
138 return cond_.checkPreCondition(arg_, allowImplicit);
139 }
140
141 /* the precondition object */
142 cond_ = nil
143
144 /* the check argument */
145 arg_ = nil
146
147 /* our list sorting index */
148 index_ = 0
149 ;
150
151
152 /* ------------------------------------------------------------------------ */
153 /*
154 * Basic Action class. An Action is the language-independent definition
155 * of the abstract action of a command.
156 */
157 class Action: BasicProd
158 /*
159 * Are we the given kind of action? By default, this simply returns
160 * true if we're of the given action class.
161 */
162 actionOfKind(cls) { return ofKind(cls); }
163
164 /*
165 * Reset the action in preparation for re-execution. This should
166 * discard any scoped context from any past execution of the
167 * command, such as cached scope information.
168 */
169 resetAction()
170 {
171 /* forget any past successful verification passes */
172 verifiedOkay = [];
173 }
174
175 /*
176 * Repeat the action, for an AGAIN command.
177 */
178 repeatAction(lastTargetActor, lastTargetActorPhrase,
179 lastIssuingActor, countsAsIssuerTurn)
180 {
181 /* execute the command */
182 executeAction(lastTargetActor, lastTargetActorPhrase,
183 lastIssuingActor, countsAsIssuerTurn, self);
184 }
185
186 /*
187 * Cancel iteration of the action. This can be called during the
188 * 'check' or 'action' phases of executing this action. It tells
189 * the action that we want to stop executing the action when we're
190 * finished with the current object.
191 *
192 * Note that this doesn't cause a jump out of the current code, so
193 * it's not like 'exit' or the other termination signals. Instead,
194 * this simply tells the action to proceed normally for the
195 * remainder of the processing for the current object, and then act
196 * as though there were no more objects to iterate over, ending the
197 * command normally. If you want to cut off the remainder of the
198 * execution cycle for the current object, you can use 'exit' (for
199 * example) immediately after calling this method.
200 */
201 cancelIteration() { iterationCanceled = true; }
202
203 /* internal flag: object iteration has been canceled */
204 iterationCanceled = nil
205
206 /*
207 * Create an instance of this action, for use by a recursive or
208 * programmatically-generated command.
209 *
210 * The generic actions defined in the library are always subclassed
211 * by language-specific library modules, because the language
212 * modules have to define the grammar rules for the verbs - we can't
213 * define the grammar rules generically because the verbs wouldn't
214 * be reusable for non-English translations if we did. As a result,
215 * library code referring to one of the library verbs by name, say
216 * TakeAction, doesn't get a language-specific subclass of the verb,
217 * but just gets the language-independent base class.
218 *
219 * However, to make full use of an Action object in a recursive
220 * command, we do need a final language-specific subclass - without
221 * this, we won't be able to generate text describing the command,
222 * for example. This method bridges this gap by finding a suitable
223 * language-specific subclass of the given action, then creating an
224 * instance of that subclass rather than an instance of the base
225 * class.
226 *
227 * By default, we'll take any subclass of this action that is itself
228 * a class. However, if any subclass has the property
229 * defaultForRecursion set to true, we'll use that class
230 * specifically - this lets the language module designate a
231 * particular subclass to use as the default for recursive commands,
232 * which might be desirable in cases where the language module
233 * defines more than one subclass of an action.
234 */
235 createActionInstance()
236 {
237 local found;
238
239 /*
240 * Iterate over our subclasses. Initialize 'found' to this base
241 * class, so that if we fail to find any subclasses, we'll at
242 * least be able to create an instance of the generic base
243 * class.
244 */
245 for (local cur = firstObj(self, ObjClasses), found = self ;
246 cur != nil ; cur = nextObj(cur, self, ObjClasses))
247 {
248 /*
249 * if this one is marked as a default for recursion, and the
250 * last one we found isn't, choose this one over the last
251 * one we found
252 */
253 if (cur.defaultForRecursion && !found.defaultForRecursion)
254 found = cur;
255
256 /*
257 * If this one is a subclass of the last one we found, pick
258 * it instead of the last one. We always want a final
259 * subclass here, never an intermediate class, so if we find
260 * a subclass of the one we've tentatively picked, we know
261 * that the tentative selection isn't final after all.
262 */
263 if (cur.ofKind(found))
264 found = cur;
265 }
266
267 /* return a new instance of what we found */
268 return found.createInstance();
269 }
270
271 /*
272 * Create an instance of this action based on another action. We'll
273 * copy the basic properties of the original action.
274 */
275 createActionFrom(orig)
276 {
277 local action;
278
279 /* create a new instance of this action */
280 action = createActionInstance();
281
282 /* copy the token list information to the new action */
283 action.tokenList = orig.tokenList;
284 action.firstTokenIndex = orig.firstTokenIndex;
285 action.lastTokenIndex = orig.lastTokenIndex;
286
287 /* the new action is implicit if the original was */
288 if (orig.isImplicit)
289 action.setImplicit(orig.implicitMsg);
290
291 /* return the new action */
292 return action;
293 }
294
295 /*
296 * Mark the command as implicit. 'msgProp' is the property (of
297 * gLibMessages) to use to announce the implicit command.
298 */
299 setImplicit(msgProp)
300 {
301 /* mark ourselves as implicit */
302 isImplicit = true;
303
304 /* do not show default reports for implicit commands */
305 showDefaultReports = nil;
306
307 /* all implicit commands are nested */
308 setNested();
309
310 /*
311 * do not include implicit commands in undo - since an implicit
312 * command is only a subpart of an explicit command, an implicit
313 * command is not undone individually but only as part of the
314 * enclosing explicit command
315 */
316 includeInUndo = nil;
317
318 /* remember the implicit command announcement message property */
319 implicitMsg = msgProp;
320 }
321
322 /*
323 * Mark the command as nested, noting the parent action (which we
324 * take as the global current action).
325 */
326 setNested()
327 {
328 /* remember the parent action */
329 parentAction = gAction;
330 }
331
332 /*
333 * Determine if I'm nested within the given action. Returns true if
334 * the given action is my parent action, or if my parent action is
335 * nested within the given action.
336 */
337 isNestedIn(action)
338 {
339 /* if my parent action is the given action, I'm nested in it */
340 if (parentAction == action)
341 return true;
342
343 /*
344 * if I have a parent action, and it's nested in the given
345 * action, then I'm nested in the given action because I'm
346 * nested in anything my parent is nested in
347 */
348 if (parentAction != nil && parentAction.isNestedIn(action))
349 return true;
350
351 /* we're not nested in the given action */
352 return nil;
353 }
354
355 /*
356 * Set the "original" action. An action with an original action is
357 * effectively part of the original action for the purposes of its
358 * reported results.
359 *
360 * An action has an original action if it's a nested or replacement
361 * action for an action.
362 */
363 setOriginalAction(action)
364 {
365 /* remember my original action */
366 originalAction = action;
367 }
368
369 /*
370 * Get the "original" action. If I'm a replacement or nested action,
371 * this returns the original main action of which I'm a part, for
372 * reporting pruposes.
373 *
374 * It's important to note that an implied action does NOT count as a
375 * nested or replacement action for the purposes of this method.
376 * That is, if a command A triggers an implied action B, which
377 * triggers a nested action C, and then after that command A itself
378 * triggers a nested action D, then
379 *
380 * A.getOriginalAction -> A
381 *. B.getOriginalAction -> B (B is implied, not nested)
382 *. C.getOriginalAction -> C (C is nested within B)
383 *. D.getOriginalAction -> A (D is nested within A)
384 *
385 * The purpose of the original action is to tell us, mainly for
386 * reporting purposes, what we're really trying to do with the
387 * action. This allows reports to hide the internal details of how
388 * the action is carried out, and instead say what the action was
389 * meant to do from the player's perspective.
390 */
391 getOriginalAction()
392 {
393 /* if I have no other original action, I'm the original action */
394 if (originalAction == nil)
395 return self;
396
397 /* return my original action's original action */
398 return originalAction.getOriginalAction();
399 }
400
401 /*
402 * Determine if this action is "part of" the given action. I'm part
403 * of the given action if I am the given action, or the given action
404 * is my "original" action, or my original action is part of the
405 * given action.
406 */
407 isPartOf(action)
408 {
409 /* if I'm the same as the given action, I'm obviously part of it */
410 if (action == self)
411 return true;
412
413 /* if my original action is part of the action, I'm part of it */
414 if (originalAction != nil && originalAction.isPartOf(action))
415 return true;
416
417 /* I'm not part of the given action */
418 return nil;
419 }
420
421 /*
422 * Mark the action as "remapped." This indicates that the action
423 * was explicitly remapped to a different action during the remap()
424 * phase.
425 */
426 setRemapped(orig) { remappedFrom = gAction; }
427
428 /* determine if I'm remapped, and get the original action if so */
429 isRemapped() { return remappedFrom != nil; }
430 getRemappedFrom() { return remappedFrom; }
431
432 /*
433 * Get the "simple synonym" remapping for one of our objects, if
434 * any. 'obj' is the resolved object to remap, and 'role' is the
435 * object role identifier (DirectObject, IndirectObject, etc).
436 * 'remapProp' is the remapping property for the role; this is
437 * simply the result of our getRemapPropForRole(role), but we ask
438 * the caller to pass this in so that it can be pre-computed in
439 * cases where we'll called in a loop.
440 *
441 * A simple synonym remapping is a remapTo that applies the same
442 * verb to a new object in the same role. For example, if we remap
443 * OPEN DESK to OPEN DRAWER, then the drawer is the simple synonym
444 * remapping for the desk in an OPEN command. A remapping is
445 * considered a simple synonym remapping only if we're remapping to
446 * the same action, AND the new object is in the same action role as
447 * the original object was.
448 *
449 * If there's no simple synonym remapping, we'll return nil.
450 */
451 getSimpleSynonymRemap(obj, role, remapProp)
452 {
453 local mapping;
454 local remapIdx;
455
456 /* if the object isn't remapped at all, there's no remapping */
457 if ((mapping = obj.(remapProp)) == nil)
458 return nil;
459
460 /* if the mapping isn't to the same action, it's not a synonym */
461 if (!ofKind(mapping[1]))
462 return nil;
463
464
465 /*
466 * Find the specific (non-role) object in the remap vector -
467 * this is the entry that's actually an object rather than a
468 * role identifier. (The remapping vector is required to have
469 * exactly one such entry. Look from the right end of the list,
470 * since the first entry is always the new action, which is
471 * itself an object, but not the object we're looking for.)
472 */
473 remapIdx = mapping.lastIndexWhich({x: dataType(x) == TypeObject});
474 if (remapIdx == nil)
475 return nil;
476
477 /*
478 * Determine if the object plays the same role in the new action
479 * as the original object did in the original action. It does
480 * if it's at the index in the mapping vector of our object role
481 * in the action. Note that the mapping vector has slot 1
482 * filled with the action, so its objects are actually one slot
483 * higher than they are in the action itself.
484 *
485 * If the new object isn't in the same role, then this isn't a
486 * simple synonym remapping.
487 */
488 if (getRoleFromIndex(remapIdx - 1) != role)
489 return nil;
490
491 /*
492 * We have the same action applied to a new object in the same
493 * role as the original object, so this is a simple synonym
494 * remapping. Return the new object we're mapping to.
495 */
496 return mapping[remapIdx];
497 }
498
499 /*
500 * the defaultForRecursion flag must be explicitly set in subclasses
501 * when desired - by default we'll use any language-specific
502 * subclass of an Action for recursive commands
503 */
504 defaultForRecursion = nil
505
506 /*
507 * Flag: the command is implicit. An implicit command is one that
508 * is performed as an implied enabling step of another command - for
509 * example, if an actor wants to throw something, the actor must be
510 * holding the object, so will implicitly try to take the object.
511 */
512 isImplicit = nil
513
514 /*
515 * The parent action. If the command is performed programmatically
516 * in the course of executing another command, this is set to the
517 * enclosing action.
518 *
519 * Note that while all implicit commands are nested, not all nested
520 * commands are implicit. A nested command may simply be a
521 * component of another command, or another command may be handled
522 * entirely by running a different command as a nested command. In
523 * any case, a nested but non-implicit command does not appear to
524 * the player as a separate command; it is simply part of the
525 * original command.
526 */
527 parentAction = nil
528
529 /*
530 * The original action we were remapped from. This is valid when
531 * the action was explicitly remapped during the remap() phase to a
532 * different action.
533 */
534 remappedFrom = nil
535
536 /*
537 * the original action - we are effectively part of the original
538 * action for reporting purposes
539 */
540 originalAction = nil
541
542 /* the libMessage property, if any, to announce the implicit command */
543 implicitMsg = nil
544
545 /*
546 * Flag: we are to show default reports for this action. In most
547 * cases we will do so, but for some types of commands (such as
548 * implicit commands), we suppress default reports.
549 */
550 showDefaultReports = true
551
552 /*
553 * Get a message parameter object for the action. Each action
554 * subclass defines this to return its objects according to its own
555 * classifications. The default action has no objects, but
556 * recognizes 'actor' as the current command's actor.
557 */
558 getMessageParam(objName)
559 {
560 switch(objName)
561 {
562 case 'pc':
563 /* return the player character */
564 return gPlayerChar;
565
566 case 'actor':
567 /* return the current actor */
568 return gActor;
569
570 default:
571 /*
572 * if we have an extra message parameters table, look up the
573 * parameter name in the table
574 */
575 if (extraMessageParams != nil)
576 return extraMessageParams[objName];
577
578 /* we don't recognize other names */
579 return nil;
580 }
581 }
582
583 /*
584 * Define an extra message-specific parameter. Message processors
585 * can use this to add their own special parameters, so that they
586 * can refer to parameters that aren't involved directly in the
587 * command. For example, a message for "take <dobj>" might want to
588 * refer to the object containing the direct object.
589 */
590 setMessageParam(objName, obj)
591 {
592 /*
593 * if we don't yet have an extra message parameters table,
594 * create a small lookup table for it
595 */
596 if (extraMessageParams == nil)
597 extraMessageParams = new LookupTable(8, 8);
598
599 /* add the parameter to the table, indexing by the parameter name */
600 extraMessageParams[objName.toLower()] = obj;
601 }
602
603 /*
604 * For convenience, this method allows setting any number of
605 * name/value pairs for message parameters.
606 */
607 setMessageParams([lst])
608 {
609 /* set each pair from the argument list */
610 for (local i = 1, local len = lst.length() ; i+1 <= len ; i += 2)
611 setMessageParam(lst[i], lst[i+1]);
612 }
613
614 /*
615 * Synthesize a global message parameter name for the given object.
616 * We'll store the association and return the synthesized name.
617 */
618 synthMessageParam(obj)
619 {
620 local nm;
621
622 /* synthesize a name */
623 nm = 'synth' + toString(synthParamID++);
624
625 /* store the association */
626 setMessageParam(nm, obj);
627
628 /* return the synthesized name */
629 return nm;
630 }
631
632 /* synthesized message object parameter serial number */
633 synthParamID = 1
634
635 /*
636 * Extra message parameters. If a message processor wants to add
637 * special message parameters of its own, we'll create a lookup
638 * table for the extra parameters. Message processors might want to
639 * add their own special parameters to allow referring to objects
640 * other than the main objects of the command.
641 */
642 extraMessageParams = nil
643
644 /*
645 * Flag: this command is repeatable with 'again'. Before executing
646 * a command, we'll save it for use by the 'again' command if this
647 * flag is true.
648 */
649 isRepeatable = true
650
651 /*
652 * Flag: this command should be included in the undo records. This
653 * is true for almost every command, but a few special commands
654 * (undo, save) are not subject to undo.
655 */
656 includeInUndo = true
657
658 /*
659 * Flag: this is a "conversational" command, as opposed to an order.
660 * When this type of command is addressed to another character, it
661 * doesn't ask the other character to do anything, but rather engages
662 * the other character in conversation. Examples:
663 *
664 *. Bob, hello
665 *. Bob, goodbye
666 *. Bob, tell me about the planet
667 *. Bob, yes
668 *. Bob, no
669 *
670 * ("Tell me about..." is a little different from the others. We
671 * treat it as conversational because it means the same thing as "ask
672 * Bob about...", which we consider conversational because it would
673 * be rendered in real life as a question. In other words, the
674 * action involves the issuing actor stating the question, which
675 * means that issuing actor is the one doing the physical work of the
676 * action. "Tell me about..." could be seen as an order, but it
677 * seems more appropriate to view it as simply an alternative way of
678 * phrasing a question.)
679 *
680 * The issuing actor is passed as a parameter because some actions
681 * are conversational only in some cases; "tell me about the planet"
682 * is conversational, but "tell Bill about the planet" isn't, since
683 * the latter doesn't ask Bob a question but orders Bob to talk to
684 * Bill.
685 *
686 * When the issuing actor and target actor are the same, this is
687 * irrelevant. The purpose of this is to distinguish orders given to
688 * another character from conversational overtures directed to the
689 * other character, so if the command is coming from the player and
690 * bound for the player character, there's obviously no conversation
691 * going on.
692 *
693 * Note also that, contrary to what one might think at first glance,
694 * a command like ASK ABOUT is NOT conversational; it's a command to
695 * ask someone about something, and isn't itself a conversational
696 * overture. The act of asking is itself a conversational overture,
697 * but the asking is the *result* of the command, not the command
698 * itself. An action is only conversational if the action itself is
699 * a conversational overture. So, "BOB, HELLO" is conversational;
700 * "BOB, ASK BILL ABOUT COMPUTER" is not, because it orders Bob to do
701 * something.
702 */
703 isConversational(issuingActor) { return nil; }
704
705 /*
706 * Get the actual verb phrase the player typed in to generate this
707 * Action, expressed in a canonical format. The canonical format
708 * consists of the lower-case version of all of the actual text the
709 * player typed, but with each noun phrase replaced by a standard
710 * placeholder token describing the slot. The placeholder tokens are
711 * '(dobj)' for the direct object, '(iobj)' for the indirect object,
712 * '(literal)' for a literal text phrase, and '(topic)' for a topic
713 * phrase.
714 *
715 * For example, if the player typed PUT BOOK AND PENCIL IN BOX, the
716 * canonical phrasing we return would be "put (dobj) in (iobj)".
717 */
718 getEnteredVerbPhrase()
719 {
720 local orig;
721 local txt;
722
723 /*
724 * If there's an original action, let the original action do the
725 * work. If we've been remapped, or if this is an implied
726 * action, we won't necessarily have been constructed from the
727 * actual player input, so we need to go back to the original
728 * action for this information.
729 */
730 if (getOriginalAction() != self)
731 return getOriginalAction.getEnteredVerbPhrase();
732
733 /* start with the original token list for the predicate */
734 orig = getPredicate().getOrigTokenList();
735
736 /* add each token to the result text */
737 for (txt = '', local i = 1, local len = orig.length() ;
738 i <= len ; ++i)
739 {
740 local foundNp;
741
742 /* add a space if this isn't the first element */
743 if (i > 1)
744 txt += ' ';
745
746 /*
747 * Check to see if we're entering one of the noun-phrase
748 * slots. We are if we've reached the first token of one of
749 * the predicate noun phrases.
750 */
751 foundNp = nil;
752 foreach (local npProp in predicateNounPhrases)
753 {
754 local match;
755
756 /* check to see if we're at this noun phrase */
757 if ((match = self.(npProp)) != nil
758 && i == match.firstTokenIndex)
759 {
760 /*
761 * we're entering this noun phrase - add the generic
762 * placeholder token for the noun phrase
763 */
764 txt += (npProp == &dobjMatch ? '(dobj)' :
765 npProp == &iobjMatch ? '(iobj)' :
766 npProp == &topicMatch ? '(topic)' :
767 npProp == &literalMatch ? '(literal)' :
768 '(other)');
769
770 /* skip the entire run of tokens for the noun phrase */
771 i = match.lastTokenIndex;
772
773 /* note that we found a noun phrase */
774 foundNp = true;
775
776 /* stop looking for a noun phrase */
777 break;
778 }
779 }
780
781 /*
782 * if we didn't find a noun phrase, this token is a literal
783 * part of the predicate grammar, so add it as-is
784 */
785 if (!foundNp)
786 txt += getTokVal(orig[i]);
787 }
788
789 /* return the phrase, with everything converted to lower-case */
790 return txt.toLower();
791 }
792
793 /*
794 * Get the grammar match tree object for the predicate that was used
795 * to enter this command. By default, if we have an original action,
796 * we return the original action; otherwise we just return 'self'.
797 *
798 * Language libraries must override this to return the original match
799 * tree object if Actions are separate from predicate match trees.
800 *
801 * (The 'predicate' is simply the grammar match tree object for the
802 * entire verb phrase from the player's actual command entry text
803 * that matched this Action. For example, in "BOB, TAKE BOX", the
804 * predicate is the match tree for the "TAKE BOX" part. In "BOB,
805 * TAKE BOX AND GO NORTH", the predicate for the Take action is still
806 * the "TAKE BOX" part. For "BOB, TAKE BOX AND BOOK AND GO NORTH",
807 * the predicate for the Take action is "TAKE BOX AND BOOK" - the
808 * full verb phrase includes any multiple-object lists in the
809 * original command.)
810 */
811 getPredicate()
812 {
813 /*
814 * By default, we just return the original Action - we assume
815 * that the language library defines Action subclasses as the
816 * actual match tree objects for predicate grammars. Language
817 * modules must override this if they use separate object types
818 * for the predicate match tree objects.
819 */
820 return getOriginalAction();
821 }
822
823 /*
824 * Get the noun-phrase information for my predicate grammar. This
825 * returns a list of the match-tree properties for the noun-phrase
826 * sub-productions in our predicate grammar. The properties
827 * generally include &dobjMatch, &iobjMatch, &literalMatch, and
828 * &topicMatch. The order of the slots isn't important; they simply
829 * tell us which ones we should find in our predicate grammar match.
830 *
831 * The base Action is intransitive, so it doesn't have any
832 * noun-phrase slots, hence this is an empty list.
833 */
834 predicateNounPhrases = []
835
836 /*
837 * Get the object "role" identifier for the given index. This
838 * returns the identifier (DirectObject, IndirectObject, etc.) for
839 * the object at the given slot index, as used in
840 * setResolvedObjects(). The first object is at index 1.
841 */
842 getRoleFromIndex(idx) { return nil; }
843
844 /*
845 * Get the "other object" role - this is the complement of the given
846 * object role for a two-object action, and is used to determine the
847 * real role of the special OtherObject placeholder in a remapTo().
848 * This is only meaningful with actions of exactly two objects.
849 */
850 getOtherObjectRole(role) { return nil; }
851
852 /* get the resolved object in a given role */
853 getObjectForRole(role) { return nil; }
854
855 /* get the match tree for the noun phrase in the given role */
856 getMatchForRole(role) { return nil; }
857
858 /* get the 'verify' property for a given object role */
859 getVerifyPropForRole(role)
860 {
861 return nil;
862 }
863
864 /* get the 'preCond' property for a given object role */
865 getPreCondPropForRole(role)
866 {
867 return nil;
868 }
869
870 /* get the 'remap' property for a given object role */
871 getRemapPropForRole(role)
872 {
873 return nil;
874 }
875
876 /*
877 * Get the ResolveInfo for the given object in the current command.
878 * Since we don't have any objects at all, we'll simply return a new
879 * ResolveInfo wrapping the given object. 'cur' is the object we're
880 * looking for, and 'oldRole' is the role the object previously
881 * played in the action.
882 */
883 getResolveInfo(obj, oldRole) { return new ResolveInfo(obj, 0, nil); }
884
885 /*
886 * Explicitly set the resolved objects. This should be overridden
887 * in each subclass for the number of objects specific to the action
888 * (a simple transitive action takes one argument, an action with
889 * both a direct and indirect object takes two arguments, and so
890 * on). The base action doesn't have any objects at all, so this
891 * takes no arguments.
892 *
893 * This method is used to set up an action to be performed
894 * programmatically, rather than based on parsed input. Since
895 * there's no parsed input in such cases, the objects are specified
896 * directly by the programmatic caller.
897 */
898 setResolvedObjects() { }
899
900 /*
901 * Explicitly set the object match trees. This sets the pre-resolved
902 * production match trees. The arguments are given in the order of
903 * their roles in the action, using the same order that
904 * setResolvedObjects() uses.
905 *
906 * The arguments to this routine can either be match tree objects,
907 * which we'll plug into our grammar tree in the respective roles
908 * exactly as given; or they can be ResolveInfo objects giving the
909 * desired resolutions, in which case we'll build the appropriate
910 * kind of PreResolvedProd for each one. The types can be freely
911 * mixed.
912 */
913 setObjectMatches() { }
914
915 /*
916 * Check that the resolved objects are all in scope. Returns true if
917 * so, nil if not.
918 *
919 * This routine is meant for use only for actions built
920 * programmatically using setResolvedObjects(). In particular, we
921 * assume that we have only one object in each slot. For normal
922 * parser-built actions, this check isn't necessary, because the
923 * parser only resolves objects that are in scope in the first place.
924 */
925 resolvedObjectsInScope()
926 {
927 /* we have no objects at all, so there is nothing out of scope */
928 return true;
929 }
930
931 /*
932 * Get the list of bindings for an anaphoric pronoun - this is a
933 * pronoun that refers back to an earlier noun phrase in the same
934 * sentence, such as HIMSELF in ASK BOB ABOUT HIMSELF. These
935 * obviously make no sense for verbs that take one (or zero)
936 * objects, since there's no earlier phrase to refer back to; these
937 * should return nil to indicate that an anaphoric pronoun is simply
938 * nonsensical in such a context. Actions of two or more objects
939 * should return a list of objects for the preceding noun phrase.
940 *
941 * Actions of two or more objects should set this if possible to the
942 * resolved object list for the previous noun phrase, as a
943 * ResolveInfo list.
944 *
945 * The tricky part is that some actions will resolve noun phrases in
946 * a different order than they appear in the actual command grammar;
947 * similarly, it's also possible that some non-English languages use
948 * cataphoric pronouns (i.e., pronouns that refer to noun phrases
949 * that appear later in the sentence). To allow for these cases,
950 * return an empty list here if a binding is grammatically possible
951 * but not yet available because of the resolution order, and note
952 * internally that the parser asked us for an anaphoric binding.
953 * Afterwards, the action's resolver method must go back and perform
954 * *another* resolve pass on the noun phrase production that
955 * requested the anaphor binding.
956 *
957 * 'typ' is the PronounType specifier for the corresponding ordinary
958 * pronoun. For 'himself', for example, typ will be PronounHim.
959 */
960 getAnaphoricBinding(typ) { return nil; }
961
962 /*
963 * Set a special pronoun override. This creates a temporary pronoun
964 * definition, which lasts as long as this action (and any nested
965 * actions). The temporary definition overrides the normal meaning
966 * of the pronoun.
967 *
968 * One example of where this is useful is in global action remapping
969 * cases where the target actor changes in the course of the
970 * remapping. For example, if we remap BOB, GIVE ME YOUR BOOK to ASK
971 * BOB FOR YOUR BOOK, the YOUR qualifier should still refer to Bob
972 * even though the command is no longer addressing Bob directly.
973 * This routine can be used in this case to override the meaning of
974 * 'you' so that it refers to Bob.
975 */
976 setPronounOverride(typ, val)
977 {
978 /* if we don't have an override table yet, create one */
979 if (pronounOverride == nil)
980 pronounOverride = new LookupTable(5, 10);
981
982 /* add it to the table */
983 pronounOverride[typ] = val;
984 }
985
986 /*
987 * Get any special pronoun override in effect for the action, as set
988 * via setPronounOverride(). This looks in our own override table
989 * for a definition; then, if we have no override of our own, we ask
990 * our parent action if we have one, then our original action.
991 */
992 getPronounOverride(typ)
993 {
994 local pro;
995
996 /* check our own table */
997 if (pronounOverride != nil
998 && (pro = pronounOverride[typ]) != nil)
999 return pro;
1000
1001 /* we don't have anything in our own table; check our parent */
1002 if (parentAction != nil
1003 && (pro = parentAction.getPronounOverride(typ)) != nil)
1004 return pro;
1005
1006 /* if still nothing, check with the original action */
1007 if (originalAction != nil
1008 && originalAction != parentAction
1009 && (pro = originalAction.getPronounOverride(typ)) != nil)
1010 return pro;
1011
1012 /* we didn't find an override */
1013 return nil;
1014 }
1015
1016 /*
1017 * the pronoun override table - this is nil by default, which means
1018 * that no overrides have been defined yet; we create a LookupTable
1019 * upon adding the first entry to the table
1020 */
1021 pronounOverride = nil
1022
1023 /* wrap an object with a ResolveInfo */
1024 makeResolveInfo(val)
1025 {
1026 /*
1027 * if it's already a ResolveInfo object, return it as-is;
1028 * otherwise, create a new ResolveInfo wrapper for it
1029 */
1030 if (dataType(val) == TypeObject && val.ofKind(ResolveInfo))
1031 return val;
1032 else
1033 return new ResolveInfo(val, 0, nil);
1034 }
1035
1036 /*
1037 * Convert an object or list of objects to a ResolveInfo list
1038 */
1039 makeResolveInfoList(val)
1040 {
1041 /* if we have a non-list collection, make it a list */
1042 if (dataType(val) == TypeObject && val.ofKind(Collection))
1043 val = val.toList();
1044
1045 /* if it's nil or an empty list, return an empty list */
1046 if (val == nil || val == [])
1047 return [];
1048
1049 /* see what we have */
1050 if (dataType(val) == TypeList)
1051 {
1052 /* it's a list - make a ResolveInfo for each item */
1053 return val.mapAll({x: makeResolveInfo(x)});
1054 }
1055 else
1056 {
1057 /* it's not a list - return a one-element ResolveInfo list */
1058 return [makeResolveInfo(val)];
1059 }
1060 }
1061
1062 /*
1063 * If the command is repeatable, save it for use by 'again'.
1064 */
1065 saveActionForAgain(issuingActor, countsAsIssuerTurn,
1066 targetActor, targetActorPhrase)
1067 {
1068 /*
1069 * Check to see if the command is repeatable. It's repeatable if
1070 * the base action is marked as repeatable, AND it's not nested,
1071 * AND it's issued by the player character, AND it's either a PC
1072 * command or it counts as an issuer turn.
1073 *
1074 * Nested commands are never repeatable with 'again', since no
1075 * one ever typed them in.
1076 *
1077 * "Again" is strictly for the player's use, so it's repeatable
1078 * only if this is the player's turn, as opposed to a scripted
1079 * action by an NPC. This is the player's turn only if the
1080 * command was issued by the player character (which means it
1081 * came from the player), and either it's directed to the player
1082 * character OR it counts as a turn for the player character.
1083 */
1084 if (isRepeatable
1085 && parentAction == nil
1086 && (issuingActor.isPlayerChar()
1087 && (targetActor.isPlayerChar() || countsAsIssuerTurn)))
1088 AgainAction.saveForAgain(issuingActor, targetActor,
1089 targetActorPhrase, self);
1090 }
1091
1092 /*
1093 * Perform this action. Throughout execution of the action, the
1094 * global parser variables that specify the current actor and action
1095 * are valid.
1096 */
1097 doAction(issuingActor, targetActor, targetActorPhrase,
1098 countsAsIssuerTurn)
1099 {
1100 local oldActor;
1101 local oldIssuer;
1102 local oldAction;
1103 local oldResults;
1104
1105 /*
1106 * save the current parser globals, for restoration when we
1107 * finish this command - if this command is nested within
1108 * another, this will let us ensure that everything is restored
1109 * properly when we finish with this command
1110 */
1111 oldActor = gActor;
1112 oldIssuer = gIssuingActor;
1113 oldAction = gAction;
1114 oldResults = gVerifyResults;
1115
1116 /*
1117 * set the new globals (note that there are no verification
1118 * results or command reports objects yet - these are valid only
1119 * while we're running the corresponding command phases)
1120 */
1121 gActor = targetActor;
1122 gIssuingActor = issuingActor;
1123 gAction = self;
1124 gVerifyResults = nil;
1125
1126 /* make sure we restore globals on our way out */
1127 try
1128 {
1129 local pc;
1130
1131 /* if applicable, save the command for AGAIN */
1132 saveActionForAgain(issuingActor, countsAsIssuerTurn,
1133 targetActor, targetActorPhrase);
1134
1135 /* start a new command visually if this isn't a nested action */
1136 if (parentAction == nil)
1137 gTranscript.addCommandSep();
1138
1139 /* have the player character note initial conditions */
1140 pc = gPlayerChar;
1141 pc.noteConditionsBefore();
1142
1143 /* run the before routine for the entire action */
1144 beforeActionMain();
1145
1146 /* run the subclass-specific processing */
1147 doActionMain();
1148
1149 /* run the after routine for the entire action */
1150 afterActionMain();
1151
1152 /*
1153 * If this is a top-level action, show the command results.
1154 * Don't show results for a nested action, since we want to
1155 * wait and let the top-level action show the results after
1156 * it has the full set of results.
1157 */
1158 if (parentAction == nil)
1159 {
1160 /*
1161 * If the player character didn't change, ask the player
1162 * character to note any condition changes. If the
1163 * player character did change to a new actor,
1164 * presumably the command will have displayed a specific
1165 * message, since this would be an unusual development
1166 * for which we can generate no generic message.
1167 */
1168 if (gPlayerChar == pc)
1169 pc.noteConditionsAfter();
1170 }
1171 }
1172 finally
1173 {
1174 /* restore the parser globals to how we found them */
1175 gActor = oldActor;
1176 gIssuingActor = oldIssuer;
1177 gAction = oldAction;
1178 gVerifyResults = oldResults;
1179 }
1180 }
1181
1182 /*
1183 * Perform processing before running the action. This is called
1184 * just once per action, even if the action will be iterated for a
1185 * list of objects.
1186 */
1187 beforeActionMain()
1188 {
1189 }
1190
1191 /*
1192 * Perform processing after running the entire action. This is
1193 * called just once per action, even if the action was iterated for
1194 * a list of objects.
1195 */
1196 afterActionMain()
1197 {
1198 /* call each registered after-action handler */
1199 if (afterActionMainList != nil)
1200 {
1201 foreach (local cur in afterActionMainList)
1202 cur.afterActionMain();
1203 }
1204
1205 /*
1206 * Mark ourselves as busy for the amount of time this action
1207 * takes. Don't count the time taken for implied actions,
1208 * though, since these are meant to be zero-time sub-actions
1209 * performed as part of the main action and thus don't have a
1210 * separate time cost.
1211 *
1212 * Note that we add our busy time in the main after-action
1213 * processing because we only want to count our time cost once
1214 * for the whole command, even if we're performing the command on
1215 * multiple objects.
1216 */
1217 if (!isImplicit)
1218 {
1219 local actor;
1220
1221 /*
1222 * If the command is conversational, the turn counts as an
1223 * issuer turn; otherwise, it counts as a turn for the target
1224 * actor. Conversational commands are effectively carried
1225 * out by the issuer, even though in form they're directed to
1226 * another actor (as in "BOB, HELLO"), so we need to count
1227 * the time they take as the issuer's time.
1228 */
1229 actor = (isConversational(gIssuingActor)
1230 ? gIssuingActor : gActor);
1231
1232 /* add the busy time to the actor */
1233 actor.addBusyTime(self, actionTime);
1234 }
1235
1236 /*
1237 * If the command failed, and this is a top-level (not nested)
1238 * action, check to see if the game wants to cancel remaining
1239 * commands on the line.
1240 */
1241 if (gTranscript.isFailure
1242 && parentAction == nil
1243 && gameMain.cancelCmdLineOnFailure)
1244 {
1245 /*
1246 * the command failed, and they want to cancel remaining
1247 * commands on failure - throw a 'cancel command line'
1248 * exception to cancel any remaining tokens
1249 */
1250 throw new CancelCommandLineException();
1251 }
1252 }
1253
1254 /*
1255 * Register an object for afterActionMain invocation. After we've
1256 * finished with the entire action - including all iterated objects
1257 * involved in the action - we'll invoke each registered object's
1258 * afterActionMain() method. This registration is only meaningful
1259 * for the current action instance, and can only be set up before
1260 * the action has been finished (i.e., before the current gAction
1261 * invokes its own afterActionMain() method).
1262 *
1263 * Each object is only registered once. If a caller attempts to
1264 * register the same object repeatedly, we'll simply ignore the
1265 * repeated requests.
1266 *
1267 * This is a convenient way to implement a collective follow-up to
1268 * the parts of an iterated action. Since repeated registrations
1269 * are ignored, each handler for an iterated object (such as a
1270 * "dobjFor" action() handler) can register its follow-up handler
1271 * without worrying about redundant registration. Then, when the
1272 * overall action is completed for each iterated object involved,
1273 * the follow-up handler will be invoked, and it can do any final
1274 * work for the overall action. For example, the follow-up handler
1275 * could display a message summarizing the iterated parts of the
1276 * action; or, it could even scan the transcript for particular
1277 * messages and replace them with a summary.
1278 */
1279 callAfterActionMain(obj)
1280 {
1281 /* if we don't have an after-action list yet, create one */
1282 if (afterActionMainList == nil)
1283 afterActionMainList = new Vector(8);
1284
1285 /* if this item isn't already in the list, add it */
1286 if (afterActionMainList.indexOf(obj) == nil)
1287 afterActionMainList.append(obj);
1288 }
1289
1290 /* list of methods to invoke after we've completed the action */
1291 afterActionMainList = nil
1292
1293 /*
1294 * the amount of time on the game clock that the action consumes -
1295 * by default, each action consumes one unit, but actions can
1296 * override this to consume more or less game time
1297 */
1298 actionTime = 1
1299
1300 /*
1301 * Zero the action time in this action and any parent actions. This
1302 * should be used when a nested replacement action is to completely
1303 * take over the time-keeping responsibility for the entire turn; all
1304 * containing actions in this case are to take zero time, since the
1305 * nested action is the only part of the turn that will count for
1306 * timing.
1307 */
1308 zeroActionTime()
1309 {
1310 /* clear my action time */
1311 actionTime = 0;
1312
1313 /* if we have a parent action, zero it and its parents */
1314 if (parentAction != nil)
1315 parentAction.zeroActionTime();
1316 }
1317
1318 /*
1319 * Execute the action for a single set of objects. This runs the
1320 * full execution sequence for the current set of objects.
1321 *
1322 * Subclasses generally won't override this method, but will instead
1323 * override the methods that implement the individual steps in the
1324 * execution sequence.
1325 */
1326 doActionOnce()
1327 {
1328 /*
1329 * Perform the sequence of operations to execute the action. If
1330 * an ExitSignal is thrown during the sequence, skip to the
1331 * end-of-turn processing.
1332 */
1333 try
1334 {
1335 local result;
1336 local impReport;
1337
1338 /*
1339 * Before doing any actual execution, check the command for
1340 * remapping. If we end up doing any remapping, the
1341 * remapping routine will simply replace the current command,
1342 * so we the remapping call will terminate the current action
1343 * with 'exit' and thus never return here.
1344 */
1345 checkRemapping();
1346
1347 /*
1348 * If this is an implicit action, check for danger: we never
1349 * try a command implicitly when the command is obviously
1350 * dangerous.
1351 */
1352 if (isImplicit)
1353 {
1354 /*
1355 * verify the action for an implicit command, checking
1356 * for actions that aren't allowe implicitly - we never
1357 * try a command implicitly when the command is (or
1358 * should be) obviously dangerous or is simply
1359 * non-obvious
1360 */
1361 result = verifyAction();
1362
1363 /*
1364 * If the action can be performed, but can't be performed
1365 * implicitly, abort. Note that we only silently ignore
1366 * the action if it is allowed normally but not
1367 * implicitly: if it's not even allowed normally, we'll
1368 * simply fail later with the normal failure message,
1369 * since there's no harm in trying.
1370 */
1371 if (result != nil
1372 && result.allowAction
1373 && !result.allowImplicit)
1374 abortImplicit;
1375 }
1376
1377 /*
1378 * If this is an implicit command, display a message
1379 * indicating that we're performing the command.
1380 */
1381 impReport = maybeAnnounceImplicit();
1382
1383 /*
1384 * Make one or two passes through verifications and
1385 * preconditions. If any precondition performs an implicit
1386 * command, we must run everything a second time to ensure
1387 * that the implicit command or commands did not invalidate
1388 * any earlier precondition or a verification.
1389 *
1390 * Run verifications before preconditions, because there
1391 * would be no point in applying implicit commands from
1392 * preconditions if the command verifies as illogical in the
1393 * first place.
1394 */
1395 for (local iter = 1 ; iter <= 2 ; ++iter)
1396 {
1397 /* verify the action */
1398 result = verifyAction();
1399
1400 /*
1401 * if verification doesn't allow the command to proceed,
1402 * show the reason and end the command
1403 */
1404 if (result != nil && !result.allowAction)
1405 {
1406 /* show the result message */
1407 result.showMessage();
1408
1409 /* mark the command as a failure */
1410 gTranscript.noteFailure();
1411
1412 /*
1413 * if we have an implicit report, mark it as a mere
1414 * attempt, since the action can't be completed
1415 */
1416 if (impReport != nil)
1417 impReport.noteJustTrying();
1418
1419 /* terminate the command */
1420 exit;
1421 }
1422
1423 /*
1424 * Check preconditions of the action. If we don't invoke
1425 * any implicit commands, we can stop here: nothing in
1426 * the game state will have changed, so there is no need
1427 * to re-verify or re-check preconditions.
1428 *
1429 * Only allow implicit actions on the first pass. Do not
1430 * perform implicit actions on the second pass, because
1431 * if we did so we could get into an infinite loop of
1432 * conflicting preconditions, where each pass would
1433 * reverse the state from the last pass.
1434 */
1435 if (!checkPreConditions(iter == 1))
1436 break;
1437 }
1438
1439 /*
1440 * Disable sense caching once we start the action phase -
1441 * once we start making changes to game state, it's too much
1442 * work to figure out when to invalidate the cache, so simply
1443 * turn off caching entirely.
1444 *
1445 * Note that the sense cache will already be disabled if we
1446 * executed any implied commands, because the first implied
1447 * command will have disabled the cache as soon as it reached
1448 * its execution phase, and no one will have turned caching
1449 * back on. It does no harm to disable it again here.
1450 */
1451 libGlobal.disableSenseCache();
1452
1453 /* if desired, run the "before" notifications before "check" */
1454 if (gameMain.beforeRunsBeforeCheck)
1455 runBeforeNotifiers();
1456
1457 /*
1458 * Invoke the action's execution method. Catch any "exit
1459 * action" exceptions - these indicate that the action is
1460 * finished but that the rest of the command processing is to
1461 * proceed as normal.
1462 */
1463 try
1464 {
1465 /* notify the actor of what we're about to do */
1466 gActor.actorAction();
1467
1468 /* check the action */
1469 checkAction();
1470
1471 /* if desired, run the "before" notifications after "check" */
1472 if (!gameMain.beforeRunsBeforeCheck)
1473 runBeforeNotifiers();
1474
1475 /* execute the action */
1476 execAction();
1477 }
1478 catch (ExitActionSignal eaSig)
1479 {
1480 /*
1481 * an exit action signal was thrown - since we've now
1482 * skipped past any remaining action processing, simply
1483 * continue with the rest of the command processing as
1484 * normal
1485 */
1486 }
1487
1488 /* call afterAction for each object in the notify list */
1489 notifyBeforeAfter(&afterAction);
1490
1491 /* notify the actor's containers of the completed action */
1492 gActor.forEachContainer(callRoomAfterAction);
1493
1494 /* run the after-action processing */
1495 afterAction();
1496 }
1497 catch (ExitSignal exc)
1498 {
1499 /* the execution sequence is finished - simply stop here */
1500 }
1501 }
1502
1503 /*
1504 * Run the "before" notifiers: this calls beforeAction on everything
1505 * in scope, and calls roomBeforeAction on the actor's containers.
1506 */
1507 runBeforeNotifiers()
1508 {
1509 /* run the before-action processing */
1510 beforeAction();
1511
1512 /*
1513 * notify the actor's containers that an action is about
1514 * to take place within them
1515 */
1516 gActor.forEachContainer(callRoomBeforeAction);
1517
1518 /* call beforeAction for each object in the notify list */
1519 notifyBeforeAfter(&beforeAction);
1520 }
1521
1522 /*
1523 * Reset the message generation context for a sense change. This
1524 * can be called when something substantial happens in the midst of
1525 * a command, and we might need different message generation rules
1526 * before and after the change. For example, this is used when a
1527 * non-player character moves from one location to another, because
1528 * the NPC might want to generate leaving and arriving messages
1529 * differently in the two locations.
1530 */
1531 recalcSenseContext()
1532 {
1533 /* tell the sense context capturer to recalculate the context */
1534 senseContext.recalcSenseContext();
1535 }
1536
1537 /*
1538 * Maybe announce the action as an implied action.
1539 */
1540 maybeAnnounceImplicit()
1541 {
1542 /*
1543 * if we're a remapped action, we'll actually want to announce
1544 * the original, not the remapping
1545 */
1546 if (remappedFrom != nil)
1547 return remappedFrom.maybeAnnounceImplicit();
1548
1549 /*
1550 * if we're implicit, and we have an implicit announcement
1551 * message, announce the implicit action
1552 */
1553 if (isImplicit && implicitMsg != nil)
1554 return gTranscript.announceImplicit(self, implicitMsg);
1555
1556 /* we don't need to announce the implied action */
1557 return nil;
1558 }
1559
1560 /*
1561 * Announce the object of an action. This should be used for each
1562 * iteration of a command that takes objects to announce the objects
1563 * on this iteration.
1564 *
1565 * We announce an object under several circumstances:
1566 *
1567 * - If we are iterating through multiple objects, we'll show the
1568 * current object to show the player the individual step in the
1569 * command being performed.
1570 *
1571 * - If 'all' was used to specify the object, we'll announce it even
1572 * if only one object is involved, to make it clear to the player
1573 * exactly what we chose as a match.
1574 *
1575 * - If we are executing the command on a single object, and the
1576 * object was chosen through disambiguation of a set of ambiguous
1577 * choices, and some of the discarded possibilities were logical but
1578 * less so than the chosen object, we'll show the assumption we
1579 * made. In such cases, our assumption is not necessarily correct,
1580 * so we'll tell the user about our choice explicitly by way of
1581 * confirmation - this gives the user a better chance of noticing
1582 * quickly if our assumption was incorrect.
1583 *
1584 * - If we supplied a default for a missing noun phrase in the
1585 * player's command, we'll show what we chose. Since the player
1586 * didn't say what they meant, we'll make it plain that we're
1587 * providing an assumption about what we thought they must have
1588 * meant.
1589 *
1590 * 'info' is the ResolveInfo object describing this resolved object,
1591 * and 'numberInList' is the total number of objects we're iterating
1592 * over for this object function (direct object, indirect object,
1593 * etc). 'whichObj' is one of the object function constants
1594 * (DirectObject, IndirectObject, etc) describing which object we're
1595 * mentioning; the language-specific message generator might use
1596 * this in conjunction with the action to include a preposition with
1597 * the displayed phrase, for example, or choose an appropriate
1598 * inflection.
1599 */
1600 announceActionObject(info, numberInList, whichObj)
1601 {
1602 /*
1603 * Show prefix announcements only if the player character is
1604 * performing the action. For NPC's, we don't use the prefix
1605 * format, because it doesn't work as well for NPC result
1606 * reports; instead, the NPC versions of the library messages
1607 * tend to use sufficiently detailed reports that the prefix
1608 * isn't required (for example, "Bob takes the iron key" rather
1609 * than just "Taken").
1610 */
1611 if (gActor.isPlayerChar)
1612 {
1613 /* check for the various announcements */
1614 if (maybeAnnounceMultiObject(info, numberInList, whichObj))
1615 {
1616 /* we've done a multi announcement, so we're now done */
1617 }
1618 else if ((info.flags_ & UnclearDisambig) != 0
1619 || ((info.flags_ & ClearDisambig) != 0
1620 && gameMain.ambigAnnounceMode == AnnounceClear))
1621 {
1622 /* show the object, since we're not certain it's right */
1623 gTranscript.announceAmbigActionObject(info.obj_, whichObj);
1624 }
1625 else if ((info.flags_ & DefaultObject) != 0
1626 && !(info.flags_ & AnnouncedDefaultObject))
1627 {
1628 /*
1629 * Show the object, since we supplied it as a default.
1630 * At this stage in the command, we have resolved
1631 * everything.
1632 */
1633 gTranscript.announceDefaultObject(
1634 info.obj_, whichObj, self, true);
1635
1636 /* note that we've announced this object */
1637 info.flags_ |= AnnouncedDefaultObject;
1638 }
1639 }
1640 }
1641
1642 /* announce a multi-action object, if appropriate */
1643 maybeAnnounceMultiObject(info, numberInList, whichObj)
1644 {
1645 /*
1646 * announce if we have more than one object, or we're set to
1647 * announce this object in any case
1648 */
1649 if (numberInList > 1 || (info.flags_ & AlwaysAnnounce) != 0)
1650 {
1651 /* show the current object of a multi-object action */
1652 gTranscript.announceMultiActionObject(
1653 info.multiAnnounce, info.obj_, whichObj);
1654
1655 /* tell the caller we made an announcement */
1656 return true;
1657 }
1658
1659 /* tell the caller we didn't make an announcement */
1660 return nil;
1661 }
1662
1663 /*
1664 * Pre-calculate the multi-object announcement text for each object.
1665 * This is important because these announcements might choose a form
1666 * for the name that distinguishes it from the other objects in the
1667 * iteration, and the basis for distinction might be state-dependent
1668 * (such as the object's current owner or location), and the relevant
1669 * state might change as we iterate over the objects. From the
1670 * user's perspective, they're referring to the objects based on the
1671 * state at the start of the command, so the user will expect to see
1672 * names based on the that state.
1673 */
1674 cacheMultiObjectAnnouncements(lst, whichObj)
1675 {
1676 /* run through the list and cache each object's announcement */
1677 foreach (local cur in lst)
1678 {
1679 /* calculate and cache this object's multi-object announcement */
1680 cur.multiAnnounce = libMessages.announceMultiActionObject(
1681 cur.obj_, whichObj, self);
1682 }
1683 }
1684
1685 /* get the list of resolved objects in the given role */
1686 getResolvedObjList(which)
1687 {
1688 /*
1689 * the base action doesn't have any objects in any roles, so just
1690 * return nil; subclasses need to override this
1691 */
1692 return nil;
1693 }
1694
1695 /*
1696 * Announce a defaulted object list, if appropriate. We'll announce
1697 * the object if we have a single object in the given resolution
1698 * list, it was defaulted, and it hasn't yet been announced.
1699 */
1700 maybeAnnounceDefaultObject(lst, which, allResolved)
1701 {
1702 /*
1703 * if the list has exactly one element, and it's marked as a
1704 * defaulted object, and it hasn't yet been announced, announce
1705 * it
1706 */
1707 if (lst != nil
1708 && lst.length() == 1
1709 && (lst[1].flags_ & DefaultObject) != 0
1710 && !(lst[1].flags_ & AnnouncedDefaultObject))
1711 {
1712 /* announce the object */
1713 gTranscript.announceDefaultObject(
1714 lst[1].obj_, which, self, allResolved);
1715
1716 /*
1717 * we've now announced the object; mark it as announced so
1718 * we don't show the same announcement again
1719 */
1720 lst[1].flags_ |= AnnouncedDefaultObject;
1721 }
1722 }
1723
1724 /*
1725 * "Pre-announce" a common object for a command that might involve
1726 * iteration over other objects. For example, in "put all in box",
1727 * the box is common to all iterations of the command, so we would
1728 * want to preannounce it, if it needs to be announced at all,
1729 * before the iterations of the command.
1730 *
1731 * We'll announce the object only if it's marked as defaulted or
1732 * unclearly disambiguated, and then only if the other list will be
1733 * announcing its objects as multi-action objects. However, we do
1734 * not pre-announce anything for a remapped action, because we'll
1735 * show the full action description for each individually announced
1736 * object, so we don't need or want a separate announcement for the
1737 * group.
1738 *
1739 * Returns true if we did any pre-announcing, nil otherwise. If we
1740 * return true, the caller should not re-announce this object during
1741 * the iteration, since our pre-announcement is common to all
1742 * iterations.
1743 */
1744 preAnnounceActionObject(info, mainList, whichObj)
1745 {
1746 /* do not pre-announce anything for a remapped action */
1747 if (isRemapped())
1748 return nil;
1749
1750 /*
1751 * determine if the main list will be announcing its objects -
1752 * it will if it has more than one object, or if its one object
1753 * is marked as "always announce"
1754 */
1755 if (mainList.length() > 1
1756 || (mainList[1].flags_ & AlwaysAnnounce) != 0)
1757 {
1758 /*
1759 * we will be announcing the main list object or objects, so
1760 * definitely pre-announce this object if appropriate
1761 */
1762 announceActionObject(info, 1, whichObj);
1763
1764 /* tell the caller we pre-announced the object */
1765 return true;
1766 }
1767
1768 /* we didn't pre-announce the object */
1769 return nil;
1770 }
1771
1772 /*
1773 * Run our action-specific pre-processing. By default, we do
1774 * nothing here.
1775 */
1776 beforeAction()
1777 {
1778 }
1779
1780 /*
1781 * Check the action. This runs the 'check' phase, and must be
1782 * overridden for each subclass.
1783 *
1784 * Intransitive actions don't generally have to do anything in the
1785 * 'check' phase, since they can simply do any necessary checks in
1786 * the 'execute' phase that runs immediately after 'check'. This
1787 * phase is separated out from 'execute' mostly for the benefit of
1788 * transitive actions, where the 'check' phase gives the involved
1789 * objects a chance to object to the action.
1790 */
1791 checkAction() { }
1792
1793 /*
1794 * Execute the action. This must be overridden by each subclass.
1795 *
1796 * Intransitive actions must do all of their work in this routine.
1797 * In most cases, transitive actions will delegate processing to one
1798 * or more of the objects involved in the command - for example,
1799 * most single-object commands will call a method in the direct
1800 * object to carry out the command.
1801 */
1802 execAction()
1803 {
1804 /* by default, just show the 'no can do' message */
1805 mainReport(&cannotDoThatMsg);
1806 }
1807
1808 /*
1809 * Run our action-specific post-processing. By default, we do
1810 * nothing here.
1811 */
1812 afterAction()
1813 {
1814 }
1815
1816 /*
1817 * Verify the action. Action subclasses with one or more objects
1818 * should call object verification routines here. Returns a
1819 * VerifyResultList with the results, or nil if there are no
1820 * verification results at all. A nil return should be taken as
1821 * success, not failure, because it means that we found no objection
1822 * to the command.
1823 */
1824 verifyAction()
1825 {
1826 /*
1827 * there are no objects in the default action, but we might have
1828 * pre-condition verifiers
1829 */
1830 return callVerifyPreCond(nil);
1831 }
1832
1833 /*
1834 * Initialize tentative resolutions for other noun phrases besides
1835 * the one indicated.
1836 */
1837 initTentative(issuingActor, targetActor, whichObj)
1838 {
1839 /* by default, we have no noun phrases to tentatively resolve */
1840 }
1841
1842 /*
1843 * Check for remapping the action. This should check with each
1844 * resolved object involved in the command to see if the object wants
1845 * to remap the action to a new action; if it does, the object must
1846 * replace the current action (using replaceAction or equivalent).
1847 * Note that replacing the action must use 'exit' to terminate the
1848 * original action, so this will never return if remapping actually
1849 * does occur.
1850 */
1851 checkRemapping()
1852 {
1853 /* by default, we have no objects, so we do nothing here */
1854 }
1855
1856 /*
1857 * Invoke a callback with a verify results list in gVerifyResults,
1858 * using the existing results list or creating a new one if there is
1859 * no existing one. Returns the results list used.
1860 */
1861 withVerifyResults(resultsSoFar, obj, func)
1862 {
1863 local oldResults;
1864
1865 /* if we don't already have a result list, create one */
1866 if (resultsSoFar == nil)
1867 resultsSoFar = new VerifyResultList();
1868
1869 /* remember the old global results list */
1870 oldResults = gVerifyResults;
1871
1872 /* install the new one */
1873 gVerifyResults = resultsSoFar;
1874
1875 /* make sure we restore the old result list on the way out */
1876 try
1877 {
1878 /* invoke the callback */
1879 (func)();
1880 }
1881 finally
1882 {
1883 /* restore the old result list */
1884 gVerifyResults = oldResults;
1885 }
1886
1887 /* return the result list */
1888 return resultsSoFar;
1889 }
1890
1891 /*
1892 * Verify the non-object-related pre-conditions. This runs
1893 * verification on each of the pre-condition objects defined for the
1894 * action.
1895 */
1896 callVerifyPreCond(resultSoFar)
1897 {
1898 /* look at each of our preconditions */
1899 foreach (local cond in preCond)
1900 {
1901 /*
1902 * If this precondition defines a verifier, call it. Check
1903 * to see if we have a verifier defined first so that we can
1904 * avoid creating a result list if we won't have any use for
1905 * it.
1906 */
1907 if (cond.propDefined(&verifyPreCondition))
1908 {
1909 /*
1910 * invoke the pre-condition verifier - this is an
1911 * action-level verifier, so there's no object involved
1912 */
1913 resultSoFar = withVerifyResults(resultSoFar, nil,
1914 {: cond.verifyPreCondition(nil) });
1915 }
1916 }
1917
1918 /* return the latest result list */
1919 return resultSoFar;
1920 }
1921
1922 /*
1923 * Call a catch-all property on the given object.
1924 *
1925 * actionProp is the custom per-object/per-action property that we
1926 * normally invoke to process the action. For example, if we're
1927 * processing verification for the direct object of Take, this would
1928 * be &verifyDobjTake.
1929 *
1930 * defProp is the default property that corresponds to actionProp.
1931 * This is the per-object/default-action property that we invoke
1932 * when the object doesn't provide a "more specialized" version of
1933 * actionProp - that is, if the object doesn't define or inherit
1934 * actionProp at a point in its class hierarchy that is more
1935 * specialized than the point at which it defines defProp, we'll
1936 * call defProp. If there is a more specialized definition of
1937 * actionProp for the object, it effectively overrides the default
1938 * handler, so we do not invoke the default handler.
1939 *
1940 * allProp is the catch-all property corresponding to actionProp.
1941 * We invoke this property in all cases.
1942 *
1943 * Returns true if there is indeed a Default property that overrides
1944 * the action, nil if not.
1945 */
1946 callCatchAllProp(obj, actionProp, defProp, allProp)
1947 {
1948 /* always invoke the catch-all property first */
1949 obj.(allProp)();
1950
1951 /*
1952 * invoke the default property only if the object doesn't have a
1953 * "more specialized" version of actionProp
1954 */
1955 if (!obj.propHidesProp(actionProp, defProp))
1956 {
1957 /* the Default overrides the action-specific method */
1958 obj.(defProp)();
1959
1960 /* tell the caller the Default routine handled it */
1961 return true;
1962 }
1963 else
1964 {
1965 /* tell the caller to call the action-specific property */
1966 return nil;
1967 }
1968 }
1969
1970 /*
1971 * Call a verification routine. This creates a results object and
1972 * makes it active, then invokes the given verification routine on
1973 * the given object.
1974 *
1975 * We call verification directly on the object, and we also call
1976 * verification on the object's preconditions.
1977 *
1978 * If resultSoFar is non-nil, it is a VerifyResultList that has the
1979 * results so far - this can be used for multi-object verifications
1980 * to gather all of the verification results for all of the objects
1981 * into a single result list. If resultSoFar is nil, we'll create a
1982 * new result list.
1983 */
1984 callVerifyProp(obj, verProp, preCondProp, remapProp,
1985 resultSoFar, whichObj)
1986 {
1987 local remapInfo;
1988
1989 /* check for remapping */
1990 if ((remapInfo = obj.(remapProp)()) != nil)
1991 {
1992 /* call the remapped verify */
1993 resultSoFar = remapVerify(whichObj, resultSoFar, remapInfo);
1994
1995 /*
1996 * If the original object has a verify that effectively
1997 * "overrides" the remap - i.e., defined by an object that
1998 * inherits from the object where the remap is defined - then
1999 * run it by the overriding verify as well.
2000 */
2001 local remapSrc = obj.propDefined(remapProp, PropDefGetClass);
2002 if (obj.propDefined(verProp)
2003 && overrides(obj, remapSrc, verProp))
2004 {
2005 resultSoFar = withVerifyResults(
2006 resultSoFar, obj, function() { obj.(verProp)(); });
2007 }
2008
2009 /* return the results */
2010 return resultSoFar;
2011 }
2012
2013 /* initialize tentative resolutions for other noun phrases */
2014 initTentative(gIssuingActor, gActor, whichObj);
2015
2016 /*
2017 * run the verifiers in the presence of a results list, and
2018 * return the result list
2019 */
2020 return withVerifyResults(resultSoFar, obj, function()
2021 {
2022 local lst;
2023
2024 /*
2025 * check the object for a default or catch-all verifier, and
2026 * call it if present; if there isn't a default that
2027 * overrides the action-specific verifier, continue to the
2028 * action-specific verifer
2029 */
2030 if (!callCatchAllProp(
2031 obj, verProp, objectRelations.verifyDefaultProps[whichObj],
2032 objectRelations.verifyAllProps[whichObj]))
2033 {
2034 /*
2035 * invoke the action-specific verifier method - this
2036 * will update the global verification results object
2037 * with the appropriate status for this action being
2038 * performed on this object
2039 */
2040 obj.(verProp)();
2041 }
2042
2043 /*
2044 * Check the pre-conditions defined for this action on this
2045 * object. For each one that has a verifier, invoke the
2046 * verifier.
2047 */
2048 lst = getObjPreConditions(obj, preCondProp, whichObj);
2049 if (lst != nil)
2050 foreach (local cur in lst)
2051 cur.verifyPreCondition(obj);
2052 });
2053 }
2054
2055 /*
2056 * Get the precondition list for an object. whichObj is the object
2057 * role of the object whose preconditions we're retrieving; this is
2058 * nil if we're looking for action-level preconditions.
2059 */
2060 getObjPreConditions(obj, preCondProp, whichObj)
2061 {
2062 local allPreProp;
2063 local defPreProp;
2064 local pre;
2065
2066 /*
2067 * if we're looking for action preconditions, there are no
2068 * default or catch-all properties, so simply get the
2069 * preconditions from the action
2070 */
2071 if (whichObj == nil)
2072 return obj.(preCondProp);
2073
2074 /* get the default-action and catch-all precondition properties */
2075 defPreProp = objectRelations.preCondDefaultProps[whichObj];
2076 allPreProp = objectRelations.preCondAllProps[whichObj];
2077
2078 /*
2079 * Check for an "overriding" default-action handler. If we have
2080 * a default-action handler that hides the specific handler for
2081 * this action, use the default handler's precondition list
2082 * instead. Otherwise, use the specific action preconditions.
2083 */
2084 if (obj.propHidesProp(defPreProp, preCondProp))
2085 pre = obj.(defPreProp);
2086 else
2087 pre = obj.(preCondProp);
2088
2089 /* if we have catch-all preconditions, add them to the list */
2090 if (obj.propDefined(allPreProp))
2091 {
2092 /* get the catch-all preconditions */
2093 local allPre = obj.(allPreProp);
2094
2095 /* add them to the list so far (if any) */
2096 pre = (pre == nil ? allPre : pre + allPre);
2097 }
2098
2099 /* return the precondition list */
2100 return pre;
2101 }
2102
2103 /*
2104 * Verify that some sort of handling for this action is defined on
2105 * at least one of the given objects. If we have no handlers at all
2106 * definfed, we'll add an "illogical" status to the verification
2107 * results to indicate that the action is not defined on this
2108 * object. This check provides a last resort for verbs with no
2109 * handling at all defined on the involved objects, to ensure that
2110 * the verb won't go completely unprocessed.
2111 *
2112 * Each entry in objList is an object involved in the action. For
2113 * each entry in objList, there must be *THREE* entries in propList:
2114 * a verify property, a check property, and an action property. If
2115 * any of these three properties is defined on the corresponding
2116 * object, we'll allow the command to proceed. If we can find none
2117 * of the given handler properties on any of our objects, we'll add
2118 * an "illogical" verify result.
2119 */
2120 verifyHandlersExist(objList, propList, result)
2121 {
2122 /*
2123 * check each object to see if any define their corresponding
2124 * action property
2125 */
2126 for (local i = 1, local j = 1, local len = objList.length() ;
2127 i <= len ; ++i, j += 3)
2128 {
2129 /* check each of the associated handler properties */
2130 for (local k = 0 ; k < 3 ; ++k)
2131 {
2132 /* check this handler property */
2133 if (objList[i].propDefined(propList[j + k]))
2134 {
2135 /* we've found a handler, so we can proceed */
2136 return result;
2137 }
2138 }
2139 }
2140
2141 /*
2142 * None of the objects defines an appropriate action method, so
2143 * this verifies as illogical. If there's no result list so
2144 * far, create one.
2145 */
2146 if (result == nil)
2147 result = new VerifyResultList();
2148
2149 /* add an "illogical" status to the results */
2150 result.addResult(new IllogicalVerifyResult(&cannotDoThatMsg));
2151
2152 /* return the result */
2153 return result;
2154 }
2155
2156 /*
2157 * Call the beforeAction or afterAction method for each object in
2158 * the notification list.
2159 */
2160 notifyBeforeAfter(prop)
2161 {
2162 local lst;
2163
2164 /* get a table of potential notification receivers */
2165 lst = getNotifyTable();
2166
2167 /* go through the table and notify each object */
2168 lst.forEachAssoc({obj, val: obj.(prop)()});
2169 }
2170
2171 /*
2172 * Get the list of objects to notify before or after the action has
2173 * been performed.
2174 */
2175 getNotifyTable()
2176 {
2177 local tab;
2178 local curObjs;
2179 local actor;
2180
2181 /* stash the current actor in a local for faster reference */
2182 actor = gActor;
2183
2184 /* start with everything connected by containment to the actor */
2185 tab = actor.connectionTable();
2186
2187 /* add the actor's explicitly registered notification list */
2188 foreach (local cur in actor.getActorNotifyList())
2189 tab[cur] = true;
2190
2191 /* add the items explicitly registered in the actor's location(s) */
2192 actor.forEachContainer(
2193 {loc: loc.getRoomNotifyList().forEach(
2194 {obj: tab[obj] = true})
2195 });
2196
2197 /* get the list of objects directly involved in the command */
2198 curObjs = getCurrentObjects();
2199
2200 /*
2201 * add any objects explicitly registered with the objects
2202 * directly involved in the command
2203 */
2204 foreach (local cur in curObjs)
2205 {
2206 /* add each item in the object's notify list */
2207 foreach (local ncur in cur.getObjectNotifyList())
2208 tab[ncur] = true;
2209 }
2210
2211 /*
2212 * Remove from the list all of the actor's containers. These
2213 * will be notified via the more specific room notification
2214 * methods, so we don't want to send them generic notifiers as
2215 * well.
2216 */
2217 tab.forEachAssoc(function(obj, val)
2218 {
2219 if (actor.isIn(obj))
2220 tab.removeElement(obj);
2221 });
2222
2223 /* if we have any explicitly registered objects, add them */
2224 if (beforeAfterObjs != nil)
2225 {
2226 /* add each object in the list of explicitly registered objects */
2227 foreach (local cur in beforeAfterObjs)
2228 tab[cur] = true;
2229 }
2230
2231 /* return the final table */
2232 return tab;
2233 }
2234
2235 /*
2236 * Register an object for explicit inclusion in beforeAction and
2237 * afterAction notifications. This can be used to register objects
2238 * that might not be connected by containment or otherwise
2239 * notifiable by normal means. If this is called after the
2240 * beforeAction notification loop has already started, then the
2241 * object will only be sent an afterAction notification.
2242 */
2243 addBeforeAfterObj(obj)
2244 {
2245 /* if we don't yet have a before/after list, create one */
2246 if (beforeAfterObjs == nil)
2247 beforeAfterObjs = new Vector(16);
2248
2249 /* add the object to the list */
2250 beforeAfterObjs.append(obj);
2251 }
2252
2253 /* vector of objects requiring explicit before/after notification */
2254 beforeAfterObjs = nil
2255
2256 /*
2257 * Get the list of all of the objects (direct object, indirect
2258 * object, and any additional objects for actions with three or more
2259 * object roles) involved in the current execution. This is valid
2260 * only during a call to doActionOnce(), since that's the only time
2261 * a particular set of objects are selected for the action.
2262 *
2263 * By default, an action has no objects roles at all, so we'll just
2264 * return an empty list.
2265 */
2266 getCurrentObjects()
2267 {
2268 return [];
2269 }
2270
2271 /*
2272 * Set the current objects. This takes a list of the same form
2273 * returned by getCurrentObjects().
2274 */
2275 setCurrentObjects(lst) { }
2276
2277 /*
2278 * Check any pre-conditions for the action.
2279 *
2280 * This should check all of the conditions that must be met for the
2281 * action to proceed. If any pre-condition can be met by running an
2282 * implicit command first, that implicit command should be executed
2283 * here. If any pre-condition cannot be met, this routine should
2284 * notify the actor and throw an ExitSignal.
2285 *
2286 * Returns true if any implicit commands are executed, nil if not.
2287 * Implicit commands can only be attempted if allowImplicit is true;
2288 * if this is nil, a precondition must simply fail (by displaying an
2289 * appropriate failure report and using 'exit') without attempting
2290 * an implicit command if its assertion does not hold.
2291 */
2292 checkPreConditions(allowImplicit)
2293 {
2294 /* check each condition in our action preconditions */
2295 return callPreConditions(getPreCondDescList(), allowImplicit);
2296 }
2297
2298 /*
2299 * Get the precondition descriptor list for the action. For the base
2300 * intransitive action type, this simply returns the list of
2301 * conditions for the action itself.
2302 */
2303 getPreCondDescList()
2304 {
2305 /* get the action-level preconditions */
2306 return getObjPreCondDescList(self, &preCond, nil, nil);
2307 }
2308
2309 /*
2310 * Get a precondition descriptor list for the given object. This
2311 * returns a list of PreCondDesc objects that wrap the preconditions
2312 * for the given object in the given role for this action.
2313 */
2314 getObjPreCondDescList(obj, preCondProp, checkArg, whichObj)
2315 {
2316 local lst;
2317
2318 /* get the list of preconditions for the given object in its role */
2319 lst = getObjPreConditions(obj, preCondProp, whichObj);
2320
2321 /* if there are no preconditions, return an empty list */
2322 if (lst == nil)
2323 return [];
2324
2325 /*
2326 * wrap the precondition objects in descriptors, so that we can
2327 * keep track of the check argument that goes with these
2328 * preconditions
2329 */
2330 return lst.mapAll({x: new PreCondDesc(x, checkArg)});
2331 }
2332
2333 /*
2334 * Call a method on all of the precondition objects in the
2335 * precondition list obtained from the given property of the given
2336 * object.
2337 */
2338 callPreConditions(lst, allowImplicit)
2339 {
2340 local ret;
2341 local i;
2342
2343 /* presume we won't call any implicit commands */
2344 ret = nil;
2345
2346 /*
2347 * note the original descriptor list order, so that we can retain
2348 * the current ordering when the execution order doesn't require
2349 * changes
2350 */
2351 i = 0;
2352 lst.forEach({x: x.index_ = i++});
2353
2354 /* sort the precondition list by execution order */
2355 lst = lst.sort(SortAsc, function(a, b) {
2356 local delta;
2357
2358 /* if the execution orders differ, sort by execution order */
2359 delta = a.cond_.preCondOrder - b.cond_.preCondOrder;
2360 if (delta != 0)
2361 return delta;
2362
2363 /* otherwise, retain the original list order */
2364 return a.index_ - b.index_;
2365 });
2366
2367 /* catch any 'exit' signals within the preconditions */
2368 try
2369 {
2370 /* invoke the check method for each condition in the list */
2371 foreach (local cur in lst)
2372 {
2373 /*
2374 * call this precondition; if it runs an implicit
2375 * command, note that we have run an implicit command
2376 */
2377 if (cur.checkPreCondition(allowImplicit))
2378 ret = true;
2379 }
2380 }
2381 catch (ExitSignal es)
2382 {
2383 /*
2384 * any 'exit' that occurs within a precondition is a failure
2385 * for the enclosing action
2386 */
2387 gTranscript.noteFailure();
2388
2389 /* re-throw the 'exit' to cancel the enclosing action */
2390 throw es;
2391 }
2392
2393 /* return true if any implicit commands were executed */
2394 return ret;
2395 }
2396
2397 /*
2398 * Our list of action-level pre-condition objects. These are the
2399 * conditions that apply to the overall action, not to the
2400 * individual objects involved. (Object-level pre-conditions are
2401 * attached to the objects, not to the action.)
2402 */
2403 preCond = []
2404
2405 /*
2406 * Finish the result list for a resolved noun phrase. This is used
2407 * just before disambiguation. We'll give each object in the list a
2408 * chance to filter the list with filterResolveList, and we'll note
2409 * the noun phrase we matched in each resolved object.
2410 */
2411 finishResolveList(lst, whichObj, np, requiredNum)
2412 {
2413 /* give each object a chance to filter the list */
2414 foreach (local cur in lst)
2415 lst = cur.obj_.filterResolveList(
2416 lst, self, whichObj, np, requiredNum);
2417
2418 /* stash the noun phrase in each object in the list */
2419 foreach (local cur in lst)
2420 cur.np_ = np;
2421
2422 /* return the list */
2423 return lst;
2424 }
2425
2426 /*
2427 * Get a list of verification results for the given ResolveInfo
2428 * objects, sorted from best to worst. Each entry in the returned
2429 * list will be a VerifyResultList object whose obj_ property is set
2430 * to the ResolveInfo object for which it was generated.
2431 */
2432 getSortedVerifyResults(lst, verProp, preCondProp, remapProp,
2433 whichObj, np, requiredNum)
2434 {
2435 local results;
2436 local idx;
2437
2438 /* if there's nothing in the list, we're done */
2439 if (lst == [])
2440 return lst;
2441
2442 /*
2443 * Before we run verification, give each object in the list a
2444 * chance to do its own filtering on the entire list. This form
2445 * of filtering allows an object to act globally on the list, so
2446 * that it can take special action according to the presence or
2447 * absence of other objects, and can affect the presence of other
2448 * objects.
2449 */
2450 lst = finishResolveList(lst, whichObj, np, requiredNum);
2451
2452 /* create a vector to hold the verification results */
2453 results = new Vector(lst.length());
2454
2455 /*
2456 * Call the given verifier method on each object, noting each
2457 * result.
2458 */
2459 idx = 0;
2460 foreach (local cur in lst)
2461 {
2462 local curResult;
2463
2464 /* call the verifier method and note the current result */
2465 curResult = callVerifyProp(cur.obj_, verProp, preCondProp,
2466 remapProp, nil, whichObj);
2467
2468 /*
2469 * save the ResolveInfo in the verify result list object, so
2470 * that we can figure out later (after sorting the results)
2471 * which original ResolveInfo this verification result
2472 * applies to
2473 */
2474 curResult.obj_ = cur;
2475
2476 /* remember the original list order */
2477 curResult.origOrder = idx++;
2478
2479 /* add this verify result to our result vector */
2480 results.append(curResult);
2481 }
2482
2483 /*
2484 * Sort the results in descending order of logicalness, and
2485 * return the sorted list. When results are equivalently
2486 * logical, keep the results in their existing order.
2487 */
2488 return results.toList().sort(SortDesc, function(x, y)
2489 {
2490 /* compare the logicalness */
2491 local c = x.compareTo(y);
2492
2493 /*
2494 * if it's the same, keep in ascending pluralOrder - note
2495 * that we must reverse the sense of this comparison, since
2496 * we're sorting the overall list in descending order
2497 */
2498 if (c == 0)
2499 c = (y.obj_.obj_.pluralOrder - x.obj_.obj_.pluralOrder);
2500
2501 /* if they're otherwise the same, preserve the original order */
2502 if (c == 0)
2503 c = (y.origOrder - x.origOrder);
2504
2505 /* return the result */
2506 return c;
2507 });
2508 }
2509
2510 /*
2511 * Combine any remapped verify results in the given verify result
2512 * list. We will remove any result that was remapped to a different
2513 * object if and only if the target of the remapping appears in the
2514 * list and has the same results as the remapped original. When
2515 * objects are remapped in this fashion, they become effectively
2516 * equivalent for the purposes of this command, so we don't have to
2517 * distinguish between them for disambiguation or defaulting
2518 * purposes.
2519 */
2520 combineRemappedVerifyResults(lst, role)
2521 {
2522 /* scan each element in the list */
2523 for (local i = 1, local len = lst.length() ; i <= len ; ++i)
2524 {
2525 local cur = lst[i];
2526
2527 /* if this element has been remapped, consider it further */
2528 if (cur.remapTarget_ != nil)
2529 {
2530 local other;
2531
2532 /*
2533 * scan for another entry in the list that matches us
2534 * for remapping purposes
2535 */
2536 other = lst.indexWhich(
2537 {x: x != cur
2538 && cur.matchForCombineRemapped(x, self, role)});
2539
2540 /*
2541 * if we found another entry, delete the other entry,
2542 * since it is indistinguishable from this entry
2543 */
2544 if (other != nil)
2545 {
2546 /* remove this element from the list */
2547 lst -= cur;
2548
2549 /* adjust our list counters for the deletion */
2550 --i;
2551 --len;
2552 }
2553 }
2554 }
2555
2556 /* return the updated list */
2557 return lst;
2558 }
2559
2560 /*
2561 * Filter an ambiguous object list using the given verification
2562 * method. We call the given verification method on each object,
2563 * noting the result, then find the best (most logical) result in
2564 * the list. We reduce the set to the objects that all have the
2565 * same best value - everything else in the list is less logical, so
2566 * we discard it. This gives us a set of objects that are all of
2567 * equivalent likelihood and all of the best likelihood of all the
2568 * objects.
2569 *
2570 * This is the typical way that we disambiguate a list of objects,
2571 * but this is merely a service routine, so individual actions can
2572 * choose to use this or other mechanisms as appropriate.
2573 */
2574 filterAmbiguousWithVerify(lst, requiredNum, verProp,
2575 preCondProp, remapProp, whichObj, np)
2576 {
2577 local results;
2578 local discards;
2579 local keepers;
2580 local bestResult;
2581 local uniqueKeepers;
2582
2583 /* if there's nothing in the list, there's nothing to do */
2584 if (lst == [])
2585 return lst;
2586
2587 /* first, filter out redundant facets */
2588 lst = filterFacets(lst);
2589
2590 /*
2591 * Call the verifier method on each object, and sort the results
2592 * from best to worst.
2593 */
2594 results = getSortedVerifyResults(lst, verProp, preCondProp,
2595 remapProp, whichObj,
2596 np, requiredNum);
2597
2598 /* note the best result value */
2599 bestResult = results[1];
2600
2601 /*
2602 * ask the noun phrase to filter this list down to the ones it
2603 * wants to keep
2604 */
2605 keepers = np.getVerifyKeepers(results);
2606
2607 /*
2608 * Count the number of unique keepers - this is the number of
2609 * items in the keepers list that don't have any equivalents in
2610 * the keepers list.
2611 *
2612 * To calculate this number, start with the total number of
2613 * items in the list, and reduce it by one for each item with an
2614 * earlier equivalent in the list. Note that we only ignore
2615 * items with unique equivalents *earlier* in the list so that
2616 * we keep exactly one of each equivalent - if we ignored every
2617 * element with a unique equivalent elsewhere in the list, we'd
2618 * ignore every equivalent item, so we'd only count the items
2619 * with no equivalents at all.
2620 */
2621 uniqueKeepers = keepers.length();
2622 for (local i = 1, local cnt = keepers.length() ; i <= cnt ; ++i)
2623 {
2624 local eqIdx;
2625
2626 /* check for a unique equivalent earlier in the list */
2627 eqIdx = keepers.indexWhich(
2628 {x: x.obj_.obj_.isVocabEquivalent(keepers[i].obj_.obj_)});
2629 if (eqIdx != nil && eqIdx < i)
2630 {
2631 /*
2632 * this one has an earlier equivalent, so don't include
2633 * it in the unique item count
2634 */
2635 --uniqueKeepers;
2636 }
2637 }
2638
2639 /*
2640 * If we found more items to keep than were required by the
2641 * caller, we were not able to reduce the set to an unambiguous
2642 * subset. In this case, keep *all* of the items that are
2643 * logical.
2644 */
2645 if (uniqueKeepers > requiredNum)
2646 {
2647 local allAllowed;
2648
2649 /* filter so that we keep all of the logical results */
2650 allAllowed = results.subset({x: x.allowAction});
2651
2652 /* if that list is non-empty, use it as the keepers */
2653 if (allAllowed.length() != 0)
2654 keepers = allAllowed;
2655 }
2656
2657 /*
2658 * Get the list of discards - this is the balance of the
2659 * original result list after removing the best ones.
2660 */
2661 discards = results - keepers;
2662
2663 /*
2664 * We now have the set of objects we want, but the entries in
2665 * the list are all VerifyResultList instances, and we just want
2666 * the objects - pull out a list of just the ResolveInfo, and
2667 * return that.
2668 */
2669 keepers = keepers.mapAll({x: x.obj_});
2670
2671 /*
2672 * Check to see if we should set flags in the results. If we
2673 * eliminated any objects, flag the remaining objects as having
2674 * been selected through disambiguation. If the best of the
2675 * discarded objects were logical, flag the survivors as
2676 * "unclear," because we only selected them as better than the
2677 * discards, and not because they were the only possible
2678 * choices.
2679 */
2680 if (discards != [])
2681 {
2682 local addedFlags;
2683
2684 /*
2685 * We have reduced the set. If the best of the discards was
2686 * ranked as highly as the survivors at the coarsest level,
2687 * flag the survivors as having been "unclearly"
2688 * disambiguated; otherwise, mark them as "clearly"
2689 * disambiguated.
2690 */
2691 if (keepers.indexOf(bestResult.obj_) != nil
2692 && (discards[1].getEffectiveResult().resultRank ==
2693 bestResult.getEffectiveResult().resultRank))
2694 {
2695 /*
2696 * we had to make a choice that discarded possibilities
2697 * that were valid, though not as good as the one we
2698 * chose - mark the objects as being not perfectly clear
2699 */
2700 addedFlags = UnclearDisambig;
2701
2702 /*
2703 * if the keepers and the rejects are all basic
2704 * equivalents, don't bother flagging this as unclear,
2705 * since there's no point in mentioning that we chose
2706 * one basic equivalent over another, as they all have
2707 * the same name
2708 */
2709 if (BasicResolveResults.filterWithDistinguisher(
2710 keepers + discards.mapAll({x: x.obj_}),
2711 basicDistinguisher).length() == 1)
2712 {
2713 /* they're all basic equivalents - mark as clear */
2714 addedFlags = ClearDisambig;
2715 }
2716 }
2717 else
2718 {
2719 /* the choice is clear */
2720 addedFlags = ClearDisambig;
2721 }
2722
2723 /* add the flags to each survivor */
2724 foreach (local cur in keepers)
2725 cur.flags_ |= addedFlags;
2726 }
2727
2728 /* return the results */
2729 return keepers;
2730 }
2731
2732 /*
2733 * Filter a plural list with a verification method. We'll reduce
2734 * the list to the subset of objects that verify as logical, if
2735 * there are any. If there are no logical objects in the list,
2736 * we'll simply return the entire original list.
2737 */
2738 filterPluralWithVerify(lst, verProp, preCondProp, remapProp, whichObj, np)
2739 {
2740 local results;
2741
2742 /* if there's nothing in the list, there's nothing to do */
2743 if (lst == [])
2744 return lst;
2745
2746 /* first, filter out redundant facets */
2747 lst = filterFacets(lst);
2748
2749 /*
2750 * Call the verifier method on each object, and sort the results
2751 * from best to worst.
2752 */
2753 results = getSortedVerifyResults(lst, verProp, preCondProp,
2754 remapProp, whichObj, np, nil);
2755
2756 /*
2757 * If the best (and thus first) result allows the action, filter
2758 * the list to keep only the "keepers," as determined by the noun
2759 * phrase. Otherwise, there are no allowed results, so return
2760 * the original list.
2761 */
2762 if (results[1].allowAction)
2763 results = np.getVerifyKeepers(results);
2764
2765 /* return the resolve results objects from the list */
2766 return results.mapAll({x: x.obj_});
2767 }
2768
2769 /*
2770 * Filter out redundant facets of the same object. The various
2771 * facets of an object are equivalent to the parser. An object that
2772 * has multiple facets is meant to appear to be one game world
2773 * object from the perspective of a character - the multiple facet
2774 * objects are an internal implementation detail.
2775 */
2776 filterFacets(lst)
2777 {
2778 local result;
2779 local actor = gActor;
2780
2781 /*
2782 * create a vector for the result list, presuming we'll keep all
2783 * of the original list elements
2784 */
2785 result = new Vector(lst.length(), lst);
2786
2787 /* check for facets */
2788 foreach (local cur in lst)
2789 {
2790 local allFacets;
2791
2792 /* if this item has any facets, check for them in our results */
2793 allFacets = cur.obj_.getFacets() + cur.obj_;
2794 if (allFacets.length() != 0)
2795 {
2796 local inScopeFacets;
2797 local best;
2798
2799 /* make a new list of the facets that appear in the results */
2800 inScopeFacets = allFacets.subset(
2801 {f: result.indexWhich({r: r.obj_ == f}) != nil});
2802
2803 /* pick the best of those facets */
2804 best = findBestFacet(actor, inScopeFacets);
2805
2806 /*
2807 * remove all of the facets besides the best one from the
2808 * result list - this will ensure that we have only the
2809 * single best facet in the final results
2810 */
2811 foreach (local r in result)
2812 {
2813 /*
2814 * if this result list item is in the facet list, and
2815 * it's not the best facet, delete it from the result
2816 * list
2817 */
2818 if (r.obj_ != best
2819 && inScopeFacets.indexOf(r.obj_) != nil)
2820 result.removeElement(r);
2821 }
2822
2823 }
2824 }
2825
2826 /* return the result list */
2827 return result.toList();
2828 }
2829
2830 /*
2831 * Get a default object using the given verification method. We'll
2832 * start with the 'all' list, then use the verification method to
2833 * reduce the list to the most likely candidates. If we find a
2834 * unique most likely candidate, we'll return a ResolveInfo list
2835 * with that result; otherwise, we'll return nothing, since there is
2836 * no suitable default.
2837 */
2838 getDefaultWithVerify(resolver, verProp, preCondProp, remapProp,
2839 whichObj, np)
2840 {
2841 local lst;
2842 local results;
2843 local bestResult;
2844
2845 /*
2846 * Start with the 'all' list for this noun phrase. This is the
2847 * set of every object that we consider obviously suitable for
2848 * the command, so it's a good starting point to guess at a
2849 * default object.
2850 */
2851 lst = resolver.getAllDefaults();
2852
2853 /* eliminate objects that can't be defaults for this action */
2854 lst = lst.subset({x: !x.obj_.hideFromDefault(self)});
2855
2856 /*
2857 * reduce equivalent items to a single instance of each
2858 * equivalent - if we have several equivalent items that are
2859 * equally good as defaults, we can pick just one
2860 */
2861 lst = resolver.filterAmbiguousEquivalents(lst, np);
2862
2863 /* if we have no entries in the list, there is no default */
2864 if (lst == [])
2865 return nil;
2866
2867 /*
2868 * get the verification results for these objects, sorted from
2869 * best to worst
2870 */
2871 results = getSortedVerifyResults(lst, verProp, preCondProp,
2872 remapProp, whichObj, np, nil);
2873
2874 /* eliminate redundant remapped objects */
2875 results = combineRemappedVerifyResults(results, whichObj);
2876
2877 /* note the best result */
2878 bestResult = results[1];
2879
2880 /*
2881 * if the best item is not allowed as an implied object, there
2882 * is no default
2883 */
2884 if (!bestResult.allowImplicit)
2885 return nil;
2886
2887 /*
2888 * The best item must be uniquely logical in order to be a
2889 * default - if more than one item is equally good, it makes no
2890 * sense to assume anything about what the user meant. So, if
2891 * we have more than one item, and the second item is equally as
2892 * logical as the first item, we cannot supply a default. (The
2893 * second item cannot be better than the first item, because of
2894 * the sorting - at most, it can be equally good.)
2895 */
2896 if (results.length() != 1 && bestResult.compareTo(results[2]) == 0)
2897 return nil;
2898
2899 /*
2900 * We have a uniquely logical item, so we can assume the user
2901 * must have been referring to this item. Return the
2902 * ResolveInfo for this item (which the verify result sorter
2903 * stashed in the obj_ property of the verify result object).
2904 *
2905 * Before returning the list, clear the 'all' flag in the result
2906 * (getAll() set that flag), and replace it with the 'default'
2907 * flag, since the object is an implied default.
2908 */
2909 bestResult.obj_.flags_ &= ~MatchedAll;
2910 bestResult.obj_.flags_ |= DefaultObject;
2911
2912 /* return the result list */
2913 return [bestResult.obj_];
2914 }
2915
2916 /*
2917 * A synthesized Action (one that's generated by something other than
2918 * parsing a command line, such as an event action or nested action)
2919 * won't have a parser token list attached to it. If we're asked to
2920 * get the token list, we need to check for this possibility. If we
2921 * don't have a token list, but we do have a parent action, we'll
2922 * defer to the parent action. Otherwise, we'll simply return nil.
2923 */
2924 getOrigTokenList()
2925 {
2926 /* if we don't have a token list, look elsewhere */
2927 if (tokenList == nil)
2928 {
2929 /* if we have a parent action, defer to it */
2930 if (parentAction != nil)
2931 return parentAction.getOrigTokenList();
2932
2933 /* we have nowhere else to look, so return an empty list */
2934 return [];
2935 }
2936
2937 /* inherit the standard handling from BasicProd */
2938 return inherited();
2939 }
2940
2941 /*
2942 * Create a topic qualifier resolver. This type of resolver is used
2943 * for qualifier phrases (e.g., possessives) within topic phrases
2944 * within objects of this verb. Topics *usually* only apply to
2945 * TopicActionBase subclasses, but not exclusively: action remappings
2946 * can sometimes require a topic phrase from one action to be
2947 * resolved in the context of another action that wouldn't normally
2948 * involve a topic phrase. That's why this is needed on the base
2949 * Action class.
2950 */
2951 createTopicQualifierResolver(issuingActor, targetActor)
2952 {
2953 /* create and return a topic qualifier object resolver */
2954 return new TopicQualifierResolver(self, issuingActor, targetActor);
2955 }
2956
2957 /*
2958 * List of objects that verified okay on a prior pass. This is a
2959 * scratch-pad for use by verifier routines, to keep track of work
2960 * they've already done. A few verifiers use this as a way to
2961 * detect when an implicit action actually finished the entire job,
2962 * which would in many cases result in a verify failure if not
2963 * checked (because a command that effects conditions that already
2964 * hold is normally illogical); by tracking that the verification
2965 * previously succeeded, the verifier can know that the action
2966 * should be allowed to proceed and do nothing.
2967 */
2968 verifiedOkay = []
2969
2970 /*
2971 * Get the missing object response production for a given resolver
2972 * role. (The base action doesn't have any objects, so there's no
2973 * such thing as a missing object query.)
2974 */
2975 getObjResponseProd(resolver) { return nil; }
2976 ;
2977
2978 /*
2979 * Call the roomBeforeAction method on a given room's containing rooms,
2980 * then on the room itself.
2981 */
2982 callRoomBeforeAction(room)
2983 {
2984 /* first, call roomBeforeAction on the room's containers */
2985 room.forEachContainer(callRoomBeforeAction);
2986
2987 /* call roomBeforeAction on this room */
2988 room.roomBeforeAction();
2989 }
2990
2991 /*
2992 * Call the roomAfterAction method on a given room, then on the room's
2993 * containing rooms.
2994 */
2995 callRoomAfterAction(room)
2996 {
2997 /* first, call roomAfterAction on this room */
2998 room.roomAfterAction();
2999
3000 /* next, call roomAfterAction on the room's containers */
3001 room.forEachContainer(callRoomAfterAction);
3002 }
3003
3004 /* ------------------------------------------------------------------------ */
3005 /*
3006 * Intransitive Action class - this is an action that takes no objects.
3007 * In general, each subclass should implement its action handling in its
3008 * execAction() method.
3009 */
3010 class IAction: Action
3011 /*
3012 * resolve my noun phrases to objects
3013 */
3014 resolveNouns(issuingActor, targetActor, results)
3015 {
3016 /*
3017 * We have no objects to resolve. The only thing we have to do
3018 * is note in the results our number of structural noun slots
3019 * for the verb, which is zero, since we have no objects at all.
3020 */
3021 results.noteNounSlots(0);
3022 }
3023
3024 /*
3025 * Execute the action.
3026 */
3027 doActionMain()
3028 {
3029 /*
3030 * we have no objects to iterate, so simply run through the
3031 * execution sequence once
3032 */
3033 doActionOnce();
3034 }
3035 ;
3036
3037 /* ------------------------------------------------------------------------ */
3038 /*
3039 * "All" and "Default" are a pseudo-actions used for dobjFor(All),
3040 * iobjFor(Default), and similar catch-all handlers. These are never
3041 * executed as actual actions, but we define them so that dobjFor(All)
3042 * and the like won't generate any warnings for undefined actions.
3043 */
3044 class AllAction: object
3045 ;
3046 class DefaultAction: object
3047 ;
3048
3049 /* ------------------------------------------------------------------------ */
3050 /*
3051 * Transitive Action class - this is an action that takes a direct
3052 * object.
3053 *
3054 * For simplicity, this object is its own object resolver - we really
3055 * don't need a separate resolver object because we have only one object
3056 * list for this verb. (In contrast, an action with both a direct and
3057 * indirect object might need separate resolution rules for the two
3058 * objects, and hence would need separate resolver objects for the two.)
3059 *
3060 * The advantage of implementing the Resolver behavior in this object,
3061 * rather than using a separate object, is that it's less trouble to
3062 * override object resolution rules - simply override the resolver
3063 * methods in the subclass where you define the grammar rule for the
3064 * action.
3065 */
3066 class TAction: Action, Resolver
3067 construct()
3068 {
3069 /* inherit only the Action constructor */
3070 inherited Action.construct();
3071 }
3072
3073 resetAction()
3074 {
3075 /* inherit default handling */
3076 inherited();
3077
3078 /* discard our cached resolver */
3079 dobjResolver_ = nil;
3080 }
3081
3082 /*
3083 * Create an action for retrying an original action with changes.
3084 */
3085 createForRetry(orig)
3086 {
3087 local action;
3088
3089 /* create the new action based on the original action */
3090 action = createActionFrom(orig);
3091
3092 /*
3093 * do not include the new command in undo, since it's merely
3094 * part of the enclosing explicit command
3095 */
3096 action.includeInUndo = nil;
3097
3098 /* mark the action as nested */
3099 action.setNested();
3100
3101 /*
3102 * Even if the original action is implicit, don't announce this
3103 * action as implicit, because it's good enough to have
3104 * announced the original implicit action. Now, this new
3105 * command actually still is implicit if the original was - we
3106 * simply don't want to announce it as such. To suppress the
3107 * extra announcement while still retaining the rest of the
3108 * desired implicitness, simply set the implicitMsg property of
3109 * the new action to nil; when there's no implicitMsg, there's
3110 * no announcement.
3111 */
3112 action.implicitMsg = nil;
3113
3114 /* return the new action */
3115 return action;
3116 }
3117
3118 /*
3119 * Retry an intransitive action as a single-object action. We'll
3120 * obtain a indirect object using the normal means (first looking
3121 * for a default, then prompting the player if we can't find a
3122 * suitable default). 'orig' is the original zero-object action.
3123 *
3124 * This routine terminates with 'exit' if it doesn't throw some
3125 * other error.
3126 */
3127 retryWithMissingDobj(orig, asker)
3128 {
3129 /* resolve and execute the replacement action */
3130 resolveAndReplaceAction(createForMissingDobj(orig, asker));
3131 }
3132
3133 /*
3134 * Retry an action as a single-object action with an ambiguous
3135 * direct object. We'll ask which of the given possible objects is
3136 * intended.
3137 */
3138 retryWithAmbiguousDobj(orig, objs, asker, objPhrase)
3139 {
3140 local action;
3141 local resolver;
3142
3143 /* create a missing-direct-object replacement action */
3144 action = createForMissingDobj(orig, asker);
3145
3146 /* reduce the object list to the objects in scope */
3147 resolver = action.getDobjResolver(gIssuingActor, gActor, true);
3148 objs = objs.subset({x: resolver.objInScope(x)});
3149
3150 /* plug in the ambiguous direct object list */
3151 action.dobjMatch = new PreResolvedAmbigProd(objs, asker, objPhrase);
3152
3153 /* resolve and execute the replacement action */
3154 resolveAndReplaceAction(action);
3155 }
3156
3157 /*
3158 * Test to see if askForDobj() would find a default direct object.
3159 * Returns true if there's a default, nil if not. If this returns
3160 * true, then askForDobj() will simply take the default and proceed;
3161 * otherwise, it will have to actually ask the user for the missing
3162 * information.
3163 */
3164 testRetryDefaultDobj(orig)
3165 {
3166 /* create the new action for checking for a direct object */
3167 local action = createForMissingDobj(orig, ResolveAsker);
3168
3169 /* get the default dobj */
3170 local def = action.getDefaultDobj(
3171 action.dobjMatch,
3172 action.getDobjResolver(gIssuingActor, gActor, nil));
3173
3174 /* if there's exactly one result, then we have a default */
3175 return (def != nil && def.length() == 1);
3176 }
3177
3178 /*
3179 * Create an instance of this action for retrying a given
3180 * single-object action with a missing direct object.
3181 */
3182 createForMissingDobj(orig, asker)
3183 {
3184 /* create the action for a retry */
3185 local action = createForRetry(orig);
3186
3187 /* use an empty noun phrase for the new action's direct object */
3188 action.dobjMatch = new EmptyNounPhraseProd();
3189
3190 /* set our custom response production and ResolveAsker */
3191 action.dobjMatch.setPrompt(action.askDobjResponseProd, asker);
3192
3193 /* initialize the new action with any pre-resolved parts */
3194 action.initForMissingDobj(orig);
3195
3196 /* return the new action */
3197 return action;
3198 }
3199
3200 /*
3201 * Initialize this action in preparation for retrying with a missing
3202 * direct object. This routine must copy any phrases from the
3203 * original action that have already been resolved. This base
3204 * TAction implementation obviously can't have anything pre-resolved
3205 * in the original, since the original must simply be an IAction.
3206 * Subclasses must override as appropriate for the kinds of base
3207 * actions from which they can be retried.
3208 */
3209 initForMissingDobj(orig) { }
3210
3211 /*
3212 * The root production to use to parse missing direct object
3213 * responses. By default, this is nounList, but individual actions
3214 * can override this as appropriate.
3215 *
3216 * Note that language modules might want to override this to allow
3217 * for special responses. For example, in English, some verbs might
3218 * want to override this with a specialized production that allows
3219 * the appropriate preposition in the response.
3220 */
3221 askDobjResponseProd = nounList
3222
3223 /* get the missing object response production for a given role */
3224 getObjResponseProd(resolver)
3225 {
3226 /* if it's the direct object, return the dobj response prod */
3227 if (resolver.whichObject == DirectObject)
3228 return askDobjResponseProd;
3229
3230 /* otherwise use the default handling */
3231 return inherited(resolver);
3232 }
3233
3234 /*
3235 * Can the direct object potentially resolve to the given simulation
3236 * object? This only determines if the object is a *syntactic*
3237 * match, meaning that it can match at a vocabulary and grammar
3238 * level. This doesn't test it for logicalness or check that it's an
3239 * otherwise valid resolution.
3240 */
3241 canDobjResolveTo(obj)
3242 {
3243 /* check our dobj match tree to see if it can resolve to 'obj' */
3244 return dobjMatch.canResolveTo(
3245 obj, self, issuer_, actor_, DirectObject);
3246 }
3247
3248 /*
3249 * Resolve objects. This is called at the start of command
3250 * execution to resolve noun phrases in the command to specific
3251 * objects.
3252 */
3253 resolveNouns(issuingActor, targetActor, results)
3254 {
3255 /* note that we have a single noun slot (the direct object) */
3256 results.noteNounSlots(1);
3257
3258 /*
3259 * Ask the direct object noun phrase list to resolve itself, and
3260 * store the resulting object list. Since we're starting a
3261 * resolution pass through our objects, reset the resolver if
3262 * we're reusing it.
3263 */
3264 dobjList_ = dobjMatch.resolveNouns(
3265 getDobjResolver(issuingActor, targetActor, true), results);
3266 }
3267
3268 /* a transitive action has one noun phrase: the direct object */
3269 predicateNounPhrases = [&dobjMatch]
3270
3271 /* get the role of an object */
3272 getRoleFromIndex(idx)
3273 {
3274 /* we only take a single object role - the direct object */
3275 return (idx == 1 ? DirectObject : inherited(idx));
3276 }
3277
3278 /* get the resolved object in a given role */
3279 getObjectForRole(role)
3280 {
3281 /* return the direct object if requested */
3282 return (role == DirectObject ? getDobj() : inherited(role));
3283 }
3284
3285 /* get the match tree for the noun phrase in the given role */
3286 getMatchForRole(role)
3287 {
3288 /* return the direct object match tree if requested */
3289 return (role == DirectObject ? dobjMatch : inherited(role));
3290 }
3291
3292 /* get the 'verify' property for a given object role */
3293 getVerifyPropForRole(role)
3294 {
3295 return (role == DirectObject ? verDobjProp : inherited(role));
3296 }
3297
3298 /* get the 'preCond' property for a given object role */
3299 getPreCondPropForRole(role)
3300 {
3301 return (role == DirectObject ? preCondDobjProp : inherited(role));
3302 }
3303
3304 /* get the 'remap' property for a given object role */
3305 getRemapPropForRole(role)
3306 {
3307 return (role == DirectObject ? remapDobjProp : inherited(role));
3308 }
3309
3310 /* get the ResolveInfo for the given object */
3311 getResolveInfo(obj, oldRole)
3312 {
3313 local info = nil;
3314
3315 /* scan our resolved direct object list for the given object */
3316 if (dobjList_ != nil)
3317 info = dobjList_.valWhich({x: x.obj_ == obj});
3318
3319 /* if we didn't find one, create one from scratch */
3320 if (info == nil)
3321 {
3322 /*
3323 * if there's anything in the old dobj role, copy the flags
3324 * and noun phrase to the new role
3325 */
3326 if (dobjList_.length() > 0)
3327 {
3328 /* get the flags and noun phrase from the old role */
3329 info = new ResolveInfo(
3330 obj, dobjList_[1].flags_, dobjList_[1].np_);
3331 }
3332 else
3333 {
3334 /* there's no old role, so start from scratch */
3335 info = new ResolveInfo(obj, 0, nil);
3336 }
3337 }
3338
3339 /* return what we found (or created) */
3340 return info;
3341 }
3342
3343 /* get the list of resolved objects in the given role */
3344 getResolvedObjList(which)
3345 {
3346 return (which == DirectObject ? getResolvedDobjList()
3347 : inherited(which));
3348 }
3349
3350 /* get the list of resolved direct objects */
3351 getResolvedDobjList()
3352 {
3353 /*
3354 * if we have a direct object list, return the objects from it;
3355 * otherwise, return an empty list
3356 */
3357 return (dobjList_ == nil ? nil : dobjList_.mapAll({x: x.obj_}));
3358 }
3359
3360 /* manually set the resolved objects - we'll set the direct object */
3361 setResolvedObjects(dobj)
3362 {
3363 /* set the resolved direct object */
3364 setResolvedDobj(dobj);
3365 }
3366
3367 /* set the resolved direct object */
3368 setResolvedDobj(dobj)
3369 {
3370 /*
3371 * set the direct object tree to a fake grammar tree that
3372 * resolves to our single direct object, in case we're asked to
3373 * resolve explicitly
3374 */
3375 dobjMatch = new PreResolvedProd(dobj);
3376
3377 /*
3378 * Set the resolved direct object list to the single object or
3379 * to the list of objects, depending on what we received.
3380 */
3381 dobjList_ = makeResolveInfoList(dobj);
3382
3383 /* set the current object as well */
3384 dobjCur_ = (dobjList_.length() > 0 ? dobjList_[1].obj_ : nil);
3385 dobjInfoCur_ = (dobjList_.length() > 0 ? dobjList_[1] : nil);
3386 }
3387
3388 /* manually set the unresolved object noun phrase match trees */
3389 setObjectMatches(dobj)
3390 {
3391 /*
3392 * if it's a ResolveInfo, handle it as a resolved object;
3393 * otherwise handle it as a match tree to be resolved
3394 */
3395 if (dobj.ofKind(ResolveInfo))
3396 setResolvedDobj(dobj);
3397 else
3398 dobjMatch = dobj;
3399 }
3400
3401 /* check that the resolved objects are in scope */
3402 resolvedObjectsInScope()
3403 {
3404 /* check the direct object */
3405 return getDobjResolver(gIssuingActor, gActor, true)
3406 .objInScope(dobjList_[1].obj_);
3407 }
3408
3409 /*
3410 * Get a message parameter object for the action. We define 'dobj'
3411 * as the direct object, in addition to any inherited targets.
3412 */
3413 getMessageParam(objName)
3414 {
3415 switch(objName)
3416 {
3417 case 'dobj':
3418 /* return the current direct object */
3419 return dobjCur_;
3420
3421 default:
3422 /* inherit default handling */
3423 return inherited(objName);
3424 }
3425 }
3426
3427 /*
3428 * Execute the action. We'll run through the execution sequence
3429 * once for each resolved direct object.
3430 */
3431 doActionMain()
3432 {
3433 /*
3434 * Set the direct object list as the antecedent, using the
3435 * language-specific pronoun setter. Don't set pronouns for a
3436 * nested command, because the player didn't necessarily refer to
3437 * the objects in a nested command.
3438 */
3439 if (parentAction == nil)
3440 gActor.setPronoun(dobjList_);
3441
3442 /* we haven't yet canceled the iteration */
3443 iterationCanceled = nil;
3444
3445 /* pre-calculate the multi-object announcement text for each dobj */
3446 cacheMultiObjectAnnouncements(dobjList_, DirectObject);
3447
3448 /* run through the sequence once for each direct object */
3449 for (local i = 1, local len = dobjList_.length() ;
3450 i <= len && !iterationCanceled ; ++i)
3451 {
3452 /* make this object our current direct object */
3453 dobjCur_ = dobjList_[i].obj_;
3454 dobjInfoCur_ = dobjList_[i];
3455
3456 /* announce the object if appropriate */
3457 announceActionObject(dobjList_[i], len, whichMessageObject);
3458
3459 /* run the execution sequence for the current direct object */
3460 doActionOnce();
3461
3462 /* if we're top-level, count the iteration in the transcript */
3463 if (parentAction == nil)
3464 gTranscript.newIter();
3465 }
3466 }
3467
3468 /* get the precondition descriptor list for the action */
3469 getPreCondDescList()
3470 {
3471 /*
3472 * return the inherited preconditions plus the conditions that
3473 * apply to the direct object
3474 */
3475 return inherited()
3476 + getObjPreCondDescList(dobjCur_, preCondDobjProp, dobjCur_,
3477 DirectObject);
3478 }
3479
3480 /*
3481 * Get the list of active objects. We have only a direct object, so
3482 * we'll return a list with the current direct object.
3483 */
3484 getCurrentObjects()
3485 {
3486 return [dobjCur_];
3487 }
3488
3489 /* set the current objects */
3490 setCurrentObjects(lst)
3491 {
3492 dobjCur_ = lst[1];
3493 dobjInfoCur_ = nil;
3494 }
3495
3496 /*
3497 * Verify the action.
3498 */
3499 verifyAction()
3500 {
3501 local result;
3502
3503 /* invoke any general (non-object) pre-condition verifiers */
3504 result = callVerifyPreCond(nil);
3505
3506 /*
3507 * invoke the verifier routine ("verXxx") on the current direct
3508 * object and return the result
3509 */
3510 result = callVerifyProp(dobjCur_, verDobjProp, preCondDobjProp,
3511 remapDobjProp, result, DirectObject);
3512
3513 /* verify that the action routine ("doXxx") exists on the object */
3514 return verifyHandlersExist(
3515 [dobjCur_], [verDobjProp, actionDobjProp, checkDobjProp],
3516 result);
3517 }
3518
3519 /* initialize tentative resolutions for other noun phrases */
3520 initTentative(issuingActor, targetActor, whichObj)
3521 {
3522 /*
3523 * we have only one noun phrase, so there's nothing else to
3524 * tentatively resolve
3525 */
3526 }
3527
3528 /*
3529 * Check for remapping
3530 */
3531 checkRemapping()
3532 {
3533 local remapInfo;
3534
3535 /* check for remapping in the direct object */
3536 if ((remapInfo = dobjCur_.(remapDobjProp)) != nil)
3537 {
3538 /*
3539 * we have a remapping, so apply it - note that this won't
3540 * return, since this will completely replace the command
3541 * and thus terminate the old command with 'exit'
3542 */
3543 remapAction(nil, DirectObject, remapInfo);
3544 }
3545 }
3546
3547 /*
3548 * Check the command.
3549 *
3550 * For a single-object transitive action, this runs the catch-all
3551 * 'check' properties (the dobjFor(Default) and dobjFor(All) 'check'
3552 * methods) on the direct object, then calls the individual 'check'
3553 * routine for this specific action.
3554 */
3555 checkAction()
3556 {
3557 try
3558 {
3559 /* call the catch-all 'check' properties */
3560 if (!callCatchAllProp(dobjCur_, checkDobjProp,
3561 &checkDobjDefault, &checkDobjAll))
3562 {
3563 /*
3564 * the action-specific check routine overrides any
3565 * Default catch-all, so call the direct object's check
3566 * routine (its "checkXxx") method
3567 */
3568 dobjCur_.(checkDobjProp)();
3569 }
3570 }
3571 catch (ExitSignal es)
3572 {
3573 /* mark the action as a failure in the transcript */
3574 gTranscript.noteFailure();
3575
3576 /* re-throw the signal */
3577 throw es;
3578 }
3579 }
3580
3581 /*
3582 * Execute the command.
3583 */
3584 execAction()
3585 {
3586 /* call the catch-all 'action' properties */
3587 if (!callCatchAllProp(dobjCur_, actionDobjProp,
3588 &actionDobjDefault, &actionDobjAll))
3589 {
3590 /*
3591 * the verb-specific 'action' handler overrides any Default
3592 * action handler, so call the verb-specific 'action'
3593 * routine in the direct object (the "doXxx" method)
3594 */
3595 dobjCur_.(actionDobjProp)();
3596 }
3597 }
3598
3599 /*
3600 * The direct object preconditions, verifier, remapper, check, and
3601 * action methods for this action. Each concrete action must define
3602 * these appropriately. By convention, the methods are named like
3603 * so:
3604 *
3605 *. preconditions: preCondDobjAction
3606 *. verifier: verDobjAction
3607 *. remap: remapDobjAction
3608 *. check: checkDobjAction
3609 *. action: actionDobjAction
3610 *
3611 * where the 'Action' suffix is replaced by the name of the action.
3612 * The DefineTAction macro applies this convention, so in most cases
3613 * library and game authors will never have to create all of those
3614 * property names manually.
3615 */
3616 verDobjProp = nil
3617 preCondDobjProp = nil
3618 remapDobjProp = nil
3619 checkDobjProp = nil
3620 actionDobjProp = nil
3621
3622 /*
3623 * Get my direct object resolver. If I don't already have one,
3624 * create one and cache it; if I've already cached one, return it.
3625 * Note that we cache the resolver because it can sometimes take a
3626 * bit of work to set one up (the scope list can in some cases be
3627 * complicated to calculate). We use the resolver only during the
3628 * object resolution phase; since game state can't change during
3629 * this phase, it's safe to keep a cached copy.
3630 */
3631 getDobjResolver(issuingActor, targetActor, reset)
3632 {
3633 /* create a new resolver if we don't already have one cached */
3634 if (dobjResolver_ == nil)
3635 dobjResolver_ = createDobjResolver(issuingActor, targetActor);
3636
3637 /* reset the resolver if desired */
3638 if (reset)
3639 dobjResolver_.resetResolver();
3640
3641 /* return it */
3642 return dobjResolver_;
3643 }
3644
3645 /*
3646 * Create a resolver for the direct object. By default, we are our
3647 * own resolver. Some actions might want to override this to create
3648 * and return a specialized resolver instance if special resolution
3649 * rules are needed.
3650 */
3651 createDobjResolver(issuingActor, targetActor)
3652 {
3653 /* initialize myself as a resolver */
3654 initResolver(issuingActor, targetActor);
3655
3656 /* return myself */
3657 return self;
3658 }
3659
3660 /*
3661 * Does this action allow "all" to be used in noun phrases? By
3662 * default, we allow it or not according to a gameMain property.
3663 *
3664 * Note that the inventory management verbs (TAKE, TAKE FROM, DROP,
3665 * PUT IN, PUT ON) override this to allow "all" to be used, so
3666 * disallowing "all" here (or via gameMain) won't disable "all" for
3667 * those verbs.
3668 */
3669 actionAllowsAll = (gameMain.allVerbsAllowAll)
3670
3671 /*
3672 * Resolve 'all' for the direct object, given a list of everything
3673 * in scope. By default, we'll simply return everything in scope;
3674 * some actions might want to override this to return a more
3675 * specific list of objects suitable for 'all'.
3676 */
3677 getAllDobj(actor, scopeList)
3678 {
3679 return scopeList;
3680 }
3681
3682 /* filter an ambiguous direct object noun phrase */
3683 filterAmbiguousDobj(lst, requiredNum, np)
3684 {
3685 /* filter using the direct object verifier method */
3686 return filterAmbiguousWithVerify(lst, requiredNum, verDobjProp,
3687 preCondDobjProp, remapDobjProp,
3688 DirectObject, np);
3689 }
3690
3691 /* filter a plural phrase */
3692 filterPluralDobj(lst, np)
3693 {
3694 /* filter using the direct object verifier method */
3695 return filterPluralWithVerify(lst, verDobjProp, preCondDobjProp,
3696 remapDobjProp, DirectObject, np);
3697 }
3698
3699 /* get the default direct object */
3700 getDefaultDobj(np, resolver)
3701 {
3702 /* get a default direct object using the verify method */
3703 return getDefaultWithVerify(resolver, verDobjProp, preCondDobjProp,
3704 remapDobjProp, DirectObject, np);
3705 }
3706
3707 /* get the current direct object of the command */
3708 getDobj() { return dobjCur_; }
3709
3710 /* get the full ResolveInfo associated with the current direct object */
3711 getDobjInfo() { return dobjInfoCur_; }
3712
3713 /* get the object resolution flags for the direct object */
3714 getDobjFlags() { return dobjInfoCur_ != nil ? dobjInfoCur_.flags_ : 0; }
3715
3716 /* get the number of direct objects */
3717 getDobjCount() { return dobjList_ != nil ? dobjList_.length() : 0; }
3718
3719 /* get the original token list of the current direct object phrase */
3720 getDobjTokens()
3721 {
3722 return dobjInfoCur_ != nil && dobjInfoCur_.np_ != nil
3723 ? dobjInfoCur_.np_.getOrigTokenList() : nil;
3724 }
3725
3726 /* get the original words (as a list of strings) of the current dobj */
3727 getDobjWords()
3728 {
3729 local l = getDobjTokens();
3730 return l != nil ? l.mapAll({x: getTokOrig(x)}) : nil;
3731 }
3732
3733 /* the predicate must assign the direct object production tree here */
3734 dobjMatch = nil
3735
3736 /* my resolved list of direct objects */
3737 dobjList_ = []
3738
3739 /*
3740 * The resolved direct object on which we're currently executing the
3741 * command. To execute the command, we iterate through the direct
3742 * object list, calling the execution sequence for each object in
3743 * the list. We set this to the current object in each iteration.
3744 */
3745 dobjCur_ = nil
3746
3747 /* the full ResolveInfo associated with dobjCur_ */
3748 dobjInfoCur_ = nil
3749
3750 /* my cached direct object resolver */
3751 dobjResolver_ = nil
3752
3753 /* -------------------------------------------------------------------- */
3754 /*
3755 * Resolver interface implementation - for the moment, we don't need
3756 * any special definitions here, since the basic Resolver
3757 * implementation (which we inherit) is suitable for a single-object
3758 * action.
3759 */
3760
3761 /* -------------------------------------------------------------------- */
3762 /*
3763 * private Resolver implementation details
3764 */
3765
3766 /*
3767 * Initialize me as a resolver.
3768 */
3769 initResolver(issuingActor, targetActor)
3770 {
3771 /* remember the actors */
3772 issuer_ = issuingActor;
3773 actor_ = targetActor;
3774
3775 /* I'm the action as well as the resolver */
3776 action_ = self;
3777
3778 /* cache the actor's default scope list */
3779 cacheScopeList();
3780 }
3781
3782 /* issuing actor */
3783 issuer_ = nil
3784
3785 /* target actor */
3786 actor_ = nil
3787
3788 /*
3789 * By default, our direct object plays the direct object role in
3790 * generated messages. Subclasses can override this if the resolved
3791 * object is to play a different role. Note that this only affects
3792 * generated messages; for parsing purposes, our object is always in
3793 * the DirectObject role.
3794 */
3795 whichMessageObject = DirectObject
3796 ;
3797
3798
3799 /* ------------------------------------------------------------------------ */
3800 /*
3801 * "Tentative" noun resolver results gather. This type of results
3802 * gatherer is used to perform a tentative pre-resolution of an object
3803 * of a multi-object action.
3804 *
3805 * Consider what happens when we resolve a two-object action, such as
3806 * "put <dobj> in <iobj>". Since we have two objects, we obviously must
3807 * resolve one object or the other first; but this means that we must
3808 * resolve one object with no knowledge of the resolution of the other
3809 * object. This often makes it very difficult to resolve that first
3810 * object intelligently, because we'd really like to know something
3811 * about the other object. For example, if we first resolve the iobj of
3812 * "put <dobj> in <iobj>", it would be nice to know which dobj we're
3813 * talking about, since we could reduce the likelihood that the iobj is
3814 * the dobj's present container.
3815 *
3816 * Tentative resolution addresses this need by giving us some
3817 * information about a later-resolved object while resolving an
3818 * earlier-resolved object, even though we obviously can't have fully
3819 * resolved the later-resolved object. In tentative resolution, we
3820 * perform the resolution of the later-resolved object, completely in
3821 * the dark about the earlier-resolved object(s), and come up with as
3822 * much information as we can. The important thing about this stage of
3823 * resolution is that we don't ask any interactive questions and we
3824 * don't count anything for ranking purposes - we simply do the best we
3825 * can and note the results, leaving any ranking or interaction for the
3826 * true resolution phase that we'll perform later.
3827 */
3828 class TentativeResolveResults: ResolveResults
3829 construct(target, issuer) { setActors(target, issuer); }
3830
3831 /*
3832 * ignore most resolution problems, since this is only a tentative
3833 * resolution pass
3834 */
3835 noMatch(action, txt) { }
3836 noMatchPoss(action, txt) { }
3837 noVocabMatch(action, txt) { }
3838 noMatchForAll() { }
3839 noteEmptyBut() { }
3840 noMatchForAllBut() { }
3841 noMatchForListBut() { }
3842 noMatchForPronoun(typ, txt) { }
3843 reflexiveNotAllowed(typ, txt) { }
3844 wrongReflexive(typ, txt) { }
3845 noMatchForPossessive(owner, txt) { }
3846 noMatchForLocation(loc, txt) { }
3847 noteBadPrep() { }
3848 nothingInLocation(loc) { }
3849 unknownNounPhrase(match, resolver) { return []; }
3850 noteLiteral(txt) { }
3851 emptyNounPhrase(resolver) { return []; }
3852 zeroQuantity(txt) { }
3853 insufficientQuantity(txt, matchList, requiredNum) { }
3854 uniqueObjectRequired(txt, matchList) { }
3855 noteAdjEnding() { }
3856 noteIndefinite() { }
3857 noteMiscWordList(txt) { }
3858 notePronoun() { }
3859 noteMatches(matchList) { }
3860 incCommandCount() { }
3861 noteActorSpecified() { }
3862 noteNounSlots(cnt) { }
3863 noteWeakPhrasing(level) { }
3864 allowActionRemapping = nil
3865
3866 /*
3867 * during the tentative phase, keep all equivalents - we don't want
3868 * to make any arbitrary choices among equivalents during this
3869 * phase, because doing so could improperly force a choice among
3870 * otherwise ambiguous resolutions to the other phrase
3871 */
3872 allowEquivalentFiltering = nil
3873
3874 /*
3875 * for ambiguous results, don't attempt to narrow things down - just
3876 * keep the entire list
3877 */
3878 ambiguousNounPhrase(keeper, asker, txt,
3879 matchList, fullMatchList, scopeList,
3880 requiredNum, resolver)
3881 {
3882 return matchList;
3883 }
3884
3885 /*
3886 * no interaction is allowed, so return nothing if we need to ask
3887 * for a missing object
3888 */
3889 askMissingObject(asker, resolver, responseProd)
3890 {
3891 /* note that we have a missing noun phrase */
3892 npMissing = true;
3893
3894 /* return nothing */
3895 return nil;
3896 }
3897
3898 /*
3899 * no interaction is allowed, so return no tokens if we need to ask
3900 * for a literal
3901 */
3902 askMissingLiteral(action, which) { return []; }
3903
3904 /* no interaction is allowed during tentative resolution */
3905 canResolveInteractively() { return nil; }
3906
3907 /*
3908 * flag: the noun phrase we're resolving is a missing noun phrase,
3909 * which means that we'll ask for it to be filled in when we get
3910 * around to resolving it for real
3911 */
3912 npMissing = nil
3913 ;
3914
3915 /*
3916 * A dummy object that we use for the *tentative* resolution of a noun
3917 * phrase when the noun phrase doesn't match anything. This lets us
3918 * distinguish cases where we have a noun phrase that has an error from a
3919 * noun phrase that's simply missing.
3920 */
3921 dummyTentativeObject: object
3922 ;
3923
3924 dummyTentativeInfo: ResolveInfo
3925 obj_ = dummyTentativeObject
3926 flags_ = 0
3927 ;
3928
3929 /* ------------------------------------------------------------------------ */
3930 /*
3931 * Transitive-with-indirect Action class - this is an action that takes
3932 * both a direct and indirect object. We subclass the basic one-object
3933 * action to add the indirect object handling.
3934 */
3935 class TIAction: TAction
3936 resetAction()
3937 {
3938 /* inherit defaulting handling */
3939 inherited();
3940
3941 /* discard our cached iobj resolver */
3942 iobjResolver_ = nil;
3943 }
3944
3945 /*
3946 * Retry a single-object action as a two-object action. We'll treat
3947 * the original action's direct object list as our direct object
3948 * list, and obtain an indirect object using the normal means (first
3949 * looking for a default, then prompting the player if we can't find
3950 * a suitable default). 'orig' is the original single-object action.
3951 *
3952 * This routine terminates with 'exit' if it doesn't throw some
3953 * other error.
3954 */
3955 retryWithMissingIobj(orig, asker)
3956 {
3957 /* resolve and execute the replacement action */
3958 resolveAndReplaceAction(createForMissingIobj(orig, asker));
3959 }
3960
3961 /*
3962 * Retry an action as a two-object action with an ambiguous indirect
3963 * object. We'll ask which of the given possible objects is
3964 * intended.
3965 */
3966 retryWithAmbiguousIobj(orig, objs, asker, objPhrase)
3967 {
3968 /* create a missing-indirect-object replacement action */
3969 local action = createForMissingIobj(orig, asker);
3970
3971 /* reduce the object list to the objects in scope */
3972 local resolver = action.getIobjResolver(gIssuingActor, gActor, true);
3973 objs = objs.subset({x: resolver.objInScope(x)});
3974
3975 /* plug in the ambiguous indirect object list */
3976 action.iobjMatch = new PreResolvedAmbigProd(objs, asker, objPhrase);
3977
3978 /* resolve and execute the replacement action */
3979 resolveAndReplaceAction(action);
3980 }
3981
3982 /*
3983 * Test to see if askForIobj() would find a default indirect object.
3984 * Returns true if there's a default, nil if not. If this returns
3985 * true, then askForIobj() will simply take the default and proceed;
3986 * otherwise, it will have to actually ask the user for the missing
3987 * information.
3988 */
3989 testRetryDefaultIobj(orig)
3990 {
3991 local action;
3992 local def;
3993
3994 /* create the new action for checking for an indirect object */
3995 action = createForMissingIobj(orig, ResolveAsker);
3996
3997 /* get the default iobj */
3998 def = action.getDefaultIobj(
3999 action.iobjMatch,
4000 action.getIobjResolver(gIssuingActor, gActor, nil));
4001
4002 /* if there's exactly one result, then we have a default */
4003 return (def != nil && def.length() == 1);
4004 }
4005
4006 /*
4007 * Create an instance of this action for retrying a given
4008 * single-object action with a missing indirect object.
4009 */
4010 createForMissingIobj(orig, asker)
4011 {
4012 /* create the new action based on the original action */
4013 local action = createForRetry(orig);
4014
4015 /* use an empty noun phrase for the new action's indirect object */
4016 action.iobjMatch = new EmptyNounPhraseProd();
4017
4018 /* set our custom response production and ResolveAsker */
4019 action.iobjMatch.setPrompt(action.askIobjResponseProd, asker);
4020
4021 /* copy what we've resolved so far */
4022 action.initForMissingIobj(orig);
4023
4024 /* return the action */
4025 return action;
4026 }
4027
4028 /*
4029 * Initialize the action for retrying with a missing direct object.
4030 *
4031 * If we're trying a TIAction, we can only be coming from a TAction
4032 * (since that's the only kind of original action that can turn into
4033 * a two-object, at least in the base library). That means the
4034 * original action already has a direct object. Now, since we're
4035 * asking for a MISSING direct object, the only possibility is that
4036 * the original action's direct object is our INDIRECT object. For
4037 * example: SWEEP WITH BROOM is turning into SWEEP <what> WITH
4038 * BROOM.
4039 */
4040 initForMissingDobj(orig)
4041 {
4042 local origDobj = orig.getDobj();
4043
4044 /*
4045 * Set the indirect object in the new action to the direct object
4046 * from the original action. If there's no individual direct
4047 * object yet, we must be retrying the overall command, before we
4048 * started iterating through the individual dobjs, so copy the
4049 * entire dobj list from the original.
4050 */
4051 iobjMatch = new PreResolvedProd(origDobj != nil
4052 ? origDobj : orig.dobjList_ );
4053 }
4054
4055 /*
4056 * Initialize the action for retrying with a missing indirect object.
4057 *
4058 * We can only be coming from a TAction, so the TAction will have a
4059 * direct object already. Simply copy that as our own direct
4060 * object. For example: UNLOCK DOOR is turning into UNLOCK DOOR
4061 * WITH <what>.
4062 */
4063 initForMissingIobj(orig)
4064 {
4065 local origDobj = orig.getDobj();
4066
4067 /*
4068 * Copy the direct object from the original. If there's no
4069 * individual direct object yet, we must be retrying the overall
4070 * command, before we started iterating through the individual
4071 * dobjs, so copy the entire dobj list.
4072 */
4073 dobjMatch = new PreResolvedProd(origDobj != nil
4074 ? origDobj : orig.dobjList_);
4075 }
4076
4077 /*
4078 * The root production to use to parse missing indirect object
4079 * responses. By default, this is singleNoun, but individual
4080 * actions can override this as appropriate.
4081 *
4082 * Note that language modules might want to override this to allow
4083 * for special responses. For example, in English, most verbs will
4084 * want to override this with a specialized production that allows
4085 * the appropriate preposition in the response.
4086 */
4087 askIobjResponseProd = singleNoun
4088
4089 /* get the missing object response production for a given role */
4090 getObjResponseProd(resolver)
4091 {
4092 /* if it's the indirect object, return the iobj response prod */
4093 if (resolver.whichObject == IndirectObject)
4094 return askIobjResponseProd;
4095
4096 /* otherwise use the default handling */
4097 return inherited(resolver);
4098 }
4099
4100 /*
4101 * Resolution order - returns DirectObject or IndirectObject to
4102 * indicate which noun phrase to resolve first in resolveNouns().
4103 * By default, we'll resolve the indirect object first, but
4104 * individual actions can override this to resolve in a non-default
4105 * order.
4106 */
4107 resolveFirst = IndirectObject
4108
4109 /*
4110 * Empty phrase resolution order. This is similar to the standard
4111 * resolution order (resolveFirst), but is used only when both the
4112 * direct and indirect objects are empty phrases.
4113 *
4114 * When both phrases are empty, we will either use a default or
4115 * prompt interactively for the missing phrase. In most cases, it
4116 * is desirable to prompt interactively for a missing direct object
4117 * first, regardless of the usual resolution order.
4118 */
4119 resolveFirstEmpty = DirectObject
4120
4121 /*
4122 * Determine which object to call first for action processing. By
4123 * default, we execute in the same order as we resolve, but this can
4124 * be overridden if necessary.
4125 */
4126 execFirst = (resolveFirst)
4127
4128 /*
4129 * Can the indirect object potentially resolve to the given
4130 * simulation object? This only determines if the object is a
4131 * *syntactic* match, meaning that it can match at a vocabulary and
4132 * grammar level. This doesn't test it for logicalness or check that
4133 * it's an otherwise valid resolution.
4134 */
4135 canIobjResolveTo(obj)
4136 {
4137 /* check our iobj match tree to see if it can resolve to 'obj' */
4138 return iobjMatch.canResolveTo(
4139 obj, self, issuer_, actor_, IndirectObject);
4140 }
4141
4142 /*
4143 * resolve our noun phrases to objects
4144 */
4145 resolveNouns(issuingActor, targetActor, results)
4146 {
4147 local first;
4148 local objMatch1, objMatch2;
4149 local objList1, objList2;
4150 local getResolver1, getResolver2;
4151 local objCur1;
4152 local remapProp;
4153 local reResolveFirst;
4154
4155 /*
4156 * note in the results that we have two noun slots (the direct
4157 * and indirect objects)
4158 */
4159 results.noteNounSlots(2);
4160
4161 /* we have no current known direct or indirect object yet */
4162 dobjCur_ = nil;
4163 iobjCur_ = nil;
4164
4165 /*
4166 * presume we won't have to re-resolve the first noun phrase,
4167 * and clear out our record of anaphor bindings
4168 */
4169 reResolveFirst = nil;
4170 needAnaphoricBinding_ = nil;
4171 lastObjList_ = nil;
4172
4173 /*
4174 * Determine which object we want to resolve first. If both
4175 * phrases are empty, use the special all-empty ordering;
4176 * otherwise, use the standard ordering for this verb.
4177 */
4178 if (dobjMatch.isEmptyPhrase && iobjMatch.isEmptyPhrase)
4179 {
4180 /* both phrases are empty - use the all-empty ordering */
4181 first = resolveFirstEmpty;
4182 }
4183 else
4184 {
4185 /*
4186 * we have at least one non-empty phrase, so use our
4187 * standard ordering
4188 */
4189 first = resolveFirst;
4190 }
4191
4192 /*
4193 * The resolution process is symmetrical for the two possible
4194 * resolution orders (direct object first or indirect object
4195 * first); all we need to do is to set up the parameters we'll
4196 * need according to which order we're using.
4197 *
4198 * This parameterized approach makes the code further below a
4199 * little mind-boggling, because it's using so much indirection.
4200 * But the alternative is worse: the alternative is to
4201 * essentially make two copies of the code below (one for the
4202 * dobj-first case and one for the iobj-first case), which is
4203 * prone to maintenance problems because of the need to keep the
4204 * two copies synchronized when making any future changes.
4205 */
4206 if (first == DirectObject)
4207 {
4208 objMatch1 = dobjMatch;
4209 objMatch2 = iobjMatch;
4210 objList1 = &dobjList_;
4211 objList2 = &iobjList_;
4212 getResolver1 = &getDobjResolver;
4213 getResolver2 = &getIobjResolver;
4214 objCur1 = &dobjCur_;
4215 remapProp = remapDobjProp;
4216 }
4217 else
4218 {
4219 objMatch1 = iobjMatch;
4220 objMatch2 = dobjMatch;
4221 objList1 = &iobjList_;
4222 objList2 = &dobjList_;
4223 getResolver1 = &getIobjResolver;
4224 getResolver2 = &getDobjResolver;
4225 objCur1 = &iobjCur_;
4226 remapProp = remapIobjProp;
4227 }
4228
4229 /*
4230 * Get the unfiltered second-resolved object list - this will
4231 * give the first-resolved object resolver access to some
4232 * minimal information about the possible second-resolved object
4233 * or objects.
4234 *
4235 * Note that we're not *really* resolving the second object here
4236 * - it is the second-resolved object, after all. What we're
4237 * doing is figuring out the *potential* set of objects that
4238 * could resolve to the second phrase, with minimal
4239 * disambiguation, so that the first object resolver is not
4240 * totally in the dark about the second object's potential
4241 * resolution.
4242 */
4243 initTentative(issuingActor, targetActor, first);
4244
4245 /* resolve the first-resolved noun phrase */
4246 self.(objList1) = objMatch1.resolveNouns(
4247 self.(getResolver1)(issuingActor, targetActor, true), results);
4248
4249 /*
4250 * If the first-resolved noun phrase asked for an anaphoric
4251 * binding, we'll need to go back and re-resolve that noun
4252 * phrase after we resolve our other noun phrase, since the
4253 * first-resolved phrase refers to the second-resolved phrase.
4254 */
4255 reResolveFirst = needAnaphoricBinding_;
4256
4257 /*
4258 * if the second-resolved phrase uses an anaphoric pronoun, the
4259 * anaphor can be taken as referring to the first-resolved
4260 * phrase's results
4261 */
4262 lastObjList_ = self.(objList1);
4263
4264 /*
4265 * if the first-resolved phrase resolves to just one object, we
4266 * can immediately set the current resolved object, so that we
4267 * can use it while resolving the second-resolved object list
4268 */
4269 if (self.(objList1).length() == 1)
4270 {
4271 /* set the current first-resolved object */
4272 self.(objCur1) = self.(objList1)[1].obj_;
4273
4274 /* if remapping is allowed at this point, look for a remapping */
4275 if (results.allowActionRemapping)
4276 {
4277 withParserGlobals(issuingActor, targetActor, self,
4278 function()
4279 {
4280 local remapInfo;
4281
4282 /* check for a remapping */
4283 if ((remapInfo = self.(objCur1).(remapProp)) != nil)
4284 {
4285 /*
4286 * we have a remapping, so apply it - note that
4287 * we're still in the process of resolving noun
4288 * phrases (since we've only resolved one of our
4289 * two noun phrases so far), so pass 'true' for
4290 * the inResolve parameter
4291 */
4292 remapAction(true, first, remapInfo);
4293 }
4294 });
4295 }
4296 }
4297
4298 /* resolve the second-resolved object */
4299 self.(objList2) = objMatch2.resolveNouns(
4300 self.(getResolver2)(issuingActor, targetActor, true), results);
4301
4302 /*
4303 * if we have to re-resolve the first noun phrase due to an
4304 * anaphoric pronoun, go back and do that now
4305 */
4306 if (reResolveFirst)
4307 {
4308 /*
4309 * use the second-resolved noun phrase as the referent of
4310 * the anaphoric pronoun(s) in the first-resolved phrase
4311 */
4312 lastObjList_ = self.(objList2);
4313
4314 /* re-resolve the first object list */
4315 self.(objList1) = objMatch1.resolveNouns(
4316 self.(getResolver1)(issuingActor, targetActor, true),
4317 results);
4318 }
4319 }
4320
4321 /* we have a direct and indirect object */
4322 predicateNounPhrases = [&dobjMatch, &iobjMatch]
4323
4324 /* get an object role */
4325 getRoleFromIndex(idx)
4326 {
4327 /*
4328 * the second object is always our indirect object; for other
4329 * roles, defer to the inherited behavior
4330 */
4331 return (idx == 2 ? IndirectObject : inherited(idx));
4332 }
4333
4334 /* get the resolved object in a given role */
4335 getObjectForRole(role)
4336 {
4337 /* return the indirect object if requested; otherwise inherit */
4338 return (role == IndirectObject ? getIobj() : inherited(role));
4339 }
4340
4341 /* get the ResolveInfo for the given resolved object */
4342 getResolveInfo(obj, oldRole)
4343 {
4344 local info;
4345
4346 /* scan our resolved direct object list for the given object */
4347 if (dobjList_ != nil)
4348 info = dobjList_.valWhich({x: x.obj_ == obj});
4349
4350 /* if we didn't find it there, try the indirect object list */
4351 if (info == nil && iobjList_ != nil)
4352 info = iobjList_.valWhich({x: x.obj_ == obj});
4353
4354 /* if we didn't find one, create one from scratch */
4355 if (info == nil)
4356 {
4357 /* get the list for the old role */
4358 local lst = (oldRole == DirectObject ? dobjList_ : iobjList_);
4359
4360 /*
4361 * if there's anything in the old role, copy its flags and
4362 * noun phrase to the new role
4363 */
4364 if (lst.length() > 0)
4365 {
4366 /* copy the old role's attributes */
4367 info = new ResolveInfo(obj, lst[1].flags_, lst[1].np_);
4368 }
4369 else
4370 {
4371 /* nothing in the old role - start from scratch */
4372 info = new ResolveInfo(obj, 0, nil);
4373 }
4374 }
4375
4376 /* return what we found (or created) */
4377 return info;
4378 }
4379
4380 /* get the OtherObject role for the given role */
4381 getOtherObjectRole(role)
4382 {
4383 /* the complementary roles are DirectObject and IndirectObject */
4384 return (role == IndirectObject ? DirectObject : IndirectObject);
4385 }
4386
4387 /* get the match tree for the noun phrase in the given role */
4388 getMatchForRole(role)
4389 {
4390 /* return the indirect object match tree if requested; else inherit */
4391 return (role == IndirectObject ? iobjMatch : inherited(role));
4392 }
4393
4394 /* get the 'verify' property for a given object role */
4395 getVerifyPropForRole(role)
4396 {
4397 return (role == IndirectObject ? verIobjProp : inherited(role));
4398 }
4399
4400 /* get the 'preCond' property for a given object role */
4401 getPreCondPropForRole(role)
4402 {
4403 return (role == IndirectObject ? preCondIobjProp : inherited(role));
4404 }
4405
4406 /* get the 'remap' property for a given object role */
4407 getRemapPropForRole(role)
4408 {
4409 return (role == IndirectObject ? remapIobjProp : inherited(role));
4410 }
4411
4412 /* get the list of resolved objects in the given role */
4413 getResolvedObjList(which)
4414 {
4415 return (which == IndirectObject ? getResolvedIobjList()
4416 : inherited(which));
4417 }
4418
4419 /* get the list of resolved indirect objects */
4420 getResolvedIobjList()
4421 {
4422 /*
4423 * if we have an indirect object list, return the objects from
4424 * it; otherwise, return an empty list
4425 */
4426 return (iobjList_ == nil ? nil : iobjList_.mapAll({x: x.obj_}));
4427 }
4428
4429 /*
4430 * Manually set the resolved objects. We'll set our direct and
4431 * indirect objects.
4432 */
4433 setResolvedObjects(dobj, iobj)
4434 {
4435 /* inherit the base class handling to set the direct object */
4436 inherited(dobj);
4437
4438 /* set the resolved iobj */
4439 setResolvedIobj(iobj);
4440 }
4441
4442 /* set a resolved iobj */
4443 setResolvedIobj(iobj)
4444 {
4445 /* build a pre-resolved production for the indirect object */
4446 iobjMatch = new PreResolvedProd(iobj);
4447
4448 /* set the resolved indirect object */
4449 iobjList_ = makeResolveInfoList(iobj);
4450
4451 /* set the current indirect object as well */
4452 iobjCur_ = (iobjList_.length() > 0 ? iobjList_[1].obj_ : nil);
4453 iobjInfoCur_ = (iobjList_.length() > 0 ? iobjList_[1] : nil);
4454 }
4455
4456 /* manually set the unresolved object noun phrase match trees */
4457 setObjectMatches(dobj, iobj)
4458 {
4459 /* inherit default handling */
4460 inherited(dobj);
4461
4462 /*
4463 * if the iobj is a ResolveInfo, set it as a resolved object;
4464 * otherwise set it as an unresolved match tree
4465 */
4466 if (iobj.ofKind(ResolveInfo))
4467 setResolvedIobj(iobj);
4468 else
4469 iobjMatch = iobj;
4470 }
4471
4472 /*
4473 * Get the anaphoric binding for the noun phrase we're currently
4474 * resolving.
4475 */
4476 getAnaphoricBinding(typ)
4477 {
4478 /* if we've resolved a prior noun phrase, return it */
4479 if (lastObjList_ != nil)
4480 return lastObjList_;
4481
4482 /*
4483 * we don't have a prior noun phrase - make a note that we have
4484 * to come back and re-resolve the current noun phrase
4485 */
4486 needAnaphoricBinding_ = true;
4487
4488 /*
4489 * return an empty list to indicate that the anaphor is
4490 * acceptable in this context but has no binding yet
4491 */
4492 return [];
4493 }
4494
4495 /*
4496 * The last object list we resolved. We keep track of this so that
4497 * we can provide it as the anaphoric binding, if an anaphor binding
4498 * is requested.
4499 */
4500 lastObjList_ = nil
4501
4502 /*
4503 * Flag: we have been asked for an anaphoric binding, but we don't
4504 * have a binding available. We'll check this after resolving the
4505 * first-resolved noun phrase so that we can go back and re-resolve
4506 * it again after resolving the other noun phrase.
4507 */
4508 needAnaphoricBinding_ = nil
4509
4510 /* check that the resolved objects are in scope */
4511 resolvedObjectsInScope()
4512 {
4513 /*
4514 * check the indirect object, and inherit the base class handling
4515 * to check the direct object
4516 */
4517 return (inherited()
4518 && (getIobjResolver(gIssuingActor, gActor, true)
4519 .objInScope(iobjList_[1].obj_)));
4520 }
4521
4522 /*
4523 * get our indirect object resolver, or create one if we haven't
4524 * already cached one
4525 */
4526 getIobjResolver(issuingActor, targetActor, reset)
4527 {
4528 /* if we don't already have one cached, create a new one */
4529 if (iobjResolver_ == nil)
4530 iobjResolver_ = createIobjResolver(issuingActor, targetActor);
4531
4532 /* reset the resolver if desired */
4533 if (reset)
4534 iobjResolver_.resetResolver();
4535
4536 /* return the cached resolver */
4537 return iobjResolver_;
4538 }
4539
4540 /*
4541 * Create our indirect object resolver. By default, we'll use a
4542 * basic indirect object resolver.
4543 */
4544 createIobjResolver(issuingActor, targetActor)
4545 {
4546 /* create and return a new basic indirect object resolver */
4547 return new IobjResolver(self, issuingActor, targetActor);
4548 }
4549
4550 /*
4551 * Resolve 'all' for the indirect object. By default, we'll return
4552 * everything in the scope list.
4553 */
4554 getAllIobj(actor, scopeList)
4555 {
4556 return scopeList;
4557 }
4558
4559 /* filter an ambiguous indirect object noun phrase */
4560 filterAmbiguousIobj(lst, requiredNum, np)
4561 {
4562 /* filter using the indirect object verifier method */
4563 return filterAmbiguousWithVerify(lst, requiredNum, verIobjProp,
4564 preCondIobjProp, remapIobjProp,
4565 IndirectObject, np);
4566 }
4567
4568 /* filter a plural phrase */
4569 filterPluralIobj(lst, np)
4570 {
4571 /* filter using the direct object verifier method */
4572 return filterPluralWithVerify(lst, verIobjProp, preCondIobjProp,
4573 remapIobjProp, IndirectObject, np);
4574 }
4575
4576 /* get the default indirect object */
4577 getDefaultIobj(np, resolver)
4578 {
4579 /* get a default indirect object using the verify method */
4580 return getDefaultWithVerify(resolver, verIobjProp, preCondIobjProp,
4581 remapIobjProp, IndirectObject, np);
4582 }
4583
4584 /*
4585 * Execute the action. We'll run through the execution sequence
4586 * once for each resolved object in our direct or indirect object
4587 * list, depending on which one is the list and which one is the
4588 * singleton.
4589 */
4590 doActionMain()
4591 {
4592 local lst;
4593 local preAnnouncedDobj;
4594 local preAnnouncedIobj;
4595
4596 /*
4597 * Get the list of resolved objects for the multiple object. If
4598 * neither has multiple objects, it doesn't matter which is
4599 * iterated, since we'll just do the command once anyway.
4600 */
4601 lst = (iobjList_.length() > 1 ? iobjList_ : dobjList_);
4602
4603 /*
4604 * Set the pronoun antecedents, using the game-specific pronoun
4605 * setter. Don't set an antecedent for a nested command.
4606 */
4607 if (parentAction == nil)
4608 {
4609 /*
4610 * Set both direct and indirect objects as potential
4611 * antecedents. Rather than trying to figure out right now
4612 * which one we might want to refer to in the future, remember
4613 * both - we'll decide which one is the logical antecedent
4614 * when we find a pronoun to resolve in a future command.
4615 */
4616 gActor.setPronounMulti(dobjList_, iobjList_);
4617
4618 /*
4619 * If one or the other object phrase was specified in the
4620 * input as a pronoun, keep the meaning of that pronoun the
4621 * same, overriding whatever we just did. Note that the
4622 * order we use here doesn't matter: if a given pronoun
4623 * appears in only one of the two lists, then the list where
4624 * it's not set has no effect on the pronoun, hence it
4625 * doesn't matter which comes first; if a pronoun appears in
4626 * both lists, it will have the same value in both lists, so
4627 * we'll just do the same thing twice, so, again, order
4628 * doesn't matter.
4629 */
4630 setPronounByInput(dobjList_);
4631 setPronounByInput(iobjList_);
4632 }
4633
4634 /*
4635 * pre-announce the non-list object if appropriate - this will
4636 * provide a common pre-announcement if we iterate through
4637 * several announcements of the main list objects
4638 */
4639 if (lst == dobjList_)
4640 {
4641 /* pre-announce the single indirect object if needed */
4642 preAnnouncedIobj = preAnnounceActionObject(
4643 iobjList_[1], dobjList_, IndirectObject);
4644
4645 /* we haven't announced the direct object yet */
4646 preAnnouncedDobj = nil;
4647
4648 /* pre-calculate the multi-object announcements */
4649 cacheMultiObjectAnnouncements(dobjList_, DirectObject);
4650 }
4651 else
4652 {
4653 /* pre-announce the single direct object if needed */
4654 preAnnouncedDobj = preAnnounceActionObject(
4655 dobjList_[1], iobjList_, DirectObject);
4656
4657 /* we haven't announced the indirect object yet */
4658 preAnnouncedIobj = nil;
4659
4660 /* pre-calculate the multi-object announcements */
4661 cacheMultiObjectAnnouncements(iobjList_, IndirectObject);
4662 }
4663
4664 /* we haven't yet canceled the iteration */
4665 iterationCanceled = nil;
4666
4667 /* iterate over the resolved list for the multiple object */
4668 for (local i = 1, local len = lst.length() ;
4669 i <= len && !iterationCanceled ; ++i)
4670 {
4671 local dobjInfo;
4672 local iobjInfo;
4673
4674 /*
4675 * make the current list item the direct or indirect object,
4676 * as appropriate
4677 */
4678 if (lst == dobjList_)
4679 {
4680 /* the direct object is the multiple object */
4681 dobjInfo = dobjInfoCur_ = lst[i];
4682 iobjInfo = iobjInfoCur_ = iobjList_[1];
4683 }
4684 else
4685 {
4686 /* the indirect object is the multiple object */
4687 dobjInfo = dobjInfoCur_ = dobjList_[1];
4688 iobjInfo = iobjInfoCur_ = lst[i];
4689 }
4690
4691 /* get the current dobj and iobj from the resolve info */
4692 dobjCur_ = dobjInfo.obj_;
4693 iobjCur_ = iobjInfo.obj_;
4694
4695 /*
4696 * if the action was remapped, and we need to announce
4697 * anything, announce the entire action
4698 */
4699 if (isRemapped())
4700 {
4701 /*
4702 * We were remapped. The entire phrasing of the new
4703 * action might have changed from what the player typed,
4704 * so it might be nonsensical to show the objects as we
4705 * usually would, as sentence fragments that are meant
4706 * to combine with what the player actually typed. So,
4707 * instead of showing the usual sentence fragments, show
4708 * the entire phrasing of the command.
4709 *
4710 * Only show the announcement if we have a reason to: we
4711 * have unclear disambiguation in one of the objects, or
4712 * one of the objects is defaulted.
4713 *
4714 * If we don't want to announce the remapped action,
4715 * still consider showing a multi-object announcement,
4716 * if we would normally need to do so.
4717 */
4718 if (needRemappedAnnouncement(dobjInfo)
4719 || needRemappedAnnouncement(iobjInfo))
4720 {
4721 /* show the remapped announcement */
4722 gTranscript.announceRemappedAction();
4723 }
4724 else
4725 {
4726 /* announce the multiple dobj if necessary */
4727 if (!preAnnouncedDobj)
4728 maybeAnnounceMultiObject(
4729 dobjInfo, dobjList_.length(), DirectObject);
4730
4731 /* announce the multiple iobj if necessary */
4732 if (!preAnnouncedIobj)
4733 maybeAnnounceMultiObject(
4734 iobjInfo, iobjList_.length(), IndirectObject);
4735 }
4736 }
4737 else
4738 {
4739 /* announce the direct object if appropriate */
4740 if (!preAnnouncedDobj)
4741 announceActionObject(dobjInfo, dobjList_.length(),
4742 DirectObject);
4743
4744 /* announce the indirect object if appropriate */
4745 if (!preAnnouncedIobj)
4746 announceActionObject(iobjInfo, iobjList_.length(),
4747 IndirectObject);
4748 }
4749
4750 /* run the execution sequence for the current direct object */
4751 doActionOnce();
4752
4753 /* if we're top-level, count the iteration in the transcript */
4754 if (parentAction == nil)
4755 gTranscript.newIter();
4756 }
4757 }
4758
4759 /*
4760 * Set the pronoun according to the pronoun type actually used in
4761 * the input. For example, if we said PUT BOX ON IT, we want IT to
4762 * continue referring to whatever IT referred to before this command
4763 * - we specifically do NOT want IT to refer to the BOX in this
4764 * case.
4765 */
4766 setPronounByInput(lst)
4767 {
4768 local objs;
4769
4770 /* get the subset of the list that was specified by pronoun */
4771 lst = lst.subset({x: x.pronounType_ != nil});
4772
4773 /*
4774 * Get a list of the unique objects in the list. This will
4775 * ensure that we can distinguish THEM from IT AND IT AND IT: if
4776 * we have the same pronoun appearing with multiple objects,
4777 * we'll know that it's because the pronoun was actually plural
4778 * (THEM) rather than a singular pronoun that was repeated (IT
4779 * AND IT AND IT).
4780 */
4781 objs = lst.mapAll({x: x.obj_}).getUnique();
4782
4783 /*
4784 * Now retain one 'lst' element for each 'objs' element. This
4785 * is a bit tricky: we're mapping each element in 'objs' to pick
4786 * out one element of 'lst' where the 'lst' element points to
4787 * the 'objs' element.
4788 */
4789 lst = objs.mapAll({o: lst.valWhich({l: l.obj_ == o})});
4790
4791 /*
4792 * Now we can set the pronouns. Go through the list, and set
4793 * each different pronoun type that appears. Set it to the
4794 * subset of the list with that matches that pronoun type, and
4795 * then remove that subset and keep iterating to pick up the
4796 * remaining pronoun types.
4797 */
4798 while (lst.length() != 0)
4799 {
4800 local cur;
4801 local typ;
4802
4803 /* on this iteration, handle the first pronoun type in the list */
4804 typ = lst[1].pronounType_;
4805
4806 /* pick out the subset with the current pronoun type */
4807 cur = lst.subset({x: x.pronounType_ == typ});
4808
4809 /* set the current pronoun to the current list */
4810 gActor.setPronounByType(typ, cur);
4811
4812 /* remove the subset we just handled from the remaining list */
4813 lst -= cur;
4814 }
4815 }
4816
4817 /*
4818 * Determine if we need to announce this action when the action was
4819 * remapped, based on the resolution information for one of our
4820 * objects. We need to announce a remapped action when either
4821 * object had unclear disambiguation or was defaulted.
4822 */
4823 needRemappedAnnouncement(info)
4824 {
4825 /*
4826 * if it's a defaulted object that hasn't been announced, or it
4827 * was unclearly disambiguated, we need an announcement
4828 */
4829 return (((info.flags_ & DefaultObject) != 0
4830 && (info.flags_ & AnnouncedDefaultObject) == 0)
4831 || (info.flags_ & UnclearDisambig) != 0);
4832 }
4833
4834 /*
4835 * Verify the action.
4836 */
4837 verifyAction()
4838 {
4839 local result;
4840
4841 /* invoke any general (non-object) pre-condition verifiers */
4842 result = callVerifyPreCond(nil);
4843
4844 /* check the direct object */
4845 result = callVerifyProp(dobjCur_, verDobjProp, preCondDobjProp,
4846 remapDobjProp, result, DirectObject);
4847
4848 /*
4849 * Check the indirect object, combining the results with the
4850 * direct object results. We combine the results for the two
4851 * objects because we're simply looking for any reason that we
4852 * can't perform the command.
4853 */
4854 result = callVerifyProp(iobjCur_, verIobjProp, preCondIobjProp,
4855 remapIobjProp, result, IndirectObject);
4856
4857 /*
4858 * check that the action method ("doXxx") is defined on at least
4859 * one of the objects
4860 */
4861 return verifyHandlersExist(
4862 [dobjCur_, iobjCur_],
4863 [verDobjProp, checkDobjProp, actionDobjProp,
4864 verIobjProp, checkIobjProp, actionIobjProp],
4865 result);
4866 }
4867
4868 /* initialize tentative resolutions for other noun phrases */
4869 initTentative(issuingActor, targetActor, whichObj)
4870 {
4871 local tRes;
4872 local ti, td;
4873
4874 /*
4875 * remember the old tentative direct and indirect objects, then
4876 * set them to empty lists - this will ensure that we don't
4877 * recursively try to get a tentative resolution for the object
4878 * we're working on right now, which would cause infinite
4879 * recursion
4880 */
4881 td = tentativeDobj_;
4882 ti = tentativeIobj_;
4883
4884 /* set them to empty lists to indicate they don't need resolving */
4885 tentativeDobj_ = [];
4886 tentativeIobj_ = [];
4887
4888 /* make sure our built-in dobj resolver is initialized */
4889 issuer_ = issuingActor;
4890 actor_ = targetActor;
4891
4892 /* make sure we set things back when we're done */
4893 try
4894 {
4895 /* initialize the other noun phrase */
4896 if (whichObj == DirectObject && ti == nil)
4897 {
4898 /* tentatively resolve the indirect object */
4899 tRes = new TentativeResolveResults(targetActor, issuingActor);
4900 ti = iobjMatch.resolveNouns(
4901 getIobjResolver(issuingActor, targetActor, true), tRes);
4902
4903 /*
4904 * if the list is empty, and we didn't have a missing
4905 * noun phrase, use a dummy object as the tentative
4906 * resolution - this distinguishes erroneous noun phrases
4907 * from those that are simply missing
4908 */
4909 if (ti == [] && !tRes.npMissing)
4910 ti = [dummyTentativeInfo];
4911 }
4912 else if (whichObj == IndirectObject && td == nil)
4913 {
4914 /* tentatively resolve the direct object */
4915 tRes = new TentativeResolveResults(targetActor, issuingActor);
4916 td = dobjMatch.resolveNouns(
4917 getDobjResolver(issuingActor, targetActor, true), tRes);
4918
4919 /* use a dummy object if appropriate */
4920 if (td == [] && !tRes.npMissing)
4921 td = [dummyTentativeInfo];
4922 }
4923 }
4924 finally
4925 {
4926 /* set the original (or updated) tentative lists */
4927 tentativeDobj_ = td;
4928 tentativeIobj_ = ti;
4929 }
4930 }
4931
4932 /*
4933 * Check for remapping
4934 */
4935 checkRemapping()
4936 {
4937 local remapInfo;
4938 local role;
4939
4940 /* presume we'll find remapping for the first-resolved object */
4941 role = resolveFirst;
4942
4943 /* check remapping for each object, in the resolution order */
4944 if (resolveFirst == DirectObject)
4945 {
4946 /* the direct object is resolved first, so try it first */
4947 if ((remapInfo = dobjCur_.(remapDobjProp)) == nil)
4948 {
4949 remapInfo = iobjCur_.(remapIobjProp);
4950 role = IndirectObject;
4951 }
4952 }
4953 else
4954 {
4955 /* the indirect object is resolved first, so remap it first */
4956 if ((remapInfo = iobjCur_.(remapIobjProp)) == nil)
4957 {
4958 remapInfo = dobjCur_.(remapDobjProp);
4959 role = DirectObject;
4960 }
4961 }
4962
4963 /* if we found a remapping, apply it */
4964 if (remapInfo != nil)
4965 remapAction(nil, role, remapInfo);
4966 }
4967
4968 /*
4969 * Check the command.
4970 *
4971 * For a two-object action, this first calls the catch-all 'check'
4972 * methods (the dobjFor(Default) and dobjFor(All) methods) on the two
4973 * objects (indirect object first), then calls the 'check' methods
4974 * for this specific action (direct object first).
4975 */
4976 checkAction()
4977 {
4978 try
4979 {
4980 /* invoke the catch-all 'check' methods on each object */
4981 local defIo = callCatchAllProp(
4982 iobjCur_, checkIobjProp, &checkIobjDefault, &checkIobjAll);
4983 local defDo = callCatchAllProp(
4984 dobjCur_, checkDobjProp, &checkDobjDefault, &checkDobjAll);
4985
4986 /*
4987 * invoke the 'check' method on each object, as long as it
4988 * overrides any corresponding Default 'check' handler
4989 */
4990 if (!defDo)
4991 dobjCur_.(checkDobjProp)();
4992 if (!defIo)
4993 iobjCur_.(checkIobjProp)();
4994 }
4995 catch (ExitSignal es)
4996 {
4997 /* mark the action as a failure in the transcript */
4998 gTranscript.noteFailure();
4999
5000 /* re-throw the signal */
5001 throw es;
5002 }
5003 }
5004
5005 /*
5006 * Execute the command.
5007 */
5008 execAction()
5009 {
5010 local defIo, defDo;
5011
5012 /* invoke the catch-all 'action' method on each object */
5013 defIo = callCatchAllProp(iobjCur_, actionIobjProp,
5014 &actionIobjDefault, &actionIobjAll);
5015 defDo = callCatchAllProp(dobjCur_, actionDobjProp,
5016 &actionDobjDefault, &actionDobjAll);
5017
5018 /*
5019 * Invoke the action method on each object, starting with the
5020 * non-list object. Call these only if the corresponding
5021 * default 'action' methods didn't override the verb-specific
5022 * methods.
5023 */
5024 if (execFirst == DirectObject)
5025 {
5026 if (!defDo)
5027 dobjCur_.(actionDobjProp)();
5028 if (!defIo)
5029 iobjCur_.(actionIobjProp)();
5030 }
5031 else
5032 {
5033 if (!defIo)
5034 iobjCur_.(actionIobjProp)();
5035 if (!defDo)
5036 dobjCur_.(actionDobjProp)();
5037 }
5038 }
5039
5040 /* get the precondition descriptor list for the action */
5041 getPreCondDescList()
5042 {
5043 /*
5044 * return the inherited preconditions plus the conditions that
5045 * apply to the indirect object
5046 */
5047 return inherited()
5048 + getObjPreCondDescList(iobjCur_, preCondIobjProp, iobjCur_,
5049 IndirectObject);
5050 }
5051
5052 /*
5053 * Get a message parameter object for the action. We define 'dobj'
5054 * as the direct object and 'iobj' as the indirect object, in
5055 * addition to any inherited targets.
5056 */
5057 getMessageParam(objName)
5058 {
5059 switch(objName)
5060 {
5061 case 'iobj':
5062 /* return the current indirect object */
5063 return iobjCur_;
5064
5065 default:
5066 /* inherit default handling */
5067 return inherited(objName);
5068 }
5069 }
5070
5071 /* get the current indirect object being executed */
5072 getIobj() { return iobjCur_; }
5073
5074 /* get the full ResolveInfo associated with the current indirect object */
5075 getIobjInfo() { return iobjInfoCur_; }
5076
5077 /* get the object resolution flags for the indirect object */
5078 getIobjFlags() { return iobjInfoCur_ != nil ? iobjInfoCur_.flags_ : 0; }
5079
5080 /* get the number of direct objects */
5081 getIobjCount() { return iobjList_ != nil ? iobjList_.length() : 0; }
5082
5083 /* get the original token list of the current indirect object phrase */
5084 getIobjTokens()
5085 {
5086 return iobjInfoCur_ != nil && iobjInfoCur_.np_ != nil
5087 ? iobjInfoCur_.np_.getOrigTokenList() : nil;
5088 }
5089
5090 /* get the original words (as a list of strings) of the current iobj */
5091 getIobjWords()
5092 {
5093 local l = getIobjTokens();
5094 return l != nil ? l.mapAll({x: getTokOrig(x)}) : nil;
5095 }
5096
5097 /*
5098 * Get the list of active objects. We have a direct and indirect
5099 * object.
5100 */
5101 getCurrentObjects()
5102 {
5103 return [dobjCur_, iobjCur_];
5104 }
5105
5106 /* set the current objects */
5107 setCurrentObjects(lst)
5108 {
5109 /* remember the current direct and indirect objects */
5110 dobjCur_ = lst[1];
5111 iobjCur_ = lst[2];
5112
5113 /* we don't have ResolveInfo objects for this call */
5114 dobjInfoCur_ = iobjInfoCur_ = nil;
5115 }
5116
5117 /*
5118 * Copy one tentative object list to the other. This is useful when
5119 * an object's verifier for one TIAction wants to forward the call
5120 * to the other object verifier for a different TIAction.
5121 */
5122 copyTentativeObjs()
5123 {
5124 /* copy whichever tentative list is populated to the other slot */
5125 if (tentativeDobj_ != nil)
5126 tentativeDobj_ = tentativeIobj_;
5127 else
5128 tentativeIobj_ = tentativeDobj_;
5129 }
5130
5131 /*
5132 * Get the tentative direct/indirect object resolution lists. A
5133 * tentative list is available for the later-resolved object while
5134 * resolving the earlier-resolved object.
5135 */
5136 getTentativeDobj() { return tentativeDobj_; }
5137 getTentativeIobj() { return tentativeIobj_; }
5138
5139 /*
5140 * the predicate grammar must assign the indirect object production
5141 * tree to iobjMatch
5142 */
5143 iobjMatch = nil
5144
5145 /* the indirect object list */
5146 iobjList_ = []
5147
5148 /* current indirect object being executed */
5149 iobjCur_ = nil
5150
5151 /* the full ResolveInfo associated with iobjCur_ */
5152 iobjInfoCur_ = nil
5153
5154 /* my cached indirect object resolver */
5155 iobjResolver_ = nil
5156
5157 /*
5158 * The tentative direct and indirect object lists. A tentative list
5159 * is available for the later-resolved object while resolving the
5160 * earlier-resolved object.
5161 */
5162 tentativeDobj_ = nil
5163 tentativeIobj_ = nil
5164
5165 /*
5166 * Verification and action properties for the indirect object. By
5167 * convention, the verification method for the indirect object of a
5168 * two-object action is verIobjXxx; the check method is
5169 * checkIobjXxx; and the action method is actionIobjXxx.
5170 */
5171 verIobjProp = nil
5172 preCondIobjProp = nil
5173 checkIobjProp = nil
5174 actionIobjProp = nil
5175
5176 /*
5177 * Action-remap properties for the indirect object. By convention,
5178 * the remapper properties are named remapDobjAction and
5179 * remapIobjAction, for the direct and indirect objects,
5180 * respectively, where Action is replaced by the root name of the
5181 * action.
5182 */
5183 remapIobjProp = nil
5184 ;
5185
5186 /* ------------------------------------------------------------------------ */
5187 /*
5188 * Common base class for actions involving literal phrases. This is a
5189 * mix-in class that can be combined with Action subclasses to create
5190 * specific kinds of literal actions.
5191 */
5192 class LiteralActionBase: object
5193 /*
5194 * Get a message parameter. We define 'literal' as the text of the
5195 * literal phrase, in addition to inherited targets.
5196 */
5197 getMessageParam(objName)
5198 {
5199 switch(objName)
5200 {
5201 case 'literal':
5202 /* return the text of the literal phrase */
5203 return text_;
5204
5205 default:
5206 /* inherit default handling */
5207 return inherited(objName);
5208 }
5209 }
5210
5211 /* manually set the resolved objects */
5212 setResolvedObjects(txt)
5213 {
5214 /* remember the literal text */
5215 text_ = txt;
5216 }
5217
5218 /* manually set the pre-resolved match trees */
5219 setObjectMatches(lit)
5220 {
5221 /* if it's not already a PreResolvedLiteralProd, wrap it */
5222 if (!lit.ofKind(PreResolvedLiteralProd))
5223 {
5224 /* save the literal text */
5225 text_ = lit;
5226
5227 /* wrap it in a match tree */
5228 lit = new PreResolvedLiteralProd(lit);
5229 }
5230
5231 /* note the new literal match tree */
5232 literalMatch = lit;
5233 }
5234
5235 /* get the current literal text */
5236 getLiteral() { return text_; }
5237
5238 /* the text of the literal phrase */
5239 text_ = nil
5240 ;
5241
5242 /* ------------------------------------------------------------------------ */
5243 /*
5244 * An action with a literal phrase as its only object, such as "say <any
5245 * text>". We'll accept anything as the literal phrase - a number, a
5246 * quoted string, or arbitrary words - and treat them all simply as text.
5247 *
5248 * The grammar rules that produce these actions must set literalMatch to
5249 * the literal phrase's match tree.
5250 *
5251 * Because we don't have any actual resolved objects, we're based on
5252 * IAction. Subclasses that implement particular literal actions should
5253 * override execAction() to carry out the action; this method can call
5254 * the getLiteral() method of self to get a string giving the literal
5255 * text.
5256 */
5257 class LiteralAction: LiteralActionBase, IAction
5258 /*
5259 * Resolve objects. We don't actually have any objects to resolve,
5260 * but we do have to get the text for the literal phrase.
5261 */
5262 resolveNouns(issuingActor, targetActor, results)
5263 {
5264 /* the literal phrase counts as one noun slot */
5265 results.noteNounSlots(1);
5266
5267 /*
5268 * "Resolve" our literal phrase. The literal phrase doesn't
5269 * resolve to an object list the way a regular noun phrase would,
5270 * but rather just resolves to a text string giving the original
5271 * literal contents of the phrase.
5272 */
5273 literalMatch.resolveLiteral(results);
5274
5275 /* retrieve the text of the phrase, exactly as the player typed it */
5276 text_ = literalMatch.getLiteralText(results, self, DirectObject);
5277 }
5278
5279 /* we have a literal phrase as our only noun phrase */
5280 predicateNounPhrases = [&literalMatch]
5281 ;
5282
5283 /* ------------------------------------------------------------------------ */
5284 /*
5285 * An action with a direct object and a literal, such as "turn dial to
5286 * <setting>" or "type <string> on keypad". We'll accept anything as the
5287 * literal phrase - a number, a quoted string, or arbitrary words - and
5288 * treat them all simply as text.
5289 *
5290 * The grammar rules that produce these actions must set dobjMatch to the
5291 * resolvable object of the command, and must set literalMatch to the
5292 * literal phrase's match tree. Note that we use dobjMatch as the
5293 * resolvable object even if the object serves grammatically as the
5294 * indirect object - this is a simplification, and the true grammatical
5295 * purpose of the object isn't important since there's only one true
5296 * object in the command.
5297 *
5298 * When referring to objects by role (such as in remapTo), callers should
5299 * ALWAYS refer to the resolvable object as DirectObject, and the literal
5300 * phrase as IndirectObject.
5301 *
5302 * Each subclass must set the property whichMessageLiteral to the
5303 * grammatical role (DirectObject, IndirectObject) the literal phrase
5304 * plays for message generation purposes. This only affects messages; it
5305 * doesn't affect anything else; in particular, regardless of the
5306 * whichMessageLiteral setting, callers should always refer to the
5307 * literal as IndirectObject when calling getObjectForRole() and the
5308 * like, and should always call getDobj() to get the resolved version of
5309 * the resolvable object phrase.
5310 */
5311 class LiteralTAction: LiteralActionBase, TAction
5312 /*
5313 * Resolve objects.
5314 */
5315 resolveNouns(issuingActor, targetActor, results)
5316 {
5317 /*
5318 * the literal phrase counts as one noun slot, and the direct
5319 * object as another
5320 */
5321 results.noteNounSlots(2);
5322
5323 /*
5324 * If the literal phrase serves as the direct object in generated
5325 * messages, ask for its literal text first, so that we ask for
5326 * it interactively first. Otherwise, get the tentative literal
5327 * text, in case it's useful to have in resolving the other
5328 * object.
5329 */
5330 if (whichMessageLiteral == DirectObject)
5331 text_ = literalMatch.getLiteralText(results, self, DirectObject);
5332 else
5333 text_ = literalMatch.getTentativeLiteralText();
5334
5335 /* resolve the direct object */
5336 dobjList_ = dobjMatch.resolveNouns(
5337 getDobjResolver(issuingActor, targetActor, true), results);
5338
5339 /*
5340 * "Resolve" the literal, ignoring the result - we call this so
5341 * that the literal can do any scoring it wants to do during
5342 * resolution; but since we're treating it literally, it
5343 * obviously has no actual resolved value.
5344 */
5345 literalMatch.resolveLiteral(results);
5346
5347 /* the literal phrase resolves to the text only */
5348 text_ = literalMatch.getLiteralText(results, self,
5349 whichMessageLiteral);
5350 }
5351
5352 /* we have a direct object and a literal phrase */
5353 predicateNounPhrases = [&dobjMatch, &literalMatch]
5354
5355 /* get an object role */
5356 getRoleFromIndex(idx)
5357 {
5358 /*
5359 * index 2 is the literal object, which is always in the indirect
5360 * object role; for others, inherit the default handling
5361 */
5362 return (idx == 2 ? IndirectObject : inherited(idx));
5363 }
5364
5365 /* get the OtherObject role for the given role */
5366 getOtherObjectRole(role)
5367 {
5368 /* the complementary roles are DirectObject and IndirectObject */
5369 return (role == DirectObject ? IndirectObject : DirectObject);
5370 }
5371
5372 /* get the resolved object in a given role */
5373 getObjectForRole(role)
5374 {
5375 /*
5376 * the literal is in the IndirectObject role; inherit the default
5377 * for others
5378 */
5379 return (role == IndirectObject ? text_ : inherited(role));
5380 }
5381
5382 /* get the match tree for the given role */
5383 getMatchForRole(role)
5384 {
5385 /*
5386 * the literal is in the IndirectObject role; inherit the default
5387 * for anything else
5388 */
5389 return (role == IndirectObject ? literalMatch : inherited(role));
5390 }
5391
5392 /* manually set the resolved objects */
5393 setResolvedObjects(dobj, txt)
5394 {
5395 /* inherit default TAction handling for the direct object */
5396 inherited TAction(dobj);
5397
5398 /* inherit the LiteralActionBase handling for the literal text */
5399 inherited LiteralActionBase(txt);
5400 }
5401
5402 /* manually set the pre-resolved match trees */
5403 setObjectMatches(dobj, lit)
5404 {
5405 /* inherit default TAction handling for the direct object */
5406 inherited TAction(dobj);
5407
5408 /* inherit the default LiteralActionBase handling for the literal */
5409 inherited LiteralActionBase(lit);
5410 }
5411
5412 /*
5413 * Get a list of the current objects. We include only the direct
5414 * object here, since the literal text is not a resolved object but
5415 * simply literal text.
5416 */
5417 getCurrentObjects() { return [dobjCur_]; }
5418
5419 /* set the current objects */
5420 setCurrentObjects(lst)
5421 {
5422 dobjCur_ = lst[1];
5423 dobjInfoCur_ = nil;
5424 }
5425
5426 /*
5427 * Retry a single-object action as an action taking both an object
5428 * and a literal phrase. We'll treat the original action's direct
5429 * object list as our direct object list, and obtain a literal
5430 * phrase interactively.
5431 *
5432 * This routine terminates with 'exit' if it doesn't throw some
5433 * other error.
5434 */
5435 retryWithMissingLiteral(orig)
5436 {
5437 local action;
5438
5439 /* create the new action based on the original action */
5440 action = createForRetry(orig);
5441
5442 /* use an empty literal phrase for the new action */
5443 action.literalMatch = new EmptyLiteralPhraseProd();
5444
5445 /* initialize for the missing literal phrase */
5446 action.initForMissingLiteral(orig);
5447
5448 /* resolve and execute the replacement action */
5449 resolveAndReplaceAction(action);
5450 }
5451
5452 /* initialize with a missing direct object phrase */
5453 initForMissingDobj(orig)
5454 {
5455 /*
5456 * Since we have a missing direct objet, we must be coming from
5457 * a LiteralAction. The LiteralAction will already have a
5458 * literal phrase, so copy it. For example: WRITE HELLO ->
5459 * WRITE HELLO ON <what>.
5460 */
5461 literalMatch = new PreResolvedLiteralProd(orig.getLiteral());
5462 }
5463
5464 /* initialize for a missing literal phrase */
5465 initForMissingLiteral(orig)
5466 {
5467 local origDobj = orig.getDobj();
5468
5469 /*
5470 * Since we have a missing literal, we must be coming from a
5471 * TAction. The TAction will already have a direct object,
5472 * which we'll want to keep as our own direct object. For
5473 * example: WRITE ON SLATE -> WRITE <what> ON SLATE.
5474 */
5475 dobjMatch = new PreResolvedProd(origDobj != nil
5476 ? origDobj : orig.dobjList_);
5477 }
5478
5479 /* object role played by the literal phrase */
5480 whichMessageLiteral = nil
5481
5482
5483 /* -------------------------------------------------------------------- */
5484 /*
5485 * Direct Object Resolver implementation. We serve as our own
5486 * direct object resolver, so we define any special resolver
5487 * behavior here.
5488 */
5489
5490 /*
5491 * the true grammatical role of the resolved object is always the
5492 * direct object
5493 */
5494 whichObject = DirectObject
5495
5496 /*
5497 * What we call our direct object might actually be playing the
5498 * grammatical role of the indirect object - in order to inherit
5499 * easily from TAction, we call our resolved object our direct
5500 * object, regardless of which grammatical role it actually plays.
5501 * For the most part it doesn't matter which is which; but for the
5502 * purposes of our resolver, we actually do care about its real role.
5503 * So, override the resolver method whichMessageObject so that it
5504 * returns whichever role is NOT served by the topic object.
5505 */
5506 whichMessageObject =
5507 (whichMessageLiteral == DirectObject ? IndirectObject : DirectObject)
5508 ;
5509
5510 /* ------------------------------------------------------------------------ */
5511 /*
5512 * Base class for actions that include a "topic" phrase. This is a
5513 * mix-in class that can be used in different types of topic actions. In
5514 * all cases, the topic phrase must be assigned to the 'topicMatch'
5515 * property in grammar rules based on this class.
5516 */
5517 class TopicActionBase: object
5518 /*
5519 * Resolve the topic phrase. This resolves the match tree in out
5520 * 'topicMatch' property, and stores the result in topicList_. This
5521 * is for use in resolveNouns().
5522 */
5523 resolveTopic(issuingActor, targetActor, results)
5524 {
5525 /* get the topic resolver */
5526 local resolver = getTopicResolver(issuingActor, targetActor, true);
5527
5528 /* resolve the topic match tree */
5529 topicList_ = topicMatch.resolveNouns(resolver, results);
5530
5531 /* make sure it's properly packaged as a ResolvedTopic */
5532 topicList_ = resolver.packageTopicList(topicList_, topicMatch);
5533 }
5534
5535 /*
5536 * Set the resolved topic to the given object list. This is for use
5537 * in setResolvedObjects().
5538 */
5539 setResolvedTopic(topic)
5540 {
5541 /* if the topic isn't given as a ResolvedTopic, wrap it in one */
5542 if (!topic.ofKind(ResolvedTopic))
5543 topic = ResolvedTopic.wrapObject(topic);
5544
5545 /* use the match object from the ResolvedTopic */
5546 topicMatch = topic.topicProd;
5547
5548 /* finally, make a ResolveInfo list out of the ResolvedTopic */
5549 topicList_ = makeResolveInfoList(topic);
5550 }
5551
5552 /*
5553 * Set the topic match tree. This is for use in setObjectMatches().
5554 */
5555 setTopicMatch(topic)
5556 {
5557 /*
5558 * If it's given as a ResolveInfo, wrap it in a PreResolvedProd.
5559 * Otherwise, if it's not a topic match (a TopicProd object), and
5560 * it has tokens, re-parse it as a topic match to make sure we
5561 * get the grammar optimized for global scope.
5562 */
5563 if (topic.ofKind(ResolveInfo))
5564 {
5565 /* it's a resolved object, so wrap it in a fake match tree */
5566 topic = new PreResolvedProd(topic);
5567 }
5568 else if (!topic.ofKind(TopicProd))
5569 {
5570 /*
5571 * Re-parse it as a topic phrase. If our dobj resolver knows
5572 * the actors, use those; otherwise default to the player
5573 * character.
5574 */
5575 local issuer = (issuer_ != nil ? issuer_ : gPlayerChar);
5576 local target = (actor_ != nil ? actor_ : gPlayerChar);
5577 topic = reparseMatchAsTopic(topic, issuer, target);
5578 }
5579
5580 /* save the topic match */
5581 topicMatch = topic;
5582 }
5583
5584 /*
5585 * Re-parse a match tree as a topic phrase. Returns a TopicProd
5586 * match tree, if possible.
5587 */
5588 reparseMatchAsTopic(topic, issuingActor, targetActor)
5589 {
5590 local toks;
5591
5592 /* we can only proceed if the match tree has a token list */
5593 if ((toks = topic.getOrigTokenList()) != nil && toks.length() > 0)
5594 {
5595 /* parse it as a topic phrase */
5596 local match = topicPhrase.parseTokens(toks, cmdDict);
5597
5598 /*
5599 * if we parsed it successfully, and we have more than one
5600 * match, get the best of the bunch
5601 */
5602 if (match != nil && match.length() > 1)
5603 {
5604 /* set up a topic resolver for the match */
5605 local resolver = getTopicResolver(
5606 issuingActor, targetActor, true);
5607
5608 /* sort it and return the best match */
5609 return CommandRanking.sortByRanking(match, resolver)[1].match;
5610 }
5611 else if (match != nil && match.length() > 0)
5612 {
5613 /* we found exactly one match, so use it */
5614 return match[1];
5615 }
5616 }
5617
5618 /*
5619 * if we make it this far, we couldn't parse it as a topic, so
5620 * just return the original
5621 */
5622 return topic;
5623 }
5624
5625 /*
5626 * get the topic resolver
5627 */
5628 getTopicResolver(issuingActor, targetActor, reset)
5629 {
5630 /* create one if we don't already have one */
5631 if (topicResolver_ == nil)
5632 topicResolver_ = createTopicResolver(issuingActor, targetActor);
5633
5634 /* reset the resolver if desired */
5635 if (reset)
5636 topicResolver_.resetResolver();
5637
5638 /* return the cached resolver */
5639 return topicResolver_;
5640 }
5641
5642 /*
5643 * Create the topic resolver.
5644 */
5645 createTopicResolver(issuingActor, targetActor)
5646 {
5647 return new TopicResolver(
5648 self, issuingActor, targetActor, topicMatch, whichMessageTopic,
5649 getTopicQualifierResolver(issuingActor, targetActor, nil));
5650 }
5651
5652 /*
5653 * Get a message parameter by name. We'll return the topic for the
5654 * keyword 'topic', and inherit the default handling for anything
5655 * else.
5656 */
5657 getMessageParam(objName)
5658 {
5659 switch(objName)
5660 {
5661 case 'topic':
5662 /* return the topic */
5663 return getTopic();
5664
5665 default:
5666 /* inherit default handling */
5667 return inherited(objName);
5668 }
5669 }
5670
5671 /* get the current topic */
5672 getTopic()
5673 {
5674 /*
5675 * Because the topic list always contains one entry (a
5676 * ResolvedTopic object encapsulating the topic information),
5677 * our current topic is always simply the first and only element
5678 * of the topic list.
5679 */
5680 return topicList_[1].obj_;
5681 }
5682
5683
5684 /*
5685 * Get the resolver for qualifiers we find in the topic phrase
5686 * (qualifiers that might need resolution include things like
5687 * possessive adjectives and locational phrases).
5688 */
5689 getTopicQualifierResolver(issuingActor, targetActor, reset)
5690 {
5691 /* if we don't already have a qualifier resolver, create one */
5692 if (topicQualResolver_ == nil)
5693 topicQualResolver_ = createTopicQualifierResolver(
5694 issuingActor, targetActor);
5695
5696 /* reset it if desired */
5697 if (reset)
5698 topicQualResolver_.resetResolver();
5699
5700 /* return it */
5701 return topicQualResolver_;
5702 }
5703
5704 /* the topic qualifier resolver */
5705 topicQualResolver_ = nil
5706
5707 /* the resolved topic object list */
5708 topicList_ = nil
5709
5710 /* my cached topic resolver */
5711 topicResolver_ = nil
5712 ;
5713
5714 /* ------------------------------------------------------------------------ */
5715 /*
5716 * An action with a topic phrase as its only object, such as "think about
5717 * <topic>".
5718 *
5719 * The grammar rules that produce these actions must set topicMatch to
5720 * the topic match tree.
5721 *
5722 * Because we don't have any actual resolved objects, we're based on
5723 * IAction. Subclasses that implement particular topic actions should
5724 * override execAction() to carry out the action; this method can call
5725 * the getTopic() method of self to get a string giving the topic.
5726 */
5727 class TopicAction: TopicActionBase, IAction
5728 /*
5729 * Resolve objects. We don't actually have any normal objects to
5730 * resolve, but we do have to get the resolved topic phrase.
5731 */
5732 resolveNouns(issuingActor, targetActor, results)
5733 {
5734 /* the topic phrase counts as one noun slot */
5735 results.noteNounSlots(1);
5736
5737 /* resolve the topic */
5738 resolveTopic(issuingActor, targetActor, results);
5739 }
5740
5741 /* manually set the resolved objects */
5742 setResolvedObjects(topic)
5743 {
5744 /* set the resolved topic */
5745 setResolvedTopic(topic);
5746 }
5747
5748 /* manually set the pre-resolved match trees */
5749 setObjectMatches(topic)
5750 {
5751 /* note the new topic match tree */
5752 setTopicMatch(topic);
5753 }
5754
5755 /* we have a topic noun phrase */
5756 predicateNounPhrases = [&topicMatch]
5757 ;
5758
5759
5760 /* ------------------------------------------------------------------------ */
5761 /*
5762 * An Action with a direct object and a topic, such as "ask <actor> about
5763 * <topic>". Topics differ from ordinary noun phrases in scope: rather
5764 * than resolving to simulation objects based on location, we resolve
5765 * these based on the actor's knowledge.
5766 *
5767 * The grammar rules that produce these actions must set dobjMatch to the
5768 * resolvable object of the command (the <actor> in "ask <actor> about
5769 * <topic>"), and must set topicMatch to the topic match tree object,
5770 * which must be a TopicProd object. Note that, in some cases, the
5771 * phrasing might make the dobjMatch the indirect object, grammatically
5772 * speaking: "type <topic> on <object>"; even in such cases, use
5773 * dobjMatch for the resolvable object.
5774 *
5775 * When we resolve the topic, we will always resolve it to a single
5776 * object of class ResolvedTopic. This contains the literal tokens of
5777 * the original command plus a list of simulation objects matching the
5778 * topic name, ordered from best to worst. This is different from the
5779 * way most commands work, since we do not resolve the topic to a simple
5780 * game world object. We keep all of this extra information because we
5781 * don't want to perform disambiguation in the normal fashion, but
5782 * instead resolve as much as we can with what we're given, and then give
5783 * the specialized action code as much information as we can to let the
5784 * action code figure out how to respond to the topic.
5785 */
5786 class TopicTAction: TopicActionBase, TAction
5787 /*
5788 * reset the action
5789 */
5790 resetAction()
5791 {
5792 /* reset the inherited state */
5793 inherited();
5794
5795 /* forget our topic resolver */
5796 topicResolver_ = nil;
5797 }
5798
5799 /*
5800 * resolve our noun phrases to objects
5801 */
5802 resolveNouns(issuingActor, targetActor, results)
5803 {
5804 local dobjRes;
5805
5806 /*
5807 * the topic phrase counts as one noun slot, and the direct
5808 * object as another
5809 */
5810 results.noteNounSlots(2);
5811
5812 /* resolve the direct object, if we have one */
5813 if (dobjMatch != nil)
5814 {
5815 /* presume we won't find an unbound anaphor */
5816 needAnaphoricBinding_ = nil;
5817
5818 /*
5819 * if the direct object phrase is an empty phrase, resolve
5820 * the topic first
5821 */
5822 if (dobjMatch.isEmptyPhrase)
5823 resolveTopic(issuingActor, targetActor, results);
5824
5825 /* get the direct object resolver */
5826 dobjRes = getDobjResolver(issuingActor, targetActor, true);
5827
5828 /* resolve the direct object */
5829 dobjList_ = dobjMatch.resolveNouns(dobjRes, results);
5830
5831 /*
5832 * if that turned up an anaphor (LOOK UP BOOK IN ITSELF),
5833 * resolve the topic phrase as though it were the direct
5834 * object
5835 */
5836 if (needAnaphoricBinding_ && topicMatch != nil)
5837 dobjList_ = topicMatch.resolveNouns(dobjRes, results);
5838 }
5839
5840 /* resolve the topic */
5841 resolveTopic(issuingActor, targetActor, results);
5842 }
5843
5844 /*
5845 * Filter the resolved topic. This is called by our
5846 * TActionTopicResolver, which refers the resolution back to us.
5847 */
5848 filterTopic(lst, np, resolver)
5849 {
5850 /* by default, simply put everything in an undifferentiated list */
5851 return new ResolvedTopic(lst, [], [], topicMatch);
5852 }
5853
5854 /*
5855 * Retry a single-object action as an action taking both an object
5856 * and a topic phrase. We'll treat the original action's direct
5857 * object list as our direct object list, and we'll obtain a topic
5858 * phrase interactively.
5859 *
5860 * This routine terminates with 'exit' if it doesn't throw some other
5861 * error.
5862 */
5863 retryWithMissingTopic(orig)
5864 {
5865 local action;
5866
5867 /* create the new action based on the original action */
5868 action = createForRetry(orig);
5869
5870 /* use an empty topic phrase for the new action */
5871 action.topicMatch = new EmptyTopicPhraseProd();
5872
5873 /* initialize for the missing topic */
5874 action.initForMissingTopic(orig);
5875
5876 /* resolve and execute the replacement action */
5877 resolveAndReplaceAction(action);
5878 }
5879
5880 /* initialize a new action we're retrying for a missing direct object */
5881 initForMissingDobj(orig)
5882 {
5883 /*
5884 * The original action must have been a TopicAction, so we
5885 * already have a topic. Simply copy the original topic to use
5886 * as our own topic. For example: ASK ABOUT BOOK -> ASK <whom>
5887 * ABOUT BOOK.
5888 */
5889 topicMatch = new PreResolvedProd(orig.getTopic());
5890 }
5891
5892 /* initialize for retrying with a missing topic phrase */
5893 initForMissingTopic(orig)
5894 {
5895 local origDobj = orig.getDobj();
5896
5897 /*
5898 * The original action must have been a TAction, so we already
5899 * have a direct object. Simply copy the original direct object
5900 * for use as our own. For example: ASK BOB -> ASK BOB ABOUT
5901 * <what>.
5902 */
5903 dobjMatch = new PreResolvedProd(origDobj != nil
5904 ? origDobj : orig.dobjList_);
5905 }
5906
5907 /* create our TAction topic resolver */
5908 createTopicResolver(issuingActor, targetActor)
5909 {
5910 return new TActionTopicResolver(
5911 self, issuingActor, targetActor, topicMatch, whichMessageTopic,
5912 getTopicQualifierResolver(issuingActor, targetActor, nil));
5913 }
5914
5915 /*
5916 * In the topic phrase, we can use an anaphoric pronoun to refer
5917 * back to the direct object. Since we resolve the direct object
5918 * phrase first, we can simply return the direct object list as the
5919 * binding. If the direct object isn't resolved yet, make a note to
5920 * come back and re-bind the anaphor.
5921 */
5922 getAnaphoricBinding(typ)
5923 {
5924 /* if we've already resolved the direct object phrase, return it */
5925 if (dobjList_ not in (nil, []))
5926 return dobjList_;
5927
5928 /* no dobj yet - make a note that we need to re-bind the anaphor */
5929 needAnaphoricBinding_ = true;
5930
5931 /*
5932 * return an empty list for now to indicate that the anaphor is
5933 * acceptable but has no binding yet
5934 */
5935 return [];
5936 }
5937
5938 /*
5939 * Flag: we have been asked for an anaphoric binding, but we don't
5940 * have a binding available. We'll check this after resolving the
5941 * first-resolved noun phrase so that we can go back and re-resolve
5942 * it again after resolving the other noun phrase.
5943 */
5944 needAnaphoricBinding_ = nil
5945
5946 /* we have a direct object and a topic phrase */
5947 predicateNounPhrases = [&dobjMatch, &topicMatch]
5948
5949 /* get an object role */
5950 getRoleFromIndex(idx)
5951 {
5952 /*
5953 * index 2 is the topic object, which is always in the indirect
5954 * object role; for others, inherit the default handling
5955 */
5956 return (idx == 2 ? IndirectObject : inherited(idx));
5957 }
5958
5959 /* get the OtherObject role for the given role */
5960 getOtherObjectRole(role)
5961 {
5962 /* the complementary roles are DirectObject and IndirectObject */
5963 return (role == DirectObject ? IndirectObject : DirectObject);
5964 }
5965
5966 /* get the resolved object in a given role */
5967 getObjectForRole(role)
5968 {
5969 /*
5970 * the topic is in the IndirectObject role; inherit the default
5971 * for others
5972 */
5973 return (role == IndirectObject ? getTopic() : inherited(role));
5974 }
5975
5976 /* get the match tree for the given role */
5977 getMatchForRole(role)
5978 {
5979 /*
5980 * the topic is in the IndirectObject role; inherit the default
5981 * for anything else
5982 */
5983 return (role == IndirectObject ? topicMatch : inherited(role));
5984 }
5985
5986 /*
5987 * Manually set the resolved objects. We'll set our direct and
5988 * indirect objects.
5989 */
5990 setResolvedObjects(dobj, topic)
5991 {
5992 /* inherit default handling for the direct object */
5993 inherited(dobj);
5994
5995 /* set the resolved topic */
5996 setResolvedTopic(topic);
5997 }
5998
5999 /* manually set the pre-resolved match trees */
6000 setObjectMatches(dobj, topic)
6001 {
6002 /* inherit default handling for the direct object */
6003 inherited(dobj);
6004
6005 /* note the new topic match tree */
6006 setTopicMatch(topic);
6007 }
6008
6009 /*
6010 * Get the list of active objects. We return only our direct
6011 * object, since our topic isn't actually a simulation object.
6012 */
6013 getCurrentObjects()
6014 {
6015 return [dobjCur_];
6016 }
6017
6018 /* set the current objects */
6019 setCurrentObjects(lst)
6020 {
6021 dobjCur_ = lst[1];
6022 dobjInfoCur_ = nil;
6023 }
6024
6025 /* the resolved topic object list */
6026 topicList_ = nil
6027
6028 /* my cached topic resolver */
6029 topicResolver_ = nil
6030
6031 /* grammatical role played by topic phrase in generated messages */
6032 whichMessageTopic = nil
6033
6034 /* -------------------------------------------------------------------- */
6035 /*
6036 * Direct Object Resolver implementation. We serve as our own
6037 * direct object resolver, so we define any special resolver
6038 * behavior here.
6039 */
6040
6041 /* the true role of the resolved object is always as the direct object */
6042 whichObject = DirectObject
6043
6044 /*
6045 * What we call our direct object might actually be playing the
6046 * grammatical role of the indirect object - in order to inherit
6047 * easily from TAction, we call our resolved object our direct
6048 * object, regardless of which grammatical role it actually plays.
6049 * For the most part it doesn't matter which is which; but for the
6050 * purposes of our resolver, we actually do care about its real role.
6051 * So, override the resolver method whichMessageObject so that it
6052 * returns whichever role is NOT served by the topic object.
6053 */
6054 whichMessageObject = (whichMessageTopic == DirectObject
6055 ? IndirectObject : DirectObject)
6056 ;
6057
6058 /*
6059 * "Conversation" TopicTAction. Many TopicTAction verbs involve
6060 * conversation with an actor, who's specified as the direct object: ASK
6061 * <actor> ABOUT <topic>, TELL <actor> ABOUT <topic>, ASK <actor> FOR
6062 * <topic>. For these common cases, the most likely default direct
6063 * object is the last interlocutor of the actor performing the command -
6064 * that is, ASK ABOUT BOOK should by default be directed to whomever we
6065 * were speaking to last.
6066 *
6067 * This subclass is suitable for such verbs. When asked for a default
6068 * direct object, we'll check for a current interlocutor, and use it as
6069 * the default if available. If no interlocutor is available, we'll
6070 * inherit the standard default handling.
6071 */
6072 class ConvTopicTAction: TopicTAction
6073 getDefaultDobj(np, resolver)
6074 {
6075 /*
6076 * check to see if the actor has a default interlocutor; if so,
6077 * use it as the default actor to be addressed here, otherwise
6078 * use the default handling
6079 */
6080 local obj = resolver.getTargetActor().getCurrentInterlocutor();
6081 if (obj != nil)
6082 return [new ResolveInfo(obj, 0, nil)];
6083 else
6084 return inherited(np, resolver);
6085 }
6086
6087 /*
6088 * Create the topic resolver. Use a conversational topic resolver
6089 * for this type of action.
6090 */
6091 createTopicResolver(issuingActor, targetActor)
6092 {
6093 return new ConvTopicResolver(
6094 self, issuingActor, targetActor, topicMatch, whichMessageTopic,
6095 getTopicQualifierResolver(issuingActor, targetActor, nil));
6096 }
6097 ;
6098
6099
6100 /* ------------------------------------------------------------------------ */
6101 /*
6102 * A conversational intransitive action. This class is for actions such
6103 * as Hello, Goodbye, Yes, No - conversational actions that don't involve
6104 * any topics or other objects, but whose expression is entirely
6105 * contained in the verb.
6106 */
6107 class ConvIAction: IAction
6108 /* this action is conversational */
6109 isConversational(issuer) { return true; }
6110 ;
6111
6112 /* ------------------------------------------------------------------------ */
6113 /*
6114 * Resolved Topic object. The topic of a TopicTAction always resolves to
6115 * one of these objects.
6116 */
6117 class ResolvedTopic: object
6118 construct(inScope, likely, others, prod)
6119 {
6120 /*
6121 * Remember our lists of objects. We keep three separate lists,
6122 * so that the action knows how we've classified the objects
6123 * matching our phrase. We keep a list of objects that are in
6124 * scope; a list of objects that aren't in scope but which the
6125 * actor thinks are likely topics; and a list of all of the other
6126 * matches.
6127 *
6128 * We keep only the simulation objects in these retained lists -
6129 * we don't keep the full ResolveInfo data here.
6130 */
6131 inScopeList = inScope.mapAll({x: x.obj_});
6132 likelyList = likely.mapAll({x: x.obj_});
6133 otherList = others.mapAll({x: x.obj_});
6134
6135 /* keep the production match tree */
6136 topicProd = prod;
6137
6138 /*
6139 * But it might still be interesting to have the ResolveInfo
6140 * data, particularly for information on the vocabulary match
6141 * strength. Keep that information in a separate lookup table
6142 * indexed by simulation object.
6143 */
6144 local rt = new LookupTable();
6145 others.forEach({x: rt[x.obj_] = x});
6146 likely.forEach({x: rt[x.obj_] = x});
6147 inScope.forEach({x: rt[x.obj_] = x});
6148
6149 /* save the ResolvedInfo lookup table */
6150 resInfoTab = rt;
6151 }
6152
6153 /*
6154 * Static method: create a ResolvedTopic to represent an object
6155 * that's already been resolved to a game object for the current
6156 * action. 'role' is the object role to wrap (DirectObject,
6157 * IndirectObject, etc).
6158 */
6159 wrapActionObject(role)
6160 {
6161 local rt;
6162
6163 /* create a ResolvedTopic with just the match tree */
6164 rt = new ResolvedTopic([], [], [], gAction.getMatchForRole(role));
6165
6166 /*
6167 * add the current resolved object in the role as the one
6168 * in-scope match
6169 */
6170 rt.inScopeList += gAction.getObjectForRole(role);
6171
6172 /* return the ResolvedTopic wrapper */
6173 return rt;
6174 }
6175
6176 /*
6177 * Static method: create a ResolvedTopic to represent the given
6178 * object.
6179 */
6180 wrapObject(obj)
6181 {
6182 local rt;
6183
6184 /* create a ResolvedTopic with a PreResolvedProd for the object */
6185 rt = new ResolvedTopic([], [], [], new PreResolvedProd(obj));
6186
6187 /* add the given object or objects as the in-scope match list */
6188 rt.inScopeList += obj;
6189
6190 /* return the ResolvedTopic wrapper */
6191 return rt;
6192 }
6193
6194 /*
6195 * Get the best object match to the topic. This is a default
6196 * implementation that can be changed by game authors or library
6197 * extensions to implement different topic-matching strategies. This
6198 * implementation simply picks an object arbitrarily from the
6199 * "strongest" of the three lists we build: if there's anything in
6200 * the inScopeList, we choose an object from that list; otherwise, if
6201 * there's anything in the likelyList, we choose an object from that
6202 * list; otherwise we choose an object from the otherList.
6203 */
6204 getBestMatch()
6205 {
6206 /* if there's an in-scope match, pick one */
6207 if (inScopeList.length() != 0)
6208 return inScopeList[1];
6209
6210 /* nothing's in scope, so try to pick a likely match */
6211 if (likelyList.length() != 0)
6212 return likelyList[1];
6213
6214 /*
6215 * there's not even anything likely, so pick an "other", if
6216 * there's anything in that list
6217 */
6218 if (otherList.length() != 0)
6219 return otherList[1];
6220
6221 /* there are no matches at all - return nil */
6222 return nil;
6223 }
6224
6225 /*
6226 * Is the given object among the possible matches for the topic?
6227 */
6228 canMatchObject(obj)
6229 {
6230 return inScopeList.indexOf(obj) != nil
6231 || likelyList.indexOf(obj) != nil
6232 || otherList.indexOf(obj) != nil;
6233 }
6234
6235 /* get the original text of the topic phrase */
6236 getTopicText() { return topicProd.getOrigText(); }
6237
6238 /*
6239 * Are we allowed to match the topic text literally, for parsing
6240 * purposes? If this is true, it means that we can match the literal
6241 * text the player entered against strings, regular expressions,
6242 * etc.; for example, we can match a TopicMatchTopic's matchPattern
6243 * regular expression. If this is nil, it means that we can only
6244 * interpret the meaning of the resolved topic by looking at the
6245 * various topic match lists (inScopeList, likelyList, otherList).
6246 *
6247 * By default, we simply return true. Note that the base library
6248 * never has any reason of its own to disallow literal matching of
6249 * topic text; this property is purely for the use of language
6250 * modules, to handle language-specific input that parses at a high
6251 * level as a topic phrase but which has some idiomatic or
6252 * grammatical function that makes it in appropriate to try to
6253 * extract the meaning of the resolved topic from the literal text of
6254 * the topic phrase in isolation. This case doesn't seem to arise in
6255 * English, but does occur in other languages: Michel Nizette cites
6256 * "parlez-en a Bob" as an example in French, where "en" is
6257 * essentially a particle modifying the verb, not a full-fledged
6258 * phrase that we can interpret separately as a topic.
6259 */
6260 canMatchLiterally = true
6261
6262 /*
6263 * get the original tokens of the topic phrase, in canonical
6264 * tokenizer format
6265 */
6266 getTopicTokens() { return topicProd.getOrigTokenList(); }
6267
6268 /*
6269 * get the original word strings of the topic phrase - this is
6270 * simply a list of the original word strings (in their original
6271 * case), without any of the extra information of the more
6272 * complicated canonical tokenizer format
6273 */
6274 getTopicWords()
6275 {
6276 /* return just the original text strings from the token list */
6277 return topicProd.getOrigTokenList().mapAll({x: getTokOrig(x)});
6278 }
6279
6280 /*
6281 * Get the parser ResolveInfo object for a given matched object.
6282 * This recovers the ResolveInfo describing the parsing result for
6283 * any object in the resolved object lists (inScopeList, etc).
6284 */
6285 getResolveInfo(obj) { return resInfoTab[obj]; }
6286
6287 /*
6288 * Our lists of resolved objects matching the topic phrase,
6289 * separated by classification.
6290 */
6291 inScopeList = nil
6292 likelyList = nil
6293 otherList = nil
6294
6295 /*
6296 * The production match tree object that matched the topic phrase in
6297 * the command. This can be used to obtain the original tokens of
6298 * the command or the original text of the phrase.
6299 */
6300 topicProd = nil
6301
6302 /*
6303 * ResolveInfo table for the resolved objects. This is a lookup
6304 * table indexed by simulation object. Each entry in the resolved
6305 * object lists (inScopeList, etc) has have a key in this table, with
6306 * the ResolveInfo object as the value for the key. This can be used
6307 * to recover the ResolveInfo object describing the parser results
6308 * for this object.
6309 */
6310 resInfoTab = nil
6311 ;
6312
6313 /*
6314 * A special topic for "nothing." It's occasionally useful to be able
6315 * to construct a TopicTAction with an empty topic phrase. For the
6316 * topic phrase to be well-formed, we need a valid ResolvedTopic object,
6317 * even though it won't refer to anything.
6318 */
6319 resolvedTopicNothing: ResolvedTopic
6320 inScopeList = []
6321 likelyList = []
6322 otherList = []
6323
6324 getTopicText() { return ''; }
6325 getTopicTokens() { return []; }
6326 getTopicWords() { return []; }
6327 ;
6328
6329 /*
6330 * Topic Resolver
6331 */
6332 class TopicResolver: Resolver
6333 construct(action, issuingActor, targetActor, prod, which,
6334 qualifierResolver)
6335 {
6336 /* inherit the base class constructor */
6337 inherited(action, issuingActor, targetActor);
6338
6339 /* the topic phrase doesn't have a true resolved role */
6340 whichObject = nil;
6341
6342 /* remember the grammatical role of our object in the command */
6343 whichMessageObject = which;
6344
6345 /* remember our topic match tree */
6346 topicProd = prod;
6347
6348 /* remember the resolver for qualifier phrases */
6349 qualifierResolver_ = qualifierResolver;
6350 }
6351
6352 resetResolver()
6353 {
6354 /* inherit the default handling */
6355 inherited();
6356
6357 /* reset our qualifier resolver as well */
6358 qualifierResolver_.resetResolver();
6359 }
6360
6361 /*
6362 * package a resolved topic list - if it's not already represented as
6363 * a ResolvedTopic object, we'll apply that wrapping
6364 */
6365 packageTopicList(lst, match)
6366 {
6367 /*
6368 * if the topic is other than a single ResolvedTopic object, run
6369 * it through the topic resolver's ambiguous noun phrase filter
6370 * to get it into that canonical form
6371 */
6372 if (lst != nil
6373 && (lst.length() > 1
6374 || (lst.length() == 1 && !lst[1].obj_.ofKind(ResolvedTopic))))
6375 {
6376 /* it's not in canonical form, so get it in canonical form now */
6377 lst = filterAmbiguousNounPhrase(lst, 1, match);
6378 }
6379
6380 /* return the result */
6381 return lst;
6382 }
6383
6384 /* our qualifier resolver */
6385 qualifierResolver_ = nil
6386
6387 /* get our qualifier resolver */
6388 getQualifierResolver() { return qualifierResolver_; }
6389 getPossessiveResolver() { return qualifierResolver_; }
6390
6391 /*
6392 * Determine if the object is in scope. We consider any vocabulary
6393 * match to be in scope for the purposes of a topic phrase, since the
6394 * subject matter of topics is mere references to things, not the
6395 * things themselves; we can, for example, ASK ABOUT things that
6396 * aren't physically present, or even about completely abstract
6397 * ideas.
6398 */
6399 objInScope(obj) { return true; }
6400
6401 /*
6402 * our scope is global, because we don't limit the scope to the
6403 * physical senses
6404 */
6405 isGlobalScope = true
6406
6407 /*
6408 * Determine if an object is in physical scope. We'll accept
6409 * anything that's in physical scope, and we'll also accept any topic
6410 * object that the actor knows about.
6411 *
6412 * Note that this isn't part of the basic Resolver interface. It's
6413 * instead provided as a service routine for our subclasses, so that
6414 * they can easily determine the physical scope of an object if
6415 * needed.
6416 */
6417 objInPhysicalScope(obj)
6418 {
6419 /*
6420 * it's in physical scope, or if the actor knows about it as a
6421 * topic, it's in scope
6422 */
6423 return (scope_.indexOf(obj) != nil);
6424 }
6425
6426 /*
6427 * Filter an ambiguous noun phrase list using the strength of
6428 * possessive qualification, if any. For a topic phrase, we want to
6429 * keep all of the possibilities.
6430 */
6431 filterPossRank(lst, num)
6432 {
6433 return lst;
6434 }
6435
6436 /*
6437 * Filter an ambiguous noun list.
6438 *
6439 * It is almost always undesirable from a user interface perspective
6440 * to ask for help disambiguating a topic phrase. In the first
6441 * place, since all topics tend to be in scope all the time, we
6442 * might reveal too much about the inner model of the story if we
6443 * were to enumerate all of the topic matches to a phrase. In the
6444 * second place, topics are used in conversational contexts, so it
6445 * almost never make sense for the parser to ask for clarification -
6446 * the other member of the conversation might ask, but not the
6447 * parser. So, we'll always filter the list to the required number,
6448 * even if it means we choose arbitrarily.
6449 *
6450 * As a first cut, we prefer objects that are physically in scope to
6451 * those not in scope: if the player is standing next to a control
6452 * panel and types "ask bob about control panel," it makes little
6453 * sense to consider any other control panels in the simulation.
6454 *
6455 * As a second cut, we'll ask the actor to filter the list. Games
6456 * that keep track of the actor's knowledge can use this to filter
6457 * according to topics the actor is likely to know about.
6458 */
6459 filterAmbiguousNounPhrase(lst, requiredNum, np)
6460 {
6461 /* ask the action to create the ResolvedTopic */
6462 local rt = resolveTopic(lst, requiredNum, np);
6463
6464 /* wrap the ResolvedTopic in the usual ResolveInfo list */
6465 return [new ResolveInfo(rt, 0, np)];
6466 }
6467
6468 /*
6469 * Resolve the topic phrase. This returns a ResolvedTopic object
6470 * encapsulating the resolution of the phrase.
6471 *
6472 * This default base class implementation simply creates a resolved
6473 * topic list with the whole set of possible matches
6474 * undifferentiated. Subclasses for specialized actions might want
6475 * to differentiate the items in the list, based on things like the
6476 * actor's knowledge so far or what's in physical scope.
6477 */
6478 resolveTopic(lst, requiredNum, np)
6479 {
6480 /* return a ResolvedTopic that lumps everything in the main list */
6481 return new ResolvedTopic(lst, [], [], topicProd);
6482 }
6483
6484 /*
6485 * Resolve an unknown phrase. We allow unknown words to be used in
6486 * topics; we simply return a ResolvedTopic that doesn't refer to
6487 * any simulation objects at all.
6488 */
6489 resolveUnknownNounPhrase(tokList)
6490 {
6491 /*
6492 * Create our ResolvedTopic object for the results. We have
6493 * words we don't know, so we're not referring to any objects,
6494 * so our underlying simulation object list is empty.
6495 */
6496 local rt = new ResolvedTopic([], [], [], topicProd);
6497
6498 /* return a resolved topic object with the empty list */
6499 return [new ResolveInfo(rt, 0, new TokenListProd(tokList))];
6500 }
6501
6502 /* filter a plural */
6503 filterPluralPhrase(lst, np)
6504 {
6505 /*
6506 * Handle this the same way we handle an ambiguous noun phrase,
6507 * so that we yield only one object. Topics are inherently
6508 * singular; we'll allow asking about a grammatically plural
6509 * term, but we'll turn it into a single topic result.
6510 */
6511 return filterAmbiguousNounPhrase(lst, 1, np);
6512 }
6513
6514 /* get a default object */
6515 getDefaultObject(np)
6516 {
6517 /* there is never a default for a topic */
6518 return nil;
6519 }
6520
6521 /* it's fine not to match a topic phrase */
6522 noVocabMatch(action, txt) { }
6523 noMatch(action, txt) { }
6524 noMatchPoss(action, txt) { }
6525
6526 /* we don't allow ALL or provide defaults */
6527 getAll(np) { return []; }
6528 getAllDefaults() { return []; }
6529
6530 /* the production match tree for the topic phrase we're resolving */
6531 topicProd = nil
6532 ;
6533
6534 /*
6535 * A topic resolver specialized for TopicTActions - actions involving a
6536 * topic and a physical object, such as CONSULT ABOUT. For these topics,
6537 * we'll let the action handle the resolution.
6538 */
6539 class TActionTopicResolver: TopicResolver
6540 resolveTopic(lst, requiredNum, np)
6541 {
6542 /* let the action handle it */
6543 return action_.filterTopic(lst, np, self);
6544 }
6545 ;
6546
6547 /*
6548 * A topic resolver specialized for conversational actions (ASK ABOUT,
6549 * TELL ABOUT, etc). When we resolve the topic, we'll differentiate the
6550 * resolution to differentiate based on the knowledge of the actor who's
6551 * performing the command.
6552 */
6553 class ConvTopicResolver: TopicResolver
6554 /*
6555 * Resolve the topic phrase. We'll break up the vocabulary matches
6556 * into three sublists: the objects that are either in physical scope
6557 * or known to the actor performing the command; objects that the
6558 * actor considers likely topics; and everything else.
6559 */
6560 resolveTopic(lst, requiredNum, np)
6561 {
6562 local inScope;
6563 local actorPrefs;
6564
6565 /*
6566 * First, get the subset of items that are in conversational
6567 * scope - we'll consider this the best set of matches.
6568 */
6569 inScope = lst.subset({x: objInConvScope(x.obj_)});
6570
6571 /*
6572 * eliminate the in-scope items from the list, so we can
6573 * consider only what remains
6574 */
6575 lst -= inScope;
6576
6577 /*
6578 * ask the actor to pick out the most likely set of topics from
6579 * the ones that remain
6580 */
6581 actorPrefs = lst.subset({x: actor_.isLikelyTopic(x.obj_)});
6582
6583 /* eliminate those items from the list */
6584 lst -= actorPrefs;
6585
6586 /* create our ResolvedTopic object and return it */
6587 return new ResolvedTopic(inScope, actorPrefs, lst, topicProd);
6588 }
6589
6590 /*
6591 * Determine if an object is in "conversational" scope - this returns
6592 * true if the object is in physical scope or it's known to the actor
6593 * performing the command.
6594 */
6595 objInConvScope(obj)
6596 {
6597 /*
6598 * if it's in physical scope, or the actor knows about it, it's
6599 * in conversation scope
6600 */
6601 return (objInPhysicalScope(obj) || actor_.knowsTopic(obj));
6602 }
6603 ;
6604
6605 /* ------------------------------------------------------------------------ */
6606 /*
6607 * System action. These actions are for out-of-game meta-verbs (save,
6608 * restore, undo). These verbs take no objects, must be performed by
6609 * the player (thus by the player character, not an NPC), and consume no
6610 * game clock time.
6611 */
6612 class SystemAction: IAction
6613 /* execute the action */
6614 execAction()
6615 {
6616 /*
6617 * Conceptually, system actions are performed by the player
6618 * directly, not by any character in the game (not even the
6619 * player character). However, we don't distinguish in the
6620 * command-entry user interface between a command the player is
6621 * performing and a command to the player character, hence we
6622 * can merely ensure that the command is not directed to a
6623 * non-player character.
6624 */
6625 if (!gActor.isPlayerChar)
6626 {
6627 gLibMessages.systemActionToNPC();
6628 exit;
6629 }
6630
6631 /*
6632 * system actions sometimes need to prompt for interactive
6633 * responses, so deactivate the report list - this will allow
6634 * interactive prompts to be shown immediately, not treated as
6635 * reports to be deferred until the command is finished
6636 */
6637 gTranscript.showReports(true);
6638 gTranscript.clearReports();
6639
6640 /* perform our specific action */
6641 execSystemAction();
6642
6643 /* re-activate the transcript for the next command */
6644 gTranscript.activate();
6645 }
6646
6647 /* each subclass must override this to perform its actual action */
6648 execSystemAction() { }
6649
6650 /*
6651 * Ask for an input file. We call the input manager, which freezes
6652 * the real-time clock, displays the appropriate local file selector
6653 * dialog, and restarts the clock.
6654 */
6655 getInputFile(prompt, dialogType, fileType, flags)
6656 {
6657 return inputManager.getInputFile(prompt, dialogType, fileType, flags);
6658 }
6659
6660 /* system actions consume no game time */
6661 actionTime = 0
6662 ;
6663
6664 /* ------------------------------------------------------------------------ */
6665 /*
6666 * An exception class for remappings that we can't handle.
6667 */
6668 class ActionRemappingTooComplexError: Exception
6669 ;
6670