-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompiler_Backend_C.H
More file actions
1311 lines (1199 loc) · 54.8 KB
/
Copy pathCompiler_Backend_C.H
File metadata and controls
1311 lines (1199 loc) · 54.8 KB
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
/*
Aleph_w
Data structures & Algorithms
version 2.0.0b
https://github.com/lrleon/Aleph-w
This file is part of Aleph-w library
Copyright (c) 2002-2026 Leandro Rabindranath Leon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/** @file Compiler_Backend_C.H
* @brief Portable C backend that emits standalone C from `Compiler_IR_Model.H`.
*
* This header introduces the first source-emitting backend in the compiler
* platform. The goal is not to model final ABI/layout decisions yet, but to
* provide a readable, deterministic, and executable lowering target that can
* be used for:
*
* - validating the explicit IR end-to-end
* - experimenting with `emit-c` workflows before a full driver exists
* - generating portable artifacts that can be compiled by a normal C toolchain
*
* The emitted C intentionally stays close to the structure of `Compiler_IR_Model.H`:
*
* - each IR function becomes one C function
* - each IR block becomes one C label plus `goto`-based control flow
* - each IR value id becomes one local temporary
* - each local/global slot remains explicit
* - a tiny tagged-value runtime is embedded in the generated translation unit
*
* The current MVP favors clarity and portability over performance. It is
* therefore a good bridge between the reusable IR and future lower-level
* backends such as LLVM IR or native assembly.
*
* @ingroup Utilities
*/
#ifndef COMPILER_BACKEND_C_H
#define COMPILER_BACKEND_C_H
#include <cctype>
#include <cstdlib>
#include <sstream>
#include <string>
#include <string_view>
#include <utility>
#include <Compiler_IR_Model.H>
#include <ah-errors.H>
#include <tpl_dynArray.H>
namespace Aleph {
/** @brief Options that control one C backend emission request. */
struct Compiler_C_Backend_Options
{
std::string module_name = "module"; ///< Prefix used to derive stable C identifiers.
bool emit_main
= false; ///< Whether to emit a standalone `main()` when the IR has a top-level body.
bool emit_comments
= true; ///< Whether to annotate the generated C with readable IR-derived comments.
};
/** @brief Result of one C backend emission request. */
struct Compiler_C_Backend_Emission
{
bool valid = true; ///< Whether emission completed successfully.
DynArray<std::string> errors; ///< Hard emission failures.
DynArray<std::string> warnings; ///< Non-fatal findings.
std::string source; ///< Final generated C translation unit.
std::string c_prefix; ///< Shared prefix used for runtime helpers and generated symbols.
std::string value_type_name; ///< Generated C typedef name for runtime values.
std::string module_struct_name; ///< Generated C struct name for module state.
std::string module_init_symbol; ///< Generated C symbol that initializes module globals.
std::string dump_globals_symbol; ///< Generated C symbol that prints current global state.
std::string print_value_symbol; ///< Generated C symbol that prints one runtime value.
std::string top_level_symbol; ///< Generated C symbol for the lowered top-level body, if any.
DynArray<std::string> function_symbols; ///< Generated C function symbols aligned with `module.functions`.
DynArray<std::string> function_descriptor_symbols; ///< Generated callable descriptor symbols
///< aligned with `module.functions`.
/** @brief Returns whether emission finished without hard errors. */
[[nodiscard]] bool ok() const noexcept
{
return valid;
}
};
namespace Compiler_Backend_C_Detail {
inline std::string sanitize_identifier(std::string_view text)
{
std::string result;
result.reserve(text.size() + 8);
for (const unsigned char ch : text)
{
if (std::isalnum(ch))
result.push_back(static_cast<char>(std::tolower(ch)));
else
result.push_back('_');
}
while (not result.empty() and result.front() == '_')
result.erase(result.begin());
while (not result.empty() and result.back() == '_')
result.pop_back();
while (result.find("__") != std::string::npos)
result.replace(result.find("__"), 2, "_");
if (result.empty())
result = "item";
if (std::isdigit(static_cast<unsigned char>(result.front())))
result.insert(result.begin(), '_');
return result;
}
inline std::string upper_identifier(std::string_view text)
{
std::string result = sanitize_identifier(text);
for (char &ch : result)
ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
return result;
}
inline std::string c_string_literal(std::string_view text)
{
std::string result;
result.reserve(text.size() + 2);
result.push_back('"');
for (const char ch : text)
switch (ch)
{
case '\\':
result += "\\\\";
break;
case '"':
result += "\\\"";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
default:
result.push_back(ch);
}
result.push_back('"');
return result;
}
inline std::string safe_comment_text(std::string text)
{
while (text.find("*/") != std::string::npos)
text.replace(text.find("*/"), 2, "* /");
return text;
}
inline bool parse_integer_literal(const std::string &text, long long &value) noexcept
{
if (text.empty())
return false;
char *end = nullptr;
value = std::strtoll(text.c_str(), &end, 10);
return end != nullptr and *end == '\0';
}
inline size_t count_parameters(const Compiler_IR_Function &function) noexcept
{
size_t count = 0;
for (size_t i = 0; i < function.local_slots.size(); ++i)
if (function.local_slots.access(i).kind == Compiler_IR_Slot_Kind::Parameter)
++count;
return count;
}
inline std::string token_name(const Compiler_Operator_Kind kind) noexcept
{
return compiler_operator_name(kind);
}
inline std::string value_name(const Compiler_IR_Value_Id id)
{
return "v" + std::to_string(id);
}
inline std::string local_name(const Compiler_IR_Local_Slot_Id id)
{
return "s" + std::to_string(id);
}
inline std::string global_name(const Compiler_IR_Global_Slot_Id id)
{
return "g" + std::to_string(id);
}
inline std::string block_label(const size_t id)
{
return "B" + std::to_string(id);
}
inline std::string indent(const size_t count)
{
return std::string(count, ' ');
}
} // namespace Compiler_Backend_C_Detail
/** @brief Emits portable C from one validated `Compiler_IR_Module`. */
class Compiler_C_Backend
{
Compiler_C_Backend_Options options;
struct Symbol_Names
{
std::string prefix;
std::string upper_prefix;
std::string tag_enum_name;
std::string value_type_name;
std::string function_type_name;
std::string function_pointer_type_name;
std::string module_struct_name;
std::string module_init_symbol;
std::string dump_globals_symbol;
std::string print_value_symbol;
std::string tag_name_symbol;
std::string panic_symbol;
std::string require_assigned_symbol;
std::string require_int_symbol;
std::string require_bool_symbol;
std::string require_function_symbol;
std::string equal_symbol;
std::string call_symbol;
std::string make_invalid_symbol;
std::string make_unit_symbol;
std::string make_bool_symbol;
std::string make_int_symbol;
std::string make_string_symbol;
std::string make_char_symbol;
std::string make_function_symbol;
std::string top_level_symbol;
std::string tag_invalid_name;
std::string tag_unit_name;
std::string tag_bool_name;
std::string tag_int_name;
std::string tag_string_name;
std::string tag_char_name;
std::string tag_function_name;
};
class Emitter
{
const Compiler_C_Backend_Options *options_ = nullptr;
const Compiler_IR_Module *module_ = nullptr;
const Compiler_Type_Context *types_ = nullptr;
Compiler_C_Backend_Emission emission_;
Symbol_Names names_;
void fail(const std::string &message)
{
emission_.valid = false;
emission_.errors.append(message);
}
void warn(const std::string &message)
{
emission_.warnings.append(message);
}
[[nodiscard]] std::string type_comment(const Compiler_Type_Id type_id) const
{
if (types_ == nullptr or type_id == 0)
return "";
return types_->to_string(type_id);
}
void initialize_symbols()
{
names_.prefix = "alephc_"
+ Compiler_Backend_C_Detail::sanitize_identifier(options_->module_name.empty()
? std::string("module")
: options_->module_name);
names_.upper_prefix = Compiler_Backend_C_Detail::upper_identifier(names_.prefix);
names_.tag_enum_name = names_.prefix + "_tag";
names_.value_type_name = names_.prefix + "_value";
names_.function_type_name = names_.prefix + "_function";
names_.function_pointer_type_name = names_.prefix + "_function_ptr";
names_.module_struct_name = names_.prefix + "_module";
names_.module_init_symbol = names_.prefix + "_module_init";
names_.dump_globals_symbol = names_.prefix + "_dump_globals";
names_.print_value_symbol = names_.prefix + "_print_value";
names_.tag_name_symbol = names_.prefix + "_tag_name";
names_.panic_symbol = names_.prefix + "_panic";
names_.require_assigned_symbol = names_.prefix + "_require_assigned";
names_.require_int_symbol = names_.prefix + "_require_int";
names_.require_bool_symbol = names_.prefix + "_require_bool";
names_.require_function_symbol = names_.prefix + "_require_function";
names_.equal_symbol = names_.prefix + "_equal";
names_.call_symbol = names_.prefix + "_call";
names_.make_invalid_symbol = names_.prefix + "_make_invalid";
names_.make_unit_symbol = names_.prefix + "_make_unit";
names_.make_bool_symbol = names_.prefix + "_make_bool";
names_.make_int_symbol = names_.prefix + "_make_int";
names_.make_string_symbol = names_.prefix + "_make_string";
names_.make_char_symbol = names_.prefix + "_make_char";
names_.make_function_symbol = names_.prefix + "_make_function";
names_.top_level_symbol = names_.prefix + "_top_level";
names_.tag_invalid_name = names_.upper_prefix + "_TAG_INVALID";
names_.tag_unit_name = names_.upper_prefix + "_TAG_UNIT";
names_.tag_bool_name = names_.upper_prefix + "_TAG_BOOL";
names_.tag_int_name = names_.upper_prefix + "_TAG_INT";
names_.tag_string_name = names_.upper_prefix + "_TAG_STRING";
names_.tag_char_name = names_.upper_prefix + "_TAG_CHAR";
names_.tag_function_name = names_.upper_prefix + "_TAG_FUNCTION";
emission_.c_prefix = names_.prefix;
emission_.value_type_name = names_.value_type_name;
emission_.module_struct_name = names_.module_struct_name;
emission_.module_init_symbol = names_.module_init_symbol;
emission_.dump_globals_symbol = names_.dump_globals_symbol;
emission_.print_value_symbol = names_.print_value_symbol;
emission_.top_level_symbol = module_->top_level != nullptr ? names_.top_level_symbol : "";
for (size_t i = 0; i < module_->functions.size(); ++i)
{
const auto &function = *module_->functions.access(i);
const std::string symbol = names_.prefix + "_f" + std::to_string(i) + "_"
+ Compiler_Backend_C_Detail::sanitize_identifier(function.name);
emission_.function_symbols.append(symbol);
emission_.function_descriptor_symbols.append(symbol + "_descriptor");
}
}
void validate_input()
{
const auto [valid, errors, warnings] = validate_ir_module(*module_);
if (not valid)
for (size_t i = 0; i < errors.size(); ++i)
fail(errors.access(i));
for (size_t i = 0; i < warnings.size(); ++i)
warn(warnings.access(i));
for (size_t i = 0; i < module_->functions.size(); ++i)
if (module_->functions.access(i)->id != i)
fail("C backend requires dense zero-based function ids; function '"
+ module_->functions.access(i)->name + "' has id "
+ std::to_string(module_->functions.access(i)->id) + " but its module index is "
+ std::to_string(i));
}
[[nodiscard]] std::string function_symbol(const size_t index) const
{
return emission_.function_symbols.access(index);
}
[[nodiscard]] std::string function_descriptor_symbol(const size_t index) const
{
return emission_.function_descriptor_symbols.access(index);
}
[[nodiscard]] bool emit_constant_expression(const Compiler_IR_Instruction &inst,
std::string &expression,
std::string &error) const
{
if (inst.text == "unit")
{
expression = names_.make_unit_symbol + "()";
return true;
}
if (inst.text == "true" or inst.text == "false")
{
expression = names_.make_bool_symbol + "("
+ std::string(inst.text == "true" ? "true" : "false") + ")";
return true;
}
long long integer_value = 0;
if (Compiler_Backend_C_Detail::parse_integer_literal(inst.text, integer_value))
{
expression = names_.make_int_symbol + "(" + std::to_string(integer_value) + "LL)";
return true;
}
if (inst.text.size() >= 2 and inst.text.front() == '"' and inst.text.back() == '"')
{
expression = names_.make_string_symbol + "(" + inst.text + ")";
return true;
}
if (inst.text.size() >= 3 and inst.text.front() == '\'' and inst.text.back() == '\'')
{
expression = names_.make_char_symbol + "(" + inst.text + ")";
return true;
}
error = "C backend does not know how to emit constant literal '" + inst.text + "'";
return false;
}
void emit_runtime_prelude(std::ostream &out) const
{
out << "#include <stdbool.h>\n"
<< "#include <stddef.h>\n"
<< "#include <stdio.h>\n"
<< "#include <stdlib.h>\n"
<< "#include <string.h>\n\n"
<< "typedef struct " << names_.value_type_name << " " << names_.value_type_name << ";\n"
<< "typedef struct " << names_.function_type_name << " " << names_.function_type_name
<< ";\n"
<< "typedef struct " << names_.module_struct_name << " " << names_.module_struct_name
<< ";\n\n"
<< "typedef enum " << names_.tag_enum_name << "\n"
<< "{\n"
<< " " << names_.tag_invalid_name << " = 0,\n"
<< " " << names_.tag_unit_name << ",\n"
<< " " << names_.tag_bool_name << ",\n"
<< " " << names_.tag_int_name << ",\n"
<< " " << names_.tag_string_name << ",\n"
<< " " << names_.tag_char_name << ",\n"
<< " " << names_.tag_function_name << "\n"
<< "} " << names_.tag_enum_name << ";\n\n"
<< "struct " << names_.value_type_name << "\n"
<< "{\n"
<< " " << names_.tag_enum_name << " tag;\n"
<< " union\n"
<< " {\n"
<< " bool boolean;\n"
<< " long long integer;\n"
<< " const char * string;\n"
<< " char character;\n"
<< " const " << names_.function_type_name << " * function;\n"
<< " } as;\n"
<< "};\n\n"
<< "typedef " << names_.value_type_name << " (*" << names_.function_pointer_type_name
<< ")(" << names_.module_struct_name << " * module,\n"
<< Compiler_Backend_C_Detail::indent(52) << "const " << names_.value_type_name
<< " * args,\n"
<< Compiler_Backend_C_Detail::indent(52) << "size_t argc);\n\n"
<< "struct " << names_.function_type_name << "\n"
<< "{\n"
<< " " << names_.function_pointer_type_name << " pointer;\n"
<< " size_t arity;\n"
<< " const char * name;\n"
<< "};\n\n"
<< "static const char *\n"
<< names_.tag_name_symbol << "(" << names_.tag_enum_name << " tag)\n"
<< "{\n"
<< " switch (tag)\n"
<< " {\n"
<< " case " << names_.tag_invalid_name << ": return \"Invalid\";\n"
<< " case " << names_.tag_unit_name << ": return \"Unit\";\n"
<< " case " << names_.tag_bool_name << ": return \"Bool\";\n"
<< " case " << names_.tag_int_name << ": return \"Int\";\n"
<< " case " << names_.tag_string_name << ": return \"String\";\n"
<< " case " << names_.tag_char_name << ": return \"Char\";\n"
<< " case " << names_.tag_function_name << ": return \"Function\";\n"
<< " }\n"
<< " return \"Unknown\";\n"
<< "}\n\n"
<< "static void\n"
<< names_.panic_symbol << "(const char * message)\n"
<< "{\n"
<< " fprintf(stderr, \"[" << names_.prefix << "] %s\\n\", message);\n"
<< " exit(1);\n"
<< "}\n\n"
<< "static " << names_.value_type_name << "\n"
<< names_.make_invalid_symbol << "(void)\n"
<< "{\n"
<< " " << names_.value_type_name << " value;\n"
<< " value.tag = " << names_.tag_invalid_name << ";\n"
<< " value.as.integer = 0;\n"
<< " return value;\n"
<< "}\n\n"
<< "static " << names_.value_type_name << "\n"
<< names_.make_unit_symbol << "(void)\n"
<< "{\n"
<< " " << names_.value_type_name << " value;\n"
<< " value.tag = " << names_.tag_unit_name << ";\n"
<< " value.as.integer = 0;\n"
<< " return value;\n"
<< "}\n\n"
<< "static " << names_.value_type_name << "\n"
<< names_.make_bool_symbol << "(bool value_in)\n"
<< "{\n"
<< " " << names_.value_type_name << " value;\n"
<< " value.tag = " << names_.tag_bool_name << ";\n"
<< " value.as.boolean = value_in;\n"
<< " return value;\n"
<< "}\n\n"
<< "static " << names_.value_type_name << "\n"
<< names_.make_int_symbol << "(long long value_in)\n"
<< "{\n"
<< " " << names_.value_type_name << " value;\n"
<< " value.tag = " << names_.tag_int_name << ";\n"
<< " value.as.integer = value_in;\n"
<< " return value;\n"
<< "}\n\n"
<< "static " << names_.value_type_name << "\n"
<< names_.make_string_symbol << "(const char * value_in)\n"
<< "{\n"
<< " " << names_.value_type_name << " value;\n"
<< " value.tag = " << names_.tag_string_name << ";\n"
<< " value.as.string = value_in;\n"
<< " return value;\n"
<< "}\n\n"
<< "static " << names_.value_type_name << "\n"
<< names_.make_char_symbol << "(char value_in)\n"
<< "{\n"
<< " " << names_.value_type_name << " value;\n"
<< " value.tag = " << names_.tag_char_name << ";\n"
<< " value.as.character = value_in;\n"
<< " return value;\n"
<< "}\n\n"
<< "static " << names_.value_type_name << "\n"
<< names_.make_function_symbol << "(const " << names_.function_type_name << " * function)\n"
<< "{\n"
<< " " << names_.value_type_name << " value;\n"
<< " value.tag = " << names_.tag_function_name << ";\n"
<< " value.as.function = function;\n"
<< " return value;\n"
<< "}\n\n"
<< "static " << names_.value_type_name << "\n"
<< names_.require_assigned_symbol << "(" << names_.value_type_name << " value,\n"
<< Compiler_Backend_C_Detail::indent(37) << "const char * context)\n"
<< "{\n"
<< " if (value.tag == " << names_.tag_invalid_name << ")\n"
<< " {\n"
<< " fprintf(stderr, \"[" << names_.prefix
<< "] %s uses an uninitialized value\\n\", context);\n"
<< " exit(1);\n"
<< " }\n"
<< " return value;\n"
<< "}\n\n"
<< "static long long\n"
<< names_.require_int_symbol << "(" << names_.value_type_name << " value,\n"
<< Compiler_Backend_C_Detail::indent(32) << "const char * context)\n"
<< "{\n"
<< " value = " << names_.require_assigned_symbol << "(value, context);\n"
<< " if (value.tag != " << names_.tag_int_name << ")\n"
<< " {\n"
<< " fprintf(stderr, \"[" << names_.prefix
<< "] %s expects Int but received %s\\n\",\n"
<< Compiler_Backend_C_Detail::indent(14) << "context,\n"
<< Compiler_Backend_C_Detail::indent(14) << names_.tag_name_symbol << "(value.tag));\n"
<< " exit(1);\n"
<< " }\n"
<< " return value.as.integer;\n"
<< "}\n\n"
<< "static bool\n"
<< names_.require_bool_symbol << "(" << names_.value_type_name << " value,\n"
<< Compiler_Backend_C_Detail::indent(33) << "const char * context)\n"
<< "{\n"
<< " value = " << names_.require_assigned_symbol << "(value, context);\n"
<< " if (value.tag != " << names_.tag_bool_name << ")\n"
<< " {\n"
<< " fprintf(stderr, \"[" << names_.prefix
<< "] %s expects Bool but received %s\\n\",\n"
<< Compiler_Backend_C_Detail::indent(14) << "context,\n"
<< Compiler_Backend_C_Detail::indent(14) << names_.tag_name_symbol << "(value.tag));\n"
<< " exit(1);\n"
<< " }\n"
<< " return value.as.boolean;\n"
<< "}\n\n"
<< "static const " << names_.function_type_name << " *\n"
<< names_.require_function_symbol << "(" << names_.value_type_name << " value,\n"
<< Compiler_Backend_C_Detail::indent(37) << "const char * context)\n"
<< "{\n"
<< " value = " << names_.require_assigned_symbol << "(value, context);\n"
<< " if (value.tag != " << names_.tag_function_name << ")\n"
<< " {\n"
<< " fprintf(stderr, \"[" << names_.prefix
<< "] %s expects Function but received %s\\n\",\n"
<< Compiler_Backend_C_Detail::indent(14) << "context,\n"
<< Compiler_Backend_C_Detail::indent(14) << names_.tag_name_symbol << "(value.tag));\n"
<< " exit(1);\n"
<< " }\n"
<< " return value.as.function;\n"
<< "}\n\n"
<< "static bool\n"
<< names_.equal_symbol << "(" << names_.value_type_name << " lhs,\n"
<< Compiler_Backend_C_Detail::indent(22) << names_.value_type_name << " rhs)\n"
<< "{\n"
<< " lhs = " << names_.require_assigned_symbol << "(lhs, \"equality lhs\");\n"
<< " rhs = " << names_.require_assigned_symbol << "(rhs, \"equality rhs\");\n"
<< " if (lhs.tag != rhs.tag)\n"
<< " return false;\n"
<< " switch (lhs.tag)\n"
<< " {\n"
<< " case " << names_.tag_invalid_name << ":\n"
<< " case " << names_.tag_unit_name << ":\n"
<< " return true;\n"
<< " case " << names_.tag_bool_name << ":\n"
<< " return lhs.as.boolean == rhs.as.boolean;\n"
<< " case " << names_.tag_int_name << ":\n"
<< " return lhs.as.integer == rhs.as.integer;\n"
<< " case " << names_.tag_string_name << ":\n"
<< " return strcmp(lhs.as.string, rhs.as.string) == 0;\n"
<< " case " << names_.tag_char_name << ":\n"
<< " return lhs.as.character == rhs.as.character;\n"
<< " case " << names_.tag_function_name << ":\n"
<< " return lhs.as.function == rhs.as.function;\n"
<< " }\n"
<< " return false;\n"
<< "}\n\n"
<< "static " << names_.value_type_name << "\n"
<< names_.call_symbol << "(" << names_.module_struct_name << " * module,\n"
<< Compiler_Backend_C_Detail::indent(19) << names_.value_type_name << " callee,\n"
<< Compiler_Backend_C_Detail::indent(19) << "const " << names_.value_type_name
<< " * args,\n"
<< Compiler_Backend_C_Detail::indent(19) << "size_t argc)\n"
<< "{\n"
<< " const " << names_.function_type_name << " * function\n"
<< " = " << names_.require_function_symbol << "(callee, \"call callee\");\n"
<< " if (function->arity != argc)\n"
<< " {\n"
<< " fprintf(stderr, \"[" << names_.prefix
<< "] function %s expects %zu arguments but received %zu\\n\",\n"
<< Compiler_Backend_C_Detail::indent(14) << "function->name,\n"
<< Compiler_Backend_C_Detail::indent(14) << "function->arity,\n"
<< Compiler_Backend_C_Detail::indent(14) << "argc);\n"
<< " exit(1);\n"
<< " }\n"
<< " return function->pointer(module, args, argc);\n"
<< "}\n\n"
<< "static void\n"
<< names_.print_value_symbol << "(FILE * out,\n"
<< Compiler_Backend_C_Detail::indent(27) << names_.value_type_name << " value)\n"
<< "{\n"
<< " value = " << names_.require_assigned_symbol << "(value, \"print value\");\n"
<< " switch (value.tag)\n"
<< " {\n"
<< " case " << names_.tag_invalid_name << ":\n"
<< " fputs(\"Invalid\", out);\n"
<< " return;\n"
<< " case " << names_.tag_unit_name << ":\n"
<< " fputs(\"Unit\", out);\n"
<< " return;\n"
<< " case " << names_.tag_bool_name << ":\n"
<< " fputs(value.as.boolean ? \"Bool(true)\" : \"Bool(false)\", out);\n"
<< " return;\n"
<< " case " << names_.tag_int_name << ":\n"
<< " fprintf(out, \"Int(%lld)\", value.as.integer);\n"
<< " return;\n"
<< " case " << names_.tag_string_name << ":\n"
<< " fprintf(out, \"String(\\\"%s\\\")\", value.as.string);\n"
<< " return;\n"
<< " case " << names_.tag_char_name << ":\n"
<< " fprintf(out, \"Char('%c')\", value.as.character);\n"
<< " return;\n"
<< " case " << names_.tag_function_name << ":\n"
<< " fprintf(out, \"Function(%s)\", value.as.function->name);\n"
<< " return;\n"
<< " }\n"
<< "}\n\n";
}
void emit_module_layout(std::ostream &out) const
{
const size_t global_count = module_->global_slots.size();
out << "enum { " << names_.upper_prefix << "_GLOBAL_COUNT = " << global_count << " };\n\n";
out << "struct " << names_.module_struct_name << "\n"
<< "{\n";
if (global_count == 0)
out << " " << names_.value_type_name << " unused_global;\n";
else
out << " " << names_.value_type_name << " globals[" << names_.upper_prefix
<< "_GLOBAL_COUNT];\n";
out << "};\n\n";
out << "static void\n"
<< names_.module_init_symbol << "(" << names_.module_struct_name << " * module)\n"
<< "{\n";
if (global_count == 0)
out << " (void) module;\n";
else
out << " for (size_t i = 0; i < " << names_.upper_prefix << "_GLOBAL_COUNT; ++i)\n"
<< " module->globals[i] = " << names_.make_invalid_symbol << "();\n";
out << "}\n\n";
out << "static void\n"
<< names_.dump_globals_symbol << "(FILE * out,\n"
<< Compiler_Backend_C_Detail::indent(27) << "const " << names_.module_struct_name
<< " * module)\n"
<< "{\n"
<< " fputs(\"Globals\\n\", out);\n";
if (global_count == 0)
out << " fputs(\" <none>\\n\", out);\n";
else
for (size_t i = 0; i < module_->global_slots.size(); ++i)
{
const auto &slot = module_->global_slots.access(i);
out << " fputs(\" g" << slot.id << " "
<< Compiler_Backend_C_Detail::safe_comment_text(slot.name) << " = \", out);\n"
<< " " << names_.print_value_symbol << "(out, module->globals[" << i << "]);\n"
<< " fputc('\\n', out);\n";
}
out << "}\n\n";
}
void emit_prototypes(std::ostream &out) const
{
for (size_t i = 0; i < module_->functions.size(); ++i)
out << "static " << names_.value_type_name << "\n"
<< function_symbol(i) << "(" << names_.module_struct_name << " * module,\n"
<< Compiler_Backend_C_Detail::indent(function_symbol(i).size() + 8) << "const "
<< names_.value_type_name << " * args,\n"
<< Compiler_Backend_C_Detail::indent(function_symbol(i).size() + 8) << "size_t argc);\n"
<< "static const " << names_.function_type_name << " "
<< function_descriptor_symbol(i) << ";\n\n";
if (module_->top_level != nullptr)
out << "static " << names_.value_type_name << "\n"
<< names_.top_level_symbol << "(" << names_.module_struct_name << " * module,\n"
<< Compiler_Backend_C_Detail::indent(names_.top_level_symbol.size() + 8) << "const "
<< names_.value_type_name << " * args,\n"
<< Compiler_Backend_C_Detail::indent(names_.top_level_symbol.size() + 8)
<< "size_t argc);\n\n";
}
void emit_function_signature(std::ostream &out, const std::string &symbol) const
{
out << "static " << names_.value_type_name << "\n"
<< symbol << "(" << names_.module_struct_name << " * module,\n"
<< Compiler_Backend_C_Detail::indent(symbol.size() + 8) << "const "
<< names_.value_type_name << " * args,\n"
<< Compiler_Backend_C_Detail::indent(symbol.size() + 8) << "size_t argc)\n";
}
void emit_slot_declarations(std::ostream &out, const Compiler_IR_Function &function) const
{
for (size_t i = 0; i < function.local_slots.size(); ++i)
{
const auto &slot = function.local_slots.access(i);
out << " " << names_.value_type_name << " "
<< Compiler_Backend_C_Detail::local_name(slot.id) << " = "
<< names_.make_invalid_symbol << "();";
if (options_->emit_comments)
{
out << " /* " << compiler_ir_slot_kind_name(slot.kind) << ' '
<< Compiler_Backend_C_Detail::safe_comment_text(slot.name);
const auto type_text = type_comment(slot.type_id);
if (not type_text.empty())
out << " : " << Compiler_Backend_C_Detail::safe_comment_text(type_text);
out << " */";
}
out << '\n';
}
}
void emit_value_declarations(std::ostream &out, const Compiler_IR_Function &function) const
{
for (size_t value_id = 1; value_id <= function.next_value_id; ++value_id)
out << " " << names_.value_type_name << " "
<< Compiler_Backend_C_Detail::value_name(value_id) << " = "
<< names_.make_invalid_symbol << "();\n";
}
void emit_parameter_bindings(std::ostream &out, const Compiler_IR_Function &function) const
{
const size_t arity = Compiler_Backend_C_Detail::count_parameters(function);
out << " if (argc != " << arity << "u)\n"
<< " {\n"
<< " fprintf(stderr, \"[" << names_.prefix << "] function "
<< Compiler_Backend_C_Detail::safe_comment_text(function.name)
<< " expects %zu arguments but received %zu\\n\",\n"
<< " (size_t) " << arity << "u,\n"
<< " argc);\n"
<< " exit(1);\n"
<< " }\n";
size_t parameter_index = 0;
for (size_t i = 0; i < function.local_slots.size(); ++i)
{
const auto &slot = function.local_slots.access(i);
if (slot.kind != Compiler_IR_Slot_Kind::Parameter)
continue;
out << " " << Compiler_Backend_C_Detail::local_name(slot.id) << " = args["
<< parameter_index << "];\n";
++parameter_index;
}
}
void emit_instruction_comment(std::ostream &out, const Compiler_IR_Instruction &inst) const
{
if (not options_->emit_comments)
return;
out << " /* ";
if (inst.result_id != 0)
out << Compiler_Backend_C_Detail::value_name(inst.result_id) << " = ";
out << compiler_ir_instruction_kind_name(inst.kind);
if (inst.kind == Compiler_IR_Instruction_Kind::Unary
or inst.kind == Compiler_IR_Instruction_Kind::Binary)
out << '(' << Compiler_Backend_C_Detail::token_name(inst.op) << ')';
if (inst.kind == Compiler_IR_Instruction_Kind::Constant)
out << '(' << Compiler_Backend_C_Detail::safe_comment_text(inst.text) << ')';
if (inst.kind == Compiler_IR_Instruction_Kind::Function_Ref)
out << "(f" << inst.function_id << ')';
out << " */\n";
}
void emit_instruction(std::ostream &out,
const Compiler_IR_Instruction &inst,
const Compiler_IR_Function &function)
{
(void) function;
const auto value = [](const Compiler_IR_Value_Id id)
{
return Compiler_Backend_C_Detail::value_name(id);
};
const auto slot = [](const Compiler_IR_Local_Slot_Id id)
{
return Compiler_Backend_C_Detail::local_name(id);
};
emit_instruction_comment(out, inst);
switch (inst.kind)
{
case Compiler_IR_Instruction_Kind::Constant:
{
std::string expression;
std::string error;
if (not emit_constant_expression(inst, expression, error))
{
fail(error);
return;
}
out << " " << value(inst.result_id) << " = " << expression << ";\n";
break;
}
case Compiler_IR_Instruction_Kind::Load:
if (inst.global_slot_id != compiler_ir_invalid_id())
out << " " << value(inst.result_id) << " = " << names_.require_assigned_symbol
<< "(module->globals[" << inst.global_slot_id << "], "
<< Compiler_Backend_C_Detail::c_string_literal(
"load " + Compiler_Backend_C_Detail::global_name(inst.global_slot_id))
<< ");\n";
else
out << " " << value(inst.result_id) << " = " << names_.require_assigned_symbol << "("
<< slot(inst.local_slot_id) << ", "
<< Compiler_Backend_C_Detail::c_string_literal(
"load " + Compiler_Backend_C_Detail::local_name(inst.local_slot_id))
<< ");\n";
break;
case Compiler_IR_Instruction_Kind::Store:
if (inst.operands.is_empty())
{
fail("C backend cannot emit Store without one operand");
return;
}
if (inst.global_slot_id != compiler_ir_invalid_id())
out << " module->globals[" << inst.global_slot_id
<< "] = " << names_.require_assigned_symbol << "(" << value(inst.operands.access(0))
<< ", "
<< Compiler_Backend_C_Detail::c_string_literal("store operand "
+ value(inst.operands.access(0)))
<< ");\n";
else
out << " " << slot(inst.local_slot_id) << " = " << names_.require_assigned_symbol
<< "(" << value(inst.operands.access(0)) << ", "
<< Compiler_Backend_C_Detail::c_string_literal("store operand "
+ value(inst.operands.access(0)))
<< ");\n";
break;
case Compiler_IR_Instruction_Kind::Unary:
if (inst.operands.is_empty())
{
fail("C backend cannot emit Unary without one operand");
return;
}
switch (inst.op)
{
case Compiler_Operator_Kind::Minus:
out << " " << value(inst.result_id) << " = " << names_.make_int_symbol << "(-"
<< names_.require_int_symbol << "(" << value(inst.operands.access(0)) << ", "
<< Compiler_Backend_C_Detail::c_string_literal("unary minus") << "));\n";
break;
case Compiler_Operator_Kind::Bang:
out << " " << value(inst.result_id) << " = " << names_.make_bool_symbol << "(!"
<< names_.require_bool_symbol << "(" << value(inst.operands.access(0)) << ", "
<< Compiler_Backend_C_Detail::c_string_literal("logical not") << "));\n";
break;
case Compiler_Operator_Kind::Tilde:
out << " " << value(inst.result_id) << " = " << names_.make_int_symbol << "(~"
<< names_.require_int_symbol << "(" << value(inst.operands.access(0)) << ", "
<< Compiler_Backend_C_Detail::c_string_literal("bitwise not") << "));\n";
break;
default:
fail("C backend does not support unary operator '"
+ Compiler_Backend_C_Detail::token_name(inst.op) + "'");
break;
}
break;
case Compiler_IR_Instruction_Kind::Binary:
if (inst.operands.size() < 2)
{
fail("C backend cannot emit Binary without two operands");
return;
}
switch (inst.op)
{
case Compiler_Operator_Kind::Plus:
case Compiler_Operator_Kind::Minus:
case Compiler_Operator_Kind::Star:
case Compiler_Operator_Kind::Amp:
case Compiler_Operator_Kind::Pipe:
case Compiler_Operator_Kind::Caret:
{
const char *op_text = inst.op == Compiler_Operator_Kind::Plus ? "+"
: inst.op == Compiler_Operator_Kind::Minus ? "-"
: inst.op == Compiler_Operator_Kind::Star ? "*"
: inst.op == Compiler_Operator_Kind::Amp ? "&"
: inst.op == Compiler_Operator_Kind::Pipe ? "|"
: "^";
out << " {\n"
<< " long long lhs_value = " << names_.require_int_symbol << "("
<< value(inst.operands.access(0)) << ", "
<< Compiler_Backend_C_Detail::c_string_literal("binary lhs "
+ std::string(op_text))
<< ");\n"
<< " long long rhs_value = " << names_.require_int_symbol << "("
<< value(inst.operands.access(1)) << ", "
<< Compiler_Backend_C_Detail::c_string_literal("binary rhs "
+ std::string(op_text))
<< ");\n"
<< " " << value(inst.result_id) << " = " << names_.make_int_symbol
<< "(lhs_value " << op_text << " rhs_value);\n"
<< " }\n";
break;
}
case Compiler_Operator_Kind::Slash:
case Compiler_Operator_Kind::Percent:
{
const char *op_text = inst.op == Compiler_Operator_Kind::Slash ? "/" : "%";
const char *message = inst.op == Compiler_Operator_Kind::Slash ? "division by zero"
: "modulo by zero";
out << " {\n"
<< " long long lhs_value = " << names_.require_int_symbol << "("
<< value(inst.operands.access(0)) << ", "
<< Compiler_Backend_C_Detail::c_string_literal("binary lhs "
+ std::string(op_text))
<< ");\n"
<< " long long rhs_value = " << names_.require_int_symbol << "("
<< value(inst.operands.access(1)) << ", "
<< Compiler_Backend_C_Detail::c_string_literal("binary rhs "
+ std::string(op_text))
<< ");\n"
<< " if (rhs_value == 0LL)\n"
<< " " << names_.panic_symbol << "("
<< Compiler_Backend_C_Detail::c_string_literal(message) << ");\n"
<< " " << value(inst.result_id) << " = " << names_.make_int_symbol
<< "(lhs_value " << op_text << " rhs_value);\n"
<< " }\n";
break;
}
case Compiler_Operator_Kind::Less:
case Compiler_Operator_Kind::LessEq:
case Compiler_Operator_Kind::Greater:
case Compiler_Operator_Kind::GreaterEq:
{
const char *op_text = inst.op == Compiler_Operator_Kind::Less ? "<"