-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathroman2.c
6172 lines (5706 loc) · 153 KB
/
roman2.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
// THE ROMAN II PROGRAMMING LANGUAGE
//
// COPYRIGHT (C) 2021-2022 GUSTAV LOUW. ALL RIGHTS RESERVED.
// THIS WORK IS LICENSED UNDER THE TERMS OF THE MIT LICENSE.
// THIS WORK IS A MATTER OF FICTION - WRITING A PROGRAMMING
// LANGUAGE INTENDED TO SOLVE LEETCODE MIGHT NOT YIELD NEW
// JOB PROSPECTS.
// Reader, hello! A high level overview of a program's structs
// is often enough to learn the heart of the machine so the code
// itself will be sparsely documented.
#include <dlfcn.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#include <stdarg.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
// Roman II (here in simply known as RR) uses the notion of a `value`
// for all of it's numerical computations, logic, and data storage.
typedef struct Value Value;
// Values are bound by type, ranging from in-memory
// characters, floats, and containers like maps and queues,
// to pointers thereof (including that of function pointers)
// and persistent-memory file storage.
typedef enum
{
// Queues are growable arrays with O(1) front and back access.
TYPE_QUEUE,
// Maps associate a string values type to values.
// Char types reference strings.
TYPE_STRING,
TYPE_CHAR,
TYPE_MAP,
// Numbers are of standard double precision.
TYPE_NUMBER,
// Pointers may point to any value type, including function types.
TYPE_POINTER,
// Function types ensure other values cannot be executed.
TYPE_FUNCTION,
// File types grant read and write access to persistent storage.
TYPE_FILE,
// Booleans control control flow and logic bound operations -
// expressions do not short circuit.
TYPE_BOOL,
// Null types are useful when all other types fail.
TYPE_NULL,
}
Type;
// Queues are growable arrows, with O(1) front and back access
// emulating the functionality of C++'s std::deque.
typedef struct
{
#define QUEUE_BLOCK_SIZE (16)
void* value[QUEUE_BLOCK_SIZE];
int64_t a;
int64_t b;
}
Block;
typedef enum
{
FRONT, BACK
}
End;
typedef int64_t
(*Diff)(void*, void*);
typedef bool
(*Comp)(void*, void*);
typedef void
(*Kill)(void*);
typedef void*
(*Copy)(void*);
typedef struct
{
Block** block;
// Data structures with `kill` and `copy` pointers define per element
// free and copy semantics.
Kill kill;
Copy copy;
int64_t size;
int64_t blocks;
}
Queue;
// Strings are growable character arrays. `cap` accounts for the
// null byte terminator; `size` does not.
typedef struct
{
char* value;
int64_t size;
int64_t cap;
}
String;
// Character types reference a parent string. The livelihood of the
// parent string is guaranteed by the existence of the character.
typedef struct
{
Value* string;
char* value;
}
Char;
// Maps associate strings with value types. Maps are hash tables and
// link by node keys with the same hash. Nodes store the key.
typedef struct Node
{
struct Node* next;
String* key;
void* value;
}
Node;
typedef struct
{
Node** bucket;
Kill kill;
Copy copy;
int64_t size;
// The prime index indexes `Map_Primes`.
// Defaulting to -1, it grows by one with each rehash.
int64_t prime_index;
// Rehashes occur when the load factor is exceeded.
float load_factor;
}
Map;
static const int64_t
Map_Primes[] = {
2, 5, 11, 23, 47, 97, 199, 409, 823, 1741, 3739, 7517, 15173, 30727,
62233, 126271, 256279, 520241, 1056323, 2144977, 4355707, 8844859,
17961079, 36473443, 74066549, 150406843, 305431229, 620239453,
1259520799, 2557710269, 4294967291,
};
// Soft types include Function types, File types, and Pointer types.
//
// Function types store the assembly `address` of the function's
// instruction as well as the number of arguments (`size`) expected.
typedef struct
{
String* name;
int64_t size;
int64_t address;
}
Function;
// Files maintain their `path` and `mode` (eg. "rw") for debugging purposes.
typedef struct
{
String* path;
String* mode;
FILE* file;
}
File;
// Pointer types may hold any value type.
typedef struct
{
Value* value;
}
Pointer;
// Like the description in the `Type` enum, a value is one of a kind,
// realized by a union of all types.
typedef union
{
File* file;
Function* function;
Queue* queue;
Map* map;
String* string;
Char* character;
Pointer* pointer;
double number;
bool boolean;
}
Of;
struct Value
{
// The union can be identified with a `type` enum.
Type type;
Of of;
// RR is garbage collected, freeing allocations initially with
// reference counting `refs` and then with a naive mark-and-sweep
// run to free circular references.
int64_t refs;
// A value deemed `constant` can be skipped by the garbage collecter.
bool constant;
};
typedef enum
{
// Values are either globally accessible or accessible from the stack.
// A global value is loaded with different offsets than a stack value.
CLASS_VALUE_GLOBAL,
CLASS_VALUE_LOCAL,
// Functions are defined as either functions, function prototypes, or
// native function prototypes. Function prototypes serve to aid circular
// function references.
CLASS_FUNCTION,
CLASS_FUNCTION_PROTOTYPE,
// Native function prototypes define the name and number of arguments
// for functions residing in shared object libraries
// (barring name mangling ala C++).
CLASS_FUNCTION_PROTOTYPE_NATIVE,
}
Class;
// Meta information related to values of class - herein refered to as
// identifiers or `idents` - store global, local, or function location,
// class type, and the module file of origin.
typedef struct
{
String* path;
Class class;
// The `stack` value is simply a stack index.
int64_t stack;
}
Meta;
// RR files are compiled to assembly on a per-module basis.
// A sector of characters are streamed from persistent storage
// and stored within an internal buffer.
typedef struct
{
// The name, compilation line, and file, are kept for debugging purposes.
FILE* file;
String* name;
int64_t line;
// The current index of the buffer, and size (should the sector read be
// less than the module buffer size), is tracked.
int64_t index;
int64_t size;
#define MODULE_BUFFER_SIZE (512)
unsigned char buffer[MODULE_BUFFER_SIZE];
}
Module;
typedef struct
{
char* file;
int64_t line;
}
Debug;
typedef struct
{
// Should a new module be encountered at compile time the current
// compilation module is pushed to the back of the `modules` queue
Queue* modules;
// CC tracks global and local `identifiers` with a single map for
// all `modules` to prevent use before definition. The `included`
// map ensures no module is included twice.
Map* identifiers;
Map* included;
// Within `assembly` each opcode is three characters long.
Queue* assembly;
// Each line of assembly maps to an RR file line number and
// file name such that, during runtime, the virtual machine can print
// usable debug messages.
Queue* debug;
// File names are stored in the `files` map, and referenced by `debug`.
// This is done to reduce string allocations. The debug information is
// passed to the virtual machine at VM runtime.
Map* files;
// RR is written with a recursive descent compiler - read ahead tokens
// that unbalance the parser are stored back in the `unget` buffer and
// later reemployed.
String* unget;
// CC tracks the number of globals, locals, and labels for loads,
// stores, and jumps. Labels are rolling incremented and therefor unique.
int64_t globals;
int64_t locals;
int64_t labels;
}
CC;
typedef struct
{
int64_t pc;
int64_t sp;
int64_t address;
}
Frame;
typedef struct
{
String* label;
int64_t address;
}
Address;
// The virtual machine converts the assembly provided by CC into a stream
// of bytecode 64 bit unsigned `instructions` and a list (queue) of `data`
// values. The lower byte of an instruction is reserved for the opcode
// command; the remaining 7 bytes manifest to be either an index for a value
// in `data`, an index to a value on the `stack`, or an index to value in
// `instructions`.
typedef struct
{
uint64_t* instructions;
Queue* data;
Queue* stack;
// Prior to constructing the `data` stack, data values are initially
// stored in a map where their values are stored in key forms to
// prevent duplication.
Map* data_dups;
// Function calls store the previous function's frame information
// in a `frame` queue. Returning from a function returns to a
// previous function's frame.
Queue* frame;
// A function's return value is stored in a special `ret`
// return register.
Value* ret;
// Debug information previously built by CC is passed to the virtual
// machine. Should the VM execute an illegal operation, execution will
// halt, the virtual machine torn down, and the line and file number
// printed to stderr alongside any additional relevant crash
// information. The `addresses` list provides quick stack undwinding info
// with a binary search that maps the function address with function name.
Queue* debug;
Queue* addresses;
// The number of `instructions` is marked by `size`.
int64_t size;
// The current executing instruction is marked by the program counter `pc`.
int64_t pc;
// `sp_decs` is number of stack pointer decrements required to prepare the
// stack for the next function call. This occurs after the next
// function stack has been prepared.
int64_t sp_decs;
// `alloc_cap` marks the maximum number of value allocations allowed until
// a garbage collection mark-and-sweep run must be performed.
int64_t alloc_cap;
// `retno` is the return integer of the `Main` function that is returned
// to the operating system once the `done` flag is set.
int retno;
bool done;
}
VM;
// Garbage collection mark-and-sweep is performed with red-black (RB) trees.
typedef struct Link
{
struct Link* l; // Left.
struct Link* r; // Right.
struct Link* p; // Parent.
Value* value;
// 0: Red
// 1: Black
int64_t color;
}
Link;
// RB Trees are specifically named `Cache` as they serve only to cache
// value allocations.
typedef struct Cache
{
Link* root;
int64_t size;
}
Cache;
// A single global `GC_Alloc` captures all currently allocated values.
// At the time of mark-and-sweep, a new red-black tree is constructed
// holding all reachable parent values and their children originating
// from the vM's global and local stack. The difference between `GC_Alloc`
// and that which is reachable is considered garbage and must be collected.
static Cache* GC_Alloc;
// Streams mock a mix-in VM runtime compiler for converting string value
// types to values. Maps, queues, numbers, booleans, strings, and
// nulls are supported,
typedef struct
{
String* string;
// The virtual machine is a dependency, yielding debug messages
// if an error is encountered during string to value conversion.
VM* vm;
int64_t index;
int64_t line;
}
Stream;
// The OPCODES X-Macro expands into an `Opcode` enum, prefixing each opcode with
// the OPCODE_ prefix. This opcode also expands into a `Gen` (Generator) array
// which ensures each new added opcode has a matching executable function.
#define OPCODES /* X-MACRO */ \
X(Abs) /* Floating point absolute. */ \
X(Aco) /* Arccos - Inverse Cos trig function */ \
X(Add) /* Numeric addition. Concatenates queues, strings. Merges dicts */ \
X(All) /* Returns true if all values in queue are boolean true. */ \
X(And) /* Logical and - returns true if two expressions are true. */ \
X(Any) /* Returns true if any value in a queue is boolean true. */ \
X(Asi) /* Arcsin - Inverse Sin trig function. */ \
X(Asr) /* Assert - Aborts VM execution if boolean expression is false. */ \
X(Ata) /* Atan - Inverse Tan trig function. */ \
X(Brf) /* Branch if false - Branches to PC if expression is false. */ \
X(Bsr) /* Binary searches a queue and returns a pointer to an element. */ \
X(Cal) /* Calls a function and pushes the return value to the stack. */ \
X(Cel) /* Numeric ceil. */ \
X(Con) /* Makes a value and all its children constant. */ \
X(Cop) /* Copies a value and all of its children. */ \
X(Cos) /* Cos trig function. */ \
X(Del) /* Deletes a queue or string element by, or a map value by key. */ \
X(Div) /* Numeric division. */ \
X(Dll) /* Calls a function within a shared object library. */ \
X(Drf) /* Dereferences a pointer. */ \
X(End) /* Ends a program. Reserved for use as the last calling opcode. */ \
X(Eql) /* Returns true if two expressions are true. */ \
X(Exi) /* Returns true if a key exists within a map. */ \
X(Ext) /* Exits a program with an exit code. */ \
X(Flr) /* Numeric floor. */ \
X(Fls) /* Pops all stack values in the current fuction stack frame. */ \
X(Gar) /* Runs the garbage collector if alloc_cap is exceeded. */ \
X(Get) /* Returns a queue value by index or map value by key. */ \
X(Glb) /* Pushes global value to stack. Increments reference count. */ \
X(God) /* Returns true if a file successfully opened. */ \
X(Grt) /* Returns true if A is greater than B. */ \
X(Gte) /* Returns true if A is greater than or Equal to B. */ \
X(Idv) /* Integer numeric division. */ \
X(Imd) /* Integer numeric modulus. */ \
X(Ins) /* Inserts a value into a map. */ \
X(Jmp) /* Jumps to program address. */ \
X(Key) /* Returns the keys of a map. */ \
X(Len) /* Returns the length of a queue. */ \
X(Loc) /* Pushes local value to stack. Increments reference count. */ \
X(Lod) /* Pushes return register to stack. */ \
X(Log) /* Numerical Log. */ \
X(Lor) /* Logical or. Returns true if one of two expressions are true. */ \
X(Lst) /* Returns true if A is less than B. */ \
X(Lte) /* Returns true if A is less than or equal to B. */ \
X(Max) /* Returns A if A is greater than B, else B. */ \
X(Mem) /* Returns true if value A and B are the same value in memory. */ \
X(Min) /* Returns A if A is less than B, else B. */ \
X(Mod) /* Numerical modulus. */ \
X(Mov) /* Moves value A into value B. */ \
X(Mul) /* Multiplies two numeric values. */ \
X(Neq) /* Returns true if A is not equal to B. */ \
X(Not) /* Returns true if B is false, else true. */ \
X(Opn) /* Opens a file. Returns a file type. */ \
X(Pop) /* Removes a stack value. */ \
X(Pow) /* Numerical power-of. */ \
X(Prt) /* Prints a value. */ \
X(Psb) /* Appends a value to a queue. */ \
X(Psf) /* Prepends a value to a queue. */ \
X(Psh) /* Pushes a value to the stack. */ \
X(Ptr) /* Pushes a pointer of a value to the stack. */ \
X(Qso) /* Quick sorts a queue using a comparison function. */ \
X(Ran) /* Returns a random number. */ \
X(Red) /* Reads a file. Returns a string. */ \
X(Ref) /* Returns a values reference count. */ \
X(Ret) /* Returns from a function. */ \
X(Sav) /* Saves a value in the return register. */ \
X(Sin) /* Sin trig function. */ \
X(Slc) /* Returns a slice of array. The slice is a copy. */ \
X(Spd) /* Stack pointer decrement. */ \
X(Sqr) /* Numerical square root. */ \
X(Srd) /* Seed the random number generator. */ \
X(Sub) /* Numerical subtraction. Queue push front. String strcmp. */ \
X(Tan) /* Tan trig function. */ \
X(Tim) /* Microsecond uptime. */ \
X(Trv) /* Return from virtual call. */ \
X(Typ) /* Returns value type. */ \
X(Val) /* Converts a string to a value. */ \
X(Vrt) /* Virtual call a function pointer. */ \
X(Wrt) /* Writes a string to file. */
typedef enum
{
#define X(name) OPCODE_##name,
OPCODES
#undef X
}
Opcode;
typedef struct
{
char* mnemonic;
Opcode opcode;
void (*exec)(VM*, int64_t);
}
Gen;
#define X(name) static void VM_##name(VM*, int64_t);
OPCODES
#undef X
static const Gen Gens[] = {
#define X(name) { #name, OPCODE_##name, VM_##name },
OPCODES
#undef X
};
// The compiler exposes the following keywords. An RR program may call
// `name` as if it were a function to directly call a supported opcode.
typedef struct
{
char* name;
char* mnemonic;
int64_t args;
}
Keyword;
static const Keyword Keywords[] = {
{ "Abs", "Abs", 1 }, // Must be sorted by `name`.
{ "Acos", "Aco", 1 },
{ "All", "All", 1 },
{ "Any", "Any", 1 },
{ "Asin", "Asi", 1 },
{ "Assert", "Asr", 1 },
{ "Atan", "Ata", 1 },
{ "Bsearch", "Bsr", 3 },
{ "Ceil", "Cel", 1 },
{ "Cos", "Cos", 1 },
{ "Del", "Del", 2 },
{ "Exists", "Exi", 2 },
{ "Exit", "Ext", 1 },
{ "Floor", "Flr", 1 },
{ "Good", "God", 1 },
{ "Keys", "Key", 1 },
{ "Len", "Len", 1 },
{ "Log", "Log", 1 },
{ "Max", "Max", 2 },
{ "Min", "Min", 2 },
{ "Open", "Opn", 2 },
{ "Pow", "Pow", 1 },
{ "Print", "Prt", 1 },
{ "Qsort", "Qso", 2 },
{ "Rand", "Ran", 0 },
{ "Read", "Red", 2 },
{ "Refs", "Ref", 1 },
{ "Sin", "Sin", 1 },
{ "Sqrt", "Sqr", 1 },
{ "Srand", "Srd", 1 },
{ "Tan", "Tan", 1 },
{ "Time", "Tim", 0 },
{ "Type", "Typ", 1 },
{ "Value", "Val", 1 },
{ "Write", "Wrt", 2 },
};
// Lastly, command line arguments allow *NIX-like systems to pass
// arguments to RR.
typedef struct
{
char* entry;
// -d: Dumps program assembly. Does not run the program.
bool dump;
// -h: Displays the help screen.
bool help;
}
Args;
// Wrappers for `malloc`, `realloc`, `free`, and `calloc` all
// specific platforms to implement their own allocators.
static void*
Malloc(int64_t size)
{
return malloc(size);
}
static void*
Realloc(void *ptr, int64_t size)
{
return realloc(ptr, size);
}
static void
Free(void* pointer)
{
free(pointer);
}
static void*
Calloc(int64_t nmemb, int64_t size)
{
return calloc(nmemb, size);
}
// Explanations on RB Tree implementations can be found on Wiki:
// https://en.wikipedia.org/wiki/Red-black_tree
static Link*
Link_Min(Link* self)
{
if(self != NULL)
while(self->l)
self = self->l;
return self;
}
static Link*
Link_Max(Link* self)
{
if(self != NULL)
while(self->r)
self = self->r;
return self;
}
static Link*
Link_Next(Link* self)
{
if(self->r)
{
self = self->r;
while(self->l)
self = self->l;
}
else
{
Link* parent = self->p;
while(parent && self == parent->r)
{
self = parent;
parent = parent->p;
}
self = parent;
}
return self;
}
static Cache*
Cache_Init(void)
{
Cache* self = Malloc(sizeof(*self));
self->root = NULL;
self->size = 0;
return self;
}
static int64_t
Link_Color(Link* self)
{
return self ? self->color : 1;
}
static bool
Link_IsBlk(Link* self)
{
return Link_Color(self) == 1;
}
static bool
Link_IsRed(Link* self)
{
return Link_Color(self) == 0;
}
static Link*
Link_Grandfather(Link* self)
{
return self->p->p;
}
static Link*
Link_Sibling(Link* self)
{
if(self == self->p->l)
return self->p->r;
else
return self->p->l;
}
static Link*
Link_Uncle(Link* self)
{
return Link_Sibling(self->p);
}
static Link*
Link_Init(Value* value, int64_t color)
{
Link* self = (Link*) Malloc(sizeof(Link));
self->value = value;
self->color = color;
self->l = self->r = self->p = NULL;
return self;
}
static int
Cache_Comp(Value* a, Value* b)
{
return (a == b) ? 0 : (a < b) ? -1 : 1;
}
static Link*
Cache_At(Cache* self, Value* value)
{
Link* link = self->root;
while(link)
{
int64_t diff = Cache_Comp(value, link->value);
if(diff == 0)
return link;
else
if(diff < 0)
link = link->l;
else
link = link->r;
}
return NULL;
}
static void
Link_Replace(Cache* self, Link* a, Link* b)
{
if(a->p)
{
if(a == a->p->l)
a->p->l = b;
else
a->p->r = b;
}
else
self->root = b;
if(b)
b->p = a->p;
}
static void
Cache_RotateL(Cache* self, Link* link)
{
Link* r = link->r;
Link_Replace(self, link, r);
link->r = r->l;
if(r->l)
r->l->p = link;
r->l = link;
link->p = r;
}
static void
Cache_RotateR(Cache* self, Link* link)
{
Link* l = link->l;
Link_Replace(self, link, l);
link->l = l->r;
if(l->r)
l->r->p = link;
l->r = link;
link->p = l;
}
static void
Cache_Set1(Cache*, Link*),
Cache_Set2(Cache*, Link*),
Cache_Set3(Cache*, Link*),
Cache_Set4(Cache*, Link*),
Cache_Set5(Cache*, Link*);
static Link*
Cache_Set(Cache* self, Value* value)
{
Link* insert = Link_Init(value, 0);
if(self->root)
{
Link* link = self->root;
while(1)
{
int64_t diff = Cache_Comp(value, link->value);
if(diff == 0)
{
Free(insert);
return NULL;
}
else
if(diff < 0)
{
if(link->l)
link = link->l;
else
{
link->l = insert;
break;
}
}
else
{
if(link->r)
link = link->r;
else
{
link->r = insert;
break;
}
}
}
insert->p = link;
}
else
self->root = insert;
Cache_Set1(self, insert);
self->size += 1;
return insert;
}
static void
Cache_Set1(Cache* self, Link* link)
{
if(link->p)
Cache_Set2(self, link);
else
link->color = 1;
}
static void
Cache_Set2(Cache* self, Link* link)
{
if(Link_IsBlk(link->p))
return;
else
Cache_Set3(self, link);
}
static void
Cache_Set3(Cache* self, Link* link)
{
if(Link_IsRed(Link_Uncle(link)))
{
link->p->color = 1;
Link_Uncle(link)->color = 1;
Link_Grandfather(link)->color = 0;
Cache_Set1(self, Link_Grandfather(link));
}
else
Cache_Set4(self, link);
}
static void
Cache_Set4(Cache* self, Link* link)
{
if(link == link->p->r && link->p == Link_Grandfather(link)->l)
{
Cache_RotateL(self, link->p);
link = link->l;
}
else
if(link == link->p->l && link->p == Link_Grandfather(link)->r)
{
Cache_RotateR(self, link->p);
link = link->r;
}
Cache_Set5(self, link);
}
static void
Cache_Set5(Cache* self, Link* link)
{
link->p->color = 1;
Link_Grandfather(link)->color = 0;
if(link == link->p->l && link->p == Link_Grandfather(link)->l)
Cache_RotateR(self, Link_Grandfather(link));
else
Cache_RotateL(self, Link_Grandfather(link));
}
static void
Cache_Del1(Cache*, Link*),
Cache_Del2(Cache*, Link*),
Cache_Del3(Cache*, Link*),
Cache_Del4(Cache*, Link*),
Cache_Del5(Cache*, Link*),
Cache_Del6(Cache*, Link*);
static void
Cache_DelLink(Cache* self, Link* link)
{
if(link->l && link->r)
{
Link* pred = Link_Max(link->l);
Value* temp = link->value;
link->value = pred->value;
pred->value = temp;
link = pred;
}
Link* child = link->r ? link->r : link->l;
if(Link_IsBlk(link))
{
link->color = Link_Color(child);
Cache_Del1(self, link);
}
Link_Replace(self, link, child);
if(link->p == NULL && child)
child->color = 1;
Free(link);
self->size -= 1;
}
static void
Cache_Del(Cache* self, Value* value)
{
Link* link = Cache_At(self, value);
if(link)
Cache_DelLink(self, link);
}
static void
Cache_Del1(Cache* self, Link* link)
{
if(link->p)
Cache_Del2(self, link);
}
static void
Cache_Del2(Cache* self, Link* link)
{
if(Link_IsRed(Link_Sibling(link)))
{
link->p->color = 0;
Link_Sibling(link)->color = 1;
if(link == link->p->l)
Cache_RotateL(self, link->p);
else
Cache_RotateR(self, link->p);
}
Cache_Del3(self, link);
}
static void
Cache_Del3(Cache* self, Link* link)
{
if(Link_IsBlk(link->p)
&& Link_IsBlk(Link_Sibling(link))
&& Link_IsBlk(Link_Sibling(link)->l)
&& Link_IsBlk(Link_Sibling(link)->r))
{
Link_Sibling(link)->color = 0;
Cache_Del1(self, link->p);
}
else
Cache_Del4(self, link);
}
static void
Cache_Del4(Cache* self, Link* link)
{
if(Link_IsRed(link->p)
&& Link_IsBlk(Link_Sibling(link))
&& Link_IsBlk(Link_Sibling(link)->l)
&& Link_IsBlk(Link_Sibling(link)->r))
{
Link_Sibling(link)->color = 0;
link->p->color = 1;
}
else
Cache_Del5(self, link);
}
static void
Cache_Del5(Cache* self, Link* link)
{
if(link == link->p->l
&& Link_IsBlk(Link_Sibling(link))
&& Link_IsRed(Link_Sibling(link)->l)
&& Link_IsBlk(Link_Sibling(link)->r))
{
Link_Sibling(link)->color = 0;
Link_Sibling(link)->l->color = 1;
Cache_RotateR(self, Link_Sibling(link));
}
else
if(link == link->p->r
&& Link_IsBlk(Link_Sibling(link))
&& Link_IsRed(Link_Sibling(link)->r)
&& Link_IsBlk(Link_Sibling(link)->l))
{
Link_Sibling(link)->color = 0;
Link_Sibling(link)->r->color = 1;
Cache_RotateL(self, Link_Sibling(link));
}
Cache_Del6(self, link);
}
static void
Cache_Del6(Cache* self, Link* link)
{
Link_Sibling(link)->color = Link_Color(link->p);
link->p->color = 1;
if(link == link->p->l)
{
Link_Sibling(link)->r->color = 1;
Cache_RotateL(self, link->p);
}