-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtowntalk.c
6188 lines (5920 loc) · 201 KB
/
towntalk.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
#if defined( __GNUC__ )
#define alloca( size ) __builtin_alloca( size )
#else
#include "alloca.h"
#endif
#if defined( FLOATING_POINT )
#include "math.h"
#endif
#include "errno.h"
#include "stddef.h"
#include "stdio.h"
#include "string.h"
#include "time.h"
#include "towntalk.h"
/*
Towntalk (c)2025 Martin Cameron.
A program file consists of a list of declarations.
When an unquoted '#' character is encountered, the rest of the line is ignored.
Variable and function names must be alphanumeric.
Commas within name and argument lists are optional.
A value may be a number, a reference, or a tuple.
References may be strings, elements, arrays, structs, functions or custom types.
A tuple is a reference with an associated number.
Strings are immutable and can be used as byte arrays.
String literals may include the escape sequences "\"", "\\", and octal "\nnn".
Buffers are arrays that cannot hold references but use much less memory.
Keywords and dollar-expressions may be expressed with a capital, eg. 'Print Time;'.
Elements are immutable trees of strings with next and child references.
A valid program file may be parsed into an element tree.
Elements are separated by whitespace, commas, ';' or '='.
Elements may contain spaces and separators by enclosing them in quotes.
Child elements are enclosed in parentheses, square brackets or braces.
If the program has been interrupted, while loops will throw an exception.
Try statements only catch instances of the associated struct of the destination.
An '!' may be used in place of '.' to specify a declaration when a local variable has the same name.
Example:
rem { Test }
function add( a b ) {
# Sum two numbers.
return +( a b );
}
program main {
var a;
let a = 0;
while <( a 10 ) {
print a;
let a = add( a 1 );
}
}
Declarations:
rem {...} Comment (all brackets inside must be balanced).
include "file.tt"; Include declarations from specified file.
library name { decls } Namespace prefix for specified declarations.
const name = expr; Global constants.
global a, b = expr; Global variables.
global ( struct ) a; Global variable with associated struct.
global [ a expr ]; Global variable initialized with array of specified length.
struct s { a,b,c } Enumeration or layout for typed arrays.
struct t( s ) { d,e,f } Struct with fields inherited from s.
function f(param){stmts} Function declaration.
program name{statements} Entry point function (no arguments).
Statements:
rem {...} Comment.
var a, b, c = expr; Local variables.
var ( struct ) a; Local variable with associated struct.
var [ a expr ]; Local variable initialized with array of specified length.
let var = expr; Assign expression to local or global variable.
let var! = expr; Assign expression to global variable.
let [ arr idx ] = expr; Assign expression to array at specified index.
let struc.f(arr) = expr; Assign expression to array at named field of specified struct.
let var.field = expr; Assign expr to local or global array variable at named field of associated struct.
print expr; Write number or string to standard output.
write expr; Same as print, but do not add a newline.
error expr; Same as print, but write to standard error.
return expr; Return from the current function.
throw expr; Return to the nearest catch statement.
exit expr; Terminate program with specified exit code.
while expr {statements} Execute statements if expr is not null and repeat.
until expr {statements} Execute statements and repeat if expr is null.
break; Exit current while statement.
continue; Stop current iteration of while statement.
if expr {statements} Execute statements if expr is not null.
else {statements} Optional, execute if expr is null.
else if expr {stmts} Equivalent to 'else { if expr { stmts } }'.
switch expr { Selection statement for numbers or strings.
case 1,2 {statements} Execute statements if expr equals 1 or 2.
case "a" {statements} Execute statements if expr equals "a".
default {statements}} Execute statements if no valid cases.
try {statements} Execute statements unless exception thrown.
catch a {statements} Assign exception to declared local var and execute.
catch (exc) e {stmts} Catch with inline structured local variable declaration.
finally {statements} Always execute even if exception thrown.
call expr; Evaluate expression and discard result.
set [ arr idx ] = expr; Variable/Array assignment (same as let).
inc a; Increment local variable.
dec a; Decrement local variable.
save str, "file"; Save bytes from string to file.
append str, "file"; Append bytes to the end of file.
Expressions:
-123 Decimal number literal.
0x100 Hexadecimal number literal.
0888 Octal integer literal.
"String" String literal.
${0,"1",$tup("2",3)} Element literal.
variable or global! Value of named local or global variable.
local++ Value of named local variable prior to increment.
local-- Value of named local variable prior to decrement.
func(expr ...) or fn!() Call declared function with specified args.
[arr idx] Array element.
struct or struct! Structure reference.
struct.field Index of struct field.
struct.field(array) Value of specified field of structured array expression.
variable.field Value of specified field of associated structure of local or global variable.
@function Reference to declared function.
@(expr ...) Recursive function call.
:(func expr ...) Call function reference with specified args.
:struct.memb(this ...) Call member-function. Equivalent to ":(struct.memb(this) this ...)", but this evaluated once.
:variable.member(...) Call member-function using associated structure. Equivalent to ":struct.member(variable ...)".
variable:func(...) Call static member-function using associated structure. Equivalent to "struct_func(variable ...)".
global!:func(...) Call static member-function using associated structure of global variable.
`(expr operator ...) Infix expression, eg `( 1 + 2 ). '(...) may also be used.
+(num num ...) Addition.
-(num num ...) Subtraction.
*(num num ...) Multiplication.
/(int int...) or _/(...) Integer division.
%(int int ...) Integer modulo-division.
$div(num num ...) Floating-point division (if supported).
<<(int int) Integer arithmetic shift-left.
>>(int int) Integer arithmetic shift-right.
=(num num) Equality.
<(num num) Less than.
<e(num num) Less than or equal.
>(num num) Greater than.
>e(num num) Greater than or equal.
&(int int ...) Integer bitwise AND.
|(int int ...) Integer bitwise OR.
^(int int ...) Ingeger bitwise XOR.
~(int) Integer bitwise NOT.
!(expr) Evaluates to 1 if argument is null.
&&(expr expr ...) Evaluates to 1 if all arguments are non-null.
||(expr expr ...) Evaluates to 1 if any argument is non-null.
?(expr expr expr) Evaluates second expr if first is non-null, else third.
$same(expr expr) Evaluates to 1 if arguments have the same value.
$cmp(str str) String/Tuple comparison, evaluates to 0 if equivalent.
$eq(expr expr) Equivalent to !( $cmp( expr expr ) ).
$str(expr ...) Number to string and string concatenation.
$cat(expr ...) String concatenation (same as $str).
$chr(str idx) Character at idx as integer.
$sub(str off len) Substring (or byte array to string).
$asc(int) Character code to string.
$hex(int) Integer to fixed-length signed hex string.
$int(str) String or value to integer.
$num(str) String or value to number.
$len(str/arr) Length of string, array or structure.
$tup(str num) String/Number tuple.
$array(len ...) Create array of specified length and values.
$array(${0,"a"}) Create array with values from element.
$new(struct ...) Create structured array, same as $array(struct ...).
$read(len) Read string from standard input.
$load("abc.bin") Load file into string.
$load("file", off, len) Load section of file into string.
$flen("file") Get the length of a file.
$src(func) Source file path of specified function reference.
$stridx(str,"chars",idx) The index of a member of chars in str from idx.
$endidx(str,"chars") The index of the last member of chars in str.
$argc Number of command-line arguments.
$argv(idx) Command-line argument as string.
$time Current time as seconds/date tuple.
$parse(str) Parse string into element list.
$unparse(elem) Concatenate element list into string.
$next(elem) Get the next element in the list or null.
$child(elem) Get the first child element or null.
$line(elem) Get the line number of the element.
$elem(elem child next) Return a copy of elem with specified references.
$expr(expr) Return an element representing the specified value.
$eval(elem) Parse the specified element as an expression and evaluate.
$pack(int/arr) Encode integers as big-endian byte string.
$unpack(str idx) Decode the specified big-endian integer.
$quote(str) Encode byte string with quotes and escapes.
$unquote(str) Decode quoted-string into byte string.
$interrupted Check and clear program interrupt status.
$function(${(){stmts}}) Compile a function reference from an element.
$buffer(len ...) Create a memory-efficient numerical array.
$type(expr) Return a value representing the type of the expression.
$field(struct idx) Name of specified struct field.
$instanceof(arr struct) Returns arr if an instance of struct, null otherwise.
$trace(message) Return a stack-trace array of function and line-number tuples.
$log(num) Floating-point natural-logarithm (if supported).
$exp(num) Floating-point natural-exponent (if supported).
$sqrt(num) Floating-point square-root (if supported).
$sin(rad) Floating-point sine (if supported).
$cos(rad) Floating-point cosine (if supported).
$tan(rad) Floating-point tangent (if supported).
$asin(num) Floating-point arc-sine (if supported).
$acos(num) Floating-point arc-cosine (if supported).
$atan(num) Floating-point arc-tangent (if supported).
*/
struct global_assignment_statement {
struct statement stmt;
struct variable *destination;
};
struct structure_statement {
struct statement stmt;
struct structure *structure;
};
/* The maximum integer value. */
const int MAX_INTEGER = ( 1 << ( sizeof( int ) * 8 - 1 ) ) - 1u;
/* Message to be used to avoid memory allocation in out-of-memory error paths. */
const char *OUT_OF_MEMORY = "Out of memory.";
static struct constant constants[] = {
{ "FALSE", 0, NULL },
{ "TRUE", 1, NULL },
{ NULL }
};
/* Forward declarations. */
struct statement * optimize_statements( struct function *func, struct statement *prev, char *message );
static int validate_name( struct element *elem, char *message );
static int validate_local( struct string *decl, int line, struct environment *env, char *message );
static int validate_decl( struct string *decl, int line, struct environment *env, char *message );
static void parse_keywords( struct keyword *keywords, struct element *elem,
struct function *func, struct variables *vars, struct statement *stmt, char *message );
struct statement* parse_keywords_indexed( struct keyword **index, struct element *elem,
struct function *func, struct variables *vars, struct statement *stmt, char *message );
struct element* parse_expression( struct element *elem, struct function *func,
struct variables *vars, struct expression *prev, char *message );
static struct element* parse_expressions( struct element *elem, struct function *func,
struct variables *vars, char terminator, struct expression *prev, int *num_exprs, char *message );
static struct element* value_to_element( number number_value, struct string *string_value,
struct environment *env, int max_depth, char *message );
static struct element* parse_infix_expression( struct element *elem,
struct function *func, struct variables *vars, struct expression *prev, char *message );
/* Allocate and return a new element with the specified string length. */
struct element* new_element( int str_len ) {
struct element *elem = malloc( sizeof( struct element ) + sizeof( char ) * ( str_len + 1 ) );
if( elem ) {
memset( elem, 0, sizeof( struct element ) );
elem->str.string = ( char * ) &elem[ 1 ];
elem->str.string[ str_len ] = 0;
elem->str.reference_count = 1;
elem->str.length = str_len;
elem->str.type = ELEMENT;
}
return elem;
}
/* Allocate and return a new array with the specified size, associated string length and reference count of 1. */
struct array* new_array( struct environment *env, int length, int str_len ) {
size_t refs_size = length * sizeof( struct string * );
size_t nums_size = length * sizeof( number );
struct array *arr = calloc( 1, sizeof( struct array ) + refs_size + nums_size + str_len + 1 );
if( arr ) {
arr->string_values = ( struct string ** ) &arr[ 1 ];
arr->number_values = ( number * ) &arr->string_values[ length ];
arr->str.string = ( char * ) &arr->number_values[ length ];
arr->str.length = str_len;
arr->str.reference_count = 1;
arr->str.type = ARRAY;
arr->length = length;
arr->prev = &env->arrays;
arr->next = env->arrays.next;
if( arr->next ) {
arr->next->prev = arr;
}
env->arrays.next = arr;
}
return arr;
}
static struct array* new_buffer( int length ) {
struct array *arr = calloc( 1, sizeof( struct array ) + sizeof( number ) * length );
if( arr ) {
arr->number_values = ( number * ) &arr[ 1 ];
arr->str.string = "[Buffer]";
arr->str.length = 8;
arr->str.reference_count = 1;
arr->str.type = ARRAY;
arr->length = length;
}
return arr;
}
/* Allocate and return a string of the specified length and reference count of 1. */
struct string* new_string( int length ) {
struct string *str = malloc( sizeof( struct string ) + sizeof( char ) * ( length + 1 ) );
if( str ) {
memset( str, 0, sizeof( struct string ) );
str->string = ( char * ) &str[ 1 ];
str->string[ length ] = 0;
str->reference_count = 1;
str->length = length;
}
return str;
}
struct string* new_string_value( char *source ) {
struct string *str = new_string( strlen( source ) );
if( str ) {
strcpy( str->string, source );
}
return str;
}
/* Return a 5-bit hash-code to be used for case-insensitively indexing the specified string. */
static int hash_code( char *str, char terminator ) {
char chr = str[ 0 ];
int idx = 1, hash = 0;
while( chr != terminator && chr ) {
hash = hash ^ chr;
chr = str[ idx++ ];
}
return hash & 0x1F;
}
/* Return a pointer to the first terminator in str, or the end. */
static char* field_end( char *str, char *terminators ) {
char mask = 0, *end = terminators;
while( *end ) {
mask |= *end++;
}
end = str;
mask = ~mask;
while( *end & mask || ( *end && !strchr( terminators, *end ) ) ) {
end++;
}
return end;
}
/* Return the first index of a member of chars in str, starting from idx.
If idx is negative, return the last index, starting from 0. */
static int str_idx( char *str, char *chars, int idx ) {
char *chr, *end;
if( idx < 0 ) {
chr = end = field_end( str, chars );
while( *end ) {
chr = end;
end = field_end( end + 1, chars );
}
} else {
chr = field_end( str + idx, chars );
}
if( *chr ) {
return chr - str;
}
return -1;
}
static int parse_string( char *input, int idx, char *output, int line, char *message ) {
int offset = idx;
char chr = input[ idx++ ];
if( chr == '"' ) {
while( ( chr & 0x7F ) >= 32 ) {
chr = input[ idx++ ];
if( chr == '\\' ) {
chr = input[ idx++ ];
} else if( chr == '"' ) {
break;
}
}
if( chr == '"' ) {
if( output ) {
memcpy( output, &input[ offset ], sizeof( char ) * ( idx - offset ) );
}
} else {
sprintf( message, "Unclosed string on line %d.", line );
idx = -3;
}
} else {
sprintf( message, "Expected '\"' on line %d.", line );
idx = -3;
}
return idx;
}
static int unquote_string( char *string, char *output ) {
int chr, offset = 0, length = 0;
if( string ) {
chr = string[ offset++ ];
while( chr ) {
if( chr == '\\' && string[ offset ] ) {
chr = string[ offset++ ];
if( chr >= '0' && chr <= '7' ) {
chr = chr - '0';
if( string[ offset ] >= '0' && string[ offset ] <= '7' ) {
chr = ( chr << 3 ) | ( string[ offset++ ] - '0' );
if( string[ offset ] >= '0' && string[ offset ] <= '7' ) {
chr = ( chr << 3 ) | ( string[ offset++ ] - '0' );
}
}
}
if( output ) {
output[ length++ ] = chr;
} else {
length++;
}
} else if( chr != '"' ) {
if( output ) {
output[ length++ ] = chr;
} else {
length++;
}
}
chr = string[ offset++ ];
}
if( output ) {
output[ length ] = 0;
}
}
return length;
}
static struct string* new_string_literal( char *source ) {
struct string *str = new_string( unquote_string( source, NULL ) );
if( str ) {
str->length = unquote_string( source, str->string );
}
return str;
}
/* Return a copy of the specified element-tree. */
static struct element* copy_element( struct element *source ) {
struct element *elem = NULL, *prev = NULL, *head = NULL;
while( source ) {
elem = new_element( source->str.length );
if( elem ) {
elem->line = source->line;
if( prev ) {
prev->next = elem;
}
prev = elem;
if( head == NULL ) {
head = elem;
}
memcpy( elem->str.string, source->str.string, sizeof( char ) * elem->str.length );
if( source->child ) {
elem->child = copy_element( source->child );
if( elem->child ) {
source = source->next;
} else {
source = elem = NULL;
}
} else {
source = source->next;
}
} else {
source = NULL;
}
}
if( elem == NULL && head ) {
unref_string( &head->str );
head = NULL;
}
return head;
}
static int parse_child_element( char *buffer, int idx, struct element *parent, int depth, char *message ) {
struct element *elem = NULL;
int offset = idx, length = 0, line = parent->line, len;
char *bracket, chr = '\n';
if( depth < 1 ) {
sprintf( message, "Maximum element depth exceeded on line %d.", line );
return -5;
}
while( chr ) {
chr = buffer[ idx++ ];
if( chr <= 32 || strchr( "\"#(),;=[]{}", chr ) ) {
if( length > 0 ) {
if( elem == NULL ) {
elem = new_element( length );
parent->child = elem;
} else {
elem->next = new_element( length );
elem = elem->next;
}
if( elem ) {
elem->line = line;
memcpy( elem->str.string, &buffer[ offset ], sizeof( char ) * length );
/*printf("%d %d %c :%s\n",offset,length,chr,elem->str.string);*/
} else {
strcpy( message, OUT_OF_MEMORY );
return -1;
}
}
if( chr == '\n' || chr == '#' ) {
while( chr && chr != '\n' ) {
chr = buffer[ idx++ ];
}
line++;
} else if( chr && strchr( "\"(,;=[{", chr ) ) {
if( chr == '"' ) {
len = parse_string( buffer, idx - 1, NULL, line, message );
if( len < 0 ) {
return len;
} else {
len = len - idx + 1;
}
} else {
len = 2;
}
if( elem == NULL ) {
elem = new_element( len );
parent->child = elem;
} else {
elem->next = new_element( len );
elem = elem->next;
}
if( elem ) {
elem->line = line;
if( chr == '"' ) {
idx = parse_string( buffer, idx - 1, elem->str.string, line, message );
if( idx < 0 ) {
return idx;
}
} else {
bracket = strchr( "()[]{}", chr );
if( bracket ) {
elem->str.string[ 0 ] = bracket[ 0 ];
elem->str.string[ 1 ] = bracket[ 1 ];
idx = parse_child_element( buffer, idx, elem, depth - 1, message );
if( idx > 0 ) {
/* Exchange line and elem->line. */
len = elem->line;
elem->line = line;
line = len;
if( buffer[ idx - 1 ] != bracket[ 1 ] ) {
sprintf( message, "Unclosed element on line %d.", line );
return -2;
}
} else {
return idx;
}
} else {
elem->str.string[ 0 ] = chr;
elem->str.string[ 1 ] = 0;
elem->str.length = 1;
}
}
} else {
strcpy( message, OUT_OF_MEMORY );
return -1;
}
} else if( chr == ')' || chr == ']' || chr == '}' ) {
parent->line = line;
return idx;
}
offset = idx;
length = 0;
} else {
length++;
}
}
return idx;
}
static struct element* parse_element( char *buffer, int max_depth, char *message ) {
int idx;
struct element elem;
elem.line = 1;
elem.str.string = NULL;
elem.str.type = ELEMENT;
elem.child = elem.next = NULL;
idx = parse_child_element( buffer, 0, &elem, max_depth, message );
if( idx > 0 ) {
if( buffer[ idx - 1 ] != 0 ) {
sprintf( message, "Unexpected closing bracket '%c' on line %d.", buffer[ idx - 1 ], elem.line );
idx = -4;
}
}
if( idx < 0 && elem.child ) {
unref_string( &elem.child->str );
elem.child = NULL;
}
return elem.child;
}
/* Load the specified portion of a file into buffer (if not null).
Returns the number of bytes available or read from offset.
Returns -1 and writes message on failure. */
long load_file( char *file_name, char *buffer, long offset, long count, char *message ) {
long length, remain = -1;
FILE *input_file = fopen( file_name, "rb" );
if( input_file != NULL ) {
if( fseek( input_file, 0L, SEEK_END ) == 0 ) {
length = ftell( input_file );
if( length >= 0 ) {
if( offset < 0 || offset > length ) {
offset = length;
}
remain = length - offset;
if( remain > 0 && buffer ) {
if( count > remain ) {
count = remain;
}
remain = fseek( input_file, offset, SEEK_SET );
if( remain == 0 ) {
clearerr( input_file );
remain = fread( buffer, 1, count, input_file );
if( ferror( input_file ) ) {
remain = -1;
}
}
}
}
}
fclose( input_file );
}
if( remain < 0 ) {
strncpy( message, strerror( errno ), 63 );
message[ 63 ] = 0;
}
return remain;
}
static int save_file( char *file_name, char *buffer, int length, int append, char *message ) {
int count = -1;
FILE *output_file = fopen( file_name, append ? "ab" : "wb" );
if( output_file != NULL ) {
count = fwrite( buffer, sizeof( char ), length, output_file );
fclose( output_file );
}
if( count < length ) {
strncpy( message, strerror( errno ), 63 );
message[ 63 ] = 0;
}
return count;
}
static void dispose_string_list( struct string_list *list ) {
struct string_list *next;
while( list ) {
next = list->next;
unref_string( list->str );
free( list );
list = next;
}
}
/* Decrement the reference-count of any referenced types,
deallocate if necessary, and assign null to the specified variable.
This must be called for all variables assigned during program execution. */
void dispose_variable( struct variable *var ) {
var->number_value = 0;
if( var->string_value ) {
unref_string( var->string_value );
var->string_value = NULL;
}
}
/* As dispose_variable(), but do not assign null for performance reasons.
The resulting variable may contain an invalid pointer and should not be re-used. */
void dispose_temporary( struct variable *var ) {
if( var->string_value ) {
unref_string( var->string_value );
}
}
/* Assign src variable to dest, managing reference counts. */
void assign_variable( struct variable *src, struct variable *dest ) {
if( dest->string_value ) {
unref_string( dest->string_value );
}
dest->number_value = src->number_value;
dest->string_value = src->string_value;
if( dest->string_value ) {
dest->string_value->reference_count++;
}
}
static int compare_variables( struct variable *var1, struct variable *var2 ) {
int result;
struct string *str1, *str2;
if( var1->number_value > var2->number_value ) {
result = 1;
} else if( var1->number_value < var2->number_value ) {
result = -1;
} else if( var1->string_value != var2->string_value ) {
if( var1->string_value && var2->string_value ) {
str1 = var1->string_value;
str2 = var2->string_value;
if( str1->length > str2->length ) {
result = memcmp( str1->string, str2->string, sizeof( char ) * str2->length );
} else {
result = memcmp( str1->string, str2->string, sizeof( char ) * str1->length );
}
if( result == 0 ) {
result = str1->length - str2->length;
}
} else if( var2->string_value ) {
result = -var2->string_value->length;
} else {
result = var1->string_value->length;
}
} else {
result = 0;
}
return result;
}
static void dispose_keywords( struct keyword *keywords ) {
struct keyword *next;
while( keywords ) {
next = keywords->next;
free( keywords );
keywords = next;
}
}
static void dispose_operators( struct operator *operators ) {
struct operator *next;
while( operators ) {
next = operators->next;
free( operators );
operators = next;
}
}
enum result evaluate_number_literal_expression( struct expression *this,
struct variables *vars, struct variable *result ) {
result->number_value = ( ( struct value_expression * ) this )->num;
return OKAY;
}
enum result evaluate_string_literal_expression( struct expression *this,
struct variables *vars, struct variable *result ) {
result->number_value = ( ( struct value_expression * ) this )->num;
result->string_value = ( ( struct value_expression * ) this )->str;
result->string_value->reference_count++;
return OKAY;
}
static void dispose_expressions( struct expression *expr ) {
struct expression *next;
while( expr ) {
next = expr->next;
dispose_expressions( expr->parameters );
if( expr->evaluate == evaluate_string_literal_expression ) {
unref_string( ( ( struct value_expression * ) expr )->str );
}
free( expr );
expr = next;
}
}
static void dispose_local_variables( struct local_variable *local ) {
struct local_variable *next;
while( local ) {
next = local->next;
free( local );
local = next;
}
}
static void dispose_global_variable( struct global_variable *global ) {
dispose_temporary( &global->value );
if( global->init_function ) {
unref_string( &global->init_function->str );
}
dispose_expressions( global->initializer );
free( global );
}
void dispose_statements( struct statement *statements ) {
struct statement *next;
while( statements ) {
next = statements->next;
dispose_expressions( statements->source );
if( statements->dispose ) {
statements->dispose( statements );
} else {
free( statements );
}
statements = next;
}
}
static void dispose_element( struct element *elem ) {
struct element *prev;
while( elem ) {
if( elem->str.reference_count == 1 ) {
if( elem->child ) {
dispose_element( elem->child );
}
prev = elem;
elem = elem->next;
free( prev );
} else {
elem->str.reference_count--;
elem = NULL;
}
}
}
static void truncate_array( struct array *arr ) {
struct string *str;
int idx = 0, len = arr->length;
if( arr->string_values ) {
while( idx < len ) {
str = arr->string_values[ idx++ ];
if( str ) {
unref_string( str );
}
}
}
arr->length = 0;
}
static void dispose_array( struct array *arr ) {
truncate_array( arr );
if( arr->prev ) {
arr->prev->next = arr->next;
if( arr->next ) {
arr->next->prev = arr->prev;
}
}
free( arr );
}
static void dispose_structure( struct structure *sct ) {
dispose_string_list( sct->fields );
free( sct );
}
static void dispose_function( struct function *func ) {
if( func->file != &func->str ) {
unref_string( func->file );
}
if( func->library ) {
unref_string( func->library );
}
dispose_local_variables( func->variable_decls );
dispose_statements( func->statements );
free( func );
}
/* Decrement the reference count of the specified value and deallocate if necessary. */
void unref_string( struct string *str ) {
if( str->reference_count == 1 ) {
switch( str->type ) {
default:
case STRING:
free( str );
break;
case ELEMENT:
dispose_element( ( struct element * ) str );
break;
case ARRAY:
dispose_array( ( struct array * ) str );
break;
case STRUCT:
dispose_structure( ( struct structure * ) str );
break;
case GLOBAL: case CONST:
dispose_global_variable( ( struct global_variable * ) str );
break;
case FUNCTION:
dispose_function( ( struct function * ) str );
break;
case CUSTOM:
( ( struct custom * ) str )->type->dispose( str );
break;
}
} else {
str->reference_count--;
}
}
static void dispose_arrays( struct array *head ) {
struct array *arr = head->next;
while( arr ) {
arr->str.reference_count++;
truncate_array( arr );
arr = arr->next;
}
while( head->next ) {
unref_string( &head->next->str );
}
}
/* Deallocate the specified environment and all types referenced by it. */
void dispose_environment( struct environment *env ) {
int idx;
for( idx = 0; idx < 32; idx++ ) {
dispose_string_list( env->decls_index[ idx ] );
dispose_keywords( env->statements_index[ idx ] );
dispose_operators( env->operators_index[ idx ] );
}
dispose_string_list( env->globals );
dispose_arrays( &env->arrays );
}
static struct string_list* new_string_list( struct string *value, struct string_list *next ) {
struct string_list *list = malloc( sizeof( struct string_list ) );
if( list ) {
list->str = value;
value->reference_count++;
list->next = next;
}
return list;
}
static struct string_list* append_string_list( struct string_list **head, struct string_list **tail, struct string *value ) {
struct string_list *list = new_string_list( value, NULL );
if( list ) {
if( *head ) {
( *tail )->next = list;
} else {
*head = list;
}
*tail = list;
}
return list;
}
static int get_string_list_index( struct string_list *list, char *value ) {
int idx = 0;
while( list && strcmp( list->str->string, value ) ) {
idx++;
list = list->next;
}
if( list == NULL ) {
idx = -1;
}
return idx;
}
/* Assign an uncatchable exception with the specified exit code and message to vars and return EXCEPTION. */
enum result throw_exit( struct variables *vars, number exit_code, const char *message ) {
struct variable *exception = vars->exception;
struct environment *env = vars->func->env;
env->exit.reference_count = 2;
env->exit.type = EXIT;
env->exit.string = ( char * ) message;
dispose_temporary( exception );
exception->number_value = exit_code;
exception->string_value = &env->exit;
return EXCEPTION;
}
static struct array* stack_trace( struct expression *expr, struct variables *vars, int msg_len, int max_depth ) {
struct array *arr = new_array( vars->func->env, max_depth, msg_len );
int idx = 0, line = expr->line;
if( arr ) {
while( vars && vars->func && idx < max_depth ) {
vars->func->str.reference_count++;
arr->string_values[ idx ] = &vars->func->str;
arr->number_values[ idx++ ] = line;
line = vars->line;
vars = vars->parent;
}
arr->length = idx;
}
return arr;
}
/* Assign an exception with the specified error code and message to vars and return EXCEPTION. */
enum result throw( struct variables *vars, struct expression *source, number num, const char *string ) {
struct variable *exception = vars->exception;
struct array *arr = NULL;
if( string ) {
arr = stack_trace( source, vars, strlen( string ), 16 );
if( arr ) {
strcpy( arr->str.string, string );
} else {
return throw_exit( vars, 1, OUT_OF_MEMORY );
}
}
dispose_temporary( exception );
exception->number_value = num;
exception->string_value = &arr->str;
return EXCEPTION;
}
/* Write the specified bytes as a string literal to output (if not null).
The encoded length is returned. */
int write_byte_string( char *bytes, int count, char *output ) {
int chr, size, idx = 0, length = 0;
if( output ) {
output[ length++ ] = '"';
while( idx < count ) {
chr = bytes[ idx++ ];
if( chr == '"' || chr == '\\' ) {
output[ length++ ] = '\\';
output[ length++ ] = chr;
} else if( ( chr & 0x7F ) < 32 || chr == 127 ) {