-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlips.c
More file actions
3058 lines (2852 loc) · 87 KB
/
lips.c
File metadata and controls
3058 lines (2852 loc) · 87 KB
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
/* Lips - tiny Lisp interpreter designed for being embedded in games
*/
#include "assert.h"
#include "stdarg.h"
#include "stdio.h"
#include "string.h"
#include "lips.h"
/// CONSTANTS
// number of values in one bucket
#ifndef BUCKET_SIZE
#define BUCKET_SIZE 1024
#endif
// number buckets that Interpreter allocates by default
#ifndef NUM_DEFAULT_BUCKETS
#define NUM_DEFAULT_BUCKETS 16
#endif
/// LIST OF STRUCTS
typedef struct Bucket Bucket;
typedef struct Iterator Iterator;
typedef struct HashTable HashTable;
typedef struct Stack Stack;
typedef struct Node Node;
typedef struct Parser Parser;
typedef struct StringData StringData;
typedef struct Token Token;
typedef struct EvalState EvalState;
typedef struct StringPool StringPool;
typedef struct PListElem PListElem;
/// MACROS
#define MAX_CHUNKS 16
#define LIPS_EOF (-1)
#define STACK_INVALID_POS ((uint32_t)-1)
#define DEAD_MASK (1u<<31)
#define MARK_MASK (1<<30)
#define IS_DEAD(cell) ((cell).type & DEAD_MASK)
#define IS_WHITESPACE(c) ((c) == ' ' || (c) == '\n' || (c) == '\t' || (c) == '\r')
#define IS_SPECIAL_CHAR(c) ((c) == '(' || (c) == ')' || (c) == '\'' || (c) == '`')
#define IS_DIGIT(c) ((c) >= '0' && (c) <= '9')
#define LOG_ERROR(machine, ...) snprintf(machine->errbuff, sizeof(machine->errbuff), __VA_ARGS__)
#define TYPE_CHECK(machine, type, cell) if (!(GET_TYPE(cell) & (type))) LIPS_THROW_ERROR(machine, "Typecheck failed (%d & %d) at line %d", GET_TYPE(cell), type, __LINE__);
#define TYPE_CHECK_FORCED(type, cell) do { \
assert((GET_TYPE(cell) & (type)) && "Typecheck failed"); \
} while (0)
#define GET_STR(cell) ((cell)->data.str)
#define GET_STR_PTR(cell) GET_STR(cell)->data
#define GET_PLIST(cell) ((cell)->data.ht)
/// LIST OF FUNCTIONS
static void* DefaultAlloc(size_t bytes);
static void DefaultDealloc(void* ptr, size_t bytes);
static void* DefaultOpenFile(const char* file, size_t* datasize);
static void DefaultReadFile(void* filehandle, char* buffer, size_t bytes);
static void DefaultCloseFile(void* filehandle);
static Lips_Cell NewCell(Lips_Machine* interp) LIPS_HOT_FUNCTION;
static void DestroyCell(Lips_Machine* machine, Lips_Cell cell);
static StringData* StringCreateEmpty(Lips_Machine* machine, uint32_t n);
static StringData* StringCreate(Lips_Machine* machine, const char* str, uint32_t n);
static StringData* StringCreateWithHash(Lips_Machine* machine, const char* str, uint32_t n, uint32_t hash);
static void StringDestroy(Lips_Machine* machine, StringData* str);
static int StringEqual(const StringData* lhs, const StringData* rhs);
const char* GDB_lips_to_c_string(Lips_Machine* machine, Lips_Cell cell);
static void ParserInit(Parser* parser, const char* str, uint32_t len);
static int ParserNextToken(Parser* parser);
static int Lips_IsTokenNumber(const Token* token);
static Lips_Cell ParseNumber(Lips_Machine* machine, const Token* token);
static Lips_Cell GenerateAST(Lips_Machine* machine, Parser* parser);
static void CreateBucket(Lips_AllocFunc alloc, Bucket* bucket, uint32_t num_elmenents, uint32_t elem_size);
static void DestroyBucket(Lips_Machine* machine, Bucket* bucket, uint32_t elem_size);
static void* BucketNew(Bucket* bucket, uint32_t elem_size);
static void BucketDelete(Bucket* bucket, void* data, uint32_t elem_size);
static void CreateStack(Lips_AllocFunc alloc, Stack* stack, uint32_t size);
static void DestroyStack(Lips_DeallocFunc dealloc, Stack* stack);
static void StackGrow(Lips_AllocFunc alloc, Lips_DeallocFunc dealloc,
Stack* stack);
static void* StackRequire(Lips_AllocFunc alloc, Lips_DeallocFunc dealloc,
Stack* stack, uint32_t bytes);
// number of released bytes returned
static uint32_t StackRelease(Stack* stack, void* data);
static void* StackRequireFromBack(Lips_AllocFunc alloc, Lips_DeallocFunc dealloc,
Stack* stack, uint32_t bytes);
static void* StackReleaseFromBack(Stack* stack, uint32_t bytes);
static EvalState* PushEvalState(Lips_Machine* machine);
static EvalState* PopEvalState(Lips_Machine* machine);
static void PushCatch(Lips_Machine* machine);
static void PopCatch(Lips_Machine* machine);
static void UnwindStack(Lips_Machine* machine);
static HashTable* MachineEnv(Lips_Machine* machine);
static HashTable* PushEnv(Lips_Machine* machine);
static void PopEnv(Lips_Machine* machine);
static HashTable* EnvParent(Lips_Machine* machine, HashTable* env);
static uint32_t NearestPowerOfTwo(uint32_t v);
// compute hash of null terminated string
static uint32_t ComputeHash(const char* string) LIPS_PURE_FUNCTION;
// compute hash of sized string(no null terminator at end)
static uint32_t ComputeHashN(const char* string, uint32_t n) LIPS_PURE_FUNCTION;
static HashTable* EnvCreate(Lips_AllocFunc alloc, Lips_DeallocFunc dealloc,
Stack* stack);
static void EnvDestroy(Stack* stack, HashTable* ht);
static void EnvReserve(Lips_Machine* machine, HashTable* ht, uint32_t capacity);
static Lips_Cell* EnvInsert(Lips_Machine* machine,
HashTable* ht, Lips_Cell key, Lips_Cell value);
static Lips_Cell HashTableSearch(const HashTable* ht, Lips_Cell key);
static Node* HashTableSearchStr(const HashTable* ht, uint32_t hash, const char* key, uint32_t n);
static Node* HashTableInsert(HashTable* ht, Lips_Cell key, Lips_Cell value);
static void HashTableIterate(HashTable* ht, Iterator* it);
static int IteratorIsEmpty(const Iterator* it);
static void IteratorGet(const Iterator* it, Lips_Cell* key, Lips_Cell* value);
static void IteratorNext(Iterator* it);
static uint32_t PListSize(const HashTable* ht);
static void PListDestroy(Lips_Machine* machine, HashTable* ht);
static HashTable* PListReserve(Lips_Machine* machine, HashTable* ht, uint32_t capacity);
static Lips_Cell PListInsert(Lips_Machine* machine, HashTable** ht, Lips_Cell key, Lips_Cell value);
static Lips_Cell PListRemove(HashTable* ht, Lips_Cell key);
static Bucket* FindBucketForString(Lips_Machine* machine);
static StringPool* GetStringPool(Lips_Machine* machine, uint32_t str_size_with_0);
static char* FindSpaceForString(StringPool* pool, Lips_AllocFunc alloc);
static void RemoveString(StringPool* pool, char* str);
static void DefineWithCurrent(Lips_Machine* machine, Lips_Cell name, Lips_Cell value);
static uint32_t CheckArgumentCount(Lips_Machine* machine, Lips_Cell callable, Lips_Cell args);
static void DefineArgumentList(Lips_Machine* machine, Lips_Cell callable, Lips_Cell argvalues);
static void DefineArgumentArray(Lips_Machine* machine, Lips_Cell callable, uint32_t numargs, Lips_Cell* argvalues);
static void FreeArgumentArray(Lips_Machine* machine, uint32_t numargs, Lips_Cell* args);
static Lips_Cell EvalNonPair(Lips_Machine* machine, Lips_Cell cell);
static void Mark(Lips_Machine* machine);
static void Sweep(Lips_Machine* machine);
/// builtin lips functions and macros
static LIPS_DECLARE_FUNCTION(list);
static LIPS_DECLARE_FUNCTION(car);
static LIPS_DECLARE_FUNCTION(cdr);
static LIPS_DECLARE_FUNCTION(equal);
static LIPS_DECLARE_FUNCTION(nilp);
static LIPS_DECLARE_FUNCTION(typeof);
static LIPS_DECLARE_FUNCTION(throw);
static LIPS_DECLARE_FUNCTION(call);
static LIPS_DECLARE_FUNCTION(format);
static LIPS_DECLARE_FUNCTION(concat);
static LIPS_DECLARE_FUNCTION(slurp);
static LIPS_DECLARE_FUNCTION(load);
static LIPS_DECLARE_FUNCTION(plist);
static LIPS_DECLARE_FUNCTION(get);
static LIPS_DECLARE_FUNCTION(insert);
static LIPS_DECLARE_FUNCTION(remove);
static LIPS_DECLARE_FUNCTION(cons);
static LIPS_DECLARE_FUNCTION(intern);
static LIPS_DECLARE_FUNCTION(bound);
static LIPS_DECLARE_MACRO(lambda);
static LIPS_DECLARE_MACRO(macro);
static LIPS_DECLARE_MACRO(define);
static LIPS_DECLARE_MACRO(quote);
static LIPS_DECLARE_MACRO(progn);
static LIPS_DECLARE_MACRO(if);
static LIPS_DECLARE_MACRO(when);
static LIPS_DECLARE_MACRO(unless);
static LIPS_DECLARE_MACRO(catch);
// TODO: implement cond
/// STRUCTS
// Copy-On-Write string
struct StringData {
char* data;
// Do we really need to use bitfields? I think they have slow memory access, not sure
uint32_t length : 22;
uint32_t bucket_index : 10;
uint32_t hash;
};
struct HashTable {
uint32_t allocated;
// 0-30 bits - number of elements in hash table
// 31 bit - constant flag
uint32_t flags;
uint32_t parent;
};
#define HASH_TABLE_DATA(ht) (Node*)((HashTable*)ht+1)
#define HASH_TABLE_CONSTANT_FLAG (1u<<31)
#define HASH_TABLE_GET_SIZE(ht) ((ht)->flags & ~HASH_TABLE_CONSTANT_FLAG)
#define HASH_TABLE_SET_SIZE(ht, sz) (ht)->flags = ((ht)->flags & HASH_TABLE_CONSTANT_FLAG) | (sz)
struct Iterator {
Node* node;
uint32_t size;
};
struct Stack {
uint8_t* data;
uint32_t left;
uint32_t right;
uint32_t size;
};
// for debug
#define PRINT_STACK_DATA(stack) do { \
printf("Stack[offset=%u, size=%u] data={", (stack).offset, (stack).size); \
for (uint32_t i = 0; i < (stack).offset; i++) { \
putchar((stack).data[i]); \
} \
printf("}\n"); \
} while (0)
struct Lips_Value {
// 0-7 bits - type
// 8-14 bits - numargs if function
// 15 bit - variable number of arguments if function
// 31 bit - garbage collector mark
uint32_t type;
union {
// integer
int64_t integer;
// real
double real;
// string, symbol or keyword
StringData* str;
// list
struct {
Lips_Value* head;
Lips_Value* tail;
} list;
// plist
HashTable* ht;
// lisp function or lisp macro
struct {
Lips_Value* args;
Lips_Value* body;
} lfunc;
// c function
struct {
Lips_Func ptr;
void* udata;
} cfunc;
// c macro
struct {
Lips_Macro ptr;
void* udata;
} cmacro;
} data;
};
#define GET_TYPE(cell) ((cell)->type & 255)
#define GET_NUMARGS(cell) (((cell)->type >> 8) & 255)
#define GET_INTEGER(cell) (cell)->data.integer
#define GET_REAL(cell) (cell)->data.real
#define GET_HEAD(cell) (cell)->data.list.head
#define GET_TAIL(cell) (cell)->data.list.tail
#define GET_CFUNC(cell) (cell)->data.cfunc
#define GET_CMACRO(cell) (cell)->data.cmacro
#define GET_LFUNC(cell) (cell)->data.lfunc
#define GET_HEAD_TYPE(cell) GET_TYPE(GET_HEAD(cell))
#define GET_TAIL_TYPE(cell) GET_TYPE(GET_TAIL(cell))
struct Node {
Lips_Cell key;
Lips_Cell value;
// counter for robin-hood hashing
size_t psl;
};
#define NODE_VALID(node) ((node).value != NULL)
struct Bucket {
void* data;
uint32_t num_elements;
uint32_t size;
uint32_t next;
};
struct Token {
const char* str;
uint32_t length;
};
struct EvalState {
Lips_Cell sexp;
Lips_Cell callable;
union {
Lips_Cell* array;
Lips_Cell list;
} args;
Lips_Cell passed_args;
union {
struct {
Lips_Cell* last;
uint32_t count;
} args;
struct {
Lips_Cell code;
uint32_t parent;
} exec;
} data;
uint32_t flags;
// parent's position in stack
uint32_t parent;
};
#define ES_STAGE_EVALUATING_ARGS 0
#define ES_STAGE_EXECUTING_CODE 1
#define ES_NUM_ENVS(es) ((es)->flags >> 1)
#define ES_STAGE(es) ((es)->flags & 1)
#define ES_INC_NUM_ENVS(es) ((es)->flags += 2)
#define ES_SET_STAGE(es, stage) (es)->flags = ((es)->flags & ~1) | stage
#define ES_PASSED_ARGS(es) (es)->passed_args
#define ES_ARG_COUNT(es) (es)->data.args.count
#define ES_LAST_ARG(es) (es)->data.args.last
#define ES_CODE(es) (es)->data.exec.code
#define ES_CATCH_PARENT(es) (es)->data.exec.parent
typedef union {
Lips_Cell cell;
Iterator iterator;
} MarkState;
#define NUM_STRING_POOL_SIZES 5
static const uint32_t string_pool_sizes[NUM_STRING_POOL_SIZES] = { 4, 8, 16, 32, 64 };
struct StringPool {
#define STRING_POOL_NUM_CHUNKS 10
// i-th chunk has 4^i * chunk[0] bytes allocated
Bucket chunks[STRING_POOL_NUM_CHUNKS];
uint32_t str_max_size;
uint32_t initial_chunk_size;
};
struct Parser {
const char* text;
uint32_t length;
uint32_t pos;
uint32_t currline;
uint32_t currcol;
uint32_t numlists;
Token currtok;
};
struct Lips_Machine {
// callbacks
Lips_AllocFunc alloc;
Lips_DeallocFunc dealloc;
Lips_OpenFileFunc open_file;
Lips_ReadFileFunc read_file;
Lips_CloseFileFunc close_file;
// pools for cells
Bucket* buckets;
uint32_t numbuckets;
uint32_t allocbuckets;
// pools for string objects
Bucket* str_buckets;
uint32_t numstr_buckets;
uint32_t allocstr_buckets;
// pools for string data
// 4, 8, 16, 32, 64
StringPool string_pools[NUM_STRING_POOL_SIZES];
// our beloved stack
Stack stack;
uint32_t envpos;
uint32_t evalpos;
uint32_t catchpos;
Lips_Cell throwvalue;
Lips_Cell default_file;
Lips_Cell S_nil;
Lips_Cell S_t;
Lips_Cell S_filename;
Lips_Cell T_integer;
Lips_Cell T_real;
Lips_Cell T_string;
Lips_Cell T_symbol;
Lips_Cell T_pair;
Lips_Cell T_function;
Lips_Cell T_macro;
char errbuff[1024];
};
#define CURRENT_EVAL_STATE(interp) (EvalState*)((interp)->stack.data + (interp)->evalpos)
/// FUNCTIONS
LIPS_COLD_FUNCTION Lips_Machine*
Lips_CreateMachine(const Lips_MachineCreateInfo* info)
{
Lips_Machine* machine;
machine = (Lips_Machine*)info->alloc(sizeof(Lips_Machine));
if (machine == NULL) return NULL;
machine->alloc = info->alloc;
machine->dealloc = info->dealloc;
machine->open_file = info->open_file;
machine->read_file = info->read_file;
machine->close_file = info->close_file;
machine->numbuckets = 0;
machine->buckets = (Bucket*)machine->alloc(sizeof(Bucket));
machine->allocbuckets = 1;
for (int i = 0; i < NUM_STRING_POOL_SIZES; i++) {
machine->string_pools[i].str_max_size = string_pool_sizes[i];
machine->string_pools[i].initial_chunk_size = 16 * 1024;
memset(machine->string_pools[i].chunks, 0, sizeof(Bucket) * STRING_POOL_NUM_CHUNKS);
}
machine->str_buckets = (Bucket*)machine->alloc(sizeof(Bucket));
machine->allocstr_buckets = 1;
machine->numstr_buckets = 0;
CreateStack(machine->alloc, &machine->stack, info->initial_stack_size);
// create root environment
HashTable* env = EnvCreate(machine->alloc, machine->dealloc, &machine->stack);
env->parent = STACK_INVALID_POS;
machine->envpos = ((uint8_t*)env - machine->stack.data);
machine->evalpos = STACK_INVALID_POS;
machine->catchpos = STACK_INVALID_POS;
// preallocate space for hash table to speed things up
EnvReserve(machine, env, 64);
// define builtins
machine->default_file = Lips_NewString(machine, "<eval>");
machine->S_nil = Lips_Define(machine, "nil", Lips_NewPair(machine, NULL, NULL));
// important optimization: this allows to reuse string "...",
// so anytime we encounter "..." in code we don't allocate a new string
Lips_Define(machine, "...", machine->S_nil);
// t is just an integer
// FIXME: do I need to add a new type for "t"?
machine->S_t = Lips_Define(machine, "t", Lips_NewInteger(machine, 1));
machine->S_filename = Lips_Define(machine, "<filename>", Lips_NewPair(machine, NULL, NULL));
LIPS_DEFINE_FUNCTION(machine, list, LIPS_NUM_ARGS_VAR, NULL);
LIPS_DEFINE_FUNCTION(machine, car, LIPS_NUM_ARGS_1, NULL);
LIPS_DEFINE_FUNCTION(machine, cdr, LIPS_NUM_ARGS_1, NULL);
Lips_Cell S_equal = LIPS_DEFINE_FUNCTION(machine, equal, LIPS_NUM_ARGS_2|LIPS_NUM_ARGS_VAR, NULL);
Lips_Define(machine, "=", S_equal);
Lips_Cell S_nilp = LIPS_DEFINE_FUNCTION(machine, nilp, LIPS_NUM_ARGS_1, NULL);
Lips_Define(machine, "not", S_nilp);
LIPS_DEFINE_FUNCTION(machine, typeof, LIPS_NUM_ARGS_1, NULL);
LIPS_DEFINE_FUNCTION(machine, throw, LIPS_NUM_ARGS_1, NULL);
LIPS_DEFINE_FUNCTION(machine, call, LIPS_NUM_ARGS_2, NULL);
LIPS_DEFINE_FUNCTION(machine, format, LIPS_NUM_ARGS_1|LIPS_NUM_ARGS_VAR, NULL);
LIPS_DEFINE_FUNCTION(machine, concat, LIPS_NUM_ARGS_2|LIPS_NUM_ARGS_VAR, NULL);
LIPS_DEFINE_FUNCTION(machine, slurp, LIPS_NUM_ARGS_1, NULL);
LIPS_DEFINE_FUNCTION(machine, load, LIPS_NUM_ARGS_1, NULL);
LIPS_DEFINE_FUNCTION(machine, plist, LIPS_NUM_ARGS_VAR, NULL);
LIPS_DEFINE_FUNCTION(machine, get, LIPS_NUM_ARGS_2, NULL);
LIPS_DEFINE_FUNCTION(machine, insert, LIPS_NUM_ARGS_3, NULL);
LIPS_DEFINE_FUNCTION(machine, remove, LIPS_NUM_ARGS_2, NULL);
LIPS_DEFINE_FUNCTION(machine, cons, LIPS_NUM_ARGS_2, NULL);
LIPS_DEFINE_FUNCTION(machine, intern, LIPS_NUM_ARGS_1, NULL);
LIPS_DEFINE_FUNCTION(machine, bound, LIPS_NUM_ARGS_1, NULL);
LIPS_DEFINE_MACRO(machine, lambda, LIPS_NUM_ARGS_2|LIPS_NUM_ARGS_VAR, NULL);
LIPS_DEFINE_MACRO(machine, macro, LIPS_NUM_ARGS_2|LIPS_NUM_ARGS_VAR, NULL);
LIPS_DEFINE_MACRO(machine, define, LIPS_NUM_ARGS_2, NULL);
LIPS_DEFINE_MACRO(machine, quote, LIPS_NUM_ARGS_1, NULL);
LIPS_DEFINE_MACRO(machine, progn, LIPS_NUM_ARGS_1|LIPS_NUM_ARGS_VAR, NULL);
LIPS_DEFINE_MACRO(machine, if, LIPS_NUM_ARGS_3|LIPS_NUM_ARGS_VAR, NULL);
LIPS_DEFINE_MACRO(machine, when, LIPS_NUM_ARGS_2|LIPS_NUM_ARGS_VAR, NULL);
LIPS_DEFINE_MACRO(machine, unless, LIPS_NUM_ARGS_2|LIPS_NUM_ARGS_VAR, NULL);
LIPS_DEFINE_MACRO(machine, catch, LIPS_NUM_ARGS_1|LIPS_NUM_ARGS_VAR, NULL);
machine->T_integer = Lips_Define(machine, "<integer>", Lips_NewSymbol(machine, "integer"));
machine->T_real = Lips_Define(machine, "<real>", Lips_NewSymbol(machine, "real"));
machine->T_string = Lips_Define(machine, "<string>", Lips_NewSymbol(machine, "string"));
machine->T_symbol = Lips_Define(machine, "<symbol>", Lips_NewSymbol(machine, "symbol"));
machine->T_pair = Lips_Define(machine, "<pair>", Lips_NewSymbol(machine, "pair"));
machine->T_function = Lips_Define(machine, "<function>", Lips_NewSymbol(machine, "function"));
machine->T_macro = Lips_Define(machine, "<macro>", Lips_NewSymbol(machine, "macro"));
return machine;
}
LIPS_COLD_FUNCTION Lips_Machine*
Lips_DefaultCreateMachine()
{
return Lips_CreateMachine(&(Lips_MachineCreateInfo) {
.alloc = &DefaultAlloc,
.dealloc = &DefaultDealloc,
.open_file = &DefaultOpenFile,
.read_file = &DefaultReadFile,
.close_file = &DefaultCloseFile,
.initial_stack_size = 16*1024
});
}
LIPS_COLD_FUNCTION void
Lips_DestroyMachine(Lips_Machine* machine)
{
PopEnv(machine);
assert(machine->envpos == STACK_INVALID_POS &&
"Tried to call Lips_DestroyMachine while running Lisp code");
// clear all resources
Lips_DeallocFunc dealloc = machine->dealloc;
DestroyStack(dealloc, &machine->stack);
for (uint32_t i = 0; i < machine->numbuckets; i++) {
// destroy each cell in bucket
Bucket* bucket = &machine->buckets[i];
for (uint32_t i = 0; bucket->size > 0; i++) {
Lips_Cell cell = (Lips_Value*)bucket->data + i;
if ((cell->type & DEAD_MASK) == 0) {
DestroyCell(machine, cell);
bucket->size--;
}
}
DestroyBucket(machine, bucket, sizeof(Lips_Value));
}
for (uint32_t i = 0; i < machine->numstr_buckets; i++)
DestroyBucket(machine, &machine->str_buckets[i], sizeof(StringData));
for (uint32_t i = 0; i < NUM_STRING_POOL_SIZES; i++) {
for (uint32_t j = 0; j < STRING_POOL_NUM_CHUNKS; j++) {
Bucket* chunk = &machine->string_pools[i].chunks[j];
if (chunk->data)
DestroyBucket(machine, chunk, string_pool_sizes[i]);
}
}
dealloc(machine->buckets, sizeof(Bucket) * machine->allocbuckets);
dealloc(machine->str_buckets, sizeof(Bucket) * machine->allocstr_buckets);
dealloc(machine, sizeof(Lips_Machine));
}
LIPS_HOT_FUNCTION Lips_Cell
Lips_Eval(Lips_Machine* machine, Lips_Cell cell)
{
#if 0
// recursive version(easily readable)
switch (GET_TYPE(cell)) {
default: assert(0 && "Value has undefined type");
case LIPS_TYPE_INTEGER:
case LIPS_TYPE_REAL:
case LIPS_TYPE_STRING:
return cell;
case LIPS_TYPE_SYMBOL:
return Lips_InternCell(machine, cell);
case LIPS_TYPE_PAIR: {
Lips_Cell name = GET_HEAD(cell);
Lips_Cell args = GET_TAIL(cell);
TYPE_CHECK(machine, LIPS_TYPE_SYMBOL, name);
Lips_Cell callable = Lips_InternCell(machine, name);
if (callable == NULL || callable == machine->S_nil) {
Lips_ThrowError(machine, "Eval: undefined symbol '%s'", GET_STR(name)->ptr);
}
return Lips_Invoke(machine, callable, args);
}
}
#else
// don't even try to understand...
// you just need to know that this is a non-recursive eval loop
if (GET_TYPE(cell) == LIPS_TYPE_PAIR) {
Lips_Cell ret;
Lips_Cell name;
const uint32_t startpos = machine->evalpos;
EvalState* state = PushEvalState(machine);
state->sexp = cell;
eval:
state->flags = 0;
ES_PASSED_ARGS(state) = GET_TAIL(state->sexp);
name = GET_HEAD(state->sexp);
if (LIPS_UNLIKELY(name == NULL)) {
ret = machine->S_nil;
} else {
if (LIPS_UNLIKELY(!Lips_IsSymbol(name))) {
Lips_SetError(machine, "First part of evaluated s-expression always must be a symbol");
goto except;
}
state->callable = Lips_InternCell(machine, name);
if (LIPS_UNLIKELY(state->callable == machine->S_nil)) {
Lips_SetError(machine, "Eval: undefined symbol '%s'", GET_STR_PTR(name));
goto except;
}
ES_ARG_COUNT(state) = CheckArgumentCount(machine, state->callable, ES_PASSED_ARGS(state));
if (LIPS_UNLIKELY(ES_ARG_COUNT(state) == (uint32_t)-1)) {
goto except;
}
if (Lips_IsFunction(state->callable)) {
state->args.array = StackRequireFromBack(machine->alloc, machine->dealloc, &machine->stack,
ES_ARG_COUNT(state) * sizeof(Lips_Cell));
ES_LAST_ARG(state) = state->args.array;
arg:
while (ES_PASSED_ARGS(state)) {
// eval arguments
Lips_Cell argument = GET_HEAD(ES_PASSED_ARGS(state));
if (GET_TYPE(argument) == LIPS_TYPE_PAIR) {
state = PushEvalState(machine);
state->sexp = argument;
goto eval;
} else {
*ES_LAST_ARG(state) = EvalNonPair(machine, argument);
ES_LAST_ARG(state)++;
ES_PASSED_ARGS(state) = GET_TAIL(ES_PASSED_ARGS(state));
}
}
} else {
state->args.list = ES_PASSED_ARGS(state);
}
if (GET_TYPE(state->callable) & ((LIPS_TYPE_C_FUNCTION^LIPS_TYPE_FUNCTION)|
(LIPS_TYPE_C_MACRO^LIPS_TYPE_MACRO))) {
Lips_Cell c = state->callable;
if (Lips_IsFunction(c)) {
// every function must be executed inside it's own environment
PushEnv(machine);
uint32_t count = ES_ARG_COUNT(state);
ret = GET_CFUNC(c).ptr(machine, count, state->args.array, GET_CFUNC(c).udata);
// array of arguments no more needed; we can free it
FreeArgumentArray(machine, count, state->args.array);
PopEnv(machine);
} else {
ret = GET_CMACRO(c).ptr(machine, state->args.list, GET_CMACRO(c).udata);
}
// fucntion returned null so need to go to latest catch
if (LIPS_UNLIKELY(ret == NULL)) {
if (ES_STAGE(state) == ES_STAGE_EXECUTING_CODE) {
goto code;
}
except:
if (machine->catchpos >= startpos) {
// unhandled throw
PopEvalState(machine);
return NULL;
}
UnwindStack(machine);
ret = machine->throwvalue;
}
} else {
// push a new environment
if (ES_ARG_COUNT(state) > 0 || Lips_IsFunction(state->callable)) {
HashTable* env = PushEnv(machine);
ES_INC_NUM_ENVS(state);
if (ES_ARG_COUNT(state) > 0) {
if (Lips_IsFunction(state->callable)) {
DefineArgumentArray(machine, state->callable, ES_ARG_COUNT(state), state->args.array);
// array of arguments no more needed; we can free it
FreeArgumentArray(machine, ES_ARG_COUNT(state), state->args.array);
} else {
DefineArgumentList(machine, state->callable, state->args.list);
env->flags |= HASH_TABLE_CONSTANT_FLAG;
}
}
}
// execute code
ES_CODE(state) = GET_LFUNC(state->callable).body;
ES_SET_STAGE(state, ES_STAGE_EXECUTING_CODE);
code:
while (ES_CODE(state)) {
Lips_Cell expression = GET_HEAD(ES_CODE(state));
if (GET_TYPE(expression) == LIPS_TYPE_PAIR) {
// TODO: implement tail call optimization
state = PushEvalState(machine);
state->sexp = expression;
goto eval;
} else {
ret = EvalNonPair(machine, expression);
}
ES_CODE(state) = GET_TAIL(ES_CODE(state));
}
}
}
state = PopEvalState(machine);
if (machine->evalpos != startpos) {
switch (ES_STAGE(state)) {
case ES_STAGE_EVALUATING_ARGS:
*ES_LAST_ARG(state) = ret;
ES_LAST_ARG(state)++;
ES_PASSED_ARGS(state) = GET_TAIL(ES_PASSED_ARGS(state));
goto arg;
case ES_STAGE_EXECUTING_CODE:
ES_CODE(state) = GET_TAIL(ES_CODE(state));
goto code;
}
}
return ret;
} else {
return EvalNonPair(machine, cell);
}
#endif
return cell;
}
Lips_Cell
Lips_EvalString(Lips_Machine* machine, const char* str, const char* filename)
{
Parser parser;
ParserInit(&parser, str, strlen(str));
Lips_Cell ast = GenerateAST(machine, &parser);
Lips_Cell str_filename;
if (filename == NULL) {
str_filename = machine->default_file;
} else {
str_filename = Lips_NewString(machine, filename);
}
Lips_Cell temp = Lips_ListPushBack(machine, machine->S_filename, str_filename);
Lips_Cell ret = Lips_Eval(machine, ast);
GET_TAIL(temp) = NULL; // this equals to Lips_ListPop(machine, machine->S_filename);
return ret;
}
const char*
Lips_GetError(const Lips_Machine* machine)
{
return machine->errbuff;
}
LIPS_HOT_FUNCTION void
Lips_GarbageCollect(Lips_Machine* machine)
{
Mark(machine);
Sweep(machine);
}
Lips_Cell
Lips_Nil(Lips_Machine* machine)
{
return machine->S_nil;
}
Lips_Cell
Lips_NewInteger(Lips_Machine* machine, int64_t num)
{
Lips_Cell cell = NewCell(machine);
cell->type = LIPS_TYPE_INTEGER;
cell->data.integer = num;
return cell;
}
Lips_Cell
Lips_NewReal(Lips_Machine* machine, double num)
{
Lips_Cell cell = NewCell(machine);
cell->type = LIPS_TYPE_REAL;
cell->data.real = num;
return cell;
}
Lips_Cell
Lips_NewString(Lips_Machine* machine, const char* str)
{
return Lips_NewStringN(machine, str, strlen(str));
}
Lips_Cell
Lips_NewStringN(Lips_Machine* machine, const char* str, uint32_t n)
{
Lips_Cell cell = NewCell(machine);
cell->type = LIPS_TYPE_STRING;
GET_STR(cell) = StringCreate(machine, str, n);
return cell;
}
Lips_Cell
Lips_NewSymbol(Lips_Machine* machine, const char* str)
{
return Lips_NewSymbolN(machine, str, strlen(str));
}
Lips_Cell
Lips_NewSymbolN(Lips_Machine* machine, const char* str, uint32_t n)
{
// try to find string in environments so we don't waste space
HashTable* env = MachineEnv(machine);
uint32_t hash = ComputeHashN(str, n);
do {
Node* node = HashTableSearchStr(env, hash, str, n);
if (node)
return node->key;
env = EnvParent(machine, env);
} while (env);
Lips_Cell cell = NewCell(machine);
cell->type = LIPS_TYPE_SYMBOL;
GET_STR(cell) = StringCreateWithHash(machine, str, n, hash);
return cell;
}
Lips_Cell
Lips_NewKeyword(Lips_Machine* machine, const char* str)
{
return Lips_NewKeywordN(machine, str, strlen(str));
}
Lips_Cell
Lips_NewKeywordN(Lips_Machine* machine, const char* str, uint32_t n)
{
Lips_Cell cell = NewCell(machine);
cell->type = LIPS_TYPE_KEYWORD;
GET_STR(cell) = StringCreate(machine, str, n);
return cell;
}
Lips_Cell
Lips_NewPair(Lips_Machine* machine, Lips_Cell head, Lips_Cell tail)
{
Lips_Cell cell = NewCell(machine);
cell->type = LIPS_TYPE_PAIR;
cell->data.list.head = head;
cell->data.list.tail = tail;
return cell;
}
Lips_Cell
Lips_NewPList(Lips_Machine* machine)
{
Lips_Cell cell = NewCell(machine);
cell->type = LIPS_TYPE_PLIST;
cell->data.ht = NULL;
return cell;
}
Lips_Cell
Lips_NewList(Lips_Machine* machine, uint32_t numCells, Lips_Cell* cells)
{
// important optimization: don't allocate unnecessary lists when we can just return nil
if (numCells == 0) {
return machine->S_nil;
}
Lips_Cell list = Lips_NewPair(machine, NULL, NULL);
Lips_Cell curr = list;
while (numCells--) {
GET_HEAD(curr) = *cells;
if (numCells > 0) {
GET_TAIL(curr) = Lips_NewPair(machine, NULL, NULL);
curr = GET_TAIL(curr);
}
cells++;
}
return list;
}
Lips_Cell
Lips_NewFunction(Lips_Machine* machine, Lips_Cell args, Lips_Cell body, uint8_t numargs)
{
Lips_Cell cell = NewCell(machine);
cell->type = LIPS_TYPE_FUNCTION | (numargs << 8);
// TODO: check all arguments are symbols
GET_LFUNC(cell).args = args;
GET_LFUNC(cell).body = body;
return cell;
}
Lips_Cell
Lips_NewMacro(Lips_Machine* machine, Lips_Cell args, Lips_Cell body, uint8_t numargs)
{
Lips_Cell cell = NewCell(machine);
cell->type = LIPS_TYPE_MACRO | (numargs << 8);
GET_LFUNC(cell).args = args;
GET_LFUNC(cell).body = body;
return cell;
}
Lips_Cell
Lips_NewCFunction(Lips_Machine* machine, Lips_Func function, uint8_t numargs, void* udata)
{
Lips_Cell cell = NewCell(machine);
cell->type = LIPS_TYPE_C_FUNCTION | (numargs << 8);
GET_CFUNC(cell).ptr = function;
GET_CFUNC(cell).udata = udata;
return cell;
}
Lips_Cell
Lips_NewCMacro(Lips_Machine* machine, Lips_Macro function, uint8_t numargs, void* udata)
{
Lips_Cell cell = NewCell(machine);
cell->type = LIPS_TYPE_C_MACRO | (numargs << 8);
GET_CMACRO(cell).ptr = function;
GET_CMACRO(cell).udata = udata;
return cell;
}
uint32_t
Lips_GetType(const Lips_Cell cell)
{
return GET_TYPE(cell);
}
uint32_t
Lips_PrintCell(Lips_Machine* machine, Lips_Cell cell, char* buff, uint32_t size)
{
char* ptr = buff;
#define PRINT(...) ptr += snprintf(ptr, size - (ptr - buff), __VA_ARGS__)
#if 0
// this is an implementation with recursion used
switch (GET_TYPE(cell)) {
default: return 0;
case LIPS_TYPE_INTEGER:
PRINT("%ld", GET_INTEGER(cell));
break;
case LIPS_TYPE_REAL:
PRINT("%f", GET_REAL(cell));
break;
case LIPS_TYPE_STRING:
PRINT("\"%s\"", GET_STRING(cell));
break;
case LIPS_TYPE_SYMBOL:
PRINT("%s", GET_STRING(cell));
break;
case LIPS_TYPE_PAIR:
PRINT("(");
if (GET_HEAD(cell)) {
ptr += Lips_PrintCell(machine, GET_HEAD(cell), ptr, size - (ptr - buff));
cell = GET_TAIL(cell);
while (cell && GET_HEAD(cell)) {
PRINT(" ");
ptr += Lips_PrintCell(machine, GET_HEAD(cell), ptr, size - (ptr - buff));
if (!GET_TAIL(cell)) break;
cell = GET_TAIL(cell);
}
}
PRINT(")");
break;
}
#else
if (GET_TYPE(cell) == LIPS_TYPE_PAIR) {
uint32_t counter = 0;
Lips_Cell* prev = NULL;
PRINT("(");
while (cell != NULL) {
// TODO: do checks for buffer overflow
if (GET_HEAD(cell) != NULL) {
switch (GET_HEAD_TYPE(cell)) {
default: assert(0);
case LIPS_TYPE_INTEGER:
PRINT("%ld", GET_INTEGER(GET_HEAD(cell)));
break;
case LIPS_TYPE_REAL:
PRINT("%f", GET_REAL(GET_HEAD(cell)));
break;
case LIPS_TYPE_STRING:
PRINT("\"%s\"", GET_STR_PTR(GET_HEAD(cell)));
break;
case LIPS_TYPE_SYMBOL:
PRINT("%s", GET_STR_PTR(GET_HEAD(cell)));
break;
case LIPS_TYPE_KEYWORD:
PRINT(":%s", GET_STR_PTR(GET_HEAD(cell)));
break;
case LIPS_TYPE_PAIR:
PRINT("(");
prev = StackRequire(machine->alloc, machine->dealloc,
&machine->stack, sizeof(Lips_Cell));
*prev = GET_TAIL(cell);
cell = GET_HEAD(cell);
counter++;
goto skip;
case LIPS_TYPE_PLIST:
// TODO: print all of plist's elements
PRINT("<plist(%u)>", PListSize(GET_PLIST(GET_HEAD(cell))));
break;
case LIPS_TYPE_FUNCTION:
case LIPS_TYPE_C_FUNCTION: {
uint32_t num = GET_NUMARGS(GET_HEAD(cell));
if (num & LIPS_NUM_ARGS_VAR)
PRINT("<func(%d+)>", num & (LIPS_NUM_ARGS_VAR-1));
else
PRINT("<func(%d)>", num);
}
break;
case LIPS_TYPE_MACRO:
case LIPS_TYPE_C_MACRO: {
uint32_t num = GET_NUMARGS(GET_HEAD(cell));
if (num & LIPS_NUM_ARGS_VAR)
PRINT("<macro(%d+)>", num & (LIPS_NUM_ARGS_VAR-1));
else
PRINT("<macro(%d)>", num);
}
break;
}
}
cell = GET_TAIL(cell);
if (cell != NULL) {
PRINT(" ");
}
skip:
if (cell == NULL) {
PRINT(")");
if (counter == 0) {
return ptr - buff;
}
cell = *prev;
assert(StackRelease(&machine->stack, prev) == sizeof(Lips_Cell));
prev--;
counter--;