Skip to content

Commit f5d1b7d

Browse files
committed
Emit header files for ccallable
1 parent 014bddd commit f5d1b7d

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/libasr/codegen/asr_to_c.cpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#include <iostream>
2+
#include <fstream>
23
#include <memory>
34

45
#include <libasr/asr.h>
@@ -655,6 +656,7 @@ R"(
655656
#include <string.h>
656657
#include <lfortran_intrinsics.h>
657658
659+
#ifndef ASSERT
658660
#define ASSERT(cond) \
659661
{ \
660662
if (!(cond)) { \
@@ -665,6 +667,9 @@ R"(
665667
exit(1); \
666668
} \
667669
}
670+
#endif
671+
672+
#ifndef ASSERT_MSG
668673
#define ASSERT_MSG(cond, msg) \
669674
{ \
670675
if (!(cond)) { \
@@ -677,6 +682,7 @@ R"(
677682
exit(1); \
678683
} \
679684
}
685+
#endif
680686
681687
)";
682688

@@ -807,6 +813,24 @@ R"(
807813
}
808814
src = to_include + head + array_types_decls + unit_src +
809815
ds_funcs_defined + util_funcs_defined;
816+
if (!emit_headers.empty()) {
817+
std::string to_includes_1 = "";
818+
for (auto &s: headers) {
819+
to_includes_1 += "#include <" + s + ">\n";
820+
}
821+
for (auto &f_name: emit_headers) {
822+
std::ofstream out_file;
823+
std::string out_src = to_includes_1 + head + f_name.second;
824+
std::string ifdefs = f_name.first.substr(0, f_name.first.length() - 2);
825+
std::transform(ifdefs.begin(), ifdefs.end(), ifdefs.begin(), ::toupper);
826+
ifdefs += "_H";
827+
out_src = "#ifndef " + ifdefs + "\n#define " + ifdefs + "\n\n" + out_src;
828+
out_src += "\n\n#endif\n";
829+
out_file.open(f_name.first);
830+
out_file << out_src;
831+
out_file.close();
832+
}
833+
}
810834
}
811835

812836
void visit_Module(const ASR::Module_t &x) {

src/libasr/codegen/asr_to_c_cpp.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,7 @@ class BaseCCPPVisitor : public ASR::BaseVisitor<Struct>
104104
std::map<uint64_t, SymbolInfo> sym_info;
105105
std::map<uint64_t, std::string> const_var_names;
106106
std::map<int32_t, std::string> gotoid2name;
107+
std::map<std::string, std::string> emit_headers;
107108

108109
// Output configuration:
109110
// Use std::string or char*
@@ -622,6 +623,15 @@ R"(#include <stdio.h>
622623
}
623624
sub += "\n";
624625
src = sub;
626+
if (f_type->m_abi == ASR::abiType::BindC
627+
&& f_type->m_deftype == ASR::deftypeType::Implementation) {
628+
if (x.m_c_header) {
629+
std::string header_name = std::string(x.m_c_header);
630+
user_headers.insert(header_name);
631+
emit_headers[header_name]+= "\n" + src;
632+
src = "";
633+
}
634+
}
625635
current_scope = current_scope_copy;
626636
}
627637

0 commit comments

Comments
 (0)