Debian Codegraph @

terps/tads/tads3/lib/_main.t

raw
1 #charset "us-ascii"
2
3 /*
4 * Copyright (c) 2000, 2006 Michael J. Roberts. All Rights Reserved.
5 *
6 * This module defines a number of low-level functions and classes that
7 * most TADS 3 programs will need, whether based on the adv3 library or
8 * not. This module includes the main program entrypoint, the basic
9 * Exception classes, and the modular initialization framework.
10 *
11 * The compiler automatically links this module into every program by
12 * default, but you can override this by specifying the "-nodef" option
13 * to t3make. If you remove this module, you'll have to provide your own
14 * implementations for many of the functions and classes defined here.
15 */
16
17 #include "tads.h"
18 #include "reflect.h"
19 #include "strbuf.h"
20
21
22 /* ------------------------------------------------------------------------ */
23 /*
24 * Main program entrypoint. The VM invokes this function at program
25 * startup.
26 */
27 _main(args)
28 {
29 /* call the common main entrypoint, with no startup file specified */
30 _mainCommon(args, nil);
31 }
32
33 /* declare 'main' as a function, in case it's not otherwise defined */
34 extern function main;
35
36 /*
37 * Main program entrypoint for restoring a saved state. The VM invokes
38 * this function at startup instead of _main() when the user explicitly
39 * specifies a saved state file to restore when starting the program.
40 * (On a command-line interpreter, this would involve using a special
41 * option on the T3 interpreter command line; for a GUI shell, this
42 * might simply involve double-clicking on the desktop icon for a saved
43 * state file.)
44 *
45 * Note that we must export this as the 'mainRestore' symbol so that the
46 * interpreter knows how to find it.
47 */
48 export _mainRestore 'mainRestore';
49 _mainRestore(args, restoreFile)
50 {
51 /* call the common main entrypoint */
52 _mainCommon(args, restoreFile);
53 }
54
55 /*
56 * Common main entrypoint. This function can be called with or without
57 * a saved state file to restore.
58 */
59 _mainCommon(args, restoreFile)
60 {
61 try
62 {
63 /*
64 * Keep going as long as we keep restarting. Note that the
65 * restoreFile only counts on the first iteration, so we clear it
66 * out after each iteration; if we RESTART after that, we'll want
67 * to just start the game from the beginning.
68 */
69 for ( ; ; restoreFile = nil)
70 {
71 /* perform load-time initialization */
72 initAfterLoad();
73
74 /* if we're in preinit-only mode, we're done */
75 if (t3GetVMPreinitMode())
76 return;
77
78 /* catch any RESTART signals thrown out of the main entrypoint */
79 try
80 {
81 /*
82 * If there's a saved state file to restore, call our
83 * mainRestore() function instead of main(). If
84 * mainRestore() isn't defined, show a message to this
85 * effect but keep going.
86 */
87 if (restoreFile != nil
88 && dataType(mainGlobal.mainRestoreFunc) == TypeFuncPtr)
89 {
90 /*
91 * Call the user's main startup-and-restore
92 * entrypoint function. Note that we call indirectly
93 * through our function pointer so that we don't
94 * force a function called mainRestore() to be linked
95 * with the program.
96 */
97 (mainGlobal.mainRestoreFunc)(args, restoreFile);
98 }
99 else
100 {
101 /*
102 * if we have a restore file but no mainRestore
103 * routine, explain to the user that they'll have to
104 * restore manually
105 */
106 if (restoreFile != nil)
107 {
108 "\n[This program cannot restore the saved position
109 file automatically. Please try restoring the
110 saved position file again using a command within
111 the program.]\b";
112 }
113
114 /* call the selected main entrypoint */
115 flexcall(&main, args);
116 }
117
118 /*
119 * we made it through the main entrypoint without a
120 * restart, so we're done
121 */
122 break;
123 }
124 catch (RestartSignal rsig)
125 {
126 /*
127 * call the intrinsic restartGame function to reset all
128 * of the static objects to their initial state
129 */
130 restartGame();
131
132 /*
133 * Now that we've reset the VM, update the restart ID in
134 * the main globals. Note that we waited until now to do
135 * this, because this change would have been lost in the
136 * reset if we'd made the change before the reset. Note
137 * also that the 'rsig' object itself will survive the
138 * reset because the thrower presumably allocated it
139 * dynamically, hence it's not a static object subject to
140 * reset.
141 */
142 mainGlobal.restartID = rsig.restartID;
143
144 /*
145 * Now we can just continue on to the next iteration of
146 * the restart loop. This will take us back to the
147 * initialization and enter the game as though we'd just
148 * started the program again.
149 */
150 }
151 }
152 }
153 catch (ProgramException exc)
154 {
155 /*
156 * just re-throw these out to the VM, so that the VM exits to
157 * the operating system with an error indication
158 */
159 throw exc;
160 }
161 catch (Exception exc)
162 {
163 /* write output to the main console */
164 t3SetSay(_default_display_fn);
165
166 /* display the unhandled exception */
167 "\n<<exc.displayException()>>\n";
168 }
169 finally
170 {
171 /* before exiting, call registered exit handlers */
172 mainAtExit.callHandlers();
173 }
174 }
175
176 /* ------------------------------------------------------------------------ */
177 /*
178 * Flexible function call. This calls the given function, passing as
179 * many arguments from the given argument list as the function actually
180 * wants. If the list doesn't have enough arguments to satisfy the
181 * function's minimum requirements, we add 'nil' arguments to pad out the
182 * minimum. If the list exceeds the function's maximum, we drop
183 * arguments past the maximum.
184 */
185 flexcall(func, [args])
186 {
187 /* get the function's desired argument list */
188 local paramDesc = getFuncParams(func);
189
190 /* add or remove arguments as needed to fit the limits */
191 local n = args.length();
192 if (n < paramDesc[1])
193 {
194 /* we need more to satisfy the minimum - add nil values */
195 args += makeList(nil, paramDesc[1] - n);
196 }
197 else if (n > paramDesc[1] + paramDesc[2] && !paramDesc[3])
198 {
199 /*
200 * the function doesn't take infinite arguments, and we have more
201 * than it allows in the fixed plus optional parts, so drop the
202 * extra elements
203 */
204 args = args.sublist(1, paramDesc[1] + paramDesc[2]);
205 }
206
207 /* call the function */
208 func(args...);
209 }
210
211 /* ------------------------------------------------------------------------ */
212 /*
213 * Restart signal. This can be used to restart from the main
214 * entrypoint. The caller should create one of these objects, then use
215 * restartGame() (or an equivalent from a different function set, if
216 * appropriate) to reset static object state to the initial program load
217 * conditions, then throw the signal object.
218 */
219 class RestartSignal: Exception
220 construct()
221 {
222 /*
223 * use the next restart ID, so we can tell that we're on a fresh
224 * run on this session
225 */
226 restartID = mainGlobal.restartID + 1;
227 }
228 ;
229
230 /* ------------------------------------------------------------------------ */
231 /*
232 * General post-load initialization. The main program entrypoint
233 * _main() calls this routine to set up the default display function,
234 * run pre-initialization if necessary, and run initialization. This
235 * routine is also useful for the target of a restartGame() routine, to
236 * perform all of the basic load-time initialization again after a
237 * restart.
238 */
239 initAfterLoad()
240 {
241 /* establish the default display function */
242 t3SetSay(_default_display_fn);
243
244 /* if we haven't run preinit, do so now */
245 if (!mainGlobal.preinited_)
246 {
247 /*
248 * Explicitly run garbage collection prior to preinit.
249 *
250 * In most cases, this is unnecessary, but in some cases it's
251 * important. In particular, object loops (over all objects, or
252 * over all instances of a given class) can still see otherwise
253 * unreachable objects. It's common to do object loops in
254 * preinit to set up static data caches and tables and so on. If
255 * there *were* any garbage objects lying around, preinit could
256 * find them via object loops, and might register them into
257 * tables or what not.
258 *
259 * Even considering the preinit object loop, doing a garbage
260 * collection sweep would *still* be redundant in most cases,
261 * since preinit is normally done right after compilation, when
262 * the program wouldn't yet have had a chance to create any
263 * garbage objects to be worried about in object loops. However,
264 * there's still one more case to consider, and that's RESTART:
265 * in a debug build, or even in some release builds, we'd have to
266 * re-run preinit after a RESTART, and there certainly could be
267 * garbage objects left around from before the RESTART.
268 *
269 * To ensure that we deal gracefully with this combination of
270 * conditions - garbage objects, RESTART, and object loops in
271 * preinit - simply do an explicit garbage collection run before
272 * invoking preinit.
273 */
274 t3RunGC();
275
276 /* run our internal preinit */
277 _preinit();
278
279 /* remember that we've run preinit */
280 mainGlobal.preinited_ = true;
281 }
282
283 /* if we're not in preinit-only mode, run internal initialization */
284 if (!t3GetVMPreinitMode())
285 _init();
286 }
287
288
289
290 /* ------------------------------------------------------------------------ */
291 /*
292 * Module Execution Object. This is an abstract base class for various
293 * classes that provide modular execution hooks. This class and its
294 * subclasses are mix-in classes - they can be multiply inherited by any
295 * object (as long as it's not already some other kind of module
296 * execution object).
297 *
298 * The point of the Module Execution Object and its subclasses is to
299 * allow libraries and user code to define execution hooks, without
300 * having to worry about what other libraries and user code bits are
301 * defining the same hook. When we need to execute a hook defined via
302 * this object, we iterate over all of the instances of the appropriate
303 * subclass and invoke its execute() method.
304 *
305 * By default, the order of execution is arbitrary. In some cases,
306 * though, dependencies will exist, so that one object cannot be invoked
307 * until another object has already been invoked. In these cases, you
308 * must set the execBeforeMe property to contain a list of the objects
309 * whose execute() methods must be invoked before this object's
310 * execute() method is invoked. The library will check this list before
311 * calling execute() on this object, and ensure that each object in the
312 * list has been invoked before calling this object's execute().
313 */
314 class ModuleExecObject: object
315 /*
316 * List of objects that must be executed before me - by default, the
317 * order doesn't matter, so we'll set this to an empty list.
318 * Instances can override this if it is necessary to execute other
319 * objects before this object can be executed.
320 */
321 execBeforeMe = []
322
323 /*
324 * List of objects that must be executed after me - this is
325 * analogous to execBeforeMe, but we make sure we run before these.
326 */
327 execAfterMe = []
328
329 /*
330 * Subclass-specific execution method. Each subclass should
331 * override this method to provide its execution code.
332 */
333 execute() { }
334
335
336 /*
337 * PRIVATE METHODS AND PROPERTIES. Subclasses and instances should
338 * not need to override or invoke these.
339 */
340
341 /* flag - true if we've been executed on this round */
342 isExecuted_ = nil
343
344 /* flag - true if we're in the process of executing */
345 isDoingExec_ = nil
346
347 /* execute - internal method: checks dependency order */
348 _execute()
349 {
350 /*
351 * If I've already been executed, there's nothing more that I
352 * need to do. We might be called by the arbitrarily-ordered
353 * iteration over all objects after we've already been executed,
354 * because we might be executed explicitly by an object that
355 * depends upon us if it's reached before we are.
356 */
357 if (isExecuted_)
358 return;
359
360 /*
361 * If we're in the process of executing any of the objects we
362 * depend upon, and a dependent calls us, we have a circular
363 * dependency.
364 */
365 if (isDoingExec_)
366 throw new CircularExecException(self);
367
368 /*
369 * Mark ourselves as being in the process of executing. If
370 * there are any circular dependencies (i.e., if we depend on an
371 * object, which in turn depends on us), it's clearly an error,
372 * in that both objects can't be executed before the other.
373 * This flag allows us to detect circular dependencies by
374 * noticing if we're called by a dependent while we're in the
375 * process of calling the things we depend upon.
376 */
377 isDoingExec_ = true;
378
379 /*
380 * Check each entry in my 'before' list to ensure that they've
381 * all been executed already. Invoke execute() now for any that
382 * haven't.
383 */
384 for (local i = 1, local cnt = execBeforeMe.length() ;
385 i <= cnt ; ++i)
386 {
387 local cur;
388
389 /* get this object */
390 cur = execBeforeMe[i];
391
392 /* if this one hasn't been executed yet, do so now */
393 if (!cur.isExecuted_)
394 {
395 /*
396 * This one hasn't been executed yet - explicitly
397 * execute it now. Note that we do this recursively
398 * through the internal execution method, so that 'cur'
399 * has a chance to execute any objects that it depends
400 * upon.
401 */
402 cur._execute();
403 }
404 }
405
406 /*
407 * we've resolved all of our dependencies, so we're good to go -
408 * run the user's execution code
409 */
410 execute();
411
412 /*
413 * mark ourselves as having been executed, so we don't run the
414 * user's code again should we be called again by a dependent or
415 * by the global iteration loop later in the scan
416 */
417 isExecuted_ = true;
418 isDoingExec_ = nil;
419 }
420
421 /* flag to indicate that this is the first time running classExec */
422 hasInitialized_ = nil
423
424 /*
425 * Class execution. Call this method on the particular class of
426 * modules to execute. We'll iterate over all instances of that
427 * class and invoke each instance's _execute() method.
428 */
429 classExec()
430 {
431 /*
432 * If this is the first time running this classExec, turn
433 * execAfterMe dependencies into appropriate execBeforeMe
434 * dependencies.
435 */
436 if (!hasInitialized_)
437 {
438 /*
439 * Go through all instances of this type of initializer, and
440 * re-cast the execAfterMe lists as execBeforeMe lists.
441 */
442 forEachInstance(self,
443 function(obj)
444 {
445 foreach(local dependent in obj.execAfterMe)
446 dependent.execBeforeMe += obj;
447 });
448
449 /* remember that we're now initialized */
450 hasInitialized_ = true;
451 }
452
453 /*
454 * since we're starting a new round, clear all of the 'executed'
455 * flags in all of the objects, to ensure that we execute all
456 * objects on this round (this cleans up the flag settings from
457 * any previous rounds)
458 */
459 forEachInstance(self,
460 { obj: obj.isExecuted_ = obj.isDoingExec_ = nil });
461
462 /* execute all objects */
463 forEachInstance(self, { obj: obj._execute() });
464 }
465 ;
466
467 /*
468 * Pre-Initialization object. During pre-initialization, we'll invoke
469 * the execute() method on each instance of this class.
470 */
471 class PreinitObject: ModuleExecObject
472 /*
473 * Each instance of this object MUST override execute() with the
474 * specific pre-initialization code that the instance wants to
475 * perform.
476 *
477 * In addition, each instance can optionally set the property
478 * execBeforeMe to a list of the other PreinitObject's that must be
479 * invoked before this object is. If this property is not set, this
480 * object's place in the preinit execution order will be arbitrary.
481 */
482 ;
483
484 /*
485 * Initialization object. During initialization, just before calling
486 * the user's main(args) function, we'll invoke the execute() method on
487 * each instance of this class.
488 */
489 class InitObject: ModuleExecObject
490 /*
491 * Each instance of this object MUST override execute() with the
492 * specific initialization code that the instance wants to perform.
493 *
494 * In addition, each instance can optionally set the property
495 * execBeforeMe to a list of the other InitObject's that must be
496 * invoked before this object is. If this property is not set, this
497 * object's place in the initialization execution order will be
498 * arbitrary.
499 */
500 ;
501
502
503 /*
504 * Exception: circular execution dependency in ModuleExecObject
505 */
506 class CircularExecException: Exception
507 construct(obj) { obj_ = obj; }
508 displayException()
509 {
510 "circular module dependency detected (refer to
511 ModuleExecObject._execute() in _main.t)";
512 }
513
514 /*
515 * The object that detected the circular dependency. We can't use
516 * this for much ourselves, but it might be useful to store this
517 * information so that it's available to the programmer from within
518 * the debugger.
519 */
520 obj_ = nil
521 ;
522
523 /*
524 * Library pre-initialization. This is called immediately after
525 * compilation to pre-initialize the program. Any changes made here to
526 * object states become part of the initial state stored in the image
527 * file, so this establishes the static initial state of the program.
528 *
529 * The advantage of doing work during pre-initialization is that this
530 * work is done once, during compilation, and is thus not repeated each
531 * time a user starts the program. Time-consuming initialization work
532 * can thus be made invisible to the user.
533 *
534 * Note that the pre-initialization code should never do anything that
535 * involves the user interface, since this code runs during compilation
536 * and does not run again when users start the program. So, anything
537 * that you want a user to see must be done during normal initialization
538 * (such as in the main() routine), not here.
539 */
540 _preinit()
541 {
542 local symtab;
543
544 /* try getting the mainRestore() function from the global symbol table */
545 if ((symtab = t3GetGlobalSymbols()) != nil)
546 mainGlobal.mainRestoreFunc = symtab['mainRestore'];
547
548 /* execute all preinit objects */
549 PreinitObject.classExec();
550 }
551
552 /*
553 * Library initialization. This is called during each program start-up
554 * to initialize the program. Since this is run each time the user
555 * starts the program, this can display any introductory messages, set
556 * up the user interface, and so on.
557 */
558 _init()
559 {
560 /* execute all init objects */
561 InitObject.classExec();
562 }
563
564 /* ------------------------------------------------------------------------ */
565 /*
566 * For convenience, a simple object iterator function. This function
567 * invokes a callback function for each instance of the given class, in
568 * arbitrary order.
569 *
570 * The callback is invoked with one argument, which gives the current
571 * instance. The callback can "break" out of the loop by throwing a
572 * BreakLoopSignal, which can be done conveniently using the breakLoop
573 * macro.
574 */
575 forEachInstance(cls, func)
576 {
577 try
578 {
579 /* loop over all objects of the given class */
580 for (local obj = firstObj(cls) ; obj != nil ; obj = nextObj(obj, cls))
581 func(obj);
582 }
583 catch (BreakLoopSignal sig)
584 {
585 /*
586 * ignore the signal - it simply means we want to terminate the
587 * loop and return to the caller
588 */
589 }
590 }
591
592 /*
593 * Find an instance of the given class for which the given function
594 * returns true. We iterate over objects of the given class in
595 * arbitrary order, and return the first instance for which the function
596 * returns true. Retursn nil if there is no such instance.
597 */
598 instanceWhich(cls, func)
599 {
600 /* loop over all objects of the given class */
601 for (local obj = firstObj(cls) ; obj != nil ; obj = nextObj(obj, cls))
602 {
603 /* if the callback returns true for this object, return the object */
604 if (func(obj))
605 return obj;
606 }
607
608 /*
609 * we didn't find any instances for which the callback returns true;
610 * indicate this by returning nil
611 */
612 return nil;
613 }
614
615 /*
616 * An exception object for breaking out of a callback loop, such as
617 * forEachInstance.
618 */
619 class BreakLoopSignal: Exception
620 displayException() { "loop break signal"; }
621 ;
622
623
624 /* ------------------------------------------------------------------------ */
625 /*
626 * Get the "translated" datatype of a value. This is essentially the
627 * same as dataType(), except that anonymous function objects and dynamic
628 * function objects are treated as being "function pointer" types
629 * (TypeFuncPtr).
630 */
631 dataTypeXlat(val)
632 {
633 local t;
634
635 /* get the base type */
636 t = dataType(val);
637
638 /* if it's an anonymous function, return TypeFuncPtr */
639 if (t == TypeObject
640 && (val.ofKind(AnonFuncPtr)
641 || (defined(DynamicFunc) && val.ofKind(DynamicFunc))))
642 return TypeFuncPtr;
643
644 /* otherwise, just return the base type */
645 return t;
646 }
647
648 /* ------------------------------------------------------------------------ */
649 /*
650 * Base class for all exception objects. We derive all exceptions from
651 * this base class so that we can write 'catch' blocks that catch all
652 * exceptions by catching 'Exception'.
653 *
654 * The displayException() method displays a message describing the
655 * exception. Subclasses should override this method.
656 */
657 class Exception: object
658 /* construct, with an optional message describing the error */
659 construct(msg?, ...)
660 {
661 /* if there's a message, save it, otherwise keep the default */
662 if (msg != nil)
663 errmsg_ = msg;
664 }
665
666 /* display the exception - should always be overridden */
667 displayException()
668 {
669 "<<errmsg_>>";
670 }
671
672 /*
673 * Get the exception message as a string. This captures the output
674 * of displayException() and returns it a string. Use this instead
675 * of accessing errmsg_, since that member is private and might not
676 * reflect the actual displayed message.
677 */
678 getExceptionMessage()
679 {
680 /* capture and return the displayed exception message as a string */
681 return _outputCapture({: displayException() });
682 }
683
684 /*
685 * Private member: The error message passed to the constructor, if
686 * any. Note that this doesn't necessarily contain the actual
687 * displayed exception message, since displayException() can be
688 * overridden in subclasses to display additional parameters or other
689 * text entirely. The definitive message is the one that
690 * displayException() generates. If you want the displayed message
691 * as a string, use getExceptionMessage().
692 */
693 errmsg_ = 'Unknown exception'
694
695 /*
696 * Display a stack trace, given a list of T3StackInfo objects. Note
697 * that, for efficiency, we do not by default cache a stack trace
698 * when an exception occurs; individual subclasses can obtain a
699 * stack trace if desired at construction and use the information to
700 * show a stack trace for the exception.
701 */
702 showStackTrace(stackList)
703 {
704 local haveSrc;
705
706 /* check to see if there's any source info in the stack trace */
707 haveSrc = nil;
708 foreach (local cur in stackList)
709 {
710 /* note if we have source info here */
711 if (cur.srcInfo_ != nil)
712 {
713 /*
714 * we have source information - note it and stop
715 * searching, since even one bit of source info is
716 * enough to show the stack
717 */
718 haveSrc = true;
719 break;
720 }
721 }
722
723 /*
724 * if we have any source information at all, or we have
725 * reflection services available to decode the stack trace
726 * symbolically, show the stack
727 */
728 if (haveSrc || mainGlobal.reflectionObj != nil)
729 {
730 for (local i = 1, local cnt = stackList.length() ; i <= cnt ; ++i)
731 {
732 local cur = stackList[i];
733
734 /* show a mark next to level 1, spaces elsewhere */
735 if (i == 1)
736 "--&gt;";
737 else
738 "\ \ \ ";
739
740 /*
741 * if there's a system reflection object, show symbolic
742 * information on the current function call; otherwise,
743 * simply show the source location
744 */
745 if (mainGlobal.reflectionObj != nil)
746 {
747 /* reflection is available - show full symbolic info */
748 "<<mainGlobal.reflectionObj.
749 formatStackFrame(cur, true)>>";
750 }
751 else
752 {
753 /* no reflection information - show source only */
754 if (cur.srcInfo_ != nil)
755 "<<cur.srcInfo_[1]>>, line <<cur.srcInfo_[2]>>";
756 else if (cur.isSystem())
757 "&lt;System&gt;";
758 else
759 "???";
760 }
761
762 /* end the line */
763 "\n";
764 }
765 }
766 }
767 ;
768
769
770 /* ------------------------------------------------------------------------ */
771 /*
772 * RuntimeError exception class. The VM creates and throws an instance
773 * of this class when any run-time error occurs. The VM explicitly sets
774 * the exceptionMessage property to a string giving the VM error message
775 * for the run-time error that occurred.
776 */
777 class RuntimeError: Exception
778 construct(errno, ...)
779 {
780 /* remember the VM error number */
781 errno_ = errno;
782
783 /*
784 * Store a stack trace for the current location. Always discard
785 * the first element of the result, since this will reflect
786 * RuntimeError.construct, which is obviously not interesting.
787 */
788 stack_ = t3GetStackTrace().sublist(2);
789
790 /*
791 * The next element of the stack trace is usually a native code
792 * frame, because the VM itself invokes our constructor in
793 * response to a runtime exception; this is not an interesting
794 * frame, so if it's present, remove it.
795 */
796 if (stack_.length() > 0 && stack_[1].isSystem())
797 stack_ = stack_.sublist(2);
798 }
799
800 /* create a runtime error with a given error message */
801 newRuntimeError(errno, msg)
802 {
803 local e = new RuntimeError(errno);
804 e.exceptionMessage = msg;
805 return e;
806 }
807
808 /* display the exception */
809 displayException()
810 {
811 /* show the exception message */
812 "Runtime error: <<exceptionMessage>>\n";
813
814 /* show a stack trace if possible */
815 showStackTrace(stack_);
816 }
817
818 /* check to see if it's a debugger signal of some kind */
819 isDebuggerSignal()
820 {
821 return errno_ is in (
822 2391, /* debugger 'abort command' signal */
823 2392 /* debugger 'restart' signal */
824 );
825 }
826
827 /* the VM error number of the exception */
828 errno_ = 0
829
830 /* the exception message, provided to us by the VM after creation */
831 exceptionMessage = ''
832
833 /* the stack trace, which we store at the time we're created */
834 stack_ = nil
835 ;
836
837 /*
838 * Export our RuntimeError class so that the VM knows about it and can
839 * create instances of it. Also export our exceptionMessage property,
840 * so the VM can store its explanatory text there.
841 */
842 export RuntimeError;
843 export exceptionMessage;
844
845 /*
846 * Unknown character set exception - this is thrown from any routine that
847 * needs a local character set mapping when no mapping exists on the local
848 * platform.
849 */
850 class UnknownCharSetException: Exception
851 displayException = "Unknown character set"
852 ;
853
854 /*
855 * this exception object must be exported for use by the CharacterSet
856 * intrinsic class
857 */
858 export UnknownCharSetException 'CharacterSet.UnknownCharSetException';
859
860
861 /*
862 * A Program Exception terminates the entire program, passing an error
863 * indication to the operating system. The VM doesn't provide a way to
864 * specify the *particular* error code to return to the OS, as there's no
865 * portable set of error codes; rather, the VM simply returns a code to
866 * the OS that means generically that an error occurred, if there's any
867 * such concept on the local operating system. The VM will normally
868 * display this message just before it terminates the program, possibly
869 * with some additional text mentioning that a program error occurred
870 * (such as "unhandled exception: <your message>").
871 */
872 class ProgramException: Exception
873 construct(msg) { exceptionMessage = msg.htmlify(); }
874 displayException() { "<<exceptionMessage>> "; }
875 ;
876
877 /*
878 * A StorageServerError is thrown when a file operation on a remote
879 * storage server fails. The storage server is used when the game runs
880 * on a Web game server in client/server mode. In Web mode, files are
881 * stored on a separate storage server rather than on the Web server
882 * itself, so that the files can be transparently accessed if the game is
883 * continued from another Web server. This exception is used when a
884 * request to the storage server fails, which could be due to an error on
885 * the storage server, a network error communicating between the game
886 * server and the storage server, or an invalid request (e.g., incorrect
887 * user credentials).
888 */
889 class StorageServerError: RuntimeError
890 construct(errno, msg)
891 {
892 /*
893 * Do the base class construction. Note that errno is the
894 * VM-level error number, which is usually just the generic
895 * "storage server error" code. The storage server provides a
896 * separate, more specific error code of its own as the first
897 * token of the message string.
898 */
899 inherited(errno);
900
901 /*
902 * storage server error messages are formatted with an error code
903 * as the first space-delimited token, and a human-readable
904 * message following
905 */
906 local sp = msg.find(' ');
907 errCode = msg.substr(1, sp - 1);
908 msg = msg.substr(sp + 1);
909
910 /*
911 * If the error code is a negative integer, it's an error on the
912 * client side sending the HTTP request to the storage server.
913 * If it's a positive integer, it's an HTTP error code from the
914 * storage server. Otherwise it's an error abbreviation token
915 * from the server.
916 */
917 local errNum = toInteger(errCode);
918 if (errNum < 0)
919 {
920 local reqErrs = [
921 -1 -> 'out of memory',
922 -2 -> 'unable to connect',
923 -3 -> 'network error',
924 -4 -> 'invalid parameters',
925 -5 -> 'error reading temporary file',
926 -6 -> 'error writing temporary file',
927 * -> 'error code <<errNum>>'
928 ];
929 errMsg = reqErrs[errNum];
930 }
931 else if (errNum > 0)
932 errMsg = 'HTTP error (status code <<errCode>>)';
933 else
934 errMsg = msg;
935 }
936
937 /* the storage server error code */
938 errCode = nil
939
940 /*
941 * error message - this is the message text we get back from the
942 * storage server for a request that's successful at the HTTP level
943 * but fails on the storage server, OR a message describing the HTTP
944 * error or network error that caused the request to fail
945 */
946 errMsg = 'no details available'
947
948 /* display the exception */
949 displayException()
950 {
951 /* show the exception message */
952 "Storage server error: <<errMsg>>\n";
953
954 /* show a stack trace if possible */
955 showStackTrace(stack_);
956 }
957 ;
958
959 /* export this for use by the interpreter networking package */
960 export StorageServerError 'StorageServerError';
961
962
963 /* ------------------------------------------------------------------------ */
964 /*
965 * Default string display function. Our main entrypoint code
966 * establishes this function as the default output function.
967 */
968 _default_display_fn(str) { _tads_io_say(str); }
969
970 /*
971 * Raw output capture. This bypasses any filtering and directly captures
972 * any output generated by the callback.
973 */
974 _outputCapture(func)
975 {
976 /* temporarily set the low-level string output to capture output */
977 local buf = new StringBuffer();
978 local oldSay = t3SetSay({str: buf.append(str)});
979
980 /* make sure we restore the "say" function on the way out */
981 try
982 {
983 /* call the callback in the new capture context */
984 func();
985
986 /* return the captured data */
987 return toString(buf);
988 }
989 finally
990 {
991 /* restore the old "say" function */
992 t3SetSay(oldSay);
993 }
994 }
995
996
997 /* ------------------------------------------------------------------------ */
998 /*
999 * The stack information object. The intrinsic function
1000 * t3GetStackTrace() in the 't3vm' function set returns a list of these
1001 * objects; each object represents a level in the stack trace.
1002 */
1003 class T3StackInfo: object
1004 /*
1005 * Construct a stack level object. The system invokes this
1006 * constructor with information on the stack level.
1007 */
1008 construct(func, obj, prop, selfObj, argList, srcInfo,
1009 locals, namedArgs, frameDesc)
1010 {
1011 /* remember the values */
1012 func_ = func;
1013 obj_ = obj;
1014 prop_ = prop;
1015 self_ = selfObj;
1016 argList_ = argList;
1017 srcInfo_ = srcInfo;
1018 locals_ = locals;
1019 namedArgs_ = namedArgs;
1020 frameDesc_ = frameDesc;
1021 }
1022
1023 /*
1024 * Is this a system routine? This returns true if an intrinsic
1025 * function or an intrinsic class method is running at this level.
1026 */
1027 isSystem()
1028 {
1029 /*
1030 * It's a system function if:
1031 *
1032 * - we have NEITHER a function nor a method
1033 *. - the function is a built-in function pointer
1034 *. - the defining object is an intrinsic class
1035 *
1036 * The first case applies to pre-3.0.19 VMs, where no information
1037 * was available for native callers. Starting in 3.0.19, full
1038 * information is available.
1039 */
1040 return ((func_ == nil && obj_ == nil)
1041 || dataType(func_) == TypeBifPtr
1042 || (obj_ != nil && IntrinsicClass.isIntrinsicClass(obj_)));
1043 }
1044
1045 /*
1046 * the function running at this stack level - this is nil if an
1047 * object property is running instead of a function
1048 */
1049 func_ = nil
1050
1051 /*
1052 * The object and property running at this stack level - these are
1053 * nil if a function is running instead of an object method. The
1054 * object is the object where the method is actually defined - this
1055 * might not be the same as self, because the object might have
1056 * inherited the method from a base class.
1057 */
1058 obj_ = nil
1059 prop_ = nil
1060
1061 /*
1062 * the 'self' object at this level - this is nil if a function is
1063 * running at this level instead of an object method
1064 */
1065 self_ = nil
1066
1067 /*
1068 * The list of positional arguments to the function or method. Each
1069 * element is the value of an argument; the list is arranged in the
1070 * same order as the arguments.
1071 */
1072 argList_ = []
1073
1074 /*
1075 * Local variables. This is a LookupTable containing the local
1076 * variables currently in scope at this stack level. Each element in
1077 * the table has a string key (index) giving the name of the local
1078 * variable, and each corresponding value is the local's current
1079 * value. The table is only included when the stack listing was
1080 * produced by a call to t3GetStackTrace() with the T3GetStackLocals
1081 * flag set; otherwise it's nil. If the locals were requested, and
1082 * the stack level has no local variables, this will be an empty
1083 * lookup table.
1084 */
1085 locals_ = nil
1086
1087 /*
1088 * Named arguments. This is a LookupTable containing the named
1089 * arguments passed in from this stack level. Each element in the
1090 * table has a string key (index) giving the name of the argument,
1091 * and each corresponding value is the value of that argument. If
1092 * there are no named arguments, this value is nil.
1093 */
1094 namedArgs_ = nil
1095
1096 /*
1097 * The source location of the next code to be executed in the
1098 * function or method in this frame. If source-level debugging
1099 * information is available for the current execution point in this
1100 * frame, this will contain a list of two values:
1101 *
1102 * srcInfo_[1] = string giving the name of the source file
1103 *. srcInfo_[2] = integer giving the line number in the source file
1104 *
1105 * If the program wasn't compiled with source-level debugging
1106 * information, or the current code location in the frame doesn't
1107 * have any source information, this will be set to nil.
1108 *
1109 * Note that the location reflected here is the *return address* in
1110 * this frame - that is, the code location that will be executed when
1111 * control returns to the frame. This means that the source location
1112 * will frequently appear as the next executable line after the one
1113 * that called the next inner frame, because this is where execution
1114 * will resume when control returns to the frame.
1115 */
1116 srcInfo_ = nil
1117
1118 /*
1119 * A StackFrameDesc object that can be used to get information from
1120 * the frame and change local variables in the frame.
1121 */
1122 frameDesc_ = nil
1123 ;
1124
1125 /* export T3StackInfo for use by the system */
1126 export T3StackInfo;
1127
1128
1129 /* ------------------------------------------------------------------------ */
1130 /*
1131 * Stream state object for String.specialsToHtml().
1132 */
1133 class SpecialsToHtmlState: object
1134 /*
1135 * Reset the state. This should be used when the output stream
1136 * context is reset, such as when clearing the window.
1137 */
1138 resetState()
1139 {
1140 flags_ = 0;
1141 tag_ = '';
1142 }
1143
1144 /*
1145 * Explicitly reset to the start of a line. This can be called after
1146 * a non-output operation that resets the line position, such as
1147 * reading an input line.
1148 */
1149 resetLine()
1150 {
1151 /* reset the in-line flag, space flag, qspace flag, and tab column */
1152 flags_ &= ~(0x0001 | 0x0040 | 0x0080 | 0x0300);
1153 }
1154
1155 /*
1156 * Internal output state flags at end of last string parsed. This is
1157 * a combination of bit flags:
1158 *
1159 * 0x0001 - last string ended within a line of text
1160 *. 0x0002 - caps flag '\^' pending
1161 *. 0x0004 - lowercase flag '\v' pending
1162 *. 0x0008 - last string ended within an HTML tag
1163 *. 0x0010 - last string ended in double-quoted HTML tag attribute text
1164 *. 0x0020 - last string ended in single-quoted HTML tag attribute text
1165 *. 0x0040 - last string ended with an ordinary space
1166 *. 0x0080 - last string ended with a quoted space '\ '
1167 *. 0x0100 - <Q> parity level: 0=double quotes, 1=single quotes
1168 *. 0x0300 - distance from last '\t' tab column (0..3)
1169 */
1170 flags_ = 0
1171
1172 /* tag in progress at end of last string parsed */
1173 tag_ = ''
1174 ;
1175
1176
1177
1178 /* ------------------------------------------------------------------------ */
1179 /*
1180 * global data object for this module
1181 */
1182 mainGlobal: object
1183 /* flag: we've run pre-initialization */
1184 preinited_ = nil
1185
1186 /*
1187 * The global reflection object - if the program is compiled with
1188 * the standard reflection module, that module will set this
1189 * property to point to the reflection object.
1190 *
1191 * We use this so that we don't require the reflection module to be
1192 * included. If the module isn't included, this will be nil, so
1193 * we'll know not to use reflection. If this is not nil, we'll know
1194 * we can use reflection services.
1195 */
1196 reflectionObj = nil
1197
1198 /*
1199 * Restart ID. This is an integer that indicates how the main
1200 * entrypoint was last reached. This is initially zero; each time
1201 * we restart the game, this is incremented.
1202 *
1203 * The restart ID is the only information that survives across a
1204 * restart boundary. Other than this, entering via a restart is
1205 * exactly like loading the program from scratch; all other
1206 * information about the program state before the restart is lost in
1207 * the restart operation.
1208 */
1209 restartID = 0
1210
1211 /* pointer to mainRestore function, if defined */
1212 mainRestoreFunc = nil
1213 ;
1214
1215 /* ------------------------------------------------------------------------ */
1216 /*
1217 * At-exit handlers. This is a registry for custom handlers that are to
1218 * be invoked just before the program terminates.
1219 */
1220 transient mainAtExit: object
1221 /*
1222 * Add an at-exit handler. User code can call this to register a
1223 * handler that will be invoked just before the program exits.
1224 */
1225 addHandler(func)
1226 {
1227 handlers.append(func);
1228 }
1229
1230 /* call our exit handlers */
1231 callHandlers()
1232 {
1233 /* call each handler in the list */
1234 foreach (local f in handlers)
1235 {
1236 try
1237 {
1238 /* call this handler */
1239 f();
1240 }
1241 catch (Exception exc)
1242 {
1243 /* display and ignore any exceptions it throws */
1244 "\nError in exit handler: <<exc.displayException()>>\n";
1245 }
1246 }
1247 }
1248
1249 /* list of exit handlers */
1250 handlers = static new Vector()
1251 ;
1252
1253 /* ------------------------------------------------------------------------ */
1254 /*
1255 * <<one of>> index generator. The compiler generates an anonymous
1256 * instance of this class for each <<one of>> list in string, setting the
1257 * property 'numItems' to the number of items in the list, and
1258 * 'listAttrs' property to a string giving the sequence type. The
1259 * compiler generates a call to getNextIndex() within the string to get
1260 * the next index value, which is an integer from 1 to numItems.
1261 */
1262 class OneOfIndexGen: object
1263 /* number of list items */
1264 numItems = 1
1265
1266 /*
1267 * List attributes. This is a string with a comma-delimited list of
1268 * tokens describing the treatment on the list for each fetch. The
1269 * first call to getNextIndex() takes the first token off the list
1270 * and generates an appropriate return value, possibly queuing up a
1271 * list of future values. The next call to getNextIndex() reads from
1272 * the queue. Once the queue is exhausted, the next call takes the
1273 * second token off the attribute list and repeats the process. Once
1274 * the attribute list is down to one token, we don't remove the
1275 * token, but simply repeat it forever.
1276 *
1277 * For example, 'seq,rand' runs through the entire list in sequence
1278 * once, then generates independently random values from then on.
1279 * 'shuffle,stop' runs through the list once in shuffled order, then
1280 * repeats the last pick from the shuffled list forever.
1281 *
1282 * The individual attribute values are:
1283 *
1284 * rand - pick an item at random, independently of past selections.
1285 *
1286 * rand-norpt - pick an item at random, but don't pick the single
1287 * most recent item chosen, to avoid repeating the same thing twice
1288 * in a row.
1289 *
1290 * rand-wt - pick an item by random, weighting the items with
1291 * decreasing probabilities. The last item is given relative weight
1292 * 1, the second to last weight 2, the third to last weight 3, etc.
1293 * In other words, the nth item from the end of the list is n times
1294 * as likely to be picked as the last item. The picks are
1295 * independent.
1296 *
1297 * seq - run through the items in sequence (1, 2, ... numItems).
1298 *
1299 * shuffle - run through the list in a shuffled order.
1300 *
1301 * shuffle2 - shuffle the list into a random order, but only run
1302 * through half before reshuffling
1303 *
1304 * stop - repeat the previous selection forever. (This should only
1305 * be used as the second or later attribute in the list, since it
1306 * depends on a prior selection being made.)
1307 */
1308 listAttrs = ''
1309
1310 /*
1311 * Get the next index value. Returns an integer from 1 to numItems.
1312 * The algorithm for choosing the index depends on the list type, as
1313 * defined by listAttrs.
1314 */
1315 getNextIndex()
1316 {
1317 /* if we're out of items, generate the next iteration of the list */
1318 if (idx_ > lst_.length())
1319 {
1320 /* pull out the first item from the attributes */
1321 local alst = listAttrs.split(',', 2);
1322
1323 /*
1324 * If we have more than one attribute, keep only the
1325 * remaining attributes, since the first attribute is for the
1326 * first list iteration only.
1327 */
1328 if (alst.length() > 1)
1329 listAttrs = alst[2];
1330
1331 /* some of the attributes are interested in the last item */
1332 local last = lst_.length() >= 1 ? lst_[lst_.length()] : nil;
1333
1334 /* build the list for the head attribute */
1335 local pick;
1336 switch (alst[1])
1337 {
1338 case 'stop':
1339 /* reuse the last item every time from now on */
1340 lst_ = [last ?? 1];
1341 break;
1342
1343 case 'seq':
1344 /* run through the list in sequence */
1345 lst_ = List.generate({i: i}, numItems);
1346 break;
1347
1348 case 'rand':
1349 /*
1350 * pick an item at random, independent of other picks -
1351 * just generate a single item list, since we'll want to
1352 * pick at random again next time
1353 */
1354 lst_ = [rand(numItems) + 1];
1355 break;
1356
1357 case 'rand-norpt':
1358 /*
1359 * Pick an item at random, but don't repeat the last item
1360 * chosen. Pick repeatedly until we select an item that
1361 * doesn't match the last selection, if there is one.
1362 * Exception: if the list has only one item, it's
1363 * impossible to choose a different item, so don't try.
1364 */
1365 do
1366 {
1367 pick = rand(numItems) + 1;
1368 }
1369 while (numItems > 1 && pick == last);
1370 lst_ = [pick];
1371 break;
1372
1373 case 'rand-wt':
1374 /*
1375 * Pick an item at random, independently of other trials,
1376 * weighting the list in decreasing order of probability.
1377 * The relative weights are 1 for the last item, 2 for
1378 * the second to last item, 3 for the third to last, etc.
1379 * This gives us a total weight of n(n+1)/2, so start by
1380 * picking a number in that range. 1 represents the last
1381 * item, 2..3 the second to last, 3..5 the third, etc.
1382 */
1383 pick = rand(numItems*(numItems+1)/2) + 1;
1384 for (local i in 1..numItems ; ; pick -= i)
1385 {
1386 /* if pick is <= i, it's this item */
1387 if (pick <= i)
1388 {
1389 lst_ = [numItems - i + 1];
1390 break;
1391 }
1392 }
1393 break;
1394
1395 case 'shuffle':
1396 case 'shuffle2':
1397 /*
1398 * Shuffle the list. Populate the list with the integer
1399 * values from 1 to numItems, then shuffle the list into
1400 * a random order.
1401 *
1402 * The shuffling algorithm, as a physical analogy: Start
1403 * with a deck of cards labeled 1 to numItems. Put all
1404 * of the cards in a hat. Pick a card at random from the
1405 * hat and set it aside - call this the "pile". Pick
1406 * another random card from the hat and put it on the top
1407 * of the pile. Repeat until the hat is empty. We now
1408 * have a pile of the cards arranged in random order.
1409 *
1410 * To implement this, we create a vector and fill it with
1411 * integers from 1 to numItems. Partition the vector
1412 * with an index 'i': items from 1..i are the hat, items
1413 * from i+1..numItems are the deck. To draw a card at
1414 * random, we pick a random number from 1..i. To remove
1415 * it from the hat, we swap it into position 'i', because
1416 * that will effectively shrink the hat by one slot and
1417 * grow the pile by one slot. Decrement i and repeat.
1418 */
1419 lst_ = Vector.generate({i: i}, numItems);
1420 for (local i in numItems..2 step -1)
1421 {
1422 /* pick a random element from the remaining set */
1423 pick = rand(i) + 1;
1424
1425 /* swap the chosen item and the last element */
1426 local tmp = lst_[i];
1427 lst_[i] = lst_[pick];
1428 lst_[pick] = tmp;
1429 }
1430
1431 /*
1432 * The whole point of shuffling is to avoid obvious
1433 * repetition, so make sure we don't repeat any previous
1434 * item from a previous run through the list as the first
1435 * item of the new list. If the first item matches the
1436 * previous item, reshuffle it into a random spot in the
1437 * list. (If the list only has one item, of course, this
1438 * is pointless, so don't bother in that case.)
1439 */
1440 if (lst_[1] == last && numItems > 1)
1441 {
1442 pick = rand(numItems - 1) + 2;
1443 lst_[1] = lst_[pick];
1444 lst_[pick] = last;
1445 }
1446
1447 /*
1448 * in half-shuffle mode, only keep the first half of the
1449 * list, so that we re-shuffle halfway through
1450 */
1451 if (alst[1] == 'shuffle2' && numItems > 2)
1452 lst_ = lst_.toList(1, numItems/2);
1453 break;
1454 }
1455
1456 /* start from the first item in the list */
1457 idx_ = 1;
1458 }
1459
1460 /* return and consume the next item */
1461 return lst_[idx_++];
1462 }
1463
1464 /* generated list */
1465 lst_ = []
1466
1467 /* current position in the list */
1468 idx_ = 1
1469 ;