Skip to content

Commit 672e8c4

Browse files
committed
Add compile time str in python_comptime_eval.h
1 parent 6d568a0 commit 672e8c4

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/lpython/semantics/python_comptime_eval.h

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ struct PythonIntrinsicProcedures {
2626
PythonIntrinsicProcedures() {
2727
comptime_eval_map = {
2828
{"abs", {m_builtin, &eval_abs}},
29+
{"str", {m_builtin, &eval_str}},
2930
};
3031
}
3132

@@ -100,6 +101,36 @@ struct PythonIntrinsicProcedures {
100101
}
101102
}
102103

104+
static ASR::expr_t *eval_str(Allocator &al, const Location &loc, Vec<ASR::expr_t*> &args) {
105+
ASR::ttype_t* str_type = ASRUtils::TYPE(ASR::make_Character_t(al,
106+
loc, 1, 1, nullptr, nullptr, 0));
107+
if (args.size() == 0) { // create an empty string
108+
return ASR::down_cast<ASR::expr_t>(ASR::make_ConstantString_t(al, loc, s2c(al, ""), str_type));
109+
}
110+
ASR::expr_t* arg = ASRUtils::expr_value(args[0]);
111+
ASR::ttype_t* arg_type = ASRUtils::expr_type(arg);
112+
if (ASRUtils::is_integer(*arg_type)) {
113+
int64_t ival = ASR::down_cast<ASR::ConstantInteger_t>(arg)->m_n;
114+
std::string s = std::to_string(ival);
115+
return ASR::down_cast<ASR::expr_t>(ASR::make_ConstantString_t(al, loc, s2c(al, s), str_type));
116+
} else if (ASRUtils::is_real(*arg_type)) {
117+
double rval = ASR::down_cast<ASR::ConstantReal_t>(arg)->m_r;
118+
std::string s = std::to_string(rval);
119+
return ASR::down_cast<ASR::expr_t>(ASR::make_ConstantString_t(al, loc, s2c(al, s), str_type));
120+
} else if (ASRUtils::is_logical(*arg_type)) {
121+
bool rv = ASR::down_cast<ASR::ConstantLogical_t>(arg)->m_value;
122+
std::string s = rv ? "True" : "False";
123+
return ASR::down_cast<ASR::expr_t>(ASR::make_ConstantString_t(al, loc, s2c(al, s), str_type));
124+
} else if (ASRUtils::is_character(*arg_type)) {
125+
char* c = ASR::down_cast<ASR::ConstantString_t>(arg)->m_s;
126+
std::string s = std::string(c);
127+
return ASR::down_cast<ASR::expr_t>(ASR::make_ConstantString_t(al, loc, s2c(al, s), str_type));
128+
} else {
129+
throw SemanticError("str() argument must be real, integer, logical, or a string, not '" +
130+
ASRUtils::type_to_str(arg_type) + "'", loc);
131+
}
132+
}
133+
103134
}; // ComptimeEval
104135

105136
} // namespace LFortran

0 commit comments

Comments
 (0)