Sfoglia il codice sorgente

fix https://github.com/pocketpy/pocketpy/issues/214

blueloveTH 2 anni fa
parent
commit
214395fab6
3 ha cambiato i file con 17 aggiunte e 3 eliminazioni
  1. 1 1
      include/pocketpy/common.h
  2. 9 2
      src/pocketpy.cpp
  3. 7 0
      tests/01_int.py

+ 1 - 1
include/pocketpy/common.h

@@ -20,7 +20,7 @@
 #include <deque>
 #include <initializer_list>
 
-#define PK_VERSION				"1.4.1"
+#define PK_VERSION				"1.4.2"
 
 #include "config.h"
 #include "export.h"

+ 9 - 2
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]);
+            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(s.sv(), &val, base)){
-                vm->ValueError("invalid literal for int(): " + s.escape());
+            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()");

+ 7 - 0
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