-
Notifications
You must be signed in to change notification settings - Fork 46
/
ulisp-avr-comments.ino
7478 lines (6929 loc) · 229 KB
/
ulisp-avr-comments.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
/* uLisp AVR Release 4.7 - www.ulisp.com
David Johnson-Davies - www.technoblogy.com - 3rd November 2024
Licensed under the MIT license: https://opensource.org/licenses/MIT
*/
// Lisp Library
const char LispLibrary[] PROGMEM = "";
// Compile options
#define checkoverflow
// #define resetautorun
#define printfreespace
// #define printgcs
// #define sdcardsupport
// #define lisplibrary
#define assemblerlist
// #define lineeditor
// #define vt100
// #define extensions
// Includes
// #include "LispLibrary.h"
#include <avr/sleep.h>
#include <setjmp.h>
#include <SPI.h>
#include <limits.h>
#if defined(sdcardsupport)
#include <SD.h>
#define SDSIZE 172
#else
#define SDSIZE 0
#endif
// Platform specific settings
#define WORDALIGNED __attribute__((aligned (2)))
#define OBJECTALIGNED __attribute__((aligned (4)))
#define BUFFERSIZE 22 /* longest builtin name + 1 */
#if defined(ARDUINO_AVR_MEGA2560)
#include <EEPROM.h>
#define WORKSPACESIZE (1344-SDSIZE) /* Objects (4*bytes) */
#define EEPROMSIZE 4096 /* Bytes */
#define STACKDIFF 320
#define CPU_ATmega2560
#elif defined(__AVR_ATmega1284P__)
#include "optiboot.h"
#define WORKSPACESIZE (2944-SDSIZE) /* Objects (4*bytes) */
// #define EEPROMSIZE 4096 /* Bytes */
#define FLASHWRITESIZE 16384 /* Bytes */
#define CODESIZE 96 /* Bytes <= 256 */
#define STACKDIFF 320
#define CPU_ATmega1284P
#elif defined(__AVR_AVR128DA48__)
#include <Flash.h>
#define Serial Serial1
#define WORKSPACESIZE (2920-SDSIZE) /* Objects (4*bytes) */
#define FLASHWRITESIZE 15872 /* Bytes */
#define CODESIZE 96 /* Bytes <= 512 */
#define STACKDIFF 320
#define CPU_AVR128DX48
#define LED_BUILTIN 20
#elif defined(__AVR_AVR128DB48__)
#include <Flash.h>
#define Serial Serial3
#define WORKSPACESIZE (2920-SDSIZE) /* Objects (4*bytes) */
#define FLASHWRITESIZE 15872 /* Bytes */
#define CODESIZE 96 /* Bytes <= 512 */
#define STACKDIFF 320
#define CPU_AVR128DX48
#define LED_BUILTIN 20
#else
#error "Board not supported!"
#endif
// C Macros
#define nil NULL
#define car(x) (((object *) (x))->car)
#define cdr(x) (((object *) (x))->cdr)
#define first(x) car(x)
#define rest(x) cdr(x)
#define second(x) first(rest(x))
#define cddr(x) cdr(cdr(x))
#define third(x) first(cddr(x))
#define push(x, y) ((y) = cons((x),(y)))
#define pop(y) ((y) = cdr(y))
#define protect(y) push((y), GCStack)
#define unprotect() pop(GCStack)
#define integerp(x) ((x) != NULL && (x)->type == NUMBER)
#define symbolp(x) ((x) != NULL && (x)->type == SYMBOL)
#define stringp(x) ((x) != NULL && (x)->type == STRING)
#define characterp(x) ((x) != NULL && (x)->type == CHARACTER)
#define arrayp(x) ((x) != NULL && (x)->type == ARRAY)
#define streamp(x) ((x) != NULL && (x)->type == STREAM)
#define mark(x) (car(x) = (object *)(((uintptr_t)(car(x))) | MARKBIT))
#define unmark(x) (car(x) = (object *)(((uintptr_t)(car(x))) & ~MARKBIT))
#define marked(x) ((((uintptr_t)(car(x))) & MARKBIT) != 0)
#define MARKBIT 1
#define setflag(x) (Flags = Flags | 1<<(x))
#define clrflag(x) (Flags = Flags & ~(1<<(x)))
#define tstflag(x) (Flags & 1<<(x))
#define issp(x) (x == ' ' || x == '\n' || x == '\r' || x == '\t')
#define isbr(x) (x == ')' || x == '(' || x == '"' || x == '#' || x == '\'')
#define fntype(x) (getminmax((uint16_t)(x))>>6)
#define longsymbolp(x) (((x)->name & 0x03) == 0)
#define longnamep(x) (((x) & 0x03) == 0)
#define twist(x) ((uint16_t)((x)<<2) | (((x) & 0xC000)>>14))
#define untwist(x) (((x)>>2 & 0x3FFF) | ((x) & 0x03)<<14)
#define arraysize(x) (sizeof(x) / sizeof(x[0]))
#define stringifyX(x) #x
#define stringify(x) stringifyX(x)
#define PACKEDS 17600
#define BUILTINS 64000
#define ENDFUNCTIONS 1536
// Code marker stores start and end of code block (max 256 bytes)
#define startblock(x) ((x->integer) & 0xFF)
#define endblock(x) ((x->integer) >> 8 & 0xFF)
#define SDCARD_SS_PIN 10
// Constants
#define TRACEMAX 3 // Maximum number of traced functions
enum type { ZZERO=0, SYMBOL=2, CODE=4, NUMBER=6, STREAM=8, CHARACTER=10, ARRAY=12, STRING=14, PAIR=16 }; // ARRAY STRING and PAIR must be last
enum token { UNUSED, BRA, KET, QUO, DOT };
enum stream { SERIALSTREAM, I2CSTREAM, SPISTREAM, SDSTREAM, STRINGSTREAM };
enum fntypes_t { OTHER_FORMS, TAIL_FORMS, FUNCTIONS, SPECIAL_FORMS };
// Stream names used by printobject
const char serialstream[] PROGMEM = "serial";
const char i2cstream[] PROGMEM = "i2c";
const char spistream[] PROGMEM = "spi";
const char sdstream[] PROGMEM = "sd";
const char stringstream[] PROGMEM = "string";
PGM_P const streamname[] PROGMEM = {serialstream, i2cstream, spistream, sdstream, stringstream};
// Typedefs
typedef uint16_t symbol_t;
typedef uint16_t builtin_t;
typedef uint16_t chars_t;
typedef struct sobject {
union {
struct {
sobject *car;
sobject *cdr;
};
struct {
unsigned int type;
union {
symbol_t name;
int integer;
chars_t chars; // For strings
};
};
};
} object;
typedef object *(*fn_ptr_type)(object *, object *);
typedef void (*mapfun_t)(object *, object **);
typedef int (*intfn_ptr_type)(int w, int x, int y, int z);
typedef const struct {
const char *string;
fn_ptr_type fptr;
uint8_t minmax;
const char *doc;
} tbl_entry_t;
typedef int (*gfun_t)();
typedef void (*pfun_t)(char);
enum builtins: builtin_t { NIL, TEE, NOTHING, OPTIONAL, FEATURES, INITIALELEMENT, ELEMENTTYPE, TEST, COLONA, COLONB,
COLONC, BIT, AMPREST, LAMBDA, LET, LETSTAR, CLOSURE, PSTAR, QUOTE, DEFUN, DEFVAR, DEFCODE, EQ, CAR, FIRST,
CDR, REST, NTH, AREF, CHAR, STRINGFN, PINMODE, DIGITALWRITE, ANALOGREAD, ANALOGREFERENCE, REGISTER,
FORMAT,
};
// Global variables
uint8_t FLAG __attribute__ ((section (".noinit")));
object Workspace[WORKSPACESIZE] OBJECTALIGNED;
#if defined(CODESIZE)
uint8_t MyCode[CODESIZE] WORDALIGNED; // Must be even
#endif
jmp_buf toplevel_handler;
jmp_buf *handler = &toplevel_handler;
unsigned int Freespace = 0;
object *Freelist;
unsigned int I2Ccount;
unsigned int TraceFn[TRACEMAX];
unsigned int TraceDepth[TRACEMAX];
builtin_t Context;
#define BACKTRACESIZE 8
uint8_t TraceStart = 0, TraceTop = 0;
symbol_t Backtrace[BACKTRACESIZE];
object *GlobalEnv;
object *GCStack = NULL;
object *GlobalString;
object *GlobalStringTail;
int GlobalStringIndex = 0;
uint8_t PrintCount = 0;
uint8_t BreakLevel = 0;
char LastChar = 0;
char LastPrint = 0;
uint16_t RandomSeed;
// Flags
enum flag { PRINTREADABLY, RETURNFLAG, ESCAPE, EXITEDITOR, LIBRARYLOADED, NOESC, NOECHO, MUFFLEERRORS, BACKTRACE };
typedef uint16_t flags_t;
volatile flags_t Flags = 1<<PRINTREADABLY; // Set by default
// Forward references
object *tee;
void pfstring (PGM_P s, pfun_t pfun);
// Error handling
int modbacktrace (int n) {
return (n+BACKTRACESIZE) % BACKTRACESIZE;
}
/*
printbacktrace - prints a call backtrace for error messages and break.
*/
void printbacktrace () {
if (TraceStart != TraceTop) pserial('[');
int tracesize = modbacktrace(TraceTop-TraceStart);
for (int i=1; i<=tracesize; i++) {
printsymbol(symbol(Backtrace[modbacktrace(TraceTop-i)]), pserial);
if (i!=tracesize) pfstring(PSTR(" <- "), pserial);
}
if (TraceStart != TraceTop) pserial(']');
}
/*
errorsub - used by all the error routines.
Prints: "Error: 'fname' string", where fname is the name of the Lisp function in which the error occurred.
*/
void errorsub (symbol_t fname, PGM_P string) {
pfl(pserial); pfstring(PSTR("Error"), pserial);
if (TraceStart != TraceTop) pserial(' ');
printbacktrace();
pfstring(PSTR(": "), pserial);
if (fname != sym(NIL)) {
pserial('\'');
psymbol(fname, pserial);
pserial('\''); pserial(' ');
}
pfstring(string, pserial);
}
void errorend () { GCStack = NULL; longjmp(*handler, 1); }
/*
errorsym - prints an error message and reenters the REPL.
Prints: "Error: 'fname' string: symbol", where fname is the name of the user Lisp function in which the error occurred,
and symbol is the object generating the error.
*/
void errorsym (symbol_t fname, PGM_P string, object *symbol) {
if (!tstflag(MUFFLEERRORS)) {
errorsub(fname, string);
pserial(':'); pserial(' ');
printobject(symbol, pserial);
pln(pserial);
}
errorend();
}
/*
errorsym2 - prints an error message and reenters the REPL.
Prints: "Error: 'fname' string", where fname is the name of the user Lisp function in which the error occurred.
*/
void errorsym2 (symbol_t fname, PGM_P string) {
if (!tstflag(MUFFLEERRORS)) {
errorsub(fname, string);
pln(pserial);
}
errorend();
}
/*
error - prints an error message and reenters the REPL.
Prints: "Error: 'Context' string: symbol", where Context is the name of the built-in Lisp function in which the error occurred,
and symbol is the object generating the error.
*/
void error (PGM_P string, object *symbol) {
errorsym(sym(Context), string, symbol);
}
/*
error2 - prints an error message and reenters the REPL.
Prints: "Error: 'Context' string", where Context is the name of the built-in Lisp function in which the error occurred.
*/
void error2 (PGM_P string) {
errorsym2(sym(Context), string);
}
/*
formaterr - displays a format error with a ^ pointing to the error
*/
void formaterr (object *formatstr, PGM_P string, uint8_t p) {
pln(pserial); indent(4, ' ', pserial); printstring(formatstr, pserial); pln(pserial);
indent(p+5, ' ', pserial); pserial('^');
error2(string);
pln(pserial);
errorend();
}
// Save space as these are used multiple times
const char notanumber[] PROGMEM = "argument is not a number";
const char notaninteger[] PROGMEM = "argument is not an integer";
const char notastring[] PROGMEM = "argument is not a string";
const char notalist[] PROGMEM = "argument is not a list";
const char notasymbol[] PROGMEM = "argument is not a symbol";
const char notproper[] PROGMEM = "argument is not a proper list";
const char toomanyargs[] PROGMEM = "too many arguments";
const char toofewargs[] PROGMEM = "too few arguments";
const char noargument[] PROGMEM = "missing argument";
const char nostream[] PROGMEM = "missing stream argument";
const char overflow[] PROGMEM = "arithmetic overflow";
const char divisionbyzero[] PROGMEM = "division by zero";
const char indexnegative[] PROGMEM = "index can't be negative";
const char invalidarg[] PROGMEM = "invalid argument";
const char invalidkey[] PROGMEM = "invalid keyword";
const char illegalclause[] PROGMEM = "illegal clause";
const char illegalfn[] PROGMEM = "illegal function";
const char invalidpin[] PROGMEM = "invalid pin";
const char oddargs[] PROGMEM = "odd number of arguments";
const char indexrange[] PROGMEM = "index out of range";
const char canttakecar[] PROGMEM = "can't take car";
const char canttakecdr[] PROGMEM = "can't take cdr";
const char unknownstreamtype[] PROGMEM = "unknown stream type";
// Set up workspace
/*
initworkspace - initialises the workspace into a linked list of free objects
*/
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++;
}
}
/*
myalloc - returns the first object from the linked list of free objects
*/
object *myalloc () {
if (Freespace == 0) { Context = NIL; error2(PSTR("no room")); }
object *temp = Freelist;
Freelist = cdr(Freelist);
Freespace--;
return temp;
}
/*
myfree - adds obj to the linked list of free objects.
inline makes gc significantly faster
*/
inline void myfree (object *obj) {
car(obj) = NULL;
cdr(obj) = Freelist;
Freelist = obj;
Freespace++;
}
// Make each type of object
/*
number - make an integer object with value n and return it
*/
object *number (int n) {
object *ptr = myalloc();
ptr->type = NUMBER;
ptr->integer = n;
return ptr;
}
/*
character - make a character object with value c and return it
*/
object *character (uint8_t c) {
object *ptr = myalloc();
ptr->type = CHARACTER;
ptr->chars = c;
return ptr;
}
/*
cons - make a cons with arg1 and arg2 return it
*/
object *cons (object *arg1, object *arg2) {
object *ptr = myalloc();
ptr->car = arg1;
ptr->cdr = arg2;
return ptr;
}
/*
symbol - make a symbol object with value name and return it
*/
object *symbol (symbol_t name) {
object *ptr = myalloc();
ptr->type = SYMBOL;
ptr->name = name;
return ptr;
}
/*
bsymbol - make a built-in symbol
*/
inline object *bsymbol (builtin_t name) {
return intern(twist(name+BUILTINS));
}
/*
codehead - make a code header object with value entry and return it
*/
object *codehead (int entry) {
object *ptr = myalloc();
ptr->type = CODE;
ptr->integer = entry;
return ptr;
}
/*
intern - looks through the workspace for an existing occurrence of symbol name and returns it,
otherwise calls symbol(name) to create a new symbol.
*/
object *intern (symbol_t name) {
for (int i=0; i<WORKSPACESIZE; i++) {
object *obj = &Workspace[i];
if (obj->type == SYMBOL && obj->name == name) return obj;
}
return symbol(name);
}
/*
eqsymbols - compares the long string/symbol obj with the string in buffer.
*/
bool eqsymbols (object *obj, char *buffer) {
object *arg = cdr(obj);
int i = 0;
while (!(arg == NULL && buffer[i] == 0)) {
if (arg == NULL || buffer[i] == 0) return false;
chars_t test = 0; int shift = 8;
for (int j=0; j<2; j++, i++) {
if (buffer[i] == 0) break;
test = test | buffer[i]<<shift;
shift = shift - 8;
}
if (arg->chars != test) return false;
arg = car(arg);
}
return true;
}
/*
internlong - looks through the workspace for an existing occurrence of the long symbol in buffer and returns it,
otherwise calls lispstring(buffer) to create a new symbol.
*/
object *internlong (char *buffer) {
for (int i=0; i<WORKSPACESIZE; i++) {
object *obj = &Workspace[i];
if (obj->type == SYMBOL && longsymbolp(obj) && eqsymbols(obj, buffer)) return obj;
}
object *obj = lispstring(buffer);
obj->type = SYMBOL;
return obj;
}
/*
stream - makes a stream object defined by streamtype and address, and returns it
*/
object *stream (uint8_t streamtype, uint8_t address) {
object *ptr = myalloc();
ptr->type = STREAM;
ptr->integer = streamtype<<8 | address;
return ptr;
}
/*
newstring - makes an empty string object and returns it
*/
object *newstring () {
object *ptr = myalloc();
ptr->type = STRING;
ptr->chars = 0;
return ptr;
}
// Features
const char arrays[] PROGMEM = ":arrays";
const char doc[] PROGMEM = ":documentation";
const char machinecode[] PROGMEM = ":machine-code";
const char errorhandling[] PROGMEM = ":error-handling";
const char sdcard[] PROGMEM = ":sd-card";
/*
copyprogmemstring - copy a PROGMEM string to RAM.
*/
char *copyprogmemstring (PGM_P s, char *buffer) {
int max = BUFFERSIZE-1;
int i = 0;
do {
char c = pgm_read_byte(s++);
buffer[i++] = c;
if (c == 0) break;
} while (i<max);
return buffer;
}
/*
features - create a list of features symbols from const strings.
*/
object *features () {
char buffer[BUFFERSIZE];
object *result = NULL;
#if defined(sdcardsupport)
push(internlong(copyprogmemstring(sdcard, buffer)), result);
#endif
push(internlong(copyprogmemstring(errorhandling, buffer)), result);
#if defined(CODESIZE)
push(internlong(copyprogmemstring(machinecode, buffer)), result);
#endif
push(internlong(copyprogmemstring(doc, buffer)), result);
push(internlong(copyprogmemstring(arrays, buffer)), result);
return result;
}
// Garbage collection
/*
markobject - recursively marks reachable objects, starting from obj
*/
void markobject (object *obj) {
MARK:
if (obj == NULL) return;
if (marked(obj)) return;
object* arg = car(obj);
unsigned int type = obj->type;
mark(obj);
if (type >= PAIR || type == ZZERO) { // cons
markobject(arg);
obj = cdr(obj);
goto MARK;
}
if (type == ARRAY) {
obj = cdr(obj);
goto MARK;
}
if ((type == STRING) || (type == SYMBOL && longsymbolp(obj))) {
obj = cdr(obj);
while (obj != NULL) {
arg = car(obj);
mark(obj);
obj = arg;
}
}
}
/*
sweep - goes through the workspace freeing objects that have not been marked,
and unmarks marked objects
*/
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);
}
}
/*
gc - performs garbage collection by calling markobject() on each of the pointers to objects in use,
followed by sweep() to free unused objects.
*/
void gc (object *form, object *env) {
#if defined(printgcs)
int start = Freespace;
#endif
markobject(tee);
markobject(GlobalEnv);
markobject(GCStack);
markobject(form);
markobject(env);
sweep();
#if defined(printgcs)
pfl(pserial); pserial('{'); pint(Freespace - start, pserial); pserial('}');
#endif
}
// Compact image
/*
movepointer - Corrects pointers to an object that has been moved from 'from' to 'to'.
Only need to scan addresses below 'from' as there are no accessible objects above that.
*/
void movepointer (object *from, object *to) {
uintptr_t limit = ((uintptr_t)(from) - (uintptr_t)(Workspace))/sizeof(uintptr_t);
for (uintptr_t i=0; i<limit; i++) {
object *obj = &Workspace[i];
unsigned int type = (obj->type) & ~MARKBIT;
if (marked(obj) && (type >= ARRAY || type==ZZERO || (type == SYMBOL && longsymbolp(obj)))) {
if (car(obj) == (object *)((uintptr_t)from | MARKBIT))
car(obj) = (object *)((uintptr_t)to | MARKBIT);
if (cdr(obj) == from) cdr(obj) = to;
}
}
// Fix strings and long symbols
for (uintptr_t i=0; i<limit; i++) {
object *obj = &Workspace[i];
if (marked(obj)) {
unsigned int type = (obj->type) & ~MARKBIT;
if (type == STRING || (type == SYMBOL && longsymbolp(obj))) {
obj = cdr(obj);
while (obj != NULL) {
if (cdr(obj) == to) cdr(obj) = from;
obj = (object *)((uintptr_t)(car(obj)) & ~MARKBIT);
}
}
}
}
}
/*
compactimage - Marks all accessible objects. Moves the last marked object down to the first free space gap, correcting
pointers by calling movepointer(). Then repeats until there are no more gaps.
*/
uintptr_t compactimage (object **arg) {
markobject(tee);
markobject(GlobalEnv);
markobject(GCStack);
object *firstfree = Workspace;
while (marked(firstfree)) firstfree++;
object *obj = &Workspace[WORKSPACESIZE-1];
while (firstfree < obj) {
if (marked(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 (*arg == obj) *arg = firstfree;
while (marked(firstfree)) firstfree++;
}
obj--;
}
sweep();
return firstfree - Workspace;
}
// Make SD card filename
char *MakeFilename (object *arg, char *buffer) {
int max = BUFFERSIZE-1;
int i = 0;
do {
char c = nthchar(arg, i);
if (c == '\0') break;
buffer[i++] = c;
} while (i<max);
buffer[i] = '\0';
return buffer;
}
// Save-image and load-image
#if defined(sdcardsupport)
/*
SDBegin - a standard call on all platforms to initialise the SD Card interface.
*/
void SDBegin() {
SD.begin(SDCARD_SS_PIN);
}
void SDWriteInt (File file, int data) {
file.write(data & 0xFF); file.write(data>>8 & 0xFF);
}
int SDReadInt (File file) {
uint8_t b0 = file.read(); uint8_t b1 = file.read();
return b0 | b1<<8;
}
#elif defined(FLASHWRITESIZE)
#if defined (CPU_ATmega1284P)
// save-image area is the 15872 bytes (31 x 512-byte pages) from 0x1c000 to 0x1FE00
const uint32_t BaseAddress = 0x1c000;
uint8_t FlashCheck() {
return 0;
}
void FlashWriteInt (uint32_t *addr, int data) {
if (((*addr) & 0xFF) == 0) optiboot_page_erase(BaseAddress + ((*addr) & 0xFF00));
optiboot_page_fill(BaseAddress + *addr, data);
if (((*addr) & 0xFF) == 0xFE) optiboot_page_write(BaseAddress + ((*addr) & 0xFF00));
(*addr)++; (*addr)++;
}
void FlashEndWrite (uint32_t *addr) {
if (((*addr) & 0xFF) != 0) optiboot_page_write((BaseAddress + ((*addr) & 0xFF00)));
}
uint8_t FlashReadByte (uint32_t *addr) {
return pgm_read_byte_far(BaseAddress + (*addr)++);
}
int FlashReadInt (uint32_t *addr) {
int data = pgm_read_word_far(BaseAddress + *addr);
(*addr)++; (*addr)++;
return data;
}
#elif defined (CPU_AVR128DX48)
// save-image area is the 15872 bytes (31 x 512-byte pages) from 0x1c000 to 0x1FE00
const uint32_t BaseAddress = 0x1c000;
uint8_t FlashCheck() {
return Flash.checkWritable();
}
void FlashWriteInt (uint32_t *addr, int data) {
if (((*addr) & 0x1FF) == 0) Flash.erasePage(BaseAddress + ((*addr) & 0xFE00));
Flash.writeWord(BaseAddress + *addr, data);
(*addr)++; (*addr)++;
}
void FlashEndWrite (uint32_t *addr) {
(void) addr;
}
uint8_t FlashReadByte (uint32_t *addr) {
return Flash.readByte(BaseAddress + (*addr)++);
}
int FlashReadInt (uint32_t *addr) {
int data = Flash.readWord(BaseAddress + *addr);
(*addr)++; (*addr)++;
return data;
}
#endif
#else
void EEPROMWriteInt (unsigned int *addr, int data) {
EEPROM.write((*addr)++, data & 0xFF); EEPROM.write((*addr)++, data>>8 & 0xFF);
}
int EEPROMReadInt (unsigned int *addr) {
uint8_t b0 = EEPROM.read((*addr)++); uint8_t b1 = EEPROM.read((*addr)++);
return b0 | b1<<8;
}
#endif
/*
saveimage - saves an image of the workspace to the persistent storage selected for the platform.
*/
unsigned int saveimage (object *arg) {
#if defined(sdcardsupport)
unsigned int imagesize = compactimage(&arg);
SDBegin();
File file;
if (stringp(arg)) {
char buffer[BUFFERSIZE];
file = SD.open(MakeFilename(arg, buffer), O_RDWR | O_CREAT | O_TRUNC);
if (!file) error2(PSTR("problem saving to SD card or invalid filename"));
arg = NULL;
} else if (arg == NULL || listp(arg)) {
file = SD.open("/ULISP.IMG", O_RDWR | O_CREAT | O_TRUNC);
if (!file) error2(PSTR("problem saving to SD card"));
}
else error(invalidarg, arg);
SDWriteInt(file, (uintptr_t)arg);
SDWriteInt(file, imagesize);
SDWriteInt(file, (uintptr_t)GlobalEnv);
SDWriteInt(file, (uintptr_t)GCStack);
#if defined(CODESIZE)
for (int i=0; i<CODESIZE; i++) file.write(MyCode[i]);
#endif
for (unsigned int i=0; i<imagesize; i++) {
object *obj = &Workspace[i];
SDWriteInt(file, (uintptr_t)car(obj));
SDWriteInt(file, (uintptr_t)cdr(obj));
}
file.close();
return imagesize;
#elif defined(FLASHWRITESIZE)
unsigned int imagesize = compactimage(&arg);
if (!(arg == NULL || listp(arg))) error(invalidarg, arg);
if (FlashCheck()) error2(PSTR("flash write not supported"));
// Save to Flash
#if defined(CODESIZE)
int bytesneeded = 10 + CODESIZE + imagesize*4;
#else
int bytesneeded = 10 + imagesize*4;
#endif
if (bytesneeded > FLASHWRITESIZE) error(PSTR("image too large"), number(imagesize));
uint32_t addr = 0;
FlashWriteInt(&addr, (uintptr_t)arg);
FlashWriteInt(&addr, imagesize);
FlashWriteInt(&addr, (uintptr_t)GlobalEnv);
FlashWriteInt(&addr, (uintptr_t)GCStack);
#if defined(CODESIZE)
for (int i=0; i<CODESIZE/2; i++) FlashWriteInt(&addr, MyCode[i*2] | MyCode[i*2+1]<<8);
#endif
for (unsigned int i=0; i<imagesize; i++) {
object *obj = &Workspace[i];
FlashWriteInt(&addr, (uintptr_t)car(obj));
FlashWriteInt(&addr, (uintptr_t)cdr(obj));
}
FlashEndWrite(&addr);
return imagesize;
#elif defined(EEPROMSIZE)
unsigned int imagesize = compactimage(&arg);
if (!(arg == NULL || listp(arg))) error(invalidarg, arg);
int bytesneeded = imagesize*4 + 10;
if (bytesneeded > EEPROMSIZE) error(PSTR("image too large"), number(imagesize));
unsigned int addr = 0;
EEPROMWriteInt(&addr, (unsigned int)arg);
EEPROMWriteInt(&addr, imagesize);
EEPROMWriteInt(&addr, (unsigned int)GlobalEnv);
EEPROMWriteInt(&addr, (unsigned int)GCStack);
for (unsigned int i=0; i<imagesize; i++) {
object *obj = &Workspace[i];
EEPROMWriteInt(&addr, (uintptr_t)car(obj));
EEPROMWriteInt(&addr, (uintptr_t)cdr(obj));
}
return imagesize;
#else
(void) arg;
error2(PSTR("not available"));
return 0;
#endif
}
/*
loadimage - loads an image of the workspace from the persistent storage selected for the platform.
*/
unsigned int loadimage (object *arg) {
#if defined(sdcardsupport)
SDBegin();
File file;
if (stringp(arg)) {
char buffer[BUFFERSIZE];
file = SD.open(MakeFilename(arg, buffer));
if (!file) error2(PSTR("problem loading from SD card or invalid filename"));
}
else if (arg == NULL) {
file = SD.open("/ULISP.IMG");
if (!file) error2(PSTR("problem loading from SD card"));
}
else error(invalidarg, arg);
SDReadInt(file);
unsigned int imagesize = SDReadInt(file);
GlobalEnv = (object *)SDReadInt(file);
GCStack = (object *)SDReadInt(file);
#if defined(CODESIZE)
for (int i=0; i<CODESIZE; i++) MyCode[i] = file.read();
#endif
for (unsigned int i=0; i<imagesize; i++) {
object *obj = &Workspace[i];
car(obj) = (object *)SDReadInt(file);
cdr(obj) = (object *)SDReadInt(file);
}
file.close();
gc(NULL, NULL);
return imagesize;
#elif defined(FLASHWRITESIZE)
(void) arg;
if (FlashCheck()) error2(PSTR("flash write not supported"));
uint32_t addr = 0;
FlashReadInt(&addr); // Skip eval address
unsigned int imagesize = FlashReadInt(&addr);
if (imagesize == 0 || imagesize == 0xFFFF) error2(PSTR("no saved image"));
GlobalEnv = (object *)FlashReadInt(&addr);
GCStack = (object *)FlashReadInt(&addr);
#if defined(CODESIZE)
for (int i=0; i<CODESIZE; i++) MyCode[i] = FlashReadByte(&addr);
#endif
for (unsigned int i=0; i<imagesize; i++) {
object *obj = &Workspace[i];
car(obj) = (object *)FlashReadInt(&addr);
cdr(obj) = (object *)FlashReadInt(&addr);
}
gc(NULL, NULL);
return imagesize;
#elif defined(EEPROMSIZE)
(void) arg;
unsigned int addr = 2; // Skip eval address
unsigned int imagesize = EEPROMReadInt(&addr);
if (imagesize == 0 || imagesize == 0xFFFF) error2(PSTR("no saved image"));
GlobalEnv = (object *)EEPROMReadInt(&addr);
GCStack = (object *)EEPROMReadInt(&addr);
for (unsigned int i=0; i<imagesize; i++) {
object *obj = &Workspace[i];
car(obj) = (object *)EEPROMReadInt(&addr);
cdr(obj) = (object *)EEPROMReadInt(&addr);
}
gc(NULL, NULL);
return imagesize;
#else
(void) arg;
error2(PSTR("not available"));
return 0;
#endif
}
/*
autorunimage - loads and runs an image of the workspace from the persistent storage selected for the platform.
*/
void autorunimage () {
#if defined(sdcardsupport)
SDBegin();
File file = SD.open("ULISP.IMG");
if (!file) error2(PSTR("problem autorunning from SD card"));
object *autorun = (object *)SDReadInt(file);
file.close();
if (autorun != NULL) {
loadimage(NULL);
apply(autorun, NULL, NULL);
}
#elif defined(FLASHWRITESIZE)
uint32_t addr = 0;
object *autorun = (object *)FlashReadInt(&addr);
if (autorun != NULL && (unsigned int)autorun != 0xFFFF) {
loadimage(nil);
apply(autorun, NULL, NULL);
}
#elif defined(EEPROMSIZE)
unsigned int addr = 0;
object *autorun = (object *)EEPROMReadInt(&addr);
if (autorun != NULL && (unsigned int)autorun != 0xFFFF) {
loadimage(nil);
apply(autorun, NULL, NULL);
}
#else
error2(PSTR("not available"));
#endif
}
// Tracing
/*
tracing - returns a number between 1 and TRACEMAX if name is being traced, or 0 otherwise
*/
int tracing (symbol_t name) {
int i = 0;
while (i < TRACEMAX) {
if (TraceFn[i] == name) return i+1;
i++;
}
return 0;
}
/*
trace - enables tracing of symbol name and adds it to the array TraceFn[].
*/
void trace (symbol_t name) {
if (tracing(name)) error(PSTR("already being traced"), symbol(name));
int i = 0;
while (i < TRACEMAX) {
if (TraceFn[i] == 0) { TraceFn[i] = name; TraceDepth[i] = 0; return; }
i++;
}
error2(PSTR("already tracing " stringify(TRACEMAX) " functions"));
}
/*
untrace - disables tracing of symbol name and removes it from the array TraceFn[].