-
Notifications
You must be signed in to change notification settings - Fork 1
/
sl.c
5973 lines (5676 loc) · 192 KB
/
sl.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include "mylib.c"
#include <ctype.h> // isspace
#include <unistd.h> // usleep
#include <math.h>
#include <setjmp.h>
#include <signal.h>
// Apparently isnan() returns 0 for -nan when GCC optimisations are enabled.
// So I needed to find my own replacement for isnan() that behaves how I want.
//#define MyIsnan(value) (isnan(value))
#define MyIsnan(value) ( (int)value && value==0.0 )
#ifdef enable_graphics_extension
#define myxlib_notstandalonetest
#include "NewBase.c"
#endif
#ifndef DISABLE_ALIGN_STUFF
// this is for testing. I discovered that messing with __attribute__((aligned(x))) can make a difference to how fast things run
#define ALIGN_ATTRIB_CONSTANT 8
#endif
// memory problem debugging stuff
#if 0
void* mymallocfordebug(size_t size ,int n, char *f,char *fun){
void *out = malloc(size);
fprintf(stderr, "line %d, %s, %s, MALLOC %p\n",n,f,fun,out);
return out;
}
void* mycallocfordebug(size_t nmemb, size_t size ,int n, char *f,char *fun){
void *out = calloc(nmemb,size);
fprintf(stderr, "line %d, %s, %s, CALLOC %p\n",n,f,fun,out);
return out;
}
void* myreallocfordebug(void *ptr, size_t size ,int n, char *f,char *fun,char *name){
void *out = realloc(ptr,size);
fprintf(stderr, "line %d, %s, %s, REALLOC %p ( input %p ) '%s'\n",n,f,fun,out,ptr,name);
return out;
}
void myfreefordebug(void *ptr, int n, char *f,char *fun,char *name){
fprintf(stderr, "line %d, %s, %s, FREEING %p '%s'\n",n,f,fun,ptr,name);
free(ptr);
}
#define malloc(a) mymallocfordebug(a,__LINE__,__FILE__,(char*)__FUNCTION__)
#define calloc(a,b) mycallocfordebug(a,b,__LINE__,__FILE__,(char*)__FUNCTION__)
#define realloc(a,b) myreallocfordebug(a,b,__LINE__,__FILE__,(char*)__FUNCTION__,#a)
#define free(p) myfreefordebug(p,__LINE__,__FILE__,(char*)__FUNCTION__,#p)
#endif
#define allow_debug_commands 1
#define TOKENTYPE_TYPE unsigned int
enum eval_action { eval_interpreter, eval_getvalue, eval_getstringvalue };
enum determined_retval { determined_neither = -1, determined_value = 0, determined_stringvalue = 1 };
struct token {
TOKENTYPE_TYPE type;
union {
double number;
void *pointer;
int i;
//int i2[2];
} data;
};
typedef struct token token;
#include "tokenslist.c"
//--------------------------
struct id_info;
typedef struct id_info id_info;
struct id_info {
char *name; // the string of this identifier
token t; // the kind of token it's meant to represent
// ----
id_info *next; // linked list
};
//--------------------------
//--------------------------
#define p_exact 0
#define p_atleast 1
struct func_info;
typedef struct func_info func_info;
struct func_info {
int function_number; // used by 'getref'
int params_type; // exact, at least
int num_params;
int num_locals;
int start_pos; // starting position in the tokens array
id_info *ids; // the names of the parameters & local variables
};
#define INITIAL_FUNCTION_DEFINITION (func_info){ -1, p_exact, 0, 0, 0, NULL };
//--------------------------
//--------------------------
#define DEFAULT_STRING_ACCUMULATOR_LEVELS 4
#define DEFAULT_NEW_STRINGVAR_BUFSIZE 256
struct stringvar { // string variable
char *string;
size_t len, bufsize;
int string_variable_number; // used by 'getref'
int unclaimed; // used by 'S'
};
typedef struct stringvar stringvar;
// ----
struct stringval { // string value
char *string;
size_t len;
};
typedef struct stringval stringval;
// ----
stringvar* newstringvar(){
stringvar *out = calloc(1,sizeof(stringvar));
out->string = calloc(DEFAULT_NEW_STRINGVAR_BUFSIZE,sizeof(char));
out->bufsize = DEFAULT_NEW_STRINGVAR_BUFSIZE;
return out;
}
//--------------------------
//--------------------------
// this is for keeping track of all the strings that are part of the program data (string constants, ids, labels, etc) so that they can all be freed when the program is unloaded.
// but also note that for convenience, it may also be used for other kinds of pointer that aren't text strings, just because it's a convenient way to keep track of pointers that would need to be freed when the program is unloaded. for example, it's used in the case of t_stringconstf to keep track of a pointer to a stringval
struct stringslist;
typedef struct stringslist stringslist;
struct stringslist {
char *string; int p;
stringslist *next; // linked list
};
void free_stringslist(stringslist *s){
if(s == NULL) return;
if(s->next) free_stringslist(s->next);
if(s->string != NULL) free(s->string);
free(s);
}
void free_stringslist_from_p(stringslist *s, stringslist *prev, int from_p){
if(s == NULL) return;
if( s->p <= from_p ){
free_stringslist_from_p(s->next, s, from_p);
}else{
if(prev){ prev->next = s->next; }
if(s->next) free_stringslist_from_p( s->next, prev, from_p);
free(s->string);
free(s);
}
}
void stringslist_addstring_with_p(stringslist *s,char *string,int p){
while(s->next) s=s->next;
//fprintf(stderr, "stringslist_addstring: %s\n",string);
s->next = calloc(1,sizeof(stringslist));
s->next->string = string;
s->next->p = p;
}
void stringslist_addstring(stringslist *s,char *string){ stringslist_addstring_with_p(s,string,0); }
stringslist* stringslist_gettail(stringslist *s){
if( ! s ) return NULL;
while( s->next ) s=s->next;
return s;
}
int stringslist_list_length(stringslist *s){
int count = 0;
while( s->next ){
s = s->next; count++;
}
return count;
}
#if 0
void stringslist_debug_show_contents(stringslist *s){
if( ! s ){
fprintf( stderr, "null...\n");
}
int count = 0;
fprintf( stderr, "stringslist contents: \n");
while( s ){
fprintf(stderr, " item %d, %p contains: %p\n",count++,s,s->string);
s=s->next;
}
}
#endif
//--------------------------
//--------------------------
// file management
struct file;
typedef struct file file;
struct file {
int open;
int read_access;
int write_access;
FILE *fp;
};
#define DEFAULT_MAX_FILES 8 // must be at least 3 to make space for stdin, stdout, stderr
//--------------------------
//--------------------------
#define MAX_FUNCS 256
struct program {
token *tokens;
int length;
int maxlen;
// ------------
double *vars;
int vsize;
int next_free_var;
// ------------
double *stack;
int ssize,sp,spo;
// ------------
func_info *functions[MAX_FUNCS];
func_info *current_function;
func_info initial_function;
// ------------
int getstringvalue_level;
int max_string_accumulator_levels;
stringvar **string_accumulator;
int max_stringvars;
stringvar **stringvars;
//int next_free_stringvar;
// ------------
int max_files;
file **files;
// ------------
id_info *ids;
id_info *external_options;
id_info *extensions; // used for external extensions
id_info *quit_procs; // used for extensions that need special routines in order to quit gracefully
stringslist *program_strings;
// ------------ these variables will hold error handler info, and info about the last error to be trapped
jmp_buf *error_handler;
stringvar *_error_message;
stringvar *_error_file;
int _error_line;
int _error_column;
//int _error_number;
// -----------------
#ifdef enable_debugger
//void *dbg;
#endif
};
typedef struct program program;
//--------------------------
// -------------------------------------------------------------------------------------------
// ----------------------- PROTOTYPES --------------------------------------------------------
// -------------------------------------------------------------------------------------------
double getvalue(int *p, program *prog);
double interpreter(int p, program *prog);
void free_ids(id_info *ids);
token* tokenise( program *prog, char *text, int *length_return, char *name_of_source_file);
token* loadtokensfromtext(program *prog, char *path,int *length_return);
void process_function_definitions(program *prog,int startpos);
void error(program *prog, int p, char *format, ...);
stringval getstringvalue( program *prog, int *pos );
int isstringvalue(TOKENTYPE_TYPE type);
int isvalue(TOKENTYPE_TYPE type);
int determine_valueorstringvalue(program *prog, int p, int errorIfNeither);
char* tokenstring(token t);
void print_sourcetext_location( program *prog, int token_p);
void stringvar_adjustsizeifnecessary(program *prog, stringvar *sv, size_t bufsize_required, int preserve);
int add_id(id_info *ids, id_info *new_id);
void add_id__error_if_fail( program *prog, int p, char *errormessage, id_info *ids, id_info *new_id);
id_info* make_id(char *id_string, token t);
id_info* find_id(id_info *ids, char *id_string);
void clean_stringvar( program *prog, stringvar *svr, int preserve );
void unclaim(program *prog, int *p);
int oscli(program *prog, int *p);
int catch( program *prog, int *p, int action, double *returnValue, stringval *returnStringValue );
void copy_stringval_to_stringvar(program *prog, stringvar *dest, stringval src);
void process_catch(program *prog, int p);
int interpreter_eval( program *prog, int action, void *return_value, stringval text );
token gettoken(program *prog, int *p, int test_run, int *pos, unsigned char *text, int len);
void interactive_prompt(program *prog);
// -------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------
// MISC RUBBISH
unsigned int
__attribute__((noinline))
unicode_string_length( stringval sv ){
unsigned int length = 0;
for( size_t i=0; i < sv.len; i++){
if( sv.string[i] && (sv.string[i] & 0b11000000) != 0b10000000 ) length++;
}
return length;
}
// -------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------
#ifdef enable_debugger
#include "_sl_debugger.c"
#endif
// -------------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------------
program*
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
newprog(int maxlen, int vsize, int ssize){
program *out = calloc(1,sizeof(program));
// allocate memory for tokens
if(maxlen){
out->tokens = calloc(maxlen,sizeof(token));
out->maxlen=maxlen;
}
// allocate memory for variables and stack
if(vsize||ssize){
out->vars = calloc(vsize+ssize,sizeof(double));
out->stack= out->vars + vsize;
out->vsize=vsize+ssize;
out->ssize=ssize;
}
// initialise function context
out->initial_function = INITIAL_FUNCTION_DEFINITION;
out->current_function = &out->initial_function;
// initialise string accumulator
out->max_string_accumulator_levels = DEFAULT_STRING_ACCUMULATOR_LEVELS;
out->string_accumulator = calloc(DEFAULT_STRING_ACCUMULATOR_LEVELS,sizeof(void*));
int i;
for(i=0; i<DEFAULT_STRING_ACCUMULATOR_LEVELS; i++){
out->string_accumulator[ i ] = newstringvar();
}
// initialise file array
out->max_files = DEFAULT_MAX_FILES;
out->files = calloc(DEFAULT_MAX_FILES,sizeof(void*));
for(i=0; i<DEFAULT_MAX_FILES; i++){
out->files[i] = calloc(1,sizeof(file));
}
out->files[0]->open=1; out->files[0]->read_access=1; out->files[0]->fp = stdin; // stdin
out->files[1]->open=1; out->files[1]->write_access=1; out->files[1]->fp = stdout; // stout
out->files[2]->open=1; out->files[2]->write_access=1; out->files[2]->fp = stderr; // sterr
// initialise id list
out->ids = calloc(1,sizeof(id_info));
// initialise stringslist
out->program_strings = calloc(1,sizeof(stringslist));
// initialise error info
out->_error_message = newstringvar();
out->_error_file = newstringvar();
copy_stringval_to_stringvar(out, out->_error_message, (stringval){"(C)2023 Johnsonscript",21} );
return out;
}
// -------------------------------------------------------------------------------------------
int
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
get_free_fileslot(program *prog){
int i;
// look for the next free fileslot.
// start at 3 because 0,1,2 are reserved for stdin, stdout, stderr
for(i=3; i < prog->max_files; i++){
if(!prog->files[i]->open) return i;
}
// if one was not found, create a new one
prog->max_files += 1;
prog->files = realloc(prog->files, sizeof(void*) * prog->max_files);
if(prog->files == NULL) error(prog, -1, "get_free_fileslot: realloc failed");
prog->files[prog->max_files-1] = calloc(1,sizeof(file));
return prog->max_files-1;
}
file* getfile(program *prog, int p, int file_reference_number, int read, int write){
int fileindex = file_reference_number - 1;
if( fileindex<0 || fileindex>=prog->max_files ) error(prog, p, "bad file access (filenumber out of range)");
file *out = prog->files[fileindex];
if( ! out->open ) error(prog, p, "bad file access (not open)");
if( read && ! out->read_access ) error(prog, p, "bad file access (not readable)");
if( write && ! out->write_access ) error(prog, p, "bad file access (not writable)");
return out;
}
// -------------------------------------------------------------------------------------------
token
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
maketoken( TOKENTYPE_TYPE type ){
token out;
out.type=type;
out.data.pointer = NULL;
return out;
}
token
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
maketoken_num( double n ){
token out;
out.type = t_number;
out.data.number = n;
return out;
}
token
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
maketoken_stackaccess( int sp_offset ){
token out;
out.type = t_stackaccess;
out.data.i = sp_offset;
return out;
}
token
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
maketoken_Df( double *pointer ){
token out;
out.type = t_Df;
out.data.pointer = (void*)pointer;
return out;
}
token
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
maketoken_Sf( stringvar *pointer ){
token out;
out.type = t_Sf;
out.data.pointer = (void*)pointer;
return out;
}
// --------------------------------------------
// ---- External function/command routines ----
// --------------------------------------------
token
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
maketoken_extfun( double (*external_function)(int*,program*) ){
token out;
out.type = t_extfun;
out.data.pointer = external_function;
return out;
}
token
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
maketoken_extsfun( stringval (*external_stringfunction)(program*,int*) ){
token out;
out.type = t_extsfun;
out.data.pointer = external_stringfunction;
return out;
}
token
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
maketoken_extc( void (*external_command)(int*,program*) ){
token out;
out.type = t_extcom;
out.data.pointer = external_command;
return out;
}
token
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
maketoken_extopt( void (*external_option_procedure)(program*,int*) ){
token out;
out.type = t_extopt;
out.data.pointer = external_option_procedure;
return out;
}
void
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
register_external_function( id_info *id_list, double (*external_function)(int*,program*), char *id ){
if( ! add_id( id_list, make_id( id, maketoken_extfun( external_function ) ) ) ){
error(NULL, -1, "register_external_function: id '%s' already exists",id);
}
}
void
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
register_external_stringfunction( id_info *id_list, stringval (*external_stringfunction)(program*,int*), char *id ){
if( ! add_id( id_list, make_id( id, maketoken_extsfun( external_stringfunction ) ) ) ){
error(NULL, -1, "register_external_stringfunction: id '%s' already exists",id);
}
}
void
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
register_external_command( id_info *id_list, void (*external_command)(int*,program*), char *id ){
if( ! add_id( id_list, make_id( id, maketoken_extc( external_command ) ) ) ){
error(NULL, -1, "register_external_command: id '%s' already exists",id);
}
}
// the string 'char *id' must have the form "OPTION_blah", starting with OPTION_ and then having a name after
void
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
register_external_option( id_info *id_list, void (*external_option_procedure)(program*,int*), char *id){
if( ! add_id( id_list, make_id( id, maketoken_extopt( external_option_procedure ) ) ) ){
error(NULL, -1, "register_external_option: id '%s' already exists",id);
}
}
// register a procedure to call when quitting.
// the string 'char *id' must have the form "QUIT_blah", starting with QUIT_ and then having a unique identifying name after
void
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
register_quit_procedure( id_info *id_list, void (*quit_procedure)(program*), char *id ){
token t; t.type = t_bad; t.data.pointer = (void*) quit_procedure;
if( ! add_id( id_list, make_id( id, t ) ) ){
error(NULL, -1, "register_external_option: id '%s' already exists",id);
}
}
// replace built-in stuff with extensions
void
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
register_replacement( id_info *id_list, TOKENTYPE_TYPE target, char *replacewith ){
id_info *replacewith_idinfo;
if( ! (replacewith_idinfo = find_id(id_list,replacewith) ) ){
token t = {0}; t.type = target;
error(NULL, -1, "extension '%s' for replacement of '%s' not found",replacewith,tokenstring(t));
}
token replacement = replacewith_idinfo->t;
char *replacement_id_string = calloc(15,sizeof(char));
strcpy(replacement_id_string, "__REPLACEMENT");
*replacement_id_string = target;
if( ! add_id( id_list, make_id( replacement_id_string, replacement ) ) ){
fprintf(stderr, "tokentype number was '%d'\n",target);
error(NULL, -1, "register_replacment: a replacement is already registered for this token type");
}
}
// ---------------------------------------------------
// ---- End of external function/command routines ----
// ---------------------------------------------------
void
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
unloadprog(program *prog){
int i;
// free the stringslist (strings that are part of the program data (string constants, ids, labels, etc))
free_stringslist(prog->program_strings);
// free the tokens, variable+stack array, identifier information
free(prog->tokens);
free(prog->vars);// this line also frees the stack array, because the stack array is simply the upper part of the variable array
free_ids(prog->ids);
// free the function information structures (and their identifier information)
for(i=0; i<MAX_FUNCS; i++){
if(prog->functions[i]){
free_ids(prog->functions[i]->ids);
free(prog->functions[i]);
}
}
// free the string accumulator
for(i=0; i<prog->max_string_accumulator_levels; i++){
free( prog->string_accumulator[i]->string );
free( prog->string_accumulator[i] );
}
free(prog->string_accumulator);
// free the string variables
for(i=0; i<prog->max_stringvars; i++){
free( prog->stringvars[i]->string );
free( prog->stringvars[i] );
}
free( prog->stringvars );
// close all open files (but ONLY if they're not stdin or stdout or stderr), free the file structs, and finally free the file array
for(i=0; i<prog->max_files; i++){
if( prog->files[i]->open && prog->files[i]->fp != stdin && prog->files[i]->fp != stdout && prog->files[i]->fp != stderr ){
fclose( prog->files[i]->fp );
}
free( prog->files[i] );
}
free( prog->files );
// free extension-related IDs
free_ids(prog->external_options);
free_ids(prog->extensions);
// free error-related string vars
free( prog->_error_message->string); free( prog->_error_message );
free( prog->_error_file->string); free( prog->_error_file );
// free the program struct itself
free( prog );
}
#define DEFAULT_VSIZE 256
#define DEFAULT_SSIZE 256
program*
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
init_program( char *str,int str_is_filepath, id_info *extensions ){
token *tokens; int tokens_length;
// create the 'program' structure, with default stack/variable array size
program *prog = newprog(0,DEFAULT_VSIZE,DEFAULT_SSIZE);
// install the extensions list (pass NULL for no extensions)
prog->extensions = extensions;
// --------------------------------------------------------
// ----- process extension --------------------------------
// --------------------------------------------------------
while( extensions ){
// --------- 'option' extensions ----------------
if( extensions->name && !strncmp("OPTION_",extensions->name,7) ){
char *extension_option_string_permanent_address = calloc( strlen(extensions->name)+1, sizeof(char));
strcpy( extension_option_string_permanent_address, extensions->name+7 );
//fprintf(stderr,"fuckin fuck %s\n",extension_option_string_permanent_address);//test, remove soon
token extension_option_token = extensions->t;
if( extension_option_token.type != t_extopt ){
error(NULL, -1, "invalid extension configuration, please check");
}
if( ! prog->external_options ){
prog->external_options = calloc(1,sizeof(id_info));
}
if( ! add_id( prog->external_options, make_id( extension_option_string_permanent_address, extension_option_token) ) ){
error(NULL, -1, "init_program: external option id '%s' already exists",extension_option_string_permanent_address);
}
stringslist_addstring(prog->program_strings, extension_option_string_permanent_address);
}
if( extensions->name && !strncmp("QUIT_",extensions->name,5) ){
if( ! prog->quit_procs ){
prog->quit_procs = calloc(1,sizeof(id_info));
}
if( ! add_id( prog->quit_procs, make_id( extensions->name, extensions->t) ) ){
error(NULL, -1, "there is already a quit procedure with this name '%s'",extensions->name);
}
}
extensions = extensions->next;
}
// --------------------------------------------------------
// --------------------------------------------------------
// --------------------------------------------------------
// get the tokens, either from program text in 'str', or by using 'str' as a filepath to load program text from a file.
// at the same time, we also build the strings list
if( str_is_filepath){
tokens = loadtokensfromtext(prog,str,&tokens_length);
}else{
tokens = tokenise(prog,str,&tokens_length,"[command line input]");
}
prog->tokens = tokens; prog->length = tokens_length; prog->maxlen = tokens_length;
// search for function definitions and process them
process_function_definitions(prog,0);
return prog;
}
// ----------------------------------------------------------------------------------------------------------------
// this returns the allocated area as an index into the variable array
int
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
allocate_variable_data(program *prog, int amount ){
if( amount <= 0 ) error(prog, -1, "allocate_variable_data: bad allocation request %d",amount);
if( prog->next_free_var+amount > (prog->vsize - prog->ssize) ) error(prog, -1, "allocate_variable_data: run out of space");
int index = prog->next_free_var; prog->next_free_var += amount;
return index;
}
// ----------------------------------------------------------------------------------------------------------------
id_info* find_id(id_info *ids, char *id_string){
while( ids ){
if( ids->name && !strcmp(id_string, ids->name) ){
return ids;
}
ids = ids->next;
}
return NULL;
}
int
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
add_id(id_info *ids, id_info *new_id){
while( ids->next ){
// check if this id name is already used in this id list
if( ids->name && !strcmp(new_id->name, ids->name) ){
//fprintf(stderr,"add_id: id was '%s'\n",new_id->name);
//error(NULL, "add_id: this id is already used in this id list");
return 0;
}
ids=ids->next;
}
ids->next = new_id;
return 1;
}
void
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
add_id__error_if_fail( program *prog, int p, char *errormessage, id_info *ids, id_info *new_id){
if( ! add_id( ids, new_id ) ){
error(prog, p, "%s, id was '%s'",errormessage,new_id->name);
}
}
id_info*
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
make_id(char *id_string, token t){
id_info *out = calloc(1, sizeof(id_info));
out->t = t;
size_t l = strlen(id_string);
char *name_permanent_address = malloc(l+1); strcpy(name_permanent_address, id_string);
out->name = name_permanent_address;
return out;
}
void
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
free_ids(id_info *ids){
if(ids == NULL ) return;
free_ids(ids->next);
free(ids->name);
free(ids);
}
void
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
process_id(program *prog, token *t){
id_info *foundid=NULL;
// first, check current function's id list
foundid = find_id( prog->current_function->ids, (char*)t->data.pointer );
// if nothing was found, check the global id list
if(foundid==NULL) foundid = find_id( prog->ids, (char*)t->data.pointer );
// if nothing was still found, error
if(foundid==NULL){
error(prog, (int) (t - prog->tokens), "process_id: unknown id '%s'",(char*)t->data.pointer);
}
// --- something was found ---
// overwrite the token with the kind of token in the found id_info
*t = foundid->t;
}
id_info*
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
peek_id(program *prog, char *searchforthis){
id_info *foundid=NULL;
// first, check current function's id list
foundid = find_id( prog->current_function->ids, searchforthis );
// if nothing was found, check the global id list
if(foundid==NULL) foundid = find_id( prog->ids, searchforthis );
return foundid;
}
void
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
list_ids(id_info *ids){
if(ids == NULL ) return;
if(ids->name)printf(" id: '%s'\n",ids->name);
list_ids(ids->next);
}
char*
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
getfuncname(program *prog,func_info *f){
id_info *id = prog->ids;
while(1){
if( id->t.type == t_Ff && id->t.data.pointer == f ) return id->name;
id = id->next;
if( id == NULL ) return NULL;
}
}
void
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
list_all_ids(program *prog){
printf("Global IDs\n");
list_ids(prog->ids);
int i;
char *funcname;
for(i=0;i<MAX_FUNCS;i++){
if(prog->functions[i]){
funcname = getfuncname( prog, prog->functions[i] );
if(funcname)
printf("The IDs of function %d ('%s')\n",i,funcname);
else
printf("The IDs of function %d\n",i);
list_ids(prog->functions[i]->ids);
}//endif function
}//next i
}//endproc
// ----------------------------------------------------------------------------------------------------------------
// example of the two different kinds of function definitions.
// the kind without named parameters or locals:
// function F1 [P2['...']] [L3] ;
// the kind with named parameters or locals:
// function myfunction [param_a param_b etc] ['...'] [[local] [localvariable_a localvariable_b etc]] ;
void
#ifndef DISABLE_ALIGN_STUFF
__attribute__((aligned(ALIGN_ATTRIB_CONSTANT)))
#endif
process_function_definition(int pos,program *prog){
int func_number=-1;
func_info *out = calloc(1,sizeof(func_info));
out->ids = calloc(1,sizeof(id_info));
char *func_id=NULL;
token tok = maketoken( t_Ff ); tok.data.pointer = (void*)out;
// is this an 'unnamed and referred to by number'-style function or a 'named and referred to by name' function?
switch( prog->tokens[pos].type ){
case t_F:
pos+=1;
func_number = getvalue(&pos,prog);
if(prog->functions[func_number]){ fprintf(stderr,"process_function_definition: this function number is already used\n"); goto process_function_definition_errorout; }
break;
case t_id:
// check if the id is allowed, eg, if it's not already used
if( find_id(prog->ids, (char*)prog->tokens[pos].data.pointer) ){ fprintf(stderr,"process_function_definition: this identifier '%s' is already used\n",(char*)prog->tokens[pos].data.pointer); goto process_function_definition_errorout; }
// find the next unused function number, error if there are no unused function numbers
{int i;
for(i=0; i<MAX_FUNCS; i++){
if( !prog->functions[i] ){ func_number = i; i=MAX_FUNCS; }
}
if(func_number == -1){ fprintf(stderr,"process_function_definition: too many functions have already been defined\n"); goto process_function_definition_errorout; }
}
// save the id's string in func_id, to be later added to the id list
func_id = (char*)prog->tokens[pos].data.pointer;
pos +=1;
break;
default: fprintf(stderr,"process_function_definition: expected F or identifier\n"); goto process_function_definition_errorout;
}
// is this a function with named parameters, or a function with unnamed parameters, or a function that has no parameters at all?
switch( prog->tokens[pos].type ){
case t_id: { // function with named parameters.
//get parameter ids, store them in the function's id list
int num_ps = 0;
while( prog->tokens[pos].type == t_id ){
add_id__error_if_fail( prog, pos, "process_function_definition: id for this parameter is already used\n",
out->ids, make_id( (char*)prog->tokens[pos].data.pointer, maketoken_stackaccess( num_ps | 0x80000000 ) ) ); // needs to be adjusted later once we know how many locals there are
num_ps +=1;
pos+=1;
}
//save the number of parameters
out->num_params = num_ps;
if( prog->tokens[pos].type == t_ellipsis ){ //ellipsis found, this function can take a variable number of parameters. set 'at least' parameters type
out->params_type = p_atleast;
pos+=1;
}
break;
}
case t_P: // function with unnamed parameters.
pos+=1;
out->num_params = (int)getvalue(&pos,prog);
if( prog->tokens[pos].type == t_ellipsis ){ //ellipsis found, this function can take a variable number of parameters. set 'at least' parameters type
out->params_type = p_atleast;
pos+=1;
}
break;
case t_endstatement: // function with no parameters (and also no locals)
goto process_function_definition_normalout;
case t_ellipsis: // function with at least 0 parameters
out->params_type = p_atleast; pos+=1;
}
// is this a function with named locals, or a function with unnamed locals, or a function with no locals at all?
switch( prog->tokens[pos].type ){
case t_local: {// function with named locals
pos+=1;
//put here: get local ids, store them in the function's id list
int num_ls = 0;
while( prog->tokens[pos].type == t_id ){
add_id__error_if_fail( prog, pos, "process_function_definition: id for this local is already used\n",
out->ids, make_id( (char*)prog->tokens[pos].data.pointer, maketoken_stackaccess( num_ls /* make extra room for _num_params */ +(out->params_type==p_atleast) ) ) );
num_ls +=1;
pos+=1;
}
if( num_ls == 0 ){ fprintf(stderr,"process_function_definition: local: expected at least one identifier\n"); goto process_function_definition_errorout; }
//save the number of locals
out->num_locals = num_ls;
break;
}
case t_L: // function with unnamed locals
pos+=1;
out->num_locals = (int)getvalue(&pos,prog);
break;
case t_endstatement: // function with no locals
goto process_function_definition_normalout;
default: fprintf(stderr,"process_function_definition: expected L or identifier\n"); goto process_function_definition_errorout;
}
// ready to end the process of defining the function
process_function_definition_normalout:
// --- store function number ---
out->function_number = func_number;
// --- one extra local ---
// if this is a function that takes a variable number of parameters, then it must have space allocated for one extra local variable, that is _num_params (L0)
out->num_locals += (out->params_type == p_atleast);
// --- adjust parameter accesses ---
// the local variables are placed on the stack before the parameters. But the parameters are defined before the local variables are.
// so once the local variables have been defined, it's necessary to adjust the quick references of the parameters.
// parameters were marked earlier by ORing them with 0x80000000 so that it would be possible to tell them apart from the locals
{
id_info *idp = out->ids->next;
while( idp && (idp->t.data.i & 0x80000000)){
idp->t.data.i = (idp->t.data.i^0x80000000) + (out->num_locals);
idp = idp->next;
}
}
if( prog->tokens[pos].type != t_endstatement ){
fprintf(stderr,"process_function_definition: the function definition is complete but ';' was not found\n"); goto process_function_definition_errorout;
}
pos+=1;
// set function execution start position
out->start_pos = pos;
// save id information if this is a named function
if( func_id ) add_id__error_if_fail( prog, -1, "process_function_definition: the id for this function is already used\n",
prog->ids, make_id( func_id, tok ) );
prog->functions[func_number] = out;
return;
process_function_definition_errorout:
// something went wrong, so abandon defining this function.
// free all the stuff that was created for it and just fuckin return
free_ids( out->ids );
free( out );
return;
}
void process_function_definitions(program *prog,int startpos){
int i;
for(i=startpos; i<prog->length; i++){
if( prog->tokens[i].type == t_deffn ) process_function_definition(i+1,prog);
}
}
// ----------------------------------------------------------------------------------------------------------------
// ----- OPTION ---------------------------------------------------------------------------------------------------
// ----------------------------------------------------------------------------------------------------------------
// process the 'option' command, which allows you to set things like the variable array size, the stack array size,
// and other stuff
// option works like this:
// option [string or number] [parameters ...] ;
// you can specify options by string or by number. options may or may not take parameters, the number of parameters depends on each option
#define opt_vsize 0 // set variable array size
#define opt_ssize 1 // set stack array size
#define opt_import 2 // import functions from another file
#define opt_seedrnd 3 // seed RNG
#define opt_unclaim 4 // unclaim a string (so it can be re-used by 'S')
#define opt_cleanup 5 // free unused memory from all stringvars and string accs
#define opt_randomise 6 // get a new random seed based on the current clock time in seconds
//#define opt_importreplace 7 // import, but existing functions with the same name are replaced
//#define opt_evalimport 8 // import, but treating string argument as code containing function definitions
//#define opt_evalimportreplace 9 // see above
//#define opt_clear 10 // forget all variables
#ifdef enable_graphics_extension
#define opt_wmclose 100 // specify action to take when the window close button is pressed
#define opt_wintitle 101 // set the window title string
#define opt_copytext 102 // put text on the clipboard
#define opt_pastetext 103 // read text from the clipboard
#define opt_setcliprect 104 // set graphics clipping rectangle
#define opt_clearcliprect 105 // reset the graphics clipping rectangle
#define opt_drawbmp 106 // treat the contents of a stringvalue as a microsoft 24bit .bmp image
#define opt_drawbmpadv 107 // drawbmp 'advanced' - with the full set of parameters
#define opt_copybmp 108 // put bmp on clipboard
#define opt_pastebmp 109 // read bmp from clipboard
#define opt_hascliptext 110 // check if the clipboard has text