From 214395fab6206568648418e35396d480c5475cc3 Mon Sep 17 00:00:00 2001 From: blueloveTH Date: Mon, 26 Feb 2024 10:40:37 +0800 Subject: [PATCH] fix https://github.com/pocketpy/pocketpy/issues/214 --- include/pocketpy/common.h | 2 +- src/pocketpy.cpp | 13 ++++++++++--- tests/01_int.py | 7 +++++++ 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/include/pocketpy/common.h b/include/pocketpy/common.h index 3bf7b9fc..bfe8cdc2 100644 --- a/include/pocketpy/common.h +++ b/include/pocketpy/common.h @@ -20,7 +20,7 @@ #include #include -#define PK_VERSION "1.4.1" +#define PK_VERSION "1.4.2" #include "config.h" #include "export.h" diff --git a/src/pocketpy.cpp b/src/pocketpy.cpp index 143c116a..6dbfa6bc 100644 --- a/src/pocketpy.cpp +++ b/src/pocketpy.cpp @@ -411,10 +411,17 @@ void init_builtins(VM* _vm) { int base = 10; if(args.size() == 1+2) base = CAST(i64, args[2]); const Str& s = CAST(Str&, args[1]); - i64 val; - if(!parse_int(s.sv(), &val, base)){ - vm->ValueError("invalid literal for int(): " + s.escape()); + std::string_view sv = s.sv(); + bool negative = false; + if(!sv.empty() && (sv[0] == '+' || sv[0] == '-')){ + negative = sv[0] == '-'; + sv.remove_prefix(1); } + i64 val; + if(!parse_int(sv, &val, base)){ + vm->ValueError(_S("invalid literal for int() with base ", base, ": ", s.escape())); + } + if(negative) val = -val; return VAR(val); } vm->TypeError("invalid arguments for int()"); diff --git a/tests/01_int.py b/tests/01_int.py index 995f9522..bbab4d31 100644 --- a/tests/01_int.py +++ b/tests/01_int.py @@ -62,6 +62,13 @@ assert int(1.5) == 1 assert int(-1.5) == -1 assert int("123") == 123 +assert int("0x123", 16) == 291 +assert int("0o123", 8) == 83 +assert int("-0x123", 16) == -291 +assert int("-0o123", 8) == -83 +assert int("-123") == -123 +assert int("+123") == 123 + # test >> << & | ^ assert 12 >> 1 == 6 assert 12 << 1 == 24