58#ifndef COMPILER_BACKEND_C_H
59#define COMPILER_BACKEND_C_H
104 [[nodiscard]]
bool ok() const noexcept
110namespace Compiler_Backend_C_Detail {
114 result.reserve(text.size() + 8);
115 for (
const unsigned char ch : text)
117 if (std::isalnum(ch))
118 result.push_back(
static_cast<char>(std::tolower(ch)));
120 result.push_back(
'_');
123 while (not result.empty()
and result.front() ==
'_')
124 result.erase(result.begin());
125 while (not result.empty()
and result.back() ==
'_')
127 while (result.find(
"__") != std::string::npos)
128 result.replace(result.find(
"__"), 2,
"_");
132 if (std::isdigit(
static_cast<unsigned char>(result.front())))
133 result.insert(result.begin(),
'_');
140 for (
char &ch : result)
141 ch =
static_cast<char>(std::toupper(
static_cast<unsigned char>(ch)));
148 result.reserve(text.size() + 2);
149 result.push_back(
'"');
150 for (
const char ch : text)
169 result.push_back(ch);
171 result.push_back(
'"');
177 while (text.find(
"*/") != std::string::npos)
178 text.replace(text.find(
"*/"), 2,
"* /");
188 value = std::strtoll(text.c_str(), &end, 10);
189 return end !=
nullptr and *end ==
'\0';
195 for (
size_t i = 0; i < function.local_slots.size(); ++i)
208 return "v" + std::to_string(
id);
213 return "s" + std::to_string(
id);
218 return "g" + std::to_string(
id);
223 return "B" + std::to_string(
id);
228 return std::string(
count,
' ');
301 if (
types_ ==
nullptr or type_id == 0)
310 ? std::string(
"module")
362 const std::string symbol =
names_.
prefix +
"_f" + std::to_string(i) +
"_"
373 for (
size_t i = 0; i < errors.size(); ++i)
374 fail(errors.access(i));
375 for (
size_t i = 0; i < warnings.size(); ++i)
376 warn(warnings.access(i));
380 fail(
"C backend requires dense zero-based function ids; function '"
382 + std::to_string(
module_->
functions.access(i)->id) +
" but its module index is "
383 + std::to_string(i));
397 std::string &expression,
398 std::string &
error)
const
400 if (inst.
text ==
"unit")
406 if (inst.
text ==
"true" or inst.
text ==
"false")
409 + std::string(inst.
text ==
"true" ?
"true" :
"false") +
")";
413 long long integer_value = 0;
419 + (integer_value == LLONG_MIN ? std::string(
"LLONG_MIN")
420 : std::to_string(integer_value) +
"LL")
437 error =
"C backend does not know how to emit constant literal '" + inst.
text +
"'";
443 out <<
"#include <limits.h>\n"
444 <<
"#include <stdbool.h>\n"
445 <<
"#include <stddef.h>\n"
446 <<
"#include <stdio.h>\n"
447 <<
"#include <stdlib.h>\n"
448 <<
"#include <string.h>\n\n"
469 <<
" bool boolean;\n"
470 <<
" long long integer;\n"
471 <<
" const char * string;\n"
472 <<
" char character;\n"
484 <<
" size_t arity;\n"
485 <<
" const char * name;\n"
487 <<
"static const char *\n"
500 <<
" return \"Unknown\";\n"
505 <<
" fprintf(stderr, \"[" <<
names_.
prefix <<
"] %s\\n\", message);\n"
509 <<
"static inline long long\n"
512 <<
" if ((rhs > 0 && lhs > LLONG_MAX - rhs) || (rhs < 0 && lhs < LLONG_MIN - rhs))\n"
514 <<
" return lhs + rhs;\n"
516 <<
"static inline long long\n"
519 <<
" if ((rhs < 0 && lhs > LLONG_MAX + rhs) || (rhs > 0 && lhs < LLONG_MIN + rhs))\n"
521 <<
" return lhs - rhs;\n"
523 <<
"static inline long long\n"
526 <<
" if (lhs > 0 ? (rhs > 0 ? lhs > LLONG_MAX / rhs : rhs < LLONG_MIN / lhs)\n"
527 <<
" : (rhs > 0 ? lhs < LLONG_MIN / rhs : lhs != 0 && rhs < LLONG_MAX / lhs))\n"
529 <<
" return lhs * rhs;\n"
531 <<
"static inline long long\n"
534 <<
" if (rhs == 0)\n"
536 <<
" if (lhs == LLONG_MIN && rhs == -1)\n"
538 <<
" return lhs / rhs;\n"
540 <<
"static inline long long\n"
543 <<
" if (rhs == 0)\n"
545 <<
" if (rhs == -1)\n"
547 <<
" return lhs % rhs;\n"
549 <<
"static inline long long\n"
552 <<
" if (operand == LLONG_MIN)\n"
554 <<
" return -operand;\n"
561 <<
" value.as.integer = 0;\n"
562 <<
" return value;\n"
569 <<
" value.as.integer = 0;\n"
570 <<
" return value;\n"
577 <<
" value.as.boolean = value_in;\n"
578 <<
" return value;\n"
585 <<
" value.as.integer = value_in;\n"
586 <<
" return value;\n"
593 <<
" value.as.string = value_in;\n"
594 <<
" return value;\n"
601 <<
" value.as.character = value_in;\n"
602 <<
" return value;\n"
609 <<
" value.as.function = function;\n"
610 <<
" return value;\n"
619 <<
"] %s uses an uninitialized value\\n\", context);\n"
622 <<
" return value;\n"
624 <<
"static long long\n"
632 <<
"] %s expects Int but received %s\\n\",\n"
637 <<
" return value.as.integer;\n"
647 <<
"] %s expects Bool but received %s\\n\",\n"
652 <<
" return value.as.boolean;\n"
662 <<
"] %s expects Function but received %s\\n\",\n"
667 <<
" return value.as.function;\n"
675 <<
" if (lhs.tag != rhs.tag)\n"
676 <<
" return false;\n"
677 <<
" switch (lhs.tag)\n"
683 <<
" return lhs.as.boolean == rhs.as.boolean;\n"
685 <<
" return lhs.as.integer == rhs.as.integer;\n"
687 <<
" return strcmp(lhs.as.string, rhs.as.string) == 0;\n"
689 <<
" return lhs.as.character == rhs.as.character;\n"
691 <<
" return lhs.as.function == rhs.as.function;\n"
693 <<
" return false;\n"
704 <<
" if (function->arity != argc)\n"
707 <<
"] function %s expects %zu arguments but received %zu\\n\",\n"
713 <<
" return function->pointer(module, args, argc);\n"
720 <<
" switch (value.tag)\n"
723 <<
" fputs(\"Invalid\", out);\n"
726 <<
" fputs(\"Unit\", out);\n"
729 <<
" fputs(value.as.boolean ? \"Bool(true)\" : \"Bool(false)\", out);\n"
732 <<
" fprintf(out, \"Int(%lld)\", value.as.integer);\n"
735 <<
" fprintf(out, \"String(\\\"%s\\\")\", value.as.string);\n"
738 <<
" fprintf(out, \"Char('%c')\", value.as.character);\n"
741 <<
" fprintf(out, \"Function(%s)\", value.as.function->name);\n"
754 if (global_count == 0)
758 <<
"_GLOBAL_COUNT];\n";
761 out <<
"static void\n"
764 if (global_count == 0)
765 out <<
" (void) module;\n";
771 out <<
"static void\n"
776 <<
" fputs(\"Globals\\n\", out);\n";
777 if (global_count == 0)
778 out <<
" fputs(\" <none>\\n\", out);\n";
783 out <<
" fputs(\" g" << slot.id <<
" "
786 <<
" fputc('\\n', out);\n";
808 <<
"size_t argc);\n\n";
822 for (
size_t i = 0; i < function.
local_slots.size(); ++i)
833 if (not type_text.empty())
843 for (
size_t value_id = 1; value_id <= function.
next_value_id; ++value_id)
852 out <<
" if (argc != " << arity <<
"u)\n"
854 <<
" fprintf(stderr, \"[" <<
names_.
prefix <<
"] function "
856 <<
" expects %zu arguments but received %zu\\n\",\n"
857 <<
" (size_t) " << arity <<
"u,\n"
862 size_t parameter_index = 0;
863 for (
size_t i = 0; i < function.
local_slots.size(); ++i)
870 << parameter_index <<
"];\n";
914 std::string expression;
944 fail(
"C backend cannot emit Store without one operand");
966 fail(
"C backend cannot emit Unary without one operand");
992 fail(
"C backend does not support unary operator '"
1001 fail(
"C backend cannot emit Binary without two operands");
1024 + std::string(op_text))
1029 + std::string(op_text))
1039 out <<
"(lhs_value " << op_text <<
" rhs_value);\n";
1055 + std::string(op_text))
1060 + std::string(op_text))
1063 <<
"(" << checked <<
"(lhs_value, rhs_value));\n"
1081 + std::string(op_text))
1086 + std::string(op_text))
1089 <<
"(lhs_value " << op_text <<
" rhs_value);\n"
1102 + std::string(op_text))
1107 + std::string(op_text))
1110 <<
"(lhs_value " << op_text <<
" rhs_value);\n"
1124 fail(
"C backend does not support binary operator '"
1133 fail(
"C backend cannot emit Call without a callee operand");
1149 + std::to_string(i - 1))
1150 <<
")" << (i + 1 < inst.
operands.
size() ?
"," :
"") <<
'\n';
1207 "entered unreachable block in function " + function.
name)
1213 fail(
"C backend cannot emit unterminated block "
1221 const std::string &symbol)
1227 if (not type_text.empty())
1234 <<
" (void) module;\n";
1241 for (
size_t i = 0; i < function.
blocks.size(); ++i)
1243 const auto &block = function.
blocks.access(i);
1248 for (
size_t inst_index = 0; inst_index < block.
instructions.size(); ++inst_index)
1289 warn(
"C backend was asked to emit main(), but the IR module has no top-level body");
1299 <<
"(&module, NULL, 0u);\n"
1300 <<
" fputs(\"Result = \", stdout);\n"
1302 <<
" fputc('\\n', stdout);\n"
1325 std::ostringstream
out;
1327 out <<
"/* Generated by Compiler_Backend_C.H from explicit IR. */\n\n";
1363 if (module ==
nullptr)
1365 emission.
valid =
false;
1366 emission.
errors.
append(
"Compiler_C_Backend::emit_module(): null IR module");
Reusable explicit-value IR model, validation, and deterministic dumps.
Exception handling system with formatted messages for Aleph-w.
size_t size_t int32_t value
size_t size_t int32_t * out
Emitter(const Compiler_C_Backend_Options &options_in, const Compiler_IR_Module &module_in, const Compiler_Type_Context *types_in)
Builds an emitter over one module and one option set.
const Compiler_IR_Module * module_
void emit_instruction(std::ostream &out, const Compiler_IR_Instruction &inst, const Compiler_IR_Function &function)
void emit_module_layout(std::ostream &out) const
void emit_function(const size_t index, std::ostream &out)
Compiler_C_Backend_Emission emission_
void emit_value_declarations(std::ostream &out, const Compiler_IR_Function &function) const
void emit_top_level(std::ostream &out)
bool emit_constant_expression(const Compiler_IR_Instruction &inst, std::string &expression, std::string &error) const
const Compiler_C_Backend_Options * options_
void initialize_symbols()
void warn(const std::string &message)
std::string function_symbol(const size_t index) const
void emit_parameter_bindings(std::ostream &out, const Compiler_IR_Function &function) const
std::string type_comment(const Compiler_Type_Id type_id) const
const Compiler_Type_Context * types_
void emit_prototypes(std::ostream &out) const
std::string function_descriptor_symbol(const size_t index) const
void emit_function_descriptors(std::ostream &out) const
void emit_main(std::ostream &out)
void emit_slot_declarations(std::ostream &out, const Compiler_IR_Function &function) const
void emit_function_body(std::ostream &out, const Compiler_IR_Function &function, const std::string &symbol)
void emit_function_signature(std::ostream &out, const std::string &symbol) const
void emit_runtime_prelude(std::ostream &out) const
Compiler_C_Backend_Emission run()
Emits the full C translation unit.
void emit_terminator(std::ostream &out, const Compiler_IR_Block &block, const Compiler_IR_Function &function)
void emit_instruction_comment(std::ostream &out, const Compiler_IR_Instruction &inst) const
void fail(const std::string &message)
Emits portable C from one validated Compiler_IR_Module.
Compiler_C_Backend_Emission emit_module(const Compiler_IR_Module *module, const Compiler_Type_Context *types=nullptr) const
Emits one validated IR module as portable C.
Compiler_C_Backend_Options options
Compiler_C_Backend(Compiler_C_Backend_Options options_in={})
Builds one reusable C backend with options_in.
Context owning all compiler type nodes.
std::string to_string(const Compiler_Type_Id id) const
Renders one type to a deterministic human-readable string.
size_t size() const noexcept
Return the current dimension of array.
T & access(const size_t i) noexcept
Fast access without checking allocation and bound_min_clock checking.
T & append()
Allocate a new entry to the end of array.
bool is_empty() const noexcept
Return true if the array is empty.
std::string global_name(const Compiler_IR_Global_Slot_Id id)
size_t count_parameters(const Compiler_IR_Function &function) noexcept
std::string token_name(const Compiler_Operator_Kind kind) noexcept
bool parse_integer_literal(const std::string &text, long long &value) noexcept
std::string indent(const size_t count)
std::string value_name(const Compiler_IR_Value_Id id)
std::string upper_identifier(std::string_view text)
std::string block_label(const size_t id)
std::string sanitize_identifier(std::string_view text)
std::string local_name(const Compiler_IR_Local_Slot_Id id)
std::string c_string_literal(std::string_view text)
std::string safe_comment_text(std::string text)
Main namespace for Aleph-w library functions.
const char * compiler_ir_terminator_kind_name(const Compiler_IR_Terminator_Kind kind) noexcept
Stable debug name for one terminator kind.
void message(const char *file, int line, const char *format,...)
Print an informational message with file and line info.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
const char * compiler_operator_name(const Compiler_Operator_Kind kind) noexcept
Returns a stable debug name for one operator kind.
Compiler_IR_Validation_Report validate_ir_module(const Compiler_IR_Module &module)
Validates all functions in one lowered IR module.
size_t Compiler_IR_Value_Id
constexpr size_t compiler_ir_invalid_id() noexcept
Returns the sentinel invalid IR id.
and
Check uniqueness with explicit hash + equality functors.
const char * compiler_ir_slot_kind_name(const Compiler_IR_Slot_Kind kind) noexcept
Stable debug name for one slot kind.
void error(const char *file, int line, const char *format,...)
Print an error message with file and line info.
size_t Compiler_IR_Global_Slot_Id
const char * compiler_ir_instruction_kind_name(const Compiler_IR_Instruction_Kind kind) noexcept
Stable debug name for one instruction kind.
Compiler_C_Backend_Emission compiler_emit_c_module(const Compiler_IR_Module *module, const Compiler_C_Backend_Options &options={}, const Compiler_Type_Context *types=nullptr)
Convenience wrapper that emits one IR module to portable C.
Compiler_Operator_Kind
Stable operator kinds shared by reusable compiler layers.
size_t Compiler_IR_Local_Slot_Id
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
static struct argp_option options[]
std::string value_type_name
std::string top_level_symbol
std::string make_function_symbol
std::string require_int_symbol
std::string function_type_name
std::string module_struct_name
std::string require_bool_symbol
std::string tag_function_name
std::string make_bool_symbol
std::string require_function_symbol
std::string int_mod_symbol
std::string function_pointer_type_name
std::string tag_name_symbol
std::string int_div_symbol
std::string int_neg_symbol
std::string tag_enum_name
std::string make_string_symbol
std::string tag_invalid_name
std::string tag_char_name
std::string tag_bool_name
std::string make_int_symbol
std::string make_unit_symbol
std::string module_init_symbol
std::string require_assigned_symbol
std::string print_value_symbol
std::string int_sub_symbol
std::string make_invalid_symbol
std::string int_mul_symbol
std::string int_add_symbol
std::string dump_globals_symbol
std::string make_char_symbol
std::string tag_string_name
std::string tag_unit_name
Result of one C backend emission request.
DynArray< std::string > errors
Hard emission failures.
bool valid
Whether emission completed successfully.
DynArray< std::string > warnings
Non-fatal findings.
std::string value_type_name
Generated C typedef name for runtime values.
std::string print_value_symbol
Generated C symbol that prints one runtime value.
std::string module_struct_name
Generated C struct name for module state.
std::string c_prefix
Shared prefix used for runtime helpers and generated symbols.
DynArray< std::string > function_descriptor_symbols
Generated callable descriptor symbols aligned with module.functions.
std::string dump_globals_symbol
Generated C symbol that prints current global state.
std::string module_init_symbol
Generated C symbol that initializes module globals.
bool ok() const noexcept
Returns whether emission finished without hard errors.
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.
std::string source
Final generated C translation unit.
Options that control one C backend emission request.
bool emit_comments
Whether to annotate the generated C with readable IR-derived comments.
bool emit_main
Whether to emit a standalone main() when the IR has a top-level body.
std::string module_name
Prefix used to derive stable C identifiers.
One basic block of IR instructions.
Lowered IR for one function or top-level body.
Compiler_IR_Value_Id next_value_id
Next value id to allocate while lowering.
DynArray< Compiler_IR_Block > blocks
Basic blocks in deterministic id order.
std::string name
Debug or source-level name.
Compiler_Type_Id type_id
Full function type, when known.
Compiler_IR_Block_Id entry_block
Canonical entry block.
DynArray< Compiler_IR_Slot > local_slots
Parameter/local slots in stable order.
One instruction producing an optional explicit result value.
std::string text
Constant spelling or debug payload.
Compiler_IR_Instruction_Kind kind
Instruction category.
Compiler_IR_Value_Id result_id
Produced value id, or 0 for void instructions.
DynArray< Compiler_IR_Value_Id > operands
Input values in deterministic order.
Compiler_Operator_Kind op
Unary/binary operator kind, when relevant.
Compiler_IR_Local_Slot_Id local_slot_id
Referenced local/parameter slot, when relevant.
Compiler_IR_Function_Id function_id
Referenced function id, when relevant.
Compiler_IR_Global_Slot_Id global_slot_id
Referenced global slot, when relevant.
Lowered IR module with shared global slots and functions.
DynArray< Compiler_IR_Slot > global_slots
Module-wide global slots.
DynArray< Compiler_IR_Function * > functions
Lowered non-top-level functions.
Compiler_IR_Function * top_level
Optional top-level body lowered as a function.
Compiler_SSA_Block_Id id
Dense SSA block id.
DynArray< Compiler_SSA_Instruction > instructions
Linear SSA instruction list.
std::string label
Deterministic debug label.
Compiler_SSA_Terminator terminator
Explicit block terminator.
Compiler_SSA_Value_Id return_value
Return value, when relevant.
DynArray< Compiler_SSA_Block_Id > successors
Successors in deterministic order.
Compiler_IR_Terminator_Kind kind
Terminator category.
Compiler_SSA_Value_Id condition_value
Branch condition, when relevant.
Lazy and scalable dynamic array implementation.