Skip to content

Commit ed9d56f

Browse files
committed
C: Implement allocatable
1 parent e487d07 commit ed9d56f

File tree

1 file changed

+40
-3
lines changed

1 file changed

+40
-3
lines changed

src/libasr/codegen/asr_to_c_cpp.h

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1811,23 +1811,60 @@ R"(#include <stdio.h>
18111811

18121812
void visit_Allocate(const ASR::Allocate_t &x) {
18131813
std::string indent(indentation_level*indentation_spaces, ' ');
1814-
std::string out = indent + "// FIXME: allocate(";
1814+
std::string out = "";
18151815
for (size_t i=0; i<x.n_args; i++) {
18161816
ASR::symbol_t* tmp_sym = nullptr;
1817+
ASR::ttype_t* type = nullptr;
18171818
ASR::expr_t* tmp_expr = x.m_args[i].m_a;
18181819
if( ASR::is_a<ASR::Var_t>(*tmp_expr) ) {
18191820
const ASR::Var_t* tmp_var = ASR::down_cast<ASR::Var_t>(tmp_expr);
18201821
tmp_sym = tmp_var->m_v;
1822+
type = ASRUtils::expr_type(tmp_expr);
18211823
} else {
18221824
throw CodeGenError("Cannot deallocate variables in expression " +
18231825
std::to_string(tmp_expr->type),
18241826
tmp_expr->base.loc);
18251827
}
1828+
std::string sym = ASRUtils::symbol_name(tmp_sym);
1829+
if (ASRUtils::is_array(type)) {
1830+
std::string size_str = "1";
1831+
out += indent + sym + "->n_dims = " + std::to_string(x.m_args[i].n_dims) + ";\n";
1832+
for (size_t j=0; j<x.m_args[i].n_dims; j++) {
1833+
std::string st, l;
1834+
if (x.m_args[i].m_dims[j].m_start) {
1835+
self().visit_expr(*x.m_args[i].m_dims[j].m_start);
1836+
st = src;
1837+
} else {
1838+
st = "0";
1839+
}
1840+
if (x.m_args[i].m_dims[j].m_length) {
1841+
self().visit_expr(*x.m_args[i].m_dims[j].m_length);
1842+
l = src;
1843+
} else {
1844+
l = "1";
1845+
}
1846+
size_str += "*" + l;
1847+
out += indent + sym + "->dims[" + std::to_string(j) + "].lower_bound = ";
1848+
out += st + ";\n";
1849+
out += indent + sym + "->dims[" + std::to_string(j) + "].length = ";
1850+
out += l + ";\n";
1851+
}
1852+
std::string ty = CUtils::get_c_type_from_ttype_t(type);
1853+
size_str += "*sizeof(" + ty + ")";
1854+
out += indent + sym + "->data = (" + ty + "*) _lfortran_malloc(" + size_str + ")";
1855+
out += ";\n";
1856+
out += indent + sym + "->is_allocated = true;\n";
1857+
} else {
1858+
std::string ty = CUtils::get_c_type_from_ttype_t(type), size_str;
1859+
size_str = "sizeof(" + ty + ")";
1860+
out += indent + sym + " = (" + ty + "*) _lfortran_malloc(" + size_str + ")";
1861+
out += ";\n";
1862+
}
18261863
//ASR::dimension_t* dims = x.m_args[i].m_dims;
18271864
//size_t n_dims = x.m_args[i].n_dims;
1828-
out += std::string(ASRUtils::symbol_name(tmp_sym)) + ", ";
1865+
// out += std::string(ASRUtils::symbol_name(tmp_sym)) + ", ";
18291866
}
1830-
out += ");\n";
1867+
//out += ");\n";
18311868
src = out;
18321869
}
18331870

0 commit comments

Comments
 (0)