Skip to content

Commit 0db45eb

Browse files
committed
Implement compile time round function
1 parent 4c26959 commit 0db45eb

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/lpython/semantics/python_comptime_eval.h

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ struct PythonIntrinsicProcedures {
4040
{"pow", {m_builtin, &eval_pow}},
4141
{"int", {m_builtin, &eval_int}},
4242
{"float", {m_builtin, &eval_float}},
43+
{"round", {m_builtin, &eval_round}},
4344
{"bin", {m_builtin, &eval_bin}},
4445
{"hex", {m_builtin, &eval_hex}},
4546
{"oct", {m_builtin, &eval_oct}},
@@ -409,6 +410,24 @@ struct PythonIntrinsicProcedures {
409410
}
410411
}
411412

413+
static ASR::expr_t *eval_round(Allocator &al, const Location &loc, Vec<ASR::expr_t*> &args) {
414+
LFORTRAN_ASSERT(ASRUtils::all_args_evaluated(args));
415+
ASR::ttype_t *type = ASRUtils::TYPE(ASR::make_Integer_t(al, loc, 4, nullptr, 0));
416+
if (args.size() != 1) {
417+
throw SemanticError("round() missing required argument 'number' (pos 1)", loc);
418+
}
419+
ASR::expr_t* expr = args[0];
420+
ASR::ttype_t* t = ASRUtils::expr_type(expr);
421+
if (ASRUtils::is_real(*t)) {
422+
double rv = ASR::down_cast<ASR::ConstantReal_t>(expr)->m_r;
423+
int64_t ival = round(rv);
424+
return ASR::down_cast<ASR::expr_t>(make_ConstantInteger_t(al, loc, ival, type));
425+
} else {
426+
throw SemanticError("round() argument must be float for now, not '" +
427+
ASRUtils::type_to_str(t) + "'", loc);
428+
}
429+
}
430+
412431
}; // ComptimeEval
413432

414433
} // namespace LFortran

0 commit comments

Comments
 (0)