| 1 |
Bytecode Interpreter |
| 2 |
==================== |
| 3 |
|
| 4 |
.. contents:: |
| 5 |
|
| 6 |
|
| 7 |
Introduction and Overview |
| 8 |
------------------------- |
| 9 |
|
| 10 |
This document describes the implementation of PyPy's |
| 11 |
Bytecode Interpreter and related Virtual Machine functionalities. |
| 12 |
|
| 13 |
PyPy's bytecode interpreter has a structure reminiscent of CPython's |
| 14 |
Virtual Machine: It processes code objects parsed and compiled from |
| 15 |
Python source code. It is implemented in the :source:`pypy/interpreter/` directory. |
| 16 |
People familiar with the CPython implementation will easily recognize |
| 17 |
similar concepts there. The major differences are the overall usage of |
| 18 |
the :doc:`object space <objspace>` indirection to perform operations on objects, and |
| 19 |
the organization of the built-in modules (described :ref:`here <modules>`). |
| 20 |
|
| 21 |
Code objects are a nicely preprocessed, structured representation of |
| 22 |
source code, and their main content is *bytecode*. We use the same |
| 23 |
compact bytecode format as CPython 2.7, with minor differences in the bytecode |
| 24 |
set. Our bytecode compiler is |
| 25 |
implemented as a chain of flexible passes (tokenizer, lexer, parser, |
| 26 |
abstract syntax tree builder and bytecode generator). The latter passes |
| 27 |
are based on the ``compiler`` package from the standard library of |
| 28 |
CPython, with various improvements and bug fixes. The bytecode compiler |
| 29 |
(living under :source:`pypy/interpreter/astcompiler/`) is now integrated and is |
| 30 |
translated with the rest of PyPy. |
| 31 |
|
| 32 |
Code objects contain |
| 33 |
condensed information about their respective functions, class and |
| 34 |
module body source codes. Interpreting such code objects means |
| 35 |
instantiating and initializing a `Frame class`_ and then |
| 36 |
calling its ``frame.eval()`` method. This main entry point |
| 37 |
initialize appropriate namespaces and then interprets each |
| 38 |
bytecode instruction. Python's standard library contains |
| 39 |
the :source:`lib-python/2.7/dis.py` module which allows to inspection |
| 40 |
of the virtual machine's bytecode instructions:: |
| 41 |
|
| 42 |
>>> import dis |
| 43 |
>>> def f(x): |
| 44 |
... return x + 1 |
| 45 |
>>> dis.dis(f) |
| 46 |
2 0 LOAD_FAST 0 (x) |
| 47 |
3 LOAD_CONST 1 (1) |
| 48 |
6 BINARY_ADD |
| 49 |
7 RETURN_VALUE |
| 50 |
|
| 51 |
CPython and PyPy are stack-based virtual machines, i.e. |
| 52 |
they don't have registers but instead push object to and pull objects |
| 53 |
from a stack. The bytecode interpreter is only responsible |
| 54 |
for implementing control flow and pushing and pulling black |
| 55 |
box objects to and from this value stack. The bytecode interpreter |
| 56 |
does not know how to perform operations on those black box |
| 57 |
(:ref:`wrapped <wrapped>`) objects for which it delegates to the :doc:`object |
| 58 |
space <objspace>`. In order to implement a conditional branch in a program's |
| 59 |
execution, however, it needs to gain minimal knowledge about a |
| 60 |
wrapped object. Thus, each object space has to offer a |
| 61 |
``is_true(w_obj)`` operation which returns an |
| 62 |
interpreter-level boolean value. |
| 63 |
|
| 64 |
For the understanding of the interpreter's inner workings it |
| 65 |
is crucial to recognize the concepts of :ref:`interpreter-level and |
| 66 |
application-level <interpreter-level>` code. In short, interpreter-level is executed |
| 67 |
directly on the machine and invoking application-level functions |
| 68 |
leads to an bytecode interpretation indirection. However, |
| 69 |
special care must be taken regarding exceptions because |
| 70 |
application level exceptions are wrapped into ``OperationErrors`` |
| 71 |
which are thus distinguished from plain interpreter-level exceptions. |
| 72 |
See :ref:`application level exceptions <applevel-exceptions>` for some more information |
| 73 |
on ``OperationErrors``. |
| 74 |
|
| 75 |
The interpreter implementation offers mechanisms to allow a |
| 76 |
caller to be unaware of whether a particular function invocation |
| 77 |
leads to bytecode interpretation or is executed directly at |
| 78 |
interpreter-level. The two basic kinds of `Gateway classes`_ |
| 79 |
expose either an interpreter-level function to |
| 80 |
application-level execution (``interp2app``) or allow |
| 81 |
transparent invocation of application-level helpers |
| 82 |
(``app2interp``) at interpreter-level. |
| 83 |
|
| 84 |
Another task of the bytecode interpreter is to care for exposing its |
| 85 |
basic code, frame, module and function objects to application-level |
| 86 |
code. Such runtime introspection and modification abilities are |
| 87 |
implemented via `interpreter descriptors`_ (also see Raymond Hettingers |
| 88 |
`how-to guide for descriptors`_ in Python, PyPy uses this model extensively). |
| 89 |
|
| 90 |
A significant complexity lies in `function argument parsing`_. Python as a |
| 91 |
language offers flexible ways of providing and receiving arguments |
| 92 |
for a particular function invocation. Not only does it take special care |
| 93 |
to get this right, it also presents difficulties for the :ref:`annotation |
| 94 |
pass <rpython:annotator>` which performs a whole-program analysis on the |
| 95 |
bytecode interpreter, argument parsing and gatewaying code |
| 96 |
in order to infer the types of all values flowing across function |
| 97 |
calls. |
| 98 |
|
| 99 |
It is for this reason that PyPy resorts to generate |
| 100 |
specialized frame classes and functions at :ref:`initialization |
| 101 |
time <rpython:initialization-time>` in order to let the annotator only see rather static |
| 102 |
program flows with homogeneous name-value assignments on |
| 103 |
function invocations. |
| 104 |
|
| 105 |
.. _how-to guide for descriptors: https://docs.python.org/3/howto/descriptor.html |
| 106 |
|
| 107 |
|
| 108 |
Bytecode Interpreter Implementation Classes |
| 109 |
------------------------------------------- |
| 110 |
|
| 111 |
.. _Frame class: |
| 112 |
.. _Frame: |
| 113 |
|
| 114 |
Frame classes |
| 115 |
~~~~~~~~~~~~~ |
| 116 |
|
| 117 |
The concept of Frames is pervasive in executing programs and |
| 118 |
on virtual machines in particular. They are sometimes called |
| 119 |
*execution frame* because they hold crucial information |
| 120 |
regarding the execution of a Code_ object, which in turn is |
| 121 |
often directly related to a Python `Function`_. Frame |
| 122 |
instances hold the following state: |
| 123 |
|
| 124 |
- the local scope holding name-value bindings, usually implemented |
| 125 |
via a "fast scope" which is an array of wrapped objects |
| 126 |
|
| 127 |
- a blockstack containing (nested) information regarding the |
| 128 |
control flow of a function (such as ``while`` and ``try`` constructs) |
| 129 |
|
| 130 |
- a value stack where bytecode interpretation pulls object |
| 131 |
from and puts results on. (``locals_stack_w`` is actually a single |
| 132 |
list containing both the local scope and the value stack.) |
| 133 |
|
| 134 |
- a reference to the *globals* dictionary, containing |
| 135 |
module-level name-value bindings |
| 136 |
|
| 137 |
- debugging information from which a current line-number and |
| 138 |
file location can be constructed for tracebacks |
| 139 |
|
| 140 |
Moreover the Frame class itself has a number of methods which implement |
| 141 |
the actual bytecodes found in a code object. The methods of the ``PyFrame`` |
| 142 |
class are added in various files: |
| 143 |
|
| 144 |
- the class ``PyFrame`` is defined in :source:`pypy/interpreter/pyframe.py`. |
| 145 |
|
| 146 |
- the file :source:`pypy/interpreter/pyopcode.py` add support for all Python opcode. |
| 147 |
|
| 148 |
.. _Code: |
| 149 |
|
| 150 |
Code Class |
| 151 |
~~~~~~~~~~ |
| 152 |
|
| 153 |
PyPy's code objects contain the same information found in CPython's code objects. |
| 154 |
They differ from Function_ objects in that they are only immutable representations |
| 155 |
of source code and don't contain execution state or references to the execution |
| 156 |
environment found in `Frames`. Frames and Functions have references |
| 157 |
to a code object. Here is a list of Code attributes: |
| 158 |
|
| 159 |
* ``co_flags`` flags if this code object has nested scopes/generators/etc. |
| 160 |
* ``co_stacksize`` the maximum depth the stack can reach while executing the code |
| 161 |
* ``co_code`` the actual bytecode string |
| 162 |
|
| 163 |
* ``co_argcount`` number of arguments this code object expects |
| 164 |
* ``co_varnames`` a tuple of all argument names pass to this code object |
| 165 |
* ``co_nlocals`` number of local variables |
| 166 |
* ``co_names`` a tuple of all names used in the code object |
| 167 |
* ``co_consts`` a tuple of prebuilt constant objects ("literals") used in the code object |
| 168 |
* ``co_cellvars`` a tuple of Cells containing values for access from nested scopes |
| 169 |
* ``co_freevars`` a tuple of Cell names from "above" scopes |
| 170 |
|
| 171 |
* ``co_filename`` source file this code object was compiled from |
| 172 |
* ``co_firstlineno`` the first linenumber of the code object in its source file |
| 173 |
* ``co_name`` name of the code object (often the function name) |
| 174 |
* ``co_lnotab`` a helper table to compute the line-numbers corresponding to bytecodes |
| 175 |
|
| 176 |
|
| 177 |
.. _Function: |
| 178 |
|
| 179 |
Function and Method classes |
| 180 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 181 |
|
| 182 |
The PyPy ``Function`` class (in :source:`pypy/interpreter/function.py`) |
| 183 |
represents a Python function. A ``Function`` carries the following |
| 184 |
main attributes: |
| 185 |
|
| 186 |
* ``func_doc`` the docstring (or None) |
| 187 |
* ``func_name`` the name of the function |
| 188 |
* ``func_code`` the Code_ object representing the function source code |
| 189 |
* ``func_defaults`` default values for the function (built at function definition time) |
| 190 |
* ``func_dict`` dictionary for additional (user-defined) function attributes |
| 191 |
* ``func_globals`` reference to the globals dictionary |
| 192 |
* ``func_closure`` a tuple of Cell references |
| 193 |
|
| 194 |
``Functions`` classes also provide a ``__get__`` descriptor which creates a Method |
| 195 |
object holding a binding to an instance or a class. Finally, ``Functions`` |
| 196 |
and ``Methods`` both offer a ``call_args()`` method which executes |
| 197 |
the function given an `Arguments`_ class instance. |
| 198 |
|
| 199 |
|
| 200 |
.. _Arguments: |
| 201 |
|
| 202 |
.. _function argument parsing: |
| 203 |
|
| 204 |
Arguments Class |
| 205 |
~~~~~~~~~~~~~~~ |
| 206 |
|
| 207 |
The Argument class (in :source:`pypy/interpreter/argument.py`) is |
| 208 |
responsible for parsing arguments passed to functions. |
| 209 |
Python has rather complex argument-passing concepts: |
| 210 |
|
| 211 |
- positional arguments |
| 212 |
|
| 213 |
- keyword arguments specified by name |
| 214 |
|
| 215 |
- default values for positional arguments, defined at function |
| 216 |
definition time |
| 217 |
|
| 218 |
- "star args" allowing a function to accept remaining |
| 219 |
positional arguments |
| 220 |
|
| 221 |
- "star keyword args" allow a function to accept additional |
| 222 |
arbitrary name-value bindings |
| 223 |
|
| 224 |
Moreover, a Function_ object can get bound to a class or instance |
| 225 |
in which case the first argument to the underlying function becomes |
| 226 |
the bound object. The ``Arguments`` provides means to allow all |
| 227 |
this argument parsing and also cares for error reporting. |
| 228 |
|
| 229 |
|
| 230 |
.. _Module: |
| 231 |
|
| 232 |
Module Class |
| 233 |
~~~~~~~~~~~~ |
| 234 |
|
| 235 |
A ``Module`` instance represents execution state usually constructed |
| 236 |
from executing the module's source file. In addition to such a module's |
| 237 |
global ``__dict__`` dictionary it has the following application level |
| 238 |
attributes: |
| 239 |
|
| 240 |
* ``__doc__`` the docstring of the module |
| 241 |
* ``__file__`` the source filename from which this module was instantiated |
| 242 |
* ``__path__`` state used for relative imports |
| 243 |
|
| 244 |
Apart from the basic Module used for importing |
| 245 |
application-level files there is a more refined |
| 246 |
``MixedModule`` class (see :source:`pypy/interpreter/mixedmodule.py`) |
| 247 |
which allows to define name-value bindings both at application |
| 248 |
level and at interpreter level. See the ``__builtin__`` |
| 249 |
module's :source:`pypy/module/__builtin__/__init__.py` file for an |
| 250 |
example and the higher level :ref:`chapter on Modules in the coding |
| 251 |
guide <modules>`. |
| 252 |
|
| 253 |
|
| 254 |
Gateway classes |
| 255 |
~~~~~~~~~~~~~~~ |
| 256 |
|
| 257 |
A unique PyPy property is the ability to easily cross the barrier |
| 258 |
between interpreted and machine-level code (often referred to as |
| 259 |
the difference between :ref:`interpreter-level and application-level <interpreter-level>`). |
| 260 |
Be aware that the according code (in :source:`pypy/interpreter/gateway.py`) |
| 261 |
for crossing the barrier in both directions is somewhat |
| 262 |
involved, mostly due to the fact that the type-inferring |
| 263 |
annotator needs to keep track of the types of objects flowing |
| 264 |
across those barriers. |
| 265 |
|
| 266 |
|
| 267 |
Making interpreter-level functions available at application-level |
| 268 |
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| 269 |
|
| 270 |
In order to make an interpreter-level function available at |
| 271 |
application level, one invokes ``pypy.interpreter.gateway.interp2app(func)``. |
| 272 |
Such a function usually takes a ``space`` argument and any number |
| 273 |
of positional arguments. Additionally, such functions can define |
| 274 |
an ``unwrap_spec`` telling the ``interp2app`` logic how |
| 275 |
application-level provided arguments should be unwrapped |
| 276 |
before the actual interpreter-level function is invoked. |
| 277 |
For example, `interpreter descriptors`_ such as the ``Module.__new__`` |
| 278 |
method for allocating and constructing a Module instance are |
| 279 |
defined with such code:: |
| 280 |
|
| 281 |
Module.typedef = TypeDef("module", |
| 282 |
__new__ = interp2app(Module.descr_module__new__.im_func, |
| 283 |
unwrap_spec=[ObjSpace, W_Root, Arguments]), |
| 284 |
__init__ = interp2app(Module.descr_module__init__), |
| 285 |
# module dictionaries are readonly attributes |
| 286 |
__dict__ = GetSetProperty(descr_get_dict, cls=Module), |
| 287 |
__doc__ = 'module(name[, doc])\n\nCreate a module object...' |
| 288 |
) |
| 289 |
|
| 290 |
The actual ``Module.descr_module__new__`` interpreter-level method |
| 291 |
referenced from the ``__new__`` keyword argument above is defined |
| 292 |
like this:: |
| 293 |
|
| 294 |
def descr_module__new__(space, w_subtype, __args__): |
| 295 |
module = space.allocate_instance(Module, w_subtype) |
| 296 |
Module.__init__(module, space, None) |
| 297 |
return space.wrap(module) |
| 298 |
|
| 299 |
Summarizing, the ``interp2app`` mechanism takes care to route |
| 300 |
an application level access or call to an internal interpreter-level |
| 301 |
object appropriately to the descriptor, providing enough precision |
| 302 |
and hints to keep the type-inferring annotator happy. |
| 303 |
|
| 304 |
|
| 305 |
Calling into application level code from interpreter-level |
| 306 |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| 307 |
|
| 308 |
Application level code is :ref:`often preferable <app-preferable>`. Therefore, |
| 309 |
we often like to invoke application level code from interpreter-level. |
| 310 |
This is done via the Gateway's ``app2interp`` mechanism |
| 311 |
which we usually invoke at definition time in a module. |
| 312 |
It generates a hook which looks like an interpreter-level |
| 313 |
function accepting a space and an arbitrary number of arguments. |
| 314 |
When calling a function at interpreter-level the caller side |
| 315 |
does usually not need to be aware if its invoked function |
| 316 |
is run through the PyPy interpreter or if it will directly |
| 317 |
execute on the machine (after translation). |
| 318 |
|
| 319 |
Here is an example showing how we implement the Metaclass |
| 320 |
finding algorithm of the Python language in PyPy:: |
| 321 |
|
| 322 |
app = gateway.applevel(r''' |
| 323 |
def find_metaclass(bases, namespace, globals, builtin): |
| 324 |
if '__metaclass__' in namespace: |
| 325 |
return namespace['__metaclass__'] |
| 326 |
elif len(bases) > 0: |
| 327 |
base = bases[0] |
| 328 |
if hasattr(base, '__class__'): |
| 329 |
return base.__class__ |
| 330 |
else: |
| 331 |
return type(base) |
| 332 |
elif '__metaclass__' in globals: |
| 333 |
return globals['__metaclass__'] |
| 334 |
else: |
| 335 |
try: |
| 336 |
return builtin.__metaclass__ |
| 337 |
except AttributeError: |
| 338 |
return type |
| 339 |
''', filename=__file__) |
| 340 |
|
| 341 |
find_metaclass = app.interphook('find_metaclass') |
| 342 |
|
| 343 |
The ``find_metaclass`` interpreter-level hook is invoked |
| 344 |
with five arguments from the ``BUILD_CLASS`` opcode implementation |
| 345 |
in :source:`pypy/interpreter/pyopcode.py`:: |
| 346 |
|
| 347 |
def BUILD_CLASS(f): |
| 348 |
w_methodsdict = f.valuestack.pop() |
| 349 |
w_bases = f.valuestack.pop() |
| 350 |
w_name = f.valuestack.pop() |
| 351 |
w_metaclass = find_metaclass(f.space, w_bases, |
| 352 |
w_methodsdict, f.w_globals, |
| 353 |
f.space.wrap(f.builtin)) |
| 354 |
w_newclass = f.space.call_function(w_metaclass, w_name, |
| 355 |
w_bases, w_methodsdict) |
| 356 |
f.valuestack.push(w_newclass) |
| 357 |
|
| 358 |
Note that at a later point we can rewrite the ``find_metaclass`` |
| 359 |
implementation at interpreter-level and we would not have |
| 360 |
to modify the calling side at all. |
| 361 |
|
| 362 |
|
| 363 |
.. _interpreter descriptors: |
| 364 |
|
| 365 |
Introspection and Descriptors |
| 366 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 367 |
|
| 368 |
Python traditionally has a very far-reaching introspection model |
| 369 |
for bytecode interpreter related objects. In PyPy and in CPython read |
| 370 |
and write accesses to such objects are routed to descriptors. |
| 371 |
Of course, in CPython those are implemented in ``C`` while in |
| 372 |
PyPy they are implemented in interpreter-level Python code. |
| 373 |
|
| 374 |
All instances of a Function_, Code_, Frame_ or Module_ classes |
| 375 |
are also ``W_Root`` instances which means they can be represented |
| 376 |
at application level. These days, a PyPy object space needs to |
| 377 |
work with a basic descriptor lookup when it encounters |
| 378 |
accesses to an interpreter-level object: an object space asks |
| 379 |
a wrapped object for its type via a ``getclass`` method and then |
| 380 |
calls the type's ``lookup(name)`` function in order to receive a descriptor |
| 381 |
function. Most of PyPy's internal object descriptors are defined at the |
| 382 |
end of :source:`pypy/interpreter/typedef.py`. You can use these definitions |
| 383 |
as a reference for the exact attributes of interpreter classes visible |
| 384 |
at application level. |