blueloveTH 3 лет назад
Родитель
Сommit
4201a811a2
8 измененных файлов с 154 добавлено и 216 удалено
  1. 65 45
      src/builtins.h
  2. 1 1
      src/compiler.h
  3. 14 14
      src/pocketpy.h
  4. 1 1
      src/safestl.h
  5. 64 152
      src/str.h
  6. 1 1
      src/vm.h
  7. 7 1
      tests/_builtin_ty.py
  8. 1 1
      tests/_class.py

+ 65 - 45
src/builtins.h

@@ -8,6 +8,56 @@ def print(*args, sep=' ', end='\n'):
     s = sep.join([str(i) for i in args])
     __sys_stdout_write(s + end)
 
+def round(x):
+    if x >= 0:
+        return int(x + 0.5)
+    else:
+        return int(x - 0.5)
+
+def abs(x):
+    if x < 0:
+        return -x
+    return x
+
+def max(a, b):
+    if a > b:
+        return a
+    return b
+
+def min(a, b):
+    if a < b:
+        return a
+    return b
+
+def sum(iterable):
+    res = 0
+    for i in iterable:
+        res += i
+    return res
+
+def map(f, iterable):
+    return [f(i) for i in iterable]
+
+def zip(a, b):
+    return [(a[i], b[i]) for i in range(min(len(a), len(b)))]
+
+def reversed(iterable):
+    a = list(iterable)
+    return [a[i] for i in range(len(a)-1, -1, -1)]
+
+def sorted(iterable, key=None, reverse=False):
+    if key is None:
+        key = lambda x: x
+    a = [key(i) for i in iterable]
+    b = list(iterable)
+    for i in range(len(a)):
+        for j in range(i+1, len(a)):
+            if (a[i] > a[j]) ^ reverse:
+                a[i], a[j] = a[j], a[i]
+                b[i], b[j] = b[j], b[i]
+    return b
+
+##### str #####
 
 str.__mul__ = lambda self, n: ''.join([self for _ in range(n)])
 
@@ -29,13 +79,27 @@ str.split = __str4split
 del __str4split
 
 def __str4index(self, sub):
-    for i in range(len(self) - len(sub) + 1):
+    for i in range(len(self)):
         if self[i:i+len(sub)] == sub:
             return i
     return -1
 str.index = __str4index
 del __str4index
 
+def __str4strip(self, chars=None):
+    chars = chars or ' \t\n\r'
+    i = 0
+    while i < len(self) and self[i] in chars:
+        i += 1
+    j = len(self) - 1
+    while j >= 0 and self[j] in chars:
+        j -= 1
+    return self[i:j+1]
+str.strip = __str4strip
+del __str4strip
+
+##### list #####
+
 list.__repr__ = lambda self: '[' + ', '.join([repr(i) for i in self]) + ']'
 tuple.__repr__ = lambda self: '(' + ', '.join([repr(i) for i in self]) + ')'
 list.__json__ = lambda self: '[' + ', '.join([i.__json__() for i in self]) + ']'
@@ -201,50 +265,6 @@ class dict:
             a.append(k.__json__()+': '+v.__json__())
         return '{'+ ', '.join(a) + '}'
 
-def round(x):
-    if x >= 0:
-        return int(x + 0.5)
-    else:
-        return int(x - 0.5)
-
-def max(a, b):
-    if a > b:
-        return a
-    return b
-
-def min(a, b):
-    if a < b:
-        return a
-    return b
-
-def sum(iterable):
-    res = 0
-    for i in iterable:
-        res += i
-    return res
-
-def map(f, iterable):
-    return [f(i) for i in iterable]
-
-def zip(a, b):
-    return [(a[i], b[i]) for i in range(min(len(a), len(b)))]
-
-def reversed(iterable):
-    a = list(iterable)
-    return [a[i] for i in range(len(a)-1, -1, -1)]
-
-def sorted(iterable, key=None, reverse=False):
-    if key is None:
-        key = lambda x: x
-    a = [key(i) for i in iterable]
-    b = list(iterable)
-    for i in range(len(a)):
-        for j in range(i+1, len(a)):
-            if (a[i] > a[j]) ^ reverse:
-                a[i], a[j] = a[j], a[i]
-                b[i], b[j] = b[j], b[i]
-    return b
-
 import json as _json
 
 def jsonrpc(method, params, raw=False):

