Debian Codegraph @

terps/tads/tads3/vmbiftad.cpp

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header: d:/cvsroot/tads/tads3/VMBIFTAD.CPP,v 1.3 1999/07/11 00:46:58 MJRoberts Exp $";
4 #endif
5
6 /*
7 * Copyright (c) 1999, 2002 Michael J. Roberts. All Rights Reserved.
8 *
9 * Please see the accompanying license file, LICENSE.TXT, for information
10 * on using and copying this software.
11 */
12 /*
13 Name
14 vmbiftad.cpp - TADS built-in function set for T3 VM
15 Function
16
17 Notes
18
19 Modified
20 04/05/99 MJRoberts - Creation
21 */
22
23 #include <stdio.h>
24 #include <string.h>
25 #include <time.h>
26
27 #include "t3std.h"
28 #include "os.h"
29 #include "utf8.h"
30 #include "vmuni.h"
31 #include "vmbiftad.h"
32 #include "vmstack.h"
33 #include "vmerr.h"
34 #include "vmerrnum.h"
35 #include "vmglob.h"
36 #include "vmpool.h"
37 #include "vmobj.h"
38 #include "vmstr.h"
39 #include "vmlst.h"
40 #include "vmrun.h"
41 #include "vmregex.h"
42 #include "vmundo.h"
43 #include "vmfile.h"
44 #include "vmsave.h"
45 #include "vmbignum.h"
46 #include "vmfunc.h"
47 #include "vmpat.h"
48 #include "vmtobj.h"
49 #include "vmimport.h"
50 #include "vmpredef.h"
51 #include "vmlookup.h"
52 #include "vmfilobj.h"
53 #include "vmnetfil.h"
54 #include "vmbytarr.h"
55 #include "vmcrc.h"
56 #include "vmfindrep.h"
57
58
59 /* ------------------------------------------------------------------------ */
60 /*
61 * Initialize the TADS intrinsics global state
62 */
63 CVmBifTADSGlobals::CVmBifTADSGlobals(VMG0_)
64 {
65 /* allocate our regular expression parser */
66 rex_parser = new CRegexParser();
67 rex_searcher = new CRegexSearcherSimple(rex_parser);
68
69 /*
70 * Allocate a global variable to hold the most recent regular
71 * expression search string. We need this in a global so that the last
72 * search string is always protected from garbage collection; we must
73 * keep the string because we might need it to extract a group-match
74 * substring.
75 */
76 last_rex_str = G_obj_table->create_global_var();
77
78 /* ISAAC is the default RNG */
79 rng_id = VMBT_RNGID_ISAAC;
80
81 /*
82 * Set the random number seed to a fixed starting value (this value
83 * is arbitrary; we chose it by throwing dice). If the program
84 * wants another sequence, it can manually change this by calling
85 * the randomize() intrinsic in our function set, which seeds the
86 * generator with an OS-dependent starting value (usually based on
87 * the system's real-time clock, to ensure that each run will use a
88 * different starting value).
89 */
90 lcg_rand_seed = 024136543305;
91
92 /* create the ISAAC context structure */
93 isaac_ctx = (struct isaacctx *)t3malloc(sizeof(struct isaacctx));
94
95 /* initialize with a fixed seed vector */
96 isaac_init(isaac_ctx, FALSE);
97
98 /* create the Mersenne Twister object */
99 mt_ctx = new CVmMT19937();
100 }
101
102 /*
103 * delete the TADS intrinsics global state
104 */
105 CVmBifTADSGlobals::~CVmBifTADSGlobals()
106 {
107 /* delete our regular expression searcher and parser */
108 delete rex_searcher;
109 delete rex_parser;
110
111 /*
112 * note that we leave our last_rex_str global variable undeleted here,
113 * as we don't have access to G_obj_table (as there's no VMG_ to a
114 * destructor); this is okay, since the object table will take care of
115 * deleting the variable for us when the object table itself is deleted
116 */
117
118 /* delete the ISAAC context */
119 t3free(isaac_ctx);
120
121 /* delete the Mersenne Twister context */
122 delete mt_ctx;
123 }
124
125 /* ------------------------------------------------------------------------ */
126 /*
127 * datatype - get the datatype of a given value
128 */
129 void CVmBifTADS::datatype(VMG_ uint argc)
130 {
131 vm_val_t val;
132 vm_val_t retval;
133
134 /* check arguments */
135 check_argc(vmg_ argc, 1);
136
137 /* pop the value */
138 G_stk->pop(&val);
139
140 /* return the appropriate value for this type */
141 retval.set_datatype(vmg_ &val);
142 retval_int(vmg_ retval.val.intval);
143 }
144
145 /* ------------------------------------------------------------------------ */
146 /*
147 * getarg - get the given argument to the current procedure
148 */
149 void CVmBifTADS::getarg(VMG_ uint argc)
150 {
151 int idx;
152
153 /* check arguments */
154 check_argc(vmg_ argc, 1);
155
156 /* get the argument index value */
157 idx = pop_int_val(vmg0_);
158
159 /* if the argument index is out of range, throw an error */
160 if (idx < 1 || idx > G_interpreter->get_cur_argc(vmg0_))
161 err_throw(VMERR_BAD_VAL_BIF);
162
163 /* return the parameter value */
164 *G_interpreter->get_r0() = *G_interpreter->get_param(vmg_ idx - 1);
165 }
166
167 /* ------------------------------------------------------------------------ */
168 /*
169 * firstobj - get the first object instance
170 */
171 void CVmBifTADS::firstobj(VMG_ uint argc)
172 {
173 /* check arguments */
174 check_argc_range(vmg_ argc, 0, 2);
175
176 /* enumerate objects starting with object 1 in the master object table */
177 enum_objects(vmg_ argc, (vm_obj_id_t)1);
178 }
179
180 /*
181 * nextobj - get the next object instance after a given object
182 */
183 void CVmBifTADS::nextobj(VMG_ uint argc)
184 {
185 vm_val_t val;
186 vm_obj_id_t prv_obj;
187
188 /* check arguments */
189 check_argc_range(vmg_ argc, 1, 3);
190
191 /* get the previous object */
192 G_interpreter->pop_obj(vmg_ &val);
193 prv_obj = val.val.obj;
194
195 /*
196 * Enumerate objects starting with the next object in the master
197 * object table after the given object. Reduce the argument count by
198 * one, since we've removed the preceding object.
199 */
200 enum_objects(vmg_ argc - 1, prv_obj + 1);
201 }
202
203 /* enum_objects flags */
204 #define VMBIFTADS_ENUM_INSTANCES 0x0001
205 #define VMBIFTADS_ENUM_CLASSES 0x0002
206
207 /*
208 * Common handler for firstobj/nextobj object iteration
209 */
210 void CVmBifTADS::enum_objects(VMG_ uint argc, vm_obj_id_t start_obj)
211 {
212 vm_val_t val;
213 vm_obj_id_t sc;
214 vm_obj_id_t obj;
215 unsigned long flags;
216
217 /* presume no superclass filter will be specified */
218 sc = VM_INVALID_OBJ;
219
220 /* presume we're enumerating instances only */
221 flags = VMBIFTADS_ENUM_INSTANCES;
222
223 /*
224 * check arguments - we can optionally have two more arguments: a
225 * superclass whose instances/subclasses we are to enumerate, and an
226 * integer giving flag bits
227 */
228 if (argc == 2)
229 {
230 /* pop the object */
231 G_interpreter->pop_obj(vmg_ &val);
232 sc = val.val.obj;
233
234 /* pop the flags */
235 flags = pop_long_val(vmg0_);
236 }
237 else if (argc == 1)
238 {
239 /* check to see if it's an object or the flags integer */
240 switch (G_stk->get(0)->typ)
241 {
242 case VM_INT:
243 /* it's the flags */
244 flags = pop_long_val(vmg0_);
245 break;
246
247 case VM_OBJ:
248 /* it's the superclass filter */
249 G_interpreter->pop_obj(vmg_ &val);
250 sc = val.val.obj;
251 break;
252
253 default:
254 /* invalid argument type */
255 err_throw(VMERR_BAD_TYPE_BIF);
256 }
257 }
258
259 /* presume we won't find anything */
260 retval_nil(vmg0_);
261
262 /*
263 * starting with the given object, scan objects until we find one
264 * that's valid and matches our superclass, if one was provided
265 */
266 for (obj = start_obj ; obj < G_obj_table->get_max_used_obj_id() ; ++obj)
267 {
268 /*
269 * If it's valid, and it's not an intrinsic class modifier object,
270 * consider it further. Skip intrinsic class modifiers, since
271 * they're not really separate objects; they're really part of the
272 * intrinsic class they modify, and all of the properties and
273 * methods of a modifier object are reachable through the base
274 * intrinsic class.
275 */
276 if (G_obj_table->is_obj_id_valid(obj)
277 && !CVmObjIntClsMod::is_intcls_mod_obj(vmg_ obj))
278 {
279 /*
280 * if it's a class, skip it if the flags indicate classes are
281 * not wanted; if it's an instance, skip it if the flags
282 * indicate that instances are not wanted
283 */
284 if (vm_objp(vmg_ obj)->is_class_object(vmg_ obj))
285 {
286 /* it's a class - skip it if classes are not wanted */
287 if ((flags & VMBIFTADS_ENUM_CLASSES) == 0)
288 continue;
289 }
290 else
291 {
292 /* it's an instance - skip it if instances are not wanted */
293 if ((flags & VMBIFTADS_ENUM_INSTANCES) == 0)
294 continue;
295 }
296
297 /*
298 * if a superclass was specified, and it matches, we have a
299 * winner
300 */
301 if (sc != VM_INVALID_OBJ)
302 {
303 /* if the object matches, return it */
304 if (vm_objp(vmg_ obj)->is_instance_of(vmg_ sc))
305 {
306 retval_obj(vmg_ obj);
307 break;
308 }
309 }
310 else
311 {
312 /*
313 * We're enumerating all objects - but skip List and String
314 * object, as we expose these as special types.
315 */
316 if (vm_objp(vmg_ obj)->get_as_list() == 0
317 && vm_objp(vmg_ obj)->get_as_string(vmg0_) == 0)
318 {
319 retval_obj(vmg_ obj);
320 break;
321 }
322 }
323 }
324 }
325 }
326
327 /* ------------------------------------------------------------------------ */
328 /*
329 * Abstract RNG algorithm interface
330 */
331 class IVmBifTadsRNG
332 {
333 public:
334 virtual ~IVmBifTadsRNG() { }
335
336 /* get the next random number */
337 virtual uint32_t rand() = 0;
338
339 /* seed the generator from random data */
340 virtual void seed_random() = 0;
341
342 /* seed from an int */
343 virtual void seed_int(int32_t i)
344 {
345 /* by default, turn this into a string and seed with the string */
346 char buf[40];
347 oswp4(buf, i);
348 t3sprintf(buf+4, sizeof(buf)-4, "%ld", (long)i);
349 seed_str(buf, 4 + strlen(buf+4));
350 }
351
352 /* seed from a string */
353 virtual void seed_str(const char *str, size_t len)
354 {
355 /* by default, hash the string to an int and seed with the int */
356 CVmCRC32 crc;
357 crc.scan_bytes(str, len);
358 seed_int((int32_t)crc.get_crc_val());
359 }
360
361 /* get the state into a ByteArray object */
362 void get_state(VMG_ vm_val_t *val)
363 {
364 size_t len = get_state_size();
365 if (len == 0)
366 {
367 /* simple int32_t state */
368 val->set_int(get_state_int());
369 }
370 else
371 {
372 /* allocate a buffer */
373 char *buf = new char[len];
374
375 /* make sure we delete the allocated buffer */
376 err_try
377 {
378 /* get the state into our buffer */
379 get_state_buf(buf);
380
381 /* create a ByteArray from the state vector */
382 val->set_obj(CVmObjByteArray::create_from_bytes(
383 vmg_ FALSE, buf, len));
384 }
385 err_finally
386 {
387 /* done with the buffer */
388 delete [] buf;
389 }
390 err_end;
391 }
392 }
393
394 /* put the state from a ByteArray object */
395 void put_state(VMG_ vm_val_t *val)
396 {
397 /* determine what to do based on the state length */
398 size_t len = get_state_size();
399 if (len == 0)
400 {
401 /* simple int32_t state */
402 put_state_int(val->num_to_int(vmg0_));
403 }
404 else
405 {
406 /* retrieve the ByteArray object */
407 CVmObjByteArray *barr = vm_val_cast(CVmObjByteArray, val);
408
409 /* check that it matches the expected state buffer size */
410 unsigned long cnt = barr->get_element_count();
411 if (cnt != len)
412 err_throw(VMERR_BAD_VAL_BIF);
413
414 /* retrieve the bytes and restore the state */
415 char *buf = new char[len];
416 err_try
417 {
418 /* retrieve the bytes */
419 barr->copy_to_buf((unsigned char *)buf, 1, len);
420
421 /* restore the state */
422 put_state_buf(buf);
423 }
424 err_finally
425 {
426 delete [] buf;
427 }
428 err_end;
429 }
430 }
431
432 protected:
433 /*
434 * Get the size of the state vector, in bytes. Return 0 if we can
435 * store the state in an int32_t.
436 */
437 virtual size_t get_state_size() = 0;
438
439 /* get/put state as an int32_t */
440 virtual int32_t get_state_int() = 0;
441 virtual void put_state_int(int32_t i) = 0;
442
443 /* save/restore current state vector to/from a buffer */
444 virtual void get_state_buf(char *buf) = 0;
445 virtual void put_state_buf(const char *buf) = 0;
446 };
447
448 /* ------------------------------------------------------------------------ */
449 /*
450 * ISAAC random number generator
451 */
452 class vmbt_isaac_ifc: public IVmBifTadsRNG
453 {
454 public:
455 vmbt_isaac_ifc(VMG0_) { ctx = G_bif_tads_globals->isaac_ctx; }
456 isaacctx *ctx;
457
458 virtual uint32_t rand() { return isaac_rand(ctx); }
459
460 /* seed from random data */
461 virtual void seed_random()
462 {
463 /* generate random bytes into the ISAAC rsl array */
464 os_gen_rand_bytes((unsigned char *)ctx->rsl, sizeof(ctx->rsl));
465
466 /* initialize from the rsl array */
467 isaac_init(ctx, TRUE);
468 }
469
470 /* seed from a string value */
471 virtual void seed_str(const char *str, size_t len)
472 {
473 /*
474 * Copy the string value into the rsl array; copy as much as will
475 * fit, and zero the rest. (The point here is to be deterministic,
476 * so we want this to be the same every time with a given seed - we
477 * don't want to include random data left behind from previous
478 * iterations.)
479 */
480 if (len > sizeof(ctx->rsl))
481 len = sizeof(ctx->rsl);
482
483 memset(ctx->rsl, 0, sizeof(ctx->rsl));
484 memcpy(ctx->rsl, str, len);
485
486 /* initialize with the rsl data */
487 isaac_init(ctx, TRUE);
488 }
489
490 virtual int32_t get_state_int() { return 0; }
491 virtual void put_state_int(int32_t) { }
492
493 virtual size_t get_state_size() { return isaac_get_state(ctx, 0); }
494 virtual void get_state_buf(char *buf) { isaac_get_state(ctx, buf); }
495 virtual void put_state_buf(const char *buf) { isaac_set_state(ctx, buf); }
496 };
497
498
499 /* ------------------------------------------------------------------------ */
500 /*
501 * Linear Congruential Random-Number Generator. This generator uses an
502 * algorithm from Knuth, The Art of Computer Programming, Volume 2, p.
503 * 170, with parameters chosen from the same book for their good
504 * statistical properties and efficiency on 32-bit hardware.
505 */
506 class vmbt_lcg_ifc: public IVmBifTadsRNG
507 {
508 public:
509 vmbt_lcg_ifc(VMG0_) { seedp = &G_bif_tads_globals->lcg_rand_seed; }
510
511 virtual uint32_t rand()
512 {
513 const uint32_t a = 1664525L;
514 const uint32_t c = 1;
515
516 /*
517 * Generate the next random value using the linear congruential
518 * method described in Knuth, The Art of Computer Programming,
519 * volume 2, p170.
520 *
521 * Use 2^32 as m, hence (n mod m) == (n & 0xFFFFFFFF). This is
522 * efficient and is well-suited to 32-bit machines, works fine on
523 * larger machines, and will even work on 16-bit machines as long
524 * as the compiler can provide us with 32-bit arithmetic (which we
525 * assume extensively elsewhere anyway).
526 *
527 * We use a = 1664525, a multiplier which has very good results
528 * with the Spectral Test (see Knuth p102) with our choice of m.
529 *
530 * Use c = 1, since this trivially satisfies Knuth's requirements
531 * about common factors.
532 *
533 * Note that the result of the multiplication might overflow a
534 * 32-bit ulong for values of lcg_rand_seed that are not small.
535 * This doesn't matter, since if it does, the machine will
536 * naturally truncate high-order bits to yield the result mod 2^32.
537 * So, on a 32-bit machine, the (&0xFFFFFFFF) part is superfluous,
538 * but it's harmless and is needed for machines with a larger word
539 * size.
540 */
541 *seedp = (int32_t)(((a * (uint32_t)*seedp) + c) & 0xFFFFFFFF);
542 return (uint32_t)*seedp;
543 }
544
545 virtual void seed_random()
546 {
547 long l;
548 os_rand(&l);
549 *seedp = (int32_t)l;
550 }
551
552 virtual void seed_int(int32_t i)
553 {
554 *seedp = i;
555 }
556
557 virtual int32_t get_state_int() { return *seedp; }
558 virtual void put_state_int(int32_t i) { *seedp = i; }
559
560 virtual size_t get_state_size() { return 0; }
561 virtual void get_state_buf(char *) { }
562 virtual void put_state_buf(const char *) { }
563
564 int32_t *seedp;
565 };
566
567
568 /* ------------------------------------------------------------------------ */
569 /*
570 * Bit-shift generator. This is from Knuth, The Art of Computer
571 * Programming, volume 2. This generator is designed to produce random
572 * strings of bits and isn't suitable for use as a general-purpose RNG.
573 *
574 * Linear congruential generators aren't ideal for generating random bits;
575 * their statistical properties are better suited for generating values
576 * over a full integer range. This generator is specially designed to
577 * produce random bits, so it could be a useful complement to an LCG RNG.
578 *
579 * Since this isn't a good general RNG, we don't currently enable it.
580 * We're keeping the code here, ifdef'd out, in case we decide to enable it
581 * in the future - which seems really unlikely, since ISAAC seems to be
582 * good at generating both full-range integers and random bits, leaving
583 * little reason to have a dedicated random bit generator.
584 */
585
586 #ifdef VMBIFTADS_RNG_BITSHIFT
587 static uint32_t bits_rng_next(VMG0_)
588 {
589 int top_bit = (G_bif_tads_globals->bits_rand_seed & 0x8000000);
590 G_bif_tads_globals->bits_rand_seed <<= 1;
591 if (top_bit)
592 G_bif_tads_globals->bits_rand_seed ^= 035604231625;
593
594 return G_bif_tads_globals->bits_rand_seed & 1;
595 }
596 #endif /* VMBIFTADS_RNG_BITSHIFT */
597
598
599 /* ------------------------------------------------------------------------ */
600 /*
601 * Mersenne Twister MT19937 RNG algorithm
602 */
603 class vmbt_mt_ifc: public IVmBifTadsRNG
604 {
605 public:
606 vmbt_mt_ifc(VMG0_) { mt = G_bif_tads_globals->mt_ctx; }
607 CVmMT19937 *mt;
608
609 virtual uint32_t rand() { return mt->rand(); }
610
611 virtual void seed_random() { mt->seed_random(); }
612 virtual void seed_int(int32_t i) { mt->seed(i); }
613 virtual void seed_str(const char *str, size_t len) { mt->seed(str, len); }
614
615 virtual int32_t get_state_int() { return 0; }
616 virtual void put_state_int(int32_t i) { }
617
618 virtual size_t get_state_size() { return mt->get_state_size(); }
619 virtual void get_state_buf(char *buf) { mt->get_state(buf); }
620 virtual void put_state_buf(const char *buf) { mt->put_state(buf); }
621 };
622
623 /* ------------------------------------------------------------------------ */
624 /*
625 * RNG interface selector. This sets up each type of RNG interface, and
626 * returns the one for the given ID. This object can be constructed on the
627 * stack for minimal memory management hassle.
628 */
629 class CVmRNGSelector
630 {
631 public:
632 CVmRNGSelector(VMG0_)
633 : isaac(vmg0_), lcg(vmg0_), mt(vmg0_) { }
634
635 IVmBifTadsRNG *get(int id)
636 {
637 switch (id)
638 {
639 case VMBT_RNGID_ISAAC:
640 return &isaac;
641
642 case VMBT_RNGID_LCG:
643 return &lcg;
644
645 case VMBT_RNGID_MT19937:
646 return &mt;
647
648 default:
649 err_throw(VMERR_BAD_VAL_BIF);
650 AFTER_ERR_THROW(return 0;)
651 }
652 }
653
654 vmbt_isaac_ifc isaac;
655 vmbt_lcg_ifc lcg;
656 vmbt_mt_ifc mt;
657 };
658
659
660 /* ------------------------------------------------------------------------ */
661 /*
662 * randomize - seed the random number generator. This has several formats:
663 *
664 *. randomize() - select the default RNG (ISAAC) and initialize it
665 *. with random seed data.
666 *
667 *. randomize(nil) - retrieve the current state of the random number
668 *. generator. Returns a list: [id, state], where 'id'
669 *. is the generator ID, and 'state' is an opaque value
670 *. representing the generator's internal state.
671 *
672 *. randomize([state]) - restores the generator and internal state
673 *. returned from a previous call to randomize(nil).
674 *
675 *. randomize(id) - select the RNG identified by 'id'.
676 *
677 *. randomize(id, nil) - select the given RNG, and initialize it with
678 *. random seed data.
679 *
680 *. randomize(id, val) - select the given RNG, and initialize it with
681 *. the given fixed seed data. The seed can be provided
682 *. as an integer or string value.
683 */
684 void CVmBifTADS::randomize(VMG_ uint argc)
685 {
686 /* check arguments */
687 check_argc_range(vmg_ argc, 0, 2);
688 if (argc == 0)
689 {
690 /*
691 * No arguments - select the default random number generator
692 * (ISAAC) and initialize it with random seed data.
693 *
694 * Load the ISAAC initialization vector with some truly random data
695 * from the operating system.
696 */
697 G_bif_tads_globals->rng_id = VMBT_RNGID_ISAAC;
698 vmbt_isaac_ifc s Pvmg0_P;
699 s.seed_random();
700
701 /* no return value */
702 retval_nil(vmg0_);
703 }
704 else if (argc == 1 && G_stk->get(0)->typ == VM_NIL)
705 {
706 /*
707 * randomize(nil) - retrieve the current RNG state. This returns a
708 * list with two elements: [id, state]. Set up the return list.
709 */
710 vm_obj_id_t lstid = CVmObjList::create(vmg_ FALSE, 2);
711 CVmObjList *lst = (CVmObjList *)vm_objp(vmg_ lstid);
712 lst->cons_clear();
713 G_stk->push()->set_obj(lstid);
714
715 /* retval[1] = the active RNG ID */
716 vm_val_t ele;
717 ele.set_int(G_bif_tads_globals->rng_id);
718 lst->cons_set_element(0, &ele);
719
720 /* retval[2] = the active RNG's saved state vector */
721 CVmRNGSelector sel Pvmg0_P;
722 sel.get(G_bif_tads_globals->rng_id)->get_state(vmg_ &ele);
723 lst->cons_set_element(1, &ele);
724
725 /* discard gc protection and return the new list */
726 G_stk->discard(1);
727 retval_obj(vmg_ lstid);
728 }
729 else if (argc == 1 && G_stk->get(0)->is_listlike(vmg0_))
730 {
731 /*
732 * Randomize([state]) - restores a previous RNG state. The first
733 * list element is the RNG ID; the second is the saved state data,
734 * in an RNG-specific format.
735 */
736 vm_val_t idele, state;
737 G_stk->get(0)->ll_index(vmg_ &idele, 1);
738 G_stk->get(0)->ll_index(vmg_ &state, 2);
739 int id = idele.num_to_int(vmg0_);
740
741 /* set the state for the selected generator */
742 CVmRNGSelector sel Pvmg0_P;
743 sel.get(id)->put_state(vmg_ &state);
744
745 /* valid ID - select the generator */
746 G_bif_tads_globals->rng_id = id;
747
748 /* no return value */
749 retval_nil(vmg0_);
750 }
751 else if ((argc == 1 || argc == 2)
752 && G_stk->get(0)->is_numeric(vmg0_))
753 {
754 /*
755 * randomize(id) - select the RNG identified by 'id'
756 *. randomize(id, nil) - select and seed with random data
757 *. randomize(id, val) - select and seed with fixed data
758 */
759
760 /* get the ID, and get the generator interface for it */
761 int id = G_stk->get(0)->num_to_int(vmg0_);
762 CVmRNGSelector sel Pvmg0_P;
763 IVmBifTadsRNG *rng = sel.get(id);
764
765 /*
766 * Determine whether and how we're seeding the RNG. If there's
767 * only the one argument, we're not seeding it. If there's a
768 * second argument, and it's nil, we're seeding with OS random
769 * data. Otherwise we're seeding with the fixed data in the second
770 * argument, which must be an integer or string value.
771 */
772 if (argc == 2)
773 {
774 /* get the seed, and sense its type */
775 vm_val_t *seed = G_stk->get(1);
776 const char *str;
777 if (seed->typ == VM_NIL)
778 {
779 /* nil - use random data from the OS */
780 rng->seed_random();
781 }
782 else if (seed->is_numeric(vmg0_))
783 {
784 /* fixed integer seed value */
785 rng->seed_int(seed->num_to_int(vmg0_));
786 }
787 else if ((str = seed->get_as_string(vmg0_)) != 0)
788 {
789 /* string seed value */
790 rng->seed_str(str + VMB_LEN, vmb_get_len(str));
791 }
792 else
793 {
794 /* other types are invalid */
795 err_throw(VMERR_BAD_TYPE_BIF);
796 }
797 }
798
799 /* if we got this far, the ID was valid, so select the RNG */
800 G_bif_tads_globals->rng_id = id;
801
802 /* no return value */
803 retval_nil(vmg0_);
804 }
805 else
806 {
807 /* invalid arguments */
808 err_throw(VMERR_WRONG_NUM_OF_ARGS);
809 }
810 }
811
812 /*
813 * LCG randomize - seed the random-number generator
814 */
815 //void CVmBifTADS::randomize(VMG_ uint argc)
816 //{
817 // /* check arguments */
818 // check_argc(vmg_ argc, 0);
819 //
820 // /* seed the generator */
821 // os_rand(&G_bif_tads_globals->lcg_rand_seed);
822 //}
823
824
825 /* ------------------------------------------------------------------------ */
826 /*
827 * Get the next random number from the selected RNG
828 */
829 static uint32_t rng_next(VMG0_)
830 {
831 CVmRNGSelector sel Pvmg0_P;
832 return sel.get(G_bif_tads_globals->rng_id)->rand();
833 }
834
835
836 /* ------------------------------------------------------------------------ */
837 /*
838 * Map a random 32-bit number to a smaller range 0..range-1.
839 *
840 * Use the "multiplication" method Knuth describes in TAoCP Vol 2 section
841 * 3.4.2. This treats the source value as a fractional value in the range
842 * [0..1); we multiply this fractional value by the upper bound to get a
843 * linearly distributed number [0..range). To turn a 32-bit integer into a
844 * fractional value in the range [0..1), divide by 2^32.
845 *
846 * We do this calculation entirely with 32-bit integer arithmetic. The
847 * nominal calculation we're performing is:
848 *
849 *. rand_val = (ulong)((((double)rand_val) / 4294967296.0)
850 *. * (double)range);
851 *
852 * To do the arithmetic entirely with integers, we refactor this by first
853 * calculating the 64-bit product of rand_val * range, then dividing the
854 * product by 2^32. This isn't possible to do directly with 32-bit ints,
855 * of course. But the division is particularly easy because it's the same
856 * as a 32-bit right-shift. So the trick is to factor out the low-order
857 * 32-bits of the product and the high-order 32-bits, which we can do with
858 * some bit shifting.
859 */
860 static inline ulong rand_range(ulong rand_val, ulong range)
861 {
862 /* calculate the high-order 32 bits of (rand_val / 2^32 * range) */
863 ulong hi = (((rand_val >> 16) & 0xffff) * ((range >> 16) & 0xffff))
864 + ((((rand_val >> 16) & 0xffff) * (range & 0xffff)) >> 16)
865 + (((rand_val & 0xffff) * ((range >> 16) & 0xffff)) >> 16);
866
867 /* calculate the low-order 32 bits */
868 ulong lo = ((((rand_val >> 16) & 0xffff) * (range & 0xffff)) & 0xffff)
869 + (((rand_val & 0xffff) * ((range >> 16) & 0xffff)) & 0xffff)
870 + ((((rand_val & 0xffff) * (range & 0xffff)) >> 16) & 0xffff);
871
872 /* add the carry from the low part into the high part to get the result */
873 return hi + (lo >> 16);
874 }
875
876 /* calculate a random number in the range [lower, upper] */
877 static inline ulong rand_range(ulong rand_val, ulong lower, ulong upper)
878 {
879 return lower + rand_range(rand_val, upper - lower + 1);
880 }
881
882 /* random number with two ranges */
883 static inline ulong rand_range(ulong rand_val,
884 ulong lo1, ulong hi1,
885 ulong lo2, ulong hi2)
886 {
887 rand_val = rand_range(rand_val, (hi1 - lo1 + 1) + (hi2 - lo2 + 1));
888 return rand_val + (rand_val <= hi1 - lo1 ? lo1 : lo2 - (hi1 - lo1 + 1));
889 }
890
891 /* random number with three ranges */
892 static inline ulong rand_range(ulong rand_val,
893 ulong lo1, ulong hi1,
894 ulong lo2, ulong hi2,
895 ulong lo3, ulong hi3)
896 {
897 rand_val = rand_range(rand_val,
898 (hi1 - lo1 + 1)
899 + (hi2 - lo2 + 1)
900 + (hi3 - lo3 + 1));
901 return rand_val
902 + (rand_val <= hi1 - lo1 ? lo1 :
903 rand_val <= hi1 - lo1 + hi2 - lo2 + 1 ? lo2 - (hi1 - lo1 + 1) :
904 lo3 - (hi1 - lo1 + 1) - (hi2 - lo2 + 1));
905 }
906
907 /* ------------------------------------------------------------------------ */
908 /*
909 * Random string template parser
910 */
911 class RandStrParser
912 {
913 public:
914 /* initialize - parse the template string */
915 RandStrParser(const char *src, size_t len);
916
917 /* delete */
918 ~RandStrParser();
919
920 /* execute the template and return a string object result */
921 void exec(VMG_ vm_val_t *result);
922
923 /* get the current character */
924 wchar_t getch() { return rem > 0 ? p.getch() : 0; }
925
926 /* parse an integer value */
927 int parseInt()
928 {
929 /* parse digits in the input */
930 int acc;
931 for (acc = 0 ; more() && is_digit(getch()) ; skip())
932 {
933 /* add this digit into the accumulator */
934 acc *= 10;
935 acc += value_of_digit(getch());
936 }
937
938 /* return the accumulator value */
939 return acc;
940 }
941
942 /* skip the current character */
943 void skip()
944 {
945 if (rem != 0)
946 p.inc(&rem);
947 }
948
949 /* is there more input? */
950 int more() const { return rem != 0; }
951
952 /* get the number of bytes remaining */
953 size_t getrem() const { return rem; }
954
955 protected:
956 /* source string pointer and remaining length */
957 utf8_ptr p;
958 size_t rem;
959
960 /* root of the parse tree */
961 class RandStrNode *tree;
962 };
963
964 class RandStrNode
965 {
966 public:
967 RandStrNode()
968 {
969 firstChild = lastChild = 0;
970 nextSibling = 0;
971 }
972
973 virtual ~RandStrNode()
974 {
975 while (firstChild != 0)
976 {
977 RandStrNode *nxt = firstChild->nextSibling;
978 delete firstChild;
979 firstChild = nxt;
980 }
981 }
982
983 /* calculate the maximum length for the generated string for this node */
984 virtual int maxlen() = 0;
985
986 /* generate the string for this node */
987 virtual void generate(VMG_ wchar_t *&dst) = 0;
988
989 /* add a child */
990 void addChild(RandStrNode *chi)
991 {
992 if (lastChild != 0)
993 lastChild->nextSibling = chi;
994 else
995 firstChild = chi;
996 lastChild = chi;
997 }
998
999 /* tree links */
1000 RandStrNode *firstChild, *lastChild;
1001 RandStrNode *nextSibling;
1002 };
1003
1004 /*
1005 * range element - this covers a single character or single 'a-z' range
1006 * within a [character list] expression
1007 */
1008 class RandStrRange: public RandStrNode
1009 {
1010 public:
1011 RandStrRange(wchar_t c1, wchar_t c2)
1012 {
1013 if (c2 > c1)
1014 this->c1 = c1, this->c2 = c2;
1015 else
1016 this->c1 = c2, this->c2 = c1;
1017 }
1018
1019 virtual int maxlen() { return 1; }
1020 virtual void generate(VMG_ wchar_t *&dst) { }
1021
1022 /* low and high end of the character range, inclusive */
1023 wchar_t c1, c2;
1024 };
1025
1026 /* literal string - this is a string of characters enclosed in quotes */
1027 class RandStrLit: public RandStrNode
1028 {
1029 public:
1030 RandStrLit(class RandStrParser *p)
1031 {
1032 /*
1033 * Allocate our buffer. To make this easy, we use the total byt
1034 * length of the string remaining. This is more than we'll
1035 * actually ever need, on two counts: we could have more bytes than
1036 * characters in the remaining source, since some characters could
1037 * be multi-byte; and the quoted section probably isn't the whole
1038 * rest of the string. So we'll waste a little memory. But this
1039 * object is short-lived and the wasted space is usually trivial,
1040 * so it's not worth the additional work to be more precise in
1041 * allocating the buffer.
1042 */
1043 buf = new wchar_t[p->getrem()];
1044 len = 0;
1045
1046 /* skip the open quote, then parse the contents */
1047 for (p->skip() ; p->more() ; p->skip())
1048 {
1049 wchar_t ch;
1050
1051 /* if we're at a close quote, we might be done */
1052 if ((ch = p->getch()) == '"')
1053 {
1054 /* skip the quote */
1055 p->skip();
1056
1057 /* if it's not stuttered, we're done */
1058 if ((ch = p->getch()) != '"')
1059 break;
1060 }
1061
1062 /* add this character to our buffer */
1063 buf[len++] = ch;
1064 }
1065 }
1066
1067 ~RandStrLit()
1068 {
1069 delete [] buf;
1070 }
1071
1072 virtual int maxlen() { return len; }
1073 virtual void generate(VMG_ wchar_t *&dst)
1074 {
1075 /* copy our string */
1076 memcpy(dst, buf, len*sizeof(*dst));
1077
1078 /* advance the pointer */
1079 dst += len;
1080 }
1081
1082 protected:
1083 /* our buffer */
1084 wchar_t *buf;
1085
1086 /* number of charactres in the buffer */
1087 size_t len;
1088 };
1089
1090 /* atom - this is a single character specifier or a [character list] */
1091 class RandStrAtom: public RandStrNode
1092 {
1093 public:
1094 RandStrAtom(class RandStrParser *p)
1095 {
1096 /* we don't have a character class or literal character yet */
1097 ch = 0;
1098 isLit = FALSE;
1099
1100 /* we have no character list items yet */
1101 listChars = 0;
1102
1103 /* check for a character list of the form [abcw-z] */
1104 if (p->getch() == '[')
1105 {
1106 /* keep going until we reach the ']' or end of string */
1107 for (p->skip() ; p->more() && p->getch() != ']' ; )
1108 {
1109 /* get the next character */
1110 wchar_t c1 = p->getch();
1111
1112 /* check for quoting */
1113 if (c1 == '%')
1114 {
1115 /* skip the '%' and get the quoted character */
1116 p->skip();
1117 c1 = (p->more() ? p->getch() : '%');
1118 }
1119
1120 /* skip the character */
1121 p->skip();
1122
1123 /* if the next character is '-', we have a range expression */
1124 if (p->getch() == '-')
1125 {
1126 /* skip the '-' */
1127 p->skip();
1128
1129 /* if there's a '%', skip it as well */
1130 if (p->getch() == '%')
1131 p->skip();
1132
1133 /* get the upper bound character */
1134 wchar_t c2 = (p->more() ? p->getch() : c1);
1135
1136 /* skip the second character */
1137 p->skip();
1138
1139 /* add the range */
1140 addChild(new RandStrRange(c1, c2));
1141 listChars += (c2 > c1 ? c2 - c1 : c1 - c2) + 1;
1142 }
1143 else
1144 {
1145 /* it's just this character in the range */
1146 addChild(new RandStrRange(c1, c1));
1147 listChars += 1;
1148 }
1149 }
1150
1151 /* skip the ']' */
1152 p->skip();
1153 }
1154 else if (p->getch() == '%')
1155 {
1156 /*
1157 * quoted character expression - skip the '%' and store the
1158 * single character
1159 */
1160 p->skip();
1161 ch = p->more() ? p->getch() : '%';
1162
1163 /* note that this is a literal character expression */
1164 isLit = TRUE;
1165
1166 /* skip the character */
1167 p->skip();
1168 }
1169 else
1170 {
1171 /* character class expression - store it and skip it */
1172 ch = p->getch();
1173 p->skip();
1174 }
1175 }
1176
1177 /* an atom generates exactly one character */
1178 virtual int maxlen() { return 1; }
1179
1180 /* generate the atom */
1181 virtual void generate(VMG_ wchar_t *&dst)
1182 {
1183 /*
1184 * If we have a character list expression, choose a character from
1185 * the list. Otherwise, generate a character according to our
1186 * character class code.
1187 */
1188 wchar_t outc;
1189 if (listChars != 0)
1190 {
1191 /* pick a random index in our range */
1192 wchar_t n = (wchar_t)rand_range(rng_next(vmg0_), listChars);
1193
1194 /* find the range containing this character */
1195 for (RandStrNode *chi = firstChild ; chi != 0 ;
1196 chi = chi->nextSibling)
1197 {
1198 /* cast the child - we know it's a range node */
1199 RandStrRange *r = (RandStrRange *)chi;
1200
1201 /* if the index is in this range, we've found it */
1202 if (n <= r->c2 - r->c1)
1203 {
1204 outc = r->c1 + n;
1205 break;
1206 }
1207
1208 /* deduct the size of this range from the index */
1209 n -= (r->c2 - r->c1 + 1);
1210 }
1211 }
1212 else if (isLit)
1213 {
1214 /* literal character expression */
1215 outc = ch;
1216 }
1217 else
1218 {
1219 /* no list, so generate a character based on the class code */
1220 ulong rand_val = rng_next(vmg0_);
1221 switch (ch)
1222 {
1223 case 'i':
1224 /* printable ASCII character 32-126 */
1225 outc = (wchar_t)rand_range(rand_val, 32, 126);
1226 break;
1227
1228 case 'l':
1229 /* printable Latin-1 character 32-126, 160-255 */
1230 outc = (wchar_t)rand_range(rand_val, 32, 126, 160, 255);
1231 break;
1232
1233 case 'u':
1234 /*
1235 * Printable Unicode character. This excludes undefined
1236 * character, the private use area, and the control
1237 * characters.
1238 */
1239 for (;;)
1240 {
1241 /* exclude the control and private use ranges */
1242 outc = (wchar_t)rand_range(
1243 rand_val, 32, 127, 160, 0xDFFF, 0xF900, 0xFFFE);
1244
1245 /* if it's a unicode character, we're set */
1246 if (t3_is_unichar(ch))
1247 break;
1248
1249 /* pick a new random number */
1250 rand_val = rng_next(vmg0_);
1251 }
1252 break;
1253
1254 case 'd':
1255 /* decimal digit 0-9 */
1256 outc = (wchar_t)rand_range(rand_val, '0', '9');
1257 break;
1258
1259 case 'X':
1260 /* upper-case hex digit 0-9 A-F */
1261 outc = (wchar_t)rand_range(rand_val, '0', '9', 'A', 'F');
1262 break;
1263
1264 case 'x':
1265 /* lower-case hex digit 0-9 a-f */
1266 outc = (wchar_t)rand_range(rand_val, '0', '9', 'a', 'f');
1267 break;
1268
1269 case 'A':
1270 /* letter A-Z */
1271 outc = (wchar_t)rand_range(rand_val, 'A', 'Z');
1272 break;
1273
1274 case 'a':
1275 /* letter a-z */
1276 outc = (wchar_t)rand_range(rand_val, 'a', 'z');
1277 break;
1278
1279 case 'b':
1280 /* random byte value 0-255 */
1281 outc = (wchar_t)rand_range(rand_val, 0, 255);
1282 break;
1283
1284 case 'c':
1285 /* mixed-case letter A-Z a-z */
1286 outc = (wchar_t)rand_range(rand_val, 'a', 'z', 'A', 'Z');
1287 break;
1288
1289 case 'z':
1290 /* mixed-case letter or number 0-9 a-z A-Z */
1291 outc = (wchar_t)rand_range(rand_val,
1292 '0', '9', 'a', 'z', 'A', 'Z');
1293 break;
1294
1295 default:
1296 /* no character */
1297 return;
1298 }
1299 }
1300
1301 /* store the output character */
1302 *dst++ = outc;
1303 }
1304
1305 protected:
1306 /* for a single-character expression, the character */
1307 wchar_t ch;
1308
1309 /* is 'ch' a literal character, or a character code expression? */
1310 int isLit;
1311
1312 /* number of characters included in all of [character list] elements */
1313 int listChars;
1314 };
1315
1316 /*
1317 * repeat group - this is an item optionally followed by a {repeat count},
1318 * a '*', or a '?'
1319 */
1320 class RandStrRepeat: public RandStrNode
1321 {
1322 public:
1323 RandStrRepeat(RandStrParser *p);
1324
1325 /*
1326 * If we have a finite upper bound, our maximum length is our child
1327 * item length times our maximum repeat count. If there's no upper
1328 * bound, our output is in principle infinite, but the probability of
1329 * the string being at least a given length N is (2/3)^N, so the odds
1330 * drop off very rapidly as N increases; at N=25, we're down to one in
1331 * 25,000. Return 50, and use this as a hard cap in the generator.
1332 */
1333 static const int MAX_UNBOUNDED = 50;
1334 virtual int maxlen()
1335 {
1336 return firstChild->maxlen() * (hi < 0 ? MAX_UNBOUNDED : hi);
1337 }
1338
1339 /* generate */
1340 virtual void generate(VMG_ wchar_t *&dst)
1341 {
1342 if (hi >= 0)
1343 {
1344 /*
1345 * Finite upper bound. Pick a random repeat count from lo to
1346 * hi, and generate our child that many times.
1347 */
1348 for (ulong cnt = rand_range(rng_next(vmg0_), lo, hi) ;
1349 cnt != 0 ; --cnt)
1350 firstChild->generate(vmg_ dst);
1351 }
1352 else
1353 {
1354 /* no upper bound - start with the fixed lower bound */
1355 int i;
1356 for (i = 0 ; i < lo ; ++i)
1357 firstChild->generate(vmg_ dst);
1358
1359 /*
1360 * Now add additional items one at a time, with 67% probability
1361 * for each added item. Stop when we fail the roll.
1362 */
1363 for (i = 0 ;
1364 rand_range(rng_next(vmg0_), 0, 99) < 67 && i < MAX_UNBOUNDED ;
1365 ++i)
1366 firstChild->generate(vmg_ dst);
1367 }
1368 }
1369
1370 /*
1371 * Repeat range. If hi is negative, there's no upper bound. Rather
1372 * than picking a number from 0 to infinity uniformly (which is
1373 * obviously impractical, since the expectation value is infinite), we
1374 * have a 50% chance of adding each additional item.
1375 */
1376 int lo, hi;
1377 };
1378
1379 /* concatenation list - this is a list of repeat groups */
1380 class RandStrCatList: public RandStrNode
1381 {
1382 public:
1383 RandStrCatList(RandStrParser *p)
1384 {
1385 /*
1386 * parse repeat groups until we reach the end of the string, the
1387 * end of the alternative, or the end of the parenthesized group
1388 */
1389 while (p->more() && p->getch() != ')' && p->getch() != '|')
1390 addChild(new RandStrRepeat(p));
1391 }
1392
1393 /*
1394 * we generate a concatenation of our children, so our length is the
1395 * sum of our child lengths
1396 */
1397 virtual int maxlen()
1398 {
1399 int sum = 0;
1400 for (RandStrNode *chi = firstChild ; chi != 0 ;
1401 sum += chi->maxlen(), chi = chi->nextSibling) ;
1402
1403 return sum;
1404 }
1405
1406 /* generate */
1407 virtual void generate(VMG_ wchar_t *&dst)
1408 {
1409 /* generate each child sequentially */
1410 for (RandStrNode *chi = firstChild ; chi != 0 ; chi = chi->nextSibling)
1411 chi->generate(vmg_ dst);
1412 }
1413 };
1414
1415 /* alternative list - this is a list of CatList items separated by '|' */
1416 class RandStrAltList: public RandStrNode
1417 {
1418 public:
1419 RandStrAltList(RandStrParser *p, int isOuterExpr)
1420 {
1421 /* no alternatives yet */
1422 altCount = 0;
1423
1424 /*
1425 * parse alternatives until we reach the end of the string or a
1426 * close paren (unless we're the outermost expression, in which
1427 * case we treat ')' as an ordinary character since there's no
1428 * enclosing group to close)
1429 */
1430 while (p->more() && (isOuterExpr || p->getch() != ')'))
1431 {
1432 /* parse the next alternative and add it to our child list */
1433 addChild(new RandStrCatList(p));
1434 altCount += 1;
1435
1436 /* if there's a '|', skip it */
1437 if (p->getch() == '|')
1438 p->skip();
1439 }
1440 }
1441
1442 /*
1443 * when we generate, we choose one child to generate, so our maximum
1444 * length is the highest of our individual child lengths
1445 */
1446 virtual int maxlen()
1447 {
1448 int lmax = 0;
1449 for (RandStrNode *chi = firstChild ; chi != 0 ; chi = chi->nextSibling)
1450 {
1451 int l = chi->maxlen();
1452 if (l > lmax)
1453 lmax = l;
1454 }
1455
1456 return lmax;
1457 }
1458
1459 /* generate */
1460 virtual void generate(VMG_ wchar_t *&dst)
1461 {
1462 /* pick one of our alternatives at random */
1463 int n = rand_range(rng_next(vmg0_), altCount);
1464
1465 /* find it and generate it */
1466 RandStrNode *chi;
1467 for (chi = firstChild ; n != 0 && chi != 0 ;
1468 --n, chi = chi->nextSibling) ;
1469
1470 /* generate the expression */
1471 if (chi != 0)
1472 chi->generate(vmg_ dst);
1473 }
1474
1475 /* number of alternatives */
1476 int altCount;
1477 };
1478
1479 /*
1480 * repeat group - this is an atom or parenthesized expression, optionally
1481 * followed by a postfix repeat count
1482 */
1483 RandStrRepeat::RandStrRepeat(RandStrParser *p)
1484 {
1485 /* if we have an open paren, parse the enclosed alt list */
1486 if (p->getch() == '(')
1487 {
1488 /* skip the open paren */
1489 p->skip();
1490
1491 /* parse the alt list */
1492 addChild(new RandStrAltList(p, FALSE));
1493
1494 /* if there's a close paren, skip it */
1495 if (p->getch() == ')')
1496 p->skip();
1497 }
1498 else if (p->getch() == '"')
1499 {
1500 /* parse the literal string */
1501 addChild(new RandStrLit(p));
1502 }
1503 else
1504 {
1505 /* no parens or quotes, so this is a simple character atom */
1506 addChild(new RandStrAtom(p));
1507 }
1508
1509 /* check for {n}, {n-m}, *, or ? */
1510 if (p->getch() == '{')
1511 {
1512 /* skip the '{' */
1513 p->skip();
1514
1515 /* parse the low end of the range */
1516 lo = p->parseInt();
1517
1518 /* if we're at a ',', get the high end of the range */
1519 if (p->getch() == ',')
1520 {
1521 /* there's a separate high part - get it */
1522 for (p->skip() ; is_space(p->getch()) ; p->skip()) ;
1523
1524 /*
1525 * if the high part is missing, there's no upper bound;
1526 * otherwise parse the finite upper bound
1527 */
1528 if (p->getch() == '}' || p->getch() == '\0')
1529 {
1530 /* -1 means "infinity" */
1531 hi = -1;
1532 }
1533 else
1534 {
1535 /* parse the upper bound */
1536 hi = p->parseInt();
1537
1538 /* make sure hi > lo */
1539 if (hi < lo)
1540 {
1541 int tmp = hi;
1542 hi = lo;
1543 lo = tmp;
1544 }
1545 }
1546 }
1547 else
1548 {
1549 /* there's only the one number, so it's the low and high */
1550 hi = lo;
1551 }
1552
1553 /* skip the '}' */
1554 if (p->getch() == '}')
1555 p->skip();
1556 }
1557 else if (p->getch() == '+')
1558 {
1559 /* one or more */
1560 lo = 1;
1561 hi = -1;
1562 p->skip();
1563 }
1564 else if (p->getch() == '*')
1565 {
1566 /* zero or more */
1567 lo = 0;
1568 hi = -1;
1569 p->skip();
1570 }
1571 else if (p->getch() == '?')
1572 {
1573 /* zero or one */
1574 lo = 0;
1575 hi = 1;
1576 p->skip();
1577 }
1578 else
1579 {
1580 /* no repeat count - generate exactly once */
1581 lo = hi = 1;
1582 }
1583 }
1584
1585 /*
1586 * main parser implementation
1587 */
1588 RandStrParser::RandStrParser(const char *src, size_t len)
1589 {
1590 /* set up our string pointer */
1591 this->p.set((char *)src);
1592 this->rem = len;
1593
1594 /* parse the tree starting at the top of the recursive descent */
1595 tree = new RandStrAltList(this, TRUE);
1596 }
1597
1598 RandStrParser::~RandStrParser()
1599 {
1600 /* delete the parse tree */
1601 delete tree;
1602 }
1603
1604 void RandStrParser::exec(VMG_ vm_val_t *result)
1605 {
1606 /* calculate the maximum length of the result */
1607 size_t len = tree->maxlen();
1608
1609 /* if the maximum length is zero, just return an empty string */
1610 if (len == 0)
1611 {
1612 result->set_obj(CVmObjString::create(vmg_ FALSE, 0));
1613 return;
1614 }
1615
1616 /* allocate a wchar_t buffer of the maximum length */
1617 wchar_t *buf = new wchar_t[len];
1618
1619 /* generate the string */
1620 wchar_t *dst = buf;
1621 tree->generate(vmg_ dst);
1622
1623 /* build the return string */
1624 result->set_obj(CVmObjString::create(vmg_ FALSE, buf, dst - buf));
1625
1626 /* done with the temporary buffer */
1627 delete [] buf;
1628 }
1629
1630 /* ------------------------------------------------------------------------ */
1631 /*
1632 * rand - generate a random number, or choose an element randomly from a
1633 * list of values or from our list of arguments.
1634 *
1635 * With one integer argument N, we choose a random number from 0 to N-1.
1636 *
1637 * With one list argument, we choose a random element of the list.
1638 *
1639 * With multiple arguments, we choose one argument at random and return
1640 * its value. Note that, because this is an ordinary built-in function,
1641 * all of our arguments will be fully evaluated.
1642 */
1643 void CVmBifTADS::rand(VMG_ uint argc)
1644 {
1645 int32_t range;
1646 int use_range;
1647 int choose_an_arg = FALSE;
1648 int choose_an_ele = FALSE;
1649 ulong rand_val;
1650
1651 /* determine the desired range of values based on the arguments */
1652 if (argc == 0)
1653 {
1654 /*
1655 * if no argument is given, produce a random number in our full
1656 * range - clear the 'use_range' flag to so indicate
1657 */
1658 use_range = FALSE;
1659 }
1660 else if (argc == 1 && G_stk->get(0)->typ == VM_INT)
1661 {
1662 /* we're returning a number in the range 0..(arg-1) */
1663 range = G_stk->get(0)->val.intval;
1664 use_range = TRUE;
1665
1666 /* discard the argument */
1667 G_stk->discard();
1668 }
1669 else if (argc == 1
1670 && G_stk->get(0)->is_listlike(vmg0_)
1671 && (range = G_stk->get(0)->ll_length(vmg0_)) >= 0)
1672 {
1673 /* use the range of 1..length */
1674 use_range = TRUE;
1675
1676 /* note that we're choosing from a list-like object */
1677 choose_an_ele = TRUE;
1678
1679 /* note - leave the object on the stack as gc protection */
1680 }
1681 else if (argc == 1
1682 && G_stk->get(0)->get_as_string(vmg0_) != 0)
1683 {
1684 /*
1685 * It's a string, giving a template for generating a new random
1686 * string. First, get the string argument.
1687 */
1688 const char *tpl = G_stk->get(0)->get_as_string(vmg0_);
1689 size_t tplbytes = vmb_get_len(tpl);
1690 tpl += VMB_LEN;
1691
1692 #if 1
1693 /* parse it */
1694 RandStrParser *rsp = new RandStrParser(tpl, tplbytes);
1695
1696 err_try
1697 {
1698 /* generate the string */
1699 vm_val_t ret;
1700 rsp->exec(vmg_ &ret);
1701
1702 /* return it */
1703 retval(vmg_ &ret);
1704 }
1705 err_finally
1706 {
1707 /* delete our parser on the way out */
1708 delete rsp;
1709 }
1710 err_end;
1711
1712 #else
1713 /* figure its character length */
1714 utf8_ptr tplp((char *)tpl);
1715 size_t tplchars = tplp.len(tplbytes);
1716
1717 /* allocate temporary space for the result, as wide characters */
1718 wchar_t *buf = new wchar_t[tplchars], *dst;
1719
1720 /* run through the template and generate random characters */
1721 for (dst = buf ; tplbytes != 0 ; )
1722 {
1723 /* generate a random number for this character */
1724 rand_val = rng_next(vmg0_);
1725
1726 /* get and skip the next template character */
1727 wchar_t tch = tplp.getch();
1728 tplp.inc(&tplbytes);
1729
1730 /* translate the template character */
1731 wchar_t ch;
1732 switch (tch)
1733 {
1734 case '.':
1735 /* printable ASCII character 32-126 */
1736 ch = (wchar_t)rand_range(rand_val, 32, 126);
1737 break;
1738
1739 case '?':
1740 /* printable Latin-1 character 32-126, 160-255 */
1741 ch = (wchar_t)rand_range(rand_val, 32, 126, 160, 255);
1742 break;
1743
1744 case '*':
1745 /*
1746 * Printable Unicode character. This excludes undefined
1747 * character, the private use area, and the control
1748 * characters.
1749 */
1750 for (;;)
1751 {
1752 /* exclude the control and private use ranges */
1753 ch = (wchar_t)rand_range(
1754 rand_val, 32, 127, 160, 0xDFFF, 0xF900, 0xFFFE);
1755
1756 /* if it's a unicode character, we're set */
1757 if (t3_is_unichar(ch))
1758 break;
1759
1760 /* pick a new random number */
1761 rand_val = rng_next(vmg0_);
1762 }
1763 break;
1764
1765 case '9':
1766 /* digit 0-9 */
1767 ch = (wchar_t)rand_range(rand_val, '0', '9');
1768 break;
1769
1770 case 'X':
1771 /* upper-case hex digit 0-9 A-F */
1772 ch = (wchar_t)rand_range(rand_val, '0', '9', 'A', 'F');
1773 break;
1774
1775 case 'x':
1776 /* lower-case hex digit 0-9 a-f */
1777 ch = (wchar_t)rand_range(rand_val, '0', '9', 'a', 'f');
1778 break;
1779
1780 case 'A':
1781 /* letter A-Z */
1782 ch = (wchar_t)rand_range(rand_val, 'A', 'Z');
1783 break;
1784
1785 case 'a':
1786 /* letter a-z */
1787 ch = (wchar_t)rand_range(rand_val, 'a', 'z');
1788 break;
1789
1790 case 'b':
1791 /* random byte value 0-255 */
1792 ch = (wchar_t)rand_range(rand_val, 0, 255);
1793 break;
1794
1795 case 'c':
1796 /* mixed-case letter A-Z a-z */
1797 ch = (wchar_t)rand_range(rand_val, 'a', 'z', 'A', 'Z');
1798 break;
1799
1800 case 'z':
1801 /* mixed-case letter or number 0-9 a-z A-Z */
1802 ch = (wchar_t)rand_range(rand_val,
1803 '0', '9', 'a', 'z', 'A', 'Z');
1804 break;
1805
1806 case '[':
1807 /*
1808 * Character range. Scan the range to count the number of
1809 * characters included.
1810 */
1811 {
1812 /*
1813 * allocate a list of range descriptors - use 'len2' as
1814 * the range count, since at the most we could have one
1815 * range per byte (but it'll usually be less)
1816 */
1817 struct rdesc
1818 {
1819 int set(wchar_t c)
1820 {
1821 start = end = c;
1822 return 1;
1823 }
1824 int set(wchar_t a, wchar_t b)
1825 {
1826 if (b > a)
1827 start = a, end = b;
1828 else
1829 start = b, end = a;
1830 return end - start + 1;
1831 }
1832 wchar_t start;
1833 wchar_t end;
1834 };
1835 rdesc *ranges = new rdesc[tplbytes];
1836 int nranges = 0, nchars = 0;
1837
1838 /* scan for the closing ']' */
1839 for ( ; tplbytes != 0 && tplp.getch() != ']' ;
1840 tplp.inc(&tplbytes))
1841 {
1842 /* check for escapes */
1843 wchar_t rch = tplp.getch();
1844 if (rch == '%')
1845 {
1846 tplp.inc(&tplbytes);
1847 rch = tplp.getch();
1848 }
1849
1850 /* if the next character is '-', it's a range */
1851 if (tplbytes > 1 && tplp.getch_at(1) == '-')
1852 {
1853 /* skip the current character and the '-' */
1854 tplp.inc(&tplbytes);
1855 tplp.inc(&tplbytes);
1856
1857 /* if the next character is quoted, skip the % */
1858 if (tplbytes > 1 && tplp.getch() == '%')
1859 tplp.inc(&tplbytes);
1860
1861 /*
1862 * The range count includes everything from
1863 * 'rch' to the current character.
1864 */
1865 if (tplbytes != 0)
1866 nchars += ranges[nranges++].set(
1867 rch, tplp.getch());
1868 }
1869 else
1870 {
1871 /* it's a single character range */
1872 nchars += ranges[nranges++].set(rch);
1873 }
1874
1875 /* if we're out of characters, we're done */
1876 if (tplbytes == 0)
1877 break;
1878 }
1879
1880 /* pick a number from 0 to rcnt */
1881 ch = (wchar_t)rand_range(rand_val, nchars);
1882
1883 /* find the character */
1884 for (int i = 0 ; i < nranges ; ++i)
1885 {
1886 /* if it's in the current range, apply it */
1887 const rdesc *r = &ranges[i];
1888 if (ch <= r->end - r->start)
1889 {
1890 ch += r->start;
1891 break;
1892 }
1893
1894 /*
1895 * it's not in this range, so deduct the range
1896 * length from the remainder and keep going
1897 */
1898 ch -= r->end - r->start + 1;
1899 }
1900
1901 /* done with the range list */
1902 delete [] ranges;
1903
1904 /* skip the closing ']' */
1905 if (tplbytes != 0 && tplp.getch() == ']')
1906 tplp.inc(&tplbytes);
1907 }
1908 break;
1909
1910 case '%':
1911 /* copy the next character unchanged */
1912 if (tplbytes != 0)
1913 {
1914 ch = tplp.getch();
1915 tplp.inc(&tplbytes);
1916 }
1917 else
1918 ch = '%';
1919 break;
1920
1921 default:
1922 /* no character */
1923 continue;
1924 }
1925
1926 /* save it in our temp buffer, and note its utf8 size */
1927 *dst++ = ch;
1928 }
1929
1930 /* convert the temp buffer to a real string */
1931 retval_obj(vmg_ CVmObjString::create(vmg_ FALSE, buf, dst - buf));
1932
1933 /* done with the temporary buffer */
1934 delete [] buf;
1935 #endif
1936
1937 /* discard the argument */
1938 G_stk->discard();
1939
1940 /* we're done */
1941 return;
1942 }
1943 else
1944 {
1945 /*
1946 * produce a random number in the range 0..(argc-1) so that we
1947 * can select one of our arguments
1948 */
1949 range = argc;
1950 use_range = TRUE;
1951
1952 /* note that we should choose an argument value */
1953 choose_an_arg = TRUE;
1954 }
1955
1956 /* get the next random number */
1957 rand_val = rng_next(vmg0_);
1958
1959 /*
1960 * Calculate our random value in the range 0..(range-1). If range
1961 * == 0, simply choose a value across our full range.
1962 */
1963 if (use_range)
1964 rand_val = rand_range(rand_val, range);
1965
1966 /*
1967 * Return the appropriate value, depending on our argument list
1968 */
1969 if (choose_an_arg)
1970 {
1971 /* return the selected argument */
1972 retval(vmg_ G_stk->get((int)rand_val));
1973
1974 /* discard all of the arguments */
1975 G_stk->discard(argc);
1976 }
1977 else if (choose_an_ele)
1978 {
1979 vm_val_t val;
1980
1981 /* get the selected element */
1982 if (range == 0)
1983 {
1984 /* there are no elements to choose from, so return nil */
1985 val.set_nil();
1986 }
1987 else
1988 {
1989 /* get the selected list element */
1990 G_stk->get(0)->ll_index(vmg_ &val, rand_val + 1);
1991 }
1992
1993 /* set the result */
1994 retval(vmg_ &val);
1995
1996 /* discard our gc protection */
1997 G_stk->discard();
1998 }
1999 else
2000 {
2001 /* simply return the random number */
2002 retval_int(vmg_ (long)rand_val);
2003 }
2004 }
2005
2006 /* ------------------------------------------------------------------------ */
2007 /*
2008 * toString - convert to string
2009 */
2010 void CVmBifTADS::toString(VMG_ uint argc)
2011 {
2012 /* check arguments */
2013 check_argc_range(vmg_ argc, 1, 3);
2014
2015 /* get the argument */
2016 vm_val_t *val = G_stk->get(0);
2017
2018 /* if there's a radix specified, pop it as well */
2019 int radix = (argc >= 2 ? G_stk->get(1)->num_to_int(vmg0_) : 10);
2020
2021 /* the radix must be from 2 to 36 */
2022 if (radix < 2 || radix > 36)
2023 err_throw(VMERR_BAD_VAL_BIF);
2024
2025 /* assume unsigned */
2026 int flags = TOSTR_UNSIGNED;;
2027
2028 /*
2029 * If the 'isSigned' argument is present, pop it as a bool; otherwise
2030 * treat the value as signed if the radix is decimal, otherwise
2031 * unsigned.
2032 */
2033 if (argc >= 3 ? G_stk->get(2)->get_logical_only() : radix == 10)
2034 flags &= ~TOSTR_UNSIGNED;
2035
2036 /* convert the value */
2037 toString(vmg_ G_interpreter->get_r0(), val, radix, flags);
2038
2039 /* discard arguments */
2040 G_stk->discard(argc);
2041 }
2042
2043 /*
2044 * explicitly convert to string
2045 */
2046 void CVmBifTADS::toString(VMG_ vm_val_t *result, const vm_val_t *val,
2047 int radix, int flags)
2048 {
2049 /* do the basic string conversion */
2050 char buf[50];
2051 const char *p = CVmObjString::cvt_to_str(
2052 vmg_ result, buf, sizeof(buf), val, radix, flags);
2053
2054 /* save the new string on the stack to protect from garbage collection */
2055 G_stk->push(result);
2056
2057 /*
2058 * if the return value wasn't already a new object, create a string
2059 * from the return value
2060 */
2061 if (result->typ != VM_OBJ)
2062 {
2063 /* we just have a string in a buffer - create a new string from it */
2064 result->set_obj(CVmObjString::create(
2065 vmg_ FALSE, p + VMB_LEN, vmb_get_len(p)));
2066 }
2067
2068 /* discard gc protection */
2069 G_stk->discard(1);
2070 }
2071
2072 /*
2073 * toInteger - convert to an integer
2074 */
2075 void CVmBifTADS::toInteger(VMG_ uint argc)
2076 {
2077 /* convert as an integer only */
2078 toIntOrNum(vmg_ argc, TRUE);
2079 }
2080
2081 /*
2082 * toNumber - convert to an integer or BigNumber
2083 */
2084 void CVmBifTADS::toNumber(VMG_ uint argc)
2085 {
2086 /* convert as integer or BigNumber */
2087 toIntOrNum(vmg_ argc, FALSE);
2088 }
2089
2090 /*
2091 * Common handler for toInteger and toNumber
2092 */
2093 void CVmBifTADS::toIntOrNum(VMG_ uint argc, int int_only)
2094 {
2095 /* check arguments */
2096 check_argc_range(vmg_ argc, 1, 2);
2097
2098 /* check for BigNumber values */
2099 vm_val_t *valp = G_stk->get(0);
2100 if (valp->typ == VM_OBJ
2101 && CVmObjBigNum::is_bignum_obj(vmg_ valp->val.obj))
2102 {
2103 /*
2104 * If we only want integer results, try converting the BigNumber to
2105 * an integer. Otherwise, simply return the BigNumber as-is.
2106 */
2107 if (int_only)
2108 {
2109 /* we only want an integer result - convert to int */
2110 long intval = ((CVmObjBigNum *)vm_objp(vmg_ valp->val.obj))
2111 ->convert_to_int();
2112
2113 /* return the integer value */
2114 retval_int(vmg_ intval);
2115 }
2116 else
2117 {
2118 /* BigNumber results are okay - just return the BigNumber */
2119 retval(vmg_ valp);
2120 }
2121
2122 /* discard arguments, and we're done */
2123 G_stk->discard(argc);
2124 return;
2125 }
2126
2127 /* if it's already an integer, just return the same value */
2128 if (valp->typ == VM_INT)
2129 {
2130 /* just return the argument value */
2131 retval_int(vmg_ valp->val.intval);
2132
2133 /* discard arguments and return */
2134 G_stk->discard(argc);
2135 return;
2136 }
2137
2138 /* if it's true or nil, convert to 1 or 0 */
2139 if (valp->typ == VM_TRUE || valp->typ == VM_NIL)
2140 {
2141 /* return 1 for true, 0 for nil */
2142 retval_int(vmg_ valp->typ == VM_TRUE ? 1 : 0);
2143 G_stk->discard(argc);
2144 return;
2145 }
2146
2147 /* the only other type of value we can convert is a string */
2148 const char *strp = G_stk->get(0)->get_as_string(vmg0_);
2149 if (strp == 0)
2150 err_throw(VMERR_STRING_VAL_REQD);
2151
2152 /* get the string length and buffer pointer */
2153 size_t len = vmb_get_len(strp);
2154 strp += VMB_LEN;
2155
2156 /* if there's a radix specified, pop it as well; the default is 10 */
2157 int radix = 10;
2158 if (argc >= 2)
2159 {
2160 /* get the radix from the stack */
2161 radix = G_stk->get(1)->num_to_int(vmg0_);
2162
2163 /* make sure it's in the valid range */
2164 if (radix < 2 || radix > 36)
2165 err_throw(VMERR_BAD_VAL_BIF);
2166 }
2167
2168 /* get a version of the string stripped of leading and trailing spaces */
2169 const char *p2 = strp;
2170 size_t len2 = len;
2171 for ( ; len2 != 0 && is_space(*p2) ; ++p2, --len2) ;
2172 for ( ; len2 != 0 && is_space(*(p2 + len2 - 1)) ; --len2) ;
2173
2174 /*
2175 * Check for "nil" and "true", ignoring leading and trailing spaces; if
2176 * it matches either of those, return the corresponding boolean value.
2177 * Otherwise, parse the string as an integer value in the given radix.
2178 */
2179 if (len2 == 3 && memcmp(p2, "nil", 3) == 0)
2180 {
2181 /* the value for "nil" is 0 */
2182 retval_int(vmg_ 0);
2183 }
2184 else if (len2 == 4 && memcmp(p2, "true", 3) == 0)
2185 {
2186 /* the value for "true" is 1 */
2187 retval_int(vmg_ 1);
2188 }
2189 else
2190 {
2191 /* parse the string as an integer (orBigNumber if it's too large) */
2192 vm_val_t val;
2193 CVmObjString::parse_num_val(vmg_ &val, strp, len, radix, int_only);
2194 retval(vmg_ &val);
2195 }
2196
2197 /* discard arguments */
2198 G_stk->discard(argc);
2199 }
2200
2201 /* ------------------------------------------------------------------------ */
2202 /*
2203 * put an integer value in a constant list, advancing the list write
2204 * pointer
2205 */
2206 static void put_list_int(char **dstp, long intval)
2207 {
2208 /* set up the integer value */
2209 vm_val_t val;
2210 val.set_int(intval);
2211
2212 /* write it to the list */
2213 vmb_put_dh(*dstp, &val);
2214
2215 /* advance the output pointer */
2216 *dstp += VMB_DATAHOLDER;
2217 }
2218
2219 /*
2220 * put an object value in a constant list, advancing the list write
2221 * pointer
2222 */
2223 static void put_list_obj(char **dstp, vm_obj_id_t objval)
2224 {
2225 vm_val_t val;
2226
2227 /* set up the integer value */
2228 val.set_obj(objval);
2229
2230 /* write it to the list */
2231 vmb_put_dh(*dstp, &val);
2232
2233 /* advance the output pointer */
2234 *dstp += VMB_DATAHOLDER;
2235 }
2236
2237
2238 /*
2239 * Given a time_t value, create a list of components giving the local time
2240 * corresponding to the time_t, using the getTime(GetDateAndTime) format.
2241 * Returns the object ID of the new list.
2242 *
2243 * The list format is [year, month, day, day-of-week, day-of-year, hour,
2244 * minute, second, seconds-since-1970].
2245 */
2246 vm_obj_id_t CVmBifTADS::format_datetime_list(VMG_ os_time_t timer)
2247 {
2248 /* note the starting stack pointer, so we can discard gc protection */
2249 vm_val_t *gsp = G_stk->get_sp();
2250
2251 /* convert the time_t to the local time */
2252 struct tm *tblock = os_localtime(&timer);
2253
2254 /* start the list buffer - set the length (9 elements) */
2255 char buf[80];
2256 vmb_put_len(buf, 9);
2257 char *dst = buf + VMB_LEN;
2258
2259 /* add the time elements to the list */
2260 put_list_int(&dst, tblock->tm_year + 1900);
2261 put_list_int(&dst, tblock->tm_mon + 1);
2262 put_list_int(&dst, tblock->tm_mday);
2263 put_list_int(&dst, tblock->tm_wday + 1);
2264 put_list_int(&dst, tblock->tm_yday + 1);
2265 put_list_int(&dst, tblock->tm_hour);
2266 put_list_int(&dst, tblock->tm_min);
2267 put_list_int(&dst, tblock->tm_sec);
2268
2269 /*
2270 * if the timer is over 0x7fffffff, we can't represent it as an
2271 * int32_t, so store it as a BigNumber value
2272 */
2273 if (timer <= 0x7fffffffU)
2274 {
2275 /* it'll fit in an ordinary 32-bit signed int */
2276 put_list_int(&dst, (uint32_t)timer);
2277 }
2278 else
2279 {
2280 /* it won't fit an int32, so convert to BigNumber */
2281 vm_obj_id_t bn;
2282 if (sizeof(timer) <= 4)
2283 {
2284 /* os_time_t must be a uint32 */
2285 bn = CVmObjBigNum::createu(vmg_ FALSE, (ulong)timer, 10);
2286 }
2287 else
2288 {
2289 /* os_time_t must be 64 bits (or larger) */
2290 bn = CVmObjBigNum::create_int64(
2291 vmg_ FALSE, (uint32_t)(timer >> 32),
2292 (uint32_t)(timer & 0xFFFFFFFF));
2293 }
2294
2295 /* save it on the stack for gc protection */
2296 G_stk->push()->set_obj(bn);
2297
2298 /* add it to the list */
2299 put_list_obj(&dst, bn);
2300 }
2301
2302 /* create a list from the formatted buffer, and return its object ID */
2303 vm_obj_id_t lst = CVmObjList::create(vmg_ FALSE, buf);
2304
2305 /* discard gc protection */
2306 G_stk->set_sp(gsp);
2307
2308 /* return the list */
2309 return lst;
2310 }
2311
2312 /*
2313 * get the current time
2314 */
2315 void CVmBifTADS::gettime(VMG_ uint argc)
2316 {
2317 /* check arguments */
2318 check_argc_range(vmg_ argc, 0, 1);
2319
2320 /* if there's an argument, get the type of time value to return */
2321 int typ;
2322 if (argc == 1)
2323 {
2324 /* get the time type code */
2325 typ = pop_int_val(vmg0_);
2326 }
2327 else
2328 {
2329 /* use the default type */
2330 typ = 1;
2331 }
2332
2333 /* check the type */
2334 switch(typ)
2335 {
2336 case 1:
2337 /*
2338 * GetTimeDateAndTime - return the current time and date as a list
2339 * of time elements
2340 */
2341
2342 /* get the current system time and format it into our list */
2343 retval_obj(vmg_ format_datetime_list(vmg_ os_time(NULL)));
2344
2345 /* done */
2346 break;
2347
2348 case 2:
2349 /*
2350 * They want the high-precision system timer value, which returns
2351 * the time in milliseconds from an arbitrary zero point.
2352 */
2353 {
2354 unsigned long t;
2355 static unsigned long t_zero;
2356 static int t_zero_set = FALSE;
2357
2358 /* retrieve the raw time from the operating system */
2359 t = os_get_sys_clock_ms();
2360
2361 /*
2362 * We only have 31 bits of precision in our result (since we
2363 * must fit the value into a signed integer), so we can only
2364 * represent time differences of about 23 days. Now, the
2365 * value from the OS could be at any arbitrary point in our
2366 * 23-day range, so there's a nontrivial probability that the
2367 * raw OS value is near enough to the wrapping point that a
2368 * future call to this same function during the current
2369 * session could encounter the wrap condition. The caller is
2370 * likely to be confused by this, because the time difference
2371 * from this call to that future call would appear to be
2372 * negative.
2373 *
2374 * There's obviously no way we can eliminate the possibility
2375 * of a negative time difference if the current program
2376 * session lasts more than 23 days of continuous execution.
2377 * Fortunately, it seems unlikely that most sessions will be
2378 * so long, which gives us a way to reduce the likelihood that
2379 * the program will encounter a wrapped timer: we can adjust
2380 * the zero point of the timer to the time of the first call
2381 * to this function. That way, the timer will wrap only if
2382 * the program session runs continuously until the timer's
2383 * range is exhausted.
2384 */
2385 if (!t_zero_set)
2386 {
2387 /* this is the first call - remember the zero point */
2388 t_zero = t;
2389 t_zero_set = TRUE;
2390 }
2391
2392 /*
2393 * Adjust the time by subtracting the zero point from the raw
2394 * OS timer. This will give us the number of milliseconds
2395 * from our zero point.
2396 *
2397 * If the system timer has wrapped since our zero point, we'll
2398 * get what looks like a negative number; but what we really
2399 * have is a large positive number with a borrow from an
2400 * unrepresented higher-precision portion, so the fact that
2401 * this value is negative doesn't matter - it will still be
2402 * sequential when treated as unsigned.
2403 */
2404 t -= t_zero;
2405
2406 /*
2407 * whatever we got, keep only the low-order 31 bits, since we
2408 * only have 31 bits in which to represent an unsigned value
2409 */
2410 t &= 0x7fffffff;
2411
2412 /* return the value we've calculated */
2413 retval_int(vmg_ t);
2414 }
2415 break;
2416
2417 default:
2418 err_throw(VMERR_BAD_VAL_BIF);
2419 }
2420 }
2421
2422 /* ------------------------------------------------------------------------ */
2423 /*
2424 * re_match - match a regular expression to a string
2425 */
2426 void CVmBifTADS::re_match(VMG_ uint argc)
2427 {
2428 const char *str;
2429 utf8_ptr p;
2430 size_t len;
2431 int match_len;
2432 vm_val_t *v1, *v2, *v3;
2433 int start_idx;
2434 CVmObjPattern *pat_obj = 0;
2435 const char *pat_str = 0;
2436
2437 /* check arguments */
2438 check_argc_range(vmg_ argc, 2, 3);
2439
2440 /*
2441 * make copies of the arguments, so we can pop the values without
2442 * actually removing them from the stack - leave the originals on the
2443 * stack for gc protection
2444 */
2445 v1 = G_stk->get(0);
2446 v2 = G_stk->get(1);
2447 v3 = (argc >= 3 ? G_stk->get(2) : 0);
2448 G_stk->push(v2);
2449 G_stk->push(v1);
2450
2451 /* note the starting index, if given */
2452 start_idx = 1;
2453 if (v3 != 0)
2454 {
2455 /* check the type */
2456 if (v3->typ != VM_INT)
2457 err_throw(VMERR_BAD_TYPE_BIF);
2458
2459 /* get the value */
2460 start_idx = (int)v3->val.intval;
2461 }
2462
2463 /*
2464 * remember the last search string (the second argument), and reset any
2465 * old group registers (since they'd point into the previous string)
2466 */
2467 G_bif_tads_globals->last_rex_str->val = *v2;
2468 G_bif_tads_globals->rex_searcher->clear_group_regs();
2469
2470 /*
2471 * check what we have for the pattern - we could have either a string
2472 * giving the regular expression, or a RexPattern object with the
2473 * compiled pattern
2474 */
2475 if (G_stk->get(0)->typ == VM_OBJ
2476 && CVmObjPattern::is_pattern_obj(vmg_ G_stk->get(0)->val.obj))
2477 {
2478 vm_val_t pat_val;
2479
2480 /* get the pattern object */
2481 G_stk->pop(&pat_val);
2482 pat_obj = (CVmObjPattern *)vm_objp(vmg_ pat_val.val.obj);
2483 }
2484 else
2485 {
2486 /* get the pattern string */
2487 pat_str = pop_str_val(vmg0_);
2488 }
2489
2490 /* get the string to match */
2491 str = pop_str_val(vmg0_);
2492 len = vmb_get_len(str);
2493 p.set((char *)str + VMB_LEN);
2494
2495 /* if the starting index is negative, it's from the end of the string */
2496 start_idx += (start_idx < 0 ? (int)p.len(len) : -1);
2497
2498 /* skip to the starting index */
2499 for ( ; start_idx > 0 && len != 0 ; --start_idx, p.inc(&len)) ;
2500
2501 /* match the pattern */
2502 if (pat_obj != 0)
2503 {
2504 /* match the compiled pattern object */
2505 match_len = G_bif_tads_globals->rex_searcher->
2506 match_pattern(pat_obj->get_pattern(vmg0_),
2507 str + VMB_LEN, p.getptr(), len);
2508 }
2509 else
2510 {
2511 /* match the pattern to the regular expression string */
2512 match_len = G_bif_tads_globals->rex_searcher->
2513 compile_and_match(pat_str + VMB_LEN, vmb_get_len(pat_str),
2514 str + VMB_LEN, p.getptr(), len);
2515 }
2516
2517 /* check for a match */
2518 if (match_len >= 0)
2519 {
2520 /* we got a match - calculate the character length of the match */
2521 retval_int(vmg_ (long)p.len(match_len));
2522 }
2523 else
2524 {
2525 /* no match - return nil */
2526 retval_nil(vmg0_);
2527 }
2528
2529 /* discard the arguments */
2530 G_stk->discard(argc);
2531 }
2532
2533
2534 /* ------------------------------------------------------------------------ */
2535 /*
2536 * Common handler for re_search() and re_search_back()
2537 */
2538 template<int dir> inline void CVmBifTADS::re_search_common(VMG_ uint argc)
2539 {
2540 /* check arguments */
2541 check_argc_range(vmg_ argc, 2, 3);
2542
2543 /*
2544 * make copies of the arguments, so we can pop the values without
2545 * actually removing them from the stack - leave the originals on the
2546 * stack for gc protection
2547 */
2548 vm_val_t *v1 = G_stk->get(0);
2549 vm_val_t *v2 = G_stk->get(1);
2550 vm_val_t *v3 = (argc >= 3 ? G_stk->get(2) : 0);
2551 G_stk->push(v2);
2552 G_stk->push(v1);
2553
2554 /* note the starting index, if given */
2555 int start_idx = (dir > 0 ? 1 : 0);
2556 if (v3 != 0)
2557 {
2558 /* check the type */
2559 if (v3->typ != VM_INT)
2560 err_throw(VMERR_BAD_TYPE_BIF);
2561
2562 /* get the value */
2563 start_idx = (int)v3->val.intval;
2564 }
2565
2566 /*
2567 * remember the last search string (the second argument), and clear out
2568 * any old group registers (since they'd point into the old string)
2569 */
2570 G_bif_tads_globals->last_rex_str->val = *v2;
2571 G_bif_tads_globals->rex_searcher->clear_group_regs();
2572
2573 /* check to see if we have a RexPattern object or an uncompiled string */
2574 const char *pat_str = 0;
2575 CVmObjPattern *pat_obj = 0;
2576 if (G_stk->get(0)->typ == VM_OBJ
2577 && CVmObjPattern::is_pattern_obj(vmg_ G_stk->get(0)->val.obj))
2578 {
2579 vm_val_t pat_val;
2580
2581 /* get the pattern object */
2582 G_stk->pop(&pat_val);
2583 pat_obj = (CVmObjPattern *)vm_objp(vmg_ pat_val.val.obj);
2584 }
2585 else
2586 {
2587 /* get the pattern string */
2588 pat_str = pop_str_val(vmg0_);
2589 }
2590
2591 /* get the string to search for the pattern */
2592 const char *str = pop_str_val(vmg0_);
2593 utf8_ptr p((char *)str + VMB_LEN);
2594 size_t len = vmb_get_len(str);
2595
2596 /* if the starting index is negative, it's from the end of the string */
2597 start_idx += (start_idx < 0 ? (int)p.len(len) :
2598 start_idx == 0 && dir < 0 ? (int)p.len(len) :
2599 -1);
2600
2601 /* skip to the starting index */
2602 for (int i = start_idx ; i > 0 && len != 0 ; --i, p.inc(&len)) ;
2603
2604 /* search for the pattern */
2605 int match_idx;
2606 int match_len;
2607 if (pat_obj != 0)
2608 {
2609 /* try finding the compiled pattern */
2610 match_idx =
2611 (dir > 0
2612 ? G_bif_tads_globals->rex_searcher->search_for_pattern(
2613 pat_obj->get_pattern(vmg0_),
2614 str + VMB_LEN, p.getptr(), len, &match_len)
2615 : G_bif_tads_globals->rex_searcher->search_back_for_pattern(
2616 pat_obj->get_pattern(vmg0_),
2617 str + VMB_LEN, p.getptr(), len, &match_len));
2618 }
2619 else
2620 {
2621 /* try finding the regular expression string pattern */
2622 match_idx =
2623 (dir > 0
2624 ? G_bif_tads_globals->rex_searcher->compile_and_search(
2625 pat_str + VMB_LEN, vmb_get_len(pat_str),
2626 str + VMB_LEN, p.getptr(), len, &match_len)
2627 : G_bif_tads_globals->rex_searcher->compile_and_search_back(
2628 pat_str + VMB_LEN, vmb_get_len(pat_str),
2629 str + VMB_LEN, p.getptr(), len, &match_len));
2630 }
2631
2632 /* check for a match */
2633 if (match_idx >= 0)
2634 {
2635 /*
2636 * We found a match - calculate the character index of the match
2637 * offset, adjusted to a 1-base. The character index is simply the
2638 * number of characters in the part of the string up to the match
2639 * index. Note that we have to add the starting index to get the
2640 * actual index in the overall string, since 'p' points to the
2641 * character at the starting index. Also note that when searching
2642 * backwards, the match index is the number of characters *before*
2643 * the starting point.
2644 */
2645 size_t char_idx;
2646 if (dir > 0)
2647 char_idx = p.len(match_idx) + start_idx + 1;
2648 else
2649 char_idx = utf8_ptr::s_len(
2650 str + VMB_LEN, start_idx - match_idx) + 1;
2651
2652 /* calculate the character length of the match */
2653 utf8_ptr matchp(p.getptr() + dir*match_idx);
2654 size_t char_len = matchp.len(match_len);
2655
2656 /* allocate a string containing the match */
2657 vm_obj_id_t match_str_obj =
2658 CVmObjString::create(vmg_ FALSE, matchp.getptr(), match_len);
2659
2660 /* push it momentarily as protection against garbage collection */
2661 G_stk->push()->set_obj(match_str_obj);
2662
2663 /*
2664 * set up a 3-element list to contain the return value:
2665 * [match_start_index, match_length, match_string]
2666 */
2667 char buf[VMB_LEN + VMB_DATAHOLDER * 3];
2668 vmb_put_len(buf, 3);
2669 char *dst = buf + VMB_LEN;
2670 put_list_int(&dst, (long)char_idx);
2671 put_list_int(&dst, (long)char_len);
2672 put_list_obj(&dst, match_str_obj);
2673
2674 /* allocate and return the list */
2675 retval_obj(vmg_ CVmObjList::create(vmg_ FALSE, buf));
2676
2677 /* we no longer need the garbage collection protection */
2678 G_stk->discard();
2679 }
2680 else
2681 {
2682 /* no match - return nil */
2683 retval_nil(vmg0_);
2684 }
2685
2686 /* discard the arguments */
2687 G_stk->discard(argc);
2688 }
2689
2690 /*
2691 * re_search - search for a substring matching a regular expression
2692 * within a string
2693 */
2694 void CVmBifTADS::re_search(VMG_ uint argc)
2695 {
2696 re_search_common<1>(vmg_ argc);
2697 }
2698
2699 /*
2700 * re_search_back - search backwards for a regular expression
2701 */
2702 void CVmBifTADS::re_search_back(VMG_ uint argc)
2703 {
2704 re_search_common<-1>(vmg_ argc);
2705 }
2706
2707 /* ------------------------------------------------------------------------ */
2708 /*
2709 * re_group - get the string matching a group in the most recent regular
2710 * expression search or match
2711 */
2712 void CVmBifTADS::re_group(VMG_ uint argc)
2713 {
2714 /* check arguments */
2715 check_argc(vmg_ argc, 1);
2716
2717 /* get the group number to retrieve */
2718 int groupno = pop_int_val(vmg0_);
2719
2720 /* group 0 is the special group for the overall match */
2721 const re_group_register *reg;
2722 if (groupno == 0)
2723 {
2724 /* get the special register for the overall match */
2725 reg = G_bif_tads_globals->rex_searcher->get_last_match();
2726 }
2727 else
2728 {
2729 /* make sure it's in range */
2730 if (groupno < 1 || groupno > RE_GROUP_REG_CNT)
2731 err_throw(VMERR_BAD_VAL_BIF);
2732
2733 /* adjust from a 1-base to a 0-base */
2734 --groupno;
2735
2736 /* if the group doesn't exist in the pattern, return nil */
2737 if (groupno >= G_bif_tads_globals->rex_searcher->get_group_cnt())
2738 {
2739 retval_nil(vmg0_);
2740 return;
2741 }
2742
2743 /* get the group register */
2744 reg = G_bif_tads_globals->rex_searcher->get_group_reg(groupno);
2745 }
2746
2747 /*
2748 * get the previous search string - get a pointer directly to the
2749 * contents of the string
2750 */
2751 const char *last_str =
2752 G_bif_tads_globals->last_rex_str->val.get_as_string(vmg0_);
2753
2754 /* if the group wasn't set, or there's no last string, return nil */
2755 if (last_str == 0 || reg->start_ofs == -1 || reg->end_ofs == -1)
2756 {
2757 retval_nil(vmg0_);
2758 return;
2759 }
2760
2761 /* set up for a list with three elements */
2762 char buf[VMB_LEN + 3*VMB_DATAHOLDER];
2763 vmb_put_len(buf, 3);
2764 char *dst = buf + VMB_LEN;
2765
2766 /* get the starting offset from the group register */
2767 int start_byte_ofs = reg->start_ofs;
2768
2769 /*
2770 * The first element is the character index of the group text in the
2771 * source string. Calculate the character index by adding 1 to the
2772 * character length of the text preceding the group; calculate the
2773 * character length from the byte length of that string. Note that the
2774 * starting in the group register is stored from the starting point of
2775 * the search, not the start of the string, so we need to add in the
2776 * starting point in the search.
2777 */
2778 utf8_ptr p((char *)last_str + VMB_LEN);
2779 put_list_int(&dst, p.len(start_byte_ofs) + 1);
2780
2781 /*
2782 * The second element is the character length of the group text.
2783 * Calculate the character length from the byte length.
2784 */
2785 p.set(p.getptr() + start_byte_ofs);
2786 put_list_int(&dst, p.len(reg->end_ofs - reg->start_ofs));
2787
2788 /*
2789 * The third element is the string itself. Create a new string
2790 * containing the matching substring.
2791 */
2792 vm_obj_id_t strobj = CVmObjString::create(
2793 vmg_ FALSE, p.getptr(), reg->end_ofs - reg->start_ofs);
2794 put_list_obj(&dst, strobj);
2795
2796 /* save the string on the stack momentarily to protect against GC */
2797 G_stk->push()->set_obj(strobj);
2798
2799 /* create and return the list value */
2800 retval_obj(vmg_ CVmObjList::create(vmg_ FALSE, buf));
2801
2802 /* we no longer need the garbage collector protection */
2803 G_stk->discard();
2804 }
2805
2806
2807 /* ------------------------------------------------------------------------ */
2808 /*
2809 * rexReplace() - replace one or all occurrences of a regular expression in
2810 * a given subject string with a given replacement string. This uses the
2811 * common find/replace handler defined in vmfindrep.h.
2812 */
2813 void CVmBifTADS::re_replace(VMG_ uint argc)
2814 {
2815 /* check arguments */
2816 check_argc_range(vmg_ argc, 3, 6);
2817
2818 /*
2819 * do the replacement - the subject string is the 2nd stack argument
2820 * (at stack offset 1), so the replacement string argument is at stack
2821 * offset 2
2822 */
2823 vm_find_replace<VMFINDREPLACE_rexReplace>(
2824 vmg_ G_interpreter->get_r0(), argc, G_stk->get(1), 0);
2825
2826 /* discard arguments */
2827 G_stk->discard(argc);
2828 }
2829
2830
2831 /* ------------------------------------------------------------------------ */
2832 /*
2833 * savepoint - establish an undo savepoint
2834 */
2835 void CVmBifTADS::savepoint(VMG_ uint argc)
2836 {
2837 /* check arguments */
2838 check_argc(vmg_ argc, 0);
2839
2840 /* establish the savepoint */
2841 G_undo->create_savept(vmg0_);
2842 }
2843
2844 /*
2845 * undo - undo changes to most recent savepoint
2846 */
2847 void CVmBifTADS::undo(VMG_ uint argc)
2848 {
2849 /* check arguments */
2850 check_argc(vmg_ argc, 0);
2851
2852 /* if no undo is available, return nil to indicate that we can't undo */
2853 if (G_undo->get_savept_cnt() == 0)
2854 {
2855 /* we can't undo */
2856 retval_nil(vmg0_);
2857 }
2858 else
2859 {
2860 /* undo to the savepoint */
2861 G_undo->undo_to_savept(vmg0_);
2862
2863 /* tell the caller that we succeeded */
2864 retval_true(vmg0_);
2865 }
2866 }
2867
2868 /* ------------------------------------------------------------------------ */
2869 /*
2870 * save
2871 */
2872 void CVmBifTADS::save(VMG_ uint argc)
2873 {
2874 /* check arguments */
2875 check_argc_range(vmg_ argc, 1, 2);
2876
2877 /* get the filename argument */
2878 const vm_val_t *filespec = G_stk->get(0);
2879
2880 /*
2881 * if there's a metadata table argument, fetch it (but leave the value
2882 * on the stack for gc protection)
2883 */
2884 CVmObjLookupTable *metatab = 0;
2885 if (argc >= 2)
2886 {
2887 /* it must be a LookupTable object, or nil */
2888 vm_val_t *v = G_stk->get(1);
2889 if (v->typ == VM_NIL)
2890 {
2891 /* nil, so there's no table - just discard the argument */
2892 G_stk->discard();
2893 }
2894 else
2895 {
2896 /* it's not nil, so it has to be a LookupTable object */
2897 if (!CVmObjLookupTable::is_lookup_table_obj(vmg_ v->val.obj))
2898 err_throw(VMERR_BAD_TYPE_BIF);
2899
2900 /* get the lookup table object */
2901 metatab = (CVmObjLookupTable *)vm_objp(vmg_ v->val.obj);
2902 }
2903 }
2904
2905 /* set up for network storage server access, if applicable */
2906 vm_rcdesc rc(vmg_ "saveGame", bif_table, 15, G_stk->get(0), argc);
2907 CVmNetFile *netfile = CVmNetFile::open(
2908 vmg_ filespec, &rc, NETF_WRITE | NETF_CREATE | NETF_TRUNC,
2909 OSFTT3SAV, "application/x-t3vm-state");
2910
2911 /* open the file and save the game */
2912 CVmFile *file = 0;
2913 err_try
2914 {
2915 /* validate file safety */
2916 CVmObjFile::check_safety_for_open(vmg_ netfile, VMOBJFILE_ACCESS_WRITE);
2917
2918 /* open the file */
2919 osfildef *fp = osfoprwtb(netfile->lclfname, OSFTT3SAV);
2920 if (fp == 0)
2921 err_throw(VMERR_CREATE_FILE);
2922
2923 /* set up the file writer */
2924 file = new CVmFile();
2925 file->set_file(fp, 0);
2926
2927 /* save the state */
2928 CVmSaveFile::save(vmg_ file, metatab);
2929
2930 /* close the file */
2931 delete file;
2932 file = 0;
2933 }
2934 err_catch_disc
2935 {
2936 /* close the file if it's still open */
2937 if (file != 0)
2938 delete file;
2939
2940 /* abandon the network file */
2941 if (netfile != 0)
2942 netfile->abandon(vmg0_);
2943
2944 /* rethrow the error */
2945 err_rethrow();
2946 }
2947 err_end;
2948
2949 /* close out the network file */
2950 netfile->close(vmg0_);
2951
2952 /* discard arguments */
2953 G_stk->discard(argc);
2954
2955 /* no return value */
2956 retval_nil(vmg0_);
2957 }
2958
2959 /*
2960 * restore
2961 */
2962 void CVmBifTADS::restore(VMG_ uint argc)
2963 {
2964 /* check arguments */
2965 check_argc(vmg_ argc, 1);
2966
2967 /* get the filename or spec */
2968 const vm_val_t *filespec = G_stk->get(0);
2969
2970 /* set up for network storage server access, if applicable */
2971 vm_rcdesc rc(vmg_ "restoreGame", bif_table, 16, G_stk->get(0), argc);
2972 CVmNetFile *netfile = CVmNetFile::open(
2973 vmg_ filespec, &rc, NETF_READ, OSFTT3SAV, "application/x-t3vm-state");
2974
2975 /* open the file and restore the game */
2976 CVmFile *file = 0;
2977 int err = 0;
2978 err_try
2979 {
2980 /* validate file safety */
2981 CVmObjFile::check_safety_for_open(vmg_ netfile, VMOBJFILE_ACCESS_READ);
2982
2983 /* open the file */
2984 osfildef *fp = osfoprb(netfile->lclfname, OSFTT3SAV);
2985 if (fp == 0)
2986 err_throw(VMERR_FILE_NOT_FOUND);
2987
2988 /* set up the file reader */
2989 file = new CVmFile(fp, 0);
2990
2991 /* restore the state; throw an exception on error */
2992 if ((err = CVmSaveFile::restore(vmg_ file)) != 0)
2993 err_throw(err);
2994 }
2995 err_finally
2996 {
2997 /* close our local file */
2998 if (file != 0)
2999 delete file;
3000
3001 /* close the network file */
3002 if (netfile != 0)
3003 netfile->close(vmg0_);
3004 }
3005 err_end;
3006
3007 /* discard arguments */
3008 G_stk->discard(argc);
3009
3010 /* no return value */
3011 retval_nil(vmg0_);
3012 }
3013
3014 /*
3015 * restart
3016 */
3017 void CVmBifTADS::restart(VMG_ uint argc)
3018 {
3019 /* check arguments */
3020 check_argc(vmg_ argc, 0);
3021
3022 /* reset the VM to the image file's initial state */
3023 CVmSaveFile::reset(vmg0_);
3024
3025 /* no return value */
3026 retval_nil(vmg0_);
3027 }
3028
3029
3030 /* ------------------------------------------------------------------------ */
3031 /*
3032 * Get the maximum value from a set of argument
3033 */
3034 void CVmBifTADS::get_max(VMG_ uint argc)
3035 {
3036 uint i;
3037 vm_val_t cur_max;
3038
3039 /* make sure we have at least one argument */
3040 if (argc < 1)
3041 err_throw(VMERR_WRONG_NUM_OF_ARGS);
3042
3043 /* start with the first argument as the presumptive maximum */
3044 cur_max = *G_stk->get(0);
3045
3046 /* if there's one list-like argument, get the max of the list elements */
3047 if (argc == 1 && cur_max.is_listlike(vmg0_))
3048 {
3049 /* get the list length */
3050 vm_val_t lst = cur_max;
3051 uint cnt = lst.ll_length(vmg0_);
3052
3053 /* if it's a zero-element list, it's an error */
3054 if (cnt == 0)
3055 err_throw(VMERR_BAD_VAL_BIF);
3056
3057 /* get the first element as the tentative maximum */
3058 lst.ll_index(vmg_ &cur_max, 1);
3059
3060 /* compare each additional list element */
3061 for (i = 2 ; i <= cnt ; ++i)
3062 {
3063 /* compare the current element and keep it if it's the highest */
3064 vm_val_t ele;
3065 lst.ll_index(vmg_ &ele, i);
3066 if (ele.compare_to(vmg_ &cur_max) > 0)
3067 cur_max = ele;
3068 }
3069 }
3070 else
3071 {
3072 /* compare each argument in turn */
3073 for (i = 1 ; i < argc ; ++i)
3074 {
3075 /*
3076 * compare this value to the maximum so far; if this value is
3077 * greater, it becomes the new maximum so far
3078 */
3079 if (G_stk->get(i)->compare_to(vmg_ &cur_max) > 0)
3080 cur_max = *G_stk->get(i);
3081 }
3082 }
3083
3084 /* discard the arguments */
3085 G_stk->discard(argc);
3086
3087 /* return the maximum value */
3088 retval(vmg_ &cur_max);
3089 }
3090
3091 /*
3092 * Get the minimum value from a set of argument
3093 */
3094 void CVmBifTADS::get_min(VMG_ uint argc)
3095 {
3096 uint i;
3097 vm_val_t cur_min;
3098
3099 /* make sure we have at least one argument */
3100 if (argc < 1)
3101 err_throw(VMERR_WRONG_NUM_OF_ARGS);
3102
3103 /* start with the first argument as the presumptive minimum */
3104 cur_min = *G_stk->get(0);
3105
3106 /* if there's one list-like argument, get the max of the list elements */
3107 if (argc == 1 && cur_min.is_listlike(vmg0_))
3108 {
3109 /* get the list length */
3110 vm_val_t lst = cur_min;
3111 uint cnt = lst.ll_length(vmg0_);
3112
3113 /* if it's a zero-element list, it's an error */
3114 if (cnt == 0)
3115 err_throw(VMERR_BAD_VAL_BIF);
3116
3117 /* get the first element as the tentative maximum */
3118 lst.ll_index(vmg_ &cur_min, 1);
3119
3120 /* compare each additional list element */
3121 for (i = 2 ; i <= cnt ; ++i)
3122 {
3123 /* compare the current element and keep it if it's the highest */
3124 vm_val_t ele;
3125 lst.ll_index(vmg_ &ele, i);
3126 if (ele.compare_to(vmg_ &cur_min) < 0)
3127 cur_min = ele;
3128 }
3129 }
3130 else
3131 {
3132 /* compare each argument in turn */
3133 for (i = 1 ; i < argc ; ++i)
3134 {
3135 /*
3136 * compare this value to the minimum so far; if this value is
3137 * less, it becomes the new minimum so far
3138 */
3139 if (G_stk->get(i)->compare_to(vmg_ &cur_min) < 0)
3140 cur_min = *G_stk->get(i);
3141 }
3142 }
3143
3144 /* discard the arguments */
3145 G_stk->discard(argc);
3146
3147 /* return the minimum value */
3148 retval(vmg_ &cur_min);
3149 }
3150
3151 /* ------------------------------------------------------------------------ */
3152 /*
3153 * makeString - construct a string by repeating a character; by
3154 * converting a unicode code point to a string; or by converting a list
3155 * of unicode code points to a string
3156 */
3157 void CVmBifTADS::make_string(VMG_ uint argc)
3158 {
3159 vm_val_t val;
3160 long rpt;
3161 vm_obj_id_t new_str_obj;
3162 CVmObjString *new_str;
3163 size_t new_str_len;
3164 char *new_strp;
3165 const char *strp = 0;
3166 int lst_len = -1;
3167 size_t i;
3168 utf8_ptr dst;
3169
3170 /* check arguments */
3171 check_argc_range(vmg_ argc, 1, 2);
3172
3173 /* get the base value */
3174 G_stk->pop(&val);
3175
3176 /* if there's a repeat count, get it */
3177 rpt = (argc >= 2 ? pop_long_val(vmg0_) : 1);
3178
3179 /* if the repeat count is less than zero, it's an error */
3180 if (rpt < 0)
3181 err_throw(VMERR_BAD_VAL_BIF);
3182
3183 /* leave the original value on the stack to protect it from GC */
3184 G_stk->push(&val);
3185
3186 /*
3187 * see what we have, and calculate how much space we'll need for the
3188 * result string
3189 */
3190 switch(val.typ)
3191 {
3192 case VM_LIST:
3193 /* it's a list of integers giving unicode character values */
3194 lst_len = val.ll_length(vmg0_);
3195
3196 do_list:
3197 /*
3198 * Run through the list and get the size of each character, so
3199 * we can determine how long the string will have to be.
3200 */
3201 for (new_str_len = 0, i = 1 ; (int)i <= lst_len ; ++i)
3202 {
3203 /* get this element */
3204 vm_val_t ele_val;
3205 val.ll_index(vmg_ &ele_val, i);
3206
3207 /* if it's not an integer, it's an error */
3208 if (ele_val.typ != VM_INT)
3209 err_throw(VMERR_INT_VAL_REQD);
3210
3211 /* add this character's byte size to the string size */
3212 new_str_len +=
3213 utf8_ptr::s_wchar_size((wchar_t)ele_val.val.intval);
3214 }
3215 break;
3216
3217 case VM_SSTRING:
3218 /* get the string pointer */
3219 strp = G_const_pool->get_ptr(val.val.ofs);
3220
3221 do_string:
3222 /*
3223 * it's a string - the output length is the same as the input
3224 * length
3225 */
3226 new_str_len = vmb_get_len(strp);
3227 break;
3228
3229 case VM_INT:
3230 /*
3231 * it's an integer giving a unicode character value - we just
3232 * need enough space to store this particular character
3233 */
3234 new_str_len = utf8_ptr::s_wchar_size((wchar_t)val.val.intval);
3235 break;
3236
3237 case VM_OBJ:
3238 /* check to see if it's a string */
3239 if ((strp = val.get_as_string(vmg0_)) != 0)
3240 goto do_string;
3241
3242 /* check to see if it's a list */
3243 if (val.is_listlike(vmg0_) && (lst_len = val.ll_length(vmg0_)) >= 0)
3244 goto do_list;
3245
3246 /* it's invalid */
3247 err_throw(VMERR_BAD_TYPE_BIF);
3248 break;
3249
3250 default:
3251 /* other types are invalid */
3252 err_throw(VMERR_BAD_TYPE_BIF);
3253 break;
3254 }
3255
3256 /*
3257 * if the length times the repeat count would be over the maximum
3258 * 16-bit string length, it's an error
3259 */
3260 if (new_str_len * rpt > 0xffffL - VMB_LEN)
3261 err_throw(VMERR_BAD_VAL_BIF);
3262
3263 /* multiply the length by the repeat count */
3264 new_str_len *= rpt;
3265
3266 /* allocate the string and gets its buffer */
3267 new_str_obj = CVmObjString::create(vmg_ FALSE, new_str_len);
3268 new_str = (CVmObjString *)vm_objp(vmg_ new_str_obj);
3269 new_strp = new_str->cons_get_buf();
3270
3271 /* set up the destination pointer */
3272 dst.set(new_strp);
3273
3274 /* run through the number of iterations requested */
3275 for ( ; rpt != 0 ; --rpt)
3276 {
3277 /* build one iteration of the string, according to the type */
3278 if (lst_len >= 0)
3279 {
3280 /* run through the list */
3281 for (i = 1 ; i <= (size_t)lst_len ; ++i)
3282 {
3283 /* get this element */
3284 vm_val_t ele_val;
3285 val.ll_index(vmg_ &ele_val, i);
3286
3287 /* add this character to the string */
3288 dst.setch((wchar_t)ele_val.val.intval);
3289 }
3290 }
3291 else if (strp != 0)
3292 {
3293 /* copy the string's contents into the output string */
3294 memcpy(dst.getptr(), strp + VMB_LEN, vmb_get_len(strp));
3295
3296 /* advance past the bytes we copied */
3297 dst.set(dst.getptr() + vmb_get_len(strp));
3298 }
3299 else
3300 {
3301 /* set this int value */
3302 dst.setch((wchar_t)val.val.intval);
3303 }
3304 }
3305
3306 /* return the new string */
3307 retval_obj(vmg_ new_str_obj);
3308
3309 /* discard the GC protection */
3310 G_stk->discard();
3311 }
3312
3313 /* ------------------------------------------------------------------------ */
3314 /*
3315 * makeList - construct a list by repeating a given value a given number of
3316 * times
3317 */
3318 void CVmBifTADS::make_list(VMG_ uint argc)
3319 {
3320 /* check arguments */
3321 check_argc_range(vmg_ argc, 1, 2);
3322
3323 /* get the value to use for each list element */
3324 vm_val_t val;
3325 G_stk->pop(&val);
3326
3327 /* if there's a repeat count, get it */
3328 long rpt = (argc >= 2 ? pop_long_val(vmg0_) : 1);
3329
3330 /* if the repeat count is less than zero, it's an error */
3331 if (rpt < 0)
3332 err_throw(VMERR_BAD_VAL_BIF);
3333
3334 /* leave the original value on the stack to protect it from GC */
3335 G_stk->push(&val);
3336
3337 /* allocate our return list */
3338 vm_obj_id_t lst_obj = CVmObjList::create(vmg_ FALSE, rpt);
3339 CVmObjList *lst = (CVmObjList *)vm_objp(vmg_ lst_obj);
3340
3341 /* fill in the list with the repeated value */
3342 for (int i = 0 ; i < rpt ; ++i)
3343 lst->cons_set_element(i, &val);
3344
3345 /* return the new list */
3346 retval_obj(vmg_ lst_obj);
3347
3348 /* discard the GC protection */
3349 G_stk->discard();
3350 }
3351
3352 /* ------------------------------------------------------------------------ */
3353 /*
3354 * getFuncParams
3355 */
3356 void CVmBifTADS::get_func_params(VMG_ uint argc)
3357 {
3358 /* check arguments */
3359 check_argc(vmg_ argc, 1);
3360
3361 /* set up a method header pointer for the function pointer argument */
3362 CVmFuncPtr hdr;
3363 if (!hdr.set(vmg_ G_stk->get(0)))
3364 err_throw(VMERR_FUNCPTR_VAL_REQD);
3365
3366 /*
3367 * Allocate our return list. We need three elements: [minArgs,
3368 * optionalArgs, isVarargs].
3369 */
3370 vm_obj_id_t lst_obj = CVmObjList::create(vmg_ FALSE, 3);
3371
3372 /* get the list object, properly cast */
3373 CVmObjList *lst = (CVmObjList *)vm_objp(vmg_ lst_obj);
3374
3375 /* set the minimum argument count */
3376 vm_val_t val;
3377 val.set_int(hdr.get_min_argc());
3378 lst->cons_set_element(0, &val);
3379
3380 /* set the optional argument count */
3381 val.set_int(hdr.get_opt_argc());
3382 lst->cons_set_element(1, &val);
3383
3384 /* set the varargs flag */
3385 val.set_logical(hdr.is_varargs());
3386 lst->cons_set_element(2, &val);
3387
3388 /* return the list */
3389 retval_obj(vmg_ lst_obj);
3390 }
3391
3392 /* ------------------------------------------------------------------------ */
3393 /*
3394 * sprintf
3395 */
3396
3397 /* bufprintf format string pointer */
3398 struct bpptr
3399 {
3400 bpptr(const char *p, size_t len)
3401 {
3402 this->p = p;
3403 this->len = len;
3404 }
3405
3406 bpptr(bpptr &src) { set(src); }
3407
3408 /* set from another pointer */
3409 void set(bpptr &src)
3410 {
3411 this->p = src.p;
3412 this->len = src.len;
3413 }
3414
3415 /* do we have more in our buffer? */
3416 int more() const { return len != 0; }
3417
3418 /* get the current character */
3419 char getch() const { return len != 0 ? *p : '\0'; }
3420
3421 /* get and skip the current character */
3422 char skipch()
3423 {
3424 if (len != 0)
3425 {
3426 char ch = *p;
3427 ++p, --len;
3428 return ch;
3429 }
3430 else
3431 return '\0';
3432 }
3433
3434 /*
3435 * match a character: if we match, return true and skip the character,
3436 * otherwise just return false
3437 */
3438 int match_skip(char ch)
3439 {
3440 if (getch() == ch)
3441 {
3442 inc();
3443 return TRUE;
3444 }
3445 else
3446 return FALSE;
3447 }
3448
3449 /* skip the current character */
3450 void inc()
3451 {
3452 if (len != 0)
3453 ++p, --len;
3454 }
3455
3456 /* get the next wide character */
3457 wchar_t getwch() const { return len != 0 ? utf8_ptr::s_getch(p) : 0; }
3458
3459 /* get and skip the next wide character */
3460 wchar_t skipwch()
3461 {
3462 wchar_t ch = getwch();
3463 incwch();
3464 return ch;
3465 }
3466
3467 /* skip the next wide character */
3468 void incwch()
3469 {
3470 if (len != 0)
3471 {
3472 size_t clen = utf8_ptr::s_charsize(*p);
3473 if (clen > len)
3474 clen = len;
3475 p += clen;
3476 len -= clen;
3477 }
3478 }
3479
3480 /* parse an integer value */
3481 int atoi()
3482 {
3483 int acc = 0;
3484 while (is_digit(getch()))
3485 {
3486 acc *= 10;
3487 acc += value_of_digit(skipch());
3488 }
3489 return acc;
3490 }
3491
3492 /* parse an integer value; return -1 if there's no integer here */
3493 int check_atoi() { return is_digit(getch()) ? atoi() : -1; }
3494
3495 /* current string pointer */
3496 const char *p;
3497
3498 /* remaining length in bytes */
3499 size_t len;
3500 };
3501
3502 /* format_int() flags */
3503 #define FI_UNSIGNED 0x0001
3504 #define FI_CAPS 0x0002
3505
3506 /* '%' formatting options */
3507 struct fmtopts
3508 {
3509 fmtopts()
3510 {
3511 sign = '\0';
3512 group = 0;
3513 prec = -1;
3514 width = -1;
3515 left_align = FALSE;
3516 pad = ' ';
3517 pound = FALSE;
3518 }
3519
3520 /*
3521 * sign character to show for positive numbers: '\0' to show nothing, '
3522 * ' to show a space, '+' to show a plus
3523 */
3524 char sign;
3525
3526 /* group charater, or '\0' if not grouping */
3527 wchar_t group;
3528
3529 /* width (%10d); -1 means no width spec */
3530 int width;
3531
3532 /* precision (%.10s); -1 means no precision spec */
3533 int prec;
3534
3535 /* true -> left align the value in its field; false -> right align */
3536 int left_align;
3537
3538 /* padding character; default is space */
3539 wchar_t pad;
3540
3541 /*
3542 * '#' flag: e E f g G -> always use a decimal point; g G -> keep
3543 * trailing zeros; x X o -> use 0x/0X/0 prefix for non-zero values
3544 */
3545 int pound;
3546 };
3547
3548 /* bufprintf output writer */
3549 struct bpwriter
3550 {
3551 bpwriter(VMG_ CVmObjString *str)
3552 {
3553 this->vmg = VMGLOB_ADDR;
3554 this->str = str;
3555 this->dst = str->cons_get_buf();
3556 }
3557
3558 /* close - set the final string length */
3559 void close()
3560 {
3561 VMGLOB_PTR(vmg);
3562 str->cons_shrink_buffer(vmg_ dst);
3563 }
3564
3565 /* write a character */
3566 void putch(char ch)
3567 {
3568 VMGLOB_PTR(vmg);
3569 dst = str->cons_append(vmg_ dst, &ch, 1, 64);
3570 }
3571
3572 /* write a UTF8 character */
3573 void putwch(wchar_t ch)
3574 {
3575 VMGLOB_PTR(vmg);
3576 dst = str->cons_append(vmg_ dst, ch, 64);
3577 }
3578
3579 /* write a UTF8 character multiple times */
3580 void putwch(wchar_t ch, int cnt)
3581 {
3582 while (cnt-- != 0)
3583 putwch(ch);
3584 }
3585
3586 /* write a string */
3587 void puts(const char *str) { puts(str, strlen(str)); }
3588 void puts(const char *str, size_t len)
3589 {
3590 VMGLOB_PTR(vmg);
3591 dst = this->str->cons_append(vmg_ dst, str, len, 64);
3592 }
3593
3594 /* format a string value */
3595 void format_string(VMG_ const vm_val_t *val, const fmtopts &opts)
3596 {
3597 /* if we don't have a string value, cast it to string */
3598 vm_val_t strval;
3599 val->cast_to_string(vmg_ &strval);
3600 G_stk->push(&strval);
3601
3602 /* get the string buffer and length */
3603 const char *str = strval.get_as_string(vmg0_);
3604 size_t bytes = vmb_get_len(str);
3605 str += VMB_LEN;
3606
3607 /* get the length of the string in characters */
3608 utf8_ptr p((char *)str);
3609 size_t chars = p.len(bytes);
3610
3611 /* If the string is longer than the precision, truncate it */
3612 if (opts.prec >= 0 && (int)chars > opts.prec)
3613 {
3614 /* limit the length (in both chars and bytes) to the precision */
3615 chars = opts.prec;
3616 bytes = p.bytelen(chars);
3617 }
3618
3619 /* write it out with the appropriate padding and alignment */
3620 format_with_padding(vmg_ str, bytes, chars, opts);
3621
3622 /* discard our gc protection */
3623 G_stk->discard();
3624 }
3625
3626 /* format a character value */
3627 void format_char(VMG_ const vm_val_t *val)
3628 {
3629 /* check what we have */
3630 const char *str = val->get_as_string(vmg0_);
3631 if (str != 0)
3632 {
3633 /* it's a string - show the first character */
3634 size_t len = vmb_get_len(str);
3635 str += VMB_LEN;
3636 if (len != 0)
3637 {
3638 /* write the first character */
3639 putwch(utf8_ptr::s_getch(str));
3640 }
3641 else
3642 {
3643 /* empty string - write a null character */
3644 putch((char)0);
3645 }
3646 }
3647 else
3648 {
3649 /* it's not a string - get the integer value */
3650 int i = val->cast_to_int(vmg0_);
3651
3652 /* make sure it's in range */
3653 if (i < 0 || i > 65535)
3654 err_throw(VMERR_NUM_OVERFLOW);
3655
3656 /* write the character value */
3657 putwch((wchar_t)i);
3658 }
3659 }
3660
3661 /* format an internal UTF-8 length+string, with padding and alignment */
3662 void format_with_padding(VMG_ const char *str, const fmtopts &opts)
3663 {
3664 /* figure the byte length and get the buffer */
3665 size_t bytes = vmb_get_len(str);
3666 str += VMB_LEN;
3667
3668 /* figure the character length */
3669 utf8_ptr p((char *)str);
3670 size_t chars = p.len(bytes);
3671
3672 /* write it out */
3673 format_with_padding(vmg_ str, bytes, chars, opts);
3674 }
3675
3676 /* format a UTF-8 string value, adding padding and alignment */
3677 void format_with_padding(VMG_ const char *str,
3678 size_t bytes, size_t chars,
3679 const fmtopts &opts)
3680 {
3681 /*
3682 * Figure the amount of padding: if the width is larger than the
3683 * string length (in characters), pad by the difference.
3684 */
3685 int npad = (opts.width > (int)chars ? opts.width - chars : 0);
3686
3687 /* if right-aligning, write the padding */
3688 if (!opts.left_align)
3689 putwch(opts.pad, npad);
3690
3691 /* write the string */
3692 puts(str, bytes);
3693
3694 /* if left-aligning, write the padding */
3695 if (opts.left_align)
3696 putwch(opts.pad, npad);
3697 }
3698
3699 /* format an integer value */
3700 void format_int(VMG_ const vm_val_t *val, int radix,
3701 const char *type_prefix,
3702 const fmtopts &opts, int flags = 0)
3703 {
3704 /* a stack buffer for conversions that can use it */
3705 char buf[256];
3706
3707 /* check the type */
3708 switch (val->typ)
3709 {
3710 case VM_NIL:
3711 /* format nil as zero */
3712 format_int(vmg_ "0", 1, type_prefix, opts, flags);
3713 break;
3714
3715 case VM_TRUE:
3716 /* format true as one */
3717 format_int(vmg_ "1", 1, type_prefix, opts, flags);
3718 break;
3719
3720 case VM_INT:
3721 {
3722 /* set flags - round to integer, unsigned if applicable */
3723 int cvtflags = TOSTR_ROUND;
3724 if ((flags & FI_UNSIGNED) != 0)
3725 cvtflags |= TOSTR_UNSIGNED;
3726
3727 /* get the basic string representation of the integer */
3728 const char *p = CVmObjString::cvt_int_to_str(
3729 buf, sizeof(buf), val->val.intval, radix, cvtflags);
3730
3731 /* apply our extra formatting to the basic string rep */
3732 format_int(vmg_ p + VMB_LEN, vmb_get_len(p),
3733 type_prefix, opts, flags);
3734 }
3735 break;
3736
3737 default:
3738 {
3739 /*
3740 * figure the string conversion flags: round to integer,
3741 * and use an unsigned interpretation if the format is
3742 * unsigned
3743 */
3744 int tsflags = TOSTR_ROUND;
3745 if (flags & FI_UNSIGNED)
3746 tsflags |= TOSTR_UNSIGNED;
3747
3748 /* cast the value to a numeric type */
3749 vm_val_t num;
3750 val->cast_to_num(vmg_ &num);
3751 G_stk->push(&num);
3752
3753 /* ...thence to string, to get a printable representation */
3754 vm_val_t str;
3755 const char *p = CVmObjString::cvt_to_str(
3756 vmg_ &str, buf, sizeof(buf), &num, radix, tsflags);
3757 G_stk->push(&str);
3758
3759 /* apply our extra formatting to the basic string rep */
3760 format_int(vmg_ p + VMB_LEN, vmb_get_len(p),
3761 type_prefix, opts, flags);
3762
3763 /* discard the GC protection */
3764 G_stk->discard(2);
3765 }
3766 break;
3767 }
3768 }
3769
3770 /*
3771 * Format an integer value for which we've generated a basic string
3772 * buffer value. This applies our extra formatting - padding, plus
3773 * sign, alignment, case conversion.
3774 */
3775 void format_int(VMG_ const char *p, size_t len,
3776 const char *type_prefix,
3777 const fmtopts &opts, int flags)
3778 {
3779 /* if they're trying to pawn off an empty string on us, use "0" */
3780 if (p == 0 || len == 0)
3781 p = "0", len = 1;
3782
3783 /* note if the value is all zeros */
3784 int zero = TRUE;
3785 const char *p2 = p;
3786 for (size_t i = 0 ; i < len ; ++i)
3787 {
3788 if (*p2 != '0')
3789 {
3790 zero = FALSE;
3791 break;
3792 }
3793 }
3794
3795 /*
3796 * get the number of digits: assume that the whole thing is digits
3797 * except for a leading minus sign
3798 */
3799 int digits = len;
3800 if (*p == '-')
3801 --digits;
3802
3803 /*
3804 * Figure the display width required. Start with the length of the
3805 * string. If we the "sign" option is set and we don't have a "-"
3806 * sign, add space for a "+" sign. If the "group" option is set,
3807 * add a comma for each group of three digits. If the '#' flag is
3808 * set, add the type prefix if the value is nonzero.
3809 */
3810 int dispwid = len;
3811 if (opts.sign != '\0' && *p != '-')
3812 dispwid += 1;
3813 if (opts.group != 0)
3814 dispwid += ((len - (*p == '-' ? 1 : 0)) - 1)/3;
3815 if (opts.pound && type_prefix != 0 && !zero)
3816 dispwid += strlen(type_prefix);
3817
3818 /*
3819 * If there's a precision setting, it means that we're to add
3820 * leading zeros to bring the number of digits up to the
3821 * precision.
3822 */
3823 if (digits < opts.prec)
3824 dispwid += opts.prec - digits;
3825
3826 /*
3827 * Figure the amount of padding. If there's an explicit width spec
3828 * in the options, and the display width is less than the width
3829 * spec, pad by the differene.
3830 */
3831 int padcnt = (opts.width > dispwid ? opts.width - dispwid : 0);
3832
3833 /* if they want right alignment, add padding characters before */
3834 if (!opts.left_align)
3835 putwch(opts.pad, padcnt);
3836
3837 /* add the + sign if needed */
3838 if (opts.sign && *p != '-')
3839 putch(opts.sign);
3840
3841 /* if there's a '-' sign, write it */
3842 if (*p == '-')
3843 putch(*p++), --len;
3844
3845 /* add the type prefix */
3846 if (opts.pound && type_prefix != 0 && !zero)
3847 puts(type_prefix);
3848
3849 /* add the leading zeros for the precision */
3850 for (int i = digits ; i < opts.prec ; ++i)
3851 putch('0');
3852
3853 /* write the digits, adding grouping commas and converting case */
3854 for (int dig = 0 ; len != 0 ; ++p, --len, ++dig)
3855 {
3856 /*
3857 * if this isn't the first digit, and we have a multiple of
3858 * three digits remaining, and we're using grouping, add the
3859 * group comma
3860 */
3861 if (opts.group != 0 && dig != 0 && len % 3 == 0)
3862 putwch(opts.group);
3863
3864 /* write this character, converting case as needed */
3865 if (is_digit(*p))
3866 putch(*p);
3867 else if ((flags & FI_CAPS) != 0)
3868 putch((char)toupper(*p));
3869 else
3870 putch((char)tolower(*p));
3871 }
3872
3873 /* if they want left alignment, add padding characters after */
3874 if (opts.left_align)
3875 putwch(opts.pad, padcnt);
3876 }
3877
3878 /* format a Roman numeral */
3879 void format_roman(VMG_ const vm_val_t *val, const fmtopts &opts, int flags)
3880 {
3881 char buf[40];
3882
3883 /* get the integer value */
3884 int32_t i = val->cast_to_int(vmg0_);
3885
3886 /*
3887 * use Roman numerals if it's in the range 1-4999, otherwise just
3888 * treat it like '%d'
3889 */
3890 if (i >= 1 && i <= 4999)
3891 {
3892 /* Roman numeral conversion chart */
3893 static const struct
3894 {
3895 const char *numeral;
3896 int val;
3897 } r[] =
3898 {
3899 { "m", 1000 },
3900 { "cm", 900 },
3901 { "d", 500 },
3902 { "cd", 400 },
3903 { "c", 100 },
3904 { "xc", 90 },
3905 { "l", 50 },
3906 { "x", 10 },
3907 { "ix", 9 },
3908 { "v", 5 },
3909 { "iv", 4 },
3910 { "i", 1 }
3911 };
3912
3913 /*
3914 * convert by repeatedly appending the highest-value Roman
3915 * numeral less than or equal to the number, deducting each
3916 * Roman numeral value from the remaining number balance until
3917 * we reach zero
3918 */
3919 for (int ri = 0 ; i != 0 && ri < countof(r) ; )
3920 {
3921 /* if this one fits, append this Roman numeral */
3922 if (r[ri].val <= i)
3923 {
3924 /* append this numeral, converting case if needed */
3925 for (const char *p = r[ri].numeral ; *p != 0 ; ++p)
3926 {
3927 if ((flags & FI_CAPS) != 0)
3928 putch((char)toupper(*p));
3929 else
3930 putch(*p);
3931 }
3932
3933 /* deduct its value from the remaining balance */
3934 i -= r[ri].val;
3935 }
3936 else
3937 {
3938 /* this numeral is too large - move on to the next one */
3939 ++ri;
3940 }
3941 }
3942 }
3943 else
3944 {
3945 t3sprintf(buf, sizeof(buf), "%ld", (long)i);
3946 format_int(vmg_ buf, strlen(buf), 0, opts, 0);
3947 }
3948 }
3949
3950 /* format a floating-point value */
3951 void format_float(VMG_ const vm_val_t *val, char type_spec,
3952 const fmtopts &opts)
3953 {
3954 /* a stack buffer for conversions that can use it */
3955 char buf[256];
3956
3957 /*
3958 * Use the precision specified, with a default of 6 digits; assume
3959 * that there's no maximum number of digits.
3960 */
3961 int prec = (opts.prec >= 0 ? opts.prec : 6);
3962 int maxdigs = -1;
3963
3964 /* figure the formatter flags */
3965 ulong flags = VMBN_FORMAT_LEADING_ZERO;
3966
3967 /* if the sign option is set, always show a sign */
3968 if (opts.sign == '+')
3969 flags |= VMBN_FORMAT_SIGN;
3970 else if (opts.sign == ' ')
3971 flags |= VMBN_FORMAT_POS_SPACE;
3972
3973 /*
3974 * if the '#' flag is set, always show a decimal point, and keep
3975 * trailing zeros with 'g' and 'G'
3976 */
3977 if (opts.pound)
3978 {
3979 flags |= VMBN_FORMAT_POINT;
3980 if (type_spec == 'g' || type_spec == 'G')
3981 flags |= VMBN_FORMAT_TRAILING_ZEROS;
3982 }
3983
3984 /* for 'E' or 'G', use capital 'E' for the exponent indicator */
3985 if (type_spec == 'E' || type_spec == 'G')
3986 flags |= VMBN_FORMAT_EXP_CAP;
3987
3988 /*
3989 * for 'e' or 'E', always use scientific notation, with a sign
3990 * symbol in the exponent value
3991 */
3992 if (type_spec == 'e' || type_spec == 'E')
3993 flags |= VMBN_FORMAT_EXP | VMBN_FORMAT_EXP_SIGN;
3994
3995 /* if the type code is 'g' or 'G', use "compact" notation */
3996 if (type_spec == 'g' || type_spec == 'G')
3997 {
3998 /* set the compact notation flag */
3999 flags |= VMBN_FORMAT_COMPACT | VMBN_FORMAT_EXP_SIGN;
4000
4001 /* the precision is the number of significant digits to show */
4002 flags |= VMBN_FORMAT_MAXSIG;
4003 maxdigs = prec;
4004 prec = -1;
4005 }
4006
4007 /* cast the value to a numeric type */
4008 vm_val_t num;
4009 val->cast_to_num(vmg_ &num);
4010 G_stk->push(&num);
4011
4012 /* check the type */
4013 switch (num.typ)
4014 {
4015 case VM_INT:
4016 {
4017 /* format the integer as though it were a float */
4018 const char *p = CVmObjBigNum::cvt_int_to_string_buf(
4019 buf, sizeof(buf), num.val.intval,
4020 maxdigs, -1, prec, 3, flags);
4021
4022 /* write it out, adding padding and alignment */
4023 format_with_padding(vmg_ p, opts);
4024 }
4025 break;
4026
4027 case VM_OBJ:
4028 /* if it's an object, it should be a BigNumber */
4029 if (CVmObjBigNum::is_bignum_obj(vmg_ num.val.obj))
4030 {
4031 /* get the BigNumber object */
4032 CVmObjBigNum *bn = (CVmObjBigNum *)vm_objp(vmg_ num.val.obj);
4033
4034 /* format the BigNumber */
4035 vm_val_t str;
4036 const char *p = bn->cvt_to_string_buf(
4037 vmg_ &str, buf, sizeof(buf),
4038 maxdigs, -1, prec, 3, flags);
4039 G_stk->push(&str);
4040
4041 /* write it out, adding padding and alignment */
4042 format_with_padding(vmg_ p, opts);
4043
4044 /* discard gc protection */
4045 G_stk->discard();
4046 }
4047 break;
4048
4049 default:
4050 break;
4051 }
4052
4053 /* discard our gc protection */
4054 G_stk->discard();
4055 }
4056
4057 /* result string */
4058 CVmObjString *str;
4059
4060 /* current write pointer */
4061 char *dst;
4062
4063 /* VM globals */
4064 vm_globals *vmg;
4065 };
4066
4067
4068 /*
4069 * Internal sprintf formatter. The arguments are on the stack in the usual
4070 * function call order, with the first argument at top of stack. We'll
4071 * allocate a new String object to hold the result.
4072 */
4073 static void tsprintf(VMG_ vm_val_t *retval, const char *fmtp, size_t fmtl,
4074 int arg0, int argc)
4075 {
4076 /* set up a format string reader */
4077 bpptr fmt(fmtp, fmtl);
4078
4079 /*
4080 * Create a string to hold the result. Use 150% the length of the
4081 * format string as a guess, with a minimum of 64 characters; we'll
4082 * expand this as needed as we go.
4083 */
4084 size_t init_len = (fmtl < 43 ? 64 : fmtl*3/2);
4085 retval->set_obj(CVmObjString::create(vmg_ FALSE, init_len));
4086
4087 /* push it for gc protection */
4088 G_stk->push(retval);
4089
4090 /* adjust the argument base for our additions */
4091 arg0 += 1;
4092
4093 /* set up an output writer */
4094 bpwriter dst(vmg_ (CVmObjString *)vm_objp(vmg_ retval->val.obj));
4095
4096 /* set up a nil value for missing arguments */
4097 vm_val_t nil_val;
4098 nil_val.set_nil();
4099
4100 /*
4101 * Scan the format string. The string is in utf8 format as always, but
4102 * our format codes are all plain ASCII characters, so a simple byte
4103 * scan is perfectly adequate.
4104 */
4105 for (int argpos = 1 ; fmt.more() ; )
4106 {
4107 /* check for format codes */
4108 char ch = fmt.skipch();
4109 if (ch == '%')
4110 {
4111 /* format specifier - remember where the '%' was */
4112 const char *pct = fmt.p - 1;
4113
4114 /* set up our initial default options */
4115 fmtopts opts;
4116 int argno = -1;
4117
4118 /* parse flags until we're out of them */
4119 for (int flags_done = FALSE ; !flags_done ; )
4120 {
4121 /* check the next character */
4122 switch (fmt.getch())
4123 {
4124 case '[':
4125 /* argument number specifier - "[digits]" */
4126 fmt.inc();
4127 argno = fmt.atoi();
4128 fmt.match_skip(']');
4129 break;
4130
4131 case '+':
4132 /* note the sign specifier */
4133 opts.sign = '+';
4134 fmt.inc();
4135 break;
4136
4137 case ' ':
4138 /* note the blank-for-plus specifier */
4139 opts.sign = ' ';
4140 fmt.inc();
4141 break;
4142
4143 case ',':
4144 /* note the group specifier */
4145 opts.group = ',';
4146 fmt.inc();
4147 break;
4148
4149 case '-':
4150 /* note the left-alignment specifier */
4151 opts.left_align = TRUE;
4152 fmt.inc();
4153 break;
4154
4155 case '_':
4156 /* padding spec - the next charater is the pad char */
4157 fmt.inc();
4158 opts.pad = fmt.skipwch();
4159 break;
4160
4161 case '#':
4162 /* pound flag - special flag per type */
4163 opts.pound = TRUE;
4164 fmt.inc();
4165 break;
4166
4167 default:
4168 /* it's not an option flag, so we're done with flags */
4169 flags_done = TRUE;
4170 break;
4171 }
4172 }
4173
4174 /*
4175 * Next comes the width, but there's one more flag character
4176 * that has a special position just before the width: '0', to
4177 * specify leading zero padding.
4178 */
4179 if (fmt.match_skip('0'))
4180 {
4181 /* obey this only if we're in right-align mode */
4182 if (!opts.left_align)
4183 opts.pad = '0';
4184 }
4185
4186 /* check for a width specifier */
4187 opts.width = fmt.check_atoi();
4188
4189 /* check for a precision specifier */
4190 if (fmt.match_skip('.'))
4191 opts.prec = fmt.atoi();
4192
4193 /* we're at the type specifier */
4194 char type_spec = fmt.skipch();
4195
4196 /* presume we'll use an argument */
4197 int used_arg = TRUE;
4198
4199 /* retrieve the current argument value */
4200 int argi = (argno > 0 ? argno : argpos);
4201 const vm_val_t *val =
4202 (argi <= argc ? G_stk->get(arg0 + argi - 1) : &nil_val);
4203
4204 /* apply the substitution based on the type */
4205 switch (type_spec)
4206 {
4207 case '%':
4208 /* literal % - copy it */
4209 dst.putch('%');
4210
4211 /* this doesn't use an argument */
4212 used_arg = FALSE;
4213 break;
4214
4215 case 'b':
4216 /* number -> binary integer */
4217 dst.format_int(vmg_ val, 2, 0, opts, FI_UNSIGNED);
4218 break;
4219
4220 case 'c':
4221 /* number -> Unicode character */
4222 dst.format_char(vmg_ val);
4223 break;
4224
4225 case 'd':
4226 /* number -> decimal integer */
4227 dst.format_int(vmg_ val, 10, 0, opts);
4228 break;
4229
4230 case 'r':
4231 /* number -> roman numeral (lowercase) */
4232 dst.format_roman(vmg_ val, opts, 0);
4233 break;
4234
4235 case 'R':
4236 /* number -> roman numeral (uppercase) */
4237 dst.format_roman(vmg_ val, opts, FI_CAPS);
4238 break;
4239
4240 case 'u':
4241 /* number -> decimal integer, unsigned interpretation */
4242 dst.format_int(vmg_ val, 10, 0, opts, FI_UNSIGNED);
4243 break;
4244
4245 case 'e':
4246 case 'E':
4247 case 'f':
4248 case 'g':
4249 case 'G':
4250 /* number -> floating point */
4251 dst.format_float(vmg_ val, type_spec, opts);
4252 break;
4253
4254 case 'o':
4255 /* number -> octal integer */
4256 dst.format_int(vmg_ val, 8, "0", opts, FI_UNSIGNED);
4257 break;
4258
4259 case 's':
4260 /* string */
4261 dst.format_string(vmg_ val, opts);
4262 break;
4263
4264 case 'x':
4265 /* number -> hex integer, lowercase letters */
4266 dst.format_int(vmg_ val, 16, "0x", opts, FI_UNSIGNED);
4267 break;
4268
4269 case 'X':
4270 /* number -> hex integer, uppercase letters */
4271 dst.format_int(vmg_ val, 16, "0X", opts,
4272 FI_UNSIGNED | FI_CAPS);
4273 break;
4274
4275 default:
4276 /* anything else is invalid - just copy the source % string */
4277 dst.puts(pct, fmt.p - pct);
4278
4279 /* we didn't use an argument after all */
4280 used_arg = FALSE;
4281 break;
4282 }
4283
4284 /* if we used a positional argument, count it */
4285 if (used_arg && argno < 0)
4286 ++argpos;
4287 }
4288 else
4289 {
4290 /* just copy this byte verbatim */
4291 dst.putch(ch);
4292 }
4293 }
4294
4295 /* set the final result string length */
4296 dst.close();
4297
4298 /* done with our gc protection */
4299 G_stk->discard();
4300 }
4301
4302 /*
4303 * sprintf
4304 */
4305 void CVmBifTADS::sprintf(VMG_ uint argc)
4306 {
4307 /* we need at least one argument */
4308 if (argc < 1)
4309 err_throw(VMERR_WRONG_NUM_OF_ARGS);
4310
4311 /* get the format string */
4312 const char *fmt = G_stk->get(0)->get_as_string(vmg0_);
4313 if (fmt == 0)
4314 err_throw(VMERR_STRING_VAL_REQD);
4315
4316 /* get the length and string buffer */
4317 size_t fmtl = vmb_get_len(fmt);
4318 fmt += VMB_LEN;
4319
4320 /* do the sprintf */
4321 vm_val_t retv;
4322 tsprintf(vmg_ &retv, fmt, fmtl, 1, argc - 1);
4323
4324 /* return the new string */
4325 retval(vmg_ &retv);
4326
4327 /* discard arguments */
4328 G_stk->discard(argc);
4329 }
4330
4331 /* ------------------------------------------------------------------------ */
4332 /*
4333 * abs() - absolute value
4334 */
4335 void CVmBifTADS::get_abs(VMG_ uint argc)
4336 {
4337 /* we need exactly one argument */
4338 if (argc != 1)
4339 err_throw(VMERR_WRONG_NUM_OF_ARGS);
4340
4341 /* check the argument type */
4342 switch (G_stk->get(0)->typ)
4343 {
4344 case VM_INT:
4345 /* integer */
4346 {
4347 /* get the integer */
4348 int32_t i = G_stk->get(0)->val.intval;
4349
4350 /* if it's negative, negate it */
4351 if (i < 0)
4352 i = -i;
4353
4354 /* return the result */
4355 retval_int(vmg_ i);
4356 }
4357 break;
4358
4359 case VM_OBJ:
4360 /* object */
4361 {
4362 /* try a BigNumber cast */
4363 CVmObjBigNum *b = vm_val_cast(CVmObjBigNum, G_stk->get(0));
4364 if (b != 0)
4365 {
4366 /* get the absolute value of the BigNumber */
4367 b->abs_val(vmg_ G_interpreter->get_r0(),
4368 G_stk->get(0)->val.obj);
4369 }
4370 else
4371 {
4372 /* invalid type */
4373 err_throw(VMERR_BAD_TYPE_BIF);
4374 }
4375 }
4376 break;
4377
4378 default:
4379 err_throw(VMERR_BAD_TYPE_BIF);
4380 }
4381
4382 /* discard arguments */
4383 G_stk->discard(argc);
4384 }
4385
4386 /* ------------------------------------------------------------------------ */
4387 /*
4388 * sgn() - sign
4389 */
4390 void CVmBifTADS::get_sgn(VMG_ uint argc)
4391 {
4392 /* we need exactly one argument */
4393 if (argc != 1)
4394 err_throw(VMERR_WRONG_NUM_OF_ARGS);
4395
4396 /* check the argument type */
4397 switch (G_stk->get(0)->typ)
4398 {
4399 case VM_INT:
4400 /* integer */
4401 {
4402 /* get the integer */
4403 int32_t i = G_stk->get(0)->val.intval;
4404
4405 /* compute the sgn value */
4406 retval_int(vmg_ i < 0 ? -1 : i == 0 ? 0 : 1);
4407 }
4408 break;
4409
4410 case VM_OBJ:
4411 /* object */
4412 {
4413 /* try a BigNumber cast */
4414 CVmObjBigNum *b = vm_val_cast(CVmObjBigNum, G_stk->get(0));
4415 if (b != 0)
4416 {
4417 /* compute the sgn value */
4418 b->sgn_val(vmg_ G_interpreter->get_r0(),
4419 G_stk->get(0)->val.obj);
4420 }
4421 else
4422 {
4423 /* invalid type */
4424 err_throw(VMERR_BAD_TYPE_BIF);
4425 }
4426 }
4427 break;
4428
4429 default:
4430 err_throw(VMERR_BAD_TYPE_BIF);
4431 }
4432
4433 /* discard arguments */
4434 G_stk->discard(argc);
4435 }
4436
4437 /* ------------------------------------------------------------------------ */
4438 /*
4439 * concat()
4440 */
4441 void CVmBifTADS::concat(VMG_ uint argc)
4442 {
4443 /*
4444 * First, run through the arguments. Convert each one that's not
4445 * already a string to a string, and count up the lengths.
4446 */
4447 size_t len = 0;
4448 for (uint i = 0 ; i < argc ; ++i)
4449 {
4450 /* cast this value to a string */
4451 vm_val_t newval;
4452 const char *str = G_stk->get(i)->cast_to_string(vmg_ &newval);
4453
4454 /* add its length */
4455 len += vmb_get_len(str);
4456
4457 /* replace it in the stack, in case we did a conversion */
4458 *G_stk->get(i) = newval;
4459 }
4460
4461 /* allocate the result string */
4462 vm_obj_id_t retobj = CVmObjString::create(vmg_ FALSE, len);
4463 CVmObjString *retstr = vm_objid_cast(CVmObjString, retobj);
4464
4465 /* get its construction buffer */
4466 char *dst = retstr->cons_get_buf();
4467
4468 /* run through the arguments again, copying them into the result buffer */
4469 for (uint i = 0 ; i < argc ; ++i)
4470 {
4471 /* get this value as a string (it's already been cast) */
4472 const char *src = G_stk->get(i)->get_as_string(vmg0_);
4473
4474 /* parse and skip the length prefix */
4475 size_t len = vmb_get_len(src);
4476 src += VMB_LEN;
4477
4478 /* add the string to the output buffer */
4479 memcpy(dst, src, len);
4480 dst += len;
4481 }
4482
4483 /* return the result string */
4484 retval_obj(vmg_ retobj);
4485
4486 /* discard arguments */
4487 G_stk->discard(argc);
4488 }
4489