From b3c59dfddab7dcdcd920f2ac77b95b6fc472710f Mon Sep 17 00:00:00 2001 From: faze-geek Date: Sat, 18 Mar 2023 01:34:55 +0530 Subject: [PATCH 1/2] fix edge cases for int of string --- integration_tests/test_str_to_int.py | 6 ++++++ src/lpython/semantics/python_intrinsic_eval.h | 18 ++++++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/integration_tests/test_str_to_int.py b/integration_tests/test_str_to_int.py index 374ca141f0..a797ea77e1 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 int(" 3 ") == 3 + assert int("+3") == 3 + assert int("\n3") == 3 + assert int("3\n") == 3 + assert 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)); } From 655f51ef289ac77c00b740c3f3e615f893202740 Mon Sep 17 00:00:00 2001 From: faze-geek Date: Sat, 18 Mar 2023 01:45:45 +0530 Subject: [PATCH 2/2] fix mismatch --- integration_tests/test_str_to_int.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/integration_tests/test_str_to_int.py b/integration_tests/test_str_to_int.py index a797ea77e1..765dd1e0f3 100644 --- a/integration_tests/test_str_to_int.py +++ b/integration_tests/test_str_to_int.py @@ -20,10 +20,10 @@ def f(): i = i32(int(s)) assert i == -1234 - assert int(" 3 ") == 3 - assert int("+3") == 3 - assert int("\n3") == 3 - assert int("3\n") == 3 - assert int("\r\t\n3\r\t\n") == 3 + 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()