forked from rebolsource/r3
/
b-init.c
1477 lines (1224 loc) · 49.2 KB
/
b-init.c
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
//
// File: %b-init.c
// Summary: "initialization functions"
// Section: bootstrap
// Project: "Rebol 3 Interpreter and Run-time (Ren-C branch)"
// Homepage: https://github.com/metaeducation/ren-c/
//
//=////////////////////////////////////////////////////////////////////////=//
//
// Copyright 2012 REBOL Technologies
// Copyright 2012-2019 Rebol Open Source Contributors
// REBOL is a trademark of REBOL Technologies
//
// See README.md and CREDITS.md for more information.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
//=////////////////////////////////////////////////////////////////////////=//
//
// The primary routine for starting up Rebol is Startup_Core(). It runs the
// bootstrap in phases, based on processing various portions of the data in
// %tmp-boot-block.r (which is the aggregated code from the %mezz/*.r files,
// packed into one file as part of the build preparation).
//
// As part of an effort to lock down the memory usage, Ren-C added a parallel
// Shutdown_Core() routine which would gracefully exit Rebol, with assurances
// that all accounting was done correctly. This includes being sure that the
// number used to track memory usage for triggering garbage collections would
// balance back out to exactly zero.
//
// (Release builds can instead close only vital resources like files, and
// trust the OS exit() to reclaim memory more quickly. However Ren-C's goal
// is to be usable as a library that may be initialized and shutdown within
// a process that's not exiting, so the ability to clean up is important.)
//
#include "sys-core.h"
#define EVAL_DOSE 10000
//
// Ensure_Basics: C
//
// Initially these checks were in the debug build only. However, they are so
// foundational that it's probably worth getting a coherent crash in any build
// where these tests don't work.
//
static void Ensure_Basics(void)
{
//=//// CHECK REBVAL SIZE ////////////////////////////////////////////=//
// The system is designed with the intent that REBVAL is 4x(32-bit) on
// 32-bit platforms and 4x(64-bit) on 64-bit platforms. It's a crtical
// performance point. For the moment we consider it to be essential
// enough that the system that it refuses to run if not true.
//
// But if someone is in an odd situation with a larger sized cell--and
// it's an even multiple of ALIGN_SIZE--it may still work. For instance:
// the DEBUG_TRACK_EXTEND_CELLS mode doubles the cell size to carry the
// file, line, and tick of their initialization (or last TOUCH_CELL()).
// Define UNUSUAL_REBVAL_SIZE to bypass this check.
size_t sizeof_REBVAL = sizeof(REBVAL); // in variable avoids warning
#if defined(UNUSUAL_REBVAL_SIZE)
if (sizeof_REBVAL % ALIGN_SIZE != 0)
panic ("size of REBVAL does not evenly divide by ALIGN_SIZE");
#else
if (sizeof_REBVAL != sizeof(void*) * 4)
panic ("size of REBVAL is not sizeof(void*) * 4");
#if defined(DEBUG_SERIES_ORIGINS) || defined(DEBUG_COUNT_TICKS)
assert(sizeof(REBSER) == sizeof(REBVAL) * 2 + sizeof(void*) * 2);
#else
assert(sizeof(REBSER) == sizeof(REBVAL) * 2);
#endif
#endif
//=//// CHECK REBSER INFO PLACEMENT ///////////////////////////////////=//
// REBSER places the `info` bits exactly after a REBVAL so they can do
// double-duty as terminator for that REBVAL when enumerated as an ARRAY.
blockscope {
size_t offset = offsetof(REBSER, info); // in variable avoids warning
if (offset - offsetof(REBSER, content) != sizeof(REBVAL))
panic ("bad structure alignment for internal array termination"); }
//=//// CHECK BYTE-ORDERING SENSITIVE FLAGS //////////////////////////=//
// See the %sys-node.h file for an explanation of what these are, and
// why having them work is fundamental to the API.
REBFLGS flags
= FLAG_LEFT_BIT(5) | FLAG_SECOND_BYTE(21) | FLAG_SECOND_UINT16(1975);
REBYTE m = FIRST_BYTE(flags); // 6th bit from left set (0b00000100 is 4)
REBYTE d = SECOND_BYTE(flags);
uint16_t y = SECOND_UINT16(flags);
if (m != 4 or d != 21 or y != 1975) {
#if defined(DEBUG_STDIO_OK)
printf("m = %u, d = %u, y = %u\n", m, d, y);
#endif
panic ("Bad composed integer assignment for byte-ordering macro.");
}
}
#if !defined(OS_STACK_GROWS_UP) && !defined(OS_STACK_GROWS_DOWN)
//
// This is a naive guess with no guarantees. If there *is* a "real"
// answer, it would be fairly nuts:
//
// http://stackoverflow.com/a/33222085/211160
//
// Prefer using a build configuration #define, if possible (although
// emscripten doesn't necessarily guarantee up or down):
//
// https://github.com/kripken/emscripten/issues/5410
//
bool Guess_If_Stack_Grows_Up(int *p) {
int i;
if (not p)
return Guess_If_Stack_Grows_Up(&i); // RECURSION: avoids inlining
if (p < &i) // !!! this comparison is undefined behavior
return true; // upward
return false; // downward
}
#endif
//
// Set_Stack_Limit: C
//
// See C_STACK_OVERFLOWING for remarks on this **non-standard** technique of
// stack overflow detection. Note that each thread would have its own stack
// address limits, so this has to be updated for threading.
//
// Currently, this is called every time PUSH_TRAP() is called when Saved_State
// is NULL, and hopefully only one instance of it per thread will be in effect
// (otherwise, the bounds would add and be useless).
//
void Set_Stack_Limit(void *base, uintptr_t bounds) {
#if defined(OS_STACK_GROWS_UP)
TG_Stack_Limit = cast(uintptr_t, base) + bounds;
#elif defined(OS_STACK_GROWS_DOWN)
TG_Stack_Limit = cast(uintptr_t, base) - bounds;
#else
TG_Stack_Grows_Up = Guess_If_Stack_Grows_Up(NULL);
if (TG_Stack_Grows_Up)
TG_Stack_Limit = cast(uintptr_t, base) + bounds;
else
TG_Stack_Limit = cast(uintptr_t, base) - bounds;
#endif
}
//
// Startup_True_And_False: C
//
// !!! Rebol is firm on TRUE and FALSE being WORD!s, as opposed to the literal
// forms of logical true and false. Not only does this frequently lead to
// confusion, but there's not consensus on what a good literal form would be.
// R3-Alpha used #[true] and #[false] (but often molded them as looking like
// the words true and false anyway). $true and $false have been proposed,
// but would not be backward compatible in files read by bootstrap.
//
// Since no good literal form exists, the %sysobj.r file uses the words. They
// have to be defined before the point that it runs (along with the natives).
//
static void Startup_True_And_False(void)
{
REBVAL *true_value = Append_Context(Lib_Context, 0, Canon(SYM_TRUE));
Init_True(true_value);
assert(IS_TRUTHY(true_value) and VAL_LOGIC(true_value) == true);
REBVAL *false_value = Append_Context(Lib_Context, 0, Canon(SYM_FALSE));
Init_False(false_value);
assert(IS_FALSEY(false_value) and VAL_LOGIC(false_value) == false);
}
//
// generic: enfix native [
//
// {Creates datatype action (currently for internal use only)}
//
// return: [void!]
// :verb [set-word!]
// spec [block!]
// ]
//
REBNATIVE(generic)
//
// The `generic` native is searched for explicitly by %make-natives.r and put
// in second place for initialization (after the `native` native).
//
// It is designed to be an enfix function that quotes its first argument,
// so when you write FOO: ACTION [...], the FOO: gets quoted to be the verb.
{
INCLUDE_PARAMS_OF_GENERIC;
REBVAL *spec = ARG(spec);
REBARR *paramlist = Make_Paramlist_Managed_May_Fail(
spec,
MKF_KEYWORDS | MKF_RETURN // return type checked only in debug build
);
// !!! There is no system yet for extension types to register which of
// the generic actions they can handle. So for the moment, we just say
// that any custom type will have its action dispatcher run--and it's
// up to the handler to give an error if there's a problem. This works,
// but it limits discoverability of types in HELP. A better answeer would
// be able to inventory which types had registered generic dispatchers
// and list the appropriate types from HELP.
//
RELVAL *param = ARR_AT(paramlist, 1);
if (SER(paramlist)->header.bits & PARAMLIST_FLAG_HAS_RETURN) {
assert(VAL_PARAM_SYM(param) == SYM_RETURN);
TYPE_SET(param, REB_CUSTOM);
++param;
}
while (VAL_PARAM_CLASS(param) != REB_P_NORMAL)
++param;
TYPE_SET(param, REB_CUSTOM);
REBACT *generic = Make_Action(
paramlist,
&Generic_Dispatcher, // return type is only checked in debug build
nullptr, // no underlying action (use paramlist)
nullptr, // no specialization exemplar (or inherited exemplar)
IDX_NATIVE_MAX // details array capacity
);
SET_ACTION_FLAG(generic, IS_NATIVE);
REBARR *details = ACT_DETAILS(generic);
Init_Word(ARR_AT(details, IDX_NATIVE_BODY), VAL_WORD_CANON(ARG(verb)));
Init_Object(ARR_AT(details, IDX_NATIVE_CONTEXT), Lib_Context);
REBVAL *verb_var = Sink_Var_May_Fail(ARG(verb), SPECIFIED);
Init_Action_Unbound(verb_var, generic); // set the word to the action
return Init_Void(D_OUT); // see ENFIX for why evaluate to void
}
//
// Add_Lib_Keys_For_Unscannable_Set_Words: C
//
// In order for the bootstrap to assign values to library words, they have to
// exist in the bootstrap context. The way they get into the context is by
// a scan for top-level SET-WORD!s in the %sys-xxx.r and %mezz-xxx.r files.
//
// ...BUT, R3-Alpha didn't resolve how to make get the SET-WORD! versions of
// things like `<:`. There is contention with scan patterns for tags that
// were never reconciled. So long as they can't be scanned as SET-WORD!,
// they have to be put into the lib context manually.
//
// !!! Now that %base-xxx.r and %mezz-xxx.r aren't actually LOAD-ed by the
// bootstrapping executable (they are just READ and have their text munged
// by PARSE), this really isn't a bootstrap limitiation. As soon as the
// scanner is fixed to make SET-WORD!s for things, the entry in this table
// isn't needed...no need to update the bootstrap executable.
//
static void Add_Lib_Keys_For_Unscannable_Set_Words(void)
{
const char *names[] = {
"<",
">",
"<=", // less than or equal !!! https://forum.rebol.info/t/349/11
// `=>:` actually works as a SET-WORD!, used for lambda functions
">=", // greater than or equal to
"=<", // equal to or less than
"<>", // not equal (the chosen meaning, as opposed to "empty tag")
// https://forum.rebol.info/t/1039
"->", // enfix path op, "SHOVE": https://trello.com/c/Kg9A45b5
"<-", // "SHOVE" variation
"|>", // Evaluate to next single expression, but do ones afterward
"<|", // Evaluate to previous expression, but do rest (like ALSO)
nullptr
};
REBLEN i;
for (i = 0; names[i] != NULL; ++i) {
REBSTR *str = Intern_UTF8_Managed(cb_cast(names[i]), strlen(names[i]));
REBVAL *val = Append_Context(Lib_Context, NULL, str);
assert(IS_NULLED(val));
UNUSED(val);
}
}
static REBVAL *Make_Locked_Tag(const char *utf8) { // helper
REBVAL *t = rebText(utf8);
mutable_KIND_BYTE(t) = REB_TAG;
mutable_MIRROR_BYTE(t) = REB_TAG;
REBSER *locker = nullptr;
Ensure_Value_Frozen(t, locker);
return t;
}
//
// Init_Action_Spec_Tags: C
//
// FUNC and PROC search for these tags, like <opt> and <local>. They are
// natives and run during bootstrap, so these string comparisons are
// needed.
//
static void Init_Action_Spec_Tags(void)
{
Root_Void_Tag = Make_Locked_Tag("void");
Root_With_Tag = Make_Locked_Tag("with");
Root_Ellipsis_Tag = Make_Locked_Tag("...");
Root_Opt_Tag = Make_Locked_Tag("opt");
Root_End_Tag = Make_Locked_Tag("end");
Root_Blank_Tag = Make_Locked_Tag("blank");
Root_Local_Tag = Make_Locked_Tag("local");
Root_Skip_Tag = Make_Locked_Tag("skip");
Root_Dequote_Tag = Make_Locked_Tag("dequote");
Root_Requote_Tag = Make_Locked_Tag("requote");
Root_Const_Tag = Make_Locked_Tag("const");
// !!! Needed for bootstrap, as `@arg` won't LOAD in old r3
//
Root_Modal_Tag = Make_Locked_Tag("modal");
}
static void Shutdown_Action_Spec_Tags(void)
{
rebRelease(Root_Void_Tag);
rebRelease(Root_With_Tag);
rebRelease(Root_Ellipsis_Tag);
rebRelease(Root_Opt_Tag);
rebRelease(Root_End_Tag);
rebRelease(Root_Blank_Tag);
rebRelease(Root_Local_Tag);
rebRelease(Root_Skip_Tag);
rebRelease(Root_Dequote_Tag);
rebRelease(Root_Requote_Tag);
rebRelease(Root_Const_Tag);
rebRelease(Root_Modal_Tag); // !!! only needed for bootstrap with old r3
}
//
// Init_Action_Meta_Shim: C
//
// Make_Paramlist_Managed_May_Fail() needs the object archetype ACTION-META
// from %sysobj.r, to have the keylist to use in generating the info used
// by HELP for the natives. However, natives themselves are used in order
// to run the object construction in %sysobj.r
//
// To break this Catch-22, this code builds a field-compatible version of
// ACTION-META. After %sysobj.r is loaded, an assert checks to make sure
// that this manual construction actually matches the definition in the file.
//
static void Init_Action_Meta_Shim(void) {
REBSYM field_syms[6] = {
SYM_SELF, SYM_DESCRIPTION, SYM_RETURN_TYPE, SYM_RETURN_NOTE,
SYM_PARAMETER_TYPES, SYM_PARAMETER_NOTES
};
REBCTX *meta = Alloc_Context_Core(REB_OBJECT, 6, NODE_FLAG_MANAGED);
REBLEN i = 1;
for (; i != 7; ++i) // BLANK!, as `make object! [x: ()]` is illegal
Init_Blank(Append_Context(meta, nullptr, Canon(field_syms[i - 1])));
Init_Object(CTX_VAR(meta, 1), meta); // it's "selfish"
Root_Action_Meta = Init_Object(Alloc_Value(), meta);
REBSER *locker = nullptr;
Ensure_Value_Frozen(Root_Action_Meta, locker);
}
static void Shutdown_Action_Meta_Shim(void) {
rebRelease(Root_Action_Meta);
}
//
// Make_Native: C
//
// Reused function in Startup_Natives() as well as extensions loading natives,
// which can be parameterized with a different context in which to look up
// bindings by deafault in the API when that native is on the stack.
//
// Each entry should be one of these forms:
//
// some-name: native [spec content]
//
// some-name: native/body [spec content] [equivalent user code]
//
// It is optional to put ENFIX between the SET-WORD! and the spec.
//
// If more refinements are added, this will have to get more sophisticated.
//
// Though the manual building of this table is not as "nice" as running the
// evaluator, the evaluator makes comparisons against native values. Having
// all natives loaded fully before ever running Eval_Core() helps with
// stability and invariants...also there's "state" in keeping track of which
// native index is being loaded, which is non-obvious. But these issues
// could be addressed (e.g. by passing the native index number / DLL in).
//
REBVAL *Make_Native(
RELVAL **item, // the item will be advanced as necessary
REBSPC *specifier,
REBNAT dispatcher,
REBVAL *module
){
assert(specifier == SPECIFIED); // currently a requirement
// Get the name the native will be started at with in Lib_Context
//
if (not IS_SET_WORD(*item))
panic (*item);
REBVAL *name = KNOWN(*item);
++*item;
bool enfix;
if (IS_WORD(*item) and VAL_WORD_SYM(*item) == SYM_ENFIX) {
enfix = true;
++*item;
}
else
enfix = false;
// See if it's being invoked with NATIVE or NATIVE/BODY
//
bool has_body;
if (IS_WORD(*item)) {
if (VAL_WORD_SYM(*item) != SYM_NATIVE)
panic (*item);
has_body = false;
}
else {
if (
not IS_PATH(*item)
or VAL_LEN_HEAD(*item) != 2
or not IS_WORD(ARR_HEAD(VAL_ARRAY(*item)))
or VAL_WORD_SYM(ARR_HEAD(VAL_ARRAY(*item))) != SYM_NATIVE
or not IS_WORD(ARR_AT(VAL_ARRAY(*item), 1))
or VAL_WORD_SYM(ARR_AT(VAL_ARRAY(*item), 1)) != SYM_BODY
){
panic (*item);
}
has_body = true;
}
++*item;
REBVAL *spec = KNOWN(*item);
++*item;
if (not IS_BLOCK(spec))
panic (spec);
// With the components extracted, generate the native and add it to
// the Natives table. The associated C function is provided by a
// table built in the bootstrap scripts, `Native_C_Funcs`.
REBARR *paramlist = Make_Paramlist_Managed_May_Fail(
KNOWN(spec),
MKF_KEYWORDS | MKF_RETURN // return type checked only in debug build
);
REBACT *act = Make_Action(
paramlist,
dispatcher, // "dispatcher" is unique to this "native"
nullptr, // no underlying action (use paramlist)
nullptr, // no specialization exemplar (or inherited exemplar)
IDX_NATIVE_MAX // details array capacity
);
SET_ACTION_FLAG(act, IS_NATIVE);
if (enfix)
SET_ACTION_FLAG(act, ENFIXED);
REBARR *details = ACT_DETAILS(act);
// If a user-equivalent body was provided, we save it in the native's
// REBVAL for later lookup.
//
if (has_body) {
if (not IS_BLOCK(*item))
panic (*item);
Derelativize(ARR_AT(details, IDX_NATIVE_BODY), *item, specifier);
++*item;
}
else
Init_Blank(ARR_AT(details, IDX_NATIVE_BODY));
// When code in the core calls APIs like `rebValue()`, it consults the
// stack and looks to see where the native function that is running
// says its "module" is. For natives, we default to Lib_Context.
//
Move_Value(ARR_AT(details, IDX_NATIVE_CONTEXT), module);
// Append the native to the module under the name given.
//
REBVAL *var = Append_Context(VAL_CONTEXT(module), name, 0);
Init_Action_Unbound(var, act);
return var;
}
//
// Startup_Natives: C
//
// Create native functions. In R3-Alpha this would go as far as actually
// creating a NATIVE native by hand, and then run code that would call that
// native for each function. Ren-C depends on having the native table
// initialized to run the evaluator (for instance to test functions against
// the UNWIND native's FUNC signature in definitional returns). So it
// "fakes it" just by calling a C function for each item...and there is no
// actual "native native".
//
// If there *were* a REBNATIVE(native) this would be its spec:
//
// native: native [
// spec [block!]
// /body "Body of equivalent usermode code (for documentation)}
// [block!]
// ]
//
// Returns an array of words bound to natives for SYSTEM/CATALOG/NATIVES
//
static REBARR *Startup_Natives(const REBVAL *boot_natives)
{
// Must be called before first use of Make_Paramlist_Managed_May_Fail()
//
Init_Action_Meta_Shim();
assert(VAL_INDEX(boot_natives) == 0); // should be at head, sanity check
RELVAL *item = VAL_ARRAY_AT(boot_natives);
REBSPC *specifier = VAL_SPECIFIER(boot_natives);
// Although the natives are not being "executed", there are typesets
// being built from the specs. So to process `foo: native [x [integer!]]`
// the INTEGER! word must be bound to its datatype. Deep walk the
// natives in order to bind these datatypes.
//
Bind_Values_Deep(item, Lib_Context);
REBARR *catalog = Make_Array(Num_Natives);
REBLEN n = 0;
REBVAL *generic_word = nullptr; // gives clear error if GENERIC not found
while (NOT_END(item)) {
if (n >= Num_Natives)
panic (item);
REBVAL *name = KNOWN(item);
assert(IS_SET_WORD(name));
REBVAL *native = Make_Native(
&item,
specifier,
Native_C_Funcs[n],
CTX_ARCHETYPE(Lib_Context)
);
// While the lib context natives can be overwritten, the system
// currently depends on having a permanent list of the natives that
// does not change, see uses via NAT_VALUE() and NAT_ACT().
//
Prep_Non_Stack_Cell(&Natives[n]);
Move_Value(&Natives[n], native); // Note: Loses enfixedness (!)
SET_CELL_FLAG(&Natives[n], PROTECTED);
REBVAL *catalog_item = Move_Value(Alloc_Tail_Array(catalog), name);
mutable_KIND_BYTE(catalog_item) = REB_WORD;
mutable_MIRROR_BYTE(catalog_item) = REB_WORD;
if (VAL_WORD_SYM(name) == SYM_GENERIC)
generic_word = name;
++n;
}
if (n != Num_Natives)
panic ("Incorrect number of natives found during processing");
if (not generic_word)
panic ("GENERIC native not found during boot block processing");
return catalog;
}
//
// Startup_Generics: C
//
// Returns an array of words bound to generics for SYSTEM/CATALOG/ACTIONS
//
static REBARR *Startup_Generics(const REBVAL *boot_generics)
{
assert(VAL_INDEX(boot_generics) == 0); // should be at head, sanity check
RELVAL *head = VAL_ARRAY_AT(boot_generics);
REBSPC *specifier = VAL_SPECIFIER(boot_generics);
// Add SET-WORD!s that are top-level in the generics block to the lib
// context, so there is a variable for each action. This means that the
// assignments can execute.
//
Bind_Values_Set_Midstream_Shallow(head, Lib_Context);
// The above actually does bind the GENERIC word to the GENERIC native,
// since the GENERIC word is found in the top-level of the block. But as
// with the natives, in order to process `foo: generic [x [integer!]]` the
// INTEGER! word must be bound to its datatype. Deep bind the code in
// order to bind the words for these datatypes.
//
Bind_Values_Deep(head, Lib_Context);
DECLARE_LOCAL (result);
if (Do_Any_Array_At_Throws(result, boot_generics, SPECIFIED))
panic (result);
if (not IS_BLANK(result))
panic (result);
// Sanity check the symbol transformation
//
if (0 != strcmp("open", STR_UTF8(Canon(SYM_OPEN))))
panic (Canon(SYM_OPEN));
REBDSP dsp_orig = DSP;
RELVAL *item = head;
for (; NOT_END(item); ++item)
if (IS_SET_WORD(item)) {
Derelativize(DS_PUSH(), item, specifier);
mutable_KIND_BYTE(DS_TOP) = REB_WORD; // change pushed to WORD!
mutable_MIRROR_BYTE(DS_TOP) = REB_WORD;
}
return Pop_Stack_Values(dsp_orig); // catalog of generics
}
//
// Startup_End_Node: C
//
// We can't actually put an end value in the middle of a block, so we poke
// this one into a program global. It is not legal to bit-copy an END (you
// always use SET_END), so we can make it unwritable.
//
static void Startup_End_Node(void)
{
PG_End_Node.header = Endlike_Header(0); // no NODE_FLAG_CELL, R/O
TRACK_CELL_IF_DEBUG(&PG_End_Node, __FILE__, __LINE__);
assert(IS_END(END_NODE)); // sanity check that it took
}
//
// Startup_Empty_Array: C
//
// Generic read-only empty array, which will be put into EMPTY_BLOCK when
// Alloc_Value() is available. Note it's too early for ARRAY_HAS_FILE_LINE.
//
// Warning: GC must not run before Init_Root_Vars() puts it in an API node!
//
static void Startup_Empty_Array(void)
{
PG_Empty_Array = Make_Array_Core(0, NODE_FLAG_MANAGED);
SET_SERIES_INFO(PG_Empty_Array, FROZEN);
}
//
// Init_Root_Vars: C
//
// Create some global variables that are useful, and need to be safe from
// garbage collection. This relies on the mechanic from the API, where
// handles are kept around until they are rebRelease()'d.
//
// This is called early, so there are some special concerns to building the
// values that would not apply later in boot.
//
static void Init_Root_Vars(void)
{
// Simple isolated VOID, NONE, TRUE, and FALSE values.
//
// They should only be accessed by macros which retrieve their values
// as `const`, to avoid the risk of accidentally changing them. (This
// rule is broken by some special system code which `m_cast`s them for
// the purpose of using them as directly recognizable pointers which
// also look like values.)
//
// It is presumed that these types will never need to have GC behavior,
// and thus can be stored safely in program globals without mention in
// the root set. Should that change, they could be explicitly added
// to the GC's root set.
Prep_Non_Stack_Cell(&PG_Nulled_Cell);
Init_Nulled(&PG_Nulled_Cell);
Prep_Non_Stack_Cell(&PG_Blank_Value);
Init_Blank(&PG_Blank_Value);
Prep_Non_Stack_Cell(&PG_False_Value);
Init_False(&PG_False_Value);
Prep_Non_Stack_Cell(&PG_True_Value);
Init_True(&PG_True_Value);
Prep_Non_Stack_Cell(&PG_Void_Value);
Init_Void(&PG_Void_Value);
Prep_Non_Stack_Cell(&PG_R_Thrown);
RESET_CELL(&PG_R_Thrown, REB_R_THROWN, CELL_MASK_NONE);
Prep_Non_Stack_Cell(&PG_R_Invisible);
RESET_CELL(&PG_R_Invisible, REB_R_INVISIBLE, CELL_MASK_NONE);
Prep_Non_Stack_Cell(&PG_R_Immediate);
RESET_CELL(&PG_R_Immediate, REB_R_IMMEDIATE, CELL_MASK_NONE);
Prep_Non_Stack_Cell(&PG_R_Redo_Unchecked);
RESET_CELL(&PG_R_Redo_Unchecked, REB_R_REDO, CELL_MASK_NONE);
EXTRA(Any, &PG_R_Redo_Unchecked).flag = false; // "unchecked"
Prep_Non_Stack_Cell(&PG_R_Redo_Checked);
RESET_CELL(&PG_R_Redo_Checked, REB_R_REDO, CELL_MASK_NONE);
EXTRA(Any, &PG_R_Redo_Checked).flag = true; // "checked"
Prep_Non_Stack_Cell(&PG_R_Reference);
RESET_CELL(&PG_R_Reference, REB_R_REFERENCE, CELL_MASK_NONE);
REBSER *locker = nullptr;
Root_Empty_Block = Init_Block(Alloc_Value(), PG_Empty_Array);
Ensure_Value_Frozen(Root_Empty_Block, locker);
// Note: rebText() can't run yet, review.
//
REBSTR *nulled_uni = Make_Unicode(1);
#if !defined(NDEBUG)
REBUNI test_nul;
NEXT_CHR(&test_nul, STR_AT(nulled_uni, 0));
assert(test_nul == '\0');
assert(STR_LEN(nulled_uni) == 0);
#endif
Root_Empty_Text = Init_Text(Alloc_Value(), nulled_uni);
Ensure_Value_Frozen(Root_Empty_Text, locker);
Root_Empty_Binary = Init_Binary(Alloc_Value(), Make_Binary(0));
Ensure_Value_Frozen(Root_Empty_Binary, locker);
Root_Space_Char = rebChar(' ');
Root_Newline_Char = rebChar('\n');
// !!! Putting the stats map in a root object is a temporary solution
// to allowing a native coded routine to have a static which is guarded
// by the GC. While it might seem better to move the stats into a
// mostly usermode implementation that hooks apply, this could preclude
// doing performance analysis on boot--when it would be too early for
// most user code to be running. It may be that the debug build has
// this form of mechanism that can diagnose boot, while release builds
// rely on a usermode stats module.
//
Root_Stats_Map = Init_Map(Alloc_Value(), Make_Map(10));
}
static void Shutdown_Root_Vars(void)
{
rebRelease(Root_Stats_Map);
Root_Stats_Map = nullptr;
rebRelease(Root_Space_Char);
Root_Space_Char = nullptr;
rebRelease(Root_Newline_Char);
Root_Newline_Char = nullptr;
rebRelease(Root_Empty_Text);
Root_Empty_Text = nullptr;
rebRelease(Root_Empty_Block);
Root_Empty_Block = nullptr;
rebRelease(Root_Empty_Binary);
Root_Empty_Binary = nullptr;
}
//
// Init_System_Object: C
//
// Evaluate the system object and create the global SYSTEM word. We do not
// BIND_ALL here to keep the internal system words out of the global context.
// (See also N_context() which creates the subobjects of the system object.)
//
static void Init_System_Object(
const REBVAL *boot_sysobj_spec,
REBARR *datatypes_catalog,
REBARR *natives_catalog,
REBARR *generics_catalog,
REBCTX *errors_catalog
) {
assert(VAL_INDEX(boot_sysobj_spec) == 0);
RELVAL *spec_head = VAL_ARRAY_AT(boot_sysobj_spec);
// Create the system object from the sysobj block (defined in %sysobj.r)
//
REBCTX *system = Make_Selfish_Context_Detect_Managed(
REB_OBJECT, // type
VAL_ARRAY_AT(boot_sysobj_spec), // scan for toplevel set-words
NULL // parent
);
Bind_Values_Deep(spec_head, Lib_Context);
// Bind it so CONTEXT native will work (only used at topmost depth)
//
Bind_Values_Shallow(spec_head, system);
// Evaluate the block (will eval CONTEXTs within). Expects void result.
//
DECLARE_LOCAL (result);
if (Do_Any_Array_At_Throws(result, boot_sysobj_spec, SPECIFIED))
panic (result);
if (not IS_BLANK(result))
panic (result);
// Create a global value for it. (This is why we are able to say `system`
// and have it bound in lines like `sys: system/contexts/sys`)
//
Init_Object(
Append_Context(Lib_Context, NULL, Canon(SYM_SYSTEM)),
system
);
// Make the system object a root value, to protect it from GC. (Someone
// could say `system: blank` in the Lib_Context, otherwise!)
//
Root_System = Init_Object(Alloc_Value(), system);
// Init_Action_Meta_Shim() made Root_Action_Meta as a bootstrap hack
// since it needed to make function meta information for natives before
// %sysobj.r's code could run using those natives. But make sure what it
// made is actually identical to the definition in %sysobj.r.
//
assert(
0 == CT_Context(
Get_System(SYS_STANDARD, STD_ACTION_META),
Root_Action_Meta,
1 // "strict equality"
)
);
// Create system/catalog/* for datatypes, natives, generics, errors
//
Init_Block(Get_System(SYS_CATALOG, CAT_DATATYPES), datatypes_catalog);
Init_Block(Get_System(SYS_CATALOG, CAT_NATIVES), natives_catalog);
Init_Block(Get_System(SYS_CATALOG, CAT_ACTIONS), generics_catalog);
Init_Object(Get_System(SYS_CATALOG, CAT_ERRORS), errors_catalog);
// Create system/codecs object
//
Init_Object(
Get_System(SYS_CODECS, 0),
Alloc_Context_Core(REB_OBJECT, 10, NODE_FLAG_MANAGED)
);
// The "standard error" template was created as an OBJECT!, because the
// `make error!` functionality is not ready when %sysobj.r runs. Fix
// up its archetype so that it is an actual ERROR!.
//
REBVAL *std_error = Get_System(SYS_STANDARD, STD_ERROR);
assert(IS_OBJECT(std_error));
mutable_KIND_BYTE(std_error) = REB_ERROR;
mutable_MIRROR_BYTE(std_error) = REB_ERROR;
mutable_KIND_BYTE(CTX_ARCHETYPE(VAL_CONTEXT(std_error))) = REB_ERROR;
mutable_MIRROR_BYTE(CTX_ARCHETYPE(VAL_CONTEXT(std_error))) = REB_ERROR;
assert(CTX_KEY_SYM(VAL_CONTEXT(std_error), 1) == SYM_SELF);
mutable_KIND_BYTE(VAL_CONTEXT_VAR(std_error, 1)) = REB_ERROR;
mutable_MIRROR_BYTE(VAL_CONTEXT_VAR(std_error, 1)) = REB_ERROR;
}
void Shutdown_System_Object(void)
{
rebRelease(Root_System);
Root_System = NULL;
}
//
// Init_Contexts_Object: C
//
// This sets up the system/contexts object.
//
// !!! One of the critical areas in R3-Alpha that was not hammered out
// completely was the question of how the binding process gets started, and
// how contexts might inherit or relate.
//
// However, the basic model for bootstrap is that the "user context" is the
// default area for new code evaluation. It starts out as a copy of an
// initial state set up in the lib context. When native routines or other
// content gets overwritten in the user context, it can be borrowed back
// from `system/contexts/lib` (typically aliased as "lib" in the user context).
//
static void Init_Contexts_Object(void)
{
DROP_GC_GUARD(Sys_Context);
Init_Object(Get_System(SYS_CONTEXTS, CTX_SYS), Sys_Context);
DROP_GC_GUARD(Lib_Context);
Init_Object(Get_System(SYS_CONTEXTS, CTX_LIB), Lib_Context);
Init_Object(Get_System(SYS_CONTEXTS, CTX_USER), Lib_Context);
}
//
// Startup_Task: C
//
// !!! Prior to the release of R3-Alpha, there had apparently been some amount
// of effort to take single-threaded assumptions and globals, and move to a
// concept where thread-local storage was used for some previously assumed
// globals. This would be a prerequisite for concurrency but not enough: the
// memory pools would need protection from one thread to share any series with
// others, due to contention between reading and writing.
//
// Ren-C kept the separation, but if threading were to be a priority it would
// likely be approached a different way. A nearer short-term feature would be
// "isolates", where independent interpreters can be loaded in the same
// process, just not sharing objects with each other.
//
void Startup_Task(void)
{
Trace_Level = 0;
Saved_State = 0;
Eval_Cycles = 0;
Eval_Dose = EVAL_DOSE;
Eval_Count = Eval_Dose;
Eval_Signals = 0;
Eval_Sigmask = ALL_BITS;
Eval_Limit = 0;
TG_Ballast = MEM_BALLAST; // or overwritten by debug build below...
TG_Max_Ballast = MEM_BALLAST;
#ifndef NDEBUG
const char *env_recycle_torture = getenv("R3_RECYCLE_TORTURE");
if (env_recycle_torture and atoi(env_recycle_torture) != 0)
TG_Ballast = 0;
if (TG_Ballast == 0) {
printf(
"**\n" \
"** R3_RECYCLE_TORTURE is nonzero in environment variable!\n" \
"** (or TG_Ballast is set to 0 manually in the init code)\n" \
"** Recycling on EVERY evaluator step, *EXTREMELY* SLOW!...\n" \
"** Useful in finding bugs before you can run RECYCLE/TORTURE\n" \
"** But you might only want to do this with -O2 debug builds.\n"
"**\n"
);
fflush(stdout);
}
#endif
// The thrown arg is not intended to ever be around long enough to be
// seen by the GC.
//
Prep_Non_Stack_Cell(&TG_Thrown_Arg);
#if !defined(NDEBUG)
SET_END(&TG_Thrown_Arg);
Prep_Non_Stack_Cell(&TG_Thrown_Label_Debug);
SET_END(&TG_Thrown_Label_Debug); // see notes, only used "SPORADICALLY()"
#endif
Startup_Raw_Print();
Startup_Scanner();
Startup_String();
}
#if !defined(NDEBUG)
//
// The C language initializes global variables to zero: