Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- openflamingo/lib/python3.10/site-packages/mypyc/doc/MakefileAdded+20
- openflamingo/lib/python3.10/site-packages/mypyc/doc/__pycache__/conf.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/mypyc/doc/bool_operations.rstAdded+27
- openflamingo/lib/python3.10/site-packages/mypyc/doc/bytes_operations.rstAdded+46
- openflamingo/lib/python3.10/site-packages/mypyc/doc/compilation_units.rstAdded+20
- openflamingo/lib/python3.10/site-packages/mypyc/doc/conf.pyAdded+59
- openflamingo/lib/python3.10/site-packages/mypyc/doc/cpython-timings.mdAdded+25
- openflamingo/lib/python3.10/site-packages/mypyc/doc/dev-intro.mdAdded+552
- openflamingo/lib/python3.10/site-packages/mypyc/doc/dict_operations.rstAdded+59
- openflamingo/lib/python3.10/site-packages/mypyc/doc/differences_from_python.rstAdded+332
- openflamingo/lib/python3.10/site-packages/mypyc/doc/float_operations.rstAdded+50
- openflamingo/lib/python3.10/site-packages/mypyc/doc/future.mdAdded+42
- openflamingo/lib/python3.10/site-packages/mypyc/doc/getting_started.rstAdded+240
- openflamingo/lib/python3.10/site-packages/mypyc/doc/index.rstAdded+62
- openflamingo/lib/python3.10/site-packages/mypyc/doc/int_operations.rstAdded+162
- openflamingo/lib/python3.10/site-packages/mypyc/doc/introduction.rstAdded+150
- openflamingo/lib/python3.10/site-packages/mypyc/doc/list_operations.rstAdded+65
- openflamingo/lib/python3.10/site-packages/mypyc/doc/native_classes.rstAdded+206
- openflamingo/lib/python3.10/site-packages/mypyc/doc/native_operations.rstAdded+55
- openflamingo/lib/python3.10/site-packages/mypyc/doc/performance_tips_and_tricks.rstAdded+244
- openflamingo/lib/python3.10/site-packages/mypyc/doc/set_operations.rstAdded+47
- openflamingo/lib/python3.10/site-packages/mypyc/doc/str_operations.rstAdded+59
- openflamingo/lib/python3.10/site-packages/mypyc/doc/using_type_annotations.rstAdded+398
- openflamingo/lib/python3.10/site-packages/mypyc/ir/__pycache__/func_ir.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/mypyc/ir/class_ir.pyAdded+503
- openflamingo/lib/python3.10/site-packages/mypyc/ir/pprint.pyAdded+516
- openflamingo/lib/python3.10/site-packages/mypyc/ir/rtypes.pyAdded+1038
- openflamingo/lib/python3.10/site-packages/mypyc/irbuild/__init__.pyAdded
- openflamingo/lib/python3.10/site-packages/mypyc/irbuild/builder.pyAdded+1457
- openflamingo/lib/python3.10/site-packages/mypyc/irbuild/ll_builder.pyAdded
- openflamingo/lib/python3.10/site-packages/mypyc/irbuild/mapper.cpython-310-x86_64-linux-gnu.soAdded
- openflamingo/lib/python3.10/site-packages/mypyc/irbuild/prepare.cpython-310-x86_64-linux-gnu.soAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/__init__.cpython-310-x86_64-linux-gnu.soAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/__init__.pyAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/__init__.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/dict_ops.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/exc_ops.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/float_ops.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/generic_ops.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/int_ops.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/list_ops.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/misc_ops.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/set_ops.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/str_ops.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/tuple_ops.cpython-310.pycAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/bytes_ops.pyAdded+109
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/dict_ops.pyAdded+325
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/exc_ops.cpython-310-x86_64-linux-gnu.soAdded
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/exc_ops.pyAdded+101
- openflamingo/lib/python3.10/site-packages/mypyc/primitives/int_ops.cpython-310-x86_64-linux-gnu.soAdded
1234567891011121314151617181920# Minimal makefile for Sphinx documentation#
# You can set these variables from the command line, and also# from the environment for the first two.SPHINXOPTS ?=SPHINXBUILD ?= sphinx-buildSOURCEDIR = .BUILDDIR = _build
# Put it first so that "make" without argument is like "make help".help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).%: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)123456789101112131415161718192021222324252627.. _bool-ops:
Native boolean operations=========================
Operations on ``bool`` values that are listed here have fast,optimized implementations.
Construction------------
* ``True``* ``False``* ``bool(obj)``
Operators---------
* ``b1 and b2``* ``b1 or b2``* ``not b``
Functions---------
* ``any(expr for ... in ...)``* ``all(expr for ... in ...)``12345678910111213141516171819202122232425262728293031323334353637383940414243444546.. _bytes-ops:
Native bytes operations========================
These ``bytes`` operations have fast, optimized implementations. Otherbytes operations use generic implementations that are often slower.
Construction------------
* Bytes literal* ``bytes(x: list)``
Operators---------
* Concatenation (``b1 + b2``)* Indexing (``b[n]``)* Slicing (``b[n:m]``, ``b[n:]``, ``b[:m]``)* Comparisons (``==``, ``!=``)
.. _bytes-methods:
Methods-------
* ``b.decode()``* ``b.decode(encoding: str)``* ``b.decode(encoding: str, errors: str)``* ``b.join(x: Iterable)``
.. note::
:ref:`str.encode() <str-methods>` is also optimized.
Formatting----------
A subset of % formatting operations are optimized (``b"..." % (...)``).
Functions---------
* ``len(b: bytes)``* ``ord(b: bytes)``1234567891011121314151617181920.. _compilation-units:
Compilation units=================
When you run mypyc to compile a set of modules, these modules form a*compilation unit*. Mypyc will use early binding for references withinthe compilation unit.
If you run mypyc multiple times to compile multiple sets of modules,each invocation will result in a new compilation unit. Referencesbetween separate compilation units will fall back to late binding,i.e. looking up names using Python namespace dictionaries. Also, allcalls will use the slower Python calling convention, where argumentsand the return value will be boxed (and potentially unboxed again inthe called function).
For maximal performance, minimize interactions across compilationunits. The simplest way to achieve this is to compile your entireprogram as a single compilation unit.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859# Configuration file for the Sphinx documentation builder.## This file only contains a selection of the most common options. For a full# list see the documentation:# https://www.sphinx-doc.org/en/master/usage/configuration.html
from __future__ import annotations
import osimport sys
# If extensions (or modules to document with autodoc) are in another directory,# add these directories to sys.path here. If the directory is relative to the# documentation root, use os.path.abspath to make it absolute, like shown here.sys.path.insert(0, os.path.abspath("../.."))
from mypy.version import __version__ as mypy_version
# -- Project information -----------------------------------------------------
project = "mypyc"copyright = "2020-2022, mypyc team"author = "mypyc team"
# The version info for the project you're documenting, acts as replacement for# |version| and |release|, also used in various other places throughout the# built documents.## The short X.Y version.version = mypy_version.split("-")[0]# The full version, including alpha/beta/rc tags.release = mypy_version
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom# ones.extensions: list[str] = []
# Add any paths that contain templates here, relative to this directory.templates_path = ["_templates"]
# List of patterns, relative to source directory, that match files and# directories to ignore when looking for source files.# This pattern also affects html_static_path and html_extra_path.exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for# a list of builtin themes.html_theme = "furo"
# Add any paths that contain custom static files (such as style sheets) here,# relative to this directory. They are copied after the builtin static files,# so a file named "default.css" will overwrite the builtin "default.css".html_static_path = ["_static"]12345678910111213141516171819202122232425# Timings of CPython Operations
Here are some *very rough* approximate timings of CPython interpreteroperations:
* `f(1)` (empty function body): 70-90ns* `f(n=1)` (empty function body): 90-110ns* `o.x`: 30-40ns* `o.f(1)` (empty method body): 80-160ns* `Cls(1)` (initialize attribute in `__init__`): 290-330ns* `x + y` (integers): 20-35ns* `a[i]` (list) : 20-40ns* `[i]` (also dealloc): 35-55ns* `a.append(i)` (list, average over 5 appends): 70ns* `d[s]` (dict, shared str key): 20ns* `d[s] = i` (dict, shared str key): 40ns* `isinstance(x, A)`: 100ns* `(x, y)`: 20-35ns* `x, y = t` (tuple expand): 10ns
Note that these results are very imprecise due to many factors, butthese should give a rough idea of the relative costs of variousoperations.
Details: CPython 3.6.2, Macbook Pro 15" (Mid 2015), macOS Sierra123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552# Introduction for Mypyc Contributors
This is a short introduction aimed at anybody who is interested incontributing to mypyc, or anybody who is curious to understand howmypyc works internally.
## Key Differences from Python
Code compiled using mypyc is often much faster than CPython since itdoes these things differently:
* Mypyc generates C that is compiled to native code, instead of compiling to interpreted byte code, which CPython uses. Interpreted byte code always has some interpreter overhead, which slows things down.
* Mypyc doesn't let you arbitrarily monkey patch classes and functions in compiled modules. This allows *early binding* -- mypyc statically binds calls to compiled functions, instead of going through a namespace dictionary. Mypyc can also call methods of compiled classes using vtables, which are more efficient than dictionary lookups used by CPython.
* Mypyc compiles classes to C extension classes, which are generally more efficient than normal Python classes. They use an efficient, fixed memory representation (essentially a C struct). This lets us use direct memory access instead of (typically) two hash table lookups to access an attribute.
* As a result of early binding, compiled code can use C calls to call compiled functions. Keyword arguments can be translated to positional arguments during compilation. Thus most calls to native functions and methods directly map to simple C calls. CPython calls are quite expensive, since mapping of keyword arguments, `*args`, and so on has to mostly happen at runtime.
* Compiled code has runtime type checks to ensure that runtimes types match the declared static types. Compiled code can thus make assumptions about the types of expressions, resulting in both faster and smaller code, since many runtime type checks performed by the CPython interpreter can be omitted.
* Compiled code can often use unboxed (not heap allocated) representations for integers, booleans and tuples.
## Supported Python Features
Mypyc supports a large subset of Python. Note that if you try tocompile something that is not supported, you may not always get a verygood error message.
Here are some major things that aren't yet supported in compiled code:
* Many dunder methods (only some work, such as `__init__` and `__eq__`)* Monkey patching compiled functions or classes* General multiple inheritance (a limited form is supported)* Named tuple defined using the class-based syntax* Defining protocols
We are generally happy to accept contributions that implement new Pythonfeatures.
## Development Environment
First you should set up the mypy development environment as described inthe [mypy docs](https://github.com/python/mypy/blob/master/README.md).macOS, Linux and Windows are supported.
## Compiling and Running Programs
When working on a mypyc feature or a fix, you'll often need to runcompiled code. For example, you may want to do interactive testing orto run benchmarks. This is also handy if you want to inspect thegenerated C code (see Inspecting Generated C).
Run `mypyc` to compile a module to a C extension using yourdevelopment version of mypyc:
```$ mypyc program.py```
This will generate a C extension for `program` in the current workingdirectory. For example, on a Linux system the generated file may becalled `program.cpython-37m-x86_64-linux-gnu.so`.
Since C extensions can't be run as programs, use `python3 -c` to runthe compiled module as a program:
```$ python3 -c "import program"```
Note that `__name__` in `program.py` will now be `program`, not`__main__`!
You can manually delete the C extension to get back to an interpretedversion (this example works on Linux):
```$ rm program.*.so```
Another option is to invoke mypyc through tests (see Testing below).
## High-level Overview of Mypyc
Mypyc compiles a Python module (or a set of modules) to C, andcompiles the generated C to a Python C extension module (ormodules). You can compile only a subset of your program to C --compiled and interpreted code can freely and transparentlyinteract. You can also freely use any Python libraries (including Cextensions) in compiled code.
Mypyc will only make compiled code faster. To see a significantspeedup, you must make sure that most of the time is spent in compiledcode -- and not in libraries, for example.
Mypyc has these passes:
* Type check the code using mypy and infer types for variables and expressions. This produces a mypy AST (defined in `mypy.nodes`) and a type map that describes the inferred types (`mypy.types.Type`) of all expressions (as PEP 484 types).
* Translate the mypy AST into a mypyc-specific intermediate representation (IR). * The IR is defined in `mypyc.ir` (see below for an explanation of the IR). * Various primitive operations used in the IR are defined in `mypyc.primitives`. * The translation to IR happens in `mypyc.irbuild`. The top-level logic is in `mypyc.irbuild.main`.
* Insert checks for uses of potentially uninitialized variables (`mypyc.transform.uninit`).
* Insert exception handling (`mypyc.transform.exceptions`).
* Insert explicit reference count inc/dec opcodes (`mypyc.transform.refcount`).
* Translate the IR into C (`mypyc.codegen`).
* Compile the generated C code using a C compiler (`mypyc.build`).
## Useful Background Information
Beyond the mypy documentation, here are some things that are helpful toknow for mypyc contributors:
* Experience with C ([The C Programming Language](https://en.wikipedia.org/wiki/The_C_Programming_Language) is a classic book about C)* Basic familiarity with the Python C API (see [Python C API documentation](https://docs.python.org/3/c-api/intro.html)). [Extending and Embedding the Python Interpreter](https://docs.python.org/3/extending/index.html) is a good tutorial for beginners.* Basics of compilers (see the [mypy wiki](https://github.com/python/mypy/wiki/Learning-Resources) for some ideas)
## Mypyc Intermediate Representation (IR)
The mypyc IR is defined in `mypyc.ir`. It covers several key conceptsthat are essential to understand by all mypyc contributors:
* `mypyc.ir.ops.Op` is an Abstract Base Class for all IR operations. These are low-level and generally map to simple fragments of C each. Mypy expressions are translated to linear sequences of these ops.
* `mypyc.ir.ops.BasicBlock` is a container of a sequence of ops with a branch/goto/return at the end, and no branch/goto/return ops in the middle. Each function is compiled to a bunch of basic blocks.
* `mypyc.ir.rtypes.RType` and its subclasses are the types used for everything in the IR. These are lower-level and simpler than mypy or PEP 484 types. For example, there are no general-purpose generic types types here. Each `List[X]` type (for any `X`) is represented by a single `list` type, for example.
* Primitive types are special RTypes of which mypyc has some special understanding, and there are typically some specialized ops. Examples include `int` (referred to as `int_rprimitive` in the code) and `list` (`list_rprimitive`). Python types for which there is no specific RType type will be represented by the catch-all `object_rprimitive` type.
* Instances of compiled classes are generally represented using the `RInstance` type. Classes are compiled to C extension classes and contain vtables for fast method calls and fast attribute access.
* IR representations of functions and classes live in `mypyc.ir.func_ir` and `mypyc.ir.class_ir`, respectively.
Look at the docstrings and comments in `mypyc.ir` for additionalinformation. See the test cases in`mypyc/test-data/irbuild-basic.test` for examples of what the IR lookslike in a pretty-printed form.
## Testing overview
Most mypyc test cases are defined in the same format (`.test`) as usedfor test cases for mypy. Look at mypy developer documentation for ageneral overview of how things work. Test cases live under`mypyc/test-data/`, and you can run all mypyc tests via `pytest-q mypyc`. If you don't make changes to code under `mypy/`, it's notimportant to regularly run mypy tests during development.
You can use `python runtests.py mypyc-fast` to run a subset of mypyctests that covers most functionality but runs significantly quickerthan the entire test suite.
When you create a PR, we have Continuous Integration jobs set up thatcompile mypy using mypyc and run the mypy test suite using thecompiled mypy. This will sometimes catch additional issues not caughtby the mypyc test suite. It's okay to not do this in your localdevelopment environment.
We discuss writing tests in more detail later in this document.
## Inspecting Generated IR
It's often useful to look at the generated IR when debugging issues orwhen trying to understand how mypyc compiles some code. When youcompile some module by running `mypyc`, mypyc will write thepretty-printed IR into `build/ops.txt`. This is the final IR thatincludes the output from exception and reference count handlinginsertion passes.
We also have tests that verify the generate IR(`mypyc/test-data/irbuild-*.text`).
## Type-checking Mypyc
`./runtests.py self` type checks mypy and mypyc. This is pretty slow,however, since it's using an uncompiled mypy.
Installing a released version of mypy using `pip` (which is compiled)and using `dmypy` (mypy daemon) is a much, much faster way to typecheck mypyc during development.
## Value Representation
Mypyc uses a tagged pointer representation for values of type `int`(`CPyTagged`), `char` for booleans, and C structs for tuples. For mostother objects mypyc uses the CPython `PyObject *`.
Python integers that fit in 31/63 bits (depending on whether we are ona 32-bit or 64-bit platform) are represented as C integers(`CPyTagged`) shifted left by 1. Integers that don't fit in thisrepresentation are represented as pointers to a `PyObject *` (this isalways a Python `int` object) with the least significant bitset. Tagged integer operations are defined in `mypyc/lib-rt/int_ops.c`and `mypyc/lib-rt/CPy.h`.
There are also low-level integer types, such as `int32` (see`mypyc.ir.rtypes`), that don't use the tagged representation. Thesetypes are not exposed to users, but they are used in generated code.
## Overview of Generated C
Mypyc compiles a function into two functions, a native function anda wrapper function:
* The native function takes a fixed number of C arguments with the correct C types. It assumes that all argument have correct types.
* The wrapper function conforms to the Python C API calling convention and takes an arbitrary set of arguments. It processes the arguments, checks their types, unboxes values with special representations and calls the native function. The return value from the native function is translated back to a Python object ("boxing").
Calls to other compiled functions don't go through the Python modulenamespace but directly call the target native C function. This makescalls very fast compared to CPython.
The generated code does runtime checking so that it can assume thatvalues always have the declared types. Whenever accessing CPythonvalues which might have unexpected types we need to insert a runtimetype check operation. For example, when getting a list item we need toinsert a runtime type check (an unbox or a cast operation), sincePython lists can contain arbitrary objects.
The generated code uses various helpers defined in`mypyc/lib-rt/CPy.h`. The implementations are in various `.c` filesunder `mypyc/lib-rt`.
## Inspecting Generated C
It's often useful to inspect the C code genenerate by mypyc to debugissues. Mypyc stores the generated C code as `build/__native.c`.Compiled native functions have the prefix `CPyDef_`, while wrapperfunctions used for calling functions from interpreted Python code havethe `CPyPy_` prefix.
## Other Important Limitations
All of these limitations will likely be fixed in the future:
* We don't detect stack overflows.
* We don't handle Ctrl-C in compiled code.
## Hints for Implementing Typical Mypyc Features
This section gives an overview of where to look for andwhat to do to implement specific kinds of mypyc features.
### Testing
Our bread-and-butter testing strategy is compiling code with mypyc andrunning it. There are downsides to this (kind of slow, tests a hugenumber of components at once, insensitive to the particular details ofthe IR), but there really is no substitute for running code. You canalso write tests that test the generated IR, however.
### Tests that compile and run code
Test cases that compile and run code are located in`mypyc/test-data/run*.test` and the test runner is in`mypyc.test.test_run`. The code to compile comes after `[casetest<name>]`. The code gets saved into the file `native.py`, and itgets compiled into the module `native`.
Each test case uses a non-compiled Python driver that imports the`native` module and typically calls some compiled functions. Sometests also perform assertions and print messages in the driver.
If you don't provide a driver, a default driver is used. The defaultdriver just calls each module-level function that is prefixed with`test_` and reports any uncaught exceptions as failures. (Failure tobuild or a segfault also count as failures.) `testStringOps` in`mypyc/test-data/run-strings.test` is an example of a test that usesthe default driver.
You should usually use the default driver (don't include`driver.py`). It's the simplest way to write most tests.
Here's an example test case that uses the default driver:
```[case testConcatenateLists]def test_concat_lists() -> None: assert [1, 2] + [5, 6] == [1, 2, 5, 6]
def test_concat_empty_lists() -> None: assert [] + [] == []```
There is one test case, `testConcatenateLists`. It has two sub-cases,`test_concat_lists` and `test_concat_empty_lists`. Note that you canuse the pytest -k argument to only run `testConcetanateLists`, but youcan't filter tests at the sub-case level.
It's recommended to have multiple sub-cases per test case, since eachtest case has significant fixed overhead. Each test case is run in afresh Python subprocess.
Many of the existing test cases provide a custom driver by having`[file driver.py]`, followed by the driver implementation. Here thedriver is not compiled, which is useful if you want to testinteractions between compiled and non-compiled code. However, many ofthe tests don't have a good reason to use a custom driver -- when theywere written, the default driver wasn't available.
Test cases can also have a `[out]` section, which specifies theexpected contents of stdout the test case should produce. New testcases should prefer assert statements to `[out]` sections.
### IR tests
If the specifics of the generated IR of a change is important(because, for example, you want to make sure a particular optimizationis triggering), you should add a `mypyc.irbuild` test as well. Testcases are located in `mypyc/test-data/irbuild-*.test` and the testdriver is in `mypyc.test.test_irbuild`. IR build tests do a directcomparison of the IR output, so try to make the test as targeted aspossible so as to capture only the important details. (Many of ourexisting IR build tests do not follow this advice, unfortunately!)
If you pass the `--update-data` flag to pytest, it will automaticallyupdate the expected output of any tests to match the actualoutput. This is very useful for changing or creating IR build tests,but make sure to carefully inspect the diff!
You may also need to add some definitions to the stubs used forbuiltins during tests (`mypyc/test-data/fixtures/ir.py`). We don't usefull typeshed stubs to run tests since they would seriously slow downtests.
### Benchmarking
Many mypyc improvements attempt to make some operations faster. Forany such change, you should run some measurements to verify thatthere actually is a measurable performance impact.
A typical benchmark would initialize some data to be operated on, andthen measure time spent in some function. In particular, you shouldnot measure time needed to run the entire benchmark program, as thiswould include Python startup overhead and other things that aren'trelevant. In general, for microbenchmarks, you want to do as little aspossible in the timed portion. So ideally you'll just have some loopsand the code under test. Be ready to provide your benchmark in codereview so that mypyc developers can check that the benchmark is fine(writing a good benchmark is non-trivial).
You should run a benchmark at least five times, in both original andchanged versions, ignore outliers, and report the averageruntime. Actual performance of a typical desktop or laptop computer isquite variable, due to dynamic CPU clock frequency changes, backgroundprocesses, etc. If you observe a high variance in timings, you'll needto run the benchmark more times. Also try closing most applications,including web browsers.
Interleave original and changed runs. Don't run 10 runs with variant Afollowed by 10 runs with variant B, but run an A run, a B run, an Arun, etc. Otherwise you risk that the CPU frequency will be differentbetween variants. You can also try adding a delay of 5 to 20s betweenruns to avoid CPU frequency changes.
Instead of averaging over many measurements, you can try to adjustyour environment to provide more stable measurements. However, thiscan be hard to do with some hardware, including many laptops. VictorStinner has written a series of blog posts about making measurementsstable:
* https://vstinner.github.io/journey-to-stable-benchmark-system.html* https://vstinner.github.io/journey-to-stable-benchmark-average.html
### Adding C Helpers
If you add an operation that compiles into a lot of C code, you mayalso want to add a C helper function for the operation to make thegenerated code smaller. Here is how to do this:
* Declare the operation in `mypyc/lib-rt/CPy.h`. We avoid macros, and we generally avoid inline functions to make it easier to target additional backends in the future.
* Consider adding a unit test for your C helper in `mypyc/lib-rt/test_capi.cc`. We use [Google Test](https://github.com/google/googletest) for writing tests in C++. The framework is included in the repository under the directory `googletest/`. The C unit tests are run as part of the pytest test suite (`test_c_unit_test`).
### Adding a Specialized Primitive Operation
Mypyc speeds up operations on primitive types such as `list` and `int`by having primitive operations specialized for specific types. Theseoperations are declared in `mypyc.primitives` (and`mypyc/lib-rt/CPy.h`). For example, `mypyc.primitives.list_ops`contains primitives that target list objects.
The operation definitions are data driven: you specify the kind ofoperation (such as a call to `builtins.len` or a binary addition) andthe operand types (such as `list_primitive`), and what code should begenerated for the operation. Mypyc does AST matching to find the mostsuitable primitive operation automatically.
Look at the existing primitive definitions and the docstrings in`mypyc.primitives.registry` for examples and more information.
### Adding a New Primitive Type
Some types (typically Python Python built-in types), such as `int` and`list`, are special cased in mypyc to generate optimized operationsspecific to these types. We'll occasionally want to add additionalprimitive types.
Here are some hints about how to add support for a new primitive type(this may be incomplete):
* Decide whether the primitive type has an "unboxed" representation (a representation that is not just `PyObject *`). For most types we'll use a boxed representation, as it's easier to implement and more closely matches Python semantics.
* Create a new instance of `RPrimitive` to support the primitive type and add it to `mypyc.ir.rtypes`. Make sure all the attributes are set correctly and also define `<foo>_rprimitive` and `is_<foo>_rprimitive`.
* Update `mypyc.irbuild.mapper.Mapper.type_to_rtype()`.
* If the type is not unboxed, update `emit_cast` in `mypyc.codegen.emit`.
If the type is unboxed, there are some additional steps:
* Update `emit_box` in `mypyc.codegen.emit`.
* Update `emit_unbox` in `mypyc.codegen.emit`.
* Update `emit_inc_ref` and `emit_dec_ref` in `mypypc.codegen.emit`. If the unboxed representation does not need reference counting, these can be no-ops.
* Update `emit_error_check` in `mypyc.codegen.emit`.
* Update `emit_gc_visit` and `emit_gc_clear` in `mypyc.codegen.emit` if the type has an unboxed representation with pointers.
The above may be enough to allow you to declare variables with thetype, pass values around, perform runtime type checks, and use genericfallback primitive operations to perform method calls, binaryoperations, and so on. You likely also want to add some faster,specialized primitive operations for the type (see Adding aSpecialized Primitive Operation above for how to do this).
Add a test case to `mypyc/test-data/run*.test` to test compilation andrunning compiled code. Ideas for things to test:
* Test using the type as an argument.
* Test using the type as a return value.
* Test passing a value of the type to a function both within compiled code and from regular Python code. Also test this for return values.
* Test using the type as list item type. Test both getting a list item and setting a list item.
### Supporting More Python Syntax
Mypyc supports most Python syntax, but there are still some gaps.
Support for syntactic sugar that doesn't need additional IR operationstypically only requires changes to `mypyc.irbuild`.
Some new syntax also needs new IR primitives to be added to`mypyc.primitives`. See `mypyc.primitives.registry` for documentationabout how to do this.
### Other Hints
* This developer documentation is not aimed to be very complete. Much of our documentation is in comments and docstring in the code. If something is unclear, study the code.
* It can be useful to look through some recent PRs to get an idea of what typical code changes, test cases, etc. look like.
* Feel free to open GitHub issues with questions if you need help when contributing, or ask questions in existing issues. Note that we only support contributors. Mypyc is not (yet) an end-user product. You can also ask questions in our Gitter chat (https://gitter.im/mypyc-dev/community).
## Undocumented Workflows
These workflows would be useful for mypyc contributors. We should addthem to mypyc developer documentation:
* How to inspect the generated IR before some transform passes.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859.. _dict-ops:
Native dict operations======================
These ``dict`` operations have fast, optimized implementations. Otherdictionary operations use generic implementations that are often slower.
Construction------------
Construct dict from keys and values:
* ``{key: value, ...}``
Construct empty dict:
* ``{}``* ``dict()``
Construct dict from another object:
* ``dict(d: dict)``* ``dict(x: Iterable)``
Dict comprehensions:
* ``{...: ... for ... in ...}``* ``{...: ... for ... in ... if ...}``
Operators---------
* ``d[key]``* ``value in d``
Statements----------
* ``d[key] = value``* ``for key in d:``
Methods-------
* ``d.get(key)``* ``d.get(key, default)``* ``d.keys()``* ``d.values()``* ``d.items()``* ``d.copy()``* ``d.clear()``* ``d1.update(d2: dict)``* ``d.update(x: Iterable)``
Functions---------
* ``len(d: dict)``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332.. _differences-from-python:
Differences from Python=======================
Mypyc aims to be sufficiently compatible with Python semantics so thatmigrating code to mypyc often doesn't require major codechanges. There are various differences to enable performance gainsthat you need to be aware of, however.
This section documents notable differences from Python. We discussmany of them also elsewhere, but it's convenient to have them here inone place.
Running compiled modules------------------------
You can't use ``python3 <module>.py`` or ``python3 -m <module>``to run compiled modules. Use ``python3 -c "import <module>"`` instead,or write a wrapper script that imports your module.
As a side effect, you can't rely on checking the ``__name__`` attribute in compiledcode, like this::
if __name__ == "__main__": # Can't be used in compiled code main()
Type errors prevent compilation-------------------------------
You can't compile code that generates mypy type check errors. You cansometimes ignore these with a ``# type: ignore`` comment, but this canresult in bad code being generated, and it's considered dangerous.
.. note::
In the future, mypyc may reject ``# type: ignore`` comments that may be unsafe.
Runtime type checking---------------------
Non-erased types in annotations will be type checked at runtime. For example,consider this function::
def twice(x: int) -> int: return x * 2
If you try to call this function with a ``float`` or ``str`` argument,you'll get a type error on the call site, even if the call site is notbeing type checked::
twice(5) # OK twice(2.2) # TypeError twice("blah") # TypeError
Also, values with *inferred* types will be type checked. For example,consider a call to the stdlib function ``socket.gethostname()`` incompiled code. This function is not compiled (no stdlib modules arecompiled with mypyc), but mypyc uses a *library stub file* to inferthe return type as ``str``. Compiled code calling ``gethostname()``will fail with ``TypeError`` if ``gethostname()`` would return anincompatible value, such as ``None``::
import socket
# Fail if returned value is not a str name = socket.gethostname()
Note that ``gethostname()`` is defined like this in the stub file for``socket`` (in typeshed)::
def gethostname() -> str: ...
Thus mypyc verifies that library stub files and annotations innon-compiled code match runtime values. This adds an extra layer oftype safety.
Casts such as ``cast(str, x)`` will also result in strict typechecks. Consider this example::
from typing import cast ... x = cast(str, y)
The last line is essentially equivalent to this Python code when compiled::
if not isinstance(y, str): raise TypeError(...) x = y
In interpreted mode ``cast`` does not perform a runtime type check.
Native classes--------------
Native classes behave differently from Python classes. See:ref:`native-classes` for the details.
Primitive types---------------
Some primitive types behave differently in compiled code to improveperformance.
``int`` objects use an unboxed (non-heap-allocated) representation for smallinteger values. A side effect of this is that the exact runtime type of``int`` values is lost. For example, consider this simple function::
def first_int(x: List[int]) -> int: return x[0]
print(first_int([True])) # Output is 1, instead of True!
``bool`` is a subclass of ``int``, so the above code isvalid. However, when the list value is converted to ``int``, ``True``is converted to the corresponding ``int`` value, which is ``1``.
Note that integers still have an arbitrary precision in compiled code,similar to normal Python integers.
Fixed-length tuples are unboxed, similar to integers. The exact typeand identity of fixed-length tuples is not preserved, and you can'treliably use ``is`` checks to compare tuples that are used in compiledcode.
.. _early-binding:
Early binding-------------
References to functions, types, most attributes, and methods in thesame :ref:`compilation unit <compilation-units>` use *early binding*:the target of the reference is decided at compile time, wheneverpossible. This contrasts with normal Python behavior of *latebinding*, where the target is found by a namespace lookup atruntime. Omitting these namespace lookups improves performance, butsome Python idioms don't work without changes.
Note that non-final module-level variables still use late binding.You may want to avoid these in very performance-critical code.
Examples of early and late binding::
from typing import Final
import lib # "lib" is not compiled
x = 0 y: Final = 1
def func() -> None: pass
class Cls: def __init__(self, attr: int) -> None: self.attr = attr
def method(self) -> None: pass
def example() -> None: # Early binding: var = y func() o = Cls() o.x o.method()
# Late binding: var = x # Module-level variable lib.func() # Accessing library that is not compiled
Pickling and copying objects----------------------------
Mypyc tries to enforce that instances native classes are properlyinitialized by calling ``__init__`` implicitly when constructingobjects, even if objects are constructed through ``pickle``,``copy.copy`` or ``copy.deepcopy``, for example.
If a native class doesn't support calling ``__init__`` without arguments,you can't pickle or copy instances of the class. Use the``mypy_extensions.mypyc_attr`` class decorator to override this behaviorand enable pickling through the ``serializable`` flag::
from mypy_extensions import mypyc_attr import pickle
@mypyc_attr(serializable=True) class Cls: def __init__(self, n: int) -> None: self.n = n
data = pickle.dumps(Cls(5)) obj = pickle.loads(data) # OK
Additional notes:
* All subclasses inherit the ``serializable`` flag.* If a class has the ``allow_interpreted_subclasses`` attribute, it implicitly supports serialization.* Enabling serialization may slow down attribute access, since compiled code has to be always prepared to raise ``AttributeError`` in case an attribute is not defined at runtime.* If you try to pickle an object without setting the ``serializable`` flag, you'll get a ``TypeError`` about missing arguments to ``__init__``.
Monkey patching---------------
Since mypyc function and class definitions are immutable, you can'tperform arbitrary monkey patching, such as replacing functions ormethods with mocks in tests.
.. note::
Each compiled module has a Python namespace that is initialized to point to compiled functions and type objects. This namespace is a regular ``dict`` object, and it *can* be modified. However, compiled code generally doesn't use this namespace, so any changes will only be visible to non-compiled code.
Stack overflows---------------
Compiled code currently doesn't check for stack overflows. Yourprogram may crash in an unrecoverable fashion if you have too manynested function calls, typically due to out-of-control recursion.
.. note::
This limitation will be fixed in the future.
Final values------------
Compiled code replaces a reference to an attribute declared ``Final`` withthe value of the attribute computed at compile time. This is an example of:ref:`early binding <early-binding>`. Example::
MAX: Final = 100
def limit_to_max(x: int) -> int: if x > MAX: return MAX return x
The two references to ``MAX`` don't involve any module namespace lookups,and are equivalent to this code::
def limit_to_max(x: int) -> int: if x > 100: return 100 return x
When run as interpreted, the first example will execute slower due tothe extra namespace lookups. In interpreted code final attributes canalso be modified.
Unsupported features--------------------
Some Python features are not supported by mypyc (yet). They can't beused in compiled code, or there are some limitations. You canpartially work around some of these limitations by running your codein interpreted mode.
Nested classes**************
Nested classes are not supported.
Conditional functions or classes********************************
Function and class definitions guarded by an if-statement are not supported.
Dunder methods**************
Native classes **cannot** use these dunders. If defined, they will notwork as expected.
* ``__del__``* ``__index__``* ``__getattr__``, ``__getattribute__``* ``__setattr__``* ``__delattr__``
Generator expressions*********************
Generator expressions are not supported. To make it easier to compileexisting code, they are implicitly replaced with list comprehensions.*This does not always produce the same behavior.*
To work around this limitation, you can usually use a generatorfunction instead. You can sometimes replace the generator expressionwith an explicit list comprehension.
Descriptors***********
Native classes can't contain arbitrary descriptors. Properties, staticmethods and class methods are supported.
Introspection*************
Various methods of introspection may break by using mypyc. Here's annon-exhaustive list of what won't work:
- Instance ``__annotations__`` is usually not kept- Frames of compiled functions can't be inspected using ``inspect``- Compiled methods aren't considered methods by ``inspect.ismethod``- ``inspect.signature`` chokes on compiled functions
Profiling hooks and tracing***************************
Compiled functions don't trigger profiling and tracing hooks, such aswhen using the ``profile``, ``cProfile``, or ``trace`` modules.
Debuggers*********
You can't set breakpoints in compiled functions or step throughcompiled functions using ``pdb``. Often you can debug your code ininterpreted mode instead.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950.. _float-ops:
Native float operations========================
These ``float`` operations have fast, optimized implementations. Otherfloating point operations use generic implementations that are oftenslower.
Construction------------
* Float literal* ``float(x: int)``* ``float(x: i64)``* ``float(x: i32)``* ``float(x: i16)``* ``float(x: u8)``* ``float(x: str)``* ``float(x: float)`` (no-op)
Operators---------
* Arithmetic (``+``, ``-``, ``*``, ``/``, ``//``, ``%``)* Comparisons (``==``, ``!=``, ``<``, etc.)* Augmented assignment (``x += y``, etc.)
Functions---------
* ``int(f)``* ``i64(f)`` (convert to 64-bit signed integer)* ``i32(f)`` (convert to 32-bit signed integer)* ``i16(f)`` (convert to 16-bit signed integer)* ``u8(f)`` (convert to 8-bit unsigned integer)* ``abs(f)``* ``math.sin(f)``* ``math.cos(f)``* ``math.tan(f)``* ``math.sqrt(f)``* ``math.exp(f)``* ``math.log(f)``* ``math.floor(f)``* ``math.ceil(f)``* ``math.fabs(f)``* ``math.pow(x, y)``* ``math.copysign(x, y)``* ``math.isinf(f)``* ``math.isnan(f)``123456789101112131415161718192021222324252627282930313233343536373839404142# Future
This document introduces some ideas for future improvements.
## Basic Optimizations
Implement basic optimizations such as common subexpression elimination andloop invariant code motion.
Importantly, common subexpression elimination could be used to avoidredundant type checks.
## Operation-specific Optimizations
Some operations or combinations of successive operations can bereplaced with more efficient operations. Examples:
* If `s` is a string, `s[i] == 'x'` doesn't need to construct the intermediate single-character string object `s[i]` but just compare the character value to `ord('x')`.
* `a + ':' + b` (two string concetenations) can be implemented as single three-operand concatenation that doesn't construct an intermediate object.
* `x in {1, 3}` can be translated into `x == 1 or x == 3` (more generally we need to evaluate all right-hand-side items).
## Integer Range Analysis
Implement integer range analysis. This can be used in various ways:
* Use untagged representations for some registers.* Use faster integer arithmetic operations for operations that only deal with short integers or that can't overflow.* Remove redundant list and string index checks.
## Always Defined Attributes
Somehow make it possible to enforce that attributes in a class are alwaysdefined. This makes attribute access faster since we don't need to explicitlycheck if the attribute is defined.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240Getting started===============
Here you will learn some basic things you need to know to get started with mypyc.
Prerequisites-------------
You need a Python C extension development environment. The way to set this updepends on your operating system.
macOS*****
Install Xcode command line tools:
.. code-block::
$ xcode-select --install
Linux*****
You need a C compiler and CPython headers and libraries. The specificsof how to install these varies by distribution. Here are instructions forUbuntu 18.04, for example:
.. code-block::
$ sudo apt install python3-dev
Windows*******
From `Build Tools for Visual Studio 2022 <https://www.visualstudio.com/downloads/#build-tools-for-visual-studio-2022>`_, install MSVC C++ build tools for your architecture and a Windows SDK. (latest versions recommended)
Installation------------
Mypyc is shipped as part of the mypy distribution. Install mypy likethis (you need Python 3.8 or later):
.. code-block::
$ python3 -m pip install -U 'mypy[mypyc]'
On some systems you need to use this instead:
.. code-block::
$ python -m pip install -U 'mypy[mypyc]'
Example program---------------
Let's start with a classic micro-benchmark, recursive fibonacci. Savethis file as ``fib.py``:
.. code-block:: python
import time
def fib(n: int) -> int: if n <= 1: return n else: return fib(n - 2) + fib(n - 1)
t0 = time.time() fib(32) print(time.time() - t0)
Note that we gave the ``fib`` function a type annotation. Without it,performance won't be as impressive after compilation.
.. note::
`Mypy documentation <https://mypy.readthedocs.io/en/stable/index.html>`_ is a good introduction if you are new to type annotations or mypy. Mypyc uses mypy to perform type checking and type inference, so some familiarity with mypy is very useful.
Compiling and running---------------------
We can run ``fib.py`` as a regular, interpreted program using CPython:
.. code-block:: console
$ python3 fib.py 0.4125328063964844
It took about 0.41s to run on my computer.
Run ``mypyc`` to compile the program to a binary C extension:
.. code-block:: console
$ mypyc fib.py
This will generate a C extension for ``fib`` in the current workingdirectory. For example, on a Linux system the generated file may becalled ``fib.cpython-37m-x86_64-linux-gnu.so``.
Since C extensions can't be run as programs, use ``python3 -c`` to runthe compiled module as a program:
.. code-block:: console
$ python3 -c "import fib" 0.04097270965576172
After compilation, the program is about 10x faster. Nice!
.. note::
``__name__`` in ``fib.py`` would now be ``"fib"``, not ``"__main__"``.
You can also pass most`mypy command line options <https://mypy.readthedocs.io/en/stable/command_line.html>`_to ``mypyc``.
Deleting compiled binary------------------------
You can manually delete the C extension to get back to an interpretedversion (this example works on Linux):
.. code-block::
$ rm fib.*.so
Using setup.py--------------
You can also use ``setup.py`` to compile modules using mypyc. Here is anexample ``setup.py`` file::
from setuptools import setup
from mypyc.build import mypycify
setup( name='mylib', packages=['mylib'], ext_modules=mypycify([ 'mylib/__init__.py', 'mylib/mod.py', ]), )
We used ``mypycify(...)`` to specify which files to compile usingmypyc. Your ``setup.py`` can include additional Python files outside``mypycify(...)`` that won't be compiled.
Now you can build a wheel (.whl) file for the package::
python3 setup.py bdist_wheel
The wheel is created under ``dist/``.
You can also compile the C extensions in-place, in the current directory (similarto using ``mypyc`` to compile modules)::
python3 setup.py build_ext --inplace
You can include most `mypy command line options<https://mypy.readthedocs.io/en/stable/command_line.html>`_ in thelist of arguments passed to ``mypycify()``. For example, here we usethe ``--disallow-untyped-defs`` flag to require that all functionshave type annotations::
... setup( name='frobnicate', packages=['frobnicate'], ext_modules=mypycify([ '--disallow-untyped-defs', # Pass a mypy flag 'frobnicate.py', ]), )
.. note:
You may be tempted to use `--check-untyped-defs <https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-check-untyped-defs>`_ to type check functions without type annotations. Note that this may reduce performance, due to many transitions between type-checked and unchecked code.
Recommended workflow--------------------
A simple way to use mypyc is to always compile your code after anycode changes, but this can get tedious, especially if you have a lotof code. Instead, you can do most development in interpreted mode.This development workflow has worked smoothly for developing mypy andmypyc (often we forget that we aren't working on a vanilla Pythonproject):
1. During development, use interpreted mode. This gives you a fast edit-run cycle.
2. Use type annotations liberally and use mypy to type check your code during development. Mypy and tests can find most errors that would break your compiled code, if you have good type annotation coverage. (Running mypy is pretty quick.)
3. After you've implemented a feature or a fix, compile your project and run tests again, now in compiled mode. Usually nothing will break here, assuming your type annotation coverage is good. This can happen locally or in a Continuous Integration (CI) job. If you have CI, compiling locally may be rarely needed.
4. Release or deploy a compiled version. Optionally, include a fallback interpreted version for platforms that mypyc doesn't support.
This mypyc workflow only involves minor tweaks to a typical Pythonworkflow. Most of development, testing and debugging happens ininterpreted mode. Incremental mypy runs, especially when using themypy daemon, are very quick (often a few hundred milliseconds).
Next steps----------
You can sometimes get good results by just annotating your code andcompiling it. If this isn't providing meaningful performance gains, ifyou have trouble getting your code to work under mypyc, or if you wantto optimize your code for maximum performance, you should read therest of the documentation in some detail.
Here are some specific recommendations, or you can just read thedocumentation in order:
* :ref:`using-type-annotations`* :ref:`native-classes`* :ref:`differences-from-python`* :ref:`performance-tips`1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162.. mypyc documentation master file, created by sphinx-quickstart on Sun Apr 5 14:01:55 2020. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive.
Welcome to mypyc documentation!===============================
Mypyc compiles Python modules to C extensions. It uses standard Python`type hints<https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html>`_ togenerate fast code.
.. toctree:: :maxdepth: 2 :caption: First steps
introduction getting_started
.. toctree:: :maxdepth: 2 :caption: Using mypyc
using_type_annotations native_classes differences_from_python compilation_units
.. toctree:: :maxdepth: 2 :caption: Native operations reference
native_operations int_operations bool_operations float_operations str_operations bytes_operations list_operations dict_operations set_operations tuple_operations
.. toctree:: :maxdepth: 2 :caption: Advanced topics
performance_tips_and_tricks
.. toctree:: :hidden: :caption: Project Links
GitHub <https://github.com/python/mypy>
Indices and tables==================
* :ref:`genindex`* :ref:`modindex`* :ref:`search`123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162.. _int-ops:
Native integer operations=========================
Mypyc supports these integer types:
* ``int`` (arbitrary-precision integer)* ``i64`` (64-bit signed integer)* ``i32`` (32-bit signed integer)* ``i16`` (16-bit signed integer)* ``u8`` (8-bit unsigned integer)
``i64``, ``i32``, ``i16`` and ``u8`` are *native integer types* andare available in the ``mypy_extensions`` module. ``int`` correspondsto the Python ``int`` type, but uses a more efficient runtimerepresentation (tagged pointer). Native integer types are value types.
All integer types have optimized primitive operations, but the nativeinteger types are more efficient than ``int``, since they don'trequire range or bounds checks.
Operations on integers that are listed here have fast, optimizedimplementations. Other integer operations use generic implementationsthat are generally slower. Some operations involving integers and othertypes, such as list indexing, are documented elsewhere.
Construction------------
``int`` type:
* Integer literal* ``int(x: float)``* ``int(x: i64)``* ``int(x: i32)``* ``int(x: i16)``* ``int(x: u8)``* ``int(x: str)``* ``int(x: str, base: int)``* ``int(x: int)`` (no-op)
``i64`` type:
* ``i64(x: int)``* ``i64(x: float)``* ``i64(x: i64)`` (no-op)* ``i64(x: i32)``* ``i64(x: i16)``* ``i64(x: u8)``* ``i64(x: str)``* ``i64(x: str, base: int)``
``i32`` type:
* ``i32(x: int)``* ``i32(x: float)``* ``i32(x: i64)`` (truncate)* ``i32(x: i32)`` (no-op)* ``i32(x: i16)``* ``i32(x: u8)``* ``i32(x: str)``* ``i32(x: str, base: int)``
``i16`` type:
* ``i16(x: int)``* ``i16(x: float)``* ``i16(x: i64)`` (truncate)* ``i16(x: i32)`` (truncate)* ``i16(x: i16)`` (no-op)* ``i16(x: u8)``* ``i16(x: str)``* ``i16(x: str, base: int)``
Conversions from ``int`` to a native integer type raise``OverflowError`` if the value is too large or small. Conversions froma wider native integer type to a narrower one truncate the value and neverfail. More generally, operations between native integer types don'tcheck for overflow.
Implicit conversions--------------------
``int`` values can be implicitly converted to a native integer type,for convenience. This means that these are equivalent::
from mypy_extensions import i64
def implicit() -> None: # Implicit conversion of 0 (int) to i64 x: i64 = 0
def explicit() -> None: # Explicit conversion of 0 (int) to i64 x = i64(0)
Similarly, a native integer value can be implicitly converted to anarbitrary-precision integer. These two functions are equivalent::
def implicit(x: i64) -> int: # Implicit conversion from i64 to int return x
def explicit(x: i64) -> int: # Explicit conversion from i64 to int return int(x)
Operators---------
* Arithmetic (``+``, ``-``, ``*``, ``//``, ``/``, ``%``)* Bitwise operations (``&``, ``|``, ``^``, ``<<``, ``>>``, ``~``)* Comparisons (``==``, ``!=``, ``<``, etc.)* Augmented assignment (``x += y``, etc.)
If one of the above native integer operations overflows or underflowswith signed operands, the behavior is undefined. Signed native integertypes should only be used if all possible values are small enough forthe type. For this reason, the arbitrary-precision ``int`` type isrecommended for signed values unless the performance of integeroperations is critical.
Operations on unsigned integers (``u8``) wrap around on overflow.
It's a compile-time error to mix different native integer types in abinary operation such as addition. An explicit conversion is required::
from mypy_extensions import i64, i32
def add(x: i64, y: i32) -> None: a = x + y # Error (i64 + i32) b = x + i64(y) # OK
You can freely mix a native integer value and an arbitrary-precision``int`` value in an operation. The native integer type is "sticky"and the ``int`` operand is coerced to the native integer type::
def example(x: i64, y: int) -> None: a = x * y # Type of "a" is "i64" ... b = 1 - x # Similarly, type of "b" is "i64"
Statements----------
For loop over a range is compiled efficiently, if the ``range(...)`` objectis constructed in the for statement (after ``in``):
* ``for x in range(end)``* ``for x in range(start, end)``* ``for x in range(start, end, step)``
If one of the arguments to ``range`` in a for loop is a native integertype, the type of the loop variable is inferred to have this nativeinteger type, instead of ``int``::
for x in range(i64(n)): # Type of "x" is "i64" ...123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150Introduction============
Mypyc compiles Python modules to C extensions. It uses standard Python`type hints<https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html>`_ togenerate fast code.
The compiled language is a strict, *gradually typed* Python variant. Itrestricts the use of some dynamic Python features to gain performance,but it's mostly compatible with standard Python.
Mypyc uses `mypy <https://www.mypy-lang.org/>`_ to perform typechecking and type inference. Most type system features in the stdlib`typing <https://docs.python.org/3/library/typing.html>`_ module aresupported.
Compiled modules can import arbitrary Python modules and third-partylibraries. You can compile anything from a single performance-criticalmodule to your entire codebase. You can run the modules you compilealso as normal, interpreted Python modules.
Existing code with type annotations is often **1.5x to 5x** fasterwhen compiled. Code tuned for mypyc can be **5x to 10x** faster.
Mypyc currently aims to speed up non-numeric code, such as serverapplications. Mypyc is also used to compile itself (and mypy).
Why mypyc?----------
**Easy to get started.** Compiled code has the look and feel ofregular Python code. Mypyc supports familiar Python syntax and idioms.
**Expressive types.** Mypyc fully supports standard Python type hints.Mypyc has local type inference, generics, optional types, tuple types,union types, and more. Type hints act as machine-checkeddocumentation, making code not only faster but also easier tounderstand and modify.
**Python ecosystem.** Mypyc runs on top of CPython, thestandard Python implementation. You can use any third-party libraries,including C extensions, installed with pip. Mypyc uses only valid Pythonsyntax, so all Python editors and IDEs work perfectly.
**Fast program startup.** Mypyc uses ahead-of-time compilation, socompilation does not slow down program startup. Slow program startupis a common issue with JIT compilers.
**Migration path for existing code.** Existing Python code oftenrequires only minor changes to compile using mypyc.
**Waiting for compilation is optional.** Compiled code also runs asnormal Python code. You can use interpreted Python during development,with familiar and fast workflows.
**Runtime type safety.** Mypyc protects you from segfaults and memorycorruption. Any unexpected runtime type safety violation is a bug inmypyc. Runtime values are checked against type annotations. (Withoutmypyc, type annotations are ignored at runtime.)
**Find errors statically.** Mypyc uses mypy for static type checkingthat helps catch many bugs.
Use cases---------
**Fix only performance bottlenecks.** Often most time is spent in a fewPython modules or functions. Add type annotations and compile thesemodules for easy performance gains.
**Compile it all.** During development you can use interpreted mode,for a quick edit-run cycle. In releases all non-test code is compiled.This is how mypy achieved a 4x performance improvement over interpretedPython.
**Take advantage of existing type hints.** If you already use typeannotations in your code, adopting mypyc will be easier. You've alreadydone most of the work needed to use mypyc.
**Alternative to a lower-level language.** Instead of writingperformance-critical code in C, C++, Cython or Rust, you may get goodperformance while staying in the comfort of Python.
**Migrate C extensions.** Maintaining C extensions is not always funfor a Python developer. With mypyc you may get performance similar tothe original C, with the convenience of Python.
Differences from Cython-----------------------
Mypyc targets many similar use cases as Cython. Mypyc does many thingsdifferently, however:
* No need to use non-standard syntax, such as ``cpdef``, or extra decorators to get good performance. Clean, normal-looking type-annotated Python code can be fast without language extensions. This makes it practical to compile entire codebases without a developer productivity hit.
* Mypyc has first-class support for features in the ``typing`` module, such as tuple types, union types and generics.
* Mypyc has powerful type inference, provided by mypy. Variable type annotations are not needed for optimal performance.
* Mypyc fully integrates with mypy for robust and seamless static type checking.
* Mypyc performs strict enforcement of type annotations at runtime, resulting in better runtime type safety and easier debugging.
Unlike Cython, mypyc doesn't directly support interfacing with C librariesor speeding up numeric code.
How does it work----------------
Mypyc uses several techniques to produce fast code:
* Mypyc uses *ahead-of-time compilation* to native code. This removes CPython interpreter overhead.
* Mypyc enforces type annotations (and type comments) at runtime, raising ``TypeError`` if runtime values don't match annotations. Value types only need to be checked in the boundaries between dynamic and static typing.
* Compiled code uses optimized, type-specific primitives.
* Mypyc uses *early binding* to resolve called functions and name references at compile time. Mypyc avoids many dynamic namespace lookups.
* Classes are compiled to *C extension classes*. They use `vtables <https://en.wikipedia.org/wiki/Virtual_method_table>`_ for fast method calls and attribute access.
* Mypyc treats compiled functions, classes, and attributes declared ``Final`` as immutable.
* Mypyc has memory-efficient, unboxed representations for integers and booleans.
Development status------------------
Mypyc is currently alpha software. It's only recommended forproduction use cases with careful testing, and if you are willing tocontribute fixes or to work around issues you will encounter.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465.. _list-ops:
Native list operations======================
These ``list`` operations have fast, optimized implementations. Otherlist operations use generic implementations that are often slower.
Construction------------
Construct list with specific items:
* ``[item0, ..., itemN]``
Construct empty list:
* ``[]``* ``list()``
Construct list from iterable:
* ``list(x: Iterable)``
List comprehensions:
* ``[... for ... in ...]``* ``[... for ... in ... if ...]``
Operators---------
* ``lst[n]`` (get item by integer index)* ``lst[n:m]``, ``lst[n:]``, ``lst[:m]``, ``lst[:]`` (slicing)* ``lst * n``, ``n * lst``* ``obj in lst``
Statements----------
Set item by integer index:
* ``lst[n] = x``
For loop over a list:
* ``for item in lst:``
Methods-------
* ``lst.append(obj)``* ``lst.extend(x: Iterable)``* ``lst.insert(index, obj)``* ``lst.pop(index=-1)``* ``lst.remove(obj)``* ``lst.count(obj)``* ``lst.index(obj)``* ``lst.reverse()``* ``lst.sort()``
Functions---------
* ``len(lst: list)``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206.. _native-classes:
Native classes==============
Classes in compiled modules are *native classes* by default (someexceptions are discussed below). Native classes are compiled to Cextension classes, which have some important differences from normalPython classes. Native classes are similar in many ways to built-intypes, such as ``int``, ``str``, and ``list``.
Immutable namespaces--------------------
The type object namespace of native classes is mostly immutable (butclass variables can be assigned to)::
class Cls: def method1(self) -> None: print("method1")
def method2(self) -> None: print("method2")
Cls.method1 = Cls.method2 # Error Cls.new_method = Cls.method2 # Error
Only attributes defined within a class definition (or in a base class)can be assigned to (similar to using ``__slots__``)::
class Cls: x: int
def __init__(self, y: int) -> None: self.x = 0 self.y = y
def method(self) -> None: self.z = "x"
o = Cls(0) print(o.x, o.y) # OK o.z = "y" # OK o.extra = 3 # Error: no attribute "extra"
.. _inheritance:
Inheritance-----------
Only single inheritance is supported (except for :ref:`traits<trait-types>`). Most non-native classes can't be used as baseclasses.
These non-native classes can be used as base classes of nativeclasses:
* ``object``* ``dict`` (and ``Dict[k, v]``)* ``BaseException``* ``Exception``* ``ValueError``* ``IndexError``* ``LookupError``* ``UserWarning``* ``typing.NamedTuple``* ``enum.Enum``
By default, a non-native class can't inherit a native class, and youcan't inherit from a native class outside the compilation unit thatdefines the class. You can enable these through``mypy_extensions.mypyc_attr``::
from mypy_extensions import mypyc_attr
@mypyc_attr(allow_interpreted_subclasses=True) class Cls: ...
Allowing interpreted subclasses has only minor impact on performanceof instances of the native class. Accessing methods and attributes ofa *non-native* subclass (or a subclass defined in another compilationunit) will be slower, since it needs to use the normal Pythonattribute access mechanism.
You need to install ``mypy-extensions`` to use ``@mypyc_attr``:
.. code-block:: text
pip install --upgrade mypy-extensions
Class variables---------------
Class variables must be explicitly declared using ``attr: ClassVar``or ``attr: ClassVar[<type>]``. You can't assign to a class variablethrough an instance. Example::
from typing import ClassVar
class Cls: cv: ClassVar = 0
Cls.cv = 2 # OK o = Cls() print(o.cv) # OK (2) o.cv = 3 # Error!
.. tip::
Constant class variables can be declared using ``typing.Final`` or ``typing.Final[<type>]``.
Generic native classes----------------------
Native classes can be generic. Type variables are *erased* at runtime,and instances don't keep track of type variable values.
Compiled code thus can't check the values of type variables whenperforming runtime type checks. These checks are delayed to whenreading a value with a type variable type::
from typing import TypeVar, Generic, cast
T = TypeVar('T')
class Box(Generic[T]): def __init__(self, item: T) -> None: self.item = item
x = Box(1) # Box[int] y = cast(Box[str], x) # OK (type variable value not checked) y.item # Runtime error: item is "int", but "str" expected
Metaclasses-----------
Most metaclasses aren't supported with native classes, since theirbehavior is too dynamic. You can use these metaclasses, however:
* ``abc.ABCMeta``* ``typing.GenericMeta`` (used by ``typing.Generic``)
.. note::
If a class definition uses an unsupported metaclass, *mypyc compiles the class into a regular Python class*.
Class decorators----------------
Similar to metaclasses, most class decorators aren't supported withnative classes, as they are usually too dynamic. These classdecorators can be used with native classes, however:
* ``mypy_extensions.trait`` (for defining :ref:`trait types <trait-types>`)* ``mypy_extensions.mypyc_attr`` (see :ref:`above <inheritance>`)* ``dataclasses.dataclass``* ``@attr.s(auto_attribs=True)``
Dataclasses and attrs classes have partial native support, and they aren't asefficient as pure native classes.
.. note::
If a class definition uses an unsupported class decorator, *mypyc compiles the class into a regular Python class*.
Deleting attributes-------------------
By default, attributes defined in native classes can't be deleted. Youcan explicitly allow certain attributes to be deleted by using``__deletable__``::
class Cls: x: int = 0 y: int = 0 other: int = 0
__deletable__ = ['x', 'y'] # 'x' and 'y' can be deleted
o = Cls() del o.x # OK del o.y # OK del o.other # Error
You must initialize the ``__deletable__`` attribute in the class body,using a list or a tuple expression with only string literal items thatrefer to attributes. These are not valid::
a = ['x', 'y']
class Cls: x: int y: int
__deletable__ = a # Error: cannot use variable 'a'
__deletable__ = ('a',) # Error: not in a class body
Other properties----------------
Instances of native classes don't usually have a ``__dict__`` attribute.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455Miscellaneous native operations===============================
This is a list of various non-type-specific operations that havecustom native implementations. If an operation has no nativeimplementation, mypyc will use fallback generic implementations thatare often not as fast.
.. note::
Operations specific to various primitive types are described in the following sections.
Operators---------
* ``x is y`` (this is very fast for all types)
Functions---------
* ``isinstance(obj, type: type)``* ``isinstance(obj, type: tuple)``* ``cast(<type>, obj)``* ``type(obj)``* ``len(obj)``* ``abs(obj)``* ``id(obj)``* ``iter(obj)``* ``next(iter: Iterator)``* ``hash(obj)``* ``getattr(obj, attr)``* ``getattr(obj, attr, default)``* ``setattr(obj, attr, value)``* ``hasattr(obj, attr)``* ``delattr(obj, name)``* ``slice(start, stop, step)``* ``globals()``
Method decorators-----------------
* ``@property``* ``@staticmethod``* ``@classmethod``* ``@abc.abstractmethod``
Statements----------
These variants of statements have custom implementations:
* ``for ... in seq:`` (for loop over a sequence)* ``for ... in enumerate(...):``* ``for ... in zip(...):``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244.. _performance-tips:
Performance tips and tricks===========================
Performance optimization is part art, part science. Just using mypycin a simple manner will likely make your code faster, but squeezingthe most performance out of your code requires the use of sometechniques we'll summarize below.
Profiling---------
If you are speeding up existing code, understanding where time isspent is important. Mypyc speeds up code that you compile. If most ofthe time is spent elsewhere, you may come back disappointed. Forexample, if you spend 40% of time outside compiled code, even ifcompiled code would go 100x faster, overall performance will only be2.5x faster.
A simple (but often effective) approach is to record the time invarious points of program execution using ``time.time()``, and toprint out elapsed time (or to write it to a log file).
The stdlib modules ``profile`` and ``cProfile`` can provide much moredetailed data. (But these only work well with non-compiled code.)
Avoiding slow libraries-----------------------
If profiling indicates that a lot of time is spent in the stdlib orthird-party libraries, you still have several options.
First, if most time is spent in a few library features, you canperhaps easily reimplement them in type-annotated Python, or extractthe relevant code and annotate it. Now it may be easy to compile thiscode to speed it up.
Second, you may be able to avoid the library altogether, or use analternative, more efficient library to achieve the same purpose.
Type annotations----------------
As discussed earlier, type annotations are key to major performancegains. You should at least consider adding annotations to anyperformance-critical functions and classes. It may also be helpful toannotate code called by this code, even if it's not compiled, sincethis may help mypy infer better types in the compile code. If you uselibraries, ensure they have stub files with decent type annotationcoverage. Writing a stub file is often easy, and you only need toannotate features you use a lot.
If annotating external code or writing stubs feel too burdensome, asimple workaround is to annotate variables explicitly. For example,here we call ``acme.get_items()``, but it has no type annotation. Wecan use an explicit type annotation for the variable to which weassign the result::
from typing import List, Tuple import acme
def work() -> None: # Annotate "items" to help mypyc items: List[Tuple[int, str]] = acme.get_items() for item in items: ... # Do some work here
Without the annotation on ``items``, the type would be ``Any`` (since``acme`` has no type annotation), resulting in slower, genericoperations being used later in the function.
Avoiding slow Python features-----------------------------
Mypyc can optimize some features more effectively than others. Herethe difference is sometimes big -- some things only get marginallyfaster at best, while others can get 10x faster, or more. Avoidingthese slow features in performance-critical parts of your code canhelp a lot.
These are some of the most important things to avoid:
* Using class decorators or metaclasses in compiled code (that aren't properly supported by mypyc)
* Heavy reliance on interpreted Python libraries (C extensions are usually fine)
These things also tend to be relatively slow:
* Using Python classes and instances of Python classes (native classes are much faster)
* Calling decorated functions (``@property``, ``@staticmethod``, and ``@classmethod`` are special cased and thus fast)
* Calling nested functions
* Calling functions or methods defined in other compilation units
* Using ``*args`` or ``**kwargs``
* Using generator functions
* Using callable values (i.e. not leveraging early binding to call functions or methods)
Nested functions can often be replaced with module-level functions ormethods of native classes.
Callable values and nested functions can sometimes be replaced with aninstance of a native class with a single method only, such as``call(...)``. You can derive the class from an ABC, if there aremultiple possible functions.
.. note::
Some slow features will likely get efficient implementations in the future. You should check this section every once in a while to see if some additional operations are fast.
Using fast native features--------------------------
Some native operations are particularly quick relative to thecorresponding interpreted operations. Using them as much as possiblemay allow you to see 10x or more in performance gains.
Some things are not much (or any) faster in compiled code, such as setmath operations. In contrast, calling a method of a native class ismuch faster in compiled code.
If you are used to optimizing for CPython, you might have replacedsome class instances with dictionaries, as they can befaster. However, in compiled code, this "optimization" would likelyslow down your code.
Similarly, caching a frequently called method in a local variable canhelp in CPython, but it can slow things down in compiled code, sincethe code won't use :ref:`early binding <early-binding>`::
def squares(n: int) -> List[int]: a = [] append = a.append # Not a good idea in compiled code! for i in range(n): append(i * i) return a
Here are examples of features that are fast, in no particular order(this list is *not* exhaustive):
* Calling compiled functions directly defined in the same compilation unit (with positional and/or keyword arguments)
* Calling methods of native classes defined in the same compilation unit (with positional and/or keyword arguments)
* Many integer operations
* Many ``float`` operations
* Booleans
* :ref:`Native list operations <list-ops>`, such as indexing, ``append``, and list comprehensions
* While loops
* For loops over ranges and lists, and with ``enumerate`` or ``zip``
* Reading dictionary items
* ``isinstance()`` checks against native classes and instances of primitive types (and unions of them)
* Accessing local variables
* Accessing attributes of native classes
* Accessing final module-level attributes
* Comparing strings for equality
These features are also fast, but somewhat less so (relative to otherrelated operations):
* Constructing instances of native classes
* Constructing dictionaries
* Setting dictionary items
* Native :ref:`dict <dict-ops>` and :ref:`set <set-ops>` operations
* Accessing module-level variables
Generally anything documented as a native operation is fast, even ifit's not explicitly mentioned here
Adjusting garbage collection----------------------------
Compilation does not speed up cyclic garbage collection. If everythingelse gets much faster, it's possible that garbage collection will takea big fraction of time. You can use ``gc.set_threshold()`` to adjustthe garbage collector to run less often::
import gc
# Spend less time in gc; do this before significant computation gc.set_threshold(150000)
... # Actual work happens here
Fast interpreter shutdown-------------------------
If you allocate many objects, it's possible that your program spends alot of time cleaning up when the Python runtime shuts down. Mypycwon't speed up the shutdown of a Python process much.
You can call ``os._exit(code)`` to immediately terminate the Pythonprocess, skipping normal cleanup. This can give a nice boost to abatch process or a command-line tool.
.. note::
This can be dangerous and can lose data. You need to ensure that all streams are flushed and everything is otherwise cleaned up properly.
Work smarter------------
Usually there are many things you can do to improve performance, evenif most tweaks will yield only minor gains. The key to being effectiveis to focus on things that give a large gain with a small effort.
For example, low-level optimizations, such as avoiding a nestedfunction, can be pointless, if you could instead avoid a metaclass --to allow a key class to be compiled as a native class. The latteroptimization could speed up numerous method calls and attributeaccesses, just like that.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647.. _set-ops:
Native set operations======================
These ``set`` operations have fast, optimized implementations. Otherset operations use generic implementations that are often slower.
Construction------------
Construct set with specific items:
* ``{item0, ..., itemN}``
Construct empty set:
* ``set()``
Construct set from iterable:
* ``set(x: Iterable)``
Set comprehensions:
* ``{... for ... in ...}``* ``{... for ... in ... if ...}``
Operators---------
* ``item in s``
Methods-------
* ``s.add(item)``* ``s.remove(item)``* ``s.discard(item)``* ``s.update(x: Iterable)``* ``s.clear()``* ``s.pop()``
Functions---------
* ``len(s: set)``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859.. _str-ops:
Native string operations========================
These ``str`` operations have fast, optimized implementations. Otherstring operations use generic implementations that are often slower.
Construction------------
* String literal* ``str(x: int)``* ``str(x: object)``
Operators---------
* Concatenation (``s1 + s2``)* Indexing (``s[n]``)* Slicing (``s[n:m]``, ``s[n:]``, ``s[:m]``)* Comparisons (``==``, ``!=``)* Augmented assignment (``s1 += s2``)
.. _str-methods:
Methods-------
* ``s.encode()``* ``s.encode(encoding: str)``* ``s.encode(encoding: str, errors: str)``* ``s1.endswith(s2: str)``* ``s.join(x: Iterable)``* ``s.replace(old: str, new: str)``* ``s.replace(old: str, new: str, count: int)``* ``s.split()``* ``s.split(sep: str)``* ``s.split(sep: str, maxsplit: int)``* ``s1.startswith(s2: str)``
.. note::
:ref:`bytes.decode() <bytes-methods>` is also optimized.
Formatting----------
A subset of these common string formatting expressions are optimized:
* F-strings* ``"...".format(...)``* ``"..." % (...)``
Functions---------
* ``len(s: str)``* ``ord(s: str)``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398.. _using-type-annotations:
Using type annotations======================
You will get the most out of mypyc if you compile code with precisetype annotations. Not all type annotations will help performanceequally, however. Using types such as :ref:`primitive types<primitive-types>`, :ref:`native classes <native-class-intro>`,:ref:`union types <union-types>`, :ref:`trait types <trait-types>`,and :ref:`tuple types <tuple-types>` as much as possible is a key tomajor performance gains over CPython.
In contrast, some other types, including ``Any``, are treated as:ref:`erased types <erased-types>`. Operations on erased types usegeneric operations that work with arbitrary objects, similar to howthe CPython interpreter works. If you only use erased types, the onlynotable benefits over CPython will be the removal of interpreteroverhead (from compilation) and a bit of :ref:`early binding<early-binding>`, which will usually only give minor performancegains.
.. _primitive-types:
Primitive types---------------
The following built-in types are treated as *primitive types* bymypyc, and many operations on these types have efficientimplementations:
* ``int`` (:ref:`native operations <int-ops>`)* ``i64`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)* ``i32`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)* ``i16`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)* ``u8`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)* ``float`` (:ref:`native operations <float-ops>`)* ``bool`` (:ref:`native operations <bool-ops>`)* ``str`` (:ref:`native operations <str-ops>`)* ``List[T]`` (:ref:`native operations <list-ops>`)* ``Dict[K, V]`` (:ref:`native operations <dict-ops>`)* ``Set[T]`` (:ref:`native operations <set-ops>`)* ``Tuple[T, ...]`` (variable-length tuple; :ref:`native operations <tuple-ops>`)* ``None``
The link after each type lists all supported native, optimizedoperations for the type. You can use all operations supported byPython, but *native operations* will have custom, optimizedimplementations.
Primitive containers--------------------
Primitive container objects such as ``list`` and ``dict`` don'tmaintain knowledge of the item types at runtime -- the item type is*erased*.
This means that item types are checked when items are accessed, notwhen a container is passed as an argument or assigned to anothervariable. For example, here we have a runtime type error on the finalline of ``example`` (the ``Any`` type means an arbitrary, uncheckedvalue)::
from typing import List, Any
def example(a: List[Any]) -> None: b: List[int] = a # No error -- items are not checked print(b[0]) # Error here -- got str, but expected int
example(["x"])
.. _native-class-intro:
Native classes--------------
Classes that get compiled to C extensions are called nativeclasses. Most common operations on instances of these classes areoptimized, including construction, attribute access and method calls.
Native class definitions look exactly like normal Python classdefinitions. A class is usually native if it's in a compiled module(though there are some exceptions).
Consider this example:
.. code-block::
class Point: def __init__(self, x: int, y: int) -> None: self.x = x self.y = y
def shift(p: Point) -> Point: return Point(p.x + 1, p.y + 1)
All operations in the above example use native operations, if the fileis compiled.
Native classes have some notable different from Python classes:
* Only attributes and methods defined in the class body or methods are supported. If you try to assign to an undefined attribute outside the class definition, ``AttributeError`` will be raised. This enables an efficient memory layout and fast method calls for native classes.
* Native classes usually don't define the ``__dict__`` attribute (they don't have an attribute dictionary). This follows from only having a specific set of attributes.
* Native classes can't have an arbitrary metaclass or use most class decorators.
Native classes only support single inheritance. A limited form ofmultiple inheritance is supported through *trait types*. You generallymust inherit from another native class (or ``object``). By default,you can't inherit a Python class from a native class (but there'san :ref:`override <inheritance>` to allow that).
See :ref:`native-classes` for more details.
.. _tuple-types:
Tuple types-----------
Fixed-length`tuple types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#tuple-types>`_such as ``Tuple[int, str]`` are representedas :ref:`value types <value-and-heap-types>` when stored in variables,passed as arguments, or returned from functions. Value types areallocated in the low-level machine stack or in CPU registers, asopposed to *heap types*, which are allocated dynamically from theheap.
Like all value types, tuples will be *boxed*, i.e. converted tocorresponding heap types, when stored in Python containers, or passedto non-native code. A boxed tuple value will be a regular Python tupleobject.
.. _union-types:
Union types-----------
`Union types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#union-types>`_and`optional types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#optional-types-and-the-none-type>`_that contain primitive types, native class types andtrait types are also efficient. If a union type has:ref:`erased <erased-types>` items, accessing items withnon-erased types is often still quite efficient.
A value with a union types is always :ref:`boxed <value-and-heap-types>`,even if it contains a value that also has an unboxed representation, suchas an integer or a boolean.
For example, using ``Optional[int]`` is quite efficient, but the valuewill always be boxed. A plain ``int`` value will usually be faster, sinceit has an unboxed representation.
.. _trait-types:
Trait types-----------
Trait types enable a form of multiple inheritance for native classes.A native class can inherit any number of traits. Trait types aredefined as classes using the ``mypy_extensions.trait`` decorator::
from mypy_extensions import trait
@trait class MyTrait: def method(self) -> None: ...
Traits can define methods, properties and attributes. They oftendefine abstract methods. Traits can be generic.
If a class subclasses both a non-trait class and traits, the traitsmust be placed at the end of the base class list::
class Base: ...
class Derived(Base, MyTrait, FooTrait): # OK ...
class Derived2(MyTrait, FooTrait, Base): # Error: traits should come last ...
Traits have some special properties:
* You shouldn't create instances of traits (though mypyc does not prevent it yet).
* Traits can subclass other traits or native classes, but the MRO must be linear (just like with native classes).
* Accessing methods or attributes through a trait type is somewhat less efficient than through a native class type, but this is much faster than through Python class types or other :ref:`erased types <erased-types>`.
You need to install ``mypy-extensions`` to use ``@trait``:
.. code-block:: text
pip install --upgrade mypy-extensions
.. _erased-types:
Erased types------------
Mypyc supports many other kinds of types as well, beyond thosedescribed above. However, these types don't have customizedoperations, and they are implemented using *type erasure*. Typeerasure means that all other types are equivalent to untyped values atruntime, i.e. they are the equivalent of the type ``Any``. Erasedtypes include these:
* Python classes (including ABCs)
* Non-mypyc extension types and primitive types (including built-in types that are not primitives)
* `Callable types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#callable-types-and-lambdas>`_
* `Type variable types <https://mypy.readthedocs.io/en/stable/generics.html>`_
* Type `Any <https://mypy.readthedocs.io/en/stable/dynamic_typing.html>`_
* Protocol types
Using erased types can still improve performance, since they canenable better types to be inferred for expressions that use thesetypes. For example, a value with type ``Callable[[], int]`` will notallow native calls. However, the return type is a primitive type, andwe can use fast operations on the return value::
from typing import Callable
def call_and_inc(f: Callable[[], int]) -> int: # Slow call, since f has an erased type n = f() # Fast increment; inferred type of n is int (primitive type) n += 1 return n
If the type of the argument ``f`` was ``Any``, the type of ``n`` wouldalso be ``Any``, resulting in a generic, slower increment operationbeing used.
Strict runtime type checking----------------------------
Compiled code ensures that any variable or expression with anon-erased type only has compatible values at runtime. This is incontrast with using *optional static typing*, such as by using mypy,when type annotations are not enforced at runtime. Mypyc ensurestype safety both statically and at runtime.
``Any`` types and erased types in general can compromise type safety,and this is by design. Inserting strict runtime type checks for allpossible values would be too expensive and against the goal ofhigh performance.
.. _value-and-heap-types:
Value and heap types--------------------
In CPython, memory for all objects is dynamically allocated on theheap. All Python types are thus *heap types*. In compiled code, sometypes are *value types* -- no object is (necessarily) allocated on theheap. ``bool``, ``float``, ``None``, :ref:`native integer types <native-ints>`and fixed-length tuples are value types.
``int`` is a hybrid. For typical integer values, it is a valuetype. Large enough integer values, those that require more than 63bits (or 31 bits on 32-bit platforms) to represent, use a heap-basedrepresentation (same as CPython).
Value types have a few differences from heap types:
* When an instance of a value type is used in a context that expects a heap value, for example as a list item, it will transparently switch to a heap-based representation (boxing) as needed.
* Similarly, mypyc transparently changes from a heap-based representation to a value representation (unboxing).
* Object identity of integers, floating point values and tuples is not preserved. You should use ``==`` instead of ``is`` if you are comparing two integers, floats or fixed-length tuples.
* When an instance of a subclass of a value type is converted to the base type, it is implicitly converted to an instance of the target type. For example, a ``bool`` value assigned to a variable with an ``int`` type will be converted to the corresponding integer.
The latter conversion is the only implicit type conversion thathappens in mypyc programs.
Example::
def example() -> None: # A small integer uses the value (unboxed) representation x = 5 # A large integer uses the heap (boxed) representation x = 2**500 # Lists always contain boxed integers a = [55] # When reading from a list, the object is automatically unboxed x = a[0] # True is converted to 1 on assignment x = True
Since integers and floating point values have a different runtimerepresentations and neither can represent all the values of the othertype, type narrowing of floating point values through assignment isdisallowed in compiled code. For consistency, mypyc rejects assigningan integer value to a float variable even in variable initialization.An explicit conversion is required.
Examples::
def narrowing(n: int) -> None: # Error: Incompatible value representations in assignment # (expression has type "int", variable has type "float") x: float = 0
y: float = 0.0 # Ok
if f(): y = n # Error if f(): y = float(n) # Ok
.. _native-ints:
Native integer types--------------------
You can use the native integer types ``i64`` (64-bit signed integer),``i32`` (32-bit signed integer), ``i16`` (16-bit signed integer), and``u8`` (8-bit unsigned integer) if you know that integer values willalways fit within fixed bounds. These types are faster than thearbitrary-precision ``int`` type, since they don't require overflowchecks on operations. They may also use less memory than ``int``values. The types are imported from the ``mypy_extensions`` module(installed via ``pip install mypy_extensions``).
Example::
from mypy_extensions import i64
def sum_list(l: list[i64]) -> i64: s: i64 = 0 for n in l: s += n return s
# Implicit conversions from int to i64 print(sum_list([1, 3, 5]))
.. note::
Since there are no overflow checks when performing native integer arithmetic, the above function could result in an overflow or other undefined behavior if the sum might not fit within 64 bits.
The behavior when running as interpreted Python program will be different if there are overflows. Declaring native integer types have no effect unless code is compiled. Native integer types are effectively equivalent to ``int`` when interpreted.
Native integer types have these additional properties:
* Values can be implicitly converted between ``int`` and a native integer type (both ways).
* Conversions between different native integer types must be explicit. A conversion to a narrower native integer type truncates the value without a runtime overflow check.
* If a binary operation (such as ``+``) or an augmented assignment (such as ``+=``) mixes native integer and ``int`` values, the ``int`` operand is implicitly coerced to the native integer type (native integer types are "sticky").
* You can't mix different native integer types in binary operations. Instead, convert between types explicitly.
For more information about native integer types, refer to:ref:`native integer operations <int-ops>`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503"""Intermediate representation of classes."""
from __future__ import annotations
from typing import List, NamedTuple
from mypyc.common import PROPSET_PREFIX, JsonDictfrom mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignaturefrom mypyc.ir.ops import DeserMaps, Valuefrom mypyc.ir.rtypes import RInstance, RType, deserialize_typefrom mypyc.namegen import NameGenerator, exported_name
# Some notes on the vtable layout: Each concrete class has a vtable# that contains function pointers for its methods. So that subclasses# may be efficiently used when their parent class is expected, the# layout of child vtables must be an extension of their base class's# vtable.## This makes multiple inheritance tricky, since obviously we cannot be# an extension of multiple parent classes. We solve this by requiring# all but one parent to be "traits", which we can operate on in a# somewhat less efficient way. For each trait implemented by a class,# we generate a separate vtable for the methods in that trait.# We then store an array of (trait type, trait vtable) pointers alongside# a class's main vtable. When we want to call a trait method, we# (at runtime!) search the array of trait vtables to find the correct one,# then call through it.# Trait vtables additionally need entries for attribute getters and setters,# since they can't always be in the same location.## To keep down the number of indirections necessary, we store the# array of trait vtables in the memory *before* the class vtable, and# search it backwards. (This is a trick we can only do once---there# are only two directions to store data in---but I don't think we'll# need it again.)# There are some tricks we could try in the future to store the trait# vtables inline in the trait table (which would cut down one indirection),# but this seems good enough for now.## As an example:# Imagine that we have a class B that inherits from a concrete class A# and traits T1 and T2, and that A has methods foo() and# bar() and B overrides bar() with a more specific type.# Then B's vtable will look something like:## T1 type object# ptr to B's T1 trait vtable# T2 type object# ptr to B's T2 trait vtable# -> | A.foo# | Glue function that converts between A.bar's type and B.bar# B.bar# B.baz## The arrow points to the "start" of the vtable (what vtable pointers# point to) and the bars indicate which parts correspond to the parent# class A's vtable layout.## Classes that allow interpreted code to subclass them also have a# "shadow vtable" that contains implementations that delegate to# making a pycall, so that overridden methods in interpreted children# will be called. (A better strategy could dynamically generate these# vtables based on which methods are overridden in the children.)
# Descriptions of method and attribute entries in class vtables.# The 'cls' field is the class that the method/attr was defined in,# which might be a parent class.# The 'shadow_method', if present, contains the method that should be# placed in the class's shadow vtable (if it has one).
class VTableMethod(NamedTuple): cls: "ClassIR" # noqa: UP037 name: str method: FuncIR shadow_method: FuncIR | None
VTableEntries = List[VTableMethod]
class ClassIR: """Intermediate representation of a class.
This also describes the runtime structure of native instances. """
def __init__( self, name: str, module_name: str, is_trait: bool = False, is_generated: bool = False, is_abstract: bool = False, is_ext_class: bool = True, is_final_class: bool = False, ) -> None: self.name = name self.module_name = module_name self.is_trait = is_trait self.is_generated = is_generated self.is_abstract = is_abstract self.is_ext_class = is_ext_class self.is_final_class = is_final_class # An augmented class has additional methods separate from what mypyc generates. # Right now the only one is dataclasses. self.is_augmented = False # Does this inherit from a Python class? self.inherits_python = False # Do instances of this class have __dict__? self.has_dict = False # Do we allow interpreted subclasses? Derived from a mypyc_attr. self.allow_interpreted_subclasses = False # Does this class need getseters to be generated for its attributes? (getseters are also # added if is_generated is False) self.needs_getseters = False # Is this class declared as serializable (supports copy.copy # and pickle) using @mypyc_attr(serializable=True)? # # Additionally, any class with this attribute False but with # an __init__ that can be called without any arguments is # *implicitly serializable*. In this case __init__ will be # called during deserialization without arguments. If this is # True, we match Python semantics and __init__ won't be called # during deserialization. # # This impacts also all subclasses. Use is_serializable() to # also consider base classes. self._serializable = False # If this a subclass of some built-in python class, the name # of the object for that class. We currently only support this # in a few ad-hoc cases. self.builtin_base: str | None = None # Default empty constructor self.ctor = FuncDecl(name, None, module_name, FuncSignature([], RInstance(self))) # Attributes defined in the class (not inherited) self.attributes: dict[str, RType] = {} # Deletable attributes self.deletable: list[str] = [] # We populate method_types with the signatures of every method before # we generate methods, and we rely on this information being present. self.method_decls: dict[str, FuncDecl] = {} # Map of methods that are actually present in an extension class self.methods: dict[str, FuncIR] = {} # Glue methods for boxing/unboxing when a class changes the type # while overriding a method. Maps from (parent class overridden, method) # to IR of glue method. self.glue_methods: dict[tuple[ClassIR, str], FuncIR] = {}
# Properties are accessed like attributes, but have behavior like method calls. # They don't belong in the methods dictionary, since we don't want to expose them to # Python's method API. But we want to put them into our own vtable as methods, so that # they are properly handled and overridden. The property dictionary values are a tuple # containing a property getter and an optional property setter. self.properties: dict[str, tuple[FuncIR, FuncIR | None]] = {} # We generate these in prepare_class_def so that we have access to them when generating # other methods and properties that rely on these types. self.property_types: dict[str, RType] = {}
self.vtable: dict[str, int] | None = None self.vtable_entries: VTableEntries = [] self.trait_vtables: dict[ClassIR, VTableEntries] = {} # N.B: base might not actually quite be the direct base. # It is the nearest concrete base, but we allow a trait in between. self.base: ClassIR | None = None self.traits: list[ClassIR] = [] # Supply a working mro for most generated classes. Real classes will need to # fix it up. self.mro: list[ClassIR] = [self] # base_mro is the chain of concrete (non-trait) ancestors self.base_mro: list[ClassIR] = [self]
# Direct subclasses of this class (use subclasses() to also include non-direct ones) # None if separate compilation prevents this from working. # # Often it's better to use has_no_subclasses() or subclasses() instead. self.children: list[ClassIR] | None = []
# Instance attributes that are initialized in the class body. self.attrs_with_defaults: set[str] = set()
# Attributes that are always initialized in __init__ or class body # (inferred in mypyc.analysis.attrdefined using interprocedural analysis) self._always_initialized_attrs: set[str] = set()
# Attributes that are sometimes initialized in __init__ self._sometimes_initialized_attrs: set[str] = set()
# If True, __init__ can make 'self' visible to unanalyzed/arbitrary code self.init_self_leak = False
# Definedness of these attributes is backed by a bitmap. Index in the list # indicates the bit number. Includes inherited attributes. We need the # bitmap for types such as native ints that can't have a dedicated error # value that doesn't overlap a valid value. The bitmap is used if the # value of an attribute is the same as the error value. self.bitmap_attrs: list[str] = []
def __repr__(self) -> str: return ( "ClassIR(" "name={self.name}, module_name={self.module_name}, " "is_trait={self.is_trait}, is_generated={self.is_generated}, " "is_abstract={self.is_abstract}, is_ext_class={self.is_ext_class}, " "is_final_class={self.is_final_class}" ")".format(self=self) )
@property def fullname(self) -> str: return f"{self.module_name}.{self.name}"
def real_base(self) -> ClassIR | None: """Return the actual concrete base class, if there is one.""" if len(self.mro) > 1 and not self.mro[1].is_trait: return self.mro[1] return None
def vtable_entry(self, name: str) -> int: assert self.vtable is not None, "vtable not computed yet" assert name in self.vtable, f"{self.name!r} has no attribute {name!r}" return self.vtable[name]
def attr_details(self, name: str) -> tuple[RType, ClassIR]: for ir in self.mro: if name in ir.attributes: return ir.attributes[name], ir if name in ir.property_types: return ir.property_types[name], ir raise KeyError(f"{self.name!r} has no attribute {name!r}")
def attr_type(self, name: str) -> RType: return self.attr_details(name)[0]
def method_decl(self, name: str) -> FuncDecl: for ir in self.mro: if name in ir.method_decls: return ir.method_decls[name] raise KeyError(f"{self.name!r} has no attribute {name!r}")
def method_sig(self, name: str) -> FuncSignature: return self.method_decl(name).sig
def has_method(self, name: str) -> bool: try: self.method_decl(name) except KeyError: return False return True
def is_method_final(self, name: str) -> bool: subs = self.subclasses() if subs is None: return self.is_final_class
if self.has_method(name): method_decl = self.method_decl(name) for subc in subs: if subc.method_decl(name) != method_decl: return False return True else: return not any(subc.has_method(name) for subc in subs)
def has_attr(self, name: str) -> bool: try: self.attr_type(name) except KeyError: return False return True
def is_deletable(self, name: str) -> bool: return any(name in ir.deletable for ir in self.mro)
def is_always_defined(self, name: str) -> bool: if self.is_deletable(name): return False return name in self._always_initialized_attrs
def name_prefix(self, names: NameGenerator) -> str: return names.private_name(self.module_name, self.name)
def struct_name(self, names: NameGenerator) -> str: return f"{exported_name(self.fullname)}Object"
def get_method_and_class( self, name: str, *, prefer_method: bool = False ) -> tuple[FuncIR, ClassIR] | None: for ir in self.mro: if name in ir.methods: func_ir = ir.methods[name] if not prefer_method and func_ir.decl.implicit: # This is an implicit accessor, so there is also an attribute definition # which the caller prefers. This happens if an attribute overrides a # property. return None return func_ir, ir
return None
def get_method(self, name: str, *, prefer_method: bool = False) -> FuncIR | None: res = self.get_method_and_class(name, prefer_method=prefer_method) return res[0] if res else None
def has_method_decl(self, name: str) -> bool: return any(name in ir.method_decls for ir in self.mro)
def has_no_subclasses(self) -> bool: return self.children == [] and not self.allow_interpreted_subclasses
def subclasses(self) -> set[ClassIR] | None: """Return all subclasses of this class, both direct and indirect.
Return None if it is impossible to identify all subclasses, for example because we are performing separate compilation. """ if self.children is None or self.allow_interpreted_subclasses: return None result = set(self.children) for child in self.children: if child.children: child_subs = child.subclasses() if child_subs is None: return None result.update(child_subs) return result
def concrete_subclasses(self) -> list[ClassIR] | None: """Return all concrete (i.e. non-trait and non-abstract) subclasses.
Include both direct and indirect subclasses. Place classes with no children first. """ subs = self.subclasses() if subs is None: return None concrete = {c for c in subs if not (c.is_trait or c.is_abstract)} # We place classes with no children first because they are more likely # to appear in various isinstance() checks. We then sort leaves by name # to get stable order. return sorted(concrete, key=lambda c: (len(c.children or []), c.name))
def is_serializable(self) -> bool: return any(ci._serializable for ci in self.mro)
def serialize(self) -> JsonDict: return { "name": self.name, "module_name": self.module_name, "is_trait": self.is_trait, "is_ext_class": self.is_ext_class, "is_abstract": self.is_abstract, "is_generated": self.is_generated, "is_augmented": self.is_augmented, "is_final_class": self.is_final_class, "inherits_python": self.inherits_python, "has_dict": self.has_dict, "allow_interpreted_subclasses": self.allow_interpreted_subclasses, "needs_getseters": self.needs_getseters, "_serializable": self._serializable, "builtin_base": self.builtin_base, "ctor": self.ctor.serialize(), # We serialize dicts as lists to ensure order is preserved "attributes": [(k, t.serialize()) for k, t in self.attributes.items()], # We try to serialize a name reference, but if the decl isn't in methods # then we can't be sure that will work so we serialize the whole decl. "method_decls": [ (k, d.id if k in self.methods else d.serialize()) for k, d in self.method_decls.items() ], # We serialize method fullnames out and put methods in a separate dict "methods": [(k, m.id) for k, m in self.methods.items()], "glue_methods": [ ((cir.fullname, k), m.id) for (cir, k), m in self.glue_methods.items() ], # We serialize properties and property_types separately out of an # abundance of caution about preserving dict ordering... "property_types": [(k, t.serialize()) for k, t in self.property_types.items()], "properties": list(self.properties), "vtable": self.vtable, "vtable_entries": serialize_vtable(self.vtable_entries), "trait_vtables": [ (cir.fullname, serialize_vtable(v)) for cir, v in self.trait_vtables.items() ], # References to class IRs are all just names "base": self.base.fullname if self.base else None, "traits": [cir.fullname for cir in self.traits], "mro": [cir.fullname for cir in self.mro], "base_mro": [cir.fullname for cir in self.base_mro], "children": ( [cir.fullname for cir in self.children] if self.children is not None else None ), "deletable": self.deletable, "attrs_with_defaults": sorted(self.attrs_with_defaults), "_always_initialized_attrs": sorted(self._always_initialized_attrs), "_sometimes_initialized_attrs": sorted(self._sometimes_initialized_attrs), "init_self_leak": self.init_self_leak, }
@classmethod def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> ClassIR: fullname = data["module_name"] + "." + data["name"] assert fullname in ctx.classes, "Class %s not in deser class map" % fullname ir = ctx.classes[fullname]
ir.is_trait = data["is_trait"] ir.is_generated = data["is_generated"] ir.is_abstract = data["is_abstract"] ir.is_ext_class = data["is_ext_class"] ir.is_augmented = data["is_augmented"] ir.is_final_class = data["is_final_class"] ir.inherits_python = data["inherits_python"] ir.has_dict = data["has_dict"] ir.allow_interpreted_subclasses = data["allow_interpreted_subclasses"] ir.needs_getseters = data["needs_getseters"] ir._serializable = data["_serializable"] ir.builtin_base = data["builtin_base"] ir.ctor = FuncDecl.deserialize(data["ctor"], ctx) ir.attributes = {k: deserialize_type(t, ctx) for k, t in data["attributes"]} ir.method_decls = { k: ctx.functions[v].decl if isinstance(v, str) else FuncDecl.deserialize(v, ctx) for k, v in data["method_decls"] } ir.methods = {k: ctx.functions[v] for k, v in data["methods"]} ir.glue_methods = { (ctx.classes[c], k): ctx.functions[v] for (c, k), v in data["glue_methods"] } ir.property_types = {k: deserialize_type(t, ctx) for k, t in data["property_types"]} ir.properties = { k: (ir.methods[k], ir.methods.get(PROPSET_PREFIX + k)) for k in data["properties"] }
ir.vtable = data["vtable"] ir.vtable_entries = deserialize_vtable(data["vtable_entries"], ctx) ir.trait_vtables = { ctx.classes[k]: deserialize_vtable(v, ctx) for k, v in data["trait_vtables"] }
base = data["base"] ir.base = ctx.classes[base] if base else None ir.traits = [ctx.classes[s] for s in data["traits"]] ir.mro = [ctx.classes[s] for s in data["mro"]] ir.base_mro = [ctx.classes[s] for s in data["base_mro"]] ir.children = data["children"] and [ctx.classes[s] for s in data["children"]] ir.deletable = data["deletable"] ir.attrs_with_defaults = set(data["attrs_with_defaults"]) ir._always_initialized_attrs = set(data["_always_initialized_attrs"]) ir._sometimes_initialized_attrs = set(data["_sometimes_initialized_attrs"]) ir.init_self_leak = data["init_self_leak"]
return ir
class NonExtClassInfo: """Information needed to construct a non-extension class (Python class).
Includes the class dictionary, a tuple of base classes, the class annotations dictionary, and the metaclass. """
def __init__(self, dict: Value, bases: Value, anns: Value, metaclass: Value) -> None: self.dict = dict self.bases = bases self.anns = anns self.metaclass = metaclass
def serialize_vtable_entry(entry: VTableMethod) -> JsonDict: return { ".class": "VTableMethod", "cls": entry.cls.fullname, "name": entry.name, "method": entry.method.decl.id, "shadow_method": entry.shadow_method.decl.id if entry.shadow_method else None, }
def serialize_vtable(vtable: VTableEntries) -> list[JsonDict]: return [serialize_vtable_entry(v) for v in vtable]
def deserialize_vtable_entry(data: JsonDict, ctx: DeserMaps) -> VTableMethod: if data[".class"] == "VTableMethod": return VTableMethod( ctx.classes[data["cls"]], data["name"], ctx.functions[data["method"]], ctx.functions[data["shadow_method"]] if data["shadow_method"] else None, ) assert False, "Bogus vtable .class: %s" % data[".class"]
def deserialize_vtable(data: list[JsonDict], ctx: DeserMaps) -> VTableEntries: return [deserialize_vtable_entry(x, ctx) for x in data]
def all_concrete_classes(class_ir: ClassIR) -> list[ClassIR] | None: """Return all concrete classes among the class itself and its subclasses.""" concrete = class_ir.concrete_subclasses() if concrete is None: return None if not (class_ir.is_abstract or class_ir.is_trait): concrete.append(class_ir) return concrete123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516"""Utilities for pretty-printing IR in a human-readable form."""
from __future__ import annotations
from collections import defaultdictfrom typing import Any, Final, Sequence, Union
from mypyc.common import short_namefrom mypyc.ir.func_ir import FuncIR, all_values_fullfrom mypyc.ir.module_ir import ModuleIRsfrom mypyc.ir.ops import ( ERR_NEVER, Assign, AssignMulti, BasicBlock, Box, Branch, Call, CallC, Cast, ComparisonOp, ControlOp, DecRef, Extend, Float, FloatComparisonOp, FloatNeg, FloatOp, GetAttr, GetElementPtr, Goto, IncRef, InitStatic, Integer, IntOp, KeepAlive, LoadAddress, LoadErrorValue, LoadGlobal, LoadLiteral, LoadMem, LoadStatic, MethodCall, Op, OpVisitor, PrimitiveOp, RaiseStandardError, Register, Return, SetAttr, SetMem, Truncate, TupleGet, TupleSet, Unborrow, Unbox, Unreachable, Value,)from mypyc.ir.rtypes import RType, is_bool_rprimitive, is_int_rprimitive
ErrorSource = Union[BasicBlock, Op]
class IRPrettyPrintVisitor(OpVisitor[str]): """Internal visitor that pretty-prints ops."""
def __init__(self, names: dict[Value, str]) -> None: # This should contain a name for all values that are shown as # registers in the output. This is not just for Register # instances -- all Ops that produce values need (generated) names. self.names = names
def visit_goto(self, op: Goto) -> str: return self.format("goto %l", op.label)
branch_op_names: Final = {Branch.BOOL: ("%r", "bool"), Branch.IS_ERROR: ("is_error(%r)", "")}
def visit_branch(self, op: Branch) -> str: fmt, typ = self.branch_op_names[op.op] if op.negated: fmt = f"not {fmt}"
cond = self.format(fmt, op.value) tb = "" if op.traceback_entry: tb = " (error at %s:%d)" % op.traceback_entry fmt = f"if {cond} goto %l{tb} else goto %l" if typ: fmt += f" :: {typ}" return self.format(fmt, op.true, op.false)
def visit_return(self, op: Return) -> str: return self.format("return %r", op.value)
def visit_unreachable(self, op: Unreachable) -> str: return "unreachable"
def visit_assign(self, op: Assign) -> str: return self.format("%r = %r", op.dest, op.src)
def visit_assign_multi(self, op: AssignMulti) -> str: return self.format("%r = [%s]", op.dest, ", ".join(self.format("%r", v) for v in op.src))
def visit_load_error_value(self, op: LoadErrorValue) -> str: return self.format("%r = <error> :: %s", op, op.type)
def visit_load_literal(self, op: LoadLiteral) -> str: prefix = "" # For values that have a potential unboxed representation, make # it explicit that this is a Python object. if isinstance(op.value, int): prefix = "object "
rvalue = repr(op.value) if isinstance(op.value, frozenset): # We need to generate a string representation that won't vary # run-to-run because sets are unordered, otherwise we may get # spurious irbuild test failures. # # Sorting by the item's string representation is a bit of a # hack, but it's stable and won't cause TypeErrors. formatted_items = [repr(i) for i in sorted(op.value, key=str)] rvalue = "frozenset({" + ", ".join(formatted_items) + "})" return self.format("%r = %s%s", op, prefix, rvalue)
def visit_get_attr(self, op: GetAttr) -> str: return self.format("%r = %s%r.%s", op, self.borrow_prefix(op), op.obj, op.attr)
def borrow_prefix(self, op: Op) -> str: if op.is_borrowed: return "borrow " return ""
def visit_set_attr(self, op: SetAttr) -> str: if op.is_init: assert op.error_kind == ERR_NEVER if op.error_kind == ERR_NEVER: # Initialization and direct struct access can never fail return self.format("%r.%s = %r", op.obj, op.attr, op.src) else: return self.format("%r.%s = %r; %r = is_error", op.obj, op.attr, op.src, op)
def visit_load_static(self, op: LoadStatic) -> str: ann = f" ({repr(op.ann)})" if op.ann else "" name = op.identifier if op.module_name is not None: name = f"{op.module_name}.{name}" return self.format("%r = %s :: %s%s", op, name, op.namespace, ann)
def visit_init_static(self, op: InitStatic) -> str: name = op.identifier if op.module_name is not None: name = f"{op.module_name}.{name}" return self.format("%s = %r :: %s", name, op.value, op.namespace)
def visit_tuple_get(self, op: TupleGet) -> str: return self.format("%r = %s%r[%d]", op, self.borrow_prefix(op), op.src, op.index)
def visit_tuple_set(self, op: TupleSet) -> str: item_str = ", ".join(self.format("%r", item) for item in op.items) return self.format("%r = (%s)", op, item_str)
def visit_inc_ref(self, op: IncRef) -> str: s = self.format("inc_ref %r", op.src) # TODO: Remove bool check (it's unboxed) if is_bool_rprimitive(op.src.type) or is_int_rprimitive(op.src.type): s += f" :: {short_name(op.src.type.name)}" return s
def visit_dec_ref(self, op: DecRef) -> str: s = self.format("%sdec_ref %r", "x" if op.is_xdec else "", op.src) # TODO: Remove bool check (it's unboxed) if is_bool_rprimitive(op.src.type) or is_int_rprimitive(op.src.type): s += f" :: {short_name(op.src.type.name)}" return s
def visit_call(self, op: Call) -> str: args = ", ".join(self.format("%r", arg) for arg in op.args) # TODO: Display long name? short_name = op.fn.shortname s = f"{short_name}({args})" if not op.is_void: s = self.format("%r = ", op) + s return s
def visit_method_call(self, op: MethodCall) -> str: args = ", ".join(self.format("%r", arg) for arg in op.args) s = self.format("%r.%s(%s)", op.obj, op.method, args) if not op.is_void: s = self.format("%r = ", op) + s return s
def visit_cast(self, op: Cast) -> str: return self.format("%r = %scast(%s, %r)", op, self.borrow_prefix(op), op.type, op.src)
def visit_box(self, op: Box) -> str: return self.format("%r = box(%s, %r)", op, op.src.type, op.src)
def visit_unbox(self, op: Unbox) -> str: return self.format("%r = unbox(%s, %r)", op, op.type, op.src)
def visit_raise_standard_error(self, op: RaiseStandardError) -> str: if op.value is not None: if isinstance(op.value, str): return self.format("%r = raise %s(%s)", op, op.class_name, repr(op.value)) elif isinstance(op.value, Value): return self.format("%r = raise %s(%r)", op, op.class_name, op.value) else: assert False, "value type must be either str or Value" else: return self.format("%r = raise %s", op, op.class_name)
def visit_call_c(self, op: CallC) -> str: args_str = ", ".join(self.format("%r", arg) for arg in op.args) if op.is_void: return self.format("%s(%s)", op.function_name, args_str) else: return self.format("%r = %s(%s)", op, op.function_name, args_str)
def visit_primitive_op(self, op: PrimitiveOp) -> str: args = [] arg_index = 0 type_arg_index = 0 for arg_type in zip(op.desc.arg_types): if arg_type: args.append(self.format("%r", op.args[arg_index])) arg_index += 1 else: assert op.type_args args.append(self.format("%r", op.type_args[type_arg_index])) type_arg_index += 1
args_str = ", ".join(args) if op.is_void: return self.format("%s %s", op.desc.name, args_str) else: return self.format("%r = %s %s", op, op.desc.name, args_str)
def visit_truncate(self, op: Truncate) -> str: return self.format("%r = truncate %r: %t to %t", op, op.src, op.src_type, op.type)
def visit_extend(self, op: Extend) -> str: if op.signed: extra = " signed" else: extra = "" return self.format("%r = extend%s %r: %t to %t", op, extra, op.src, op.src_type, op.type)
def visit_load_global(self, op: LoadGlobal) -> str: ann = f" ({repr(op.ann)})" if op.ann else "" return self.format("%r = load_global %s :: static%s", op, op.identifier, ann)
def visit_int_op(self, op: IntOp) -> str: return self.format("%r = %r %s %r", op, op.lhs, IntOp.op_str[op.op], op.rhs)
def visit_comparison_op(self, op: ComparisonOp) -> str: if op.op in (ComparisonOp.SLT, ComparisonOp.SGT, ComparisonOp.SLE, ComparisonOp.SGE): sign_format = " :: signed" elif op.op in (ComparisonOp.ULT, ComparisonOp.UGT, ComparisonOp.ULE, ComparisonOp.UGE): sign_format = " :: unsigned" else: sign_format = "" return self.format( "%r = %r %s %r%s", op, op.lhs, ComparisonOp.op_str[op.op], op.rhs, sign_format )
def visit_float_op(self, op: FloatOp) -> str: return self.format("%r = %r %s %r", op, op.lhs, FloatOp.op_str[op.op], op.rhs)
def visit_float_neg(self, op: FloatNeg) -> str: return self.format("%r = -%r", op, op.src)
def visit_float_comparison_op(self, op: FloatComparisonOp) -> str: return self.format("%r = %r %s %r", op, op.lhs, op.op_str[op.op], op.rhs)
def visit_load_mem(self, op: LoadMem) -> str: return self.format("%r = load_mem %r :: %t*", op, op.src, op.type)
def visit_set_mem(self, op: SetMem) -> str: return self.format("set_mem %r, %r :: %t*", op.dest, op.src, op.dest_type)
def visit_get_element_ptr(self, op: GetElementPtr) -> str: return self.format("%r = get_element_ptr %r %s :: %t", op, op.src, op.field, op.src_type)
def visit_load_address(self, op: LoadAddress) -> str: if isinstance(op.src, Register): return self.format("%r = load_address %r", op, op.src) elif isinstance(op.src, LoadStatic): name = op.src.identifier if op.src.module_name is not None: name = f"{op.src.module_name}.{name}" return self.format("%r = load_address %s :: %s", op, name, op.src.namespace) else: return self.format("%r = load_address %s", op, op.src)
def visit_keep_alive(self, op: KeepAlive) -> str: if op.steal: steal = "steal " else: steal = "" return self.format( "keep_alive {}{}".format(steal, ", ".join(self.format("%r", v) for v in op.src)) )
def visit_unborrow(self, op: Unborrow) -> str: return self.format("%r = unborrow %r", op, op.src)
# Helpers
def format(self, fmt: str, *args: Any) -> str: """Helper for formatting strings.
These format sequences are supported in fmt:
%s: arbitrary object converted to string using str() %r: name of IR value/register %d: int %f: float %l: BasicBlock (formatted as label 'Ln') %t: RType """ result = [] i = 0 arglist = list(args) while i < len(fmt): n = fmt.find("%", i) if n < 0: n = len(fmt) result.append(fmt[i:n]) if n < len(fmt): typespec = fmt[n + 1] arg = arglist.pop(0) if typespec == "r": # Register/value assert isinstance(arg, Value) if isinstance(arg, Integer): result.append(str(arg.value)) elif isinstance(arg, Float): result.append(repr(arg.value)) else: result.append(self.names[arg]) elif typespec == "d": # Integer result.append("%d" % arg) elif typespec == "f": # Float result.append("%f" % arg) elif typespec == "l": # Basic block (label) assert isinstance(arg, BasicBlock) result.append("L%s" % arg.label) elif typespec == "t": # RType assert isinstance(arg, RType) result.append(arg.name) elif typespec == "s": # String result.append(str(arg)) else: raise ValueError(f"Invalid format sequence %{typespec}") i = n + 2 else: i = n return "".join(result)
def format_registers(func_ir: FuncIR, names: dict[Value, str]) -> list[str]: result = [] i = 0 regs = all_values_full(func_ir.arg_regs, func_ir.blocks) while i < len(regs): i0 = i group = [names[regs[i0]]] while i + 1 < len(regs) and regs[i + 1].type == regs[i0].type: i += 1 group.append(names[regs[i]]) i += 1 result.append("{} :: {}".format(", ".join(group), regs[i0].type)) return result
def format_blocks( blocks: list[BasicBlock], names: dict[Value, str], source_to_error: dict[ErrorSource, list[str]],) -> list[str]: """Format a list of IR basic blocks into a human-readable form.""" # First label all of the blocks for i, block in enumerate(blocks): block.label = i
handler_map: dict[BasicBlock, list[BasicBlock]] = {} for b in blocks: if b.error_handler: handler_map.setdefault(b.error_handler, []).append(b)
visitor = IRPrettyPrintVisitor(names)
lines = [] for i, block in enumerate(blocks): handler_msg = "" if block in handler_map: labels = sorted("L%d" % b.label for b in handler_map[block]) handler_msg = " (handler for {})".format(", ".join(labels))
lines.append("L%d:%s" % (block.label, handler_msg)) if block in source_to_error: for error in source_to_error[block]: lines.append(f" ERR: {error}") ops = block.ops if ( isinstance(ops[-1], Goto) and i + 1 < len(blocks) and ops[-1].label == blocks[i + 1] and not source_to_error.get(ops[-1], []) ): # Hide the last goto if it just goes to the next basic block, # and there are no assocatiated errors with the op. ops = ops[:-1] for op in ops: line = " " + op.accept(visitor) lines.append(line) if op in source_to_error: for error in source_to_error[op]: lines.append(f" ERR: {error}")
if not isinstance(block.ops[-1], (Goto, Branch, Return, Unreachable)): # Each basic block needs to exit somewhere. lines.append(" [MISSING BLOCK EXIT OPCODE]") return lines
def format_func(fn: FuncIR, errors: Sequence[tuple[ErrorSource, str]] = ()) -> list[str]: lines = [] cls_prefix = fn.class_name + "." if fn.class_name else "" lines.append( "def {}{}({}):".format(cls_prefix, fn.name, ", ".join(arg.name for arg in fn.args)) ) names = generate_names_for_ir(fn.arg_regs, fn.blocks) for line in format_registers(fn, names): lines.append(" " + line)
source_to_error = defaultdict(list) for source, error in errors: source_to_error[source].append(error)
code = format_blocks(fn.blocks, names, source_to_error) lines.extend(code) return lines
def format_modules(modules: ModuleIRs) -> list[str]: ops = [] for module in modules.values(): for fn in module.functions: ops.extend(format_func(fn)) ops.append("") return ops
def generate_names_for_ir(args: list[Register], blocks: list[BasicBlock]) -> dict[Value, str]: """Generate unique names for IR values.
Give names such as 'r5' to temp values in IR which are useful when pretty-printing or generating C. Ensure generated names are unique. """ names: dict[Value, str] = {} used_names = set()
temp_index = 0
for arg in args: names[arg] = arg.name used_names.add(arg.name)
for block in blocks: for op in block.ops: values = []
for source in op.sources(): if source not in names: values.append(source)
if isinstance(op, (Assign, AssignMulti)): values.append(op.dest) elif isinstance(op, ControlOp) or op.is_void: continue elif op not in names: values.append(op)
for value in values: if value in names: continue if isinstance(value, Register) and value.name: name = value.name elif isinstance(value, (Integer, Float)): continue else: name = "r%d" % temp_index temp_index += 1
# Append _2, _3, ... if needed to make the name unique. if name in used_names: n = 2 while True: candidate = "%s_%d" % (name, n) if candidate not in used_names: name = candidate break n += 1
names[value] = name used_names.add(name)
return names123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038"""Types used in the intermediate representation.
These are runtime types (RTypes), as opposed to mypy Type objects.The latter are only used during type checking and not directly used atruntime. Runtime types are derived from mypy types, but there's nosimple one-to-one correspondence. (Here 'runtime' means 'runtimechecked'.)
The generated IR ensures some runtime type safety properties based onRTypes. Compiled code can assume that the runtime value matches thestatic RType of a value. If the RType of a register is 'builtins.str'(str_rprimitive), for example, the generated IR will ensure that theregister will have a 'str' object.
RTypes are simpler and less expressive than mypy (or PEP 484)types. For example, all mypy types of form 'list[T]' (for arbitrary T)are erased to the single RType 'builtins.list' (list_rprimitive).
mypyc.irbuild.mapper.Mapper.type_to_rtype converts mypy Types to mypycRTypes."""
from __future__ import annotations
from abc import abstractmethodfrom typing import TYPE_CHECKING, ClassVar, Final, Generic, TypeVarfrom typing_extensions import TypeGuard
from mypyc.common import IS_32_BIT_PLATFORM, PLATFORM_SIZE, JsonDict, short_namefrom mypyc.namegen import NameGenerator
if TYPE_CHECKING: from mypyc.ir.class_ir import ClassIR from mypyc.ir.ops import DeserMaps
T = TypeVar("T")
class RType: """Abstract base class for runtime types (erased, only concrete; no generics)."""
name: str # If True, the type has a special unboxed representation. If False, the # type is represented as PyObject *. Even if True, the representation # may contain pointers. is_unboxed = False # This is the C undefined value for this type. It's used for initialization # if there's no value yet, and for function return value on error/exception. # # TODO: This shouldn't be specific to C or a string c_undefined: str # If unboxed: does the unboxed version use reference counting? is_refcounted = True # C type; use Emitter.ctype() to access _ctype: str # If True, error/undefined value overlaps with a valid value. To # detect an exception, PyErr_Occurred() must be used in addition # to checking for error value as the return value of a function. # # For example, no i64 value can be reserved for error value, so we # pick an arbitrary value (e.g. -113) to signal error, but this is # also a valid non-error value. error_overlap = False
@abstractmethod def accept(self, visitor: RTypeVisitor[T]) -> T: raise NotImplementedError()
def short_name(self) -> str: return short_name(self.name)
def __str__(self) -> str: return short_name(self.name)
def __repr__(self) -> str: return "<%s>" % self.__class__.__name__
def serialize(self) -> JsonDict | str: raise NotImplementedError(f"Cannot serialize {self.__class__.__name__} instance")
def deserialize_type(data: JsonDict | str, ctx: DeserMaps) -> RType: """Deserialize a JSON-serialized RType.
Arguments: data: The decoded JSON of the serialized type ctx: The deserialization maps to use """ # Since there are so few types, we just case on them directly. If # more get added we should switch to a system like mypy.types # uses. if isinstance(data, str): if data in ctx.classes: return RInstance(ctx.classes[data]) elif data in RPrimitive.primitive_map: return RPrimitive.primitive_map[data] elif data == "void": return RVoid() else: assert False, f"Can't find class {data}" elif data[".class"] == "RTuple": return RTuple.deserialize(data, ctx) elif data[".class"] == "RUnion": return RUnion.deserialize(data, ctx) raise NotImplementedError("unexpected .class {}".format(data[".class"]))
class RTypeVisitor(Generic[T]): """Generic visitor over RTypes (uses the visitor design pattern)."""
@abstractmethod def visit_rprimitive(self, typ: RPrimitive) -> T: raise NotImplementedError
@abstractmethod def visit_rinstance(self, typ: RInstance) -> T: raise NotImplementedError
@abstractmethod def visit_runion(self, typ: RUnion) -> T: raise NotImplementedError
@abstractmethod def visit_rtuple(self, typ: RTuple) -> T: raise NotImplementedError
@abstractmethod def visit_rstruct(self, typ: RStruct) -> T: raise NotImplementedError
@abstractmethod def visit_rarray(self, typ: RArray) -> T: raise NotImplementedError
@abstractmethod def visit_rvoid(self, typ: RVoid) -> T: raise NotImplementedError
class RVoid(RType): """The void type (no value).
This is a singleton -- use void_rtype (below) to refer to this instead of constructing a new instance. """
is_unboxed = False name = "void" ctype = "void"
def accept(self, visitor: RTypeVisitor[T]) -> T: return visitor.visit_rvoid(self)
def serialize(self) -> str: return "void"
def __eq__(self, other: object) -> bool: return isinstance(other, RVoid)
def __hash__(self) -> int: return hash(RVoid)
# Singleton instance of RVoidvoid_rtype: Final = RVoid()
class RPrimitive(RType): """Primitive type such as 'object' or 'int'.
These often have custom ops associated with them. The 'object' primitive type can be used to hold arbitrary Python objects.
Different primitive types have different representations, and primitives may be unboxed or boxed. Primitive types don't need to directly correspond to Python types, but most do.
NOTE: All supported primitive types are defined below (e.g. object_rprimitive). """
# Map from primitive names to primitive types and is used by deserialization primitive_map: ClassVar[dict[str, RPrimitive]] = {}
def __init__( self, name: str, *, is_unboxed: bool, is_refcounted: bool, is_native_int: bool = False, is_signed: bool = False, ctype: str = "PyObject *", size: int = PLATFORM_SIZE, error_overlap: bool = False, ) -> None: RPrimitive.primitive_map[name] = self
self.name = name self.is_unboxed = is_unboxed self.is_refcounted = is_refcounted self.is_native_int = is_native_int self.is_signed = is_signed self._ctype = ctype self.size = size self.error_overlap = error_overlap if ctype == "CPyTagged": self.c_undefined = "CPY_INT_TAG" elif ctype in ("int16_t", "int32_t", "int64_t"): # This is basically an arbitrary value that is pretty # unlikely to overlap with a real value. self.c_undefined = "-113" elif ctype == "CPyPtr": # TODO: Invent an overlapping error value? self.c_undefined = "0" elif ctype == "PyObject *": # Boxed types use the null pointer as the error value. self.c_undefined = "NULL" elif ctype == "char": self.c_undefined = "2" elif ctype in ("PyObject **", "void *"): self.c_undefined = "NULL" elif ctype == "double": self.c_undefined = "-113.0" elif ctype in ("uint8_t", "uint16_t", "uint32_t", "uint64_t"): self.c_undefined = "239" # An arbitrary number else: assert False, "Unrecognized ctype: %r" % ctype
def accept(self, visitor: RTypeVisitor[T]) -> T: return visitor.visit_rprimitive(self)
def serialize(self) -> str: return self.name
def __repr__(self) -> str: return "<RPrimitive %s>" % self.name
def __eq__(self, other: object) -> bool: return isinstance(other, RPrimitive) and other.name == self.name
def __hash__(self) -> int: return hash(self.name)
# NOTE: All the supported instances of RPrimitive are defined# below. Use these instead of creating new instances.
# Used to represent arbitrary objects and dynamically typed (Any)# values. There are various ops that let you perform generic, runtime# checked operations on these (that match Python semantics). See the# ops in mypyc.primitives.misc_ops, including py_getattr_op,# py_call_op, and many others.## If there is no more specific RType available for some value, we fall# back to using this type.## NOTE: Even though this is very flexible, this type should be used as# little as possible, as generic ops are typically slow. Other types,# including other primitive types and RInstance, are usually much# faster.object_rprimitive: Final = RPrimitive("builtins.object", is_unboxed=False, is_refcounted=True)
# represents a low level pointer of an objectobject_pointer_rprimitive: Final = RPrimitive( "object_ptr", is_unboxed=False, is_refcounted=False, ctype="PyObject **")
# Arbitrary-precision integer (corresponds to Python 'int'). Small# enough values are stored unboxed, while large integers are# represented as a tagged pointer to a Python 'int' PyObject. The# lowest bit is used as the tag to decide whether it is a signed# unboxed value (shifted left by one) or a PyObject * pointing to an# 'int' object. Pointers have the least significant bit set.## The undefined/error value is the null pointer (1 -- only the least# significant bit is set)).## This cannot represent a subclass of int. An instance of a subclass# of int is coerced to the corresponding 'int' value.int_rprimitive: Final = RPrimitive( "builtins.int", is_unboxed=True, is_refcounted=True, ctype="CPyTagged")
# An unboxed integer. The representation is the same as for unboxed# int_rprimitive (shifted left by one). These can be used when an# integer is known to be small enough to fit size_t (CPyTagged).short_int_rprimitive: Final = RPrimitive( "short_int", is_unboxed=True, is_refcounted=False, ctype="CPyTagged")
# Low level integer types (correspond to C integer types)
int16_rprimitive: Final = RPrimitive( "i16", is_unboxed=True, is_refcounted=False, is_native_int=True, is_signed=True, ctype="int16_t", size=2, error_overlap=True,)int32_rprimitive: Final = RPrimitive( "i32", is_unboxed=True, is_refcounted=False, is_native_int=True, is_signed=True, ctype="int32_t", size=4, error_overlap=True,)int64_rprimitive: Final = RPrimitive( "i64", is_unboxed=True, is_refcounted=False, is_native_int=True, is_signed=True, ctype="int64_t", size=8, error_overlap=True,)uint8_rprimitive: Final = RPrimitive( "u8", is_unboxed=True, is_refcounted=False, is_native_int=True, is_signed=False, ctype="uint8_t", size=1, error_overlap=True,)
# The following unsigned native int types (u16, u32, u64) are not# exposed to the user. They are for internal use within mypyc only.
u16_rprimitive: Final = RPrimitive( "u16", is_unboxed=True, is_refcounted=False, is_native_int=True, is_signed=False, ctype="uint16_t", size=2, error_overlap=True,)uint32_rprimitive: Final = RPrimitive( "u32", is_unboxed=True, is_refcounted=False, is_native_int=True, is_signed=False, ctype="uint32_t", size=4, error_overlap=True,)uint64_rprimitive: Final = RPrimitive( "u64", is_unboxed=True, is_refcounted=False, is_native_int=True, is_signed=False, ctype="uint64_t", size=8, error_overlap=True,)
# The C 'int' typec_int_rprimitive = int32_rprimitive
if IS_32_BIT_PLATFORM: c_size_t_rprimitive = uint32_rprimitive c_pyssize_t_rprimitive = RPrimitive( "native_int", is_unboxed=True, is_refcounted=False, is_native_int=True, is_signed=True, ctype="int32_t", size=4, )else: c_size_t_rprimitive = uint64_rprimitive c_pyssize_t_rprimitive = RPrimitive( "native_int", is_unboxed=True, is_refcounted=False, is_native_int=True, is_signed=True, ctype="int64_t", size=8, )
# Untyped pointer, represented as integer in the C backendpointer_rprimitive: Final = RPrimitive("ptr", is_unboxed=True, is_refcounted=False, ctype="CPyPtr")
# Untyped pointer, represented as void * in the C backendc_pointer_rprimitive: Final = RPrimitive( "c_ptr", is_unboxed=False, is_refcounted=False, ctype="void *")
# The type corresponding to mypyc.common.BITMAP_TYPEbitmap_rprimitive: Final = uint32_rprimitive
# Floats are represent as 'float' PyObject * values. (In the future# we'll likely switch to a more efficient, unboxed representation.)float_rprimitive: Final = RPrimitive( "builtins.float", is_unboxed=True, is_refcounted=False, ctype="double", size=8, error_overlap=True,)
# An unboxed Python bool value. This actually has three possible values# (0 -> False, 1 -> True, 2 -> error). If you only need True/False, use# bit_rprimitive instead.bool_rprimitive: Final = RPrimitive( "builtins.bool", is_unboxed=True, is_refcounted=False, ctype="char", size=1)
# A low-level boolean value with two possible values: 0 and 1. Any# other value results in undefined behavior. Undefined or error values# are not supported.bit_rprimitive: Final = RPrimitive( "bit", is_unboxed=True, is_refcounted=False, ctype="char", size=1)
# The 'None' value. The possible values are 0 -> None and 2 -> error.none_rprimitive: Final = RPrimitive( "builtins.None", is_unboxed=True, is_refcounted=False, ctype="char", size=1)
# Python list object (or an instance of a subclass of list).list_rprimitive: Final = RPrimitive("builtins.list", is_unboxed=False, is_refcounted=True)
# Python dict object (or an instance of a subclass of dict).dict_rprimitive: Final = RPrimitive("builtins.dict", is_unboxed=False, is_refcounted=True)
# Python set object (or an instance of a subclass of set).set_rprimitive: Final = RPrimitive("builtins.set", is_unboxed=False, is_refcounted=True)
# Python str object. At the C layer, str is referred to as unicode# (PyUnicode).str_rprimitive: Final = RPrimitive("builtins.str", is_unboxed=False, is_refcounted=True)
# Python bytes object.bytes_rprimitive: Final = RPrimitive("builtins.bytes", is_unboxed=False, is_refcounted=True)
# Tuple of an arbitrary length (corresponds to Tuple[t, ...], with# explicit '...').tuple_rprimitive: Final = RPrimitive("builtins.tuple", is_unboxed=False, is_refcounted=True)
# Python range object.range_rprimitive: Final = RPrimitive("builtins.range", is_unboxed=False, is_refcounted=True)
def is_tagged(rtype: RType) -> bool: return rtype is int_rprimitive or rtype is short_int_rprimitive
def is_int_rprimitive(rtype: RType) -> bool: return rtype is int_rprimitive
def is_short_int_rprimitive(rtype: RType) -> bool: return rtype is short_int_rprimitive
def is_int16_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]: return rtype is int16_rprimitive
def is_int32_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]: return rtype is int32_rprimitive or ( rtype is c_pyssize_t_rprimitive and rtype._ctype == "int32_t" )
def is_int64_rprimitive(rtype: RType) -> bool: return rtype is int64_rprimitive or ( rtype is c_pyssize_t_rprimitive and rtype._ctype == "int64_t" )
def is_fixed_width_rtype(rtype: RType) -> TypeGuard[RPrimitive]: return ( is_int64_rprimitive(rtype) or is_int32_rprimitive(rtype) or is_int16_rprimitive(rtype) or is_uint8_rprimitive(rtype) )
def is_uint8_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]: return rtype is uint8_rprimitive
def is_uint32_rprimitive(rtype: RType) -> bool: return rtype is uint32_rprimitive
def is_uint64_rprimitive(rtype: RType) -> bool: return rtype is uint64_rprimitive
def is_c_py_ssize_t_rprimitive(rtype: RType) -> bool: return rtype is c_pyssize_t_rprimitive
def is_pointer_rprimitive(rtype: RType) -> bool: return rtype is pointer_rprimitive
def is_float_rprimitive(rtype: RType) -> bool: return isinstance(rtype, RPrimitive) and rtype.name == "builtins.float"
def is_bool_rprimitive(rtype: RType) -> bool: return isinstance(rtype, RPrimitive) and rtype.name == "builtins.bool"
def is_bit_rprimitive(rtype: RType) -> bool: return isinstance(rtype, RPrimitive) and rtype.name == "bit"
def is_object_rprimitive(rtype: RType) -> bool: return isinstance(rtype, RPrimitive) and rtype.name == "builtins.object"
def is_none_rprimitive(rtype: RType) -> bool: return isinstance(rtype, RPrimitive) and rtype.name == "builtins.None"
def is_list_rprimitive(rtype: RType) -> bool: return isinstance(rtype, RPrimitive) and rtype.name == "builtins.list"
def is_dict_rprimitive(rtype: RType) -> bool: return isinstance(rtype, RPrimitive) and rtype.name == "builtins.dict"
def is_set_rprimitive(rtype: RType) -> bool: return isinstance(rtype, RPrimitive) and rtype.name == "builtins.set"
def is_str_rprimitive(rtype: RType) -> bool: return isinstance(rtype, RPrimitive) and rtype.name == "builtins.str"
def is_bytes_rprimitive(rtype: RType) -> bool: return isinstance(rtype, RPrimitive) and rtype.name == "builtins.bytes"
def is_tuple_rprimitive(rtype: RType) -> bool: return isinstance(rtype, RPrimitive) and rtype.name == "builtins.tuple"
def is_range_rprimitive(rtype: RType) -> bool: return isinstance(rtype, RPrimitive) and rtype.name == "builtins.range"
def is_sequence_rprimitive(rtype: RType) -> bool: return isinstance(rtype, RPrimitive) and ( is_list_rprimitive(rtype) or is_tuple_rprimitive(rtype) or is_str_rprimitive(rtype) )
class TupleNameVisitor(RTypeVisitor[str]): """Produce a tuple name based on the concrete representations of types."""
def visit_rinstance(self, t: RInstance) -> str: return "O"
def visit_runion(self, t: RUnion) -> str: return "O"
def visit_rprimitive(self, t: RPrimitive) -> str: if t._ctype == "CPyTagged": return "I" elif t._ctype == "char": return "C" elif t._ctype == "int64_t": return "8" # "8 byte integer" elif t._ctype == "int32_t": return "4" # "4 byte integer" elif t._ctype == "int16_t": return "2" # "2 byte integer" elif t._ctype == "uint8_t": return "U1" # "1 byte unsigned integer" elif t._ctype == "double": return "F" assert not t.is_unboxed, f"{t} unexpected unboxed type" return "O"
def visit_rtuple(self, t: RTuple) -> str: parts = [elem.accept(self) for elem in t.types] return "T{}{}".format(len(parts), "".join(parts))
def visit_rstruct(self, t: RStruct) -> str: assert False, "RStruct not supported in tuple"
def visit_rarray(self, t: RArray) -> str: assert False, "RArray not supported in tuple"
def visit_rvoid(self, t: RVoid) -> str: assert False, "rvoid in tuple?"
class RTuple(RType): """Fixed-length unboxed tuple (represented as a C struct).
These are used to represent mypy TupleType values (fixed-length Python tuples). Since this is unboxed, the identity of a tuple object is not preserved within compiled code. If the identity of a tuple is important, or there is a need to have multiple references to a single tuple object, a variable-length tuple should be used (tuple_rprimitive or Tuple[T, ...] with explicit '...'), as they are boxed.
These aren't immutable. However, user code won't be able to mutate individual tuple items. """
is_unboxed = True
def __init__(self, types: list[RType]) -> None: self.name = "tuple" self.types = tuple(types) self.is_refcounted = any(t.is_refcounted for t in self.types) # Generate a unique id which is used in naming corresponding C identifiers. # This is necessary since C does not have anonymous structural type equivalence # in the same way python can just assign a Tuple[int, bool] to a Tuple[int, bool]. self.unique_id = self.accept(TupleNameVisitor()) # Nominally the max c length is 31 chars, but I'm not honestly worried about this. self.struct_name = f"tuple_{self.unique_id}" self._ctype = f"{self.struct_name}" self.error_overlap = all(t.error_overlap for t in self.types) and bool(self.types)
def accept(self, visitor: RTypeVisitor[T]) -> T: return visitor.visit_rtuple(self)
def __str__(self) -> str: return "tuple[%s]" % ", ".join(str(typ) for typ in self.types)
def __repr__(self) -> str: return "<RTuple %s>" % ", ".join(repr(typ) for typ in self.types)
def __eq__(self, other: object) -> bool: return isinstance(other, RTuple) and self.types == other.types
def __hash__(self) -> int: return hash((self.name, self.types))
def serialize(self) -> JsonDict: types = [x.serialize() for x in self.types] return {".class": "RTuple", "types": types}
@classmethod def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RTuple: types = [deserialize_type(t, ctx) for t in data["types"]] return RTuple(types)
# Exception tuple: (exception class, exception instance, traceback object)exc_rtuple = RTuple([object_rprimitive, object_rprimitive, object_rprimitive])
# Dictionary iterator tuple: (should continue, internal offset, key, value)# See mypyc.irbuild.for_helpers.ForDictionaryCommon for more details.dict_next_rtuple_pair = RTuple( [bool_rprimitive, short_int_rprimitive, object_rprimitive, object_rprimitive])# Same as above but just for key or value.dict_next_rtuple_single = RTuple([bool_rprimitive, short_int_rprimitive, object_rprimitive])
def compute_rtype_alignment(typ: RType) -> int: """Compute alignment of a given type based on platform alignment rule""" platform_alignment = PLATFORM_SIZE if isinstance(typ, RPrimitive): return typ.size elif isinstance(typ, RInstance): return platform_alignment elif isinstance(typ, RUnion): return platform_alignment elif isinstance(typ, RArray): return compute_rtype_alignment(typ.item_type) else: if isinstance(typ, RTuple): items = list(typ.types) elif isinstance(typ, RStruct): items = typ.types else: assert False, "invalid rtype for computing alignment" max_alignment = max(compute_rtype_alignment(item) for item in items) return max_alignment
def compute_rtype_size(typ: RType) -> int: """Compute unaligned size of rtype""" if isinstance(typ, RPrimitive): return typ.size elif isinstance(typ, RTuple): return compute_aligned_offsets_and_size(list(typ.types))[1] elif isinstance(typ, RUnion): return PLATFORM_SIZE elif isinstance(typ, RStruct): return compute_aligned_offsets_and_size(typ.types)[1] elif isinstance(typ, RInstance): return PLATFORM_SIZE elif isinstance(typ, RArray): alignment = compute_rtype_alignment(typ) aligned_size = (compute_rtype_size(typ.item_type) + (alignment - 1)) & ~(alignment - 1) return aligned_size * typ.length else: assert False, "invalid rtype for computing size"
def compute_aligned_offsets_and_size(types: list[RType]) -> tuple[list[int], int]: """Compute offsets and total size of a list of types after alignment
Note that the types argument are types of values that are stored sequentially with platform default alignment. """ unaligned_sizes = [compute_rtype_size(typ) for typ in types] alignments = [compute_rtype_alignment(typ) for typ in types]
current_offset = 0 offsets = [] final_size = 0 for i in range(len(unaligned_sizes)): offsets.append(current_offset) if i + 1 < len(unaligned_sizes): cur_size = unaligned_sizes[i] current_offset += cur_size next_alignment = alignments[i + 1] # compute aligned offset, # check https://en.wikipedia.org/wiki/Data_structure_alignment for more information current_offset = (current_offset + (next_alignment - 1)) & -next_alignment else: struct_alignment = max(alignments) final_size = current_offset + unaligned_sizes[i] final_size = (final_size + (struct_alignment - 1)) & -struct_alignment return offsets, final_size
class RStruct(RType): """C struct type"""
def __init__(self, name: str, names: list[str], types: list[RType]) -> None: self.name = name self.names = names self.types = types # generate dummy names if len(self.names) < len(self.types): for i in range(len(self.types) - len(self.names)): self.names.append("_item" + str(i)) self.offsets, self.size = compute_aligned_offsets_and_size(types) self._ctype = name
def accept(self, visitor: RTypeVisitor[T]) -> T: return visitor.visit_rstruct(self)
def __str__(self) -> str: # if not tuple(unnamed structs) return "{}{{{}}}".format( self.name, ", ".join(name + ":" + str(typ) for name, typ in zip(self.names, self.types)), )
def __repr__(self) -> str: return "<RStruct {}{{{}}}>".format( self.name, ", ".join(name + ":" + repr(typ) for name, typ in zip(self.names, self.types)), )
def __eq__(self, other: object) -> bool: return ( isinstance(other, RStruct) and self.name == other.name and self.names == other.names and self.types == other.types )
def __hash__(self) -> int: return hash((self.name, tuple(self.names), tuple(self.types)))
def serialize(self) -> JsonDict: assert False
@classmethod def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RStruct: assert False
class RInstance(RType): """Instance of user-defined class (compiled to C extension class).
The runtime representation is 'PyObject *', and these are always boxed and thus reference-counted.
These support fast method calls and fast attribute access using vtables, and they usually use a dict-free, struct-based representation of attributes. Method calls and attribute access can skip the vtable if we know that there is no overriding.
These are also sometimes called 'native' types, since these have the most efficient representation and ops (along with certain RPrimitive types and RTuple). """
is_unboxed = False
def __init__(self, class_ir: ClassIR) -> None: # name is used for formatting the name in messages and debug output # so we want the fullname for precision. self.name = class_ir.fullname self.class_ir = class_ir self._ctype = "PyObject *"
def accept(self, visitor: RTypeVisitor[T]) -> T: return visitor.visit_rinstance(self)
def struct_name(self, names: NameGenerator) -> str: return self.class_ir.struct_name(names)
def getter_index(self, name: str) -> int: return self.class_ir.vtable_entry(name)
def setter_index(self, name: str) -> int: return self.getter_index(name) + 1
def method_index(self, name: str) -> int: return self.class_ir.vtable_entry(name)
def attr_type(self, name: str) -> RType: return self.class_ir.attr_type(name)
def __repr__(self) -> str: return "<RInstance %s>" % self.name
def __eq__(self, other: object) -> bool: return isinstance(other, RInstance) and other.name == self.name
def __hash__(self) -> int: return hash(self.name)
def serialize(self) -> str: return self.name
class RUnion(RType): """union[x, ..., y]"""
is_unboxed = False
def __init__(self, items: list[RType]) -> None: self.name = "union" self.items = items self.items_set = frozenset(items) self._ctype = "PyObject *"
@staticmethod def make_simplified_union(items: list[RType]) -> RType: """Return a normalized union that covers the given items.
Flatten nested unions and remove duplicate items.
Overlapping items are *not* simplified. For example, [object, str] will not be simplified. """ items = flatten_nested_unions(items) assert items
unique_items = dict.fromkeys(items) if len(unique_items) > 1: return RUnion(list(unique_items)) else: return next(iter(unique_items))
def accept(self, visitor: RTypeVisitor[T]) -> T: return visitor.visit_runion(self)
def __repr__(self) -> str: return "<RUnion %s>" % ", ".join(str(item) for item in self.items)
def __str__(self) -> str: return "union[%s]" % ", ".join(str(item) for item in self.items)
# We compare based on the set because order in a union doesn't matter def __eq__(self, other: object) -> bool: return isinstance(other, RUnion) and self.items_set == other.items_set
def __hash__(self) -> int: return hash(("union", self.items_set))
def serialize(self) -> JsonDict: types = [x.serialize() for x in self.items] return {".class": "RUnion", "types": types}
@classmethod def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RUnion: types = [deserialize_type(t, ctx) for t in data["types"]] return RUnion(types)
def flatten_nested_unions(types: list[RType]) -> list[RType]: if not any(isinstance(t, RUnion) for t in types): return types # Fast path
flat_items: list[RType] = [] for t in types: if isinstance(t, RUnion): flat_items.extend(flatten_nested_unions(t.items)) else: flat_items.append(t) return flat_items
def optional_value_type(rtype: RType) -> RType | None: """If rtype is the union of none_rprimitive and another type X, return X.
Otherwise return None. """ if isinstance(rtype, RUnion) and len(rtype.items) == 2: if rtype.items[0] == none_rprimitive: return rtype.items[1] elif rtype.items[1] == none_rprimitive: return rtype.items[0] return None
def is_optional_type(rtype: RType) -> bool: """Is rtype an optional type with exactly two union items?""" return optional_value_type(rtype) is not None
class RArray(RType): """Fixed-length C array type (for example, int[5]).
Note that the implementation is a bit limited, and these can basically be only used for local variables that are initialized in one location. """
def __init__(self, item_type: RType, length: int) -> None: self.item_type = item_type # Number of items self.length = length self.is_refcounted = False
def accept(self, visitor: RTypeVisitor[T]) -> T: return visitor.visit_rarray(self)
def __str__(self) -> str: return f"{self.item_type}[{self.length}]"
def __repr__(self) -> str: return f"<RArray {self.item_type!r}[{self.length}]>"
def __eq__(self, other: object) -> bool: return ( isinstance(other, RArray) and self.item_type == other.item_type and self.length == other.length )
def __hash__(self) -> int: return hash((self.item_type, self.length))
def serialize(self) -> JsonDict: assert False
@classmethod def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RArray: assert False
PyObject = RStruct( name="PyObject", names=["ob_refcnt", "ob_type"], types=[c_pyssize_t_rprimitive, pointer_rprimitive],)
PyVarObject = RStruct( name="PyVarObject", names=["ob_base", "ob_size"], types=[PyObject, c_pyssize_t_rprimitive])
setentry = RStruct( name="setentry", names=["key", "hash"], types=[pointer_rprimitive, c_pyssize_t_rprimitive])
smalltable = RStruct(name="smalltable", names=[], types=[setentry] * 8)
PySetObject = RStruct( name="PySetObject", names=[ "ob_base", "fill", "used", "mask", "table", "hash", "finger", "smalltable", "weakreflist", ], types=[ PyObject, c_pyssize_t_rprimitive, c_pyssize_t_rprimitive, c_pyssize_t_rprimitive, pointer_rprimitive, c_pyssize_t_rprimitive, c_pyssize_t_rprimitive, smalltable, pointer_rprimitive, ],)
PyListObject = RStruct( name="PyListObject", names=["ob_base", "ob_item", "allocated"], types=[PyVarObject, pointer_rprimitive, c_pyssize_t_rprimitive],)
def check_native_int_range(rtype: RPrimitive, n: int) -> bool: """Is n within the range of a native, fixed-width int type?
Assume the type is a fixed-width int type. """ if not rtype.is_signed: return 0 <= n < (1 << (8 * rtype.size)) else: limit = 1 << (rtype.size * 8 - 1) return -limit <= n < limit12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457"""Builder class used to transform a mypy AST to the IR form.
The IRBuilder class maintains transformation state and provides accessto various helpers used to implement the transform.
The top-level transform control logic is in mypyc.irbuild.main.
mypyc.irbuild.visitor.IRBuilderVisitor is used to dispatch based on mypyAST node type to code that actually does the bulk of the work. Forexample, expressions are transformed in mypyc.irbuild.expression andfunctions are transformed in mypyc.irbuild.function."""
from __future__ import annotations
from contextlib import contextmanagerfrom typing import Any, Callable, Final, Iterator, Sequence, Unionfrom typing_extensions import overload
from mypy.build import Graphfrom mypy.maptype import map_instance_to_supertypefrom mypy.nodes import ( ARG_NAMED, ARG_POS, GDEF, LDEF, PARAM_SPEC_KIND, TYPE_VAR_KIND, TYPE_VAR_TUPLE_KIND, ArgKind, CallExpr, Decorator, Expression, FuncDef, IndexExpr, IntExpr, Lvalue, MemberExpr, MypyFile, NameExpr, OpExpr, OverloadedFuncDef, RefExpr, StarExpr, Statement, SymbolNode, TupleExpr, TypeAlias, TypeInfo, TypeParam, UnaryExpr, Var,)from mypy.types import ( AnyType, DeletedType, Instance, ProperType, TupleType, Type, TypedDictType, TypeOfAny, UninhabitedType, UnionType, get_proper_type,)from mypy.util import module_prefix, split_targetfrom mypy.visitor import ExpressionVisitor, StatementVisitorfrom mypyc.common import BITMAP_BITS, SELF_NAME, TEMP_ATTR_NAMEfrom mypyc.crash import catch_errorsfrom mypyc.errors import Errorsfrom mypyc.ir.class_ir import ClassIR, NonExtClassInfofrom mypyc.ir.func_ir import INVALID_FUNC_DEF, FuncDecl, FuncIR, FuncSignature, RuntimeArgfrom mypyc.ir.ops import ( NAMESPACE_MODULE, NAMESPACE_TYPE_VAR, Assign, BasicBlock, Branch, ComparisonOp, GetAttr, InitStatic, Integer, IntOp, LoadStatic, Op, PrimitiveDescription, RaiseStandardError, Register, SetAttr, TupleGet, Unreachable, Value,)from mypyc.ir.rtypes import ( RInstance, RTuple, RType, RUnion, bitmap_rprimitive, c_pyssize_t_rprimitive, dict_rprimitive, int_rprimitive, is_float_rprimitive, is_list_rprimitive, is_none_rprimitive, is_object_rprimitive, is_tagged, is_tuple_rprimitive, none_rprimitive, object_rprimitive, str_rprimitive,)from mypyc.irbuild.context import FuncInfo, ImplicitClassfrom mypyc.irbuild.ll_builder import LowLevelIRBuilderfrom mypyc.irbuild.mapper import Mapperfrom mypyc.irbuild.nonlocalcontrol import ( BaseNonlocalControl, GeneratorNonlocalControl, LoopNonlocalControl, NonlocalControl,)from mypyc.irbuild.prebuildvisitor import PreBuildVisitorfrom mypyc.irbuild.prepare import RegisterImplInfofrom mypyc.irbuild.targets import ( AssignmentTarget, AssignmentTargetAttr, AssignmentTargetIndex, AssignmentTargetRegister, AssignmentTargetTuple,)from mypyc.irbuild.util import bytes_from_str, is_constantfrom mypyc.options import CompilerOptionsfrom mypyc.primitives.dict_ops import dict_get_item_op, dict_set_item_opfrom mypyc.primitives.generic_ops import iter_op, next_op, py_setattr_opfrom mypyc.primitives.list_ops import list_get_item_unsafe_op, list_pop_last, to_listfrom mypyc.primitives.misc_ops import check_unpack_count_op, get_module_dict_op, import_opfrom mypyc.primitives.registry import CFunctionDescription, function_ops
# These int binary operations can borrow their operands safely, since the# primitives take this into consideration.int_borrow_friendly_op: Final = {"+", "-", "==", "!=", "<", "<=", ">", ">="}
class IRVisitor(ExpressionVisitor[Value], StatementVisitor[None]): pass
class UnsupportedException(Exception): pass
SymbolTarget = Union[AssignmentTargetRegister, AssignmentTargetAttr]
class IRBuilder: def __init__( self, current_module: str, types: dict[Expression, Type], graph: Graph, errors: Errors, mapper: Mapper, pbv: PreBuildVisitor, visitor: IRVisitor, options: CompilerOptions, singledispatch_impls: dict[FuncDef, list[RegisterImplInfo]], ) -> None: self.builder = LowLevelIRBuilder(errors, options) self.builders = [self.builder] self.symtables: list[dict[SymbolNode, SymbolTarget]] = [{}] self.runtime_args: list[list[RuntimeArg]] = [[]] self.function_name_stack: list[str] = [] self.class_ir_stack: list[ClassIR] = [] # Keep track of whether the next statement in a block is reachable # or not, separately for each block nesting level self.block_reachable_stack: list[bool] = [True]
self.current_module = current_module self.mapper = mapper self.types = types self.graph = graph self.ret_types: list[RType] = [] self.functions: list[FuncIR] = [] self.function_names: set[tuple[str | None, str]] = set() self.classes: list[ClassIR] = [] self.final_names: list[tuple[str, RType]] = [] self.type_var_names: list[str] = [] self.callable_class_names: set[str] = set() self.options = options
# These variables keep track of the number of lambdas, implicit indices, and implicit # iterators instantiated so we avoid name conflicts. The indices and iterators are # instantiated from for-loops. self.lambda_counter = 0 self.temp_counter = 0
# These variables are populated from the first-pass PreBuildVisitor. self.free_variables = pbv.free_variables self.prop_setters = pbv.prop_setters self.encapsulating_funcs = pbv.encapsulating_funcs self.nested_fitems = pbv.nested_funcs.keys() self.fdefs_to_decorators = pbv.funcs_to_decorators self.module_import_groups = pbv.module_import_groups
self.singledispatch_impls = singledispatch_impls
self.visitor = visitor
# This list operates similarly to a function call stack for nested functions. Whenever a # function definition begins to be generated, a FuncInfo instance is added to the stack, # and information about that function (e.g. whether it is nested, its environment class to # be generated) is stored in that FuncInfo instance. When the function is done being # generated, its corresponding FuncInfo is popped off the stack. self.fn_info = FuncInfo(INVALID_FUNC_DEF, "", "") self.fn_infos: list[FuncInfo] = [self.fn_info]
# This list operates as a stack of constructs that modify the # behavior of nonlocal control flow constructs. self.nonlocal_control: list[NonlocalControl] = []
self.errors = errors # Notionally a list of all of the modules imported by the # module being compiled, but stored as an OrderedDict so we # can also do quick lookups. self.imports: dict[str, None] = {}
self.can_borrow = False
# High-level control
def set_module(self, module_name: str, module_path: str) -> None: """Set the name and path of the current module.
This must be called before transforming any AST nodes. """ self.module_name = module_name self.module_path = module_path self.builder.set_module(module_name, module_path)
@overload def accept(self, node: Expression, *, can_borrow: bool = False) -> Value: ...
@overload def accept(self, node: Statement) -> None: ...
def accept(self, node: Statement | Expression, *, can_borrow: bool = False) -> Value | None: """Transform an expression or a statement.
If can_borrow is true, prefer to generate a borrowed reference. Borrowed references are faster since they don't require reference count manipulation, but they are only safe to use in specific contexts. """ with self.catch_errors(node.line): if isinstance(node, Expression): old_can_borrow = self.can_borrow self.can_borrow = can_borrow try: res = node.accept(self.visitor) res = self.coerce(res, self.node_type(node), node.line) # If we hit an error during compilation, we want to # keep trying, so we can produce more error # messages. Generate a temp of the right type to keep # from causing more downstream trouble. except UnsupportedException: res = Register(self.node_type(node)) self.can_borrow = old_can_borrow if not can_borrow: self.flush_keep_alives() return res else: try: node.accept(self.visitor) except UnsupportedException: pass return None
def flush_keep_alives(self) -> None: self.builder.flush_keep_alives()
# Pass through methods for the most common low-level builder ops, for convenience.
def add(self, op: Op) -> Value: return self.builder.add(op)
def goto(self, target: BasicBlock) -> None: self.builder.goto(target)
def activate_block(self, block: BasicBlock) -> None: self.builder.activate_block(block)
def goto_and_activate(self, block: BasicBlock) -> None: self.builder.goto_and_activate(block)
def self(self) -> Register: return self.builder.self()
def py_get_attr(self, obj: Value, attr: str, line: int) -> Value: return self.builder.py_get_attr(obj, attr, line)
def load_str(self, value: str) -> Value: return self.builder.load_str(value)
def load_bytes_from_str_literal(self, value: str) -> Value: """Load bytes object from a string literal.
The literal characters of BytesExpr (the characters inside b'') are stored in BytesExpr.value, whose type is 'str' not 'bytes'. Thus we perform a special conversion here. """ return self.builder.load_bytes(bytes_from_str(value))
def load_int(self, value: int) -> Value: return self.builder.load_int(value)
def load_float(self, value: float) -> Value: return self.builder.load_float(value)
def unary_op(self, lreg: Value, expr_op: str, line: int) -> Value: return self.builder.unary_op(lreg, expr_op, line)
def binary_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value: return self.builder.binary_op(lreg, rreg, expr_op, line)
def coerce(self, src: Value, target_type: RType, line: int, force: bool = False) -> Value: return self.builder.coerce(src, target_type, line, force, can_borrow=self.can_borrow)
def none_object(self) -> Value: return self.builder.none_object()
def none(self) -> Value: return self.builder.none()
def true(self) -> Value: return self.builder.true()
def false(self) -> Value: return self.builder.false()
def new_list_op(self, values: list[Value], line: int) -> Value: return self.builder.new_list_op(values, line)
def new_set_op(self, values: list[Value], line: int) -> Value: return self.builder.new_set_op(values, line)
def translate_is_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value: return self.builder.translate_is_op(lreg, rreg, expr_op, line)
def py_call( self, function: Value, arg_values: list[Value], line: int, arg_kinds: list[ArgKind] | None = None, arg_names: Sequence[str | None] | None = None, ) -> Value: return self.builder.py_call(function, arg_values, line, arg_kinds, arg_names)
def add_bool_branch(self, value: Value, true: BasicBlock, false: BasicBlock) -> None: self.builder.add_bool_branch(value, true, false)
def load_native_type_object(self, fullname: str) -> Value: return self.builder.load_native_type_object(fullname)
def gen_method_call( self, base: Value, name: str, arg_values: list[Value], result_type: RType | None, line: int, arg_kinds: list[ArgKind] | None = None, arg_names: list[str | None] | None = None, ) -> Value: return self.builder.gen_method_call( base, name, arg_values, result_type, line, arg_kinds, arg_names, self.can_borrow )
def load_module(self, name: str) -> Value: return self.builder.load_module(name)
def call_c(self, desc: CFunctionDescription, args: list[Value], line: int) -> Value: return self.builder.call_c(desc, args, line)
def primitive_op(self, desc: PrimitiveDescription, args: list[Value], line: int) -> Value: return self.builder.primitive_op(desc, args, line)
def int_op(self, type: RType, lhs: Value, rhs: Value, op: int, line: int) -> Value: return self.builder.int_op(type, lhs, rhs, op, line)
def compare_tuples(self, lhs: Value, rhs: Value, op: str, line: int) -> Value: return self.builder.compare_tuples(lhs, rhs, op, line)
def builtin_len(self, val: Value, line: int) -> Value: return self.builder.builtin_len(val, line)
def new_tuple(self, items: list[Value], line: int) -> Value: return self.builder.new_tuple(items, line)
# Helpers for IR building
def add_to_non_ext_dict( self, non_ext: NonExtClassInfo, key: str, val: Value, line: int ) -> None: # Add an attribute entry into the class dict of a non-extension class. key_unicode = self.load_str(key) self.primitive_op(dict_set_item_op, [non_ext.dict, key_unicode, val], line)
def gen_import(self, id: str, line: int) -> None: self.imports[id] = None
needs_import, out = BasicBlock(), BasicBlock() self.check_if_module_loaded(id, line, needs_import, out)
self.activate_block(needs_import) value = self.call_c(import_op, [self.load_str(id)], line) self.add(InitStatic(value, id, namespace=NAMESPACE_MODULE)) self.goto_and_activate(out)
def check_if_module_loaded( self, id: str, line: int, needs_import: BasicBlock, out: BasicBlock ) -> None: """Generate code that checks if the module `id` has been loaded yet.
Arguments: id: name of module to check if imported line: line number that the import occurs on needs_import: the BasicBlock that is run if the module has not been loaded yet out: the BasicBlock that is run if the module has already been loaded""" first_load = self.load_module(id) comparison = self.translate_is_op(first_load, self.none_object(), "is not", line) self.add_bool_branch(comparison, out, needs_import)
def get_module(self, module: str, line: int) -> Value: # Python 3.7 has a nice 'PyImport_GetModule' function that we can't use :( mod_dict = self.call_c(get_module_dict_op, [], line) # Get module object from modules dict. return self.primitive_op(dict_get_item_op, [mod_dict, self.load_str(module)], line)
def get_module_attr(self, module: str, attr: str, line: int) -> Value: """Look up an attribute of a module without storing it in the local namespace.
For example, get_module_attr('typing', 'TypedDict', line) results in the value of 'typing.TypedDict'.
Import the module if needed. """ self.gen_import(module, line) module_obj = self.get_module(module, line) return self.py_get_attr(module_obj, attr, line)
def assign_if_null(self, target: Register, get_val: Callable[[], Value], line: int) -> None: """If target is NULL, assign value produced by get_val to it.""" error_block, body_block = BasicBlock(), BasicBlock() self.add(Branch(target, error_block, body_block, Branch.IS_ERROR)) self.activate_block(error_block) self.add(Assign(target, self.coerce(get_val(), target.type, line))) self.goto(body_block) self.activate_block(body_block)
def assign_if_bitmap_unset( self, target: Register, get_val: Callable[[], Value], index: int, line: int ) -> None: error_block, body_block = BasicBlock(), BasicBlock() o = self.int_op( bitmap_rprimitive, self.builder.args[-1 - index // BITMAP_BITS], Integer(1 << (index & (BITMAP_BITS - 1)), bitmap_rprimitive), IntOp.AND, line, ) b = self.add(ComparisonOp(o, Integer(0, bitmap_rprimitive), ComparisonOp.EQ)) self.add(Branch(b, error_block, body_block, Branch.BOOL)) self.activate_block(error_block) self.add(Assign(target, self.coerce(get_val(), target.type, line))) self.goto(body_block) self.activate_block(body_block)
def maybe_add_implicit_return(self) -> None: if is_none_rprimitive(self.ret_types[-1]) or is_object_rprimitive(self.ret_types[-1]): self.add_implicit_return() else: self.add_implicit_unreachable()
def add_implicit_return(self) -> None: block = self.builder.blocks[-1] if not block.terminated: retval = self.coerce(self.builder.none(), self.ret_types[-1], -1) self.nonlocal_control[-1].gen_return(self, retval, self.fn_info.fitem.line)
def add_implicit_unreachable(self) -> None: block = self.builder.blocks[-1] if not block.terminated: self.add(Unreachable())
def disallow_class_assignments(self, lvalues: list[Lvalue], line: int) -> None: # Some best-effort attempts to disallow assigning to class # variables that aren't marked ClassVar, since we blatantly # miscompile the interaction between instance and class # variables. for lvalue in lvalues: if ( isinstance(lvalue, MemberExpr) and isinstance(lvalue.expr, RefExpr) and isinstance(lvalue.expr.node, TypeInfo) ): var = lvalue.expr.node[lvalue.name].node if isinstance(var, Var) and not var.is_classvar: self.error("Only class variables defined as ClassVar can be assigned to", line)
def non_function_scope(self) -> bool: # Currently the stack always has at least two items: dummy and top-level. return len(self.fn_infos) <= 2
def top_level_fn_info(self) -> FuncInfo | None: if self.non_function_scope(): return None return self.fn_infos[2]
def init_final_static( self, lvalue: Lvalue, rvalue_reg: Value, class_name: str | None = None, *, type_override: RType | None = None, ) -> None: assert isinstance(lvalue, NameExpr) assert isinstance(lvalue.node, Var) if lvalue.node.final_value is None: if class_name is None: name = lvalue.name else: name = f"{class_name}.{lvalue.name}" assert name is not None, "Full name not set for variable" coerced = self.coerce(rvalue_reg, type_override or self.node_type(lvalue), lvalue.line) self.final_names.append((name, coerced.type)) self.add(InitStatic(coerced, name, self.module_name))
def load_final_static( self, fullname: str, typ: RType, line: int, error_name: str | None = None ) -> Value: split_name = split_target(self.graph, fullname) assert split_name is not None module, name = split_name return self.builder.load_static_checked( typ, name, module, line=line, error_msg=f'value for final name "{error_name}" was not set', )
def init_type_var(self, value: Value, name: str, line: int) -> None: unique_name = name + "___" + str(line) self.type_var_names.append(unique_name) self.add(InitStatic(value, unique_name, self.module_name, namespace=NAMESPACE_TYPE_VAR))
def load_type_var(self, name: str, line: int) -> Value: return self.add( LoadStatic( object_rprimitive, name + "___" + str(line), self.module_name, namespace=NAMESPACE_TYPE_VAR, ) )
def load_literal_value(self, val: int | str | bytes | float | complex | bool) -> Value: """Load value of a final name, class-level attribute, or constant folded expression.""" if isinstance(val, bool): if val: return self.true() else: return self.false() elif isinstance(val, int): return self.builder.load_int(val) elif isinstance(val, float): return self.builder.load_float(val) elif isinstance(val, str): return self.builder.load_str(val) elif isinstance(val, bytes): return self.builder.load_bytes(val) elif isinstance(val, complex): return self.builder.load_complex(val) else: assert False, "Unsupported literal value"
def get_assignment_target( self, lvalue: Lvalue, line: int = -1, *, for_read: bool = False ) -> AssignmentTarget: if line == -1: line = lvalue.line if isinstance(lvalue, NameExpr): # If we are visiting a decorator, then the SymbolNode we really want to be looking at # is the function that is decorated, not the entire Decorator node itself. symbol = lvalue.node if isinstance(symbol, Decorator): symbol = symbol.func if symbol is None: # Semantic analyzer doesn't create ad-hoc Vars for special forms. assert lvalue.is_special_form symbol = Var(lvalue.name) if not for_read and isinstance(symbol, Var) and symbol.is_cls: self.error("Cannot assign to the first argument of classmethod", line) if lvalue.kind == LDEF: if symbol not in self.symtables[-1]: if isinstance(symbol, Var) and not isinstance(symbol.type, DeletedType): reg_type = self.type_to_rtype(symbol.type) else: reg_type = self.node_type(lvalue) # If the function is a generator function, then first define a new variable # in the current function's environment class. Next, define a target that # refers to the newly defined variable in that environment class. Add the # target to the table containing class environment variables, as well as the # current environment. if self.fn_info.is_generator: return self.add_var_to_env_class( symbol, reg_type, self.fn_info.generator_class, reassign=False )
# Otherwise define a new local variable. return self.add_local_reg(symbol, reg_type) else: # Assign to a previously defined variable. return self.lookup(symbol) elif lvalue.kind == GDEF: globals_dict = self.load_globals_dict() name = self.load_str(lvalue.name) return AssignmentTargetIndex(globals_dict, name) else: assert False, lvalue.kind elif isinstance(lvalue, IndexExpr): # Indexed assignment x[y] = e base = self.accept(lvalue.base) index = self.accept(lvalue.index) return AssignmentTargetIndex(base, index) elif isinstance(lvalue, MemberExpr): # Attribute assignment x.y = e can_borrow = self.is_native_attr_ref(lvalue) obj = self.accept(lvalue.expr, can_borrow=can_borrow) return AssignmentTargetAttr(obj, lvalue.name, can_borrow=can_borrow) elif isinstance(lvalue, TupleExpr): # Multiple assignment a, ..., b = e star_idx: int | None = None lvalues = [] for idx, item in enumerate(lvalue.items): targ = self.get_assignment_target(item) lvalues.append(targ) if isinstance(item, StarExpr): if star_idx is not None: self.error("Two starred expressions in assignment", line) star_idx = idx
return AssignmentTargetTuple(lvalues, star_idx)
elif isinstance(lvalue, StarExpr): return self.get_assignment_target(lvalue.expr)
assert False, "Unsupported lvalue: %r" % lvalue
def read( self, target: Value | AssignmentTarget, line: int = -1, can_borrow: bool = False ) -> Value: if isinstance(target, Value): return target if isinstance(target, AssignmentTargetRegister): return target.register if isinstance(target, AssignmentTargetIndex): reg = self.gen_method_call( target.base, "__getitem__", [target.index], target.type, line ) if reg is not None: return reg assert False, target.base.type if isinstance(target, AssignmentTargetAttr): if isinstance(target.obj.type, RInstance) and target.obj.type.class_ir.is_ext_class: borrow = can_borrow and target.can_borrow return self.add(GetAttr(target.obj, target.attr, line, borrow=borrow)) else: return self.py_get_attr(target.obj, target.attr, line)
assert False, "Unsupported lvalue: %r" % target
def assign(self, target: Register | AssignmentTarget, rvalue_reg: Value, line: int) -> None: if isinstance(target, Register): self.add(Assign(target, self.coerce_rvalue(rvalue_reg, target.type, line))) elif isinstance(target, AssignmentTargetRegister): rvalue_reg = self.coerce_rvalue(rvalue_reg, target.type, line) self.add(Assign(target.register, rvalue_reg)) elif isinstance(target, AssignmentTargetAttr): if isinstance(target.obj_type, RInstance): rvalue_reg = self.coerce_rvalue(rvalue_reg, target.type, line) self.add(SetAttr(target.obj, target.attr, rvalue_reg, line)) else: key = self.load_str(target.attr) boxed_reg = self.builder.box(rvalue_reg) self.primitive_op(py_setattr_op, [target.obj, key, boxed_reg], line) elif isinstance(target, AssignmentTargetIndex): target_reg2 = self.gen_method_call( target.base, "__setitem__", [target.index, rvalue_reg], None, line ) assert target_reg2 is not None, target.base.type elif isinstance(target, AssignmentTargetTuple): if isinstance(rvalue_reg.type, RTuple) and target.star_idx is None: rtypes = rvalue_reg.type.types assert len(rtypes) == len(target.items) for i in range(len(rtypes)): item_value = self.add(TupleGet(rvalue_reg, i, line)) self.assign(target.items[i], item_value, line) elif ( is_list_rprimitive(rvalue_reg.type) or is_tuple_rprimitive(rvalue_reg.type) ) and target.star_idx is None: self.process_sequence_assignment(target, rvalue_reg, line) else: self.process_iterator_tuple_assignment(target, rvalue_reg, line) else: assert False, "Unsupported assignment target"
def coerce_rvalue(self, rvalue: Value, rtype: RType, line: int) -> Value: if is_float_rprimitive(rtype) and is_tagged(rvalue.type): typename = rvalue.type.short_name() if typename == "short_int": typename = "int" self.error( "Incompatible value representations in assignment " + f'(expression has type "{typename}", variable has type "float")', line, ) return self.coerce(rvalue, rtype, line)
def process_sequence_assignment( self, target: AssignmentTargetTuple, rvalue: Value, line: int ) -> None: """Process assignment like 'x, y = s', where s is a variable-length list or tuple.""" # Check the length of sequence. expected_len = Integer(len(target.items), c_pyssize_t_rprimitive) self.builder.call_c(check_unpack_count_op, [rvalue, expected_len], line)
# Read sequence items. values = [] for i in range(len(target.items)): item = target.items[i] index = self.builder.load_int(i) if is_list_rprimitive(rvalue.type): item_value = self.call_c(list_get_item_unsafe_op, [rvalue, index], line) else: item_value = self.builder.gen_method_call( rvalue, "__getitem__", [index], item.type, line ) values.append(item_value)
# Assign sequence items to the target lvalues. for lvalue, value in zip(target.items, values): self.assign(lvalue, value, line)
def process_iterator_tuple_assignment_helper( self, litem: AssignmentTarget, ritem: Value, line: int ) -> None: error_block, ok_block = BasicBlock(), BasicBlock() self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR))
self.activate_block(error_block) self.add( RaiseStandardError(RaiseStandardError.VALUE_ERROR, "not enough values to unpack", line) ) self.add(Unreachable())
self.activate_block(ok_block) self.assign(litem, ritem, line)
def process_iterator_tuple_assignment( self, target: AssignmentTargetTuple, rvalue_reg: Value, line: int ) -> None: iterator = self.primitive_op(iter_op, [rvalue_reg], line)
# This may be the whole lvalue list if there is no starred value split_idx = target.star_idx if target.star_idx is not None else len(target.items)
# Assign values before the first starred value for litem in target.items[:split_idx]: ritem = self.call_c(next_op, [iterator], line) error_block, ok_block = BasicBlock(), BasicBlock() self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR))
self.activate_block(error_block) self.add( RaiseStandardError( RaiseStandardError.VALUE_ERROR, "not enough values to unpack", line ) ) self.add(Unreachable())
self.activate_block(ok_block)
self.assign(litem, ritem, line)
# Assign the starred value and all values after it if target.star_idx is not None: post_star_vals = target.items[split_idx + 1 :] iter_list = self.primitive_op(to_list, [iterator], line) iter_list_len = self.builtin_len(iter_list, line) post_star_len = Integer(len(post_star_vals)) condition = self.binary_op(post_star_len, iter_list_len, "<=", line)
error_block, ok_block = BasicBlock(), BasicBlock() self.add(Branch(condition, ok_block, error_block, Branch.BOOL))
self.activate_block(error_block) self.add( RaiseStandardError( RaiseStandardError.VALUE_ERROR, "not enough values to unpack", line ) ) self.add(Unreachable())
self.activate_block(ok_block)
for litem in reversed(post_star_vals): ritem = self.primitive_op(list_pop_last, [iter_list], line) self.assign(litem, ritem, line)
# Assign the starred value self.assign(target.items[target.star_idx], iter_list, line)
# There is no starred value, so check if there are extra values in rhs that # have not been assigned. else: extra = self.call_c(next_op, [iterator], line) error_block, ok_block = BasicBlock(), BasicBlock() self.add(Branch(extra, ok_block, error_block, Branch.IS_ERROR))
self.activate_block(error_block) self.add( RaiseStandardError( RaiseStandardError.VALUE_ERROR, "too many values to unpack", line ) ) self.add(Unreachable())
self.activate_block(ok_block)
def push_loop_stack(self, continue_block: BasicBlock, break_block: BasicBlock) -> None: self.nonlocal_control.append( LoopNonlocalControl(self.nonlocal_control[-1], continue_block, break_block) )
def pop_loop_stack(self) -> None: self.nonlocal_control.pop()
def make_spill_target(self, type: RType) -> AssignmentTarget: """Moves a given Value instance into the generator class' environment class.""" name = f"{TEMP_ATTR_NAME}{self.temp_counter}" self.temp_counter += 1 target = self.add_var_to_env_class(Var(name), type, self.fn_info.generator_class) return target
def spill(self, value: Value) -> AssignmentTarget: """Moves a given Value instance into the generator class' environment class.""" target = self.make_spill_target(value.type) # Shouldn't be able to fail, so -1 for line self.assign(target, value, -1) return target
def maybe_spill(self, value: Value) -> Value | AssignmentTarget: """ Moves a given Value instance into the environment class for generator functions. For non-generator functions, leaves the Value instance as it is.
Returns an AssignmentTarget associated with the Value for generator functions and the original Value itself for non-generator functions. """ if self.fn_info.is_generator: return self.spill(value) return value
def maybe_spill_assignable(self, value: Value) -> Register | AssignmentTarget: """ Moves a given Value instance into the environment class for generator functions. For non-generator functions, allocate a temporary Register.
Returns an AssignmentTarget associated with the Value for generator functions and an assignable Register for non-generator functions. """ if self.fn_info.is_generator: return self.spill(value)
if isinstance(value, Register): return value
# Allocate a temporary register for the assignable value. reg = Register(value.type) self.assign(reg, value, -1) return reg
def extract_int(self, e: Expression) -> int | None: if isinstance(e, IntExpr): return e.value elif isinstance(e, UnaryExpr) and e.op == "-" and isinstance(e.expr, IntExpr): return -e.expr.value else: return None
def get_sequence_type(self, expr: Expression) -> RType: return self.get_sequence_type_from_type(self.types[expr])
def get_sequence_type_from_type(self, target_type: Type) -> RType: target_type = get_proper_type(target_type) if isinstance(target_type, UnionType): return RUnion.make_simplified_union( [self.get_sequence_type_from_type(item) for item in target_type.items] ) assert isinstance(target_type, Instance), target_type if target_type.type.fullname == "builtins.str": return str_rprimitive else: return self.type_to_rtype(target_type.args[0])
def get_dict_base_type(self, expr: Expression) -> list[Instance]: """Find dict type of a dict-like expression.
This is useful for dict subclasses like SymbolTable. """ target_type = get_proper_type(self.types[expr]) if isinstance(target_type, UnionType): types = [get_proper_type(item) for item in target_type.items] else: types = [target_type]
dict_types = [] for t in types: if isinstance(t, TypedDictType): t = t.fallback dict_base = next(base for base in t.type.mro if base.fullname == "typing.Mapping") else: assert isinstance(t, Instance), t dict_base = next(base for base in t.type.mro if base.fullname == "builtins.dict") dict_types.append(map_instance_to_supertype(t, dict_base)) return dict_types
def get_dict_key_type(self, expr: Expression) -> RType: dict_base_types = self.get_dict_base_type(expr) if len(dict_base_types) == 1: return self.type_to_rtype(dict_base_types[0].args[0]) else: rtypes = [self.type_to_rtype(t.args[0]) for t in dict_base_types] return RUnion.make_simplified_union(rtypes)
def get_dict_value_type(self, expr: Expression) -> RType: dict_base_types = self.get_dict_base_type(expr) if len(dict_base_types) == 1: return self.type_to_rtype(dict_base_types[0].args[1]) else: rtypes = [self.type_to_rtype(t.args[1]) for t in dict_base_types] return RUnion.make_simplified_union(rtypes)
def get_dict_item_type(self, expr: Expression) -> RType: key_type = self.get_dict_key_type(expr) value_type = self.get_dict_value_type(expr) return RTuple([key_type, value_type])
def _analyze_iterable_item_type(self, expr: Expression) -> Type: """Return the item type given by 'expr' in an iterable context.""" # This logic is copied from mypy's TypeChecker.analyze_iterable_item_type. if expr not in self.types: # Mypy thinks this is unreachable. iterable: ProperType = AnyType(TypeOfAny.from_error) else: iterable = get_proper_type(self.types[expr]) echk = self.graph[self.module_name].type_checker().expr_checker iterator = echk.check_method_call_by_name("__iter__", iterable, [], [], expr)[0]
from mypy.join import join_types
if isinstance(iterable, TupleType): joined: Type = UninhabitedType() for item in iterable.items: joined = join_types(joined, item) return joined else: # Non-tuple iterable. return echk.check_method_call_by_name("__next__", iterator, [], [], expr)[0]
def is_native_module(self, module: str) -> bool: """Is the given module one compiled by mypyc?""" return self.mapper.is_native_module(module)
def is_native_ref_expr(self, expr: RefExpr) -> bool: return self.mapper.is_native_ref_expr(expr)
def is_native_module_ref_expr(self, expr: RefExpr) -> bool: return self.mapper.is_native_module_ref_expr(expr)
def is_synthetic_type(self, typ: TypeInfo) -> bool: """Is a type something other than just a class we've created?""" return typ.is_named_tuple or typ.is_newtype or typ.typeddict_type is not None
def get_final_ref(self, expr: MemberExpr) -> tuple[str, Var, bool] | None: """Check if `expr` is a final attribute.
This needs to be done differently for class and module attributes to correctly determine fully qualified name. Return a tuple that consists of the qualified name, the corresponding Var node, and a flag indicating whether the final name was defined in a compiled module. Return None if `expr` does not refer to a final attribute. """ final_var = None if isinstance(expr.expr, RefExpr) and isinstance(expr.expr.node, TypeInfo): # a class attribute sym = expr.expr.node.get(expr.name) if sym and isinstance(sym.node, Var): # Enum attribute are treated as final since they are added to the global cache expr_fullname = expr.expr.node.bases[0].type.fullname is_final = sym.node.is_final or expr_fullname == "enum.Enum" if is_final: final_var = sym.node fullname = f"{sym.node.info.fullname}.{final_var.name}" native = self.is_native_module(expr.expr.node.module_name) elif self.is_module_member_expr(expr): # a module attribute if isinstance(expr.node, Var) and expr.node.is_final: final_var = expr.node fullname = expr.node.fullname native = self.is_native_ref_expr(expr) if final_var is not None: return fullname, final_var, native return None
def emit_load_final( self, final_var: Var, fullname: str, name: str, native: bool, typ: Type, line: int ) -> Value | None: """Emit code for loading value of a final name (if possible).
Args: final_var: Var corresponding to the final name fullname: its qualified name name: shorter name to show in errors native: whether the name was defined in a compiled module typ: its type line: line number where loading occurs """ if final_var.final_value is not None: # this is safe even for non-native names return self.load_literal_value(final_var.final_value) elif native and module_prefix(self.graph, fullname): return self.load_final_static(fullname, self.mapper.type_to_rtype(typ), line, name) else: return None
def is_module_member_expr(self, expr: MemberExpr) -> bool: return isinstance(expr.expr, RefExpr) and isinstance(expr.expr.node, MypyFile)
def call_refexpr_with_args( self, expr: CallExpr, callee: RefExpr, arg_values: list[Value] ) -> Value: # Handle data-driven special-cased primitive call ops. if callee.fullname and expr.arg_kinds == [ARG_POS] * len(arg_values): fullname = get_call_target_fullname(callee) primitive_candidates = function_ops.get(fullname, []) target = self.builder.matching_primitive_op( primitive_candidates, arg_values, expr.line, self.node_type(expr) ) if target: return target
# Standard native call if signature and fullname are good and all arguments are positional # or named. callee_node = callee.node if isinstance(callee_node, OverloadedFuncDef): callee_node = callee_node.impl # TODO: use native calls for any decorated functions which have all their decorators # removed, not just singledispatch functions (which we don't do now just in case those # decorated functions are callable classes or cannot be called without the python API for # some other reason) if ( isinstance(callee_node, Decorator) and callee_node.func not in self.fdefs_to_decorators and callee_node.func in self.singledispatch_impls ): callee_node = callee_node.func if ( callee_node is not None and callee.fullname and callee_node in self.mapper.func_to_decl and all(kind in (ARG_POS, ARG_NAMED) for kind in expr.arg_kinds) ): decl = self.mapper.func_to_decl[callee_node] return self.builder.call(decl, arg_values, expr.arg_kinds, expr.arg_names, expr.line)
# Fall back to a Python call function = self.accept(callee) return self.py_call( function, arg_values, expr.line, arg_kinds=expr.arg_kinds, arg_names=expr.arg_names )
def shortcircuit_expr(self, expr: OpExpr) -> Value: return self.builder.shortcircuit_helper( expr.op, self.node_type(expr), lambda: self.accept(expr.left), lambda: self.accept(expr.right), expr.line, )
# Basic helpers
def flatten_classes(self, arg: RefExpr | TupleExpr) -> list[ClassIR] | None: """Flatten classes in isinstance(obj, (A, (B, C))).
If at least one item is not a reference to a native class, return None. """ if isinstance(arg, RefExpr): if isinstance(arg.node, TypeInfo) and self.is_native_module_ref_expr(arg): ir = self.mapper.type_to_ir.get(arg.node) if ir: return [ir] return None else: res: list[ClassIR] = [] for item in arg.items: if isinstance(item, (RefExpr, TupleExpr)): item_part = self.flatten_classes(item) if item_part is None: return None res.extend(item_part) else: return None return res
def enter(self, fn_info: FuncInfo | str = "") -> None: if isinstance(fn_info, str): fn_info = FuncInfo(name=fn_info) self.builder = LowLevelIRBuilder(self.errors, self.options) self.builder.set_module(self.module_name, self.module_path) self.builders.append(self.builder) self.symtables.append({}) self.runtime_args.append([]) self.fn_info = fn_info self.fn_infos.append(self.fn_info) self.ret_types.append(none_rprimitive) if fn_info.is_generator: self.nonlocal_control.append(GeneratorNonlocalControl()) else: self.nonlocal_control.append(BaseNonlocalControl()) self.activate_block(BasicBlock())
def leave(self) -> tuple[list[Register], list[RuntimeArg], list[BasicBlock], RType, FuncInfo]: builder = self.builders.pop() self.symtables.pop() runtime_args = self.runtime_args.pop() ret_type = self.ret_types.pop() fn_info = self.fn_infos.pop() self.nonlocal_control.pop() self.builder = self.builders[-1] self.fn_info = self.fn_infos[-1] return builder.args, runtime_args, builder.blocks, ret_type, fn_info
@contextmanager def enter_method( self, class_ir: ClassIR, name: str, ret_type: RType, fn_info: FuncInfo | str = "", self_type: RType | None = None, ) -> Iterator[None]: """Generate IR for a method.
If the method takes arguments, you should immediately afterwards call add_argument() for each non-self argument (self is created implicitly).
Args: class_ir: Add method to this class name: Short name of the method ret_type: Return type of the method fn_info: Optionally, additional information about the method self_type: If not None, override default type of the implicit 'self' argument (by default, derive type from class_ir) """ self.enter(fn_info) self.function_name_stack.append(name) self.class_ir_stack.append(class_ir) self.ret_types[-1] = ret_type if self_type is None: self_type = RInstance(class_ir) self.add_argument(SELF_NAME, self_type) try: yield finally: arg_regs, args, blocks, ret_type, fn_info = self.leave() sig = FuncSignature(args, ret_type) name = self.function_name_stack.pop() class_ir = self.class_ir_stack.pop() decl = FuncDecl(name, class_ir.name, self.module_name, sig) ir = FuncIR(decl, arg_regs, blocks) class_ir.methods[name] = ir class_ir.method_decls[name] = ir.decl self.functions.append(ir)
def add_argument(self, var: str | Var, typ: RType, kind: ArgKind = ARG_POS) -> Register: """Declare an argument in the current function.
You should use this instead of directly calling add_local() in new code. """ if isinstance(var, str): var = Var(var) reg = self.add_local(var, typ, is_arg=True) self.runtime_args[-1].append(RuntimeArg(var.name, typ, kind)) return reg
def lookup(self, symbol: SymbolNode) -> SymbolTarget: return self.symtables[-1][symbol]
def add_local(self, symbol: SymbolNode, typ: RType, is_arg: bool = False) -> Register: """Add register that represents a symbol to the symbol table.
Args: is_arg: is this a function argument """ assert isinstance(symbol, SymbolNode) reg = Register( typ, remangle_redefinition_name(symbol.name), is_arg=is_arg, line=symbol.line ) self.symtables[-1][symbol] = AssignmentTargetRegister(reg) if is_arg: self.builder.args.append(reg) return reg
def add_local_reg( self, symbol: SymbolNode, typ: RType, is_arg: bool = False ) -> AssignmentTargetRegister: """Like add_local, but return an assignment target instead of value.""" self.add_local(symbol, typ, is_arg) target = self.symtables[-1][symbol] assert isinstance(target, AssignmentTargetRegister) return target
def add_self_to_env(self, cls: ClassIR) -> AssignmentTargetRegister: """Low-level function that adds a 'self' argument.
This is only useful if using enter() instead of enter_method(). """ return self.add_local_reg(Var(SELF_NAME), RInstance(cls), is_arg=True)
def add_target(self, symbol: SymbolNode, target: SymbolTarget) -> SymbolTarget: self.symtables[-1][symbol] = target return target
def type_to_rtype(self, typ: Type | None) -> RType: return self.mapper.type_to_rtype(typ)
def node_type(self, node: Expression) -> RType: if isinstance(node, IntExpr): # TODO: Don't special case IntExpr return int_rprimitive if node not in self.types: return object_rprimitive mypy_type = self.types[node] return self.type_to_rtype(mypy_type)
def add_var_to_env_class( self, var: SymbolNode, rtype: RType, base: FuncInfo | ImplicitClass, reassign: bool = False ) -> AssignmentTarget: # First, define the variable name as an attribute of the environment class, and then # construct a target for that attribute. name = remangle_redefinition_name(var.name) self.fn_info.env_class.attributes[name] = rtype attr_target = AssignmentTargetAttr(base.curr_env_reg, name)
if reassign: # Read the local definition of the variable, and set the corresponding attribute of # the environment class' variable to be that value. reg = self.read(self.lookup(var), self.fn_info.fitem.line) self.add(SetAttr(base.curr_env_reg, name, reg, self.fn_info.fitem.line))
# Override the local definition of the variable to instead point at the variable in # the environment class. return self.add_target(var, attr_target)
def is_builtin_ref_expr(self, expr: RefExpr) -> bool: assert expr.node, "RefExpr not resolved" return "." in expr.node.fullname and expr.node.fullname.split(".")[0] == "builtins"
def load_global(self, expr: NameExpr) -> Value: """Loads a Python-level global.
This takes a NameExpr and uses its name as a key to retrieve the corresponding PyObject * from the _globals dictionary in the C-generated code. """ # If the global is from 'builtins', turn it into a module attr load instead if self.is_builtin_ref_expr(expr): assert expr.node, "RefExpr not resolved" return self.load_module_attr_by_fullname(expr.node.fullname, expr.line) if ( self.is_native_module_ref_expr(expr) and isinstance(expr.node, TypeInfo) and not self.is_synthetic_type(expr.node) ): assert expr.fullname return self.load_native_type_object(expr.fullname) return self.load_global_str(expr.name, expr.line)
def load_global_str(self, name: str, line: int) -> Value: _globals = self.load_globals_dict() reg = self.load_str(name) return self.primitive_op(dict_get_item_op, [_globals, reg], line)
def load_globals_dict(self) -> Value: return self.add(LoadStatic(dict_rprimitive, "globals", self.module_name))
def load_module_attr_by_fullname(self, fullname: str, line: int) -> Value: module, _, name = fullname.rpartition(".") left = self.load_module(module) return self.py_get_attr(left, name, line)
def is_native_attr_ref(self, expr: MemberExpr) -> bool: """Is expr a direct reference to a native (struct) attribute of an instance?""" obj_rtype = self.node_type(expr.expr) return ( isinstance(obj_rtype, RInstance) and obj_rtype.class_ir.is_ext_class and obj_rtype.class_ir.has_attr(expr.name) and not obj_rtype.class_ir.get_method(expr.name) )
def mark_block_unreachable(self) -> None: """Mark statements in the innermost block being processed as unreachable.
This should be called after a statement that unconditionally leaves the block, such as 'break' or 'return'. """ self.block_reachable_stack[-1] = False
# Lacks a good type because there wasn't a reasonable type in 3.5 :( def catch_errors(self, line: int) -> Any: return catch_errors(self.module_path, line)
def warning(self, msg: str, line: int) -> None: self.errors.warning(msg, self.module_path, line)
def error(self, msg: str, line: int) -> None: self.errors.error(msg, self.module_path, line)
def note(self, msg: str, line: int) -> None: self.errors.note(msg, self.module_path, line)
def add_function(self, func_ir: FuncIR, line: int) -> None: name = (func_ir.class_name, func_ir.name) if name in self.function_names: self.error(f'Duplicate definition of "{name[1]}" not supported by mypyc', line) return self.function_names.add(name) self.functions.append(func_ir)
def gen_arg_defaults(builder: IRBuilder) -> None: """Generate blocks for arguments that have default values.
If the passed value is an error value, then assign the default value to the argument. """ fitem = builder.fn_info.fitem nb = 0 for arg in fitem.arguments: if arg.initializer: target = builder.lookup(arg.variable)
def get_default() -> Value: assert arg.initializer is not None
# If it is constant, don't bother storing it if is_constant(arg.initializer): return builder.accept(arg.initializer)
# Because gen_arg_defaults runs before calculate_arg_defaults, we # add the static/attribute to final_names/the class here. elif not builder.fn_info.is_nested: name = fitem.fullname + "." + arg.variable.name builder.final_names.append((name, target.type)) return builder.add(LoadStatic(target.type, name, builder.module_name)) else: name = arg.variable.name builder.fn_info.callable_class.ir.attributes[name] = target.type return builder.add( GetAttr(builder.fn_info.callable_class.self_reg, name, arg.line) )
assert isinstance(target, AssignmentTargetRegister) reg = target.register if not reg.type.error_overlap: builder.assign_if_null(target.register, get_default, arg.initializer.line) else: builder.assign_if_bitmap_unset( target.register, get_default, nb, arg.initializer.line ) nb += 1
def remangle_redefinition_name(name: str) -> str: """Remangle names produced by mypy when allow-redefinition is used and a name is used with multiple types within a single block.
We only need to do this for locals, because the name is used as the name of the register; for globals, the name itself is stored in a register for the purpose of doing dict lookups. """ return name.replace("'", "__redef__")
def get_call_target_fullname(ref: RefExpr) -> str: if isinstance(ref.node, TypeAlias): # Resolve simple type aliases. In calls they evaluate to the type they point to. target = get_proper_type(ref.node.target) if isinstance(target, Instance): return target.type.fullname return ref.fullname
def create_type_params( builder: IRBuilder, typing_mod: Value, type_args: list[TypeParam], line: int) -> list[Value]: """Create objects representing various kinds of Python 3.12 type parameters.
The "typing_mod" argument is the "_typing" module object. The type objects are looked up from it.
The returned list has one item for each "type_args" item, in the same order. Each item is either a TypeVar, TypeVarTuple or ParamSpec instance. """ tvs = [] type_var_imported: Value | None = None for type_param in type_args: if type_param.kind == TYPE_VAR_KIND: if type_var_imported: # Reuse previously imported value as a minor optimization tvt = type_var_imported else: tvt = builder.py_get_attr(typing_mod, "TypeVar", line) type_var_imported = tvt elif type_param.kind == TYPE_VAR_TUPLE_KIND: tvt = builder.py_get_attr(typing_mod, "TypeVarTuple", line) else: assert type_param.kind == PARAM_SPEC_KIND tvt = builder.py_get_attr(typing_mod, "ParamSpec", line) if type_param.kind != TYPE_VAR_TUPLE_KIND: # To match runtime semantics, pass infer_variance=True tv = builder.py_call( tvt, [builder.load_str(type_param.name), builder.true()], line, arg_kinds=[ARG_POS, ARG_NAMED], arg_names=[None, "infer_variance"], ) else: tv = builder.py_call(tvt, [builder.load_str(type_param.name)], line) builder.init_type_var(tv, type_param.name, line) tvs.append(tv) return tvs123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""Primitive bytes ops."""
from __future__ import annotations
from mypyc.ir.ops import ERR_MAGICfrom mypyc.ir.rtypes import ( RUnion, bytes_rprimitive, c_int_rprimitive, c_pyssize_t_rprimitive, dict_rprimitive, int_rprimitive, list_rprimitive, object_rprimitive, str_rprimitive,)from mypyc.primitives.registry import ( ERR_NEG_INT, binary_op, custom_op, function_op, load_address_op, method_op,)
# Get the 'bytes' type object.load_address_op(name="builtins.bytes", type=object_rprimitive, src="PyBytes_Type")
# bytes(obj)function_op( name="builtins.bytes", arg_types=[RUnion([list_rprimitive, dict_rprimitive, str_rprimitive])], return_type=bytes_rprimitive, c_function_name="PyBytes_FromObject", error_kind=ERR_MAGIC,)
# bytearray(obj)function_op( name="builtins.bytearray", arg_types=[object_rprimitive], return_type=bytes_rprimitive, c_function_name="PyByteArray_FromObject", error_kind=ERR_MAGIC,)
# bytes ==/!= (return -1/0/1)bytes_compare = custom_op( arg_types=[bytes_rprimitive, bytes_rprimitive], return_type=c_int_rprimitive, c_function_name="CPyBytes_Compare", error_kind=ERR_NEG_INT,)
# bytes + bytes# bytearray + bytearraybinary_op( name="+", arg_types=[bytes_rprimitive, bytes_rprimitive], return_type=bytes_rprimitive, c_function_name="CPyBytes_Concat", error_kind=ERR_MAGIC, steals=[True, False],)
# bytes[begin:end]bytes_slice_op = custom_op( arg_types=[bytes_rprimitive, int_rprimitive, int_rprimitive], return_type=bytes_rprimitive, c_function_name="CPyBytes_GetSlice", error_kind=ERR_MAGIC,)
# bytes[index]# bytearray[index]method_op( name="__getitem__", arg_types=[bytes_rprimitive, int_rprimitive], return_type=int_rprimitive, c_function_name="CPyBytes_GetItem", error_kind=ERR_MAGIC,)
# bytes.join(obj)method_op( name="join", arg_types=[bytes_rprimitive, object_rprimitive], return_type=bytes_rprimitive, c_function_name="CPyBytes_Join", error_kind=ERR_MAGIC,)
# Join bytes objects and return a new bytes.# The first argument is the total number of the following bytes.bytes_build_op = custom_op( arg_types=[c_pyssize_t_rprimitive], return_type=bytes_rprimitive, c_function_name="CPyBytes_Build", error_kind=ERR_MAGIC, var_arg_type=bytes_rprimitive,)
function_op( name="builtins.ord", arg_types=[bytes_rprimitive], return_type=int_rprimitive, c_function_name="CPyBytes_Ord", error_kind=ERR_MAGIC,)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325"""Primitive dict ops."""
from __future__ import annotations
from mypyc.ir.ops import ERR_FALSE, ERR_MAGIC, ERR_NEVERfrom mypyc.ir.rtypes import ( bit_rprimitive, bool_rprimitive, c_int_rprimitive, c_pyssize_t_rprimitive, dict_next_rtuple_pair, dict_next_rtuple_single, dict_rprimitive, int_rprimitive, list_rprimitive, object_rprimitive,)from mypyc.primitives.registry import ( ERR_NEG_INT, binary_op, custom_op, function_op, load_address_op, method_op,)
# Get the 'dict' type object.load_address_op(name="builtins.dict", type=object_rprimitive, src="PyDict_Type")
# Construct an empty dictionary via dict().function_op( name="builtins.dict", arg_types=[], return_type=dict_rprimitive, c_function_name="PyDict_New", error_kind=ERR_MAGIC,)
# Construct an empty dictionary.dict_new_op = custom_op( arg_types=[], return_type=dict_rprimitive, c_function_name="PyDict_New", error_kind=ERR_MAGIC)
# Construct a dictionary from keys and values.# Positional argument is the number of key-value pairs# Variable arguments are (key1, value1, ..., keyN, valueN).dict_build_op = custom_op( arg_types=[c_pyssize_t_rprimitive], return_type=dict_rprimitive, c_function_name="CPyDict_Build", error_kind=ERR_MAGIC, var_arg_type=object_rprimitive,)
# Construct a dictionary from another dictionary.function_op( name="builtins.dict", arg_types=[dict_rprimitive], return_type=dict_rprimitive, c_function_name="PyDict_Copy", error_kind=ERR_MAGIC, priority=2,)
# Generic one-argument dict constructor: dict(obj)dict_copy = function_op( name="builtins.dict", arg_types=[object_rprimitive], return_type=dict_rprimitive, c_function_name="CPyDict_FromAny", error_kind=ERR_MAGIC,)
# dict[key]dict_get_item_op = method_op( name="__getitem__", arg_types=[dict_rprimitive, object_rprimitive], return_type=object_rprimitive, c_function_name="CPyDict_GetItem", error_kind=ERR_MAGIC,)
# dict[key] = valuedict_set_item_op = method_op( name="__setitem__", arg_types=[dict_rprimitive, object_rprimitive, object_rprimitive], return_type=c_int_rprimitive, c_function_name="CPyDict_SetItem", error_kind=ERR_NEG_INT,)
# key in dictbinary_op( name="in", arg_types=[object_rprimitive, dict_rprimitive], return_type=c_int_rprimitive, c_function_name="PyDict_Contains", error_kind=ERR_NEG_INT, truncated_type=bool_rprimitive, ordering=[1, 0],)
# dict1.update(dict2)dict_update_op = method_op( name="update", arg_types=[dict_rprimitive, dict_rprimitive], return_type=c_int_rprimitive, c_function_name="CPyDict_Update", error_kind=ERR_NEG_INT, priority=2,)
# Operation used for **value in dict displays.# This is mostly like dict.update(obj), but has customized error handling.dict_update_in_display_op = custom_op( arg_types=[dict_rprimitive, object_rprimitive], return_type=c_int_rprimitive, c_function_name="CPyDict_UpdateInDisplay", error_kind=ERR_NEG_INT,)
# dict.update(obj)method_op( name="update", arg_types=[dict_rprimitive, object_rprimitive], return_type=c_int_rprimitive, c_function_name="CPyDict_UpdateFromAny", error_kind=ERR_NEG_INT,)
# dict.get(key, default)method_op( name="get", arg_types=[dict_rprimitive, object_rprimitive, object_rprimitive], return_type=object_rprimitive, c_function_name="CPyDict_Get", error_kind=ERR_MAGIC,)
# dict.get(key)dict_get_method_with_none = method_op( name="get", arg_types=[dict_rprimitive, object_rprimitive], return_type=object_rprimitive, c_function_name="CPyDict_GetWithNone", error_kind=ERR_MAGIC,)
# dict.setdefault(key, default)dict_setdefault_op = method_op( name="setdefault", arg_types=[dict_rprimitive, object_rprimitive, object_rprimitive], return_type=object_rprimitive, c_function_name="CPyDict_SetDefault", error_kind=ERR_MAGIC,)
# dict.setdefault(key)method_op( name="setdefault", arg_types=[dict_rprimitive, object_rprimitive], return_type=object_rprimitive, c_function_name="CPyDict_SetDefaultWithNone", error_kind=ERR_MAGIC,)
# dict.setdefault(key, empty tuple/list/set)# The third argument marks the data type of the second argument.# 1: list 2: dict 3: set# Other number would lead to an error.dict_setdefault_spec_init_op = custom_op( arg_types=[dict_rprimitive, object_rprimitive, c_int_rprimitive], return_type=object_rprimitive, c_function_name="CPyDict_SetDefaultWithEmptyDatatype", error_kind=ERR_MAGIC,)
# dict.keys()method_op( name="keys", arg_types=[dict_rprimitive], return_type=object_rprimitive, c_function_name="CPyDict_KeysView", error_kind=ERR_MAGIC,)
# dict.values()method_op( name="values", arg_types=[dict_rprimitive], return_type=object_rprimitive, c_function_name="CPyDict_ValuesView", error_kind=ERR_MAGIC,)
# dict.items()method_op( name="items", arg_types=[dict_rprimitive], return_type=object_rprimitive, c_function_name="CPyDict_ItemsView", error_kind=ERR_MAGIC,)
# dict.clear()method_op( name="clear", arg_types=[dict_rprimitive], return_type=bit_rprimitive, c_function_name="CPyDict_Clear", error_kind=ERR_FALSE,)
# dict.copy()method_op( name="copy", arg_types=[dict_rprimitive], return_type=dict_rprimitive, c_function_name="CPyDict_Copy", error_kind=ERR_MAGIC,)
# list(dict.keys())dict_keys_op = custom_op( arg_types=[dict_rprimitive], return_type=list_rprimitive, c_function_name="CPyDict_Keys", error_kind=ERR_MAGIC,)
# list(dict.values())dict_values_op = custom_op( arg_types=[dict_rprimitive], return_type=list_rprimitive, c_function_name="CPyDict_Values", error_kind=ERR_MAGIC,)
# list(dict.items())dict_items_op = custom_op( arg_types=[dict_rprimitive], return_type=list_rprimitive, c_function_name="CPyDict_Items", error_kind=ERR_MAGIC,)
# PyDict_Next() fast iterationdict_key_iter_op = custom_op( arg_types=[dict_rprimitive], return_type=object_rprimitive, c_function_name="CPyDict_GetKeysIter", error_kind=ERR_MAGIC,)
dict_value_iter_op = custom_op( arg_types=[dict_rprimitive], return_type=object_rprimitive, c_function_name="CPyDict_GetValuesIter", error_kind=ERR_MAGIC,)
dict_item_iter_op = custom_op( arg_types=[dict_rprimitive], return_type=object_rprimitive, c_function_name="CPyDict_GetItemsIter", error_kind=ERR_MAGIC,)
dict_next_key_op = custom_op( arg_types=[object_rprimitive, int_rprimitive], return_type=dict_next_rtuple_single, c_function_name="CPyDict_NextKey", error_kind=ERR_NEVER,)
dict_next_value_op = custom_op( arg_types=[object_rprimitive, int_rprimitive], return_type=dict_next_rtuple_single, c_function_name="CPyDict_NextValue", error_kind=ERR_NEVER,)
dict_next_item_op = custom_op( arg_types=[object_rprimitive, int_rprimitive], return_type=dict_next_rtuple_pair, c_function_name="CPyDict_NextItem", error_kind=ERR_NEVER,)
# check that len(dict) == const during iterationdict_check_size_op = custom_op( arg_types=[dict_rprimitive, int_rprimitive], return_type=bit_rprimitive, c_function_name="CPyDict_CheckSize", error_kind=ERR_FALSE,)
dict_ssize_t_size_op = custom_op( arg_types=[dict_rprimitive], return_type=c_pyssize_t_rprimitive, c_function_name="PyDict_Size", error_kind=ERR_NEVER,)
# Delete an item from a dictdict_del_item = custom_op( arg_types=[object_rprimitive, object_rprimitive], return_type=c_int_rprimitive, c_function_name="PyDict_DelItem", error_kind=ERR_NEG_INT,)
supports_mapping_protocol = custom_op( arg_types=[object_rprimitive], return_type=c_int_rprimitive, c_function_name="CPyMapping_Check", error_kind=ERR_NEVER,)
mapping_has_key = custom_op( arg_types=[object_rprimitive, object_rprimitive], return_type=c_int_rprimitive, c_function_name="PyMapping_HasKey", error_kind=ERR_NEVER,)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101"""Exception-related primitive ops."""
from __future__ import annotations
from mypyc.ir.ops import ERR_ALWAYS, ERR_FALSE, ERR_NEVERfrom mypyc.ir.rtypes import bit_rprimitive, exc_rtuple, object_rprimitive, void_rtypefrom mypyc.primitives.registry import custom_op
# If the argument is a class, raise an instance of the class. Otherwise, assume# that the argument is an exception object, and raise it.raise_exception_op = custom_op( arg_types=[object_rprimitive], return_type=void_rtype, c_function_name="CPy_Raise", error_kind=ERR_ALWAYS,)
# Raise StopIteration exception with the specified value (which can be NULL).set_stop_iteration_value = custom_op( arg_types=[object_rprimitive], return_type=void_rtype, c_function_name="CPyGen_SetStopIterationValue", error_kind=ERR_ALWAYS,)
# Raise exception with traceback.# Arguments are (exception type, exception value, traceback).raise_exception_with_tb_op = custom_op( arg_types=[object_rprimitive, object_rprimitive, object_rprimitive], return_type=void_rtype, c_function_name="CPyErr_SetObjectAndTraceback", error_kind=ERR_ALWAYS,)
# Reraise the currently raised exception.reraise_exception_op = custom_op( arg_types=[], return_type=void_rtype, c_function_name="CPy_Reraise", error_kind=ERR_ALWAYS)
# Propagate exception if the CPython error indicator is set (an exception was raised).no_err_occurred_op = custom_op( arg_types=[], return_type=bit_rprimitive, c_function_name="CPy_NoErrOccured", error_kind=ERR_FALSE,)
err_occurred_op = custom_op( arg_types=[], return_type=object_rprimitive, c_function_name="PyErr_Occurred", error_kind=ERR_NEVER, is_borrowed=True,)
# Keep propagating a raised exception by unconditionally giving an error value.# This doesn't actually raise an exception.keep_propagating_op = custom_op( arg_types=[], return_type=bit_rprimitive, c_function_name="CPy_KeepPropagating", error_kind=ERR_FALSE,)
# Catches a propagating exception and makes it the "currently# handled exception" (by sticking it into sys.exc_info()). Returns the# exception that was previously being handled, which must be restored# later.error_catch_op = custom_op( arg_types=[], return_type=exc_rtuple, c_function_name="CPy_CatchError", error_kind=ERR_NEVER)
# Restore an old "currently handled exception" returned from.# error_catch (by sticking it into sys.exc_info())restore_exc_info_op = custom_op( arg_types=[exc_rtuple], return_type=void_rtype, c_function_name="CPy_RestoreExcInfo", error_kind=ERR_NEVER,)
# Checks whether the exception currently being handled matches a particular type.exc_matches_op = custom_op( arg_types=[object_rprimitive], return_type=bit_rprimitive, c_function_name="CPy_ExceptionMatches", error_kind=ERR_NEVER,)
# Get the value of the exception currently being handled.get_exc_value_op = custom_op( arg_types=[], return_type=object_rprimitive, c_function_name="CPy_GetExcValue", error_kind=ERR_NEVER,)
# Get exception info (exception type, exception instance, traceback object).get_exc_info_op = custom_op( arg_types=[], return_type=exc_rtuple, c_function_name="CPy_GetExcInfo", error_kind=ERR_NEVER)openflamingo/lib/python3.10/site-packages/mypyc/doc/MakefileAdded+20
openflamingo/lib/python3.10/site-packages/mypyc/doc/__pycache__/conf.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/mypyc/doc/bool_operations.rstAdded+27
openflamingo/lib/python3.10/site-packages/mypyc/doc/bytes_operations.rstAdded+46
openflamingo/lib/python3.10/site-packages/mypyc/doc/compilation_units.rstAdded+20
openflamingo/lib/python3.10/site-packages/mypyc/doc/conf.pyAdded+59
openflamingo/lib/python3.10/site-packages/mypyc/doc/cpython-timings.mdAdded+25
openflamingo/lib/python3.10/site-packages/mypyc/doc/dev-intro.mdAdded+552
openflamingo/lib/python3.10/site-packages/mypyc/doc/dict_operations.rstAdded+59
openflamingo/lib/python3.10/site-packages/mypyc/doc/differences_from_python.rstAdded+332
openflamingo/lib/python3.10/site-packages/mypyc/doc/float_operations.rstAdded+50
openflamingo/lib/python3.10/site-packages/mypyc/doc/future.mdAdded+42
openflamingo/lib/python3.10/site-packages/mypyc/doc/getting_started.rstAdded+240
openflamingo/lib/python3.10/site-packages/mypyc/doc/index.rstAdded+62
openflamingo/lib/python3.10/site-packages/mypyc/doc/int_operations.rstAdded+162
openflamingo/lib/python3.10/site-packages/mypyc/doc/introduction.rstAdded+150
openflamingo/lib/python3.10/site-packages/mypyc/doc/list_operations.rstAdded+65
openflamingo/lib/python3.10/site-packages/mypyc/doc/native_classes.rstAdded+206
openflamingo/lib/python3.10/site-packages/mypyc/doc/native_operations.rstAdded+55
openflamingo/lib/python3.10/site-packages/mypyc/doc/performance_tips_and_tricks.rstAdded+244
openflamingo/lib/python3.10/site-packages/mypyc/doc/set_operations.rstAdded+47
openflamingo/lib/python3.10/site-packages/mypyc/doc/str_operations.rstAdded+59
openflamingo/lib/python3.10/site-packages/mypyc/doc/using_type_annotations.rstAdded+398
openflamingo/lib/python3.10/site-packages/mypyc/ir/__pycache__/func_ir.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/mypyc/ir/class_ir.pyAdded+503
openflamingo/lib/python3.10/site-packages/mypyc/ir/pprint.pyAdded+516
openflamingo/lib/python3.10/site-packages/mypyc/ir/rtypes.pyAdded+1038
openflamingo/lib/python3.10/site-packages/mypyc/irbuild/__init__.pyAdded
openflamingo/lib/python3.10/site-packages/mypyc/irbuild/builder.pyAdded+1457
openflamingo/lib/python3.10/site-packages/mypyc/irbuild/ll_builder.pyAdded
openflamingo/lib/python3.10/site-packages/mypyc/irbuild/mapper.cpython-310-x86_64-linux-gnu.soAdded
openflamingo/lib/python3.10/site-packages/mypyc/irbuild/prepare.cpython-310-x86_64-linux-gnu.soAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__init__.cpython-310-x86_64-linux-gnu.soAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__init__.pyAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/__init__.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/dict_ops.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/exc_ops.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/float_ops.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/generic_ops.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/int_ops.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/list_ops.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/misc_ops.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/set_ops.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/str_ops.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/__pycache__/tuple_ops.cpython-310.pycAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/bytes_ops.pyAdded+109
openflamingo/lib/python3.10/site-packages/mypyc/primitives/dict_ops.pyAdded+325
openflamingo/lib/python3.10/site-packages/mypyc/primitives/exc_ops.cpython-310-x86_64-linux-gnu.soAdded
openflamingo/lib/python3.10/site-packages/mypyc/primitives/exc_ops.pyAdded+101
openflamingo/lib/python3.10/site-packages/mypyc/primitives/int_ops.cpython-310-x86_64-linux-gnu.soAdded