-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlval.c
More file actions
1538 lines (1269 loc) · 43.5 KB
/
lval.c
File metadata and controls
1538 lines (1269 loc) · 43.5 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
#include "lval.h"
#include <errno.h>
#include <string.h>
#include "mpc.h"
#include "parser.h"
#define MAX_ERR 4096
// TODO: Add shorter error descriptions
// TODO: Prototype remaining builtins
// TODO: Refactor some fields and variable names
// TODO: Refactor consistent usage of lsym, lvar, ...
// TODO: Fix some descriptions of parameters in comments
// TODO: Split source file to multiple modular files
// Asserts condition `cond` is false, if not throws an error and deletes `lval`
#define LASSERT(lval, cond, fmt, ...) \
if (!(cond)) { \
lval_del(lval); \
/* __VA_ARGS__ allows to variable number of arguments */ \
/* ## in front eats "," on expansion if __VA_ARGS is empty */ \
return lval_wrap_err(fmt, ##__VA_ARGS__); \
}
// Asserts if child of `lval` at given index has the same type as `expected` or
// else, throw error
#define LASSERT_CHILD_TYPE(lbuiltin, lval, index, expected) \
LASSERT(lval, lval->children[index]->type == expected, \
"Function '%s' was passed incorrect type of argument for " \
"argument: %i\n" \
"Got '%s' expected '%s'", \
lbuiltin, index, lval_print_type(lval->children[index]->type), \
lval_print_type(expected))
// Asserts if correct number of arguments were passed, i.e by counting children
#define LASSERT_CHILD_COUNT(lbuiltin, lval, count) \
LASSERT(lval, lval->child_count == count, \
"Function '%s' was passed incorrect number of arguments\n" \
"Got %i, expected %i", \
lbuiltin, lval->child_count, count)
// Asserts if function `lbuiltin` was passed with no arguments
#define LASSERT_CHILD_NOT_EMPTY(lbuiltin, lval, index) \
LASSERT(lval, lval->children[index]->child_count != 0, \
"Functions '%s' was passed {} for argument at index %i", lbuiltin, \
index)
///////////////////////////////////////////////////////////////////////////////
/* Function Declarations */
///////////////////////////////////////////////////////////////////////////////
/* LVal Wrapper functions */
/**
* @brief Convert a long to a LVal
* @param val: A long to be converted to a LVal
* @retval A LVal with num field set and type LVAL_NUM
*/
LVal *lval_wrap_long(long val);
/**
* @brief Wrap a char string as a LVal symbol
* @param *str: String to wrap
* @retval A LVal of type LVAL_SYM
*/
LVal *lval_wrap_sym(char *sym);
/**
* @brief Wrap error with variable arguments to LVal
* @note Copies a maximum of MAX_ERR bytes including null,
* may lead to truncated error string
* @param *fmt: Format of the given variable argument error string
* @retval A LVal of type LVAL_ERR
*/
LVal *lval_wrap_err(char *fmt, ...);
/**
* @brief Wrap S/Q-Expressions
* @param type: Type of expression
* @retval A LVal of type: `type`
*/
LVal *lval_wrap_expr(int type);
// lval_wrap_expr with type LVAL_SEXPR
LVal *lval_wrap_sexpr(void);
// lval_wrap_expr with type LVAL_QEXPR
LVal *lval_wrap_qexpr(void);
/**
* @brief Wrap a LBuiltin as an LVal
* @param lbuiltin: A LBuiltin
* @retval A LVal with type LVAL_FUN
*/
LVal *lval_wrap_lbuiltin(LBuiltin lbuiltin);
/* LVal methods for modification and evaluation */
/**
* @brief Wrap as a lambda expression (local functions)
* @note // To-do: Correct explanation for @param
* @param *lformals: The formal part of the lambda expression
* @param *lbody: The body of the lambda expression
* @retval A LVal with type LVAL_FUN with lbuiltin field set to NULL
*/
LVal *lval_wrap_lambda(LVal *lformals, LVal *lbody);
/**
* @brief Wrap a string as a LVal
* @param *str: The string to be wrapped
* @retval A LVal of type LVAL_STR
*/
LVal *lval_wrap_str(char *str);
/* Functions to operate on LVal */
/**
* @brief Delete a LVal
* @param *lval: The LVal which need to be freed along with its contents
* @retval None
*/
void lval_del(LVal *lval);
/**
* @brief Add a LVal to another LVal
* @param *parent: The parent LVal, the child is added to this LVal
* @param *child: The child LVal which needs to be added
* @retval Returns the parent LVal
*/
LVal *lval_add(LVal *parent, LVal *child);
/**
* @brief Add an LVal to the end of other
* @param *augend: The parent to which the other LVal is added
* @param *addend: The child which is joined with augend
* @retval The joined LVal (augend += addend)
*/
LVal *lval_join(LVal *augend, LVal *addend);
/**
* @brief Pop child at ith position
* @param *lval: Parent LVal
* @param index: Location of child
* @retval The popped child
*/
LVal *lval_pop(LVal *lval, int index);
/**
* @brief Get child at ith position, delete rest
* @param *lval: The parent lval
* @param index: Position of child
* @retval Child at ith position
*/
LVal *lval_take(LVal *lval, int index);
/**
* @brief Call a function `lfun` with `largs` as arguments
* @note TODO: Expand on inner-workings
* @param *lenv: The LEnv where the lfun will be stored
* @param *lfun: A `lbuiltin` / local function
* @param *largs: The arguments to be passed to the function `lfun`
* @retval A partial or complete evaluation of function on exhausting its
* formals
*/
LVal *lval_call(LEnv *lenv, LVal *lfun, LVal *largs);
/**
* @brief Compare two LVal's
* @param *first: The first LVal
* @param *second: The second LVal
* @retval 1 if they are equal, 0 otherwise
*/
int lval_eq(LVal *first, LVal *second);
/**
* @brief Evaluate an LVal
* @note Fetches symbols from LEnv, Handles SEXPR, or just returns LVal
* @param *lenv: LEnv from which the symbols must be fetched
* @param *lval: A LVal of any type
* @retval A LVal computed depending on type (@see @note)
*/
LVal *lval_eval(LEnv *lenv, LVal *lval);
/**
* @brief Evaluate a S-Expression
* @param *lenv: A LEnv which contains symbol list
* @param *lval: A LVal of type LVAL_SEXPR
* @retval Result wrapped as a LVal
*/
LVal *lval_eval_sexpr(LEnv *lenv, LVal *lval);
/* LEnv Functions */
/**
* @brief Create a new LEnv
* @retval A LEnv with fields initialized to NULL/0
*/
LEnv *lenv_new(void);
/**
* @brief Delete a LEnv
* @param *lenv: The LEnv to be deleted
* @retval None
*/
void lenv_del(LEnv *lenv);
/**
* @brief Search for LVal of type LVAL_SYM in LEnv "hay" containing the same
* symbol(sym) as "pin"
* @param *hay: LEnv "hay" to search the symbol(LVal) "pin" in
* @param *pin: The symbol(LVal) "pin" to be searched for in the LEnv "hay"
* @retval A copy of LVal in "hay" having symbol same as "pin" if exists, else
* error of the type LVAL_ERR
*/
LVal *lenv_get(LEnv *hay, LVal *pin);
/**
* @brief Put an LVal with symbol lsym inside a LEnv
* @param *lenv: A LEnv in which the LVal is to be added
* @param *lsym: The symbol of the LVal which is to be added into LEnv
* @param *lval: The LVal with symbol lsym which is to be added into LEnv
* @retval None
*/
void lenv_put(LEnv *lenv, LVal *lsym, LVal *lval);
/**
* @brief Copy a LEnv
* @param *lenv: The LEnv to be copied
* @retval The copied LEnv
*/
LEnv *lenv_copy(LEnv *lenv);
/**
* @brief Put a symbol inside a global environment
* @param *lenv: Immediate LEnv environment
* @param *lsym: The symbol used to represent lval, of type LVAL_SYM
* @param *lval: The value of the symbol
* @retval None
*/
void lenv_put_global(LEnv *lenv, LVal *lsym, LVal *lval);
/* MPC AST handlers */
/**
* @brief Read ast as a LVal
* @param *node: The ast to be converted
* @retval A LVal
*/
LVal *lval_read_ast(mpc_ast_t *node);
/**
* @brief Handler for lval_wrap_long
* @note Converts string to long converts to LVal on success
* @param *node: ast node containing a long number as contents
* @retval A LVal of type LVAL_NUM on success, LVAL_ERR otherwise
*/
LVal *lval_read_long(mpc_ast_t *node);
/**
* @brief Handle unescaped wrapping of LVAL_STR
* @param *node: AST node having string as its contents
* @retval A LVal of type
*/
LVal *lval_read_str(mpc_ast_t *node);
/* LVal printing methods */
/**
* @brief Print value of LVal adding a new line at the end
* @param val: An LVal
* @retval None
*/
void lval_println(LVal *lval);
/**
* @brief Print value of LVal
* @note Switches between different types of LVal and prints appropriately
* @param val: An LVal
* @retval None
*/
void lval_print(LVal *lval);
/**
* @brief Print an S-Expression
* @note lval_print handler for S-Expression
* @param *lval: LVal with type LVAL_SEXPR
* @param open: Character to be inserted before S-Expression
* @param close: Character to be inserted at end of S-Expression
* @retval None
*/
void lval_print_expr(LVal *lval, char open, char close);
// lval_print_expr wrapper for S-Expressions
void lval_print_sexpr(LVal *lval);
// lval_print_expr wrapper for Q-Expressions
void lval_print_qexpr(LVal *lval);
/**
* @brief Print a escaped string
* @param *lstr: A LVal of type LVAL_STR
* @retval None
*/
void lval_print_str(LVal *lstr);
/**
* @brief Print type of LVal
* @param type: Takes integer value of type for LVAL_TYPE enum
* @retval String representing the LVAL_TYPE
*/
char *lval_print_type(int type);
/* LVal Builtins */
/**
* @brief Convert a LVal sequence to qexpr
* @param *lval: A LVal
* @param *lenv: Not used
* @retval Returns an LVal of type LVAL_QEXPR
*/
LVal *builtin_list(LEnv *lenv, LVal *lval);
/**
* @brief Returns head of a qexpr
* @note eg: head {0 1 2} => 0
* @param *lenv: Not used
* @param *lval: A LVal with type qexpr and atleast one child
* @retval Head of qexpr
*/
LVal *builtin_head(LEnv *lenv, LVal *lval);
/**
* @brief Return the rest of the qexpr without the head
* @note eg: tail {0 1 2} => {1 2}
* @param *lenv: Not used
* @param *lval: A LVal with type qexpr and atleast one child
* @retval Tail of qexpr
*/
LVal *builtin_tail(LEnv *lenv, LVal *lval);
/**
* @brief Evaluate a qexpr
* @note Evaluates a qexpr as a sexpr using lval_eval
* @param *lenv: Not used
* @param *lval: LVal of type LVAL_QEXPR
* @retval Value of qexpr
*/
LVal *builtin_eval(LEnv *lenv, LVal *lval);
/**
* @brief Join multiple qexpr
* @param *lenv: Not used
* @param *lval: LVal of type LVAL_QEXPR with children of type LVAL_QEXPR
* @retval The joined lval
*/
LVal *builtin_join(LEnv *lenv, LVal *lval);
/**
* @brief Evaluate operation LVAL_SYM between LVAL_NUM
* @param *lenv: Not used
* @param *lval: LVal containing numbers as children
* @param *op: Corresponding operator as string for the operation
* @retval Result wrapped as LVal
*/
LVal *builtin_op(LEnv *lenv, LVal *lval, char *op);
/**
* @brief Evaluate comparision between two LVAL_NUM
* @param *lenv: Not used/Cast to void/Required for adding to a LEnv
* @param *lval: A LVal having children who are to be compared
* @param *op: The operator as a string
* @retval Result wrapped as a LVal
*/
LVal *builtin_cmp(LEnv *lenv, LVal *lval, char *op);
/**
* @brief A builtin for if conditional
* @param *lenv: The corresponding lval
* @param *lval: The lval containing the condition and body
* @retval Evaluation of lval which is in true condition
*/
LVal *builtin_if(LEnv *lenv, LVal *lval);
/**
* @brief Builtins for lambda expressions
* @param *lenv: The default LEnv
* @param *lval: LVal having two child QEXPR for lformals and lbody
* @retval A LVal of type LVAL_FUN wrapped using lval_wrap_lambda
*/
LVal *builtin_lambda(LEnv *lenv, LVal *lval);
/**
* @brief Builtin for creating local, global functions
* @note Used by builtin_def, builtin_put
* @param *lenv: The LEnv to be operated on
* @param *lval: A LVal containing QEXPR for symbols(paramters) and, their
* values
* @param *fun: Name of builtin, either "def" or "="
* @retval Evaluated LVal
*/
LVal *builtin_var(LEnv *lenv, LVal *lval, char *fun);
/* A wrapper to builtin_var for global definitions */
LVal *builtin_def(LEnv *lenv, LVal *lval);
/* A wrapper to builtin_var for local definitions */
LVal *builtin_put(LEnv *lenv, LVal *lval);
/**
* @brief Load files containing valid lispy expression
* @param *lenv: The environment where the expressions are loaded
* @param *lval: The LVal containing the filename
* @retval A LVal of result or LVAL_ERR on error
*/
LVal *builtin_load(LEnv *lenv, LVal *lval);
/**
* @brief Print a expression
* @param *lenv: A LEnv
* @param *lval: A LVal containing the expressions
* @retval A LVal of type LVAL_SEXPR
*/
LVal *builtin_print(LEnv *lenv, LVal *lval);
/**
* @brief Create a LVAL_ERR from string
* @param *lenv: A LEnv
* @param *lval: LVal containing error string
* @retval A LVal of type LVAL_ERR
*/
LVal *builtin_err(LEnv *lenv, LVal *lval);
/* Wrappers for single operations of builtin_op */
LVal *builtin_add(LEnv *lenv, LVal *lval);
LVal *builtin_sub(LEnv *lenv, LVal *lval);
LVal *builtin_mul(LEnv *lenv, LVal *lval);
LVal *builtin_div(LEnv *lenv, LVal *lval);
LVal *builtin_mod(LEnv *lenv, LVal *lval);
/* Wrappers for single operations of builtin_ord */
LVal *builtin_gt(LEnv *lenv, LVal *lval);
LVal *builtin_lt(LEnv *lenv, LVal *lval);
LVal *builtin_ge(LEnv *lenv, LVal *lval);
LVal *builtin_le(LEnv *lenv, LVal *lval);
/* Wrappers for single operations of builtin_cmp */
LVal *builtin_eq(LEnv *lenv, LVal *lval);
LVal *builtin_ne(LEnv *lenv, LVal *lval);
/**
* @brief Associate a builtin and its symbol in a LEnv
* @param *lenv: The LEnv where the builtin is to be stored
* @param *sym: The symbol name of the builtin
* @param lbuiltin: The lbuiltin to be associated with sym
* @retval None
*/
void lenv_add_builtin(LEnv *lenv, char *sym, LBuiltin lbuiltin);
/**
* @brief Add default builtins to LEnv
* @param *lenv: The LEnv where the builtins are to be added
* @retval None
*/
void lenv_init_builtins(LEnv *lenv);
///////////////////////////////////////////////////////////////////////////////
/* Functions to wrap primitives as LVal */
///////////////////////////////////////////////////////////////////////////////
LVal *lval_wrap_long(long num) {
LVal *lval = malloc(sizeof(LVal));
lval->type = LVAL_NUM;
lval->num = num;
return lval;
}
LVal *lval_wrap_sym(char *sym) {
LVal *lsym = malloc(sizeof(LVal));
lsym->type = LVAL_SYM;
lsym->sym = malloc(strlen(sym) + 1);
strcpy(lsym->sym, sym);
return lsym;
}
LVal *lval_wrap_err(char *fmt, ...) {
LVal *lerr = malloc(sizeof(LVal));
lerr->type = LVAL_ERR;
// Create a variable list to store the arguments
va_list va;
// Initialize the va_list
// va_start takes two arguments:
// The va_list and the last argument before ellipsis
va_start(va, fmt);
// Allocate maximum size of error string
lerr->err = malloc(MAX_ERR);
// Copy the va string to lerr->err atmost MAX_ERR bytes including null
// Leaving space for null byte is therefore required
vsnprintf(lerr->err, MAX_ERR - 1, fmt, va);
// Resize(Reduce) lerr->err to size of va string from MAX_ERR
// Again here, strlen doesn't output size of string including null byte
lerr->err = realloc(lerr->err, strlen(lerr->err) + 1);
// Free va_list
va_end(va);
return lerr;
}
LVal *lval_wrap_expr(int type) {
LVal *lval = malloc(sizeof(LVal));
lval->type = type;
lval->child_count = 0;
lval->children = NULL;
return lval;
}
LVal *lval_wrap_sexpr(void) { return lval_wrap_expr(LVAL_SEXPR); }
LVal *lval_wrap_qexpr(void) { return lval_wrap_expr(LVAL_QEXPR); }
LVal *lval_wrap_lbuiltin(LBuiltin lbuiltin) {
LVal *lfun = malloc(sizeof(LVal));
lfun->type = LVAL_FUN;
lfun->lbuiltin = lbuiltin;
return lfun;
}
LVal *lval_wrap_lambda(LVal *lformals, LVal *lbody) {
LVal *llambda = malloc(sizeof(LVal));
llambda->type = LVAL_FUN;
// lambdas are user functions so, lbuiltin field is set to NULL
llambda->lbuiltin = NULL;
// Also provide a new local environment
llambda->lenv = lenv_new();
// Set formals(parameter list) and the body of lambda
llambda->lformals = lformals;
llambda->lbody = lbody;
return llambda;
}
LVal *lval_wrap_str(char *str) {
LVal *lstr = malloc(sizeof(LVal));
lstr->type = LVAL_STR;
lstr->str = malloc(strlen(str) + 1);
strcpy(lstr->str, str);
return lstr;
}
///////////////////////////////////////////////////////////////////////////////
/* Functions to operate on LVal struct */
///////////////////////////////////////////////////////////////////////////////
void lval_del(LVal *lval) {
switch (lval->type) {
case LVAL_NUM:
break;
case LVAL_FUN:
if (!(lval->lbuiltin)) {
lenv_del(lval->lenv);
lval_del(lval->lformals);
lval_del(lval->lbody);
}
break;
case LVAL_ERR:
free(lval->err);
break;
case LVAL_SYM:
free(lval->sym);
break;
case LVAL_STR:
free(lval->str);
break;
case LVAL_SEXPR:
case LVAL_QEXPR:
for (int i = 0; i < lval->child_count; i++) {
lval_del(lval->children[i]);
}
free(lval->children);
break;
}
free(lval);
}
LVal *lval_copy(LVal *lval) {
LVal *copy = malloc(sizeof(LVal));
copy->type = lval->type;
switch (copy->type) {
case LVAL_NUM:
copy->num = lval->num;
break;
case LVAL_FUN:
if (lval->lbuiltin) {
copy->lbuiltin = lval->lbuiltin;
} else {
copy->lbuiltin = NULL;
copy->lenv = lenv_copy(lval->lenv);
copy->lformals = lval_copy(lval->lformals);
copy->lbody = lval_copy(lval->lbody);
}
break;
case LVAL_SYM:
copy->sym = malloc(strlen(lval->sym) + 1);
strcpy(copy->sym, lval->sym);
break;
case LVAL_ERR:
copy->err = malloc(strlen(lval->err) + 1);
strcpy(copy->err, lval->err);
break;
case LVAL_STR:
copy->str = malloc(strlen(lval->str) + 1);
strcpy(copy->str, lval->str);
break;
case LVAL_SEXPR:
case LVAL_QEXPR:
copy->child_count = lval->child_count;
copy->children = malloc(sizeof(LVal) * copy->child_count);
for (int i = 0; i < copy->child_count; i++) {
copy->children[i] = lval_copy(lval->children[i]);
}
break;
}
return copy;
}
// Add a single child LVal to parent LVal
LVal *lval_add(LVal *parent, LVal *child) {
parent->child_count += 1;
parent->children =
realloc(parent->children, sizeof(LVal *) * parent->child_count);
// Last child is child_count - 1 due to 0-based indexing
parent->children[parent->child_count - 1] = child;
return parent;
}
// Add addend's children to augend
LVal *lval_join(LVal *augend, LVal *addend) {
for (int i = 0; i < addend->child_count; i++) {
augend = lval_add(augend, addend->children[i]);
}
free(addend->children);
free(addend);
return augend;
}
LVal *lval_pop(LVal *lval, int index) {
LVal *popped = lval->children[index];
// Move memory one LVal to the left
memmove(&lval->children[index], // Destination
&lval->children[index + 1], // Source
(size_t)(sizeof(LVal *) * (lval->child_count - index - 1)) // Size
);
lval->child_count -= 1;
// Resize the `lval->children` array to the new size (i.e child_count - 1)
lval->children =
realloc(lval->children, sizeof(LVal *) * lval->child_count);
// Return LVal at the ith position
return popped;
}
// TODO: What is the point of doing a memmove if the LVal is going to be
// deleted?
LVal *lval_take(LVal *lval, int index) {
// Pop LVal at the given index
LVal *popped = lval_pop(lval, index);
// Delete the rest of the LVal
lval_del(lval);
// Return the popped value
return popped;
}
LVal *lval_call(LEnv *lenv, LVal *lfun, LVal *largs) {
// Return the lbuiltin itself if a lbuiltin
if (lfun->lbuiltin) {
return lfun->lbuiltin(lenv, largs);
}
// Store original args/params count
int nargs = largs->child_count;
int nparams = lfun->lformals->child_count;
// Part I: Assignment of args to params
while (largs->child_count) {
// Handle when args are remaining even after parameters are exhausted
if (lfun->lformals->child_count == 0) {
lval_del(largs);
return lval_wrap_err(
"Function was passed too many arguments!\n"
"Got %i, Expected %i",
nargs, nparams);
}
// Get the first variable symbol
LVal *lsym = lval_pop(lfun->lformals, 0);
// Handle variable arguments
if (strcmp(lsym->sym, "&") == 0) {
// Check there is only a single param(formal) following "&"
if (lfun->lformals->child_count != 1) {
lval_del(largs);
return lval_wrap_err(
"Function format invalid!\n"
"'&' not followed by a single symbol!");
}
// Get the next symbol
LVal *lsym_next = lval_pop(lfun->lformals, 0);
// Assign the next symbol the remaining args as qexpr
lenv_put(lfun->lenv, lsym_next, builtin_list(lenv, largs));
lval_del(lsym);
lval_del(lsym_next);
break;
}
// Else, without variable arguments
// Get the first variable's value
LVal *lsym_val = lval_pop(largs, 0);
// Puts the symbol and its value inside the environment
lenv_put(lfun->lenv, lsym, lsym_val);
lval_del(lsym);
lval_del(lsym_val);
}
// After exhausting all arguments delete `largs`
lval_del(largs);
// Part II: Evaluation
if (lfun->lformals->child_count > 0 &&
strcmp(lfun->lformals->children[0]->sym, "&") == 0) {
// Handle edge-case when `&` is not followed by a single argument,
// But wasn't caught by assignment due to absence of args
if (lfun->lformals->child_count != 2) {
return lval_wrap_err(
"Function format invalid!\n"
"'&' not followed by a single symbol!");
}
lval_del(lval_pop(lfun->lformals, 0));
LVal *lsym_next = lval_pop(lfun->lformals, 0);
LVal *lsym_val = lval_wrap_qexpr();
lenv_put(lfun->lenv, lsym_next, lsym_val);
lval_del(lsym_next);
lval_del(lsym_val);
}
// If all params(formals) are bound, evaluate
if (lfun->lformals->child_count == 0) {
lfun->lenv->parent = lenv;
return builtin_eval(
lfun->lenv, lval_add(lval_wrap_sexpr(), lval_copy(lfun->lbody)));
} else {
// For partial evaluation, return a copy of function
return lval_copy(lfun);
}
}
int lval_eq(LVal *first, LVal *second) {
if (first->type != second->type) {
return 0;
}
int type = first->type;
switch (type) {
case LVAL_NUM:
return (first->num == second->num);
case LVAL_ERR:
return (strcmp(first->err, second->err) == 0);
case LVAL_SYM:
return (strcmp(first->sym, second->sym) == 0);
case LVAL_STR:
return (strcmp(first->str, second->str) == 0);
case LVAL_FUN:
if (first->lbuiltin || second->lbuiltin) {
return (first->lbuiltin == second->lbuiltin);
} else {
return (lval_eq(first->lformals, second->lformals) &&
lval_eq(first->lbody, second->lbody));
}
case LVAL_QEXPR:
case LVAL_SEXPR:
if (first->child_count != second->child_count) {
return 0;
}
for (int i = 0; i < first->child_count; i++) {
if (!lval_eq(first->children[i], second->children[i])) {
return 0;
}
}
return 1;
default:
return 0;
}
}
///////////////////////////////////////////////////////////////////////////////
/* Functions to operate on LEnv's */
///////////////////////////////////////////////////////////////////////////////
LEnv *lenv_new(void) {
LEnv *lenv = malloc(sizeof(LEnv));
lenv->parent = NULL;
lenv->lvals = NULL;
lenv->syms = NULL;
lenv->child_count = 0;
return lenv;
}
void lenv_del(LEnv *lenv) {
for (int i = 0; i < lenv->child_count; i++) {
free(lenv->syms[i]);
lval_del(lenv->lvals[i]);
}
free(lenv->lvals);
free(lenv->syms);
free(lenv);
}
LVal *lenv_get(LEnv *hay, LVal *pin) {
// Check in local environment
for (int i = 0; i < hay->child_count; i++) {
if (strcmp(hay->syms[i], pin->sym) == 0) {
return lval_copy(hay->lvals[i]);
}
}
// If not found, check in its parent environment
if (hay->parent) {
return lenv_get(hay->parent, pin);
}
return lval_wrap_err("Unbound symbol: '%s'", pin->sym);
}
void lenv_put(LEnv *lenv, LVal *lsym, LVal *lval) {
for (int i = 0; i < lenv->child_count; i++) {
// Check if symbol already exists
if (strcmp(lenv->syms[i], lsym->sym) == 0) {
// If exists, delete it
lval_del(lenv->lvals[i]);
// Copy the new value from LVal
lenv->lvals[i] = lval_copy(lval);
return;
}
}
// If symbol is not present
// Increase child count
lenv->child_count += 1;
// Reallocate to accomodate new child
lenv->lvals = realloc(lenv->lvals, sizeof(LVal *) * lenv->child_count);
lenv->syms = realloc(lenv->syms, sizeof(char *) * lenv->child_count);
// Set symbol and its value as last child
lenv->syms[lenv->child_count - 1] = malloc(strlen(lsym->sym) + 1);
strcpy(lenv->syms[lenv->child_count - 1], lsym->sym);
lenv->lvals[lenv->child_count - 1] = lval_copy(lval);
}
LEnv *lenv_copy(LEnv *lenv) {
LEnv *copy = malloc(sizeof(LEnv));
copy->parent = lenv->parent;
copy->child_count = lenv->child_count;
copy->lvals = malloc(sizeof(LVal) * copy->child_count);
copy->syms = malloc(sizeof(char *) * copy->child_count);
for (int i = 0; i < copy->child_count; i++) {
copy->syms[i] = malloc(strlen(lenv->syms[i]) + 1);
strcpy(copy->syms[i], lenv->syms[i]);
copy->lvals[i] = lval_copy(lenv->lvals[i]);
}
return copy;
}
void lenv_put_global(LEnv *lenv, LVal *lsym, LVal *lval) {
while (lenv->parent) {
lenv = lenv->parent;
}
lenv_put(lenv, lsym, lval);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
LVal *lval_read_long(mpc_ast_t *node) {
errno = 0;
long val = strtol(node->contents, NULL, 10);
return errno != ERANGE ? lval_wrap_long(val)
: lval_wrap_err("Number too large!");
}
LVal *lval_read_str(mpc_ast_t *node) {
// Chops of ending quote
node->contents[strlen(node->contents) - 1] = '\0';
// Copies string without starting quote
char *unescaped = malloc(strlen(node->contents + 1) + 1);
unescaped = strcpy(unescaped, node->contents + 1);
// Unescape string
unescaped = mpcf_unescape(unescaped);
LVal *lstr = lval_wrap_str(unescaped);
free(unescaped);
return lstr;
}
LVal *lval_read_ast(mpc_ast_t *node) {
if (strstr(node->tag, "num")) {
return lval_read_long(node);
}
if (strstr(node->tag, "sym")) {
return lval_wrap_sym(node->contents);
}
if (strstr(node->tag, "str")) {
return lval_read_str(node);
}
LVal *root = NULL;
if ((strcmp(node->tag, ">") == 0) || (strstr(node->tag, "sexpr"))) {
root = lval_wrap_sexpr();
} else if (strstr(node->tag, "qexpr")) {
root = lval_wrap_qexpr();
}
for (int i = 0; i < node->children_num; i++) {
if ((strcmp(node->children[i]->contents, "(") == 0) ||
(strcmp(node->children[i]->contents, ")") == 0) ||
(strcmp(node->children[i]->contents, "{") == 0) ||
(strcmp(node->children[i]->contents, "}") == 0) ||
(strcmp(node->children[i]->tag, "regex") == 0) ||
(strstr(node->children[i]->tag, "comment"))) {
continue;
} else {
root = lval_add(root, lval_read_ast(node->children[i]));
}
}
return root;
}
///////////////////////////////////////////////////////////////////////////////
/* Functions to print LVal's */
///////////////////////////////////////////////////////////////////////////////
void lval_print(LVal *lval) {
switch (lval->type) {
case LVAL_NUM:
printf("%ld", lval->num);
break;
case LVAL_FUN:
if (lval->lbuiltin) {
printf("<builtin>");
} else {
printf("(\\ ");
lval_print(lval->lformals);
printf(" ");
lval_print(lval->lbody);
printf(")");
}
break;
case LVAL_ERR:
printf("Error: %s", lval->err);
break;
case LVAL_SYM:
printf("%s", lval->sym);
break;
case LVAL_STR:
lval_print_str(lval);
break;