-
Notifications
You must be signed in to change notification settings - Fork 0
/
mll.d
executable file
·1254 lines (1030 loc) · 35.8 KB
/
mll.d
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
/**
* mll.d - My Little Lisp
*
* Author: Bystroushaak (bystrousak@kitakitsune.org)
* Version: 0.12.0
* Date: 01.09.2012
*
* Copyright:
* This work is licensed under a CC BY.
* http://creativecommons.org/licenses/by/3.0/
*
* TODO:
* skipStringsAndFind(char c)
*
* Remove var pro EnvStack
*/
module mll;
import std.string;
import std.container;
import core.exception;
import std.conv : to;
import std.algorithm : remove;
import std.stdio; // TODO: Remove
const string INF_PARAMS = "...";
static enum string[char] quoters = ['\'':"quote", '`':"quasiquote", ',':"unquote"];
// generate asoc. array reverse_quoters which have keys from quoters as values
// I just wanted try mixin :)
private string genReverseQuoters(){
string r_quoters = "static enum char[string] reverse_quoters = [";
foreach(char key, string val; quoters){
r_quoters ~= '"' ~ val ~ "\":'" ~ (key == '\'' ? "\\'" : "" ~ key) ~ "', ";
}
return r_quoters ~ "];";
}
mixin(genReverseQuoters());
static string[] builtins = [
"lambda",
"macro",
"quote",
"q",
"unquote",
"uq",
"quasiquote",
"qq",
"list",
"cons",
"defl",
"defg",
"set!",
"car",
"cdr",
"eq",
"atom",
"null?",
"if",
"cond",
"=",
"+",
"-",
"*",
"/",
">",
"<",
"<=",
">=",
"show_stack"
];
/*******************************************************************************
* Exceptions *******************************************************************
*******************************************************************************
* Exception tree:
*
* Exception
* '-> LispException
* |-> UndefinedSymbolException
* |-> BadNumberOfParametersException
* |-> BadTypeOfParametersException
* '-> ParseEception
* '-> BlankExpressionException
*
*/
class LispException : Exception{
this(string msg){
super(msg);
}
}
///
class ParseException : LispException{
this(string msg){
super(msg);
}
}
///
class BlankExpressionException : ParseException{
this(string msg){
super(msg);
}
}
///
class UndefinedSymbolException : LispException{
this(string msg){
super(msg);
}
}
///
class BadNumberOfParametersException : LispException{
this(string msg){
super(msg);
}
}
///
class BadTypeOfParametersException : LispException{
this(string msg){
super(msg);
}
}
/*******************************************************************************
* Objects **********************************************************************
*******************************************************************************/
/// Generic object used for representation everything in my little lisp.
class LispObject{
public string toString(){
if (typeid(this) == typeid(LispArray))
return (cast(LispArray) this).toString();
else if (typeid(this) == typeid(LispSymbol))
return (cast(LispSymbol) this).toString();
throw new Exception("Unimplemented : toString() for LispObject");
}
public string toLispString(){
if (typeid(this) == typeid(LispArray))
return (cast(LispArray) this).toLispString();
else if (typeid(this) == typeid(LispSymbol))
return (cast(LispSymbol) this).toLispString();
throw new Exception("Unimplemented : toLispString() for LispObject");
}
public string toSugar(){
if (typeid(this) == typeid(LispArray))
return (cast(LispArray) this).toSugar();
else if (typeid(this) == typeid(LispSymbol))
return (cast(LispSymbol) this).toLispString();
throw new Exception("Unimplemented : toSugar() for LispObject");
}
}
/// Object used for representation of mll arrays.
class LispArray : LispObject{
private LispObject[] members;
this(){}
this(LispObject[] members){
this.members = members;
}
// I didn't wanted to do this, but dmd forced me :( -> "Error: need 'this'
// to access member members" when calling la.members[0]
public LispObject[] getMembers(){
return members.dup;
}
/// Returns lisp representation of this list
public string toLispString(){
string output;
foreach(LispObject member; this.members)
output ~= member.toLispString() ~ " ";
// remove space from the end of last object
if (output.length >= 2)
output.length--;
// do not add () to top level object which contains whole dom
if (! (this.members.length == 1 && typeid(this.members[0]) == typeid(LispArray)))
output = "(" ~ output ~ ")";
return output;
}
/// Converts lisp tree of list expression to string with syntax sugar
public override string toSugar(){
string output;
LispArray a;
LispSymbol s;
LispObject[] members;
if (this.members.length > 0 &&
(s = cast(LispSymbol) this.members[0]) !is null && // first member LispSymbol
s.getName() in reverse_quoters){ // which name is in quoters
// remove clean lisp quoters and replace it with character
// representation from reverse_quoters
for(int j = 0; j < this.members.length; j++){
string name = s.getName();
if (j + 1 < this.members.length){
output ~= reverse_quoters[name] ~ this.members[j + 1].toSugar() ~ " ";
j += 2;
}else
output ~= this.members[j].toSugar() ~ " ";
}
}else
foreach(LispObject o; this.members)
output ~= o.toSugar() ~ " ";
// remove space from the end of last object
if (output.length >= 2)
output.length--;
// do not add () to top level object which contains whole dom
if (! (output.length > 0 && std.algorithm.indexOf(quoters.keys(), output[0]) >= 0))
output = "(" ~ output ~ ")";
return output;
}
/// Returns D representation of this list
public string toString(){
return to!string(members);
}
public bool opEquals(Object o){
LispArray a = cast(LispArray) o;
if (a is null)
return false;
LispObject[] arr_members = a.getMembers();
if (arr_members.length != this.members.length)
return false;
for(int i = 0; i < this.members.length; i++){
if (typeid(this.members[i]) != typeid(arr_members))
return false;
if (this.members[i] != arr_members[i])
return false;
}
return true;
}
}
/**
* LispSymbol - Object used for representing symbols in parsed tree
*/
class LispSymbol : LispObject{
private string name;
this(){}
this(string name){
this.name = name;
}
public string getName(){
return this.name;
}
// Necesarry when you want to use objects as keys in associative array
public override bool opEquals(Object o){
LispSymbol s = cast(LispSymbol) o;
return s && s.getName() == this.name;
}
public override int opCmp(Object o){
LispSymbol s = cast(LispSymbol) o;
if (!s)
return -1;
if (!(s && s.opEquals(this) && this.opEquals(s)))
return -1;
return this.name.length - s.name.length;
}
public override hash_t toHash(){
return this.name.length;
}
/// Return lisp representation of this object
public string toString(){
return this.name;
}
public override string toLispString(){
return this.name;
}
public override string toSugar(){
return this.name;
}
}
/**
* Environment Stack
*
* This object is used for storing functions and variables.
*/
class EnvStack{
private LispObject[LispSymbol] global_env;
private auto local_env = SList!(LispObject[LispSymbol])(); // Single linked list, much faster than array
public uint le_length;
private LispObject[LispSymbol] env;
public:
///
this(){
this.pushLevel();
}
/**
* Create new blank level of variable stack - used for multiple levels of
* local variables.
*/
void pushLevel(){
// Copy variables from previous scope to this - linear lookup in find()
// makes this two times faster, but little more memory expensive
if (local_env.empty){
LispObject[LispSymbol] le;
local_env.insert(le);
}else
local_env.insert(local_env.front().dup);
le_length++;
}
/**
* Remove level of local variables.
*
* See: pushLevel()
*/
void popLevel(){
if (le_length > 0){
local_env.removeFront();
le_length--;
}
}
/**
* Add new local (temporary) variable - this is used for mapping function
* arguments to local namespace.
*/
void addLocal(LispSymbol key, LispObject value){
env = local_env.front();
env[key] = value;
local_env.front(env);
}
/**
* Add new local variable.
*
* This function puts variables one level higher than addLocal(), so
* they survive definition (which happens in its own separate namespace,
* because every eval() call creates one).
*
* Variables could be type of LispSymbol or LispList.
*/
void addLocalVariable(LispSymbol key, LispObject value){
if (le_length > 1){
auto slice = local_env[];
slice.popFront(); // I want $ - 2
env = slice.front();
env[key] = value;
slice.front(env);
}else{
env = local_env.front();
env[key] = value;
local_env.front(env);
}
}
/// Same as addLocal, but adds variables to global namespace
void addGlobal(LispSymbol key, LispObject value){
global_env[key] = value;
}
/**
* Find and return representation of symbol.
*
* Throws:
* UndefinedSymbolException
*/
LispObject find(LispSymbol key){
if (key in local_env.front()) // key in local environment?
return local_env.front()[key];
if (key in global_env) // key in global environment?
return global_env[key];
return null;
}
/**
* Set value of DEFINED symbol.
*
* Throws:
* UndefinedSymbolException
*/
void set(LispSymbol key, LispObject val){
if (key in local_env.front()){ // key in local environment?
env = local_env.front();
env[key] = val;
local_env.front(env);
return;
}
if (key in global_env){ // key in global environment?
global_env[key] = val;
return;
}
throw new UndefinedSymbolException("Undefined symbol '" ~ to!string(key) ~ "'!");
}
///
string toString(){
string output = "Local env:\n";
for (int i = le_length - 1; i >= 0; i--){
output ~= "\t" ~ to!string(i) ~ ": " ~ to!string(local_env.front()) ~ "\n";
local_env.removeFront();
}
output ~= "\nGlobal env:\n";
output ~= "\t" ~ to!string(global_env) ~ "\n";
return output;
}
///
string toLispString(){
string output = ""; //((local (\n";
//for (int i = local_env.length - 1; i >= 0; i--){
// output ~= "\t(q (" ~ to!string(i) ~ "))\n";
//}
return output;
}
}
/*******************************************************************************
* Functions ********************************************************************
*******************************************************************************/
/**
* FindMatchingBracket - function, which go thru source and returns first
* matching bracket.
*
* Params:
* source = Lisp source, which MUST begins with bracket, which will used as
* opening bracket for search.
*
* TODO:
* Add support for builtin strings
*/
private int findMatchingBracket(string source){
if (source.length == 0)
return -1;
else if (source.length == 1)
throw new ParseException("Can't find matching bracket - your input string is too small.");
if (source[0] != '(')
throw new ParseException("Can't find matching bracket, because your string doesn't start with one!");
// find it
int i = 1;
int level = 1;
for (; i < source.length && level > 0; i++){
char c = source[i];
if (c == '(')
level++;
else if (c == ')')
level--;
}
if (level != 0)
return -1;
return i;
}
//TODO: Add support for builtin strings
private string[] splitSymbols(string symbols){
return symbols.split(" ");
}
/**
* See: parse() for details
*
*/
private LispObject[] parseTree(string source, bool first){
LispObject[] output;
source = source.strip();
if (source.length > 0 && std.algorithm.indexOf(quoters.keys() ~ '(', source[0]) < 0 && first)
throw new ParseException("Invalid expression; correct expressions starts with '(', not with '" ~ source[0] ~ "'!");
// create dom tree
LispArray la = new LispArray();
while(source.length > 0){
if (source[0] == '('){ // recursively parse everything inside expression
int expr_length = findMatchingBracket(source);
if (expr_length < 0)
throw new ParseException("Unclosed expression!\n>" ~ source ~ "< !!");
if (expr_length >= 2)
la.members ~= parseTree(source[1 .. expr_length - 1], false); // recursion, whee..
if (expr_length < source.length)
source = source[expr_length + 1 .. $];
else
source.length = 0;
}else{ // parse symbols
string tmp;
// to tmp save symbols in list until next expression (>>xe xa<< (exp)) -> tmp = xe xa
int next_expr = source.indexOf('(');
if (next_expr > 0){
tmp = source[0 .. next_expr];
if (next_expr < source.length)
source = source[next_expr .. $];
else
source.length = 0;
}else{
tmp = source;
source.length = 0;
}
// append symbols to the list
foreach(string symbol; tmp.splitSymbols()){
symbol = symbol.strip();
if (symbol.length > 0)
la.members ~= new LispSymbol(symbol);
}
}
}
output ~= la;
return output;
}
/**
* Convert lisp tree from parse() with syntax sugar `', to clear lisp containing
* only quasiquote, quote and unquote.
*/
LispObject sugarToRealLisp(LispObject o){
LispArray a;
LispSymbol s;
string name;
LispObject[] members;
if ((s = cast(LispSymbol) o) !is null){ // symbols quotation
name = s.getName();
if (name.length > 1 && std.algorithm.indexOf(quoters.keys(), name[0]) >= 0){ // if symbol starts with quoter
return new LispArray([new LispSymbol(quoters[name[0]]), new LispSymbol(name.length > 2 ? name[1 .. $] : "" ~ name[1])]);
}else if (std.algorithm.indexOf(quoters.keys(), name[0]) >= 0) // symbol IS quoter
throw new ParseException("Misplaced quoter >" ~ name ~ "< - quoters can't be used as symbols!");
else
return o;
}else if ((a = cast(LispArray) o) !is null){ // arays quotation
LispArray output = new LispArray();
members = a.getMembers();
LispObject m;
for(int i = 0; i < members.length; i++){
m = members[i];
if ((s = cast(LispSymbol) m) !is null){
name = s.getName();
// quote array
if (name.length == 1 && std.algorithm.indexOf(quoters.keys(), name[0]) >= 0){ // quoter before array
if (i + 1 <= members.length - 1){
if ((a = cast(LispArray) members[i + 1]) !is null){
output.members ~= new LispArray([new LispSymbol(quoters[name[0]]), sugarToRealLisp(a)]);
i += 2;
}else // quoter at the and of list
throw new ParseException("Misplaced quoter >" ~ name ~ "< - quoters can't be used as symbols!");
}else
throw new ParseException("Misplaced quoter >" ~ name ~ "< - quoters can't be used as symbols!");
}else
output.members ~= sugarToRealLisp(m);
}else if ((a = cast(LispArray) m) !is null) // arrays are recursively quoted
output.members ~= sugarToRealLisp(m);
else
throw new ParseException("Can't remove sugar - LispObject is not supported in arrays!");
}
if ((members = output.getMembers()).length == 1 && typeid(members[0]) == typeid(LispArray))
return members[0];
return output;
}else
throw new ParseException("Can't remove sugar - LispObject is not supported!");
}
/**
* Parse lisp source code to in-memory tree of symbols.
*
* Throws:
* ParseException
* RangeError
*
*/
public LispArray parse(string source){
source = source.strip();
if (source.length == 0)
return new LispArray();
if (std.algorithm.indexOf(quoters.keys(), source[0]) >= 0)
return cast(LispArray) (cast(LispArray) parseTree("(" ~ source ~ ")", true)[0]).getMembers()[0];
else
return cast(LispArray) (cast(LispArray) parseTree(source, true)[0]).getMembers()[0];
}
bool isNumeric(LispObject o){
LispSymbol s = cast(LispSymbol) o;
if (s is null)
return false;
try{
to!int(s.getName());
}catch(std.conv.ConvException){
try{
to!double(s.getName());
}catch(std.conv.ConvException){
return false;
}
}
return true;
}
bool isDouble(LispSymbol s){
if (!isNumeric(s))
return false;
if (s.getName().indexOf(",") >= 0 || s.getName().indexOf(".") >= 0)
return true;
return false;
}
/**
* Evaluate expression expr in environment env.
*
* Params:
* expr = parsed tree of lisp expressions
* env = environment of variables
*/
public LispObject eval(LispObject expr, EnvStack env){
env.pushLevel(); // install new local namespace
scope(exit){ // D, fuck yeah
env.popLevel();
}
LispArray la;
LispSymbol s;
LispObject[] parameters;
if ((s = cast(LispSymbol) expr) !is null){ // handle variables
string name = s.getName();
// look to the symbol table, return saved value, numeric value, or throw
// error, if expr is not value/number
LispObject o = env.find(s); // return saved value
if (o !is null)
return o;
else if (std.algorithm.indexOf(builtins, name) >= 0) // check if symbol is builtin
return expr;
else{
try{
to!long(name);
}catch(std.conv.ConvException){
try{
to!double(name);
}catch(std.conv.ConvException){
throw new UndefinedSymbolException("Undefined symbol " ~ name ~ "!");
}
}
}
return s; // return numeric value
}else if (((la = cast(LispArray) expr) !is null) && // builtin keyword calling; gimme LispArray
((parameters = la.getMembers()).length > 0) && // which have one or more members
(typeid(parameters[0]) == typeid(LispSymbol))){ // and first member is LispSymbol
// save useful information
s = cast(LispSymbol) parameters[0];
string name = s.getName().toLower();
parameters = parameters.remove(0); // get parameters
/// Used for checking lenght of array - this saves lot of space and repeatedly written code.
void checkParamLength(LispObject[] parameters, int expected_length, string name){
if (expected_length == 1 && parameters.length != 1)
throw new BadNumberOfParametersException(name ~ " expects only one parameter!");
else if (expected_length == 2 && parameters.length != 2)
throw new BadNumberOfParametersException(name ~ " expects two parameters!");
else if (expected_length != parameters.length)
throw new BadNumberOfParametersException(name ~ " expects " ~ to!string(expected_length) ~
" parameters, not " ~ to!string(parameters.length) ~ "!");
}
/* Internal keyword definitions ***************************************/
if (name == "lambda"){
checkParamLength(parameters, 2, "lambda");
return expr; // lambdas are returned back, because eval evals them later with args
}else if (name == "macro"){
checkParamLength(parameters, 2, "macro");
return expr; // macros are practically same as lambda
}else if (name == "q" || name == "quote"){
checkParamLength(parameters, 1, "quote");
return parameters[0];
}else if (name == "uq" || name == "unquote"){
checkParamLength(parameters, 1, "unquote");
return eval(new LispArray(parameters), env); // xex, eval really evaluate only lists
}else if (name == "qq" || name == "quasiquote"){
LispObject[] output;
// eval unquote in quasiquotes
if (parameters.length == 2 && (s = cast(LispSymbol) parameters[0]) !is null && (s.getName() == "uq" || s.getName() == "unquote"))
return eval(parameters[1], env);
// ou yeah, recursively make everything quasiquote
foreach(LispObject p; parameters){
if (typeid(p) == typeid(LispSymbol))
output ~= p;
else{
la = cast(LispArray) p;
output ~= eval(new LispArray([cast(LispObject) new LispSymbol("qq")] ~ la.getMembers()), env);
}
}
return new LispArray(output);
}else if (name == "list"){
return new LispArray(parameters);
}else if (name == "cons"){
checkParamLength(parameters, 2, "cons");
LispObject[] output;
foreach(LispObject lo; parameters){
lo = eval(lo, env);
if (typeid(lo) == typeid(LispSymbol))
output ~= lo;
else if (typeid(lo) == typeid(LispArray))
output ~= (cast(LispArray) lo).getMembers();
}
return new LispArray(output);
}else if (name == "defl" || name == "defg"){
checkParamLength(parameters, 2, "defl/defg");
// first parameter must be symbol - if parameter is array, try evaluate it to get symbol
if (typeid(parameters[0]) == typeid(LispArray))
s = cast(LispSymbol) eval(parameters[0], env);
else
s = cast(LispSymbol) parameters[0];
if (!s)
throw new BadTypeOfParametersException("Can't use " ~ s.toLispString() ~ " as idenfiticator!");
parameters[1] = eval(parameters[1], env);
if (name == "defg")
env.addGlobal(s, parameters[1]);
else
env.addLocalVariable(s, parameters[1]);
return s;
}else if (name == "set!"){
checkParamLength(parameters, 2, "set!");
// first parameter must be symbol - if parameter is array, try evaluate it to get symbol
if (typeid(parameters[0]) == typeid(LispArray))
s = cast(LispSymbol) eval(parameters[0], env);
else
s = cast(LispSymbol) parameters[0];
if (!s)
throw new BadTypeOfParametersException("Can't use " ~ s.toLispString() ~ " as idenfiticator!");
env.set(s, parameters[1]);
return s;
}else if (name == "car"){
checkParamLength(parameters, 1, "car");
parameters[0] = eval(parameters[0], env);
if (typeid(parameters[0]) != typeid(LispArray))
throw new BadTypeOfParametersException(parameters[0].toLispString() ~ " is not a list!");
if ((la = cast(LispArray) parameters[0]).getMembers().length > 0)
return la.getMembers()[0];
else
return new LispArray();
}else if (name == "cdr"){
checkParamLength(parameters, 1, "cdr");
parameters[0] = eval(parameters[0], env);
if (typeid(parameters[0]) != typeid(LispArray))
throw new BadTypeOfParametersException(parameters[0].toLispString() ~ " is not a list!");
if ((la = cast(LispArray) parameters[0]).getMembers().length > 1)
return new LispArray(la.getMembers()[1 .. $]);
else
return new LispArray();
}else if (name == "eq"){
checkParamLength(parameters, 2, "eq");
if (eval(parameters[0], env) == eval(parameters[1], env))
return new LispArray([new LispSymbol("t")]);
else
return new LispArray();
}else if (name == "atom?"){
checkParamLength(parameters, 1, "atom?");
s = cast(LispSymbol) eval(parameters[0], env);
if (s is null)
return new LispArray();
try
to!int(s.getName());
catch(std.conv.ConvException)
try
to!double(s.getName());
catch(std.conv.ConvException)
return new LispArray();
return new LispArray([new LispSymbol("t")]);
}else if (name == "null?"){
checkParamLength(parameters, 1, "null?");
la = cast(LispArray) eval(parameters[0], env);
if (la && la.getMembers().length == 0)
return new LispArray([new LispSymbol("t")]);
else
return new LispArray();
}else if (name == "if"){
checkParamLength(parameters, 3, "if");
la = cast(LispArray) eval(parameters[0], env);
if (la && la.getMembers().length == 0) // == false
return eval(parameters[2], env);
else
return eval(parameters[1], env);
}else if (name == "cond"){
if (parameters.length == 0)
throw new BadTypeOfParametersException("cond requires at least one parameter!");
foreach(LispObject o; parameters){
// o = eval(o, env);
la = cast(LispArray) o;
if (la is null)
throw new BadTypeOfParametersException("Can't use symbols as parameters!");
LispObject[] cond_params = la.getMembers();
if (cond_params.length != 2)
throw new BadNumberOfParametersException("cond expects pair of arguments!");
la = cast(LispArray) eval(cond_params[0], env);
if (! (la && la.getMembers().length == 0)) // == true
return eval(cond_params[1], env);
}
}else if (std.algorithm.indexOf(["+", "-", "*", "/"], name) >= 0){ // arithmetic, wheee
if (parameters.length < 2 && name != "-")
throw new BadNumberOfParametersException(name ~ " require at least two parameters!");
else if (parameters.length < 1 && name == "-")
throw new BadNumberOfParametersException("- requires at least one parameter!");
// check if parameters are numbers
LispObject o;
LispSymbol[] args;
foreach(LispObject arg; parameters){
o = eval(arg, env);
if ((s = cast(LispSymbol) o) is null || !isNumeric(s))
throw new BadTypeOfParametersException(name ~ "expects only numbers as parameters!");
args ~= s;
}
// double vs int values :3
long iresult;
double dresult;
bool use_iresult = !isDouble(args[0]);
if (use_iresult)
iresult = to!long(args[0].getName());
else
dresult = to!double(args[0].getName());
if (args.length == 1 && name == "-")
return new LispSymbol(to!string(0 - (use_iresult ? iresult : dresult)));
args = args.remove(0);
foreach(LispSymbol arg; args){
if (use_iresult && arg.isDouble()){
dresult = iresult;
use_iresult = false;
}
if (name == "+"){
if (use_iresult)
iresult += to!long(arg.getName());
else
dresult += to!double(arg.getName());
}else if (name == "-"){
if (use_iresult)
iresult -= to!long(arg.getName());
else
dresult -= to!double(arg.getName());
}else if (name == "*"){
if (use_iresult)
iresult *= to!long(arg.getName());
else
dresult *= to!double(arg.getName());
}else if (name == "/"){
if (use_iresult)
iresult /= to!long(arg.getName());
else
dresult /= to!double(arg.getName());
}else
throw new LispException("Goofy please..");
}
return new LispSymbol(to!string(use_iresult ? iresult : dresult));
}else if (std.algorithm.indexOf(["<", ">", "<=", ">=", "="], name) >= 0){
checkParamLength(parameters, 2, name);
LispSymbol p1 = cast(LispSymbol) eval(parameters[0], env);
LispSymbol p2 = cast(LispSymbol) eval(parameters[1], env);
if (p1 is null || p2 is null)
throw new BadTypeOfParametersException(name ~ " parameters can't be lists!");
if (!(isNumeric(p1) && isNumeric(p2)))
throw new BadTypeOfParametersException(name ~ " parameters must be numeric!");
double n1, n2;
n1 = to!double(p1.getName());
n2 = to!double(p2.getName());
if (name == "<")
return (n1 < n2 ? new LispArray([new LispSymbol("t")]) : new LispArray());
else if (name == ">")
return (n1 > n2 ? new LispArray([new LispSymbol("t")]) : new LispArray());
else if (name == "<=")
return (n1 <= n2 ? new LispArray([new LispSymbol("t")]) : new LispArray());
else if (name == ">=")
return (n1 >= n2 ? new LispArray([new LispSymbol("t")]) : new LispArray());
else if (name == "=")
return (n1 == n2 ? new LispArray([new LispSymbol("t")]) : new LispArray());
else
throw new LispException("Goofy please..");
}else if (name == "show_stack"){
std.stdio.writeln(env);
return new LispArray();
}
}
parameters = (cast(LispArray) expr).getMembers();
if (parameters.length == 0)
return expr;
// eval first symbol/list - needed for macro call detection
LispObject[] par_values = [eval(parameters[0], env)];