This commit is contained in:
blueloveTH 2023-02-01 13:12:21 +08:00
parent b30c46250a
commit 956c0e24e3
5 changed files with 24 additions and 91 deletions

View File

@ -270,28 +270,11 @@ class dict:
a.append(k.__json__()+': '+v.__json__()) a.append(k.__json__()+': '+v.__json__())
return '{'+ ', '.join(a) + '}' return '{'+ ', '.join(a) + '}'
import json as _json import ffi
def jsonrpc(method, params, raw=False): def input():
assert type(method) is str return ffi.input()
assert type(params) is list or type(params) is tuple
data = {
'jsonrpc': '2.0',
'method': method,
'params': params,
}
ret = __string_channel_call(_json.dumps(data))
ret = _json.loads(ret)
if raw:
return ret
assert type(ret) is dict
if 'result' in ret:
return ret['result']
raise JsonRpcError(ret['error']['message'])
def input(prompt=None):
return jsonrpc('input', [prompt])
class FileIO: class FileIO:
def __init__(self, path, mode): def __init__(self, path, mode):
assert type(path) is str assert type(path) is str
@ -299,19 +282,19 @@ class FileIO:
assert mode in ['r', 'w', 'rt', 'wt'] assert mode in ['r', 'w', 'rt', 'wt']
self.path = path self.path = path
self.mode = mode self.mode = mode
self.fp = jsonrpc('fopen', [path, mode]) self.fp = ffi.fopen(path, mode)
def read(self): def read(self):
assert self.mode in ['r', 'rt'] assert self.mode in ['r', 'rt']
return jsonrpc('fread', [self.fp]) return ffi.fread(self.fp)
def write(self, s): def write(self, s):
assert self.mode in ['w', 'wt'] assert self.mode in ['w', 'wt']
assert type(s) is str assert type(s) is str
jsonrpc('fwrite', [self.fp, s]) ffi.fwrite(self.fp, s)
def close(self): def close(self):
jsonrpc('fclose', [self.fp]) ffi.fclose(self.fp)
def __enter__(self): def __enter__(self):
pass pass
@ -423,42 +406,6 @@ class set:
return self._a.keys().__iter__() return self._a.keys().__iter__()
)"; )";
const char* __OS_CODE = R"(
def listdir(path):
assert type(path) is str
return jsonrpc("os.listdir", [path])
def mkdir(path):
assert type(path) is str
return jsonrpc("os.mkdir", [path])
def rmdir(path):
assert type(path) is str
return jsonrpc("os.rmdir", [path])
def remove(path):
assert type(path) is str
return jsonrpc("os.remove", [path])
path = object()
def __path4exists(path):
assert type(path) is str
return jsonrpc("os.path.exists", [path])
path.exists = __path4exists
del __path4exists
def __path4join(*paths):
s = '/'.join(paths)
s = s.replace('\\', '/')
s = s.replace('//', '/')
s = s.replace('//', '/')
return s
path.join = __path4join
del __path4join
)";
const char* __RANDOM_CODE = R"( const char* __RANDOM_CODE = R"(
import time as _time import time as _time

View File

@ -316,7 +316,7 @@ void __initializeBuiltinFunctions(VM* _vm) {
} }
int _index = (int)vm->PyInt_AS_C(args[1]); int _index = (int)vm->PyInt_AS_C(args[1]);
_index = vm->normalizedIndex(_index, _self.u8_length()); _index = vm->normalized_index(_index, _self.u8_length());
return vm->PyStr(_self.u8_getitem(_index)); return vm->PyStr(_self.u8_getitem(_index));
}); });
@ -434,14 +434,14 @@ void __initializeBuiltinFunctions(VM* _vm) {
} }
int _index = (int)vm->PyInt_AS_C(args[1]); int _index = (int)vm->PyInt_AS_C(args[1]);
_index = vm->normalizedIndex(_index, _self.size()); _index = vm->normalized_index(_index, _self.size());
return _self[_index]; return _self[_index];
}); });
_vm->bindMethod<2>("list", "__setitem__", [](VM* vm, const pkpy::ArgList& args) { _vm->bindMethod<2>("list", "__setitem__", [](VM* vm, const pkpy::ArgList& args) {
PyVarList& _self = vm->PyList_AS_C(args[0]); PyVarList& _self = vm->PyList_AS_C(args[0]);
int _index = (int)vm->PyInt_AS_C(args[1]); int _index = (int)vm->PyInt_AS_C(args[1]);
_index = vm->normalizedIndex(_index, _self.size()); _index = vm->normalized_index(_index, _self.size());
_self[_index] = args[2]; _self[_index] = args[2];
return vm->None; return vm->None;
}); });
@ -449,7 +449,7 @@ void __initializeBuiltinFunctions(VM* _vm) {
_vm->bindMethod<1>("list", "__delitem__", [](VM* vm, const pkpy::ArgList& args) { _vm->bindMethod<1>("list", "__delitem__", [](VM* vm, const pkpy::ArgList& args) {
PyVarList& _self = vm->PyList_AS_C(args[0]); PyVarList& _self = vm->PyList_AS_C(args[0]);
int _index = (int)vm->PyInt_AS_C(args[1]); int _index = (int)vm->PyInt_AS_C(args[1]);
_index = vm->normalizedIndex(_index, _self.size()); _index = vm->normalized_index(_index, _self.size());
_self.erase(_self.begin() + _index); _self.erase(_self.begin() + _index);
return vm->None; return vm->None;
}); });
@ -472,7 +472,7 @@ void __initializeBuiltinFunctions(VM* _vm) {
_vm->bindMethod<1>("tuple", "__getitem__", [](VM* vm, const pkpy::ArgList& args) { _vm->bindMethod<1>("tuple", "__getitem__", [](VM* vm, const pkpy::ArgList& args) {
const PyVarList& _self = vm->PyTuple_AS_C(args[0]); const PyVarList& _self = vm->PyTuple_AS_C(args[0]);
int _index = (int)vm->PyInt_AS_C(args[1]); int _index = (int)vm->PyInt_AS_C(args[1]);
_index = vm->normalizedIndex(_index, _self.size()); _index = vm->normalized_index(_index, _self.size());
return _self[_index]; return _self[_index];
}); });
@ -575,7 +575,6 @@ void __add_module_dis(VM* vm){
}); });
} }
#define PY_CLASS(mod, name) inline static PyVar _tp(VM* vm) { return vm->_modules[#mod]->attribs[#name]; } #define PY_CLASS(mod, name) inline static PyVar _tp(VM* vm) { return vm->_modules[#mod]->attribs[#name]; }
struct ReMatch { struct ReMatch {
@ -588,24 +587,18 @@ struct ReMatch {
static PyVar _bind(VM* vm){ static PyVar _bind(VM* vm){
PyVar _tp_match = vm->new_user_type_object(vm->_modules["re"], "Match", vm->_tp_object); PyVar _tp_match = vm->new_user_type_object(vm->_modules["re"], "Match", vm->_tp_object);
vm->bindMethod<0>(_tp_match, "start", [](VM* vm, const pkpy::ArgList& args) { vm->bindMethod<0>(_tp_match, "start", CPP_LAMBDA(vm->PyInt(UNION_GET(ReMatch, args[0]).start)));
return vm->PyInt(UNION_GET(ReMatch, args[0]).start); vm->bindMethod<0>(_tp_match, "end", CPP_LAMBDA(vm->PyInt(UNION_GET(ReMatch, args[0]).end)));
});
vm->bindMethod<0>(_tp_match, "end", [](VM* vm, const pkpy::ArgList& args) {
return vm->PyInt(UNION_GET(ReMatch, args[0]).end);
});
vm->bindMethod<0>(_tp_match, "span", [](VM* vm, const pkpy::ArgList& args) { vm->bindMethod<0>(_tp_match, "span", [](VM* vm, const pkpy::ArgList& args) {
auto& m = UNION_GET(ReMatch, args[0]); auto& m = UNION_GET(ReMatch, args[0]);
PyVarList vec = { vm->PyInt(m.start), vm->PyInt(m.end) }; return vm->PyTuple({ vm->PyInt(m.start), vm->PyInt(m.end) });
return vm->PyTuple(vec);
}); });
vm->bindMethod<1>(_tp_match, "group", [](VM* vm, const pkpy::ArgList& args) { vm->bindMethod<1>(_tp_match, "group", [](VM* vm, const pkpy::ArgList& args) {
auto& m = UNION_GET(ReMatch, args[0]); auto& m = UNION_GET(ReMatch, args[0]);
int index = (int)vm->PyInt_AS_C(args[1]); int index = (int)vm->PyInt_AS_C(args[1]);
index = vm->normalizedIndex(index, m.m.size()); index = vm->normalized_index(index, m.m.size());
return vm->PyStr(m.m[index].str()); return vm->PyStr(m.m[index].str());
}); });
return _tp_match; return _tp_match;
@ -772,13 +765,15 @@ extern "C" {
__add_module_math(vm); __add_module_math(vm);
__add_module_re(vm); __add_module_re(vm);
__add_module_dis(vm); __add_module_dis(vm);
vm->new_module("ffi");
// add builtins | no exception handler | must succeed // add builtins | no exception handler | must succeed
_Code code = vm->compile(__BUILTINS_CODE, "<builtins>", EXEC_MODE); _Code code = vm->compile(__BUILTINS_CODE, "<builtins>", EXEC_MODE);
vm->_exec(code, vm->builtins, pkpy::make_shared<PyVarDict>()); vm->_exec(code, vm->builtins, pkpy::make_shared<PyVarDict>());
pkpy_vm_add_module(vm, "random", __RANDOM_CODE); pkpy_vm_add_module(vm, "random", __RANDOM_CODE);
pkpy_vm_add_module(vm, "os", __OS_CODE);
} }
__EXPORT __EXPORT

View File

@ -700,7 +700,7 @@ public:
return nullptr; return nullptr;
} }
int normalizedIndex(int index, int size){ int normalized_index(int index, int size){
if(index < 0) index += size; if(index < 0) index += size;
if(index < 0 || index >= size){ if(index < 0 || index >= size){
indexError("index out of range, " + std::to_string(index) + " not in [0, " + std::to_string(size) + ")"); indexError("index out of range, " + std::to_string(index) + " not in [0, " + std::to_string(size) + ")");

View File

@ -1,4 +1,7 @@
from math import log, log10, log2, sin, cos, tan, e, pi, isclose, isnan, isinf from math import log, log10, log2, sin, cos, tan, e, pi, isnan, isinf
def isclose(a, b):
return abs(a-b) < 0.000001
assert isclose(e, 2.718281828459045) assert isclose(e, 2.718281828459045)
assert isclose(pi, 3.141592653589793) assert isclose(pi, 3.141592653589793)

View File

@ -1,12 +0,0 @@
import os
# test os.path.join
f = os.path.join
assert f('/', 'a') == '/a'
assert f('/', 'a/', 'b/') == '/a/b/'
assert f('c', 'd') == 'c/d'
assert f('C:\\', 'a') == 'C:/a'
assert f('C:\\', 'a\\', 'b\\') == 'C:/a/b/'
assert f('c\\', 'd/') == 'c/d/'