-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathsh.c
2456 lines (2186 loc) · 96.1 KB
/
sh.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
// POSIX shell codegen
#include "sh-runtime.c"
void handle_shell_include() {
FILE* shell_include_fp;
int c;
if (tok == STRING) {
// Include pack_string and unpack_string functions
// since they will likely be used in the included file
runtime_use_put_pstr = true;
runtime_use_unpack_string = true;
// Include the file as-is without any preprocessing
shell_include_fp = fopen_source_file(STRING_BUF(val), include_stack->dirname);
while ((c = fgetc(shell_include_fp)) != EOF) {
putchar(c);
}
putchar('\n');
fclose(shell_include_fp);
get_tok_macro(); // Skip the string
} else {
putstr("tok="); putint(tok); putchar('\n');
syntax_error("expected string to #include_shell directive");
}
}
// codegen
#define text int
#define TEXT_POOL_SIZE 1000000
#ifdef PNUT_CC
// On pnut, intptr_t is not defined
#define intptr_t int
#endif
intptr_t text_pool[TEXT_POOL_SIZE];
int text_alloc = 1; // Start at 1 because 0 is the empty text
// Text pool nodes
enum TEXT_NODES {
TEXT_TREE,
TEXT_INTEGER,
TEXT_STRING,
TEXT_ESCAPED
};
// Place prototype of mutually recursive functions here
typedef enum STMT_CTX {
// Default context
STMT_CTX_DEFAULT = 0,
// Indicates that the parent statement was a else statement so that if
// statement uses elif instead of if.
STMT_CTX_ELSE_IF = 1,
// Indicates that we are in a switch statement where breaks mean the end of
// the conditional block.
STMT_CTX_SWITCH = 2,
} STMT_CTX;
text comp_lvalue_address(ast node);
text comp_lvalue(ast node);
text comp_fun_call_code(ast node, ast assign_to);
void comp_fun_call(ast node, ast assign_to);
bool comp_body(ast node, STMT_CTX stmt_ctx);
bool comp_statement(ast node, STMT_CTX stmt_ctx);
void mark_mutable_variables_body(ast node);
void handle_enum_struct_union_type_decl(ast node);
ast handle_side_effects_go(ast node, int executes_conditionally);
// Because concatenating strings is very expensive and a common operation, we
// use a tree structure to represent the concatenated strings. That way, the
// concatenation can be done in O(1).
// At the end of the codegen process, the tree will be flattened into a single
// string.
// A few macros to help us change the representation of text objects
#define TEXT_FROM_INT(i) i
#define TEXT_FROM_CHAR(i) i
#define TEXT_FROM_PTR(p) ((intptr_t) (p))
#define TEXT_TO_INT(p) ((int) (p))
#define TEXT_TO_CHAR(p) ((char) (p))
#define wrap_char(c) (-c)
text wrap_int(int i) {
if (text_alloc + 2 >= TEXT_POOL_SIZE) fatal_error("string tree pool overflow");
text_pool[text_alloc] = TEXT_FROM_INT(TEXT_INTEGER);
text_pool[text_alloc + 1] = TEXT_FROM_INT(i);
return (text_alloc += 2) - 2;
}
text escape_text(text t, bool for_printf) {
if (text_alloc + 3 >= TEXT_POOL_SIZE) fatal_error("string tree pool overflow");
text_pool[text_alloc] = TEXT_FROM_INT(TEXT_ESCAPED);
text_pool[text_alloc + 1] = TEXT_FROM_INT(t);
text_pool[text_alloc + 2] = TEXT_FROM_INT(for_printf);
return (text_alloc += 3) - 3;
}
text string_concat(text t1, text t2) {
if (text_alloc + 4 >= TEXT_POOL_SIZE) fatal_error("string tree pool overflow");
text_pool[text_alloc] = TEXT_FROM_INT(TEXT_TREE);
text_pool[text_alloc + 1] = TEXT_FROM_INT(2);
text_pool[text_alloc + 2] = TEXT_FROM_INT(t1);
text_pool[text_alloc + 3] = TEXT_FROM_INT(t2);
return (text_alloc += 4) - 4;
}
text string_concat3(text t1, text t2, text t3) {
if (text_alloc + 5 >= TEXT_POOL_SIZE) fatal_error("string tree pool overflow");
text_pool[text_alloc] = TEXT_FROM_INT(TEXT_TREE);
text_pool[text_alloc + 1] = TEXT_FROM_INT(3);
text_pool[text_alloc + 2] = TEXT_FROM_INT(t1);
text_pool[text_alloc + 3] = TEXT_FROM_INT(t2);
text_pool[text_alloc + 4] = TEXT_FROM_INT(t3);
return (text_alloc += 5) - 5;
}
text string_concat4(text t1, text t2, text t3, text t4) {
if (text_alloc + 6 >= TEXT_POOL_SIZE) fatal_error("string tree pool overflow");
text_pool[text_alloc] = TEXT_FROM_INT(TEXT_TREE);
text_pool[text_alloc + 1] = TEXT_FROM_INT(4);
text_pool[text_alloc + 2] = TEXT_FROM_INT(t1);
text_pool[text_alloc + 3] = TEXT_FROM_INT(t2);
text_pool[text_alloc + 4] = TEXT_FROM_INT(t3);
text_pool[text_alloc + 5] = TEXT_FROM_INT(t4);
return (text_alloc += 6) - 6;
}
text string_concat5(text t1, text t2, text t3, text t4, text t5) {
if (text_alloc + 7 >= TEXT_POOL_SIZE) fatal_error("string tree pool overflow");
text_pool[text_alloc] = TEXT_FROM_INT(TEXT_TREE);
text_pool[text_alloc + 1] = TEXT_FROM_INT(5);
text_pool[text_alloc + 2] = TEXT_FROM_INT(t1);
text_pool[text_alloc + 3] = TEXT_FROM_INT(t2);
text_pool[text_alloc + 4] = TEXT_FROM_INT(t3);
text_pool[text_alloc + 5] = TEXT_FROM_INT(t4);
text_pool[text_alloc + 6] = TEXT_FROM_INT(t5);
return (text_alloc += 7) - 7;
}
// Dead code but keeping it around in case we need to wrap mutable strings
// text wrap_str(char *s) {
// int i = 0;
// int result = text_alloc;
//
// text_pool[result] = TEXT_FROM_INT(TEXT_TREE);
// text_alloc += 2;
// while (s[i] != 0) {
// text_pool[text_alloc] = wrap_char(s[i]);
// text_alloc += 1;
// i += 1;
// }
//
// text_pool[result + 1] = TEXT_FROM_INT(i);
//
// return result;
// }
// Like wrap_str, but assumes that the string is immutable and doesn't need to be copied
text wrap_str_imm(char *s, char *end) {
if (text_alloc + 3 >= TEXT_POOL_SIZE) fatal_error("string tree pool overflow");
text_pool[text_alloc] = TEXT_FROM_INT(TEXT_STRING);
text_pool[text_alloc + 1] = TEXT_FROM_PTR(s);
text_pool[text_alloc + 2] = TEXT_FROM_PTR(end); // end of string address. 0 for null-terminated strings
return (text_alloc += 3) - 3;
}
text wrap_str_lit(char *s) {
return wrap_str_imm(s, 0);
}
text wrap_str_pool(int s) {
return wrap_str_imm(string_pool + s, 0);
}
text concatenate_strings_with(text t1, text t2, text sep) {
if (t1 == 0) return t2;
if (t2 == 0) return t1;
return string_concat3(t1, sep, t2);
}
void print_escaped_char(char c, int for_printf) {
// C escape sequences
if (c == '\0') { putchar('\\'); putchar('0'); }
else if (c == '\a') { putchar('\\'); putchar('a'); }
else if (c == '\b') { putchar('\\'); putchar('b'); }
else if (c == '\f') { putchar('\\'); putchar('f'); }
else if (c == '\n') { putchar('\\'); putchar('n'); }
else if (c == '\r') { putchar('\\'); putchar('r'); }
else if (c == '\t') { putchar('\\'); putchar('t'); }
else if (c == '\v') { putchar('\\'); putchar('v'); }
// backslashes are escaped twice, first by the shell and then by def_str
else if (c == '\\') { putchar('\\'); putchar('\\'); putchar('\\'); putchar('\\'); }
// Shell special characters: $, `, ", ', ?, and newline
// Note that ' and ? are not escaped properly by dash, but that's ok because
// we use double quotes and ' and ? can be left as is.
else if (c == '$') { putchar('\\'); putchar('$'); }
else if (c == '`') { putchar('\\'); putchar('`'); }
else if (c == '"') { putchar('\\'); putchar('"'); }
// else if (c == '\'') { putchar('\\'); putchar('\''); }
// else if (c == '?') { putchar('\\'); putchar('?'); }
// when we're escaping a string for shell's printf, % must be escaped
else if (c == '%' && for_printf) { putchar('%'); putchar('%'); }
else putchar(c);
}
void print_escaped_string(char *string_start, char *string_end, int for_printf) {
if (string_end) {
while (string_start < string_end) {
print_escaped_char(*string_start, for_printf);
string_start += 1;
}
} else {
while (*string_start != 0) {
print_escaped_char(*string_start, for_printf);
string_start += 1;
}
}
}
void print_escaped_text(text t, bool for_printf) {
int i;
if (t == 0) return;
if (t < 0) { // it's a character
print_escaped_char(-t, for_printf);
} else if (text_pool[t] == TEXT_FROM_INT(TEXT_TREE)) {
i = 0;
while (TEXT_FROM_INT(i) < text_pool[t + 1]) {
if (text_pool[t + i + 2] < 0) {
print_escaped_char(-TEXT_TO_CHAR(text_pool[t + i + 2]), for_printf);
} else {
print_escaped_text(TEXT_TO_INT(text_pool[t + i + 2]), for_printf);
}
i += 1;
}
} else if (text_pool[t] == TEXT_FROM_INT(TEXT_INTEGER)) {
putint(TEXT_TO_INT(text_pool[t + 1]));
} else if (text_pool[t] == TEXT_FROM_INT(TEXT_STRING)) {
print_escaped_string((char*) text_pool[t + 1], (char*) text_pool[t + 2], for_printf);
} else if (text_pool[t] == TEXT_FROM_INT(TEXT_ESCAPED)) {
fatal_error("Cannot escape a string that is already escaped");
} else {
printf("\nt=%d %d\n", t, TEXT_TO_INT(text_pool[t]));
fatal_error("print_escaped_text: unexpected string tree node");
}
}
void print_text(text t) {
int i;
if (t == 0) return;
if (t < 0) { // it's a character
putchar(-t);
} else if (text_pool[t] == TEXT_FROM_INT(TEXT_TREE)) {
i = 0;
while (TEXT_FROM_INT(i) < text_pool[t + 1]) {
if (text_pool[t + i + 2] < 0) {
putchar(-TEXT_TO_CHAR(text_pool[t + i + 2]));
} else {
print_text(TEXT_TO_INT(text_pool[t + i + 2]));
}
i += 1;
}
} else if (text_pool[t] == TEXT_FROM_INT(TEXT_INTEGER)) {
putint(TEXT_TO_INT(text_pool[t + 1]));
} else if (text_pool[t] == TEXT_FROM_INT(TEXT_STRING)) {
if (TEXT_TO_INT(text_pool[t + 2]) == 0) {
putstr((char*) text_pool[t + 1]);
} else {
i = text_pool[t + 1]; // start
while (i < TEXT_TO_INT(text_pool[t + 2])) {
putchar(string_pool[i]);
i += 1;
}
}
} else if (text_pool[t] == TEXT_FROM_INT(TEXT_ESCAPED)) {
print_escaped_text(TEXT_TO_INT(text_pool[t + 1]), TEXT_TO_INT(text_pool[t + 2]));
} else {
printf("\nt=%d %d\n", t, TEXT_TO_INT(text_pool[t]));
fatal_error("print_text: unexpected string tree node");
}
}
// Codegen context
#define GLO_DECL_SIZE 100000
text glo_decls[GLO_DECL_SIZE]; // Generated code
int glo_decl_ix = 0; // Index of last generated line of code
int nest_level = 0; // Current level of indentation
int in_tail_position = false; // Is the current statement in tail position?
int gensym_ix = 0; // Counter for fresh_ident
int fun_gensym_ix = 0; // Maximum value of gensym_ix for the current function
int max_gensym_ix = 0; // Maximum value of gensym_ix for all functions
int string_counter = 0; // Counter for string literals
#define CHARACTERS_BITFIELD_SIZE 16
int characters_useds[16]; // Characters used in string literals. Bitfield, each int stores 16 bits, so 16 ints in total
bool any_character_used = false; // If any character is used
ast rest_loc_var_fixups = 0; // rest_loc_vars call to fixup after compiling a function
bool main_defined = false; // If the main function is defined
bool main_returns = false; // If the main function returns a value
bool top_level_stmt = true; // If the current statement is at the top level
// Internal identifier node types. These
enum IDENTIFIER_TYPE {
IDENTIFIER_INTERNAL = 600,
IDENTIFIER_STRING,
IDENTIFIER_DOLLAR,
IDENTIFIER_EMPTY
};
void init_comp_context() {
int i = 0;
// Initialize characters_useds table
while (i < 16) {
characters_useds[i] = 0;
i += 1;
}
}
void append_glo_decl(text decl) {
glo_decls[glo_decl_ix] = nest_level;
glo_decls[glo_decl_ix + 1] = 1; // If it's active or not. Used by undo_glo_decls and replay_glo_decls
glo_decls[glo_decl_ix + 2] = decl;
glo_decl_ix += 3;
}
int append_glo_decl_fixup() {
glo_decls[glo_decl_ix] = -nest_level; // Negative value to indicate that it's a fixup
glo_decls[glo_decl_ix + 1] = 1; // If it's active or not. Used by undo_glo_decls and replay_glo_decls
glo_decls[glo_decl_ix + 2] = 0;
glo_decl_ix += 3;
return glo_decl_ix - 3;
}
void fixup_glo_decl(int fixup_ix, text decl) {
if (glo_decls[fixup_ix] >= 0) fatal_error("fixup_glo_decl: invalid fixup");
glo_decls[fixup_ix] = -glo_decls[fixup_ix]; // Make nest level positive
glo_decls[fixup_ix + 2] = decl;
}
// Remove the n last declarations by decrementing the active field.
// A non-positive active value means that the declaration is active,
// A 0 value means that the declaration was unset once.
// A negative value means that the declaration was unset multiple times.
// Because undone declarations are generally replayed, declarations with negative
// values are ignored when replayed since they have already been replayed before.
// This is useful to compile some code at a different time than it is used.
void undo_glo_decls(int start) {
while (start < glo_decl_ix) {
glo_decls[start + 1] -= 1; // To support nested undone declarations
start += 3;
}
}
// Check if there are any active and non-empty declarations since the start index.
// This is used to determine if a ':' statement must be added to the current block.
bool any_active_glo_decls(int start) {
while (start < glo_decl_ix) {
if (glo_decls[start + 1] && glo_decls[start + 2] != 0) return true;
start += 3;
}
return false;
}
// Replay the declarations betwee start and end. Replayed declarations must first
// be undone with undo_glo_decls.
// The reindent parameter controls if the declarations should be replayed at the
// current nest level or at the nest level when they were added.
void replay_glo_decls(int start, int end, int reindent) {
while (start < end) {
if (glo_decls[start + 1] == 0) { // Skip inactive declarations that are at the current level
append_glo_decl(glo_decls[start + 2]);
if (!reindent) glo_decls[glo_decl_ix - 3] = glo_decls[start]; // Replace nest_level
}
start += 3;
}
}
text replay_glo_decls_inline(int start, int end) {
text res = 0;
while (start < end) {
if (glo_decls[start + 1] == 0) { // Skip inactive declarations
res = concatenate_strings_with(res, glo_decls[start + 2], wrap_str_lit("; "));
}
start += 3;
}
if (res != 0) { res = string_concat(res, wrap_str_lit("; ")); }
return res;
}
void print_glo_decls() {
int i = 0;
int level;
while (i < glo_decl_ix) {
if (glo_decls[i + 1] == 1) { // Skip inactive declarations
if (glo_decls[i + 2] != 0) {
level = glo_decls[i];
while (level > 0) {
putchar(' '); putchar(' ');
level -= 1;
}
print_text(glo_decls[i + 2]);
putchar('\n');
}
}
i += 3;
}
}
// Environment tracking
#include "env.c"
// Similar to env_var, but doesn't use the local environment and assumes that the
// identifier is internal or global. This is faster than env_var when we know that
// the variable is not local.
text format_special_var(ast ident, ast prefixed_with_dollar) {
int op = get_op(ident);
if (op == IDENTIFIER_INTERNAL) {
return string_concat(wrap_str_lit("__t"), get_val_(IDENTIFIER_INTERNAL, ident));
} else if (op == IDENTIFIER_STRING) {
return string_concat(wrap_str_lit("__str_"), get_val_(IDENTIFIER_STRING, ident));
} else if (op == IDENTIFIER_DOLLAR) {
if (prefixed_with_dollar) {
if (get_val_(IDENTIFIER_DOLLAR, ident) <= 9) {
return wrap_int(get_val_(IDENTIFIER_DOLLAR, ident));
} else {
return string_concat3(wrap_char('{'), wrap_int(get_val_(IDENTIFIER_DOLLAR, ident)), wrap_char('}'));
}
} else {
if (get_val_(IDENTIFIER_DOLLAR, ident) <= 9) {
return string_concat(wrap_char('$'), wrap_int(get_val_(IDENTIFIER_DOLLAR, ident)));
} else {
return string_concat3(wrap_str_lit("${"), wrap_int(get_val_(IDENTIFIER_DOLLAR, ident)), wrap_char('}'));
}
}
} else if (op == IDENTIFIER_EMPTY) {
return wrap_str_lit("__");
} else {
printf("op=%d %c", op, op);
fatal_error("format_special_var: unknown identifier type");
return 0;
}
}
text struct_member_var(ast member_name_ident) {
return string_concat(wrap_str_lit("__"), wrap_str_pool(probe_string(get_val_(IDENTIFIER, member_name_ident))));
}
text struct_sizeof_var(ast struct_name_ident) {
return string_concat(wrap_str_lit("__sizeof__"), wrap_str_pool(probe_string(get_val_(IDENTIFIER, struct_name_ident))));
}
text global_var(ast ident) {
return string_concat(wrap_char('_'), wrap_str_pool(probe_string(ident)));
}
text env_var_with_prefix(ast ident, ast prefixed_with_dollar) {
if (get_op(ident) == IDENTIFIER) {
if (cgc_lookup_var(get_val_(IDENTIFIER, ident), cgc_locals)) {
// TODO: Constant param optimization
if (get_val_(IDENTIFIER, ident) == ARGV_ID) {
return wrap_str_lit("argv_");
} else {
return wrap_str_pool(probe_string(get_val_(IDENTIFIER, ident)));
}
} else {
return global_var(get_val_(IDENTIFIER, ident));
}
} else {
return format_special_var(ident, prefixed_with_dollar);
}
}
text env_var(ast ident) {
return env_var_with_prefix(ident, false);
}
text function_name(int ident_tok) {
return string_concat(wrap_char('_'), wrap_str_pool(probe_string(ident_tok)));
}
ast fresh_ident() {
gensym_ix += 1;
if (gensym_ix > fun_gensym_ix) {
fun_gensym_ix = gensym_ix;
}
if (gensym_ix > max_gensym_ix) {
max_gensym_ix = gensym_ix;
}
return new_ast0(IDENTIFIER_INTERNAL, wrap_int(gensym_ix));
}
ast fresh_string_ident(int string_probe) {
// Strings are interned, meaning that the same string used twice will have the
// same address. We use the token tag to mark the string as already defined.
// This allows comp_defstr to use the same string variable for the same string.
if (heap[string_probe + 3] == 0) { // tag defaults to 0
string_counter += 1;
heap[string_probe + 3] = string_counter - 1;
}
return new_ast0(IDENTIFIER_STRING, wrap_int(heap[string_probe + 3]));
}
void add_var_to_local_env(ast decl, enum BINDING kind) {
int ident_probe = get_child_(VAR_DECL, decl, 0);
// Make sure we're not shadowing an existing local variable
if (cgc_lookup_var(ident_probe, cgc_locals)) {
putstr("var="); putstr(string_pool + probe_string(ident_probe)); putchar('\n');
fatal_error("Variable is already in local environment");
}
// The var is not part of the environment, so we add it.
cgc_add_local_var(kind, ident_probe, get_child_(VAR_DECL, decl, 1));
}
void add_fun_params_to_local_env(ast lst) {
while (lst != 0) {
add_var_to_local_env(get_child__(',', VAR_DECL, lst, 0), BINDING_PARAM_LOCAL);
lst = get_child_opt_(',', ',', lst, 1);
}
}
// Since global and internal variables are prefixed with _, we restrict the name
// of variables to not start with _. Also, because some shells treat some
// variables as special, we prevent their use.
//
// Also, the shell backend doesn't support variables with aggregate types.
void assert_var_decl_is_safe(ast variable, bool local) { // Helper function for assert_idents_are_safe
ast ident_probe = get_child_(VAR_DECL, variable, 0);
char* name = string_pool + probe_string(ident_probe);
ast type = get_child_(VAR_DECL, variable, 1);
if (name[0] == '_'
|| (name[0] != '\0' && name[1] == '_' && name[2] == '\0')) { // Check for a_ variables that could conflict with character constants
printf("%s ", name);
fatal_error("variable name is invalid. It can't start or end with '_'.");
}
// IFS is a special shell variable that's overwritten by certain.
// In zsh, writing to argv assigns to $@, so we map argv to argv_, and forbid argv_.
// This check only applies to local variables because globals are prefixed with _.
if (local && (ident_probe == ARGV__ID || ident_probe == IFS_ID)) {
printf("%s ", name);
fatal_error("variable name is invalid. It can't be 'IFS' or 'argv_'.");
}
// Local variables don't correspond to memory locations, and can't store
// more than 1 number/pointer.
if (local && (get_op(type) == '[' || (get_op(type) == STRUCT_KW && get_stars(type) == 0))) {
printf("%s ", name);
fatal_error("array/struct value type is not supported for shell backend. Use a reference type instead.");
}
}
void check_param_decls(ast lst) {
while (lst != 0) {
assert_var_decl_is_safe(get_child__(',', VAR_DECL, lst, 0), true);
lst = get_child_(',', lst, 1);
}
}
#ifdef SH_SAVE_VARS_WITH_SET
// Save the value of local variables to positional parameters
text save_local_vars() {
int env = cgc_locals_fun;
ast ident;
text res = 0;
int counter = fun_gensym_ix;
while (env != 0) {
// TODO: Constant param optimization
// if (variable_is_constant_param(local_var)) continue;
ident = new_ast0(IDENTIFIER, binding_ident(env));
res = concatenate_strings_with(string_concat(wrap_char('$'), env_var_with_prefix(ident, true)), res, wrap_char(' '));
env = binding_next(env);
}
while (counter > 0) {
ident = new_ast0(IDENTIFIER_INTERNAL, wrap_int(fun_gensym_ix - counter + 1));
res = concatenate_strings_with(res, string_concat(wrap_char('$'), env_var_with_prefix(ident, true)), wrap_char(' '));
counter -= 1;
}
if (res) {
runtime_use_local_vars = true;
return string_concat(wrap_str_lit("set $@ "), res);
} else {
return 0;
}
}
// Restore the previous value of local variables from positional parameters
text restore_local_vars(int params_count) {
int env = cgc_locals_fun;
ast ident;
// Position of the saved local vars, starting from 0
int local_var_pos = 0;
text res = 0;
int counter = fun_gensym_ix;
// Number of non-constant variables in the environment.
// Used to account for traversal of local env in reverse order.
int env_non_cst_size = 0;
while (env != 0) {
env_non_cst_size += 1;
env = binding_next(env);
// TODO: Constant param optimization
// if(variable_is_constant_param(local_var)) continue;
}
env = cgc_locals_fun;
while (env != 0) {
// TODO: Constant param optimization
// if (variable_is_constant_param(local_var)) continue;
ident = new_ast0(IDENTIFIER, binding_ident(env));
res = concatenate_strings_with(string_concat5(wrap_str_lit("$(("), env_var_with_prefix(ident, true), wrap_str_lit(" = $"), format_special_var(new_ast0(IDENTIFIER_DOLLAR, params_count + env_non_cst_size - local_var_pos), true), wrap_str_lit("))")), res, wrap_char(' '));
local_var_pos += 1;
env = binding_next(env);
}
while (counter > 0) {
ident = new_ast0(IDENTIFIER_INTERNAL, wrap_int(fun_gensym_ix - counter + 1));
res = concatenate_strings_with(res, string_concat5(wrap_str_lit("$(("), env_var_with_prefix(ident, true), wrap_str_lit(" = $"), format_special_var(new_ast0(IDENTIFIER_DOLLAR, params_count + local_var_pos + 1), true), wrap_str_lit("))")), wrap_char(' '));
local_var_pos += 1;
counter -= 1;
}
if (res) {
runtime_use_local_vars = true;
return string_concat3(wrap_str_lit(": $((__tmp = $1)) "), res, wrap_str_lit(" $(($1 = __tmp))"));
} else {
return 0;
}
}
#else
#ifdef SH_INITIALIZE_PARAMS_WITH_LET
// Save the value of local variables to positional parameters
text let_params(int params) {
ast ident;
text res = 0;
int params_ix = 2;
while (params != 0) {
// TODO: Constant param optimization
ident = new_ast0(IDENTIFIER, get_child_(VAR_DECL, get_child__(',', VAR_DECL, params, 0), 0));
res = concatenate_strings_with(res, string_concat4(wrap_str_lit("let "), env_var_with_prefix(ident, false), wrap_char(' '), format_special_var(new_ast0(IDENTIFIER_DOLLAR, params_ix), false)), wrap_str_lit("; "));
params = get_child_opt_(',', ',', params, 1);
params_ix += 1;
}
runtime_use_local_vars |= res != 0;
return res;
}
#endif
text save_local_vars() {
int env = cgc_locals_fun;
ast ident;
text res = 0;
int counter = fun_gensym_ix;
while (counter > 0) {
ident = new_ast0(IDENTIFIER_INTERNAL, wrap_int(counter));
res = concatenate_strings_with(string_concat(wrap_str_lit("let "), format_special_var(ident, true)), res, wrap_str_lit("; "));
counter -= 1;
}
while (env != 0) {
#ifdef SH_INITIALIZE_PARAMS_WITH_LET
if (binding_kind(env) != BINDING_PARAM_LOCAL) { // Skip params
#else
// TODO: Constant param optimization
// Constant function parameters are assigned to $1, $2, ... and don't need to be saved
if (true)
// if (!variable_is_constant_param(local_var)) {
#endif
ident = new_ast0(IDENTIFIER, binding_ident(env));
res = concatenate_strings_with(string_concat(wrap_str_lit("let "), env_var_with_prefix(ident, true)), res, wrap_str_lit("; "));
}
env = binding_next(env);
}
runtime_use_local_vars |= res != 0;
return res;
}
// The only difference between save_local_vars and restore_local_vars is the
// order of the arguments and the call to unsave_vars instead of save_vars.
text restore_local_vars(int params_count) {
int env = cgc_locals_fun;
ast ident;
text res = 0;
int counter = fun_gensym_ix;
while (counter > 0) {
ident = new_ast0(IDENTIFIER_INTERNAL, wrap_int(counter));
res = concatenate_strings_with(res, format_special_var(ident, false), wrap_char(' '));
counter -= 1;
}
while (env != 0) {
// Constant function parameters are assigned to $1, $2, ... and don't need to be saved
// TODO: Constant param optimization
// if (!variable_is_constant_param(local_var)) {
ident = new_ast0(IDENTIFIER, binding_ident(env));
res = concatenate_strings_with(res, env_var(ident), wrap_char(' '));
// }
env = binding_next(env);
}
if (res) {
runtime_use_local_vars = true;
return string_concat(wrap_str_lit("endlet $1 "), res);
} else {
return 0;
}
}
#endif
text op_to_str(int op) {
if (op < 256) return string_concat3(wrap_char(' '), wrap_char(op), wrap_char(' '));
else if (op == AMP_AMP) return wrap_str_lit(" && ");
else if (op == AMP_EQ) return wrap_str_lit(" &= ");
else if (op == BAR_BAR) return wrap_str_lit(" || ");
else if (op == BAR_EQ) return wrap_str_lit(" |= ");
else if (op == CARET_EQ) return wrap_str_lit(" ^= ");
else if (op == EQ_EQ) return wrap_str_lit(" == ");
else if (op == GT_EQ) return wrap_str_lit(" >= ");
else if (op == LSHIFT_EQ) return wrap_str_lit(" <<= ");
else if (op == LT_EQ) return wrap_str_lit(" <= ");
else if (op == LSHIFT) return wrap_str_lit(" << ");
else if (op == MINUS_EQ) return wrap_str_lit(" -= ");
else if (op == EXCL_EQ) return wrap_str_lit(" != ");
else if (op == PERCENT_EQ) return wrap_str_lit(" %= ");
else if (op == PLUS_EQ) return wrap_str_lit(" += ");
else if (op == RSHIFT_EQ) return wrap_str_lit(" >>= ");
else if (op == RSHIFT) return wrap_str_lit(" >> ");
else if (op == SLASH_EQ) return wrap_str_lit(" /= ");
else if (op == STAR_EQ) return wrap_str_lit(" *= ");
else {
printf("op=%d %c\n", op, op);
fatal_error("op_to_str: unexpected operator");
return 0;
}
}
// Similar to op_to_str, but returns the shell test operand instead of the C-style operands.
text test_op_to_str(int op) {
// For == and !=, because integers are stored as strings in most shells, the
// conversion to int can be avoided by comparing the strings instead of using
// -eq and -ne.
if (op == EQ_EQ) return wrap_str_lit(" = ");
else if (op == EXCL_EQ) return wrap_str_lit(" != ");
else if (op == '<') return wrap_str_lit(" -lt ");
else if (op == '>') return wrap_str_lit(" -gt ");
else if (op == LT_EQ) return wrap_str_lit(" -le ");
else if (op == GT_EQ) return wrap_str_lit(" -ge ");
else {
printf("op=%d %c\n", op, op);
fatal_error("test_op_to_str: unexpected operator");
return 0;
}
}
text character_ident(int c) {
// Mark character as used
characters_useds[c / CHARACTERS_BITFIELD_SIZE] |= 1 << (c % CHARACTERS_BITFIELD_SIZE);
any_character_used = true;
if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9')) {
return string_concat5(wrap_char('_'), wrap_char('_'), wrap_char(c), wrap_char('_'), wrap_char('_'));
} else {
if (c == '\0') return wrap_str_lit("__NUL__");
else if (c == '\n') return wrap_str_lit("__NEWLINE__");
else if (c == ' ') return wrap_str_lit("__SPACE__");
else if (c == '!') return wrap_str_lit("__EXCL__");
else if (c == '"') return wrap_str_lit("__DQUOTE__");
else if (c == '#') return wrap_str_lit("__SHARP__");
else if (c == '$') return wrap_str_lit("__DOLLAR__");
else if (c == '%') return wrap_str_lit("__PERCENT__");
else if (c == '&') return wrap_str_lit("__AMP__");
else if (c == '\'') return wrap_str_lit("__QUOTE__");
else if (c == '(') return wrap_str_lit("__LPAREN__");
else if (c == ')') return wrap_str_lit("__RPAREN__");
else if (c == '*') return wrap_str_lit("__STAR__");
else if (c == '+') return wrap_str_lit("__PLUS__");
else if (c == ',') return wrap_str_lit("__COMMA__");
else if (c == '-') return wrap_str_lit("__MINUS__");
else if (c == '.') return wrap_str_lit("__PERIOD__");
else if (c == '/') return wrap_str_lit("__SLASH__");
else if (c == ':') return wrap_str_lit("__COLON__");
else if (c == ';') return wrap_str_lit("__SEMICOLON__");
else if (c == '<') return wrap_str_lit("__LT__");
else if (c == '=') return wrap_str_lit("__EQ__");
else if (c == '>') return wrap_str_lit("__GT__");
else if (c == '?') return wrap_str_lit("__QUESTION__");
else if (c == '@') return wrap_str_lit("__AT__");
else if (c == '^') return wrap_str_lit("__CARET__");
else if (c == '[') return wrap_str_lit("__LBRACK__");
else if (c == '\\') return wrap_str_lit("__BACKSLASH__");
else if (c == ']') return wrap_str_lit("__RBRACK__");
else if (c == '_') return wrap_str_lit("__UNDERSCORE__");
else if (c == '`') return wrap_str_lit("__BACKTICK__");
else if (c == '{') return wrap_str_lit("__LBRACE__");
else if (c == '|') return wrap_str_lit("__BAR__");
else if (c == '}') return wrap_str_lit("__RBRACE__");
else if (c == '~') return wrap_str_lit("__TILDE__");
else if (c == '\a') return wrap_str_lit("__ALARM__");
else if (c == '\b') return wrap_str_lit("__BACKSPACE__");
else if (c == '\f') return wrap_str_lit("__PAGE__");
else if (c == '\r') return wrap_str_lit("__RET__");
else if (c == '\t') return wrap_str_lit("__TAB__");
else if (c == '\v') return wrap_str_lit("__VTAB__");
else { fatal_error("Unknown character"); return 0; }
}
}
ast replaced_fun_calls = 0;
ast replaced_fun_calls_tail = 0;
ast conditional_fun_calls = 0;
ast conditional_fun_calls_tail = 0;
ast literals_inits = 0;
bool contains_side_effects = 0;
ast handle_fun_call_side_effect(ast node, ast assign_to, bool executes_conditionally) {
int start_gensym_ix = gensym_ix;
ast sub1, sub2;
if (assign_to == 0) {
assign_to = fresh_ident(); // Unique identifier for the function call
start_gensym_ix = gensym_ix;
// At this point, the temporary identifier of the variable is not live and
// can be used to evaluate the function arguments. This reduces the number
// of temporary variables.
gensym_ix -= 1;
}
// Traverse the arguments and replace them with the result of
// handle_side_effects_go sub is the parent node of the current argument
sub2 = get_child_('(', node, 1);
if (sub2 != 0) { // Check if not an empty list
sub1 = node; // For 1 param, the parent node is the fun call node
// If there are 2 or more params, we traverse the ',' nodes ...
while (get_op(sub2) == ',') {
sub1 = sub2;; // .. and the parent node is the ',' node
set_child(sub1, 0, handle_side_effects_go(get_child_(',', sub2, 0), executes_conditionally));
sub2 = get_child_(',', sub2, 1);
}
// Handle the last argument
set_child(sub1, 1, handle_side_effects_go(sub2, executes_conditionally));
}
// All the temporary variables used for the function parameters can be
// reused after the function call, so resetting the gensym counter.
gensym_ix = start_gensym_ix;
sub1 = new_ast2('=', assign_to, node);
sub1 = new_ast2(',', sub1, 0);
if (executes_conditionally) {
if (conditional_fun_calls == 0) { conditional_fun_calls = sub1; }
else { set_child(conditional_fun_calls_tail, 1, sub1); }
conditional_fun_calls_tail = sub1;
}
else {
if (replaced_fun_calls == 0) { replaced_fun_calls = sub1; }
else { set_child(replaced_fun_calls_tail, 1, sub1); }
replaced_fun_calls_tail = sub1;
}
return assign_to;
}
// We can't have function calls and other side effects in $(( ... )), so we need to handle them separately.
// For unconditional function calls, they are replaced with unique identifiers and returned as a list with their new identifiers.
// For pre/post-increments/decrements, we map them to a pre-side-effects and replace with the corresponding operation.
// Note that pre/post-increments/decrements of function calls are not supported.
ast handle_side_effects_go(ast node, bool executes_conditionally) {
int op = get_op(node);
int nb_children = get_nb_children(node);
ast sub1, sub2;
ast previous_conditional_fun_calls;
ast left_conditional_fun_calls, right_conditional_fun_calls;
int start_gensym_ix = gensym_ix;
ast child0, child1, child2;
if (nb_children >= 1) { child0 = get_child(node, 0); }
if (nb_children >= 2) { child1 = get_child(node, 1); }
if (nb_children >= 3) { child2 = get_child(node, 2); }
if (nb_children == 0) {
if (op == IDENTIFIER || op == IDENTIFIER_INTERNAL || op == IDENTIFIER_STRING || op == IDENTIFIER_DOLLAR || op == INTEGER || op == CHARACTER) {
return node;
} else if (op == STRING) {
/* We must initialize strings before the expression */
sub1 = fresh_string_ident(get_val_(STRING, node));
literals_inits = new_ast2(',', new_ast2('=', sub1, get_val_(STRING, node)), literals_inits);
return sub1;
} else {
printf("handle_side_effects_go: op=%d %c", op, op);
fatal_error("unexpected operator");
return 0;
}
} else if (nb_children == 1) {
if (op == '&' || op == '*' || op == '+' || op == '-' || op == '~' || op == '!' || op == PARENS) {
// TODO: Reuse ast node?
return new_ast1(op, handle_side_effects_go(child0, executes_conditionally));
} else if (op == PLUS_PLUS_PRE || op == MINUS_MINUS_PRE || op == PLUS_PLUS_POST || op == MINUS_MINUS_POST) {
contains_side_effects = true;
return new_ast1(op, handle_side_effects_go(child0, executes_conditionally));
} else if (op == SIZEOF_KW) {
return node; // sizeof is a compile-time operator
} else {
printf("1: op=%d %c", op, op);
fatal_error("unexpected operator");
return 0;
}
} else if (nb_children == 2) {
if (op == '(') { // Function call
return handle_fun_call_side_effect(node, 0, executes_conditionally);
} else if (op == '=') {
if (get_op(child1) == '(') { // Function call
// In that case, we reuse the left hand side of the assignment as the result location
return handle_fun_call_side_effect(child1, child0, executes_conditionally);
} else {
sub1 = handle_side_effects_go(child0, executes_conditionally);
sub2 = handle_side_effects_go(child1, executes_conditionally); // We could inline that one since the assignment to the global variable is done after the last handle_side_effects_go call
return new_ast2(op, sub1, sub2);
}
} else if (op == '&' || op == '|' || op == '<' || op == '>' || op == '+' || op == '-' || op == '*' || op == '/'
|| op == '%' || op == '^' || op == ',' || op == EQ_EQ || op == EXCL_EQ || op == LT_EQ || op == GT_EQ || op == LSHIFT || op == RSHIFT || op == '['
|| op == '.' || op == ARROW ) {
sub1 = handle_side_effects_go(child0, executes_conditionally);
sub2 = handle_side_effects_go(child1, executes_conditionally); // We could inline that one since the assignment to the global variable is done after the last handle_side_effects_go call
return new_ast2(op, sub1, sub2);
} else if (op == AMP_EQ || op == BAR_EQ || op == CARET_EQ || op == LSHIFT_EQ || op == MINUS_EQ || op == PERCENT_EQ || op == PLUS_EQ || op == RSHIFT_EQ || op == SLASH_EQ || op == STAR_EQ) {
// Just like previous case, except that we update contains_side_effects
contains_side_effects = true;
sub1 = handle_side_effects_go(child0, executes_conditionally);
sub2 = handle_side_effects_go(child1, executes_conditionally); // We could inline that one since the assignment to the global variable is done after the last handle_side_effects_go call
return new_ast2(op, sub1, sub2);
} else if (op == AMP_AMP || op == BAR_BAR) {
previous_conditional_fun_calls = conditional_fun_calls;
conditional_fun_calls = 0;
// The left side is always executed, unless the whole expression is executed conditionally.
// We could compile it as always executed, but it makes the Shell code less regular so we compile it conditionally.
sub1 = handle_side_effects_go(child0, true);
gensym_ix = start_gensym_ix; // Reset gensym counter because the 2 sides are independent
left_conditional_fun_calls = conditional_fun_calls;
conditional_fun_calls = 0;
sub2 = handle_side_effects_go(child1, true);
gensym_ix = start_gensym_ix; // Reset gensym counter because the 2 sides are independent
right_conditional_fun_calls = conditional_fun_calls;
conditional_fun_calls = previous_conditional_fun_calls;
return new_ast4(op, sub1, sub2, left_conditional_fun_calls, right_conditional_fun_calls);
} else if (op == CAST) {
return new_ast2(CAST, child0, handle_side_effects_go(child1, executes_conditionally));
} else {
printf("2: op=%d %c", op, op);
fatal_error("unexpected operator");
return 0;
}
} else if (nb_children == 3) {
if (op == '?') {
previous_conditional_fun_calls = conditional_fun_calls;
conditional_fun_calls = 0;
sub1 = handle_side_effects_go(child1, true);
left_conditional_fun_calls = conditional_fun_calls;
conditional_fun_calls = 0;
sub2 = handle_side_effects_go(child2, true);
right_conditional_fun_calls = conditional_fun_calls;
if (left_conditional_fun_calls != 0 || right_conditional_fun_calls != 0) {
fatal_error("Conditional function calls in ternary operator not allowed");
}
return new_ast3('?', handle_side_effects_go(child0, executes_conditionally), sub1, sub2);
} else {
printf("3: op=%d %c\n", op, op);
fatal_error("unexpected operator");
return 0;
}
} else if (nb_children == 4) {
printf("4: op=%d %c\n", op, op);
fatal_error("unexpected operator");
return 0;