| 1 |
from pypy.interpreter.error import oefmt, OperationError |
| 2 |
from pypy.interpreter.astcompiler import consts |
| 3 |
from rpython.rtyper.lltypesystem import rffi, lltype |
| 4 |
from rpython.rlib.objectmodel import we_are_translated |
| 5 |
from rpython.rlib.rarithmetic import widen |
| 6 |
from pypy.module.cpyext.api import ( |
| 7 |
cpython_api, CANNOT_FAIL, CONST_STRING, FILEP, fread, feof, Py_ssize_tP, |
| 8 |
cpython_struct, ferror) |
| 9 |
from pypy.module.cpyext.pyobject import PyObject |
| 10 |
from pypy.module.cpyext.pyerrors import PyErr_SetFromErrno |
| 11 |
from pypy.module.cpyext.frameobject import PyFrameObject |
| 12 |
from pypy.module.__builtin__ import compiling |
| 13 |
|
| 14 |
PyCompilerFlags = cpython_struct( |
| 15 |
"PyCompilerFlags", (("cf_flags", rffi.INT), |
| 16 |
("cf_feature_version", rffi.INT))) |
| 17 |
PyCompilerFlagsPtr = lltype.Ptr(PyCompilerFlags) |
| 18 |
|
| 19 |
PyCF_MASK = (consts.CO_FUTURE_DIVISION | |
| 20 |
consts.CO_FUTURE_ABSOLUTE_IMPORT | |
| 21 |
consts.CO_FUTURE_WITH_STATEMENT | |
| 22 |
consts.CO_FUTURE_PRINT_FUNCTION | |
| 23 |
consts.CO_FUTURE_UNICODE_LITERALS) |
| 24 |
|
| 25 |
@cpython_api([PyObject, PyObject, PyObject], PyObject) |
| 26 |
def PyEval_CallObjectWithKeywords(space, w_obj, w_arg, w_kwds): |
| 27 |
return space.call(w_obj, w_arg, w_kwds) |
| 28 |
|
| 29 |
@cpython_api([], PyObject, result_borrowed=True) |
| 30 |
def PyEval_GetBuiltins(space): |
| 31 |
"""Return a dictionary of the builtins in the current execution |
| 32 |
frame, or the interpreter of the thread state if no frame is |
| 33 |
currently executing.""" |
| 34 |
caller = space.getexecutioncontext().gettopframe_nohidden() |
| 35 |
if caller is not None: |
| 36 |
w_globals = caller.get_w_globals() |
| 37 |
w_builtins = space.getitem(w_globals, space.newtext('__builtins__')) |
| 38 |
if not space.isinstance_w(w_builtins, space.w_dict): |
| 39 |
w_builtins = w_builtins.getdict(space) |
| 40 |
else: |
| 41 |
w_builtins = space.builtin.getdict(space) |
| 42 |
return w_builtins |
| 43 |
|
| 44 |
@cpython_api([], PyObject, error=CANNOT_FAIL, result_borrowed=True) |
| 45 |
def PyEval_GetLocals(space): |
| 46 |
"""Return a dictionary of the local variables in the current execution |
| 47 |
frame, or NULL if no frame is currently executing.""" |
| 48 |
caller = space.getexecutioncontext().gettopframe_nohidden() |
| 49 |
if caller is None: |
| 50 |
return None |
| 51 |
return caller.getdictscope() |
| 52 |
|
| 53 |
@cpython_api([], PyObject, error=CANNOT_FAIL, result_borrowed=True) |
| 54 |
def PyEval_GetGlobals(space): |
| 55 |
"""Return a dictionary of the global variables in the current execution |
| 56 |
frame, or NULL if no frame is currently executing.""" |
| 57 |
caller = space.getexecutioncontext().gettopframe_nohidden() |
| 58 |
if caller is None: |
| 59 |
return None |
| 60 |
return caller.get_w_globals() |
| 61 |
|
| 62 |
@cpython_api([], PyFrameObject, error=CANNOT_FAIL, result_borrowed=True) |
| 63 |
def PyEval_GetFrame(space): |
| 64 |
caller = space.getexecutioncontext().gettopframe_nohidden() |
| 65 |
return caller |
| 66 |
|
| 67 |
@cpython_api([PyObject, PyObject, PyObject], PyObject) |
| 68 |
def PyEval_EvalCode(space, w_code, w_globals, w_locals): |
| 69 |
"""This is a simplified interface to PyEval_EvalCodeEx(), with just |
| 70 |
the code object, and the dictionaries of global and local variables. |
| 71 |
The other arguments are set to NULL.""" |
| 72 |
if w_globals is None: |
| 73 |
w_globals = space.w_None |
| 74 |
if w_locals is None: |
| 75 |
w_locals = space.w_None |
| 76 |
return compiling.eval(space, w_code, w_globals, w_locals) |
| 77 |
|
| 78 |
@cpython_api([PyObject, PyObject], PyObject) |
| 79 |
def PyObject_CallObject(space, w_obj, w_arg): |
| 80 |
""" |
| 81 |
Call a callable Python object callable_object, with arguments given by the |
| 82 |
tuple args. If no arguments are needed, then args may be NULL. Returns |
| 83 |
the result of the call on success, or NULL on failure. This is the equivalent |
| 84 |
of the Python expression apply(callable_object, args) or |
| 85 |
callable_object(*args).""" |
| 86 |
return space.call(w_obj, w_arg) |
| 87 |
|
| 88 |
@cpython_api([PyObject], PyObject) |
| 89 |
def PyObject_CallNoArgs(space, w_obj): |
| 90 |
return space.call_function(w_obj) |
| 91 |
|
| 92 |
@cpython_api([PyObject, PyObject], PyObject) |
| 93 |
def PyObject_CallOneArg(space, w_obj, w_arg): |
| 94 |
return space.call_function(w_obj, w_arg) |
| 95 |
|
| 96 |
@cpython_api([PyObject, PyObject], PyObject) |
| 97 |
def PyObject_CallMethodNoArgs(space, w_self, w_name): |
| 98 |
name = space.text_w(w_name) |
| 99 |
return space.call_method(w_self, name) |
| 100 |
|
| 101 |
@cpython_api([PyObject, PyObject, PyObject], PyObject) |
| 102 |
def PyObject_CallMethodOneArg(space, w_self, w_name, w_arg): |
| 103 |
name = space.text_w(w_name) |
| 104 |
return space.call_method(w_self, name, w_arg) |
| 105 |
|
| 106 |
@cpython_api([PyObject, PyObject, PyObject], PyObject) |
| 107 |
def PyObject_Call(space, w_obj, w_args, w_kw): |
| 108 |
""" |
| 109 |
Call a callable Python object, with arguments given by the |
| 110 |
tuple args, and named arguments given by the dictionary kw. If no named |
| 111 |
arguments are needed, kw may be NULL. args must not be NULL, use an |
| 112 |
empty tuple if no arguments are needed. Returns the result of the call on |
| 113 |
success, or NULL on failure. This is the equivalent of the Python expression |
| 114 |
apply(callable_object, args, kw) or callable_object(*args, **kw).""" |
| 115 |
return space.call(w_obj, w_args, w_kw) |
| 116 |
|
| 117 |
|
| 118 |
@cpython_api([PyObject, PyObject, PyObject], PyObject) |
| 119 |
def PyCFunction_Call(space, w_obj, w_args, w_kw): |
| 120 |
return space.call(w_obj, w_args, w_kw) |
| 121 |
|
| 122 |
|
| 123 |
Py_single_input = 256 |
| 124 |
Py_file_input = 257 |
| 125 |
Py_eval_input = 258 |
| 126 |
Py_func_type_input = 345 |
| 127 |
|
| 128 |
def compile_string(space, source, filename, start, flags=0, feature_version=-1): |
| 129 |
w_source = space.newbytes(source) |
| 130 |
start = rffi.cast(lltype.Signed, start) |
| 131 |
if start == Py_file_input: |
| 132 |
mode = 'exec' |
| 133 |
elif start == Py_eval_input: |
| 134 |
mode = 'eval' |
| 135 |
elif start == Py_single_input: |
| 136 |
mode = 'single' |
| 137 |
elif start == Py_func_type_input: |
| 138 |
mode = 'func_type' |
| 139 |
else: |
| 140 |
raise oefmt(space.w_ValueError, |
| 141 |
"invalid mode parameter for compilation") |
| 142 |
return compiling.compile(space, w_source, filename, mode, flags, |
| 143 |
_feature_version=feature_version) |
| 144 |
|
| 145 |
def run_string(space, source, filename, start, w_globals, w_locals): |
| 146 |
w_code = compile_string(space, source, filename, start) |
| 147 |
return compiling.eval(space, w_code, w_globals, w_locals) |
| 148 |
|
| 149 |
@cpython_api([CONST_STRING], rffi.INT_real, error=-1) |
| 150 |
def PyRun_SimpleString(space, command): |
| 151 |
"""This is a simplified interface to PyRun_SimpleStringFlags() below, |
| 152 |
leaving the PyCompilerFlags* argument set to NULL.""" |
| 153 |
command = rffi.charp2str(command) |
| 154 |
run_string(space, command, "<string>", Py_file_input, |
| 155 |
space.w_None, space.w_None) |
| 156 |
return 0 |
| 157 |
|
| 158 |
@cpython_api([CONST_STRING, rffi.INT_real,PyObject, PyObject], PyObject) |
| 159 |
def PyRun_String(space, source, start, w_globals, w_locals): |
| 160 |
"""This is a simplified interface to PyRun_StringFlags() below, leaving |
| 161 |
flags set to NULL.""" |
| 162 |
source = rffi.charp2str(source) |
| 163 |
filename = "<string>" |
| 164 |
return run_string(space, source, filename, start, w_globals, w_locals) |
| 165 |
|
| 166 |
@cpython_api([CONST_STRING, rffi.INT_real, PyObject, PyObject, |
| 167 |
PyCompilerFlagsPtr], PyObject) |
| 168 |
def PyRun_StringFlags(space, source, start, w_globals, w_locals, flagsptr): |
| 169 |
"""Execute Python source code from str in the context specified by the |
| 170 |
dictionaries globals and locals with the compiler flags specified by |
| 171 |
flags. The parameter start specifies the start token that should be used to |
| 172 |
parse the source code. |
| 173 |
|
| 174 |
Returns the result of executing the code as a Python object, or NULL if an |
| 175 |
exception was raised.""" |
| 176 |
source = rffi.charp2str(source) |
| 177 |
if flagsptr: |
| 178 |
flags = rffi.cast(lltype.Signed, flagsptr.c_cf_flags) |
| 179 |
feature_version = rffi.cast(lltype.Signed, flagsptr.c_cf_feature_version) |
| 180 |
else: |
| 181 |
flags = 0 |
| 182 |
feature_version = -1 |
| 183 |
w_code = compile_string(space, source, "<string>", start, flags=flags, |
| 184 |
feature_version=feature_version) |
| 185 |
return compiling.eval(space, w_code, w_globals, w_locals) |
| 186 |
|
| 187 |
@cpython_api([FILEP, CONST_STRING, rffi.INT_real, PyObject, PyObject], PyObject) |
| 188 |
def PyRun_File(space, fp, filename, start, w_globals, w_locals): |
| 189 |
"""This is a simplified interface to PyRun_FileExFlags() below, leaving |
| 190 |
closeit set to 0 and flags set to NULL.""" |
| 191 |
BUF_SIZE = 8192 |
| 192 |
source = "" |
| 193 |
filename = rffi.charp2str(filename) |
| 194 |
with rffi.scoped_alloc_buffer(BUF_SIZE) as buf: |
| 195 |
while True: |
| 196 |
try: |
| 197 |
count = fread(buf.raw, 1, BUF_SIZE, fp) |
| 198 |
except OSError: |
| 199 |
PyErr_SetFromErrno(space, space.w_IOError) |
| 200 |
return |
| 201 |
count = rffi.cast(lltype.Signed, count) |
| 202 |
source += rffi.charpsize2str(buf.raw, count) |
| 203 |
if count < BUF_SIZE: |
| 204 |
if ferror(fp): |
| 205 |
PyErr_SetFromErrno(space, space.w_IOError) |
| 206 |
return |
| 207 |
if feof(fp): |
| 208 |
break |
| 209 |
PyErr_SetFromErrno(space, space.w_IOError) |
| 210 |
return run_string(space, source, filename, start, w_globals, w_locals) |
| 211 |
|
| 212 |
|
| 213 |
@cpython_api([PyObject, Py_ssize_tP], rffi.INT_real, error=0) |
| 214 |
def _PyEval_SliceIndex(space, w_obj, pi): |
| 215 |
"""Extract a slice index from a PyInt or PyLong or an object with the |
| 216 |
nb_index slot defined, and store in *pi. |
| 217 |
Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX, |
| 218 |
and silently boost values less than -PY_SSIZE_T_MAX-1 to -PY_SSIZE_T_MAX-1. |
| 219 |
|
| 220 |
Return 0 on error, 1 on success. |
| 221 |
|
| 222 |
Note: If v is NULL, return success without storing into *pi. This |
| 223 |
is because_PyEval_SliceIndex() is called by apply_slice(), which can be |
| 224 |
called by the SLICE opcode with v and/or w equal to NULL. |
| 225 |
""" |
| 226 |
if w_obj is not None: |
| 227 |
pi[0] = space.getindex_w(w_obj, None) |
| 228 |
return 1 |
| 229 |
|
| 230 |
@cpython_api([CONST_STRING, CONST_STRING, rffi.INT_real, PyCompilerFlagsPtr], |
| 231 |
PyObject) |
| 232 |
def Py_CompileStringFlags(space, source, filename, start, flagsptr): |
| 233 |
"""Parse and compile the Python source code in str, returning the |
| 234 |
resulting code object. The start token is given by start; this |
| 235 |
can be used to constrain the code which can be compiled and should |
| 236 |
be Py_eval_input, Py_file_input, or Py_single_input. The filename |
| 237 |
specified by filename is used to construct the code object and may |
| 238 |
appear in tracebacks or SyntaxError exception messages. This |
| 239 |
returns NULL if the code cannot be parsed or compiled.""" |
| 240 |
source = rffi.charp2str(source) |
| 241 |
filename = rffi.charp2str(filename) |
| 242 |
if flagsptr: |
| 243 |
flags = rffi.cast(lltype.Signed, flagsptr.c_cf_flags) |
| 244 |
else: |
| 245 |
flags = 0 |
| 246 |
return compile_string(space, source, filename, start, flags) |
| 247 |
|
| 248 |
@cpython_api([PyCompilerFlagsPtr], rffi.INT_real, error=CANNOT_FAIL) |
| 249 |
def PyEval_MergeCompilerFlags(space, cf): |
| 250 |
"""This function changes the flags of the current evaluation |
| 251 |
frame, and returns true on success, false on failure.""" |
| 252 |
flags = rffi.cast(lltype.Signed, cf.c_cf_flags) |
| 253 |
result = flags != 0 |
| 254 |
current_frame = space.getexecutioncontext().gettopframe_nohidden() |
| 255 |
if current_frame: |
| 256 |
codeflags = current_frame.pycode.co_flags |
| 257 |
compilerflags = codeflags & PyCF_MASK |
| 258 |
if compilerflags: |
| 259 |
result = 1 |
| 260 |
flags |= compilerflags |
| 261 |
|
| 262 |
|
| 263 |
|
| 264 |
|
| 265 |
cf.c_cf_flags = rffi.cast(rffi.INT, flags) |
| 266 |
return result |
| 267 |
|
| 268 |
@cpython_api([], rffi.INT_real, error=CANNOT_FAIL) |
| 269 |
def Py_GetRecursionLimit(space): |
| 270 |
from pypy.module.sys.vm import getrecursionlimit |
| 271 |
return space.int_w(getrecursionlimit(space)) |
| 272 |
|
| 273 |
@cpython_api([rffi.INT_real], lltype.Void, error=CANNOT_FAIL) |
| 274 |
def Py_SetRecursionLimit(space, limit): |
| 275 |
from pypy.module.sys.vm import setrecursionlimit |
| 276 |
setrecursionlimit(space, widen(limit)) |
| 277 |
|
| 278 |
limit = 0 |
| 279 |
|
| 280 |
@cpython_api([CONST_STRING], rffi.INT_real, error=1) |
| 281 |
def Py_EnterRecursiveCall(space, where): |
| 282 |
"""Marks a point where a recursive C-level call is about to be performed. |
| 283 |
|
| 284 |
If USE_STACKCHECK is defined, this function checks if the the OS |
| 285 |
stack overflowed using PyOS_CheckStack(). In this is the case, it |
| 286 |
sets a MemoryError and returns a nonzero value. |
| 287 |
|
| 288 |
The function then checks if the recursion limit is reached. If this is the |
| 289 |
case, a RuntimeError is set and a nonzero value is returned. |
| 290 |
Otherwise, zero is returned. |
| 291 |
|
| 292 |
where should be a string such as " in instance check" to be |
| 293 |
concatenated to the RuntimeError message caused by the recursion depth |
| 294 |
limit.""" |
| 295 |
if not we_are_translated(): |
| 296 |
|
| 297 |
global limit |
| 298 |
limit += 1 |
| 299 |
if limit > 10: |
| 300 |
raise oefmt(space.w_RecursionError, |
| 301 |
"maximum recursion depth exceeded%s", rffi.charp2str(where)) |
| 302 |
return 0 |
| 303 |
from rpython.rlib.rstack import stack_almost_full |
| 304 |
if stack_almost_full(): |
| 305 |
raise oefmt(space.w_RecursionError, |
| 306 |
"maximum recursion depth exceeded%s", rffi.charp2str(where)) |
| 307 |
return 0 |
| 308 |
|
| 309 |
@cpython_api([], lltype.Void) |
| 310 |
def Py_LeaveRecursiveCall(space): |
| 311 |
"""Ends a Py_EnterRecursiveCall(). Must be called once for each |
| 312 |
successful invocation of Py_EnterRecursiveCall().""" |
| 313 |
|
| 314 |
if not we_are_translated(): |
| 315 |
limit = 0 |
| 316 |
|
| 317 |
@cpython_api([], PyObject, result_borrowed=True) |
| 318 |
def _PyEval_GetAsyncGenFirstiter(space): |
| 319 |
|
| 320 |
ec = space.getexecutioncontext() |
| 321 |
return ec.w_asyncgen_firstiter_fn |
| 322 |
|
| 323 |
@cpython_api([], PyObject, result_borrowed=True) |
| 324 |
def _PyEval_GetAsyncGenFinalizer(space): |
| 325 |
|
| 326 |
ec = space.getexecutioncontext() |
| 327 |
return ec.w_asyncgen_finalizer_fn |
| 328 |
|
| 329 |
@cpython_api([PyObject], rffi.CONST_CCHARP) |
| 330 |
def PyEval_GetFuncName(space, w_obj): |
| 331 |
try: |
| 332 |
if space.isinstance_w(w_obj, space.w_type): |
| 333 |
|
| 334 |
|
| 335 |
w_name = space.getattr(space.type(w_obj), space.newtext('__name__')) |
| 336 |
else: |
| 337 |
w_name = space.getattr(w_obj, space.newtext('__name__')) |
| 338 |
name = space.utf8_w(w_name) |
| 339 |
except OperationError as e: |
| 340 |
e.write_unraisable(space, "PyEval_GetFuncName") |
| 341 |
name = "unknown" |
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
return rffi.str2constcharp(name, track_allocation=False) |
| 346 |
|
| 347 |
|
| 348 |
|