+ 1 - 1
src/compiler.h

@@ -353,7 +353,7 @@ public:
     void exprFString() {
         static const std::regex pattern(R"(\{(.*?)\})");
         PyVar value = parser->previous.value;
-        std::string s = vm->PyStr_AS_C(value).str();
+        _Str s = vm->PyStr_AS_C(value);
         std::sregex_iterator begin(s.begin(), s.end(), pattern);
         std::sregex_iterator end;
         int size = 0;

+ 14 - 14
src/pocketpy.h

@@ -47,7 +47,7 @@ void __initializeBuiltinFunctions(VM* _vm) {
 
     _vm->bindBuiltinFunc("super", [](VM* vm, const pkpy::ArgList& args) {
         vm->__checkArgSize(args, 0);
-        auto it = vm->topFrame()->f_locals.find("self"_c);
+        auto it = vm->topFrame()->f_locals.find(m_self);
         if(it == vm->topFrame()->f_locals.end()) vm->typeError("super() can only be called in a class method");
         return vm->newObject(vm->_tp_super, it->second);
     });
@@ -113,7 +113,7 @@ void __initializeBuiltinFunctions(VM* _vm) {
         std::vector<_Str> names;
         for (auto& [k, _] : args[0]->attribs) names.push_back(k);
         for (auto& [k, _] : args[0]->_type->attribs) {
-            if (k.str().find("__") == 0) continue;
+            if (k.find("__") == 0) continue;
             if (std::find(names.begin(), names.end(), k) == names.end()) names.push_back(k);
         }
         PyVarList ret;
@@ -194,8 +194,8 @@ void __initializeBuiltinFunctions(VM* _vm) {
             const _Str& s = vm->PyStr_AS_C(args[0]);
             try{
                 size_t parsed = 0;
-                _Int val = std::stoll(s.str(), &parsed, 10);
-                if(parsed != s.str().size()) throw std::invalid_argument("");
+                _Int val = std::stoll(s, &parsed, 10);
+                if(parsed != s.size()) throw std::invalid_argument("");
                 return vm->PyInt(val);
             }catch(std::invalid_argument&){
                 vm->valueError("invalid literal for int(): '" + s + "'");
@@ -256,7 +256,7 @@ void __initializeBuiltinFunctions(VM* _vm) {
             if(s == "inf") return vm->PyFloat(INFINITY);
             if(s == "-inf") return vm->PyFloat(-INFINITY);
             try{
-                _Float val = std::stod(s.str());
+                _Float val = std::stod(s);
                 return vm->PyFloat(val);
             }catch(std::invalid_argument&){
                 vm->valueError("invalid literal for float(): '" + s + "'");
@@ -306,7 +306,7 @@ void __initializeBuiltinFunctions(VM* _vm) {
     _vm->bindMethod("str", "__contains__", [](VM* vm, const pkpy::ArgList& args) {
         const _Str& _self = vm->PyStr_AS_C(args[0]);
         const _Str& _other = vm->PyStr_AS_C(args[1]);
-        return vm->PyBool(_self.str().find(_other.str()) != _Str::npos);
+        return vm->PyBool(_self.find(_other) != _Str::npos);
     });
 
     _vm->bindMethod("str", "__str__", [](VM* vm, const pkpy::ArgList& args) {
@@ -365,7 +365,7 @@ void __initializeBuiltinFunctions(VM* _vm) {
         vm->__checkArgSize(args, 1, true);
         const _Str& _self (vm->PyStr_AS_C(args[0]));
         _StrStream ss;
-        for(auto c : _self.str()) ss << (char)toupper(c);
+        for(auto c : _self) ss << (char)toupper(c);
         return vm->PyStr(ss.str());
     });
 
@@ -373,7 +373,7 @@ void __initializeBuiltinFunctions(VM* _vm) {
         vm->__checkArgSize(args, 1, true);
         const _Str& _self (vm->PyStr_AS_C(args[0]));
         _StrStream ss;
-        for(auto c : _self.str()) ss << (char)tolower(c);
+        for(auto c : _self) ss << (char)tolower(c);
         return vm->PyStr(ss.str());
     });
 
@@ -382,12 +382,12 @@ void __initializeBuiltinFunctions(VM* _vm) {
         const _Str& _self = vm->PyStr_AS_C(args[0]);
         const _Str& _old = vm->PyStr_AS_C(args[1]);
         const _Str& _new = vm->PyStr_AS_C(args[2]);
-        std::string _copy = _self.str();
+        _Str _copy = _self;
         // replace all occurences of _old with _new in _copy
         size_t pos = 0;
-        while ((pos = _copy.find(_old.str(), pos)) != std::string::npos) {
-            _copy.replace(pos, _old.str().length(), _new.str());
-            pos += _new.str().length();
+        while ((pos = _copy.find(_old, pos)) != std::string::npos) {
+            _copy.replace(pos, _old.length(), _new);
+            pos += _new.length();
         }
         return vm->PyStr(_copy);
     });
@@ -396,14 +396,14 @@ void __initializeBuiltinFunctions(VM* _vm) {
         vm->__checkArgSize(args, 2, true);
         const _Str& _self = vm->PyStr_AS_C(args[0]);
         const _Str& _prefix = vm->PyStr_AS_C(args[1]);
-        return vm->PyBool(_self.str().find(_prefix.str()) == 0);
+        return vm->PyBool(_self.find(_prefix) == 0);
     });
 
     _vm->bindMethod("str", "endswith", [](VM* vm, const pkpy::ArgList& args) {
         vm->__checkArgSize(args, 2, true);
         const _Str& _self = vm->PyStr_AS_C(args[0]);
         const _Str& _suffix = vm->PyStr_AS_C(args[1]);
-        return vm->PyBool(_self.str().rfind(_suffix.str()) == _self.str().length() - _suffix.str().length());
+        return vm->PyBool(_self.rfind(_suffix) == _self.length() - _suffix.length());
     });
 
     _vm->bindMethod("str", "join", [](VM* vm, const pkpy::ArgList& args) {

+ 1 - 1
src/safestl.h

@@ -51,7 +51,7 @@ public:
     const PyVar& operator[](const _Str& key) const {
         auto it = find(key);
         if (it == end()){
-            auto msg = "map key not found, '" + key.str() + "'";
+            auto msg = "map key not found, '" + key + "'";
             throw std::out_of_range(msg);
         }
         return it->second;

Разница между файлами не показана из-за своего большого размера
+ 64 - 152
src/str.h


+ 1 - 1
src/vm.h

@@ -857,7 +857,7 @@ public:
         this->True = newObject(_tp_bool, true);
         this->False = newObject(_tp_bool, false);
         this->builtins = newModule("builtins");
-        this->_main = newModule("__main__"_c);
+        this->_main = newModule("__main__");
 
         setAttr(_tp_type, __base__, _tp_object);
         _tp_type->_type = _tp_type;

+ 7 - 1
tests/_builtin_ty.py

@@ -166,4 +166,10 @@ assert result == [1, 'a', 2, 'b', 3, 'c']
 a = [1,2,3,-1]
 assert sorted(a) == [-1,1,2,3]
 assert sorted(a, lambda x:-x) == [3,2,1,-1]
-assert sorted(a, None, True) == [3,2,1,-1]
+assert sorted(a, None, True) == [3,2,1,-1]
+
+assert abs(0) == 0
+assert abs(1.0) == 1.0
+assert abs(-1.0) == 1.0
+assert abs(1) == 1
+assert abs(-1) == 1

+ 1 - 1
tests/_class.py

@@ -5,7 +5,7 @@ class A:
 
     def add(self):
         return self.a + self.b
-    
+
     def sub(self):
         return self.a - self.b
     

Некоторые файлы не были показаны из-за большого количества измененных файлов