-
Notifications
You must be signed in to change notification settings - Fork 17
/
vmbiftad.cpp
4489 lines (3843 loc) · 131 KB
/
vmbiftad.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifdef RCSID
static char RCSid[] =
"$Header: d:/cvsroot/tads/tads3/VMBIFTAD.CPP,v 1.3 1999/07/11 00:46:58 MJRoberts Exp $";
#endif
/*
* Copyright (c) 1999, 2002 Michael J. Roberts. All Rights Reserved.
*
* Please see the accompanying license file, LICENSE.TXT, for information
* on using and copying this software.
*/
/*
Name
vmbiftad.cpp - TADS built-in function set for T3 VM
Function
Notes
Modified
04/05/99 MJRoberts - Creation
*/
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "t3std.h"
#include "os.h"
#include "utf8.h"
#include "vmuni.h"
#include "vmbiftad.h"
#include "vmstack.h"
#include "vmerr.h"
#include "vmerrnum.h"
#include "vmglob.h"
#include "vmpool.h"
#include "vmobj.h"
#include "vmstr.h"
#include "vmlst.h"
#include "vmrun.h"
#include "vmregex.h"
#include "vmundo.h"
#include "vmfile.h"
#include "vmsave.h"
#include "vmbignum.h"
#include "vmfunc.h"
#include "vmpat.h"
#include "vmtobj.h"
#include "vmimport.h"
#include "vmpredef.h"
#include "vmlookup.h"
#include "vmfilobj.h"
#include "vmnetfil.h"
#include "vmbytarr.h"
#include "vmcrc.h"
#include "vmfindrep.h"
/* ------------------------------------------------------------------------ */
/*
* Initialize the TADS intrinsics global state
*/
CVmBifTADSGlobals::CVmBifTADSGlobals(VMG0_)
{
/* allocate our regular expression parser */
rex_parser = new CRegexParser();
rex_searcher = new CRegexSearcherSimple(rex_parser);
/*
* Allocate a global variable to hold the most recent regular
* expression search string. We need this in a global so that the last
* search string is always protected from garbage collection; we must
* keep the string because we might need it to extract a group-match
* substring.
*/
last_rex_str = G_obj_table->create_global_var();
/* ISAAC is the default RNG */
rng_id = VMBT_RNGID_ISAAC;
/*
* Set the random number seed to a fixed starting value (this value
* is arbitrary; we chose it by throwing dice). If the program
* wants another sequence, it can manually change this by calling
* the randomize() intrinsic in our function set, which seeds the
* generator with an OS-dependent starting value (usually based on
* the system's real-time clock, to ensure that each run will use a
* different starting value).
*/
lcg_rand_seed = 024136543305;
/* create the ISAAC context structure */
isaac_ctx = (struct isaacctx *)t3malloc(sizeof(struct isaacctx));
/* initialize with a fixed seed vector */
isaac_init(isaac_ctx, FALSE);
/* create the Mersenne Twister object */
mt_ctx = new CVmMT19937();
}
/*
* delete the TADS intrinsics global state
*/
CVmBifTADSGlobals::~CVmBifTADSGlobals()
{
/* delete our regular expression searcher and parser */
delete rex_searcher;
delete rex_parser;
/*
* note that we leave our last_rex_str global variable undeleted here,
* as we don't have access to G_obj_table (as there's no VMG_ to a
* destructor); this is okay, since the object table will take care of
* deleting the variable for us when the object table itself is deleted
*/
/* delete the ISAAC context */
t3free(isaac_ctx);
/* delete the Mersenne Twister context */
delete mt_ctx;
}
/* ------------------------------------------------------------------------ */
/*
* datatype - get the datatype of a given value
*/
void CVmBifTADS::datatype(VMG_ uint argc)
{
vm_val_t val;
vm_val_t retval;
/* check arguments */
check_argc(vmg_ argc, 1);
/* pop the value */
G_stk->pop(&val);
/* return the appropriate value for this type */
retval.set_datatype(vmg_ &val);
retval_int(vmg_ retval.val.intval);
}
/* ------------------------------------------------------------------------ */
/*
* getarg - get the given argument to the current procedure
*/
void CVmBifTADS::getarg(VMG_ uint argc)
{
int idx;
/* check arguments */
check_argc(vmg_ argc, 1);
/* get the argument index value */
idx = pop_int_val(vmg0_);
/* if the argument index is out of range, throw an error */
if (idx < 1 || idx > G_interpreter->get_cur_argc(vmg0_))
err_throw(VMERR_BAD_VAL_BIF);
/* return the parameter value */
*G_interpreter->get_r0() = *G_interpreter->get_param(vmg_ idx - 1);
}
/* ------------------------------------------------------------------------ */
/*
* firstobj - get the first object instance
*/
void CVmBifTADS::firstobj(VMG_ uint argc)
{
/* check arguments */
check_argc_range(vmg_ argc, 0, 2);
/* enumerate objects starting with object 1 in the master object table */
enum_objects(vmg_ argc, (vm_obj_id_t)1);
}
/*
* nextobj - get the next object instance after a given object
*/
void CVmBifTADS::nextobj(VMG_ uint argc)
{
vm_val_t val;
vm_obj_id_t prv_obj;
/* check arguments */
check_argc_range(vmg_ argc, 1, 3);
/* get the previous object */
G_interpreter->pop_obj(vmg_ &val);
prv_obj = val.val.obj;
/*
* Enumerate objects starting with the next object in the master
* object table after the given object. Reduce the argument count by
* one, since we've removed the preceding object.
*/
enum_objects(vmg_ argc - 1, prv_obj + 1);
}
/* enum_objects flags */
#define VMBIFTADS_ENUM_INSTANCES 0x0001
#define VMBIFTADS_ENUM_CLASSES 0x0002
/*
* Common handler for firstobj/nextobj object iteration
*/
void CVmBifTADS::enum_objects(VMG_ uint argc, vm_obj_id_t start_obj)
{
vm_val_t val;
vm_obj_id_t sc;
vm_obj_id_t obj;
unsigned long flags;
/* presume no superclass filter will be specified */
sc = VM_INVALID_OBJ;
/* presume we're enumerating instances only */
flags = VMBIFTADS_ENUM_INSTANCES;
/*
* check arguments - we can optionally have two more arguments: a
* superclass whose instances/subclasses we are to enumerate, and an
* integer giving flag bits
*/
if (argc == 2)
{
/* pop the object */
G_interpreter->pop_obj(vmg_ &val);
sc = val.val.obj;
/* pop the flags */
flags = pop_long_val(vmg0_);
}
else if (argc == 1)
{
/* check to see if it's an object or the flags integer */
switch (G_stk->get(0)->typ)
{
case VM_INT:
/* it's the flags */
flags = pop_long_val(vmg0_);
break;
case VM_OBJ:
/* it's the superclass filter */
G_interpreter->pop_obj(vmg_ &val);
sc = val.val.obj;
break;
default:
/* invalid argument type */
err_throw(VMERR_BAD_TYPE_BIF);
}
}
/* presume we won't find anything */
retval_nil(vmg0_);
/*
* starting with the given object, scan objects until we find one
* that's valid and matches our superclass, if one was provided
*/
for (obj = start_obj ; obj < G_obj_table->get_max_used_obj_id() ; ++obj)
{
/*
* If it's valid, and it's not an intrinsic class modifier object,
* consider it further. Skip intrinsic class modifiers, since
* they're not really separate objects; they're really part of the
* intrinsic class they modify, and all of the properties and
* methods of a modifier object are reachable through the base
* intrinsic class.
*/
if (G_obj_table->is_obj_id_valid(obj)
&& !CVmObjIntClsMod::is_intcls_mod_obj(vmg_ obj))
{
/*
* if it's a class, skip it if the flags indicate classes are
* not wanted; if it's an instance, skip it if the flags
* indicate that instances are not wanted
*/
if (vm_objp(vmg_ obj)->is_class_object(vmg_ obj))
{
/* it's a class - skip it if classes are not wanted */
if ((flags & VMBIFTADS_ENUM_CLASSES) == 0)
continue;
}
else
{
/* it's an instance - skip it if instances are not wanted */
if ((flags & VMBIFTADS_ENUM_INSTANCES) == 0)
continue;
}
/*
* if a superclass was specified, and it matches, we have a
* winner
*/
if (sc != VM_INVALID_OBJ)
{
/* if the object matches, return it */
if (vm_objp(vmg_ obj)->is_instance_of(vmg_ sc))
{
retval_obj(vmg_ obj);
break;
}
}
else
{
/*
* We're enumerating all objects - but skip List and String
* object, as we expose these as special types.
*/
if (vm_objp(vmg_ obj)->get_as_list() == 0
&& vm_objp(vmg_ obj)->get_as_string(vmg0_) == 0)
{
retval_obj(vmg_ obj);
break;
}
}
}
}
}
/* ------------------------------------------------------------------------ */
/*
* Abstract RNG algorithm interface
*/
class IVmBifTadsRNG
{
public:
virtual ~IVmBifTadsRNG() { }
/* get the next random number */
virtual uint32_t rand() = 0;
/* seed the generator from random data */
virtual void seed_random() = 0;
/* seed from an int */
virtual void seed_int(int32_t i)
{
/* by default, turn this into a string and seed with the string */
char buf[40];
oswp4(buf, i);
t3sprintf(buf+4, sizeof(buf)-4, "%ld", (long)i);
seed_str(buf, 4 + strlen(buf+4));
}
/* seed from a string */
virtual void seed_str(const char *str, size_t len)
{
/* by default, hash the string to an int and seed with the int */
CVmCRC32 crc;
crc.scan_bytes(str, len);
seed_int((int32_t)crc.get_crc_val());
}
/* get the state into a ByteArray object */
void get_state(VMG_ vm_val_t *val)
{
size_t len = get_state_size();
if (len == 0)
{
/* simple int32_t state */
val->set_int(get_state_int());
}
else
{
/* allocate a buffer */
char *buf = new char[len];
/* make sure we delete the allocated buffer */
err_try
{
/* get the state into our buffer */
get_state_buf(buf);
/* create a ByteArray from the state vector */
val->set_obj(CVmObjByteArray::create_from_bytes(
vmg_ FALSE, buf, len));
}
err_finally
{
/* done with the buffer */
delete [] buf;
}
err_end;
}
}
/* put the state from a ByteArray object */
void put_state(VMG_ vm_val_t *val)
{
/* determine what to do based on the state length */
size_t len = get_state_size();
if (len == 0)
{
/* simple int32_t state */
put_state_int(val->num_to_int(vmg0_));
}
else
{
/* retrieve the ByteArray object */
CVmObjByteArray *barr = vm_val_cast(CVmObjByteArray, val);
/* check that it matches the expected state buffer size */
unsigned long cnt = barr->get_element_count();
if (cnt != len)
err_throw(VMERR_BAD_VAL_BIF);
/* retrieve the bytes and restore the state */
char *buf = new char[len];
err_try
{
/* retrieve the bytes */
barr->copy_to_buf((unsigned char *)buf, 1, len);
/* restore the state */
put_state_buf(buf);
}
err_finally
{
delete [] buf;
}
err_end;
}
}
protected:
/*
* Get the size of the state vector, in bytes. Return 0 if we can
* store the state in an int32_t.
*/
virtual size_t get_state_size() = 0;
/* get/put state as an int32_t */
virtual int32_t get_state_int() = 0;
virtual void put_state_int(int32_t i) = 0;
/* save/restore current state vector to/from a buffer */
virtual void get_state_buf(char *buf) = 0;
virtual void put_state_buf(const char *buf) = 0;
};
/* ------------------------------------------------------------------------ */
/*
* ISAAC random number generator
*/
class vmbt_isaac_ifc: public IVmBifTadsRNG
{
public:
vmbt_isaac_ifc(VMG0_) { ctx = G_bif_tads_globals->isaac_ctx; }
isaacctx *ctx;
virtual uint32_t rand() { return isaac_rand(ctx); }
/* seed from random data */
virtual void seed_random()
{
/* generate random bytes into the ISAAC rsl array */
os_gen_rand_bytes((unsigned char *)ctx->rsl, sizeof(ctx->rsl));
/* initialize from the rsl array */
isaac_init(ctx, TRUE);
}
/* seed from a string value */
virtual void seed_str(const char *str, size_t len)
{
/*
* Copy the string value into the rsl array; copy as much as will
* fit, and zero the rest. (The point here is to be deterministic,
* so we want this to be the same every time with a given seed - we
* don't want to include random data left behind from previous
* iterations.)
*/
if (len > sizeof(ctx->rsl))
len = sizeof(ctx->rsl);
memset(ctx->rsl, 0, sizeof(ctx->rsl));
memcpy(ctx->rsl, str, len);
/* initialize with the rsl data */
isaac_init(ctx, TRUE);
}
virtual int32_t get_state_int() { return 0; }
virtual void put_state_int(int32_t) { }
virtual size_t get_state_size() { return isaac_get_state(ctx, 0); }
virtual void get_state_buf(char *buf) { isaac_get_state(ctx, buf); }
virtual void put_state_buf(const char *buf) { isaac_set_state(ctx, buf); }
};
/* ------------------------------------------------------------------------ */
/*
* Linear Congruential Random-Number Generator. This generator uses an
* algorithm from Knuth, The Art of Computer Programming, Volume 2, p.
* 170, with parameters chosen from the same book for their good
* statistical properties and efficiency on 32-bit hardware.
*/
class vmbt_lcg_ifc: public IVmBifTadsRNG
{
public:
vmbt_lcg_ifc(VMG0_) { seedp = &G_bif_tads_globals->lcg_rand_seed; }
virtual uint32_t rand()
{
const uint32_t a = 1664525L;
const uint32_t c = 1;
/*
* Generate the next random value using the linear congruential
* method described in Knuth, The Art of Computer Programming,
* volume 2, p170.
*
* Use 2^32 as m, hence (n mod m) == (n & 0xFFFFFFFF). This is
* efficient and is well-suited to 32-bit machines, works fine on
* larger machines, and will even work on 16-bit machines as long
* as the compiler can provide us with 32-bit arithmetic (which we
* assume extensively elsewhere anyway).
*
* We use a = 1664525, a multiplier which has very good results
* with the Spectral Test (see Knuth p102) with our choice of m.
*
* Use c = 1, since this trivially satisfies Knuth's requirements
* about common factors.
*
* Note that the result of the multiplication might overflow a
* 32-bit ulong for values of lcg_rand_seed that are not small.
* This doesn't matter, since if it does, the machine will
* naturally truncate high-order bits to yield the result mod 2^32.
* So, on a 32-bit machine, the (&0xFFFFFFFF) part is superfluous,
* but it's harmless and is needed for machines with a larger word
* size.
*/
*seedp = (int32_t)(((a * (uint32_t)*seedp) + c) & 0xFFFFFFFF);
return (uint32_t)*seedp;
}
virtual void seed_random()
{
long l;
os_rand(&l);
*seedp = (int32_t)l;
}
virtual void seed_int(int32_t i)
{
*seedp = i;
}
virtual int32_t get_state_int() { return *seedp; }
virtual void put_state_int(int32_t i) { *seedp = i; }
virtual size_t get_state_size() { return 0; }
virtual void get_state_buf(char *) { }
virtual void put_state_buf(const char *) { }
int32_t *seedp;
};
/* ------------------------------------------------------------------------ */
/*
* Bit-shift generator. This is from Knuth, The Art of Computer
* Programming, volume 2. This generator is designed to produce random
* strings of bits and isn't suitable for use as a general-purpose RNG.
*
* Linear congruential generators aren't ideal for generating random bits;
* their statistical properties are better suited for generating values
* over a full integer range. This generator is specially designed to
* produce random bits, so it could be a useful complement to an LCG RNG.
*
* Since this isn't a good general RNG, we don't currently enable it.
* We're keeping the code here, ifdef'd out, in case we decide to enable it
* in the future - which seems really unlikely, since ISAAC seems to be
* good at generating both full-range integers and random bits, leaving
* little reason to have a dedicated random bit generator.
*/
#ifdef VMBIFTADS_RNG_BITSHIFT
static uint32_t bits_rng_next(VMG0_)
{
int top_bit = (G_bif_tads_globals->bits_rand_seed & 0x8000000);
G_bif_tads_globals->bits_rand_seed <<= 1;
if (top_bit)
G_bif_tads_globals->bits_rand_seed ^= 035604231625;
return G_bif_tads_globals->bits_rand_seed & 1;
}
#endif /* VMBIFTADS_RNG_BITSHIFT */
/* ------------------------------------------------------------------------ */
/*
* Mersenne Twister MT19937 RNG algorithm
*/
class vmbt_mt_ifc: public IVmBifTadsRNG
{
public:
vmbt_mt_ifc(VMG0_) { mt = G_bif_tads_globals->mt_ctx; }
CVmMT19937 *mt;
virtual uint32_t rand() { return mt->rand(); }
virtual void seed_random() { mt->seed_random(); }
virtual void seed_int(int32_t i) { mt->seed(i); }
virtual void seed_str(const char *str, size_t len) { mt->seed(str, len); }
virtual int32_t get_state_int() { return 0; }
virtual void put_state_int(int32_t i) { }
virtual size_t get_state_size() { return mt->get_state_size(); }
virtual void get_state_buf(char *buf) { mt->get_state(buf); }
virtual void put_state_buf(const char *buf) { mt->put_state(buf); }
};
/* ------------------------------------------------------------------------ */
/*
* RNG interface selector. This sets up each type of RNG interface, and
* returns the one for the given ID. This object can be constructed on the
* stack for minimal memory management hassle.
*/
class CVmRNGSelector
{
public:
CVmRNGSelector(VMG0_)
: isaac(vmg0_), lcg(vmg0_), mt(vmg0_) { }
IVmBifTadsRNG *get(int id)
{
switch (id)
{
case VMBT_RNGID_ISAAC:
return &isaac;
case VMBT_RNGID_LCG:
return &lcg;
case VMBT_RNGID_MT19937:
return &mt;
default:
err_throw(VMERR_BAD_VAL_BIF);
AFTER_ERR_THROW(return 0;)
}
}
vmbt_isaac_ifc isaac;
vmbt_lcg_ifc lcg;
vmbt_mt_ifc mt;
};
/* ------------------------------------------------------------------------ */
/*
* randomize - seed the random number generator. This has several formats:
*
*. randomize() - select the default RNG (ISAAC) and initialize it
*. with random seed data.
*
*. randomize(nil) - retrieve the current state of the random number
*. generator. Returns a list: [id, state], where 'id'
*. is the generator ID, and 'state' is an opaque value
*. representing the generator's internal state.
*
*. randomize([state]) - restores the generator and internal state
*. returned from a previous call to randomize(nil).
*
*. randomize(id) - select the RNG identified by 'id'.
*
*. randomize(id, nil) - select the given RNG, and initialize it with
*. random seed data.
*
*. randomize(id, val) - select the given RNG, and initialize it with
*. the given fixed seed data. The seed can be provided
*. as an integer or string value.
*/
void CVmBifTADS::randomize(VMG_ uint argc)
{
/* check arguments */
check_argc_range(vmg_ argc, 0, 2);
if (argc == 0)
{
/*
* No arguments - select the default random number generator
* (ISAAC) and initialize it with random seed data.
*
* Load the ISAAC initialization vector with some truly random data
* from the operating system.
*/
G_bif_tads_globals->rng_id = VMBT_RNGID_ISAAC;
vmbt_isaac_ifc s Pvmg0_P;
s.seed_random();
/* no return value */
retval_nil(vmg0_);
}
else if (argc == 1 && G_stk->get(0)->typ == VM_NIL)
{
/*
* randomize(nil) - retrieve the current RNG state. This returns a
* list with two elements: [id, state]. Set up the return list.
*/
vm_obj_id_t lstid = CVmObjList::create(vmg_ FALSE, 2);
CVmObjList *lst = (CVmObjList *)vm_objp(vmg_ lstid);
lst->cons_clear();
G_stk->push()->set_obj(lstid);
/* retval[1] = the active RNG ID */
vm_val_t ele;
ele.set_int(G_bif_tads_globals->rng_id);
lst->cons_set_element(0, &ele);
/* retval[2] = the active RNG's saved state vector */
CVmRNGSelector sel Pvmg0_P;
sel.get(G_bif_tads_globals->rng_id)->get_state(vmg_ &ele);
lst->cons_set_element(1, &ele);
/* discard gc protection and return the new list */
G_stk->discard(1);
retval_obj(vmg_ lstid);
}
else if (argc == 1 && G_stk->get(0)->is_listlike(vmg0_))
{
/*
* Randomize([state]) - restores a previous RNG state. The first
* list element is the RNG ID; the second is the saved state data,
* in an RNG-specific format.
*/
vm_val_t idele, state;
G_stk->get(0)->ll_index(vmg_ &idele, 1);
G_stk->get(0)->ll_index(vmg_ &state, 2);
int id = idele.num_to_int(vmg0_);
/* set the state for the selected generator */
CVmRNGSelector sel Pvmg0_P;
sel.get(id)->put_state(vmg_ &state);
/* valid ID - select the generator */
G_bif_tads_globals->rng_id = id;
/* no return value */
retval_nil(vmg0_);
}
else if ((argc == 1 || argc == 2)
&& G_stk->get(0)->is_numeric(vmg0_))
{
/*
* randomize(id) - select the RNG identified by 'id'
*. randomize(id, nil) - select and seed with random data
*. randomize(id, val) - select and seed with fixed data
*/
/* get the ID, and get the generator interface for it */
int id = G_stk->get(0)->num_to_int(vmg0_);
CVmRNGSelector sel Pvmg0_P;
IVmBifTadsRNG *rng = sel.get(id);
/*
* Determine whether and how we're seeding the RNG. If there's
* only the one argument, we're not seeding it. If there's a
* second argument, and it's nil, we're seeding with OS random
* data. Otherwise we're seeding with the fixed data in the second
* argument, which must be an integer or string value.
*/
if (argc == 2)
{
/* get the seed, and sense its type */
vm_val_t *seed = G_stk->get(1);
const char *str;
if (seed->typ == VM_NIL)
{
/* nil - use random data from the OS */
rng->seed_random();
}
else if (seed->is_numeric(vmg0_))
{
/* fixed integer seed value */
rng->seed_int(seed->num_to_int(vmg0_));
}
else if ((str = seed->get_as_string(vmg0_)) != 0)
{
/* string seed value */
rng->seed_str(str + VMB_LEN, vmb_get_len(str));
}
else
{
/* other types are invalid */
err_throw(VMERR_BAD_TYPE_BIF);
}
}
/* if we got this far, the ID was valid, so select the RNG */
G_bif_tads_globals->rng_id = id;
/* no return value */
retval_nil(vmg0_);
}
else
{
/* invalid arguments */
err_throw(VMERR_WRONG_NUM_OF_ARGS);
}
}
/*
* LCG randomize - seed the random-number generator
*/
//void CVmBifTADS::randomize(VMG_ uint argc)
//{
// /* check arguments */
// check_argc(vmg_ argc, 0);
//
// /* seed the generator */
// os_rand(&G_bif_tads_globals->lcg_rand_seed);
//}
/* ------------------------------------------------------------------------ */
/*
* Get the next random number from the selected RNG
*/
static uint32_t rng_next(VMG0_)
{
CVmRNGSelector sel Pvmg0_P;
return sel.get(G_bif_tads_globals->rng_id)->rand();
}
/* ------------------------------------------------------------------------ */
/*
* Map a random 32-bit number to a smaller range 0..range-1.
*
* Use the "multiplication" method Knuth describes in TAoCP Vol 2 section
* 3.4.2. This treats the source value as a fractional value in the range
* [0..1); we multiply this fractional value by the upper bound to get a
* linearly distributed number [0..range). To turn a 32-bit integer into a
* fractional value in the range [0..1), divide by 2^32.
*
* We do this calculation entirely with 32-bit integer arithmetic. The
* nominal calculation we're performing is:
*
*. rand_val = (ulong)((((double)rand_val) / 4294967296.0)
*. * (double)range);
*
* To do the arithmetic entirely with integers, we refactor this by first
* calculating the 64-bit product of rand_val * range, then dividing the
* product by 2^32. This isn't possible to do directly with 32-bit ints,
* of course. But the division is particularly easy because it's the same
* as a 32-bit right-shift. So the trick is to factor out the low-order
* 32-bits of the product and the high-order 32-bits, which we can do with
* some bit shifting.
*/
static inline ulong rand_range(ulong rand_val, ulong range)
{
/* calculate the high-order 32 bits of (rand_val / 2^32 * range) */
ulong hi = (((rand_val >> 16) & 0xffff) * ((range >> 16) & 0xffff))
+ ((((rand_val >> 16) & 0xffff) * (range & 0xffff)) >> 16)
+ (((rand_val & 0xffff) * ((range >> 16) & 0xffff)) >> 16);
/* calculate the low-order 32 bits */
ulong lo = ((((rand_val >> 16) & 0xffff) * (range & 0xffff)) & 0xffff)
+ (((rand_val & 0xffff) * ((range >> 16) & 0xffff)) & 0xffff)
+ ((((rand_val & 0xffff) * (range & 0xffff)) >> 16) & 0xffff);
/* add the carry from the low part into the high part to get the result */
return hi + (lo >> 16);
}
/* calculate a random number in the range [lower, upper] */
static inline ulong rand_range(ulong rand_val, ulong lower, ulong upper)
{
return lower + rand_range(rand_val, upper - lower + 1);
}
/* random number with two ranges */
static inline ulong rand_range(ulong rand_val,
ulong lo1, ulong hi1,
ulong lo2, ulong hi2)
{
rand_val = rand_range(rand_val, (hi1 - lo1 + 1) + (hi2 - lo2 + 1));
return rand_val + (rand_val <= hi1 - lo1 ? lo1 : lo2 - (hi1 - lo1 + 1));
}
/* random number with three ranges */
static inline ulong rand_range(ulong rand_val,
ulong lo1, ulong hi1,
ulong lo2, ulong hi2,
ulong lo3, ulong hi3)
{
rand_val = rand_range(rand_val,
(hi1 - lo1 + 1)
+ (hi2 - lo2 + 1)
+ (hi3 - lo3 + 1));
return rand_val
+ (rand_val <= hi1 - lo1 ? lo1 :
rand_val <= hi1 - lo1 + hi2 - lo2 + 1 ? lo2 - (hi1 - lo1 + 1) :
lo3 - (hi1 - lo1 + 1) - (hi2 - lo2 + 1));
}
/* ------------------------------------------------------------------------ */
/*
* Random string template parser
*/
class RandStrParser
{
public:
/* initialize - parse the template string */
RandStrParser(const char *src, size_t len);
/* delete */
~RandStrParser();
/* execute the template and return a string object result */
void exec(VMG_ vm_val_t *result);
/* get the current character */
wchar_t getch() { return rem > 0 ? p.getch() : 0; }
/* parse an integer value */
int parseInt()
{
/* parse digits in the input */
int acc;
for (acc = 0 ; more() && is_digit(getch()) ; skip())
{
/* add this digit into the accumulator */
acc *= 10;
acc += value_of_digit(getch());
}
/* return the accumulator value */
return acc;
}
/* skip the current character */
void skip()
{
if (rem != 0)
p.inc(&rem);
}
/* is there more input? */
int more() const { return rem != 0; }
/* get the number of bytes remaining */
size_t getrem() const { return rem; }
protected:
/* source string pointer and remaining length */
utf8_ptr p;
size_t rem;
/* root of the parse tree */
class RandStrNode *tree;
};
class RandStrNode
{
public:
RandStrNode()
{
firstChild = lastChild = 0;
nextSibling = 0;
}
virtual ~RandStrNode()
{
while (firstChild != 0)
{
RandStrNode *nxt = firstChild->nextSibling;
delete firstChild;
firstChild = nxt;
}
}
/* calculate the maximum length for the generated string for this node */
virtual int maxlen() = 0;
/* generate the string for this node */
virtual void generate(VMG_ wchar_t *&dst) = 0;
/* add a child */
void addChild(RandStrNode *chi)
{
if (lastChild != 0)
lastChild->nextSibling = chi;
else
firstChild = chi;
lastChild = chi;
}
/* tree links */
RandStrNode *firstChild, *lastChild;