forked from technoblogy/tiny-lisp-computer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TinyLispComputer.ino
2973 lines (2680 loc) · 79.2 KB
/
TinyLispComputer.ino
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
/* Tiny Lisp Computer 2 - uLisp 1.5
David Johnson-Davies - www.technoblogy.com - 24th January 2017
Licensed under the MIT license: https://opensource.org/licenses/MIT
*/
#include <setjmp.h>
#include <SPI.h>
// Compile options
#define checkoverflow
#define resetautorun
// #define printfreespace
#define serialmonitor
#define tinylispcomputer
// C Macros
#define nil NULL
#define car(x) (((object *) (x))->car)
#define cdr(x) (((object *) (x))->cdr)
#define first(x) (((object *) (x))->car)
#define second(x) (car(cdr(x)))
#define cddr(x) (cdr(cdr(x)))
#define third(x) (car(cdr(cdr(x))))
#define fourth(x) (car(cdr(cdr(cdr(x)))))
#define push(x, y) ((y) = cons((x),(y)))
#define pop(y) ((y) = cdr(y))
#define numberp(x) ((x)->type == NUMBER)
#define stringp(x) ((x)->type == STRING)
#define streamp(x) ((x)->type == STREAM)
#define listp(x) ((x) == NULL || (x)->type >= PAIR || (x)->type == ZERO)
#define consp(x) (((x)->type >= PAIR || (x)->type == ZERO) && (x) != NULL)
#define mark(x) (car(x) = (object *)(((unsigned int)(car(x))) | 0x8000))
#define unmark(x) (car(x) = (object *)(((unsigned int)(car(x))) & 0x7FFF))
#define marked(x) ((((unsigned int)(car(x))) & 0x8000) != 0)
// 1:Show GCs 2:show symbol addresses
// #define debug1
// #define debug2
// Constants
// RAMSTART, RAMEND, and E2END are defined by the processor's ioxxx.h file
const int RAMsize = RAMEND - RAMSTART + 1;
const int workspacesize = (RAMsize - RAMsize/4 - 280)/4;
const int EEPROMsize = E2END;
const int buflen = 17; // Length of longest symbol + 1
enum type {ZERO, SYMBOL, NUMBER, STRING, STREAM, PAIR }; // PAIR must be last
enum token { UNUSED, BRA, KET, QUO, DOT };
enum stream { SERIALSTREAM, I2CSTREAM, SPISTREAM };
enum function { SYMBOLS, NIL, TEE, LAMBDA, LET, LETSTAR, CLOSURE, SPECIAL_FORMS, QUOTE, DEFUN, DEFVAR,
SETQ, LOOP, PUSH, POP, INCF, DECF, SETF, DOLIST, DOTIMES, FORMILLIS, WITHI2C, WITHSPI, TAIL_FORMS, PROGN,
RETURN, IF, COND, WHEN, UNLESS, AND, OR, FUNCTIONS, NOT, NULLFN, CONS, ATOM, LISTP, CONSP, NUMBERP,
STREAMP, EQ, CAR, FIRST, CDR, REST, CAAR, CADR, SECOND, CDAR, CDDR, CAAAR, CAADR, CADAR, CADDR, THIRD,
CDAAR, CDADR, CDDAR, CDDDR, LENGTH, LIST, REVERSE, NTH, ASSOC, MEMBER, APPLY, FUNCALL, APPEND, MAPC,
MAPCAR, ADD, SUBTRACT, MULTIPLY, DIVIDE, MOD, ONEPLUS, ONEMINUS, ABS, RANDOM, MAX, MIN, NUMEQ, LESS,
LESSEQ, GREATER, GREATEREQ, NOTEQ, PLUSP, MINUSP, ZEROP, ODDP, EVENP, STRINGP, STRINGEQ, SUBSEQ, LOGAND,
LOGIOR, LOGXOR, LOGNOT, ASH, LOGBITP, READ, EVAL, GLOBALS, LOCALS, MAKUNBOUND, BREAK, PRINT, PRINC,
WRITEBYTE, READBYTE, RESTARTI2C, GC, ROOM, SAVEIMAGE, LOADIMAGE, CLS, PINMODE, DIGITALREAD, DIGITALWRITE,
ANALOGREAD, ANALOGWRITE, DELAY, MILLIS, NOTE, EDIT, ENDFUNCTIONS };
// Typedefs
typedef struct sobject {
union {
struct {
sobject *car;
sobject *cdr;
};
struct {
enum type type;
union {
unsigned int name;
int integer;
};
};
};
} object;
typedef object *(*fn_ptr_type)(object *, object *);
typedef struct {
const char *string;
fn_ptr_type fptr;
int min;
int max;
} tbl_entry_t;
// Global variables
jmp_buf exception;
object workspace[workspacesize];
unsigned int freespace = 0;
char ReturnFlag = 0;
object *freelist;
extern uint8_t _end;
int i2cCount;
object *GlobalEnv;
object *GCStack = NULL;
char buffer[buflen+1];
char BreakLevel = 0;
char LastChar = 0;
char LastPrint = 0;
volatile char Escape = 0;
char ExitEditor = 0;
char PrintReadably = 1;
// Forward references
object *tee;
object *tf_progn (object *form, object *env);
object *eval (object *form, object *env);
object *read ();
void repl(object *env);
void printobject (object *form);
char *lookupstring (unsigned int name);
int lookupfn (unsigned int name);
int builtin (char* n);
void Display (char c);
// Set up workspace
void initworkspace () {
freelist = NULL;
for (int i=workspacesize-1; i>=0; i--) {
object *obj = &workspace[i];
car(obj) = NULL;
cdr(obj) = freelist;
freelist = obj;
freespace++;
}
}
object *myalloc () {
if (freespace == 0) error(F("No room"));
object *temp = freelist;
freelist = cdr(freelist);
freespace--;
return temp;
}
inline void myfree (object *obj) {
car(obj) = NULL;
cdr(obj) = freelist;
freelist = obj;
freespace++;
}
// Make each type of object
object *number (int n) {
object *ptr = myalloc();
ptr->type = NUMBER;
ptr->integer = n;
return ptr;
}
object *cons (object *arg1, object *arg2) {
object *ptr = myalloc();
ptr->car = arg1;
ptr->cdr = arg2;
return ptr;
}
object *symbol (unsigned int name) {
object *ptr = myalloc();
ptr->type = SYMBOL;
ptr->name = name;
return ptr;
}
object *stream (unsigned char streamtype, unsigned char address) {
object *ptr = myalloc();
ptr->type = STREAM;
ptr->integer = streamtype<<8 | address;
return ptr;
}
// Garbage collection
void markobject (object *obj) {
MARK:
if (obj == NULL) return;
if (marked(obj)) return;
object* arg = car(obj);
int type = obj->type;
mark(obj);
if (type >= PAIR || type == ZERO) { // cons
markobject(arg);
obj = cdr(obj);
goto MARK;
}
if (type == STRING) {
obj = cdr(obj);
while (obj != NULL) {
arg = car(obj);
mark(obj);
obj = arg;
}
}
}
void sweep () {
freelist = NULL;
freespace = 0;
for (int i=workspacesize-1; i>=0; i--) {
object *obj = &workspace[i];
if (!marked(obj)) myfree(obj); else unmark(obj);
}
}
void gc (object *form, object *env) {
#if defined(debug1)
int start = freespace;
#endif
markobject(tee);
markobject(GlobalEnv);
markobject(GCStack);
markobject(form);
markobject(env);
sweep();
#if defined(debug1)
pchar('{');
pint(freespace - start);
pchar('}');
#endif
}
// Save-image and load-image
typedef struct {
unsigned int eval;
unsigned int datasize;
unsigned int globalenv;
unsigned int tee;
char data[];
} struct_image;
struct_image EEMEM image;
void movepointer (object *from, object *to) {
for (int i=0; i<workspacesize; i++) {
object *obj = &workspace[i];
int type = (obj->type) & 0x7FFF;
if (marked(obj) && type >= PAIR) {
if (car(obj) == (object *)((unsigned int)from | 0x8000))
car(obj) = (object *)((unsigned int)to | 0x8000);
if (cdr(obj) == from) cdr(obj) = to;
}
}
}
int compactimage (object **arg) {
markobject(tee);
markobject(GlobalEnv);
markobject(GCStack);
object *firstfree = workspace;
while (marked(firstfree)) firstfree++;
for (int i=0; i<workspacesize; i++) {
object *obj = &workspace[i];
if (marked(obj) && firstfree < obj) {
car(firstfree) = car(obj);
cdr(firstfree) = cdr(obj);
unmark(obj);
movepointer(obj, firstfree);
if (GlobalEnv == obj) GlobalEnv = firstfree;
if (GCStack == obj) GCStack = firstfree;
if (tee == obj) tee = firstfree;
if (*arg == obj) *arg = firstfree;
while (marked(firstfree)) firstfree++;
}
}
sweep();
return firstfree - workspace;
}
int saveimage (object *arg) {
unsigned int imagesize = compactimage(&arg);
// Save to EEPROM
if ((imagesize*4+8) > EEPROMsize) {
pfstring(F("Error: Image size too large: "));
pint(imagesize+2); pln();
GCStack = NULL;
longjmp(exception, 1);
}
eeprom_write_word(&image.datasize, imagesize);
eeprom_write_word(&image.eval, (unsigned int)arg);
eeprom_write_word(&image.globalenv, (unsigned int)GlobalEnv);
eeprom_write_word(&image.tee, (unsigned int)tee);
eeprom_write_block(workspace, image.data, imagesize*4);
return imagesize+2;
}
int loadimage () {
unsigned int imagesize = eeprom_read_word(&image.datasize);
if (imagesize == 0 || imagesize == 0xFFFF) error(F("No saved image"));
GlobalEnv = (object *)eeprom_read_word(&image.globalenv);
tee = (object *)eeprom_read_word(&image.tee) ;
eeprom_read_block(workspace, image.data, imagesize*4);
gc(NULL, NULL);
return imagesize+2;
}
// Error handling
void error (const __FlashStringHelper *string) {
pfstring(F("Error: "));
pfstring(string); pln();
GCStack = NULL;
longjmp(exception, 1);
}
void error2 (object *symbol, const __FlashStringHelper *string) {
pfstring(F("Error: '"));
printobject(symbol);
pfstring(F("' "));
pfstring(string); pln();
GCStack = NULL;
longjmp(exception, 1);
}
// Helper functions
int toradix40 (int ch) {
if (ch == 0) return 0;
if (ch >= '0' && ch <= '9') return ch-'0'+30;
ch = ch | 0x20;
if (ch >= 'a' && ch <= 'z') return ch-'a'+1;
error(F("Illegal character in symbol"));
return 0;
}
int fromradix40 (int n) {
if (n >= 1 && n <= 26) return 'a'+n-1;
if (n >= 30 && n <= 39) return '0'+n-30;
if (n == 27) return '-';
return 0;
}
int pack40 (char *buffer) {
return (((toradix40(buffer[0]) * 40) + toradix40(buffer[1])) * 40 + toradix40(buffer[2]));
}
int digitvalue (char d) {
if (d>='0' && d<='9') return d-'0';
d = d | 0x20;
if (d>='a' && d<='f') return d-'a'+10;
return 16;
}
char *name(object *obj){
buffer[3] = '\0';
if(obj->type != SYMBOL) error(F("Error in name"));
unsigned int x = obj->name;
if (x < ENDFUNCTIONS) return lookupstring(x);
for (int n=2; n>=0; n--) {
buffer[n] = fromradix40(x % 40);
x = x / 40;
}
return buffer;
}
int integer(object *obj){
if(obj->type != NUMBER) error(F("not a number"));
return obj->integer;
}
int istream(object *obj){
if(obj->type != STREAM) error(F("not a stream"));
return obj->integer;
}
int issymbol(object *obj, unsigned int n) {
return obj->type == SYMBOL && obj->name == n;
}
int eq (object *arg1, object *arg2) {
int same_object = (arg1 == arg2);
int same_symbol = (arg1->type == SYMBOL && arg2->type == SYMBOL && arg1->name == arg2->name);
int same_number = (arg1->type == NUMBER && arg2->type == NUMBER && arg1->integer == arg2->integer);
return (same_object || same_symbol || same_number);
}
// Lookup variable in environment
object *value(unsigned int n, object *env) {
while (env != NULL) {
object *item = car(env);
if(car(item)->name == n) return item;
env = cdr(env);
}
return nil;
}
object *findvalue (object *var, object *env) {
unsigned int varname = var->name;
object *pair = value(varname, env);
if (pair == NULL) pair = value(varname, GlobalEnv);
if (pair == NULL) error2(var,F("unknown variable"));
return pair;
}
object *findtwin (object *var, object *env) {
while (env != NULL) {
object *pair = car(env);
if (car(pair) == var) return pair;
env = cdr(env);
}
return NULL;
}
object *closure (int tail, object *fname, object *state, object *function, object *args, object **env) {
object *params = first(function);
function = cdr(function);
// Push state if not already in env
while (state != NULL) {
object *pair = first(state);
if (findtwin(car(pair), *env) == NULL) push(first(state), *env);
state = cdr(state);
}
// Add arguments to environment
while (params != NULL && args != NULL) {
object *var = first(params);
object *value = first(args);
if (tail) {
object *pair = findtwin(var, *env);
if (pair != NULL) cdr(pair) = value;
else push(cons(var,value), *env);
} else push(cons(var,value), *env);
params = cdr(params);
args = cdr(args);
}
if (params != NULL) error2(fname, F("has too few parameters"));
if (args != NULL) error2(fname, F("has too many parameters"));
// Do an implicit progn
return tf_progn(function, *env);
}
inline int listlength (object *list) {
int length = 0;
while (list != NULL) {
list = cdr(list);
length++;
}
return length;
}
inline int stringlength (object *form) {
int length = 0;
form = cdr(form);
while (form != NULL) {
int chars = form->integer;
if (chars & 0xFF) length++;
if (chars & 0xFF00) length++;
form = car(form);
}
return length;
}
char character (object *string, int n) {
object *arg = cdr(string);
for (int i=0; i<(n>>1); i++) {
if (arg == NULL) error(F("'subseq' index out of range"));
arg = car(arg);
}
char ch;
if (n&1) ch = (arg->integer) & 0xFF; else ch = (arg->integer)>>8 & 0xFF;
if (ch == 0) error(F("'subseq' index out of range"));
return ch;
}
object *apply (object *function, object *args, object **env) {
if (function->type == SYMBOL) {
unsigned int name = function->name;
int nargs = listlength(args);
if (name >= ENDFUNCTIONS) error2(function, F("is not a function"));
if (nargs<lookupmin(name)) error2(function, F("has too few arguments"));
if (nargs>lookupmax(name)) error2(function, F("has too many arguments"));
return ((fn_ptr_type)lookupfn(name))(args, *env);
}
if (listp(function) && issymbol(car(function), LAMBDA)) {
function = cdr(function);
object *result = closure(1, NULL, NULL, function, args, env);
return eval(result, *env);
}
if (listp(function) && issymbol(car(function), CLOSURE)) {
function = cdr(function);
object *result = closure(1, NULL, car(function), cdr(function), args, env);
return eval(result, *env);
}
error2(function, F("illegal function"));
return NULL;
}
// In-place operations
object **place (object *args, object *env) {
if (!consp(args)) return &cdr(findvalue(args, env));
object* function = first(args);
if (issymbol(function, CAR) || issymbol(function, FIRST)) {
object *value = eval(second(args), env);
if (!listp(value)) error(F("Can't take car"));
return &car(value);
}
if (issymbol(function, CDR) || issymbol(function, REST)) {
object *value = eval(second(args), env);
if (!listp(value)) error(F("Can't take cdr"));
return &cdr(value);
}
if (issymbol(function, NTH)) {
int index = integer(eval(second(args), env));
object *list = eval(third(args), env);
if (!consp(list)) error(F("'nth' second argument is not a list"));
while (index > 0) {
list = cdr(list);
if (list == NULL) error(F("'nth' index out of range"));
index--;
}
return &car(list);
}
error(F("Illegal place"));
return nil;
}
// Checked car and cdr
inline object *carx (object *arg) {
if (!listp(arg)) error(F("Can't take car"));
if (arg == nil) return nil;
return car(arg);
}
inline object *cdrx (object *arg) {
if (!listp(arg)) error(F("Can't take cdr"));
if (arg == nil) return nil;
return cdr(arg);
}
// I2C interface
#if defined(__AVR_ATmega328P__)
uint8_t const TWI_SDA_PIN = 18;
uint8_t const TWI_SCL_PIN = 19;
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
uint8_t const TWI_SDA_PIN = 20;
uint8_t const TWI_SCL_PIN = 21;
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284P__)
uint8_t const TWI_SDA_PIN = 17;
uint8_t const TWI_SCL_PIN = 16;
#elif defined(__AVR_ATmega32U4__)
uint8_t const TWI_SDA_PIN = 6;
uint8_t const TWI_SCL_PIN = 5;
#endif
uint32_t const F_TWI = 400000L; // Hardware I2C clock in Hz
uint8_t const TWSR_MTX_DATA_ACK = 0x28;
uint8_t const TWSR_MTX_ADR_ACK = 0x18;
uint8_t const TWSR_MRX_ADR_ACK = 0x40;
uint8_t const TWSR_START = 0x08;
uint8_t const TWSR_REP_START = 0x10;
uint8_t const I2C_READ = 1;
uint8_t const I2C_WRITE = 0;
void I2Cinit(bool enablePullup) {
TWSR = 0; // no prescaler
TWBR = (F_CPU/F_TWI - 16)/2; // set bit rate factor
if (enablePullup) {
digitalWrite(TWI_SDA_PIN, HIGH);
digitalWrite(TWI_SCL_PIN, HIGH);
}
}
uint8_t I2Cread(uint8_t last) {
TWCR = 1<<TWINT | 1<<TWEN | (last ? 0 : (1<<TWEA));
while (!(TWCR & 1<<TWINT));
return TWDR;
}
bool I2Cwrite(uint8_t data) {
TWDR = data;
TWCR = 1<<TWINT | 1 << TWEN;
while (!(TWCR & 1<<TWINT));
return (TWSR & 0xF8) == TWSR_MTX_DATA_ACK;
}
bool I2Cstart(uint8_t addressRW) {
TWCR = 1<<TWINT | 1<<TWSTA | 1<<TWEN; // send START condition
while (!(TWCR & 1<<TWINT));
if ((TWSR & 0xF8) != TWSR_START && (TWSR & 0xF8) != TWSR_REP_START) return false;
TWDR = addressRW; // send device address and direction
TWCR = 1<<TWINT | 1<<TWEN;
while (!(TWCR & 1<<TWINT));
if (addressRW & I2C_READ) return (TWSR & 0xF8) == TWSR_MRX_ADR_ACK;
else return (TWSR & 0xF8) == TWSR_MTX_ADR_ACK;
}
bool I2Crestart(uint8_t addressRW) {
return I2Cstart(addressRW);
}
void I2Cstop(void) {
TWCR = 1<<TWINT | 1<<TWEN | 1<<TWSTO;
while (TWCR & 1<<TWSTO); // wait until stop and bus released
}
// Special forms
object *sp_quote (object *args, object *env) {
(void) env;
return first(args);
}
object *sp_defun (object *args, object *env) {
(void) env;
object *var = first(args);
if (var->type != SYMBOL) error2(var, F("is not a symbol"));
object *val = cons(symbol(LAMBDA), cdr(args));
object *pair = value(var->name,GlobalEnv);
if (pair != NULL) { cdr(pair) = val; return var; }
push(cons(var, val), GlobalEnv);
return var;
}
object *sp_defvar (object *args, object *env) {
object *var = first(args);
if (var->type != SYMBOL) error2(var, F("is not a symbol"));
object *val = eval(second(args), env);
object *pair = value(var->name,GlobalEnv);
if (pair != NULL) { cdr(pair) = val; return var; }
push(cons(var, val), GlobalEnv);
return var;
}
object *sp_setq (object *args, object *env) {
object *arg = eval(second(args), env);
object *pair = findvalue(first(args), env);
cdr(pair) = arg;
return arg;
}
object *sp_loop (object *args, object *env) {
ReturnFlag = 0;
object *start = args;
for (;;) {
args = start;
while (args != NULL) {
object *form = car(args);
object *result = eval(form,env);
if (ReturnFlag == 1) {
ReturnFlag = 0;
return result;
}
args = cdr(args);
}
}
}
object *sp_push (object *args, object *env) {
object *item = eval(first(args), env);
object **loc = place(second(args), env);
push(item, *loc);
return *loc;
}
object *sp_pop (object *args, object *env) {
object **loc = place(first(args), env);
object *result = car(*loc);
pop(*loc);
return result;
}
object *sp_incf (object *args, object *env) {
object **loc = place(first(args), env);
int increment = 1;
int result = integer(*loc);
args = cdr(args);
if (args != NULL) increment = integer(eval(first(args), env));
#if defined(checkoverflow)
if (increment < 1) { if (-32768 - increment > result) error(F("'incf' arithmetic overflow")); }
else { if (32767 - increment < result) error(F("'incf' arithmetic overflow")); }
#endif
result = result + increment;
*loc = number(result);
return *loc;
}
object *sp_decf (object *args, object *env) {
object **loc = place(first(args), env);
int decrement = 1;
int result = integer(*loc);
args = cdr(args);
if (args != NULL) decrement = integer(eval(first(args), env));
#if defined(checkoverflow)
if (decrement < 1) { if (32767 + decrement < result) error(F("'decf' arithmetic overflow")); }
else { if (-32768 + decrement > result) error(F("'decf' arithmetic overflow")); }
#endif
result = result - decrement;
*loc = number(result);
return *loc;
}
object *sp_setf (object *args, object *env) {
object **loc = place(first(args), env);
object *result = eval(second(args), env);
*loc = result;
return result;
}
object *sp_dolist (object *args, object *env) {
object *params = first(args);
object *var = first(params);
object *result = nil;
object *list = eval(second(params), env);
if (!listp(list)) error(F("'dolist' argument is not a list"));
push(list, GCStack); // Don't GC the list
object *pair = cons(var,nil);
push(pair,env);
params = cdr(cdr(params));
if (params != NULL) result = car(params);
object *forms = cdr(args);
while (list != NULL) {
cdr(pair) = first(list);
list = cdr(list);
eval(tf_progn(forms,env), env);
}
cdr(pair) = nil;
pop(GCStack);
return eval(result, env);
}
object *sp_dotimes (object *args, object *env) {
object *params = first(args);
object *var = first(params);
object *result = nil;
int count = integer(eval(second(params), env));
int index = 0;
params = cdr(cdr(params));
if (params != NULL) result = car(params);
object *pair = cons(var,number(0));
push(pair,env);
object *forms = cdr(args);
while (index < count) {
cdr(pair) = number(index);
index++;
eval(tf_progn(forms,env), env);
}
cdr(pair) = number(index);
return eval(result, env);
}
object *sp_formillis (object *args, object *env) {
object *param = first(args);
unsigned long start = millis();
unsigned long now, total = 0;
if (param != NULL) total = integer(first(param));
eval(tf_progn(cdr(args),env), env);
do now = millis() - start; while (now < total);
if (now <= 32767) return number(now);
return nil;
}
object *sp_withi2c (object *args, object *env) {
object *params = first(args);
object *var = first(params);
int address = integer(eval(second(params), env));
params = cddr(params);
int read = 0; // Write
i2cCount = 0;
if (params != NULL) {
object *rw = eval(first(params), env);
if (numberp(rw)) i2cCount = integer(rw);
read = (rw != NULL);
}
I2Cinit(1); // Pullups
object *pair = cons(var, (I2Cstart(address<<1 | read)) ? stream(I2CSTREAM, address) : nil);
push(pair,env);
object *forms = cdr(args);
object *result = eval(tf_progn(forms,env), env);
I2Cstop();
return result;
}
object *sp_withspi (object *args, object *env) {
object *params = first(args);
object *var = first(params);
int pin = integer(eval(second(params), env));
int divider = 0, mode = 0, bitorder = 1;
object *pair = cons(var, stream(SPISTREAM, pin));
push(pair,env);
SPI.begin();
params = cddr(params);
if (params != NULL) {
int d = integer(eval(first(params), env));
if (d<1 || d>7) error(F("'with-spi' invalid divider"));
if (d == 7) divider = 3;
else if (d & 1) divider = (d>>1) + 4;
else divider = (d>>1) - 1;
params = cdr(params);
if (params != NULL) {
bitorder = (eval(first(params), env) == NULL);
params = cdr(params);
if (params != NULL) mode = integer(eval(first(params), env));
}
}
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
SPI.setBitOrder(bitorder);
SPI.setClockDivider(divider);
SPI.setDataMode(mode);
object *forms = cdr(args);
object *result = eval(tf_progn(forms,env), env);
digitalWrite(pin, HIGH);
SPI.end();
return result;
}
// Tail-recursive forms
object *tf_progn (object *args, object *env) {
if (args == NULL) return nil;
object *more = cdr(args);
while (more != NULL) {
eval(car(args), env);
args = more;
more = cdr(args);
}
return car(args);
}
object *tf_return (object *args, object *env) {
ReturnFlag = 1;
return tf_progn(args, env);
}
object *tf_if (object *args, object *env) {
if (eval(first(args), env) != nil) return second(args);
return third(args);
}
object *tf_cond (object *args, object *env) {
while (args != NULL) {
object *clause = first(args);
object *test = eval(first(clause), env);
object *forms = cdr(clause);
if (test != nil) {
if (forms == NULL) return test; else return tf_progn(forms, env);
}
args = cdr(args);
}
return nil;
}
object *tf_when (object *args, object *env) {
if (eval(first(args), env) != nil) return tf_progn(cdr(args),env);
else return nil;
}
object *tf_unless (object *args, object *env) {
if (eval(first(args), env) != nil) return nil;
else return tf_progn(cdr(args),env);
}
object *tf_and (object *args, object *env) {
if (args == NULL) return tee;
object *more = cdr(args);
while (more != NULL) {
if (eval(car(args), env) == NULL) return nil;
args = more;
more = cdr(args);
}
return car(args);
}
object *tf_or (object *args, object *env) {
object *more = cdr(args);
while (more != NULL) {
object *result = eval(car(args), env);
if (result != NULL) return result;
args = more;
more = cdr(args);
}
return car(args);
}
// Core functions
object *fn_not (object *args, object *env) {
(void) env;
return (first(args) == nil) ? tee : nil;
}
object *fn_cons (object *args, object *env) {
(void) env;
return cons(first(args),second(args));
}
object *fn_atom (object *args, object *env) {
(void) env;
object *arg1 = first(args);
return consp(arg1) ? nil : tee;
}
object *fn_listp (object *args, object *env) {
(void) env;
object *arg1 = first(args);
return listp(arg1) ? tee : nil;
}
object *fn_consp (object *args, object *env) {
(void) env;
object *arg1 = first(args);
return consp(arg1) ? tee : nil;
}
object *fn_numberp (object *args, object *env) {
(void) env;
object *arg1 = first(args);
return numberp(arg1) ? tee : nil;
}
object *fn_streamp (object *args, object *env) {
(void) env;
object *arg1 = first(args);
return streamp(arg1) ? tee : nil;
}
object *fn_eq (object *args, object *env) {
(void) env;
object *arg1 = first(args);
object *arg2 = second(args);
return eq(arg1, arg2) ? tee : nil;
}
// List functions
object *fn_car (object *args, object *env) {
(void) env;
return carx(first(args));
}
object *fn_cdr (object *args, object *env) {
(void) env;
return cdrx(first(args));
}
object *fn_caar (object *args, object *env) {
(void) env;
return carx(carx(first(args)));
}
object *fn_cadr (object *args, object *env) {
(void) env;
return carx(cdrx(first(args)));
}
object *fn_cdar (object *args, object *env) {
(void) env;
return cdrx(carx(first(args)));
}
object *fn_cddr (object *args, object *env) {
(void) env;
return cdrx(cdrx(first(args)));
}
object *fn_caaar (object *args, object *env) {
(void) env;
return carx(carx(carx(first(args))));
}
object *fn_caadr (object *args, object *env) {
(void) env;
return carx(carx(cdrx(first(args))));
}
object *fn_cadar (object *args, object *env) {
(void) env;
return carx(cdrx(carx(first(args))));
}
object *fn_caddr (object *args, object *env) {
(void) env;
return carx(cdrx(cdrx(first(args))));
}
object *fn_cdaar (object *args, object *env) {
(void) env;
return cdrx(carx(carx(first(args))));