-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathwisp.cpp
More file actions
1827 lines (1540 loc) · 62.3 KB
/
Copy pathwisp.cpp
File metadata and controls
1827 lines (1540 loc) · 62.3 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
/// A microlisp named Wisp, by Adam McDaniel
////////////////////////////////////////////////////////////////////////////////
/// LANGUAGE OPTIONS ///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Comment this define out to drop support for libm functions
#define HAS_LIBM
#ifdef HAS_LIBM
#include <cmath>
#else
#define NO_LIBM_SUPPORT "no libm support"
#endif
// Comment this define out to drop support for standard library functions.
// This allows the program to run without a runtime.
#define USE_STD
#ifdef USE_STD
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <ctime>
std::string read_file_contents(std::string filename) {
std::ifstream f;
f.open(filename.c_str());
if (!f)
throw std::runtime_error("could not open file");
f.seekg(0, std::ios::end);
std::string contents;
contents.reserve(f.tellg());
f.seekg(0, std::ios::beg);
contents.assign(std::istreambuf_iterator<char>(f),
std::istreambuf_iterator<char>());
f.close();
return contents;
}
#else
#define NO_STD "no standard library support"
#endif
////////////////////////////////////////////////////////////////////////////////
/// REQUIRED INCLUDES //////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#include <map>
#include <string>
#include <vector>
#include <sstream>
#include <exception>
////////////////////////////////////////////////////////////////////////////////
/// ERROR MESSAGES /////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#define TOO_FEW_ARGS "too few arguments to function"
#define TOO_MANY_ARGS "too many arguments to function"
#define INVALID_ARGUMENT "invalid argument"
#define MISMATCHED_TYPES "mismatched types"
#define CALL_NON_FUNCTION "called non-function"
#define UNKNOWN_ERROR "unknown exception"
#define INVALID_LAMBDA "invalid lambda"
#define INVALID_BIN_OP "invalid binary operation"
#define INVALID_ORDER "cannot order expression"
#define BAD_CAST "cannot cast"
#define ATOM_NOT_DEFINED "atom not defined"
#define EVAL_EMPTY_LIST "evaluated empty list"
#define INTERNAL_ERROR "interal virtual machine error"
#define INDEX_OUT_OF_RANGE "index out of range"
#define MALFORMED_PROGRAM "malformed program"
////////////////////////////////////////////////////////////////////////////////
/// TYPE NAMES /////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#define STRING_TYPE "string"
#define INT_TYPE "int"
#define FLOAT_TYPE "float"
#define UNIT_TYPE "unit"
#define FUNCTION_TYPE "function"
#define ATOM_TYPE "atom"
#define QUOTE_TYPE "quote"
#define LIST_TYPE "list"
////////////////////////////////////////////////////////////////////////////////
/// HELPER FUNCTIONS ///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Convert an object to a string using a stringstream conveniently
template <typename T>
std::string to_string(T t) {
// Create a stringstream
std::ostringstream ss;
// Convert the object to a string
ss << std::dec << t;
// Return the string
return ss.str();
}
// Replace a substring with a replacement string in a source string
void replace_substring(std::string &src, std::string substr, std::string replacement) {
size_t i=0;
for (i=src.find(substr, i); i!=std::string::npos; i=src.find(substr, i)) {
src.replace(i, substr.size(), replacement);
i += replacement.size();
}
}
// Is this character a valid lisp symbol character
bool is_symbol(char ch) {
return (isalnum(ch) || ispunct(ch)) && ch != '(' && ch != ')' && ch != '"' && ch != '\'';
}
////////////////////////////////////////////////////////////////////////////////
/// LISP CONSTRUCTS ////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Forward declaration for Environment class definition
class Value;
// An instance of a function's scope.
class Environment {
public:
// Default constructor
Environment() : parent_scope(NULL) {}
// Does this environment, or its parent environment,
// have this atom in scope?
// This is only used to determine which atoms to capture when
// creating a lambda function.
bool has(std::string name) const;
// Get the value associated with this name in this scope
Value get(std::string name) const;
// Set the value associated with this name in this scope
void set(std::string name, Value value);
void combine(Environment const &other);
void set_parent_scope(Environment *parent) {
parent_scope = parent;
}
// Output this scope in readable form to a stream.
friend std::ostream &operator<<(std::ostream &os, Environment const &v);
private:
// The definitions in the scope.
std::map<std::string, Value> defs;
Environment *parent_scope;
};
// An exception thrown by the lisp
class Error {
public:
// Create an error with the value that caused the error,
// the scope where the error was found, and the message.
Error(Value v, Environment const &env, const char *msg);
// Copy constructor is needed to prevent double frees
Error(Error const &other);
~Error();
// Get the printable error description.
std::string description();
private:
Value *cause;
Environment env;
const char *msg;
};
// The type for a builtin function, which takes a list of values,
// and the environment to run the function in.
typedef Value (*Builtin)(std::vector<Value>, Environment &);
class Value {
public:
////////////////////////////////////////////////////////////////////////////////
/// CONSTRUCTORS ///////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Constructs a unit value
Value() : type(UNIT) {}
// Constructs an integer
Value(int i) : type(INT) { stack_data.i = i; }
// Constructs a floating point value
Value(double f) : type(FLOAT) { stack_data.f = f; }
// Constructs a list
Value(std::vector<Value> list) : type(LIST), list(list) {}
// Construct a quoted value
static Value quote(Value quoted) {
Value result;
result.type = QUOTE;
// The first position in the list is
// used to store the quoted expression.
result.list.push_back(quoted);
return result;
}
// Construct an atom
static Value atom(std::string s) {
Value result;
result.type = ATOM;
// We use the `str` member to store the atom.
result.str = s;
return result;
}
// Construct a string
static Value string(std::string s) {
Value result;
result.type = STRING;
// We use the `str` member to store the string.
result.str = s;
return result;
}
// Construct a lambda function
Value(std::vector<Value> params, Value ret, Environment const &env) : type(LAMBDA) {
// We store the params and the result in the list member
// instead of having dedicated members. This is to save memory.
list.push_back(Value(params));
list.push_back(ret);
// Lambdas capture only variables that they know they will use.
std::vector<std::string> used_atoms = ret.get_used_atoms();
for (size_t i=0; i<used_atoms.size(); i++) {
// If the environment has a symbol that this lambda uses, capture it.
if (env.has(used_atoms[i]))
lambda_scope.set(used_atoms[i], env.get(used_atoms[i]));
}
}
// Construct a builtin function
Value(std::string name, Builtin b) : type(BUILTIN) {
// Store the name of the builtin function in the str member
// to save memory, and use the builtin function slot in the union
// to store the function pointer.
str = name;
stack_data.b = b;
}
////////////////////////////////////////////////////////////////////////////////
/// C++ INTEROP METHODS ////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Get all of the atoms used in a given Value
std::vector<std::string> get_used_atoms() {
std::vector<std::string> result, tmp;
switch (type) {
case QUOTE:
// The data for a quote is stored in the
// first slot of the list member.
return list[0].get_used_atoms();
case ATOM:
// If this is an atom, add it to the list
// of used atoms in this expression.
result.push_back(as_atom());
return result;
case LAMBDA:
// If this is a lambda, get the list of used atoms in the body
// of the expression.
return list[1].get_used_atoms();
case LIST:
// If this is a list, add each of the atoms used in all
// of the elements in the list.
for (size_t i=0; i<list.size(); i++) {
// Get the atoms used in the element
tmp = list[i].get_used_atoms();
// Add the used atoms to the current list of used atoms
result.insert(result.end(), tmp.begin(), tmp.end());
}
return result;
default:
return result;
}
}
// Is this a builtin function?
bool is_builtin() {
return type == BUILTIN;
}
// Apply this as a function to a list of arguments in a given environment.
Value apply(std::vector<Value> args, Environment &env);
// Evaluate this value as lisp code.
Value eval(Environment &env);
bool is_number() const {
return type == INT || type == FLOAT;
}
// Get the "truthy" boolean value of this value.
bool as_bool() const {
return *this != Value(0);
}
// Get this item's integer value
int as_int() const {
return cast_to_int().stack_data.i;
}
// Get this item's floating point value
double as_float() const {
return cast_to_int().stack_data.f;
}
// Get this item's string value
std::string as_string() const {
// If this item is not a string, throw a cast error.
if (type != STRING)
throw Error(*this, Environment(), BAD_CAST);
return str;
}
// Get this item's atom value
std::string as_atom() const {
// If this item is not an atom, throw a cast error.
if (type != ATOM)
throw Error(*this, Environment(), BAD_CAST);
return str;
}
// Get this item's list value
std::vector<Value> as_list() const {
// If this item is not a list, throw a cast error.
if (type != LIST)
throw Error(*this, Environment(), BAD_CAST);
return list;
}
// Push an item to the end of this list
void push(Value val) {
// If this item is not a list, you cannot push to it.
// Throw an error.
if (type != LIST)
throw Error(*this, Environment(), MISMATCHED_TYPES);
list.push_back(val);
}
// Push an item from the end of this list
Value pop() {
// If this item is not a list, you cannot pop from it.
// Throw an error.
if (type != LIST)
throw Error(*this, Environment(), MISMATCHED_TYPES);
// Remember the last item in the list
Value result = list[list.size()-1];
// Remove it from this instance
list.pop_back();
// Return the remembered value
return result;
}
////////////////////////////////////////////////////////////////////////////////
/// TYPECASTING METHODS ////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Cast this to an integer value
Value cast_to_int() const {
switch (type) {
case INT: return *this;
case FLOAT: return Value(int(stack_data.f));
// Only ints and floats can be cast to an int
default:
throw Error(*this, Environment(), BAD_CAST);
}
}
// Cast this to a floating point value
Value cast_to_float() const {
switch (type) {
case FLOAT: return *this;
case INT: return Value(float(stack_data.i));
// Only ints and floats can be cast to a float
default:
throw Error(*this, Environment(), BAD_CAST);
}
}
////////////////////////////////////////////////////////////////////////////////
/// COMPARISON OPERATIONS //////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool operator==(Value other) const {
// If either of these values are floats, promote the
// other to a float, and then compare for equality.
if (type == FLOAT && other.type == INT) return *this == other.cast_to_float();
else if (type == INT && other.type == FLOAT) return this->cast_to_float() == other;
// If the values types aren't equal, then they cannot be equal.
else if (type != other.type) return false;
switch (type) {
case FLOAT:
return stack_data.f == other.stack_data.f;
case INT:
return stack_data.i == other.stack_data.i;
case BUILTIN:
return stack_data.b == other.stack_data.b;
case STRING:
case ATOM:
// Both atoms and strings store their
// data in the str member.
return str == other.str;
case LAMBDA:
case LIST:
// Both lambdas and lists store their
// data in the list member.
return list == other.list;
case QUOTE:
// The values for quotes are stored in the
// first slot of the list member.
return list[0] == other.list[0];
default:
return true;
}
}
bool operator!=(Value other) const {
return !(*this == other);
}
// bool operator<(Value other) const {
// if (other.type != FLOAT && other.type != INT)
// throw Error(*this, Environment(), INVALID_BIN_OP);
// switch (type) {
// case FLOAT:
// return stack_data.f < other.cast_to_float().stack_data.f;
// case INT:
// if (other.type == FLOAT)
// return cast_to_float().stack_data.f < other.stack_data.f;
// else return stack_data.i < other.stack_data.i;
// default:
// throw Error(*this, Environment(), INVALID_ORDER);
// }
// }
////////////////////////////////////////////////////////////////////////////////
/// ORDERING OPERATIONS ////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
bool operator>=(Value other) const {
return !(*this < other);
}
bool operator<=(Value other) const {
return (*this == other) || (*this < other);
}
bool operator>(Value other) const {
return !(*this <= other);
}
bool operator<(Value other) const {
// Other type must be a float or an int
if (other.type != FLOAT && other.type != INT)
throw Error(*this, Environment(), INVALID_BIN_OP);
switch (type) {
case FLOAT:
// If this is a float, promote the other value to a float and compare.
return stack_data.f < other.cast_to_float().stack_data.f;
case INT:
// If the other value is a float, promote this value to a float and compare.
if (other.type == FLOAT)
return cast_to_float().stack_data.f < other.stack_data.f;
// Otherwise compare the integer values
else return stack_data.i < other.stack_data.i;
default:
// Only allow comparisons between integers and floats
throw Error(*this, Environment(), INVALID_ORDER);
}
}
////////////////////////////////////////////////////////////////////////////////
/// ARITHMETIC OPERATIONS //////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// This function adds two lisp values, and returns the lisp value result.
Value operator+(Value other) const {
// If the other value's type is the unit type,
// don't even bother continuing.
// Unit types consume all arithmetic operations.
if (other.type == UNIT) return other;
// Other type must be a float or an int
if ((is_number() || other.is_number()) &&
!(is_number() && other.is_number()))
throw Error(*this, Environment(), INVALID_BIN_OP);
switch (type) {
case FLOAT:
// If one is a float, promote the other by default and do
// float addition.
return Value(stack_data.f + other.cast_to_float().stack_data.f);
case INT:
// If the other type is a float, go ahead and promote this expression
// before continuing with the addition.
if (other.type == FLOAT)
return Value(cast_to_float() + other.stack_data.f);
// Otherwise, do integer addition.
else return Value(stack_data.i + other.stack_data.i);
case STRING:
// If the other value is also a string, do the concat
if (other.type == STRING)
return Value::string(str + other.str);
// We throw an error if we try to concat anything of non-string type
else throw Error(*this, Environment(), INVALID_BIN_OP);
case LIST:
// If the other value is also a list, do the concat
if (other.type == LIST) {
// Maintain the value that will be returned
Value result = *this;
// Add each item in the other list to the end of this list
for (size_t i=0; i<other.list.size(); i++)
result.push(other.list[i]);
return result;
} else throw Error(*this, Environment(), INVALID_BIN_OP);
case UNIT:
return *this;
default:
throw Error(*this, Environment(), INVALID_BIN_OP);
}
}
// This function subtracts two lisp values, and returns the lisp value result.
Value operator-(Value other) const {
// If the other value's type is the unit type,
// don't even bother continuing.
// Unit types consume all arithmetic operations.
if (other.type == UNIT) return other;
// Other type must be a float or an int
if (other.type != FLOAT && other.type != INT)
throw Error(*this, Environment(), INVALID_BIN_OP);
switch (type) {
case FLOAT:
// If one is a float, promote the other by default and do
// float subtraction.
return Value(stack_data.f - other.cast_to_float().stack_data.f);
case INT:
// If the other type is a float, go ahead and promote this expression
// before continuing with the subtraction
if (other.type == FLOAT)
return Value(cast_to_float().stack_data.f - other.stack_data.f);
// Otherwise, do integer subtraction.
else return Value(stack_data.i - other.stack_data.i);
case UNIT:
// Unit types consume all arithmetic operations.
return *this;
default:
// This operation was done on an unsupported type
throw Error(*this, Environment(), INVALID_BIN_OP);
}
}
// This function multiplies two lisp values, and returns the lisp value result.
Value operator*(Value other) const {
// If the other value's type is the unit type,
// don't even bother continuing.
// Unit types consume all arithmetic operations.
if (other.type == UNIT) return other;
// Other type must be a float or an int
if (other.type != FLOAT && other.type != INT)
throw Error(*this, Environment(), INVALID_BIN_OP);
switch (type) {
case FLOAT:
return Value(stack_data.f * other.cast_to_float().stack_data.f);
case INT:
// If the other type is a float, go ahead and promote this expression
// before continuing with the product
if (other.type == FLOAT)
return Value(cast_to_float().stack_data.f * other.stack_data.f);
// Otherwise, do integer multiplication.
else return Value(stack_data.i * other.stack_data.i);
case UNIT:
// Unit types consume all arithmetic operations.
return *this;
default:
// This operation was done on an unsupported type
throw Error(*this, Environment(), INVALID_BIN_OP);
}
}
// This function divides two lisp values, and returns the lisp value result.
Value operator/(Value other) const {
// If the other value's type is the unit type,
// don't even bother continuing.
// Unit types consume all arithmetic operations.
if (other.type == UNIT) return other;
// Other type must be a float or an int
if (other.type != FLOAT && other.type != INT)
throw Error(*this, Environment(), INVALID_BIN_OP);
switch (type) {
case FLOAT:
return Value(stack_data.f / other.cast_to_float().stack_data.f);
case INT:
// If the other type is a float, go ahead and promote this expression
// before continuing with the product
if (other.type == FLOAT)
return Value(cast_to_float().stack_data.f / other.stack_data.f);
// Otherwise, do integer multiplication.
else return Value(stack_data.i / other.stack_data.i);
case UNIT:
// Unit types consume all arithmetic operations.
return *this;
default:
// This operation was done on an unsupported type
throw Error(*this, Environment(), INVALID_BIN_OP);
}
}
// This function finds the remainder of two lisp values, and returns the lisp value result.
Value operator%(Value other) const {
// If the other value's type is the unit type,
// don't even bother continuing.
// Unit types consume all arithmetic operations.
if (other.type == UNIT) return other;
// Other type must be a float or an int
if (other.type != FLOAT && other.type != INT)
throw Error(*this, Environment(), INVALID_BIN_OP);
switch (type) {
// If we support libm, we can find the remainder of floating point values.
#ifdef HAS_LIBM
case FLOAT:
return Value(fmod(stack_data.f, other.cast_to_float().stack_data.f));
case INT:
if (other.type == FLOAT)
return Value(fmod(cast_to_float().stack_data.f, other.stack_data.f));
else return Value(stack_data.i % other.stack_data.i);
#else
case INT:
// If we do not support libm, we have to throw errors for floating point values.
if (other.type != INT)
throw Error(other, Environment(), NO_LIBM_SUPPORT);
return Value(stack_data.i % other.stack_data.i);
#endif
case UNIT:
// Unit types consume all arithmetic operations.
return *this;
default:
// This operation was done on an unsupported type
throw Error(*this, Environment(), INVALID_BIN_OP);
}
}
// Get the name of the type of this value
std::string get_type_name() {
switch (type) {
case QUOTE: return QUOTE_TYPE;
case ATOM: return ATOM_TYPE;
case INT: return INT_TYPE;
case FLOAT: return FLOAT_TYPE;
case LIST: return LIST_TYPE;
case STRING: return STRING_TYPE;
case BUILTIN:
case LAMBDA:
// Instead of differentiating between
// lambda and builtin types, we group them together.
// This is because they are both callable.
return FUNCTION_TYPE;
case UNIT:
return UNIT_TYPE;
default:
// We don't know the name of this type.
// This isn't the users fault, this is just unhandled.
// This should never be reached.
throw Error(*this, Environment(), INTERNAL_ERROR);
}
}
std::string display() const {
std::string result;
switch (type) {
case QUOTE:
return "'" + list[0].debug();
case ATOM:
return str;
case INT:
return to_string(stack_data.i);
case FLOAT:
return to_string(stack_data.f);
case STRING:
return str;
case LAMBDA:
for (size_t i=0; i<list.size(); i++) {
result += list[i].debug();
if (i < list.size()-1) result += " ";
}
return "(lambda " + result + ")";
case LIST:
for (size_t i=0; i<list.size(); i++) {
result += list[i].debug();
if (i < list.size()-1) result += " ";
}
return "(" + result + ")";
case BUILTIN:
return "<" + str + " at " + to_string(long(stack_data.b)) + ">";
case UNIT:
return "@";
default:
// We don't know how to display whatever type this is.
// This isn't the users fault, this is just unhandled.
// This should never be reached.
throw Error(*this, Environment(), INTERNAL_ERROR);
}
}
std::string debug() const {
std::string result;
switch (type) {
case QUOTE:
return "'" + list[0].debug();
case ATOM:
return str;
case INT:
return to_string(stack_data.i);
case FLOAT:
return to_string(stack_data.f);
case STRING:
for (size_t i=0; i<str.length(); i++) {
if (str[i] == '"') result += "\\\"";
else result.push_back(str[i]);
}
return "\"" + result + "\"";
case LAMBDA:
for (size_t i=0; i<list.size(); i++) {
result += list[i].debug();
if (i < list.size()-1) result += " ";
}
return "(lambda " + result + ")";
case LIST:
for (size_t i=0; i<list.size(); i++) {
result += list[i].debug();
if (i < list.size()-1) result += " ";
}
return "(" + result + ")";
case BUILTIN:
return "<" + str + " at " + to_string(long(stack_data.b)) + ">";
case UNIT:
return "@";
default:
// We don't know how to debug whatever type this is.
// This isn't the users fault, this is just unhandled.
// This should never be reached.
throw Error(*this, Environment(), INTERNAL_ERROR);
}
}
friend std::ostream &operator<<(std::ostream &os, Value const &v) {
return os << v.display();
}
private:
enum {
QUOTE,
ATOM,
INT,
FLOAT,
LIST,
STRING,
LAMBDA,
BUILTIN,
UNIT
} type;
union {
int i;
double f;
Builtin b;
} stack_data;
std::string str;
std::vector<Value> list;
Environment lambda_scope;
};
Error::Error(Value v, Environment const &env, const char *msg) : env(env), msg(msg) {
cause = new Value;
*cause = v;
}
Error::Error(Error const &other) : env(other.env), msg(other.msg) {
cause = new Value(*other.cause);
}
Error::~Error() {
delete cause;
}
std::string Error::description() {
return "error: the expression `" + cause->debug() + "` failed in scope " + to_string(env) + " with message \"" + msg + "\"";
}
void Environment::combine(Environment const &other) {
// Normally, I would use the `insert` method of the `map` class,
// but it doesn't overwrite previously declared values for keys.
std::map<std::string, Value>::const_iterator itr = other.defs.begin();
for (; itr!=other.defs.end(); itr++) {
// Iterate through the keys and assign each value.
defs[itr->first] = itr->second;
}
}
std::ostream &operator<<(std::ostream &os, Environment const &e) {
std::map<std::string, Value>::const_iterator itr = e.defs.begin();
os << "{ ";
for (; itr != e.defs.end(); itr++) {
os << '\'' << itr->first << "' : " << itr->second.debug() << ", ";
}
return os << "}";
}
void Environment::set(std::string name, Value value) {
defs[name] = value;
}
Value Value::apply(std::vector<Value> args, Environment &env) {
Environment e;
std::vector<Value> params;
switch (type) {
case LAMBDA:
// Get the list of parameter atoms
params = list[0].list;
if (params.size() != args.size())
throw Error(Value(args), env, args.size() > params.size()?
TOO_MANY_ARGS : TOO_FEW_ARGS
);
// Get the captured scope from the lambda
e = lambda_scope;
// And make this scope the parent scope
e.set_parent_scope(&env);
// Iterate through the list of parameters and
// insert the arguments into the scope.
for (size_t i=0; i<params.size(); i++) {
if (params[i].type != ATOM)
throw Error(*this, env, INVALID_LAMBDA);
// Set the parameter name into the scope.
e.set(params[i].str, args[i]);
}
// Evaluate the function body with the function scope
return list[1].eval(e);
case BUILTIN:
// Here, we call the builtin function with the current scope.
// This allows us to write special forms without syntactic sugar.
// For functions that are not special forms, we just evaluate
// the arguments before we run the function.
return (stack_data.b)(args, env);
default:
// We can only call lambdas and builtins
throw Error(*this, env, CALL_NON_FUNCTION);
}
}
Value Value::eval(Environment &env) {
std::vector<Value> args;
Value function;
Environment e;
switch (type) {
case QUOTE:
return list[0];
case ATOM:
return env.get(str);
case LIST:
if (list.size() < 1)
throw Error(*this, env, EVAL_EMPTY_LIST);
args = std::vector<Value>(list.begin() + 1, list.end());
// Only evaluate our arguments if it's not builtin!
// Builtin functions can be special forms, so we
// leave them to evaluate their arguments.
function = list[0].eval(env);
if (!function.is_builtin())
for (size_t i=0; i<args.size(); i++)
args[i] = args[i].eval(env);
return function.apply(
args,
env
);
default:
return *this;
}
}
void skip_whitespace(std::string &s, int &ptr) {
while (isspace(s[ptr])) { ptr++; }
}
// Parse a single value and increment the pointer
// to the beginning of the next value to parse.
Value parse(std::string &s, int &ptr) {
skip_whitespace(s, ptr);
// Skip comments
while (s[ptr] == ';') {
// If this is a comment
int work_ptr = ptr;
// Skip to the end of the line
while (s[work_ptr] != '\n' && work_ptr < int(s.length())) { work_ptr++; }
ptr = work_ptr;
skip_whitespace(s, ptr);
// If we're at the end of the string, return an empty value
if (s.substr(ptr, s.length()-ptr-1) == "")
return Value();
}
// Parse the value
if (s == "") {
return Value();
} else if (s[ptr] == '\'') {
// If this is a quote
ptr++;
return Value::quote(parse(s, ptr));
} else if (s[ptr] == '(') {
// If this is a list
skip_whitespace(s, ++ptr);
Value result = Value(std::vector<Value>());
while (s[ptr] != ')')
result.push(parse(s, ptr));
skip_whitespace(s, ++ptr);
return result;
} else if (isdigit(s[ptr]) || (s[ptr] == '-' && isdigit(s[ptr + 1]))) {
// If this is a number
bool negate = s[ptr] == '-';
if (negate) ptr++;
int save_ptr = ptr;
while (isdigit(s[ptr]) || s[ptr] == '.') ptr++;
std::string n = s.substr(save_ptr, ptr);
skip_whitespace(s, ptr);
if (n.find('.') != std::string::npos)
return Value((negate? -1 : 1) * atof(n.c_str()));
else return Value((negate? -1 : 1) * atoi(n.c_str()));
} else if (s[ptr] == '\"') {
// If this is a string
int n = 1;
while (s[ptr + n] != '\"') {
if (ptr + n >= int(s.length()))
throw std::runtime_error(MALFORMED_PROGRAM);
if (s[ptr + n] == '\\') n++;
n++;
}
std::string x = s.substr(ptr+1, n-1);
ptr += n+1;
skip_whitespace(s, ptr);
// Iterate over the characters in the string, and
// replace escaped characters with their intended values.
for (size_t i=0; i<x.size(); i++) {
if (x[i] == '\\' && x[i+1] == '\\')
x.replace(i, 2, "\\");
else if (x[i] == '\\' && x[i+1] == '"')
x.replace(i, 2, "\"");
else if (x[i] == '\\' && x[i+1] == 'n')
x.replace(i, 2, "\n");
else if (x[i] == '\\' && x[i+1] == 't')
x.replace(i, 2, "\t");