-
Notifications
You must be signed in to change notification settings - Fork 2
/
s9core.txt
2091 lines (1518 loc) · 74.9 KB
/
s9core.txt
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
================================================================
| S9CORE |
| A Toolkit for Implementing Dynamic Languages |
| Mk IVc |
================================================================
Nils M Holm, 2007-2018
In the public domain
If your country does not have a public domain, the CC0 applies:
https://creativecommons.org/share-your-work/public-domain/cc0/
----------------------------------------------------------------
RATIONALE
----------------------------------------------------------------
Dynamic languages typically require some basic infrastructure
that is common in their implementations, including
- garbage collection
- primitive functions
- dynamic type checking
- bignum arithmetics"
- heap images
S9core offers all of the above, and some more, in a single
object file that can be linked against a dynamic language
implementation. It takes care of all the nitty gritty stuff and
allows the implementor to focus on the design of the language
itself.
----------------------------------------------------------------
FEATURES
----------------------------------------------------------------
- Precise, constant-space, stop-the-world garbage collection
with vector pool compaction (defragmentation) and finalization
of I/O ports
- Non-copying GC, all nodes stay in their original locations
- Bignum (unbounded-precision) integer arithmetics
- Decimal-based, platform-independent real number arithmetics
- Persistent heap images
- Type-checked primitive functions
- Symbol identity
- Memory allocation on heap exclusively (no malloc() until the
heap grows)
- A basis for implementing interpreters, runtime libraries, etc
- Statically or dynamically linked
- A system() function for Plan 9
- Available on Unix, Plan 9, and in C89/POSIX environments
----------------------------------------------------------------
REFERENCE MANUAL
----------------------------------------------------------------
===== SETUP AND NAMESPACE ======================================
A module that intends to use the S9core tool kit must include
the S9core header using
#include <s9core.h>
As of Mk II, the tool kit has a separate name space which is
implemented by beginning all symbol names with a
S9_ or s9_
prefix. However, many symbols can be "imported" by adding
#include <s9import.h>
Doing so will create aliases of most definitions with the prefix
removed, so you can write, for instance:
cons(a, cons(b, NIL))
instead of
s9_cons(a, s9_cons(b, S9_NIL))
There are some symbol names that will not have aliases, mostly
tunable parameters of s9core.h. Those names will print with
their prefixes in this text. All other names will have their
prefixes removed.
When a module wants to use S9core functions without importing
them, the following rules apply:
A lower-case function or macro name is prefixed with s9_, e.g.
bignum_add() becomes s9_bignum_add().
A capitalized function or macro name has its first letter
converted to lower case and an S9_ prefix attached, e.g.:
Real_exponent becomes S9_real_exponent.
An upper-case symbol gets an S9_ prefix, e.g.: NIL becomes
S9_NIL.
----- S9_VERSION -----------------------------------------------
The S9_VERSION macro expands to a string holding the S9core
version in "YYYYMMDD" (year, month, day) format.
===== C-LEVEL DATA TYPES =======================================
At C level, there are only two data types in S9core. Dynamic
typing is implemented by adding type tags to objects on the heap.
----- cell -----------------------------------------------------
A "cell" is a reference to an object on the heap. All objects
are addressed using cells. A cell is wide enough to hold an
offset to any object on the heap.
As of S9core Mk IV, the preferred cell type is "int", even in
64-bit environments. Use of 64-bit types can be forced by
compiling S9core with the S9_BITS_PER_WORD_64 definition, but
doing so is discouraged, because it increases the size of the
heap significantly and has little benefits.
Example: cell x, y;
----- PRIM (struct S9_primitive) -------------------------------
A PRIM is a structure containing information about a primitive
procedure:
struct S9_primitive {
char *name;
cell (*handler)(cell expr);
int min_args;
int max_args;
int arg_types[3];
};
The name field names the primitive procedure. The handler is
a pointer to a function from cell to cell implementing the
primitive function. Because a cell may reference a list or
vector, functions may in fact have any number of arguments
(and, for that matter, return values).
The min_args, max_args, and arg_types[] fields define the type
of the primitive function. min_args and max_args specify the
expected argument count. When they are equal, the argument count
is fixed. When max_args is less then zero, the function accepts
any number of arguments that is greater than or equal to
min_args.
The arg_types[] array holds the type tags of the first three
argument of the primitive. Functions with more than three
arguments must check additional arguments internally. Unused
argument slots can be set to T_ANY (any type accepted).
Example:
PRIM Prims[] = {
{ "cons", p_cons, 2, 2, { T_ANY, T_ANY, T_ANY } },
{ "car", p_car, 1, 1, { T_PAIR, T_ANY, T_ANY } },
{ "cdr", p_cdr. 1, 1, { T_PAIR, T_ANY, T_ANY } },
{ NULL }
};
Where p_cons, p_car, and p_cdr are the functions implementing
the corresponding primitives.
===== CALLING CONVENTIONS ======================================
All S9core functions protect their parameters from the garbage
collector so it is safe, for example, to write
make_real(1, 0, make_integer(x));
or
cell n = cons(c, NIL);
n = cons(b, n);
n = cons(a, n);
In the first case, the integer created by make_integer() will
be protected in the application of make_real(). In the second
example, the object /c/ will be protected in the first call,
and the list /n/ will be protected in all subsequent applications
cons(). Note that the objects /b/ and /a/ are not protected
during the first call and /a/ is not protected during the second
call, though.
Use save() and unsave() to protect objects temporarily.
===== INITIALIZATION AND SHUTDOWN ==============================
----- void s9_init(cell **extroots, cell *stk, int *ptr); ------
The s9_init() function initializes the memory pools, connects
the first three I/O ports to stdin, stdout, and stderr, and sets
up the internal S9core structures. It must be called before any
other S9core functions can be used.
The extroots parameter is a pointer to an array of addresses of
cells that will be protected from the garbage collector (the
so-called "GC roots"). The last array member must be NULL.
Because cells can reference trees, lists, or vectors, larger
structures may be protected from GC by including their handles
in this array.
The stk (stack) and ptr (stack pointer) parameters specify a
stack and stack pointer that will be managed by the S9 garbage
collector. The stack must be an S9 vector and the stack pointer
must be a C integer. Objects on the stack between (and including)
zero and ptr will be protected from the GC. That is, a ptr value
of -1 indicates that the stack is empty.
The stack vector stk itself must also included in the extroots
parameter in order to protect it from GC recycling.
When a stack is used, it should be set to NIL before calling
s9_init(). When no stack is to be used, both stk and ptr should
be NULL.
Example:
#define STACK_SIZE 1000
cell Environment;
cell *GC_roots[] = { &Environment, &Stack, NULL };
cell Stack = NIL;
int Ptr = -1;
...
s9_init(GC_roots, &Stack, &Ptr);
Stack = make_vector(STACK_SIZE);
----- void s9_fini(void); --------------------------------------
The s9_fini() function shuts down S9core and releases all memory
allocated by it. This function is normally never called, because
clean-up is done by the operating system.
The only reason to call it is to prepare for the
re-initialization of the toolkit, for example to
recover from a failed image load (see load_image()).
----- void s9_abort(void); -------------------------------------
----- void s9_reset(void); -------------------------------------
The s9_abort() function will set an internal flag in the S9core
toolkit that aborts complex operations like bignum arithmetics
early and attempts to return to the caller as soon as possible.
It should be set when handling an error at the level of the
language being implemented on top of S9core.
s9_reset() resets the abort condition. It should be called when
recovering from an error condition and before using any other
S9core functions. Otherwise erroneous results will be delivered.
----- void fatal(char *msg); -----------------------------------
This function prints the given message and then aborts program
execution.
----- MEMORY ALLOCATION ----------------------------------------
----- S9_NODE_LIMIT --------------------------------------------
----- S9_VECTOR_LIMIT ------------------------------------------
The S9_NODE_LIMIT and S9_VECTOR_LIMIT constants specify the
maximum sizes of the node pool and the vector pool, respectively.
The "pools" are used to allocate objects at run time. Their
sizes are measured in "nodes" for the node pool and cells for
the vector pool. Both sizes default to 14013 times 1024
(14,013K).
The size of a cell is the size of a pointer on the host
platform. The size of a node is two cells plus a char. So the
total node memory limit using the default settings on a 32-bit
or 64-bit host would be:
14013 times 1024 times (2 times 4+1) = 129,143,808 bytes
The default vector pool limit would be:
14013K cells = 57,397,248 bytes
The sizes grow significantly when using a 64-bit version of
S9core (which is not recommended), as can be seen on the
section on set_node_limit(), below.
At run time, the S9core toolbox will /never/ allocate more
memory than the sum of the above (plus the small amount
allocated to primitive functions at initialization time).
When S9core runs out of memory, it will print a message and
terminate program execution. However, a program can request to
handle memory allocation failure itself by passing a handler to
the mem_error_handler() function (further explanations can be
found below).
The amount allocated to S9core can be changed by the user.
See the set_node_limit() and set_vector_limit() functions for
details.
----- void mem_error_handler(void (*h)(int src)); --------------
When a function pointer is passed to mem_error_handler(), S9core
will no longer terminate program execution when a node or vector
allocation request fails. The request will /succeed/ and the
function passed to mem_error_handler() will be called.
****************************************************************
The function is then required to handle the error as soon as
possible, for example by interrupting program execution and
returning to the REPL, or by signaling an exception.
****************************************************************
The integer argument passed to a memory error handler will
identify the source of the error: 1 denotes the node allocator
and 2 indicates the vector allocator.
Allocation requests can still succeed in case of a low memory
condition, because S9core never allocates more than 50% of each
pool. (This is done, because using more than half of a pool will
result in GC thrashing, which would reduce performance
dramatically.)
As soon as a memory error handler has been invoked, thrashing
/will/ start immediately. Program execution will slow down to a
crawl and eventually the allocator will fail to recover from a
low-memory condition and kill the process, even with memory
error handling enabled.
The default handler (which just terminates program execution)
can be reinstalled by passing NULL to mem_error_handler().
----- void set_node_limit(int k); ------------------------------
These functions modify the node pool and vector pool memory
limits. The value passed to the function will become the new
limit for the respective pool. The limits must be set up
immediately after initialization and may not be altered once
set. Limits are specified in kilo nodes, i.e. they will be
multiplied by 1024 internally.
Setting either value to zero will disable the corresponding
memory limit, i.e. S9core will grow the memory pools
indefinitely until physical memory allocation fails. This may
cause massive swapping in memory-heavy applications.
S9core memory pools both start with a size of 32768 units
(S9_INITIAL_SEGMENT_SIZE constant) and grow exponentially to
a base of 3/2. With the default settings, the limit will be
reached after growing either pool for 15 times.
Note that actual memory limits all have the form 32768 * 1.5^n,
so a limit that is not constructed using the above formula will
probably be smaller than expected. Reasonable memory limits
(using the default segment size) are listed in figure 1.
As can be seen in the table, the minimal memory footprint of
S9core is 416K bytes on 32-bit and 800K bytes on 64-bit system
using a 64-bit version of S9core (the default is to use a 32-bit
version even on 64-bit systems). In order to obtain a smaller
initial memory footprint, the S9_INITIAL_SEGMENT_SIZE constant
has to be reduced and the table in figure 1 has to be
recalculated.
Limit 64-bit memory 32-bit memory
--------- ------------- -------------
32 800K 416K
48 1200K 625K
72 1800K 937K
108 2700K 1405K
162 4050K 2107K
243 6075K 3160K
364 9100K 4733K
546 14M 7089K
820 21M 11M
1,230 31M 16M
1,846 46M 24M
2,768 69M 36M
4,152 104M 54M
6,228 156M 81M
9,342 234M 121M
---------------------------------------
14,013 350M 182M
---------------------------------------
21,019 525M 273M
31,529 788M 410M
47,293 1182M 615M
70,939 1773M 922M
106,409 2660M 1383M
159,613 3990M 2075M
239,419 5985M 3112M
359,128 8978M 4669M
538,692 13G 7003M
808,038 20G 10G
1,212,057 30G 16G
1,818,085 45G 24G
2,727,127 68G 35G
4,090,690 102G 53G
6,136,034 153G 80G
---------------------------------------
Fig 1. Memory Limits
----- ARITHMETICS ----------------------------------------------
----- S9_DIGITS_PER_CELL ---------------------------------------
----- S9_INT_SEG_LIMIT -----------------------------------------
S9_DIGITS_PER_CELL is the number of decimal digits that can be
represented by a cell and S9_INT_SEG_LIMIT is the smallest
integer that can /not/ be represented by an "integer segment"
(which has the size of one cell). The integer segment limit is
equal to 10^S9_DITIGS_PER_CELL.
A cell is called an integer segment in S9core arithmetics,
because numbers are represented by chains of cells (segments).
The practical use of the S9_INT_SEG_LIMIT constant is that
bignums that are smaller than this limit can be converted to
(long) integers just be extracting their first segment.
These values are /not/ tunable. S9_DIGITS_PER_CELL is 9 on both
32-bit and 64-bit machines and (theoretically) 4 on 16-bit
machines. It can be extended to 18 by compiling a 64-bit
version of S9core (using S9_BITS_PER_WORD_64), but doing so
is not recommended.
----- S9_MANTISSA_SEGMENTS -------------------------------------
----- S9_MANTISSA_SIZE -----------------------------------------
S9_MANTISSA_SEGMENTS his is the number of integer segments (see
above) in the mantissae of real numbers. The default is two
segments (18 digits) on both 32-bit and 64-bit platforms. When
doing a 64-bit build, the default is one segment (which is also
18 digits). Each additional mantissa segment increases precision
by S9_DIGITS_PER_CELL (see above), but also slows down real
number computations.
This is a compile-time option and cannot be tweaked at run time.
S9_MANTISSA_SIZE is the number of decimal digits in a mantissa.
It is used in the computation of various values, such as Epsilon.
===== S9CORE TYPES =============================================
S9core data types are pretty LISP- or Scheme-centric, but most
of them can be used in a variety of languages.
Each type may be associated with a predicate testing for the
type, an allocator creating an object of the given type, and one
or more accessors that extract values from the type. Predicates
always return 0 (false) or 1 (true). Type predicates succeed
(return 1) if the object passed to them is of the given type.
----- SPECIAL VALUES -------------------------------------------
Special values are constant, unique, can be compared with ==,
and have no allocators.
................................................................
Type: NIL
Predicate: x == NIL
NIL ("Not In List") denotes the end of a list, an empty list,
or an empty return value. For example, to create a list of the
objects /a/, /b/, and /c/, the following S9core code would be
used:
cell list = cons(c, NIL);
list = cons(b, list);
list = cons(a, list);
See also: T_LIST
................................................................
Type: END_OF_FILE
Predicate: eof_p(x)
x == END_OF_FIL
END_OF_FILE is an object that is reserved for indicating the end
of file when reading from an input source. The eof_p() predicate
returns truth only for the END_OF_FILE object.
................................................................
Type: UNDEFINED
Predicate: undefined_p(x)
x == UNDEFINED
The UNDEFINED value is returned by a function to indicate that
its value for the given arguments is undefined. For example,
bignum_divide(One, Zero)
would return UNDEFINED.
................................................................
Type: UNSPECIFIC
Predicate: unspecific_p(x)
x == UNSPECIFIC
The UNSPECIFIC value can be returned by functions to
indicate that their return value is of no importance
and should be ignored.
................................................................
Type: USER_SPECIALS
Predicate: special_p()
When more special values are needed, they should be assigned
/decreasing/ values starting at the value of the USER_SPECIALS
constant. The predicate special_p() will return truth for all
special values, including user-defined ones.
Examples:
#define TOP (USER_SPECIALS-0)
#define BOTTOM (USER_SPECIALS-1)
................................................................
Type: VOID
Predicate: x == VOID
VOID denotes the absence of a value. While UNSPECIFIC is
typically /returned/ by a function to indicate that its
value is uninteresting, VOID may be /passed/ to a function
to indicate that the corresponding argument may be ignored.
----- TAGGED TYPES ---------------------------------------------
A "tagged" object is a compound data object (pair, tree) with a
type tag in its first slot. Tagged objects typically carry some
payload, such as an integer value, an I/O port, or a symbol name.
The internal structure of a tagged object does not matter; it is
created using an allocator function and its payload is accessed
using one or multiple accessor functions.
----- type_tag(x) ----------------------------------------------
The type_tag() accessor extracts the type tag, like T_BOOLEAN or
T_INTEGER, from the given object. When the object does not have
a type tag, it returns a special value, T_NONE.
................................................................
Type: T_ANY
When used in a PRIM structure, this type tag matches any other
type (i.e. the described primitive procedure will accept any
type in its place).
................................................................
Type: T_BOOLEAN
Allocator: TRUE, FALSE
Predicate: boolean_p(x)
The TRUE and FALSE objects denote logical truth and falsity.
................................................................
Type: T_CHAR
Allocator: make_char(int c)
Predicate: char_p(x)
Accessor: int char_value(x)
T_CHAR objects store single characters. The make_char() function
expects the character to store, and char_value() retrieves the
character.
Example:
make_char('x')
................................................................
Type: T_FIXNUM
Allocator: mkfix(int c)
Predicate: fix_p(x)
Accessor: int fixval(x)
T_FIXNUM objects store C int's. The mkfix() function expects
the value to store, and fixval() retrieves the value. Fixnums
are only used to store integer values in S9core data structures.
S9core does not define any operations on fixnums.
Example:
mkfix(123)
................................................................
Type: T_INPUT_PORT
Allocator: make_port(int portno, T_INPUT_PORT)
Predicate: input_port_p(x)
Accessor: int port_no(x)
The make_port() allocator boxes a port handle. The port handle
must be obtained by one of the I/O routines before passing it
to this function. port_no() returns the port handle stored in
an T_INPUT_PORT (or T_OUTPUT_PORT) object.
Example:
cell p = open_input_port(path);
if (p >= 0) return make_port(p, T_INPUT_PORT);
................................................................
Type: T_INTEGER
Allocator: make_integer(cell segment)
int_to_bignum(int x)
Predicate: integer_p(x)
small_int_p(x)
Accessor: cell bignum_to_int(cell x, int *of)
small_int_value(x)
The make_integer() function creates a single-segment bignum
integer in the range from
-10^S9_DITIGS_PER_CELL + 1 to 10^S9_DITIGS_PER_CELL - 1
The int_to_bignum() function creates a bignum integer with
any integer value. It is not as efficient as make_integer(),
but covers the whole range of C int's.
To create even larger bignum integers, the string_to_bignum()
function has to be used.
The bignum_to_int() accessor returns the value of a bignum
integer X, if the bignum is in the range from INT_MIN to
INT_MAX. There is no way to convert bignums outside of this
range to a native C type.
The integer pointed to by "of" serves as an overflow indicator.
When it is set to 0 when bignum_to_int() returns, the function
returned a valid int. When it is set to 1, the conversion
failed and the result must be discarded.
The small_int_p() predicate returns 1, if its argument is a
single-segment integer as created by make_integer(). The value
of such an integer can be extracted more efficiently by using
the small_int_value() accessor.
****************************************************************
Neither bignum_to_int() nor int_to_bignum() work in 64-bit mode,
because integer segments are too long there. Both will fail with
a fatal error in 64-bit mode.
****************************************************************
Example:
cell x = make_integer(-12345);
int i = bignum_to_int(x);
................................................................
Type: T_LIST
T_PAIR
Allocator: cons(cell car_val, cell cdr_val)
Predicate: pair_p(x)
Accessor: cell car(x)
cell cdr(x)
The difference between the T_PAIR and T_LIST type tags is that
T_LIST also includes NIL, which T_PAIR does not. Both type tags
are used for primitive procedure type checking exclusively.
The cons() allocator returns an ordered pair of any two values.
It is in fact an incarnation of the LISP function of the same
name. The accessors car() and cdr() retrieve the first and
second value from a pair, respectively.
pair_p() succeeds for pairs created by cons().
T_LIST corresponds to
pair_p(x) || x == NIL
Further accessors, like caar() and friends, are also available
and will be explained later in this text.
Example:
cons(One, NIL); /* list */
cell x = cons(One, Two); /* pair */
car(x); /* One */
cdr(x); /* Two */
................................................................
Type: T_OUTPUT_PORT
Allocator: make_port(int portno, T_OUTPUT_PORT)
Predicate: output_port_p(x)
Accessor: int port_no(x)
See T_INPUT_PORT, above, for details.
Example:
make_port(port_no, T_OUTPUT_PORT);
................................................................
Type: T_PRIMITIVE
Allocator: make_primitive(PRIM *p)
Predicate: primitive_p(x)
Accessor: int prim_slot(x)
int prim_info(x)
The make_primitive() function allocates a slot in an internal
primitive function table, fills in the information in the given
PRIM structure, and returns a primitive function object
referencing that table entry. The prim_info() function retrieves
the stored information (as a PRIM *).
The prim_slot() accessor returns the slot number allocated for a
given primitive function object in the internal table. Table
offsets can be used to identify individual primitive functions.
See the discussion of the PRIM structure for an example of how
to set up a primitive function. Given the table shown there,
the following code would create the corresponding T_PRIMITIVE
objects:
for (i=0; p[i].name; i++) {
prim = make_primitive(&p[i]);
...
}
................................................................
Type: T_FUNCTION
Predicate: function_p(x)
Function objects are deliberately underspecified. The user
is required to define their own function object structure
and accessors.
For example, a LISP function allocator might look like this:
cell make_function(cell args, cell body, cell env) {
/* args and body should be GC-protected! */
cell fun = cons(env, NIL);
fun = cons(body, fun);
fun = cons(args, fun);
return new_atom(T_FUNCTION, fun);
}
Given the structure of this function object, the corresponding
accessors would look like this:
#define fun_args(x) (cadr(x))
#define fun_body(x) (caddr(x))
#define fun_env(x) (cadddr(x))
................................................................
Type: T_REAL
Allocator: make_real(int s, cell e, cell m)
Make_real(int f, cell e, cell m)
Predicate: real_p(x)
Accessor: cell real_mantissa(x)
cell real_exponent(x)
Real_flags(x)
A real number consists of three parts, a "mantissa" (the digits
of the number), an exponent (the position of the decimal point),
and a "flags" field, currently just containing the sign of the
number.
The value of a real number is
sign * mantissa * 10^exponent
The real_mantissa() and real_exponent() functions extract the
mantissa and exponent, respectively. When applied to a bignum
integer, the mantissa will be the number itself and the exponent
will always be 0.
Note that real_mantissa returns a bignum integer, but
real_exponent returns an unboxed, cell-sized integer.
The Real_flags() accessor can only be applied to real numbers.
It extracts the flags field.
The make_real() function is the principal real number allocator.
It expects a sign /s/ (-1 or 1), an exponent as single cell, and
a mantissa in the form of a bignum integer. When the mantissa is
too large, the function will return UNDEFINED.
Make_real() is a "quick and dirty" allocator. It expects a
flags field in the place of a sign, a chain of integer segments
instead of a bignum, and it does not perform any overflow
checking.
****************************************************************
Caution: This function can create an invalid real number!
****************************************************************
Examples:
cell m = make_integer(123);
cell r = make_real( 1, 0, m); /* 123 */
cell r = make_real( 1, 10, m); /* 1.23e+12 */
cell r = make_real(-1, -5, m); /* -0.00123 */
................................................................
Type: T_STRING
Allocator: make_string(char *s, int k)
Predicate: string_p(x)
Accessor: char *string(x)
int string_len(x)
The make_string() function creates a string of the length /k/
and initializes it with the content of /s/. When the length /n/
of /s/ is less than /k/, the last /k-n/ characters of the
resulting string object will be undefined.
Strings are counted /and/ NUL-terminated. The counted length of
a given string is returned by the string_len() function, the C
string length of /x/ is "strlen(string(x))" .
................................................................
The string() accessor returns a pointer to the char array
holding the string.
****************************************************************
Note: no string obtained by string() or symbol_name() may be
passed to make_string() as an initialization string, because
vector objects (including strings and symbols) may move during
heap compaction.
****************************************************************
The proper way to copy a string is
int k = string_len(source);
cell dest = make_string("", k-1);
memcpy(string(dest), string(source), k);
Alternatively, the copy_string() function may be used.
................................................................
Type: T_SYMBOL
Allocator: make_symbol(char *s, int k)
symbol_ref(char *s)
Predicate: symbol_p(x)\fP"
Accessor: char *symbol_name(x)
int symbol_len(x)
Typically, the symbol_ref() function is used to create or
reference a symbol. A symbol is a unique string with an identity
operation defined on it. I.e. referencing the same string twice
using symbol_ref() will return /the same symbol/. Hence symbols
can be compared using the == operator.
The make_symbol() function creates an uninterned symbol, i.e. a
symbol with no identity (which cannot be compared or referenced).
In a typical implementation, this function will not be used.
See the T_STRING description for further details and caveats.
Example:
cell sym = symbol_ref("foo");
................................................................
Type: T_SYNTAX
Predicate: syntax_p(x)
Like function objects, syntactic abstractions ("macros") are
deliberately underspecified. Typically, the value of a T_SYNTAX
object would be a T_FUNCTION object.
................................................................
Type: T_VECTOR
Allocator: make_vector(int k)
Predicate: vector_p(x)
Accessor: cell *vector(x)
int vector_len(x)
The make_vector() function returns a vector of /k/ elements
(slots) with all slots set to UNDEFINED.
vector() returns a pointer to the slots of the given vector,
vector_len() returns the number of slots.
Example:
cell v = make_vector(100);
save(v);
for (i=0; i<100; i++) {
x = make_integer(i);
vector(v)[i] = x;
}
unsave(1);
****************************************************************
Note: the result of vector() may not be used on the left side of
an assignment where the right side allocates any objects. When
in doubt, first assign the value to a temporary variable and
then the variable to the vector. For an explanation see T_STRING.
****************************************************************
................................................................
Type: T_CONTINUATION
Predicate: continuation_p(x)
A "continuation" object is used to store the value of a captured
continuation (as in Scheme's call/cc). Its implementation is
left to the user.
----- ADDITIONAL ALLOCATORS ------------------------------------
----- cell cons3(cell a, cell d, int t); -----------------------
The cons3() function is the principal node allocator of S9core.
It is like cons(), but has an additional parameter for the "tag"
field. The tag field of a node assigns specific properties to a
node. For example, it can turn a node into an "atom", a vector
reference, or an I/O port reference. In fact, cons() is a
wrapper around cons3() that supplies an empty (zero) tag field.
The most interesting user-level application of cons3() is maybe
the option to mix in a CONST_TAG in order to create an immutable
node. Note though, that immutability is not enforced by S9core
itself, because it never alters any nodes. However,
implementations using S9core can use the constant_p() predicate
to check for immutability.
Also note that "atoms" are typically created by the new_atom()
allocator, explained below.
----- cell copy_string(cell x); --------------------------------
This function creates an new string object with the same content
as the given string object.
----- new_atom(x, d) -------------------------------------------
----- atom_p(x) ------------------------------------------------
An "atom" is a node with its atom flag set. Unlike a "cons" node,
as delivered by cons(), an atom has no reference to another node
in its car field. Instead of a reference, it can carry any value
in the car field, for example: the character of a character
object, a bignum integer segment, or a type tag. The new_atom()
function expects any value in the /x/ parameter and a node
reference in the /d/ parameter.
Tagged S9core objects are composed of multiple atoms. For
example, the following program would create a "character"
object containing the character 'x' :
cell n = new_atom('x', NIL);
n = new_atom(T_CHAR, n);
(Don't do this, though; use make_char() instead!)
The atom_p() function checks whether the given node is an atom.
S9core atoms encompass all the special values (like NIL, TRUE,
END_OF_FILE, etc), all nodes with the atom flag set (including
all tagged types), and all vector objects (see below). In fact,
only "conses" (as delivered by cons()) are considered to be
non-atomic).
----- cell new_port(void); -------------------------------------
The new_port() function returns a handle to a port, but does not
assign any FILE to it. A file can be assigned by using the
return value of new_port() as an index to the Ports[] array. A
negative return value indicates failure (out of free ports).
Example:
int p = new_port();
if (p >= 0) {
Ports[p] = fopen(file, "r");
}
----- cell new_vec(cell type, int size); -----------------------
This function allocates a new vector. A vector object has a type
tag in its car field and a reference into the vector pool in its
cdr field, that is, neither of its fields reference any other
node. The /type/ parameter is the type tag to be installed in
the new vector atom and /size/ is the number /bytes/ to allocate
in the vector pool. The newly allocated segment of the vector
pool will be left uninitialized except when /type/ is T_VECTOR.
Slots of T_VECTOR objects will be initialized with NIL.
Example:
new_vec(T_STRING, 100);
new_vec(T_VECTOR, 100 * sizeof(cell));
----- save(n) --------------------------------------------------
----- cell unsave(int k); --------------------------------------
save() saves an object on the internal S9core stack and unsave(n)
removes /n/ elements from the stack and returns the one last
removed (i.e. the previously /n^th/ element on the stack).
The S9core stack is mostly used to protect objects from being
recycled by the GC.