diff --git a/integration_tests/test_str_to_int.py b/integration_tests/test_str_to_int.py index 374ca141f0..765dd1e0f3 100644 --- a/integration_tests/test_str_to_int.py +++ b/integration_tests/test_str_to_int.py @@ -20,4 +20,10 @@ def f(): i = i32(int(s)) assert i == -1234 + assert i32(int(" 3 ")) == 3 + assert i32(int("+3")) == 3 + assert i32(int("\n3")) == 3 + assert i32(int("3\n")) == 3 + assert i32(int("\r\t\n3\r\t\n")) == 3 + f() diff --git a/src/lpython/semantics/python_intrinsic_eval.h b/src/lpython/semantics/python_intrinsic_eval.h index cb3c777e42..99a8053a2b 100644 --- a/src/lpython/semantics/python_intrinsic_eval.h +++ b/src/lpython/semantics/python_intrinsic_eval.h @@ -77,20 +77,34 @@ struct IntrinsicNodeHandler { char *c = ASR::down_cast( ASRUtils::expr_value(arg))->m_s; int ival = 0; + std::string str; char *ch = c; - if (*ch == '-') { + if (*ch == '-' || *ch == '+') { ch++; } while (*ch) { + if(*ch == ' '){ + ch++; + continue; + } + if(*ch == '\\'){ + ch++; + if (*ch == 'n' || *ch == 'r' || *ch == 't') { + ch++; + continue; + } + throw SemanticError("invalid literal for int() with base 10: '"+ std::string(c) + "'", arg->base.loc); + } if (*ch == '.') { throw SemanticError("invalid literal for int() with base 10: '"+ std::string(c) + "'", arg->base.loc); } if (*ch < '0' || *ch > '9') { throw SemanticError("invalid literal for int() with base 10: '"+ std::string(c) + "'", arg->base.loc); } + str+=*ch; ch++; } - ival = std::stoi(c); + ival = std::stoi(str); return (ASR::asr_t *)ASR::down_cast(ASR::make_IntegerConstant_t(al, loc, ival, to_type)); }